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
bdmarius/jndarray-toolbox
src/main/java/internals/TensorLogicFunctions.java
[ { "identifier": "NumberUtils", "path": "src/main/java/utils/NumberUtils.java", "snippet": "public class NumberUtils {\n\n public static Map<JNumDataType, Map<JNumDataType, BiFunction<Number, Number, Number>>> ADD = loadAddFunctions();\n public static Map<JNumDataType, Map<JNumDataType, BiFunction<...
import utils.NumberUtils; import utils.TypeUtils; import java.util.function.Function;
19,507
package internals; public class TensorLogicFunctions { /** * Returns true if all elements are lower than the given value */ static boolean lower(Tensor tensor, Number value) { return all(tensor, (x ->
package internals; public class TensorLogicFunctions { /** * Returns true if all elements are lower than the given value */ static boolean lower(Tensor tensor, Number value) { return all(tensor, (x ->
NumberUtils.lower(tensor.getDataType(), x, TypeUtils.parseDataType(value.getClass()), value)));
1
2023-11-13 19:53:02+00:00
24k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/menus/FlowerCreationMenu.java
[ { "identifier": "BetterFlowers", "path": "src/main/java/com/uroria/betterflowers/BetterFlowers.java", "snippet": "@Getter\npublic final class BetterFlowers extends JavaPlugin {\n\n private final FlowerManager flowerManager;\n private final LanguageManager languageManager;\n\n public BetterFlowe...
import com.uroria.betterflowers.BetterFlowers; import com.uroria.betterflowers.data.FlowerGroupData; import com.uroria.betterflowers.flowers.SingleFlower; import com.uroria.betterflowers.flowers.placable.FlowerGroup; import com.uroria.betterflowers.managers.LanguageManager; import com.uroria.betterflowers.utils.BukkitPlayerInventory; import com.uroria.betterflowers.utils.CandleCollection; import com.uroria.betterflowers.utils.FlowerCollection; import com.uroria.betterflowers.data.FlowerData; import com.uroria.betterflowers.utils.ItemBuilder; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
20,715
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>(); this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.no")) .build(); this.notActive = new ItemBuilder(Material.RED_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.group.no.no")) .build(); this.wholeCategoryRan = new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.yes")) .build(); this.wholeCategory = new ItemBuilder(Material.MAGENTA_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.no.yes")) .build(); } public void open() { this.closeActions.add(() -> { personalFlower.clear(); randomizer.clear(); isGroup.clear(); }); generateCategories(); openInventory(player); } private void generateFlowerOverlay() { //generates placeholder for (var index = 27; index < 54; index++) { if (index >= 36 && index <= 44) continue; this.setSlot(index, new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.placeholder")) .build(), this::cancelClick); } //generates the display for the randomizer for (var index = 0; index < 9; index++) { if (index >= randomizer.size() || index >= isGroup.size()) break; if (isGroup.get(index) && randomizer.get(index)) setSlot(45 + index, wholeCategoryRan, this::cancelClick); if (isGroup.get(index) && !randomizer.get(index)) setSlot(45 + index, wholeCategory, this::cancelClick); if (!isGroup.get(index) && randomizer.get(index)) setSlot((45 + index), active, this::cancelClick); if (!isGroup.get(index) && !randomizer.get(index)) setSlot((45 + index), notActive, this::cancelClick); } //generates the chosen list of flowers to display the current flower list for (var index = 0; index < personalFlower.size(); index++) { final var singleFlower = personalFlower.get(index); setSlot((36 + index), new ItemBuilder(singleFlower.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%",singleFlower.getName() + " ID " + index)) .build(), this::cancelClick); } setSlot(29, new ItemBuilder(Material.ECHO_SHARD) .setName(languageManager.getComponent("gui.flower.item.display.create")) .build(), this::onCreateClick); setSlot(30, new ItemBuilder(Material.STRUCTURE_VOID) .setName(languageManager.getComponent("gui.flower.item.display.back")) .build(), this::onBackClick); setSlot(32, new ItemBuilder(Material.BARRIER) .setName(languageManager.getComponent("gui.flower.item.display.delete")) .build(), this::onDeleteClick); setSlot(33, new ItemBuilder(Material.REDSTONE) .setName(languageManager.getComponent("gui.flower.item.display.remove")) .build(), this::onRemoveClick); } private void generateCategories() { clearSlots(); generateFlowerOverlay();
package com.uroria.betterflowers.menus; public final class FlowerCreationMenu extends BukkitPlayerInventory { private final LanguageManager languageManager; private final List<FlowerData> personalFlower; private final List<Boolean> isGroup; private final List<Boolean> randomizer; private final Player player; private final ItemStack active; private final ItemStack notActive; private final ItemStack wholeCategoryRan; private final ItemStack wholeCategory; private final BetterFlowers betterFlowers; public FlowerCreationMenu(Player player, BetterFlowers betterFlowers) { super(betterFlowers.getLanguageManager().getComponent("gui.flower.title"), 6); this.player = player; this.betterFlowers = betterFlowers; this.languageManager = betterFlowers.getLanguageManager(); this.personalFlower = new ArrayList<>(); this.randomizer = new ArrayList<>(); this.isGroup = new ArrayList<>(); this.active = new ItemBuilder(Material.LIME_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.no")) .build(); this.notActive = new ItemBuilder(Material.RED_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.group.no.no")) .build(); this.wholeCategoryRan = new ItemBuilder(Material.BLUE_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.yes.yes")) .build(); this.wholeCategory = new ItemBuilder(Material.MAGENTA_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.randomizer.no.yes")) .build(); } public void open() { this.closeActions.add(() -> { personalFlower.clear(); randomizer.clear(); isGroup.clear(); }); generateCategories(); openInventory(player); } private void generateFlowerOverlay() { //generates placeholder for (var index = 27; index < 54; index++) { if (index >= 36 && index <= 44) continue; this.setSlot(index, new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE) .setName(languageManager.getComponent("gui.flower.item.display.placeholder")) .build(), this::cancelClick); } //generates the display for the randomizer for (var index = 0; index < 9; index++) { if (index >= randomizer.size() || index >= isGroup.size()) break; if (isGroup.get(index) && randomizer.get(index)) setSlot(45 + index, wholeCategoryRan, this::cancelClick); if (isGroup.get(index) && !randomizer.get(index)) setSlot(45 + index, wholeCategory, this::cancelClick); if (!isGroup.get(index) && randomizer.get(index)) setSlot((45 + index), active, this::cancelClick); if (!isGroup.get(index) && !randomizer.get(index)) setSlot((45 + index), notActive, this::cancelClick); } //generates the chosen list of flowers to display the current flower list for (var index = 0; index < personalFlower.size(); index++) { final var singleFlower = personalFlower.get(index); setSlot((36 + index), new ItemBuilder(singleFlower.getDisplay()) .setName(languageManager.getComponent("gui.flower.item.display.flower", "%flower%",singleFlower.getName() + " ID " + index)) .build(), this::cancelClick); } setSlot(29, new ItemBuilder(Material.ECHO_SHARD) .setName(languageManager.getComponent("gui.flower.item.display.create")) .build(), this::onCreateClick); setSlot(30, new ItemBuilder(Material.STRUCTURE_VOID) .setName(languageManager.getComponent("gui.flower.item.display.back")) .build(), this::onBackClick); setSlot(32, new ItemBuilder(Material.BARRIER) .setName(languageManager.getComponent("gui.flower.item.display.delete")) .build(), this::onDeleteClick); setSlot(33, new ItemBuilder(Material.REDSTONE) .setName(languageManager.getComponent("gui.flower.item.display.remove")) .build(), this::onRemoveClick); } private void generateCategories() { clearSlots(); generateFlowerOverlay();
final var flowers = List.copyOf(Arrays.stream(FlowerCollection.values()).toList());
6
2023-11-18 16:13:59+00:00
24k
jpdev01/asaasSdk
src/main/java/io/github/jpdev/asaassdk/doc/Examples.java
[ { "identifier": "Asaas", "path": "src/main/java/io/github/jpdev/asaassdk/http/Asaas.java", "snippet": "public class Asaas {\n\n private static final String ENDPOINT_PRODUCTION = \"https://www.asaas.com/api/v3\";\n private static final String ENDPOINT_SANDBOX = \"https://sandbox.asaas.com/api/v3\";...
import io.github.jpdev.asaassdk.http.Asaas; import io.github.jpdev.asaassdk.rest.accounts.Account; import io.github.jpdev.asaassdk.rest.accounts.AccountCreator; import io.github.jpdev.asaassdk.rest.action.ResourceSet; import io.github.jpdev.asaassdk.rest.bill.Bill; import io.github.jpdev.asaassdk.rest.commons.DeletedResource; import io.github.jpdev.asaassdk.rest.customeraccount.CustomerAccount; import io.github.jpdev.asaassdk.rest.finance.FinanceBalance; import io.github.jpdev.asaassdk.rest.financialtransaction.FinancialTransaction; import io.github.jpdev.asaassdk.rest.installment.Installment; import io.github.jpdev.asaassdk.rest.invoice.Invoice; import io.github.jpdev.asaassdk.rest.invoice.Taxes; import io.github.jpdev.asaassdk.rest.myaccount.accountnumber.AccountNumber; import io.github.jpdev.asaassdk.rest.myaccount.commercialinfo.CommercialInfo; import io.github.jpdev.asaassdk.rest.myaccount.fee.AccountFee; import io.github.jpdev.asaassdk.rest.myaccount.status.MyAccountStatus; import io.github.jpdev.asaassdk.rest.notification.NotificationConfig; import io.github.jpdev.asaassdk.rest.payment.Payment; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentLinkChargeType; import io.github.jpdev.asaassdk.rest.payment.enums.PaymentStatus; import io.github.jpdev.asaassdk.rest.payment.identificationfield.PaymentIdentificationField; import io.github.jpdev.asaassdk.rest.payment.status.PaymentStatusData; import io.github.jpdev.asaassdk.rest.paymentlink.PaymentLink; import io.github.jpdev.asaassdk.rest.pix.addresskey.PixAddressKey; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyStatus; import io.github.jpdev.asaassdk.rest.pix.enums.PixAddressKeyType; import io.github.jpdev.asaassdk.rest.pix.enums.PixTransactionType; import io.github.jpdev.asaassdk.rest.pix.qrcode.PixQrCode; import io.github.jpdev.asaassdk.rest.pix.qrcode.decode.PixDecodedQrCode; import io.github.jpdev.asaassdk.rest.pix.transaction.PixTransaction; import io.github.jpdev.asaassdk.rest.transfer.Transfer; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountSetting; import io.github.jpdev.asaassdk.rest.transfer.children.BankAccountType; import io.github.jpdev.asaassdk.rest.transfer.children.BankSetting; import io.github.jpdev.asaassdk.utils.BillingType; import io.github.jpdev.asaassdk.utils.Money; import java.math.BigDecimal; import java.util.Date;
21,446
Transfer ted = Transfer.tedCreator() .setBankAccount(bankAccountSetting) .setValue(Money.create(new BigDecimal(1.01))) .create(); } private void bill() { Bill bill = Bill.creator() .setIdentificationField("25794150099003551916515000211407100000000000000") .create(); } private void pixStaticQrCode() { PixQrCode qrCode = PixQrCode .creator() .setAddressKey(PixAddressKey.reader().read().getData().get(0).key) .setDescription("teste") .setValue(Money.create(0.01)) .create(); System.out.printf(qrCode.payload); } private void payment() { Payment payment = Payment.creator() .setCustomer("cus_000072683114") .setBillingType(BillingType.PIX) .setDueDate(new Date()) .setInstallmentCount(2) .setInstallmentValue(Money.create(50)) .setDescription("Teste") .create(); ResourceSet<Payment> paymentResourceSet = Payment.reader() .setStatus(PaymentStatus.RECEIVED) .setStartPaymentDate(new Date()) .setFinishDueDate(new Date()) .read(); DeletedResource paymentDeleted = Payment.deleter(payment.getId()).delete(); payment = Payment.restorer(payment.getId()).create(); PaymentStatusData paymentStatusData = Payment.statusFetcher("pay_9087711026766517").fetch(); PaymentIdentificationField linhaDigitavel = Payment.identificationFieldFetcher("pay_9087711026766517").fetch(); } private void customerAccount() { CustomerAccount.fetcher("cus_000072683044").fetch(); CustomerAccount customerAccount = CustomerAccount.creator() .setName("criado via API") .setCpfCnpj("10030823005") .create(); } private void notification() { ResourceSet<NotificationConfig> notificationConfigList = NotificationConfig.customerAccountReader("cus_000072683044").read(); NotificationConfig.updater(notificationConfigList.getData().get(0).getId()).setEnabled(false).update(); } private void paymentLink() { PaymentLink link = PaymentLink.fetcher("725104409743").fetch(); ResourceSet<PaymentLink> paymentLinkResourceSet = PaymentLink .reader() .read(); DeletedResource deletedPaymentLink = PaymentLink .deleter("725104409743") .delete(); PaymentLink paymentLink = PaymentLink.creator() .setName("name") .setBillingType(BillingType.PIX) .setChargeType(PaymentLinkChargeType.INSTALLMENT) .setEndDate(new Date()) .setDueDateLimitDays(10) .setMaxInstallmentCount(2) .create(); PaymentLink updated = PaymentLink.updater(paymentLink.getId()) .setName("name") .setBillingType(BillingType.PIX) .setChargeType(PaymentLinkChargeType.INSTALLMENT) .setEndDate(new Date()) .setDueDateLimitDays(10) .setMaxInstallmentCount(2) .update(); } private void financialTransaction() { ResourceSet<FinancialTransaction> financialTransactionResourceSet = FinancialTransaction .reader() .setTransferId("transferId") .read(); } private void invoice() { Invoice invoice = Invoice.creator() .setServiceDescription("Nota fiscal da Fatura 101940. Descrição dos Serviços: ANÁLISE E DESENVOLVIMENTO DE SISTEMAS") .setObservations("Mensal referente aos trabalhos de Junho.") .setValue(Money.create(300)) .setDeductions(Money.create(2)) .setEffectiveDate(new Date()) .setMunicipalServiceName("Análise e Desenvolvimento de Sistemas") .setTaxes( new Taxes() .setRetainIss(true) .setIss(Money.create(3)) .setCofins(Money.create(3)) .setCsll(Money.create(1)) .setInss(Money.create(3)) .setIr(Money.create(1.5)) .setPis(Money.create(0.65)) ) .create(); } private void finance() { FinanceBalance financeBalance = FinanceBalance.fetcher().fetch(); } private void installment() {
package io.github.jpdev.asaassdk.doc; public class Examples { public static void main(String[] args) { Asaas.init(Secret.getAccessToken()); myStatus(); subAccount(); } private void pixTransaction() { ResourceSet<PixTransaction> pixTransactionResourceSet = PixTransaction.reader().read(); PixTransaction pixTransaction = PixTransaction.fetcher("bc515f74-d5c7-4bc2-93e5-3bafc0a9b15d").fetch(); PixTransaction cancelledPixTransaction = PixTransaction.canceller("35363f6e-93e2-11ec-b9d9-96f4053b1bd4").create(); ResourceSet<PixTransaction> pixTransactionDebitResourceSet = PixTransaction.reader() .setType(PixTransactionType.DEBIT) .read(); } private void pixAddressKey() { ResourceSet<PixAddressKey> pixAddressKeyResourceSet = PixAddressKey.reader() .setStatus(PixAddressKeyStatus.ACTIVE) .setLimit(1) .read(); PixAddressKey.creator().setType(PixAddressKeyType.EVP).create(); PixAddressKey.reader().read(); } private void decodePixQrCode() { PixDecodedQrCode decodedQrCode = PixDecodedQrCode.decoder() .setPayload("payload") .create(); } private void transfer() { ResourceSet<Transfer> transferList = Transfer.reader().read(); Transfer transfer = Transfer.pixAddressKeyCreator() .setPixAddressKey("09414368965") .setValue(Money.create(0.01)) .setDescription("teste") .setPixAddressKeyType(PixAddressKeyType.CPF) .create(); System.out.println(transfer.getValue().toString()); Date birthDate = new Date(); BankAccountSetting bankAccountSetting = new BankAccountSetting() .setBank( new BankSetting().setCode("085") ) .setAccountName("Paulo") .setOwnerName("Paulo") .setOwnerBirthDate(new Date()) .setCpfCnpj("06928316000124") .setAgency("0108") .setAccount("10895") .setAccountDigit("5") .setBankAccountType(BankAccountType.CONTA_CORRENTE); Transfer pixManualTransfer = Transfer.pixManualCreator() .setBankAccount(bankAccountSetting) .setValue(Money.create(new BigDecimal(1.01))) .create(); System.out.println(pixManualTransfer.getValue().toString()); Transfer ted = Transfer.tedCreator() .setBankAccount(bankAccountSetting) .setValue(Money.create(new BigDecimal(1.01))) .create(); } private void bill() { Bill bill = Bill.creator() .setIdentificationField("25794150099003551916515000211407100000000000000") .create(); } private void pixStaticQrCode() { PixQrCode qrCode = PixQrCode .creator() .setAddressKey(PixAddressKey.reader().read().getData().get(0).key) .setDescription("teste") .setValue(Money.create(0.01)) .create(); System.out.printf(qrCode.payload); } private void payment() { Payment payment = Payment.creator() .setCustomer("cus_000072683114") .setBillingType(BillingType.PIX) .setDueDate(new Date()) .setInstallmentCount(2) .setInstallmentValue(Money.create(50)) .setDescription("Teste") .create(); ResourceSet<Payment> paymentResourceSet = Payment.reader() .setStatus(PaymentStatus.RECEIVED) .setStartPaymentDate(new Date()) .setFinishDueDate(new Date()) .read(); DeletedResource paymentDeleted = Payment.deleter(payment.getId()).delete(); payment = Payment.restorer(payment.getId()).create(); PaymentStatusData paymentStatusData = Payment.statusFetcher("pay_9087711026766517").fetch(); PaymentIdentificationField linhaDigitavel = Payment.identificationFieldFetcher("pay_9087711026766517").fetch(); } private void customerAccount() { CustomerAccount.fetcher("cus_000072683044").fetch(); CustomerAccount customerAccount = CustomerAccount.creator() .setName("criado via API") .setCpfCnpj("10030823005") .create(); } private void notification() { ResourceSet<NotificationConfig> notificationConfigList = NotificationConfig.customerAccountReader("cus_000072683044").read(); NotificationConfig.updater(notificationConfigList.getData().get(0).getId()).setEnabled(false).update(); } private void paymentLink() { PaymentLink link = PaymentLink.fetcher("725104409743").fetch(); ResourceSet<PaymentLink> paymentLinkResourceSet = PaymentLink .reader() .read(); DeletedResource deletedPaymentLink = PaymentLink .deleter("725104409743") .delete(); PaymentLink paymentLink = PaymentLink.creator() .setName("name") .setBillingType(BillingType.PIX) .setChargeType(PaymentLinkChargeType.INSTALLMENT) .setEndDate(new Date()) .setDueDateLimitDays(10) .setMaxInstallmentCount(2) .create(); PaymentLink updated = PaymentLink.updater(paymentLink.getId()) .setName("name") .setBillingType(BillingType.PIX) .setChargeType(PaymentLinkChargeType.INSTALLMENT) .setEndDate(new Date()) .setDueDateLimitDays(10) .setMaxInstallmentCount(2) .update(); } private void financialTransaction() { ResourceSet<FinancialTransaction> financialTransactionResourceSet = FinancialTransaction .reader() .setTransferId("transferId") .read(); } private void invoice() { Invoice invoice = Invoice.creator() .setServiceDescription("Nota fiscal da Fatura 101940. Descrição dos Serviços: ANÁLISE E DESENVOLVIMENTO DE SISTEMAS") .setObservations("Mensal referente aos trabalhos de Junho.") .setValue(Money.create(300)) .setDeductions(Money.create(2)) .setEffectiveDate(new Date()) .setMunicipalServiceName("Análise e Desenvolvimento de Sistemas") .setTaxes( new Taxes() .setRetainIss(true) .setIss(Money.create(3)) .setCofins(Money.create(3)) .setCsll(Money.create(1)) .setInss(Money.create(3)) .setIr(Money.create(1.5)) .setPis(Money.create(0.65)) ) .create(); } private void finance() { FinanceBalance financeBalance = FinanceBalance.fetcher().fetch(); } private void installment() {
ResourceSet<Installment> installmentResourceSet = Installment.reader().read();
9
2023-11-12 01:19:17+00:00
24k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/client/gui/hud/items/HudItemHydration.java
[ { "identifier": "Gui_EventManager", "path": "src/main/java/enviromine/client/gui/Gui_EventManager.java", "snippet": "@SideOnly(Side.CLIENT)\npublic class Gui_EventManager\n{\n\n\tint width, height;\n\n\t//Render HUD\n\t//Render Player\n\n\t// Button Functions\n\tGuiButton enviromine;\n\n\t// Captures th...
import org.lwjgl.opengl.GL11; import enviromine.client.gui.Gui_EventManager; import enviromine.client.gui.UI_Settings; import enviromine.client.gui.hud.HUDRegistry; import enviromine.client.gui.hud.HudItem; import enviromine.core.EM_Settings; import enviromine.utils.Alignment; import enviromine.utils.EnviroUtils; import enviromine.utils.RenderAssist; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector;
19,051
package enviromine.client.gui.hud.items; public class HudItemHydration extends HudItem { @Override public String getName() { return "Hydration"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.hydration"); } @Override public String getButtonLabel() { return getNameLoc() + "Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMLEFT; } @Override public int getDefaultPosX() { return 8; } @Override public int getDefaultPosY() { return (HUDRegistry.screenHeight - 15); } @Override public int getWidth() { return UI_Settings.minimalHud && !rotated ? 0 : 64; } @Override public int getHeight() { return 8; } @Override public boolean isEnabledByDefault() { return EM_Settings.enableHydrate; } @Override public boolean isBlinking() { if(blink() && Gui_EventManager.tracker.hydration < 25) { return true; } else { return false; } } @Override public int getDefaultID() { return 1; } @Override public void render() { EntityClientPlayerMP ecplayermp = Minecraft.getMinecraft().thePlayer; if( (EM_Settings.dimensionProperties.containsKey(ecplayermp.dimension) && !EM_Settings.dimensionProperties.get(ecplayermp.dimension).trackHydration) || !EM_Settings.enableHydrate
package enviromine.client.gui.hud.items; public class HudItemHydration extends HudItem { @Override public String getName() { return "Hydration"; } public String getNameLoc() { return StatCollector.translateToLocal("options.enviromine.hud.hydration"); } @Override public String getButtonLabel() { return getNameLoc() + "Bar"; } @Override public Alignment getDefaultAlignment() { return Alignment.BOTTOMLEFT; } @Override public int getDefaultPosX() { return 8; } @Override public int getDefaultPosY() { return (HUDRegistry.screenHeight - 15); } @Override public int getWidth() { return UI_Settings.minimalHud && !rotated ? 0 : 64; } @Override public int getHeight() { return 8; } @Override public boolean isEnabledByDefault() { return EM_Settings.enableHydrate; } @Override public boolean isBlinking() { if(blink() && Gui_EventManager.tracker.hydration < 25) { return true; } else { return false; } } @Override public int getDefaultID() { return 1; } @Override public void render() { EntityClientPlayerMP ecplayermp = Minecraft.getMinecraft().thePlayer; if( (EM_Settings.dimensionProperties.containsKey(ecplayermp.dimension) && !EM_Settings.dimensionProperties.get(ecplayermp.dimension).trackHydration) || !EM_Settings.enableHydrate
|| (EM_Settings.witcheryVampireImmunities && EnviroUtils.isPlayerAVampire(ecplayermp))
6
2023-11-16 18:15:29+00:00
24k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/items/guns/GenericGun.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import net.minecraft.client.Minecraft; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationHandler; import sheridan.gunscraft.capability.CapabilityHandler; import sheridan.gunscraft.entities.EntityRegister; import sheridan.gunscraft.entities.projectile.GenericProjectile; import sheridan.gunscraft.events.ClientTickEvents; import sheridan.gunscraft.events.RenderEvents; import sheridan.gunscraft.items.BaseItem; import sheridan.gunscraft.items.attachments.util.GunAttachmentSlot; import sheridan.gunscraft.items.attachments.util.NBTAttachmentsMap; import sheridan.gunscraft.render.TransformData; import sheridan.gunscraft.sounds.SoundEvents; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
20,796
package sheridan.gunscraft.items.guns; public class GenericGun extends BaseItem implements IGenericGun{ public static final int SEMI = 0, BURST = 1, AUTO = 2, CHARGE = 3; private static Map<Integer, String> fireModeNameMap = new HashMap<>(); static { fireModeNameMap.put(SEMI, "SEMI"); fireModeNameMap.put(BURST, "BURST"); fireModeNameMap.put(AUTO, "AUTO"); fireModeNameMap.put(CHARGE, "CHARGE"); } public int baseMagSize; public ResourceLocation[] textures; public boolean canHoldInOneHand; public int[] fireModes; public float baseSpread; public float maxSpread; public float spreadPreShoot; public float bulletSpeed; public float baseDamage; public float minDamage; public int bulletLifeLength; public int shootDelay; public String normalFireSound; private float[] soundArgs; public boolean isFreeBlot; public boolean isPistol; public int reloadLength; public int burstCount; public float aimingSpeed; public float recoilUp; public float recoilRandom; public float recoilDec; public Map<String, GunAttachmentSlot> slotMap; private TranslationTextComponent introduction; protected String seriesName; public String bulletType; public GenericGun(Properties properties, int baseMagSize,boolean canHoldInOneHand, ResourceLocation[] textures, int[] fireModes, float baseSpread, float maxSpread, float spreadPreShoot, float bulletSpeed, float baseDamage, float minDamage, int bulletLifeLength, int shootDelay, String normalFireSound, float[] soundArgs, boolean isFreeBlot, boolean isPistol, int reloadLength, int burstCount, float aimingSpeed, float recoilUp, float recoilRandom, float recoilDec, String seriesName, String bulletType) { super(properties); this.baseMagSize = baseMagSize; this.textures = textures; this.canHoldInOneHand = canHoldInOneHand; this.fireModes = fireModes; this.baseSpread = baseSpread; this.maxSpread = maxSpread; this.spreadPreShoot = spreadPreShoot; this.bulletSpeed = bulletSpeed; this.baseDamage = baseDamage; this.minDamage = minDamage; this.bulletLifeLength = bulletLifeLength; this.shootDelay = shootDelay; this.normalFireSound = normalFireSound; this.soundArgs = soundArgs; this.isFreeBlot = isFreeBlot; this.isPistol = isPistol; this.reloadLength = reloadLength; this.burstCount = burstCount; this.aimingSpeed = aimingSpeed; this.recoilUp = recoilUp; this.recoilRandom = recoilRandom; this.recoilDec = recoilDec; this.seriesName = seriesName; this.bulletType = bulletType; } public static String getFireModeStr(int key) { if (fireModeNameMap.containsKey(key)) { return fireModeNameMap.get(key); } return "UNKNOWN"; } @Override public ResourceLocation getTexture(int index) { return textures[index % textures.length]; } @Override public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) { ItemStack mainHandStack = Minecraft.getInstance().player != null ? Minecraft.getInstance().player.getHeldItemMainhand() : null; if (oldStack.getItem() != newStack.getItem() || slotChanged && (mainHandStack == newStack)) {
package sheridan.gunscraft.items.guns; public class GenericGun extends BaseItem implements IGenericGun{ public static final int SEMI = 0, BURST = 1, AUTO = 2, CHARGE = 3; private static Map<Integer, String> fireModeNameMap = new HashMap<>(); static { fireModeNameMap.put(SEMI, "SEMI"); fireModeNameMap.put(BURST, "BURST"); fireModeNameMap.put(AUTO, "AUTO"); fireModeNameMap.put(CHARGE, "CHARGE"); } public int baseMagSize; public ResourceLocation[] textures; public boolean canHoldInOneHand; public int[] fireModes; public float baseSpread; public float maxSpread; public float spreadPreShoot; public float bulletSpeed; public float baseDamage; public float minDamage; public int bulletLifeLength; public int shootDelay; public String normalFireSound; private float[] soundArgs; public boolean isFreeBlot; public boolean isPistol; public int reloadLength; public int burstCount; public float aimingSpeed; public float recoilUp; public float recoilRandom; public float recoilDec; public Map<String, GunAttachmentSlot> slotMap; private TranslationTextComponent introduction; protected String seriesName; public String bulletType; public GenericGun(Properties properties, int baseMagSize,boolean canHoldInOneHand, ResourceLocation[] textures, int[] fireModes, float baseSpread, float maxSpread, float spreadPreShoot, float bulletSpeed, float baseDamage, float minDamage, int bulletLifeLength, int shootDelay, String normalFireSound, float[] soundArgs, boolean isFreeBlot, boolean isPistol, int reloadLength, int burstCount, float aimingSpeed, float recoilUp, float recoilRandom, float recoilDec, String seriesName, String bulletType) { super(properties); this.baseMagSize = baseMagSize; this.textures = textures; this.canHoldInOneHand = canHoldInOneHand; this.fireModes = fireModes; this.baseSpread = baseSpread; this.maxSpread = maxSpread; this.spreadPreShoot = spreadPreShoot; this.bulletSpeed = bulletSpeed; this.baseDamage = baseDamage; this.minDamage = minDamage; this.bulletLifeLength = bulletLifeLength; this.shootDelay = shootDelay; this.normalFireSound = normalFireSound; this.soundArgs = soundArgs; this.isFreeBlot = isFreeBlot; this.isPistol = isPistol; this.reloadLength = reloadLength; this.burstCount = burstCount; this.aimingSpeed = aimingSpeed; this.recoilUp = recoilUp; this.recoilRandom = recoilRandom; this.recoilDec = recoilDec; this.seriesName = seriesName; this.bulletType = bulletType; } public static String getFireModeStr(int key) { if (fireModeNameMap.containsKey(key)) { return fireModeNameMap.get(key); } return "UNKNOWN"; } @Override public ResourceLocation getTexture(int index) { return textures[index % textures.length]; } @Override public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) { ItemStack mainHandStack = Minecraft.getInstance().player != null ? Minecraft.getInstance().player.getHeldItemMainhand() : null; if (oldStack.getItem() != newStack.getItem() || slotChanged && (mainHandStack == newStack)) {
ClientProxy.equipDuration = 5;
0
2023-11-14 14:00:55+00:00
24k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/fragments/APKsFragment.java
[ { "identifier": "APKInstallerActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/APKInstallerActivity.java", "snippet": "public class APKInstallerActivity extends AppCompatActivity {\n\n private AppCompatImageButton mExploreIcon;\n private AppCompatImageView mAppIcon;\n ...
import android.app.Activity; import android.content.ClipData; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.appcompat.widget.PopupMenu; import androidx.documentfile.provider.DocumentFile; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.APKInstallerActivity; import com.threethan.questpatcher.activities.InstallerFilePickerActivity; import com.threethan.questpatcher.adapters.APKsAdapter; import com.threethan.questpatcher.utils.APKData; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.APKExplorer; import com.threethan.questpatcher.utils.AppData; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.tasks.ExploreAPK; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.tabs.TabLayout; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Objects; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
14,699
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021 */ public class APKsFragment extends Fragment { private LinearLayoutCompat mProgress; private RecyclerView mRecyclerView; private APKsAdapter mRecycleViewAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apks, container, false); Common.initializeAPKsTitle(mRootView, R.id.app_title); Common.initializeAPKsSearchWord(mRootView, R.id.search_word); mProgress = mRootView.findViewById(R.id.progress_layout); AppCompatImageButton mSearchButton = mRootView.findViewById(R.id.search_button); AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort_button); AppCompatImageButton mAddButton = mRootView.findViewById(R.id.add_button); LinearLayoutCompat mBottomLayout = mRootView.findViewById(R.id.layout_bottom); TabLayout mTabLayout = mRootView.findViewById(R.id.tab_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity())); Common.getAPKsTitle().setText(getString(R.string.apps_exported)); mTabLayout.setVisibility(View.VISIBLE); mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.apks))); mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.bundles))); Objects.requireNonNull(mTabLayout.getTabAt(getTabPosition(requireActivity()))).select(); mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { String mStatus = sCommonUtils.getString("apkTypes", "apks", requireActivity()); switch (tab.getPosition()) { case 0: if (!mStatus.equals("apks")) { sCommonUtils.saveString("apkTypes", "apks", requireActivity()); loadAPKs(requireActivity()); } break; case 1: if (!mStatus.equals("bundles")) { sCommonUtils.saveString("apkTypes", "bundles", requireActivity()); loadAPKs(requireActivity()); } break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); mSearchButton.setOnClickListener(v -> { if (Common.getAPKsSearchWord().getVisibility() == View.VISIBLE) { Common.getAPKsSearchWord().setVisibility(View.GONE); Common.getAPKsTitle().setVisibility(View.VISIBLE); if (Common.getAPKsSearchWord() != null) { Common.getAPKsSearchWord().setText(null); }
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021 */ public class APKsFragment extends Fragment { private LinearLayoutCompat mProgress; private RecyclerView mRecyclerView; private APKsAdapter mRecycleViewAdapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apks, container, false); Common.initializeAPKsTitle(mRootView, R.id.app_title); Common.initializeAPKsSearchWord(mRootView, R.id.search_word); mProgress = mRootView.findViewById(R.id.progress_layout); AppCompatImageButton mSearchButton = mRootView.findViewById(R.id.search_button); AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort_button); AppCompatImageButton mAddButton = mRootView.findViewById(R.id.add_button); LinearLayoutCompat mBottomLayout = mRootView.findViewById(R.id.layout_bottom); TabLayout mTabLayout = mRootView.findViewById(R.id.tab_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity())); Common.getAPKsTitle().setText(getString(R.string.apps_exported)); mTabLayout.setVisibility(View.VISIBLE); mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.apks))); mTabLayout.addTab(mTabLayout.newTab().setText(getString(R.string.bundles))); Objects.requireNonNull(mTabLayout.getTabAt(getTabPosition(requireActivity()))).select(); mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { String mStatus = sCommonUtils.getString("apkTypes", "apks", requireActivity()); switch (tab.getPosition()) { case 0: if (!mStatus.equals("apks")) { sCommonUtils.saveString("apkTypes", "apks", requireActivity()); loadAPKs(requireActivity()); } break; case 1: if (!mStatus.equals("bundles")) { sCommonUtils.saveString("apkTypes", "bundles", requireActivity()); loadAPKs(requireActivity()); } break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); mSearchButton.setOnClickListener(v -> { if (Common.getAPKsSearchWord().getVisibility() == View.VISIBLE) { Common.getAPKsSearchWord().setVisibility(View.GONE); Common.getAPKsTitle().setVisibility(View.VISIBLE); if (Common.getAPKsSearchWord() != null) { Common.getAPKsSearchWord().setText(null); }
AppData.toggleKeyboard(0, Common.getAPKsSearchWord(), requireActivity());
6
2023-11-18 15:13:30+00:00
24k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/MenuServiceImpl.java
[ { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) ...
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.dimple.exception.BadRequestException; import com.dimple.exception.EntityExistException; import com.dimple.modules.system.domain.Menu; import com.dimple.modules.system.domain.Role; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.domain.vo.MenuMetaVO; import com.dimple.modules.system.domain.vo.MenuVO; import com.dimple.modules.system.repository.MenuRepository; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.MenuService; import com.dimple.modules.system.service.RoleService; import com.dimple.modules.system.service.dto.MenuDTO; import com.dimple.modules.system.service.dto.MenuQueryCriteria; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.mapstruct.MenuMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors;
15,245
package com.dimple.modules.system.service.impl; /** * @className: MenuServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "menu") public class MenuServiceImpl implements MenuService { private final MenuRepository menuRepository;
package com.dimple.modules.system.service.impl; /** * @className: MenuServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "menu") public class MenuServiceImpl implements MenuService { private final MenuRepository menuRepository;
private final UserRepository userRepository;
8
2023-11-10 03:30:36+00:00
24k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/DataSourceEditFrame.java
[ { "identifier": "AbstractEditContainerModel", "path": "service/src/main/java/com/lazycoder/service/vo/datasourceedit/general/AbstractEditContainerModel.java", "snippet": "@Data\npublic abstract class AbstractEditContainerModel {\n\n /**\n * 不常用控制列表\n */\n protected LinkedHashMap<String, Ba...
import com.formdev.flatlaf.ui.FlatTabbedPaneUI; import com.lazycoder.service.vo.datasourceedit.general.AbstractEditContainerModel; import com.lazycoder.uidatasourceedit.formatedit.FormatEditPane; import com.lazycoder.uidatasourceedit.generalset.GeneralSettingPane; import com.lazycoder.uidatasourceedit.moduleedit.ModuleEditPane; import com.lazycoder.uidatasourceedit.modulemanagement.ModuleManagementPane; import com.lazycoder.uiutils.folder.FoldButton; import com.lazycoder.uiutils.mycomponent.LazyCoderCommonFrame; import com.lazycoder.uiutils.utils.SysUtil; import com.lazycoder.utils.swing.LazyCoderOptionPane; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener;
16,565
package com.lazycoder.uidatasourceedit; public class DataSourceEditFrame extends LazyCoderCommonFrame { /** * */ private static final long serialVersionUID = -5066333190331583114L; private JPanel contentPane; private JTabbedPane tabbedPane; private GeneralSettingPane generalSettingPane; private FormatEditPane formatEditPane; private ModuleManagementPane moduleManagementPane; private ModuleEditPane moduleEditPane; /** * Create the frame. */ public DataSourceEditFrame() { setTitle("编辑数据源——" + DataSourceEditHolder.currentUserDataSourceLabel.getDataSourceName()); //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//真正使用用这句 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// 测试使用用这句 // setExtendedState(JFrame.MAXIMIZED_BOTH); //设置最高并去掉任务栏高度 摘自 https://www.iteye.com/blog/krs-2042006 //getScreenInsets是指获得屏幕的 insets //设置frame的大小 this.setSize(SysUtil.SCREEN_SIZE.width, SysUtil.SCREEN_SIZE.height - SysUtil.taskbarInsets.bottom); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS)); tabbedPane = new JTabbedPane(JTabbedPane.LEFT); // tabbedPane.putClientProperty("TabbedPane.underlineColor", new ColorUIResource(Color.red)); FlatTabbedPaneUI tabbedPaneUI = new FlatTabbedPaneUI() { @Override protected void installDefaults() { super.installDefaults(); underlineColor = getBackground(); focusColor = new Color(236, 245, 255); // selectedBackground = new Color(242, 243, 245); hoverColor = new Color(242, 243, 245); selectedForeground = new Color(69, 125, 255); } }; tabbedPane.setUI(tabbedPaneUI); contentPane.add(tabbedPane); dbEditInit(); sysEditInit(); moduleManagementInit(); moduleEditInit(); tabbedPane.addChangeListener(changeListener); DataSourceEditHolder.dataSourceEditFrame = this; closingWindow(); setVisible(true); } /** * 设置当前选中的tab面板 * * @param selectedIndex */ public void setSelectedTab(int selectedIndex) { tabbedPane.setSelectedIndex(selectedIndex); } /** * 获取当前选中的面板(0:系统设置模板模板 1:必填模板和可选模板内容编辑面板 2:模块管理模板 3:模块内容编辑面板) * * @return */ public int getCurrentSelectedIndex() { return tabbedPane.getSelectedIndex(); } private void dbEditInit() { generalSettingPane = new GeneralSettingPane(); generalSettingPane.setPreferredSize(new Dimension(1430, 960)); JScrollPane dbEditScrollPane = new JScrollPane(generalSettingPane); tabbedPane.addTab("通用管理", null, dbEditScrollPane, null); } private void sysEditInit() { formatEditPane = new FormatEditPane(); DataSourceEditHolder.formatEditPane = formatEditPane; tabbedPane.addTab("格式设置", null, formatEditPane, null); } private void moduleManagementInit() { moduleManagementPane = new ModuleManagementPane(); DataSourceEditHolder.moduleManagementPane = moduleManagementPane; JScrollPane moduleEditScrollPane = new JScrollPane(moduleManagementPane); tabbedPane.addTab("模块管理", null, moduleEditScrollPane, null); } private void moduleEditInit() { moduleEditPane = new ModuleEditPane(); DataSourceEditHolder.moduleEditPane = moduleEditPane; JScrollPane moduleScrollPane = new JScrollPane(moduleEditPane); tabbedPane.addTab("模块设置", null, moduleScrollPane, null); showHandCursor(); } private void showHandCursor() { ArrayList<FoldButton> list = ModuleEditPaneHolder.initPaneHiddenButtonList; for (int i = 0; i < list.size(); i++) { list.get(i).addMouseListener(adapter); } } public ArrayList<AbstractEditContainerModel> getAllEditContainerModel() { ArrayList<AbstractEditContainerModel> list = new ArrayList<AbstractEditContainerModel>(); list.addAll(formatEditPane.getAllEditContainerModel()); list.addAll(moduleEditPane.getAllEditContainerModel()); return list; } private ChangeListener changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub int tabNumber = getCurrentSelectedIndex(); if (tabNumber == 1) {// 切换到格式面板 formatEditPane.reloadFormatCodeInputPane(); } else if (tabNumber == 3) {// 切换到模块模板 if (ModuleEditPaneHolder.needUseCodeFileEditPane != null) { ModuleEditPaneHolder.needUseCodeFileEditPane.reloadFormatCodeInputPane(); } if (ModuleEditPaneHolder.moduleFilePutCodePane != null) { ModuleEditPaneHolder.moduleFilePutCodePane.showModuleCodeFilePath(); } } } }; private MouseAdapter adapter = new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(java.awt.event.MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }; /** * 关闭窗口 */ private void closingWindow() { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) {
package com.lazycoder.uidatasourceedit; public class DataSourceEditFrame extends LazyCoderCommonFrame { /** * */ private static final long serialVersionUID = -5066333190331583114L; private JPanel contentPane; private JTabbedPane tabbedPane; private GeneralSettingPane generalSettingPane; private FormatEditPane formatEditPane; private ModuleManagementPane moduleManagementPane; private ModuleEditPane moduleEditPane; /** * Create the frame. */ public DataSourceEditFrame() { setTitle("编辑数据源——" + DataSourceEditHolder.currentUserDataSourceLabel.getDataSourceName()); //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//真正使用用这句 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// 测试使用用这句 // setExtendedState(JFrame.MAXIMIZED_BOTH); //设置最高并去掉任务栏高度 摘自 https://www.iteye.com/blog/krs-2042006 //getScreenInsets是指获得屏幕的 insets //设置frame的大小 this.setSize(SysUtil.SCREEN_SIZE.width, SysUtil.SCREEN_SIZE.height - SysUtil.taskbarInsets.bottom); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS)); tabbedPane = new JTabbedPane(JTabbedPane.LEFT); // tabbedPane.putClientProperty("TabbedPane.underlineColor", new ColorUIResource(Color.red)); FlatTabbedPaneUI tabbedPaneUI = new FlatTabbedPaneUI() { @Override protected void installDefaults() { super.installDefaults(); underlineColor = getBackground(); focusColor = new Color(236, 245, 255); // selectedBackground = new Color(242, 243, 245); hoverColor = new Color(242, 243, 245); selectedForeground = new Color(69, 125, 255); } }; tabbedPane.setUI(tabbedPaneUI); contentPane.add(tabbedPane); dbEditInit(); sysEditInit(); moduleManagementInit(); moduleEditInit(); tabbedPane.addChangeListener(changeListener); DataSourceEditHolder.dataSourceEditFrame = this; closingWindow(); setVisible(true); } /** * 设置当前选中的tab面板 * * @param selectedIndex */ public void setSelectedTab(int selectedIndex) { tabbedPane.setSelectedIndex(selectedIndex); } /** * 获取当前选中的面板(0:系统设置模板模板 1:必填模板和可选模板内容编辑面板 2:模块管理模板 3:模块内容编辑面板) * * @return */ public int getCurrentSelectedIndex() { return tabbedPane.getSelectedIndex(); } private void dbEditInit() { generalSettingPane = new GeneralSettingPane(); generalSettingPane.setPreferredSize(new Dimension(1430, 960)); JScrollPane dbEditScrollPane = new JScrollPane(generalSettingPane); tabbedPane.addTab("通用管理", null, dbEditScrollPane, null); } private void sysEditInit() { formatEditPane = new FormatEditPane(); DataSourceEditHolder.formatEditPane = formatEditPane; tabbedPane.addTab("格式设置", null, formatEditPane, null); } private void moduleManagementInit() { moduleManagementPane = new ModuleManagementPane(); DataSourceEditHolder.moduleManagementPane = moduleManagementPane; JScrollPane moduleEditScrollPane = new JScrollPane(moduleManagementPane); tabbedPane.addTab("模块管理", null, moduleEditScrollPane, null); } private void moduleEditInit() { moduleEditPane = new ModuleEditPane(); DataSourceEditHolder.moduleEditPane = moduleEditPane; JScrollPane moduleScrollPane = new JScrollPane(moduleEditPane); tabbedPane.addTab("模块设置", null, moduleScrollPane, null); showHandCursor(); } private void showHandCursor() { ArrayList<FoldButton> list = ModuleEditPaneHolder.initPaneHiddenButtonList; for (int i = 0; i < list.size(); i++) { list.get(i).addMouseListener(adapter); } } public ArrayList<AbstractEditContainerModel> getAllEditContainerModel() { ArrayList<AbstractEditContainerModel> list = new ArrayList<AbstractEditContainerModel>(); list.addAll(formatEditPane.getAllEditContainerModel()); list.addAll(moduleEditPane.getAllEditContainerModel()); return list; } private ChangeListener changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub int tabNumber = getCurrentSelectedIndex(); if (tabNumber == 1) {// 切换到格式面板 formatEditPane.reloadFormatCodeInputPane(); } else if (tabNumber == 3) {// 切换到模块模板 if (ModuleEditPaneHolder.needUseCodeFileEditPane != null) { ModuleEditPaneHolder.needUseCodeFileEditPane.reloadFormatCodeInputPane(); } if (ModuleEditPaneHolder.moduleFilePutCodePane != null) { ModuleEditPaneHolder.moduleFilePutCodePane.showModuleCodeFilePath(); } } } }; private MouseAdapter adapter = new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(java.awt.event.MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }; /** * 关闭窗口 */ private void closingWindow() { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) {
int show = LazyCoderOptionPane.showConfirmDialog(null, "亲,确定要退出系统吗?\n退出前,记得要保存所有数据喔 (*^▽^*)", "系统提示", JOptionPane.YES_NO_OPTION);
8
2023-11-16 11:55:06+00:00
24k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506_ex/KSBatchSwitch2.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n...
import android.util.Log; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.base.PropertyValue; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.device.BatchSwitch; import kr.or.kashi.hde.ksx4506.KSAddress; import kr.or.kashi.hde.ksx4506.KSBatchSwitch; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.Map;
16,528
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * 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 kr.or.kashi.hde.ksx4506_ex; /** * Extended implementation of [KS X 4506] the batch-switch */ public class KSBatchSwitch2 extends KSBatchSwitch { private static final String TAG = "KSBatchSwitch2"; private static final boolean DBG = true; public static final int CMD_LIFE_INFORMATION_DISPLAY_REQ = 0x51; public static final int CMD_3WAYLIGHT_STATUS_UPDATE_REQ = 0x52; public static final int CMD_PARKING_LOCATION_DISPLAY_REQ = 0x53; public static final int CMD_COOKTOP_STATUS_UPDATE_REQ = 0x55; public static final int CMD_COOKTOP_SETTING_RESULT_REQ = 0x56; public static final int CMD_ELEVATOR_ARRIVAL_UPDATE_REQ = 0x57; private boolean mCooktopOffReqReceived = false; private boolean mHeaterSavingReqReceived = false; private boolean mHeaterSavingOffReceived = false; public KSBatchSwitch2(MainContext mainContext, Map defaultProps) { super(mainContext, defaultProps); } @Override
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * 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 kr.or.kashi.hde.ksx4506_ex; /** * Extended implementation of [KS X 4506] the batch-switch */ public class KSBatchSwitch2 extends KSBatchSwitch { private static final String TAG = "KSBatchSwitch2"; private static final boolean DBG = true; public static final int CMD_LIFE_INFORMATION_DISPLAY_REQ = 0x51; public static final int CMD_3WAYLIGHT_STATUS_UPDATE_REQ = 0x52; public static final int CMD_PARKING_LOCATION_DISPLAY_REQ = 0x53; public static final int CMD_COOKTOP_STATUS_UPDATE_REQ = 0x55; public static final int CMD_COOKTOP_SETTING_RESULT_REQ = 0x56; public static final int CMD_ELEVATOR_ARRIVAL_UPDATE_REQ = 0x57; private boolean mCooktopOffReqReceived = false; private boolean mHeaterSavingReqReceived = false; private boolean mHeaterSavingOffReceived = false; public KSBatchSwitch2(MainContext mainContext, Map defaultProps) { super(mainContext, defaultProps); } @Override
protected @ParseResult int parseCharacteristicRsp(KSPacket packet, PropertyMap outProps) {
0
2023-11-10 01:19:44+00:00
24k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/core/WidgetManager.java
[ { "identifier": "TextTools", "path": "src/main/java/io/xlorey/FluxLoader/client/api/TextTools.java", "snippet": "public class TextTools {\n /**\n * Drawing colored text at specified coordinates\n * @param text the text to be drawn. Must not be null\n * @param font text font corresponding ...
import imgui.ImGui; import imgui.ImGuiIO; import imgui.gl3.ImGuiImplGl3; import imgui.glfw.ImGuiImplGlfw; import io.xlorey.FluxLoader.client.api.TextTools; import io.xlorey.FluxLoader.client.ui.ScreenWidget; import io.xlorey.FluxLoader.client.ui.pluginMenu.MainMenuButton; import io.xlorey.FluxLoader.client.ui.pluginMenu.PluginMenu; import io.xlorey.FluxLoader.interfaces.IWidget; import io.xlorey.FluxLoader.utils.Constants; import org.lwjglx.opengl.Display; import zombie.GameWindow; import zombie.core.Core; import zombie.core.opengl.RenderThread; import zombie.gameStates.MainScreenState; import zombie.ui.UIFont; import java.util.ArrayList;
15,712
package io.xlorey.FluxLoader.client.core; /** * Custom UI management system */ public class WidgetManager { /** * Pointer to the game window */ private static final long windowHandler = Display.getWindow(); /** * Implementation of ImGui GLFW */ private final static ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw(); /** * Implementation of ImGui GL3 */ private final static ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3(); /** * Flag indicating the initialization state of ImGui */ private static boolean isImGuiInit = false; /** * A register of all UI elements that should be rendered */
package io.xlorey.FluxLoader.client.core; /** * Custom UI management system */ public class WidgetManager { /** * Pointer to the game window */ private static final long windowHandler = Display.getWindow(); /** * Implementation of ImGui GLFW */ private final static ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw(); /** * Implementation of ImGui GL3 */ private final static ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3(); /** * Flag indicating the initialization state of ImGui */ private static boolean isImGuiInit = false; /** * A register of all UI elements that should be rendered */
public static ArrayList<IWidget> widgetsRegistry = new ArrayList<>();
4
2023-11-16 09:05:44+00:00
24k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/events/listeners/UtilityListener.java
[ { "identifier": "SkyBlock", "path": "src/main/java/com/sweattypalms/skyblock/SkyBlock.java", "snippet": "public final class SkyBlock extends JavaPlugin {\n\n private static SkyBlock instance;\n\n public static SkyBlock getInstance() {\n return instance;\n }\n\n public boolean debug = ...
import com.sweattypalms.skyblock.SkyBlock; import com.sweattypalms.skyblock.api.sequence.Sequence; import com.sweattypalms.skyblock.api.sequence.SequenceAction; import com.sweattypalms.skyblock.core.enchants.EnchantManager; import com.sweattypalms.skyblock.core.events.def.SkyblockDeathEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockInteractEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockMobDamagePlayerEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent; import com.sweattypalms.skyblock.core.helpers.PlaceholderFormatter; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.TriggerType; import com.sweattypalms.skyblock.core.items.builder.armor.IHeadHelmet; import com.sweattypalms.skyblock.core.items.builder.item.IShortBow; import com.sweattypalms.skyblock.core.mobs.builder.ISkyblockMob; import com.sweattypalms.skyblock.core.mobs.builder.dragons.DragonManager; import com.sweattypalms.skyblock.core.mobs.builder.dragons.IEndDragon; import com.sweattypalms.skyblock.core.mobs.builder.dragons.loot.IDragonLoot; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import net.minecraft.server.v1_8_R3.EntityLiving; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEnderDragonPart; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftItem; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftLivingEntity; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.*; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Text; import java.util.List;
16,799
package com.sweattypalms.skyblock.core.events.listeners; public class UtilityListener implements Listener { @NotNull private static SkyblockDeathEvent getSkyblockDeathEvent(LivingEntity livingEntity) { SkyblockDeathEvent.DeathCause reason; EntityDamageEvent lastDamageCause = livingEntity.getLastDamageCause(); if (lastDamageCause == null) { reason = SkyblockDeathEvent.DeathCause.OTHER; } else { reason = SkyblockDeathEvent.DeathCause.getCause(lastDamageCause.getCause()); } SkyblockDeathEvent _event; if (reason == SkyblockDeathEvent.DeathCause.ENTITY) { _event = new SkyblockDeathEvent(livingEntity.getKiller(), livingEntity); } else { _event = new SkyblockDeathEvent(livingEntity, reason); } return _event; } @EventHandler public void onJoin(PlayerJoinEvent event) { String message = "$eWelcome to $cSkyblock$e!"; message = PlaceholderFormatter.format(message); event.getPlayer().sendMessage(message); event.setJoinMessage(null); if (SkyblockPlayer.getSkyblockPlayer(event.getPlayer()) != null) return; new SkyblockPlayer(event.getPlayer()); } @EventHandler(priority = EventPriority.LOW) public void interactEventForwarder(PlayerInteractEvent event) { Player player = event.getPlayer(); SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player); TriggerType triggerType = TriggerType.getTriggerType(event.getAction()); if (triggerType == null || triggerType == TriggerType.NONE) return; SkyblockInteractEvent skyblockInteractEvent = new SkyblockInteractEvent(skyblockPlayer, triggerType); if (event.getClickedBlock() != null) { skyblockInteractEvent.setInteractedBlock(event.getClickedBlock()); } SkyBlock.getInstance().getServer().getPluginManager().callEvent(skyblockInteractEvent); if (skyblockInteractEvent.isCancelled()) event.setCancelled(true); } @EventHandler public void equipHelmetThroughEvent(PlayerInteractEvent event) { Player player = event.getPlayer(); ItemStack itemInHand = player.getInventory().getItemInHand(); SkyblockItem skyblockItem = SkyblockItem.fromItemStack(itemInHand); if (skyblockItem == null) return; if (skyblockItem.getItemType() != SkyblockItemType.HELMET || !(skyblockItem instanceof IHeadHelmet)) return; if (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR) { player.getInventory().setHelmet(itemInHand); player.getInventory().setItemInHand(null); } } /** * For forwarding the EntityDeathEvent to the SkyblockDeathEvent * * @param event EntityDeathEvent */ @EventHandler(priority = EventPriority.LOW) public void onDeathBukkit(EntityDeathEvent event) { LivingEntity livingEntity = event.getEntity(); event.setDroppedExp(0); event.getDrops().clear(); if (livingEntity instanceof Player player) { SkyblockDeathEvent _event = new SkyblockDeathEvent(player, SkyblockDeathEvent.DeathCause.OTHER); Bukkit.getPluginManager().callEvent(_event); return; } EntityLiving entityLiving = ((CraftLivingEntity) event.getEntity()).getHandle(); if (!(entityLiving instanceof ISkyblockMob skyblockMob)) return; SkyblockDeathEvent _event = getSkyblockDeathEvent(livingEntity); SkyBlock.getInstance().getServer().getPluginManager().callEvent(_event); } @EventHandler public void playerDeathBukkit(PlayerDeathEvent event) { event.setDeathMessage(null); event.setKeepInventory(true); event.setKeepLevel(true); event.setDroppedExp(0);
package com.sweattypalms.skyblock.core.events.listeners; public class UtilityListener implements Listener { @NotNull private static SkyblockDeathEvent getSkyblockDeathEvent(LivingEntity livingEntity) { SkyblockDeathEvent.DeathCause reason; EntityDamageEvent lastDamageCause = livingEntity.getLastDamageCause(); if (lastDamageCause == null) { reason = SkyblockDeathEvent.DeathCause.OTHER; } else { reason = SkyblockDeathEvent.DeathCause.getCause(lastDamageCause.getCause()); } SkyblockDeathEvent _event; if (reason == SkyblockDeathEvent.DeathCause.ENTITY) { _event = new SkyblockDeathEvent(livingEntity.getKiller(), livingEntity); } else { _event = new SkyblockDeathEvent(livingEntity, reason); } return _event; } @EventHandler public void onJoin(PlayerJoinEvent event) { String message = "$eWelcome to $cSkyblock$e!"; message = PlaceholderFormatter.format(message); event.getPlayer().sendMessage(message); event.setJoinMessage(null); if (SkyblockPlayer.getSkyblockPlayer(event.getPlayer()) != null) return; new SkyblockPlayer(event.getPlayer()); } @EventHandler(priority = EventPriority.LOW) public void interactEventForwarder(PlayerInteractEvent event) { Player player = event.getPlayer(); SkyblockPlayer skyblockPlayer = SkyblockPlayer.getSkyblockPlayer(player); TriggerType triggerType = TriggerType.getTriggerType(event.getAction()); if (triggerType == null || triggerType == TriggerType.NONE) return; SkyblockInteractEvent skyblockInteractEvent = new SkyblockInteractEvent(skyblockPlayer, triggerType); if (event.getClickedBlock() != null) { skyblockInteractEvent.setInteractedBlock(event.getClickedBlock()); } SkyBlock.getInstance().getServer().getPluginManager().callEvent(skyblockInteractEvent); if (skyblockInteractEvent.isCancelled()) event.setCancelled(true); } @EventHandler public void equipHelmetThroughEvent(PlayerInteractEvent event) { Player player = event.getPlayer(); ItemStack itemInHand = player.getInventory().getItemInHand(); SkyblockItem skyblockItem = SkyblockItem.fromItemStack(itemInHand); if (skyblockItem == null) return; if (skyblockItem.getItemType() != SkyblockItemType.HELMET || !(skyblockItem instanceof IHeadHelmet)) return; if (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR) { player.getInventory().setHelmet(itemInHand); player.getInventory().setItemInHand(null); } } /** * For forwarding the EntityDeathEvent to the SkyblockDeathEvent * * @param event EntityDeathEvent */ @EventHandler(priority = EventPriority.LOW) public void onDeathBukkit(EntityDeathEvent event) { LivingEntity livingEntity = event.getEntity(); event.setDroppedExp(0); event.getDrops().clear(); if (livingEntity instanceof Player player) { SkyblockDeathEvent _event = new SkyblockDeathEvent(player, SkyblockDeathEvent.DeathCause.OTHER); Bukkit.getPluginManager().callEvent(_event); return; } EntityLiving entityLiving = ((CraftLivingEntity) event.getEntity()).getHandle(); if (!(entityLiving instanceof ISkyblockMob skyblockMob)) return; SkyblockDeathEvent _event = getSkyblockDeathEvent(livingEntity); SkyBlock.getInstance().getServer().getPluginManager().callEvent(_event); } @EventHandler public void playerDeathBukkit(PlayerDeathEvent event) { event.setDeathMessage(null); event.setKeepInventory(true); event.setKeepLevel(true); event.setDroppedExp(0);
new Sequence().add(
1
2023-11-15 15:05:58+00:00
24k
GoogleCloudPlatform/dataflow-ordered-processing
simulator/src/main/java/com/google/cloud/simulator/Simulator.java
[ { "identifier": "Matcher", "path": "business-model/src/main/java/com/google/cloud/orderbook/Matcher.java", "snippet": "public class Matcher {\n\n // Ordering orders in a tree -- ordered by price and orderId\n // (orderId is always increasing)\n private class OrderKey {\n\n OrderKey(long price, lon...
import com.google.cloud.orderbook.Matcher; import com.google.cloud.orderbook.MatcherContext; import com.google.cloud.orderbook.Order; import com.google.cloud.orderbook.model.OrderBookEvent; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import java.lang.Math;
20,883
/* * Copyright 2023 Google LLC * * 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 com.google.cloud.simulator; /* * Simulator that generates orders against a matcher. */ public class Simulator { /** * Create a complex (multiple contract) simulator. * * @param context MatcherContext for the context of the matching engine * @param numContracts Number of contracts to generate * @param midPrice Starting mid price for all contracts * @param seed Random seed (0 = default randomization) * @param degreeDist Degree of uneven distribution (0 = unform, 1 = linear, 2 = power of 2, etc) * @return Iterable<OrderbookEvent> -- produce OrderBookEvents from the simulator */ static public Iterator<List<OrderBookEvent>> getComplexSimulator( MatcherContext context, long numContracts, long midPrice, long seed, long degreeDistribution) { // Minimum tick long minTicks = 10; // Maximum delay -- number of ticks to wait until sending the next order long maxTicks = 50; // Start all of the simulators for (long i = 1; i <= numContracts; i++) { // Calculate a number between 0 and 1 (but not one) double degreeToOne = 1-Math.pow(((double)i/numContracts), degreeDistribution); // Convert to the number of ticks long orderTicks = minTicks + Math.round((maxTicks - minTicks) * degreeToOne); new Simulator(context, i, midPrice, seed, orderTicks); } return context.iterator(); } private final MatcherContext context;
/* * Copyright 2023 Google LLC * * 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 com.google.cloud.simulator; /* * Simulator that generates orders against a matcher. */ public class Simulator { /** * Create a complex (multiple contract) simulator. * * @param context MatcherContext for the context of the matching engine * @param numContracts Number of contracts to generate * @param midPrice Starting mid price for all contracts * @param seed Random seed (0 = default randomization) * @param degreeDist Degree of uneven distribution (0 = unform, 1 = linear, 2 = power of 2, etc) * @return Iterable<OrderbookEvent> -- produce OrderBookEvents from the simulator */ static public Iterator<List<OrderBookEvent>> getComplexSimulator( MatcherContext context, long numContracts, long midPrice, long seed, long degreeDistribution) { // Minimum tick long minTicks = 10; // Maximum delay -- number of ticks to wait until sending the next order long maxTicks = 50; // Start all of the simulators for (long i = 1; i <= numContracts; i++) { // Calculate a number between 0 and 1 (but not one) double degreeToOne = 1-Math.pow(((double)i/numContracts), degreeDistribution); // Convert to the number of ticks long orderTicks = minTicks + Math.round((maxTicks - minTicks) * degreeToOne); new Simulator(context, i, midPrice, seed, orderTicks); } return context.iterator(); } private final MatcherContext context;
private final Matcher m;
0
2023-11-15 21:26:06+00:00
24k
Hikaito/Fox-Engine
src/system/project/ProjectManager.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import system.Program; import system.backbone.ColorAdapter; import system.layerTree.RendererTypeAdapter; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.layerTree.data.TreeUnit; import system.backbone.FileOperations; import system.backbone.VersionNumber; import system.gui.WarningWindow; import system.project.treeElements.ProjectFolderInterface; import system.project.treeElements.*; import system.gui.project.ProjectEditor; import system.gui.project.ProjectFileSelection; import system.gui.project.ProjectReconciliation; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedList; import java.util.SortedSet; import java.util.TreeSet;
19,255
package system.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectManager { // UUID methods public String getUUID(){return root.getUUID();} public boolean matchesUUID(String other){ return root.getUUID().equals(other); } public String getTitle(){return root.getTitle();} // reject if program number is lower than project public static boolean evaluateProjectNumber(VersionNumber program, VersionNumber project){ if(program.compareTo(project) < 0) return false; return true; } // project root protected ProjectRoot root; public ProjectRoot getRoot(){return root;} // tree generation public DefaultMutableTreeNode getTree(){ return root.getTree(); } // updates menu offshoot entities public void updateDependencies(){ buildDictionary(); root.generateMenu(); } //region dictionary---------------------------- // dictionary protected HashMap<Long, ProjectFile> dictionary; //build dictionary public void buildDictionary(){ dictionary = new HashMap<>(); // generate new dictionary addDict(root); // build from root } // build dictionary recursive protected void addDict(ProjectUnitCore root){ // case file: add to dictionary if (root instanceof ProjectFile){ ProjectFile unit = (ProjectFile) root; //cast object dictionary.put(unit.getID(), unit); } //recurse to all children for file types else if (root instanceof ProjectFolderInterface){ ProjectFolderInterface unit = (ProjectFolderInterface) root; //cast object for (ProjectUnitCore child: unit.getChildren()){ addDict(child); } } } //query dictionary; returns null if none found public ProjectFile getFile(long code){ // return null if nocode if(code == Program.getDefaultFileCode()) return null; return dictionary.get(code); } // endregion // save file------------------------------------ // GSON builder private static final Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag .setPrettyPrinting() // creates a pretty version of the output .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter .registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer .registerTypeAdapter(ProjectUnitCore.class, new ProjectTypeAdapter()) // registers abstract classes .create(); // function for saving file public boolean saveFile(){ // derive json String json = gson.toJson(root); //generate absolute path to location String path = Paths.get(root.getPath(), Program.getProjectFile()).toString(); // write json to file try { FileWriter out = new FileWriter(path, false); out.write(json); out.close(); // log action Program.log("File '" + Program.getProjectFile() + "' saved as project file at " + path); } catch (IOException e) { e.printStackTrace(); return false; } return true; } // initialization function---------------------------- public void initializeEmpty(){ root = new ProjectRoot("Null Project"); //create project root Program.log("Project initialized from filesystem."); } public void initializeProject(String fullpath){ // attempt opening ProjectRoot tempRoot = readTree(fullpath); // read file // test version number if(!evaluateProjectNumber(Program.getProgramVersion(), tempRoot.getProgramVersion())){ WarningWindow.warningWindow("Project version invalid. Program version: " + Program.getProgramVersion() + "; Project version: " + tempRoot.getProgramVersion()); initializeEmpty(); return; } // open directory root = tempRoot; // if project version acceptible, save project root = readTree(fullpath); Program.log("Project at "+ fullpath + " imported."); // open file editing dialogue // dictionary generated on window close try { ProjectEditor window = new ProjectEditor(this); } catch (IOException e) { e.printStackTrace(); } } protected ProjectRoot readTree(String fullpath){ // open directory File file = new File(fullpath); // create file object to represent path String title = file.getName(); //set project name to folder title ProjectRoot tempRoot = new ProjectRoot(title); //create project root tempRoot.setPath(fullpath); //set directory path // recurse for each item in folder on created folder as parent File[] files = file.listFiles(); assert files != null; for(File child: files){ initializeTree(tempRoot.getChildren(), child, tempRoot); } // generate parents when complete tempRoot.generateParents(); Program.log("Project at "+ fullpath + " read from filesystem."); return tempRoot; } protected void initializeTree(LinkedList<ProjectUnitCore> folder, File file, ProjectRoot temproot){ //recursive case: folder; repeat call for each file inside if (file.isDirectory()){ // exclude internal folders if(file.getAbsolutePath().endsWith(Program.getSaveFolder()) || file.getAbsolutePath().endsWith(Program.getRenderFolder()) || file.getAbsolutePath().endsWith(Program.getTemplateFolder())){ return; } // create a folder node and add to tree ProjectFolder folderObj = new ProjectFolder(file.getName(), temproot.getNextID()); folder.addLast(folderObj); // recurse for each item in folder on created folder as parent File[] files = file.listFiles(); assert files != null; for(File child: files){ initializeTree(folderObj.getChildren(), child, temproot); } } // base case: file. add file if a valid file is found else{ // if the file has a valid extension
package system.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectManager { // UUID methods public String getUUID(){return root.getUUID();} public boolean matchesUUID(String other){ return root.getUUID().equals(other); } public String getTitle(){return root.getTitle();} // reject if program number is lower than project public static boolean evaluateProjectNumber(VersionNumber program, VersionNumber project){ if(program.compareTo(project) < 0) return false; return true; } // project root protected ProjectRoot root; public ProjectRoot getRoot(){return root;} // tree generation public DefaultMutableTreeNode getTree(){ return root.getTree(); } // updates menu offshoot entities public void updateDependencies(){ buildDictionary(); root.generateMenu(); } //region dictionary---------------------------- // dictionary protected HashMap<Long, ProjectFile> dictionary; //build dictionary public void buildDictionary(){ dictionary = new HashMap<>(); // generate new dictionary addDict(root); // build from root } // build dictionary recursive protected void addDict(ProjectUnitCore root){ // case file: add to dictionary if (root instanceof ProjectFile){ ProjectFile unit = (ProjectFile) root; //cast object dictionary.put(unit.getID(), unit); } //recurse to all children for file types else if (root instanceof ProjectFolderInterface){ ProjectFolderInterface unit = (ProjectFolderInterface) root; //cast object for (ProjectUnitCore child: unit.getChildren()){ addDict(child); } } } //query dictionary; returns null if none found public ProjectFile getFile(long code){ // return null if nocode if(code == Program.getDefaultFileCode()) return null; return dictionary.get(code); } // endregion // save file------------------------------------ // GSON builder private static final Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag .setPrettyPrinting() // creates a pretty version of the output .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter .registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer .registerTypeAdapter(ProjectUnitCore.class, new ProjectTypeAdapter()) // registers abstract classes .create(); // function for saving file public boolean saveFile(){ // derive json String json = gson.toJson(root); //generate absolute path to location String path = Paths.get(root.getPath(), Program.getProjectFile()).toString(); // write json to file try { FileWriter out = new FileWriter(path, false); out.write(json); out.close(); // log action Program.log("File '" + Program.getProjectFile() + "' saved as project file at " + path); } catch (IOException e) { e.printStackTrace(); return false; } return true; } // initialization function---------------------------- public void initializeEmpty(){ root = new ProjectRoot("Null Project"); //create project root Program.log("Project initialized from filesystem."); } public void initializeProject(String fullpath){ // attempt opening ProjectRoot tempRoot = readTree(fullpath); // read file // test version number if(!evaluateProjectNumber(Program.getProgramVersion(), tempRoot.getProgramVersion())){ WarningWindow.warningWindow("Project version invalid. Program version: " + Program.getProgramVersion() + "; Project version: " + tempRoot.getProgramVersion()); initializeEmpty(); return; } // open directory root = tempRoot; // if project version acceptible, save project root = readTree(fullpath); Program.log("Project at "+ fullpath + " imported."); // open file editing dialogue // dictionary generated on window close try { ProjectEditor window = new ProjectEditor(this); } catch (IOException e) { e.printStackTrace(); } } protected ProjectRoot readTree(String fullpath){ // open directory File file = new File(fullpath); // create file object to represent path String title = file.getName(); //set project name to folder title ProjectRoot tempRoot = new ProjectRoot(title); //create project root tempRoot.setPath(fullpath); //set directory path // recurse for each item in folder on created folder as parent File[] files = file.listFiles(); assert files != null; for(File child: files){ initializeTree(tempRoot.getChildren(), child, tempRoot); } // generate parents when complete tempRoot.generateParents(); Program.log("Project at "+ fullpath + " read from filesystem."); return tempRoot; } protected void initializeTree(LinkedList<ProjectUnitCore> folder, File file, ProjectRoot temproot){ //recursive case: folder; repeat call for each file inside if (file.isDirectory()){ // exclude internal folders if(file.getAbsolutePath().endsWith(Program.getSaveFolder()) || file.getAbsolutePath().endsWith(Program.getRenderFolder()) || file.getAbsolutePath().endsWith(Program.getTemplateFolder())){ return; } // create a folder node and add to tree ProjectFolder folderObj = new ProjectFolder(file.getName(), temproot.getNextID()); folder.addLast(folderObj); // recurse for each item in folder on created folder as parent File[] files = file.listFiles(); assert files != null; for(File child: files){ initializeTree(folderObj.getChildren(), child, temproot); } } // base case: file. add file if a valid file is found else{ // if the file has a valid extension
if (FileOperations.validExtension(file.getName(), Program.getFileExtensionLoadImage())) {
6
2023-11-12 21:12:21+00:00
24k
ryosoraa/E-Rapor
src/main/java/com/erapor/erapor/service/UserServices.java
[ { "identifier": "ApiException", "path": "src/main/java/com/erapor/erapor/exception/ApiException.java", "snippet": "public class ApiException extends RuntimeException{\n public ApiException(String message) {\n super(message);\n }\n}" }, { "identifier": "AccountsDAO", "path": "src...
import com.erapor.erapor.exception.ApiException; import com.erapor.erapor.model.DAO.AccountsDAO; import com.erapor.erapor.model.DTO.RegisterDTO; import com.erapor.erapor.repository.AccountsRepository; import com.erapor.erapor.security.BCrypt; import jakarta.validation.ConstraintViolation; import jakarta.validation.ConstraintViolationException; import jakarta.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Set;
16,512
package com.erapor.erapor.service; @Service public class UserServices { @Autowired AccountsRepository accountsRepository; @Autowired Validator validator; @Transactional
package com.erapor.erapor.service; @Service public class UserServices { @Autowired AccountsRepository accountsRepository; @Autowired Validator validator; @Transactional
public void register(RegisterDTO registerDTO){
2
2023-11-11 19:40:43+00:00
24k
shizotoaster/thaumon
common/src/main/java/jdlenl/thaumon/Thaumon.java
[ { "identifier": "ThaumonBlocks", "path": "common/src/main/java/jdlenl/thaumon/block/ThaumonBlocks.java", "snippet": "public class ThaumonBlocks {\n public static Supplier<Block> AMBER;\n public static Supplier<Block> AMBER_STAIRS;\n public static Supplier<Block> AMBER_SLAB;\n public static S...
import jdlenl.thaumon.block.ThaumonBlocks; import jdlenl.thaumon.item.ThaumonItems; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
14,486
package jdlenl.thaumon; public class Thaumon { public static final String MOD_ID = "thaumon"; public static Logger logger = LoggerFactory.getLogger(MOD_ID); public static void init() {
package jdlenl.thaumon; public class Thaumon { public static final String MOD_ID = "thaumon"; public static Logger logger = LoggerFactory.getLogger(MOD_ID); public static void init() {
ThaumonItems.init();
1
2023-11-16 06:03:29+00:00
24k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/predictionengine/predictions/PredictionEngineWater.java
[ { "identifier": "GrimPlayer", "path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java", "snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keep...
import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox; import ac.grim.grimac.utils.data.VectorData; import ac.grim.grimac.utils.enums.FluidTag; import ac.grim.grimac.utils.nmsutil.Collisions; import ac.grim.grimac.utils.nmsutil.FluidFallingAdjustedMovement; import io.github.retrooper.packetevents.utils.player.ClientVersion; import org.bukkit.util.Vector; import java.util.HashSet; import java.util.Set;
20,183
package ac.grim.grimac.predictionengine.predictions; public class PredictionEngineWater extends PredictionEngine { boolean isFalling; double playerGravity; float swimmingSpeed; float swimmingFriction; double lastY; public void guessBestMovement(float swimmingSpeed, GrimPlayer player, boolean isFalling, double playerGravity, float swimmingFriction, double lastY) { this.isFalling = isFalling; this.playerGravity = playerGravity; this.swimmingSpeed = swimmingSpeed; this.swimmingFriction = swimmingFriction; this.lastY = lastY; super.guessBestMovement(swimmingSpeed, player); } public static void staticVectorEndOfTick(GrimPlayer player, Vector vector, float swimmingFriction, double playerGravity, boolean isFalling) { vector.multiply(new Vector(swimmingFriction, 0.8F, swimmingFriction)); Vector fluidVector = FluidFallingAdjustedMovement.getFluidFallingAdjustedMovement(player, playerGravity, isFalling, vector); vector.setX(fluidVector.getX()); vector.setY(fluidVector.getY()); vector.setZ(fluidVector.getZ()); } @Override public void addJumpsToPossibilities(GrimPlayer player, Set<VectorData> existingVelocities) { for (VectorData vector : new HashSet<>(existingVelocities)) { existingVelocities.add(vector.returnNewModified(vector.vector.clone().add(new Vector(0, 0.04, 0)), VectorData.VectorType.Jump)); if (player.slightlyTouchingWater && player.lastOnGround && !player.onGround) { Vector withJump = vector.vector.clone(); super.doJump(player, withJump); existingVelocities.add(new VectorData(withJump, vector, VectorData.VectorType.Jump)); } } } @Override public void endOfTick(GrimPlayer player, double playerGravity, float friction) { super.endOfTick(player, playerGravity, friction); for (VectorData vector : player.getPossibleVelocitiesMinusKnockback()) { staticVectorEndOfTick(player, vector.vector, swimmingFriction, playerGravity, isFalling); } } @Override public Set<VectorData> fetchPossibleStartTickVectors(GrimPlayer player) { // "hacky" climbing where player enters ladder within 0.03 movement (WHY THE FUCK DOES 0.03 EXIST???) if (player.lastWasClimbing == 0 && player.pointThreeEstimator.isNearClimbable() && (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) || !Collisions.isEmpty(player, player.boundingBox.copy().expand( player.clientVelocity.getX(), 0, player.clientVelocity.getZ()).expand(0.5, -SimpleCollisionBox.COLLISION_EPSILON, 0.5)))) { player.lastWasClimbing = FluidFallingAdjustedMovement.getFluidFallingAdjustedMovement(player, playerGravity, isFalling, player.clientVelocity.clone().setY(0.2D * 0.8F)).getY(); } Set<VectorData> baseVelocities = super.fetchPossibleStartTickVectors(player); return transformSwimmingVectors(player, baseVelocities); } public static Set<VectorData> transformSwimmingVectors(GrimPlayer player, Set<VectorData> base) { Set<VectorData> swimmingVelocities = new HashSet<>(); // Vanilla checks for swimming // We check for: eye in water (last tick for some versions) // fluid on eyes (current tick) // Or vanilla is swimming // Or last tick swimming // // This stops players from abusing this mechanic while on top of water, which could theoretically allow // some form of a new Jesus hack. // Anyways, Jesus doesn't make too much sense on 1.13+ clients anyways when swimming is faster
package ac.grim.grimac.predictionengine.predictions; public class PredictionEngineWater extends PredictionEngine { boolean isFalling; double playerGravity; float swimmingSpeed; float swimmingFriction; double lastY; public void guessBestMovement(float swimmingSpeed, GrimPlayer player, boolean isFalling, double playerGravity, float swimmingFriction, double lastY) { this.isFalling = isFalling; this.playerGravity = playerGravity; this.swimmingSpeed = swimmingSpeed; this.swimmingFriction = swimmingFriction; this.lastY = lastY; super.guessBestMovement(swimmingSpeed, player); } public static void staticVectorEndOfTick(GrimPlayer player, Vector vector, float swimmingFriction, double playerGravity, boolean isFalling) { vector.multiply(new Vector(swimmingFriction, 0.8F, swimmingFriction)); Vector fluidVector = FluidFallingAdjustedMovement.getFluidFallingAdjustedMovement(player, playerGravity, isFalling, vector); vector.setX(fluidVector.getX()); vector.setY(fluidVector.getY()); vector.setZ(fluidVector.getZ()); } @Override public void addJumpsToPossibilities(GrimPlayer player, Set<VectorData> existingVelocities) { for (VectorData vector : new HashSet<>(existingVelocities)) { existingVelocities.add(vector.returnNewModified(vector.vector.clone().add(new Vector(0, 0.04, 0)), VectorData.VectorType.Jump)); if (player.slightlyTouchingWater && player.lastOnGround && !player.onGround) { Vector withJump = vector.vector.clone(); super.doJump(player, withJump); existingVelocities.add(new VectorData(withJump, vector, VectorData.VectorType.Jump)); } } } @Override public void endOfTick(GrimPlayer player, double playerGravity, float friction) { super.endOfTick(player, playerGravity, friction); for (VectorData vector : player.getPossibleVelocitiesMinusKnockback()) { staticVectorEndOfTick(player, vector.vector, swimmingFriction, playerGravity, isFalling); } } @Override public Set<VectorData> fetchPossibleStartTickVectors(GrimPlayer player) { // "hacky" climbing where player enters ladder within 0.03 movement (WHY THE FUCK DOES 0.03 EXIST???) if (player.lastWasClimbing == 0 && player.pointThreeEstimator.isNearClimbable() && (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) || !Collisions.isEmpty(player, player.boundingBox.copy().expand( player.clientVelocity.getX(), 0, player.clientVelocity.getZ()).expand(0.5, -SimpleCollisionBox.COLLISION_EPSILON, 0.5)))) { player.lastWasClimbing = FluidFallingAdjustedMovement.getFluidFallingAdjustedMovement(player, playerGravity, isFalling, player.clientVelocity.clone().setY(0.2D * 0.8F)).getY(); } Set<VectorData> baseVelocities = super.fetchPossibleStartTickVectors(player); return transformSwimmingVectors(player, baseVelocities); } public static Set<VectorData> transformSwimmingVectors(GrimPlayer player, Set<VectorData> base) { Set<VectorData> swimmingVelocities = new HashSet<>(); // Vanilla checks for swimming // We check for: eye in water (last tick for some versions) // fluid on eyes (current tick) // Or vanilla is swimming // Or last tick swimming // // This stops players from abusing this mechanic while on top of water, which could theoretically allow // some form of a new Jesus hack. // Anyways, Jesus doesn't make too much sense on 1.13+ clients anyways when swimming is faster
if ((player.wasEyeInWater || player.fluidOnEyes == FluidTag.WATER || player.isSwimming || player.wasSwimming) && player.playerVehicle == null) {
3
2023-11-11 05:14:12+00:00
24k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/fragment/HomeFragment.java
[ { "identifier": "DataBaseHelper", "path": "app/src/main/java/com/buaa/food/DataBaseHelper.java", "snippet": "public class DataBaseHelper extends SQLiteOpenHelper {\n private static final String DB_NAME = \"BuaaFood.db\";\n private Context context;\n\n private ByteArrayOutputStream byteArrayOutp...
import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.AppCompatTextView; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import com.buaa.food.DataBaseHelper; import com.buaa.food.DishPreview; import com.buaa.food.http.glide.GlideApp; import com.buaa.food.ui.activity.DishDetailActivity; import com.bumptech.glide.load.MultiTransformation; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.load.resource.bitmap.CenterInside; import com.gyf.immersionbar.ImmersionBar; import com.hjq.base.FragmentPagerAdapter; import com.buaa.food.R; import com.buaa.food.app.AppFragment; import com.buaa.food.app.TitleBarFragment; import com.buaa.food.ui.activity.HomeActivity; import com.buaa.food.ui.adapter.TabAdapter; import com.buaa.food.widget.XCollapsingToolbarLayout; import com.umeng.commonsdk.debug.D; import java.util.ArrayList; import java.util.List; import java.util.Random; import timber.log.Timber;
21,044
package com.buaa.food.ui.fragment; public final class HomeFragment extends TitleBarFragment<HomeActivity> implements TabAdapter.OnTabListener, ViewPager.OnPageChangeListener,
package com.buaa.food.ui.fragment; public final class HomeFragment extends TitleBarFragment<HomeActivity> implements TabAdapter.OnTabListener, ViewPager.OnPageChangeListener,
XCollapsingToolbarLayout.OnScrimsListener {
8
2023-11-14 10:04:26+00:00
24k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/processed/BlockModel.java
[ { "identifier": "ModelHelper", "path": "src/main/java/useless/dragonfly/helper/ModelHelper.java", "snippet": "public class ModelHelper {\n\tpublic static final Map<NamespaceId, ModelData> modelDataFiles = new HashMap<>();\n\tpublic static final Map<NamespaceId, BlockModel> registeredModels = new HashMap...
import useless.dragonfly.helper.ModelHelper; import useless.dragonfly.model.block.data.ModelData; import useless.dragonfly.model.block.data.PositionData; import useless.dragonfly.registries.TextureRegistry; import useless.dragonfly.utilities.NamespaceId; import javax.annotation.Nonnull; import java.util.HashMap;
16,118
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0];
package useless.dragonfly.model.block.processed; public class BlockModel { private static final HashMap<String, PositionData> defaultDisplays = new HashMap<>(); static { PositionData gui = new PositionData(); gui.rotation = new double[]{30, 225, 0}; gui.translation = new double[] {0, 0, 0}; gui.scale = new double[]{0.625, 0.625, 0.625}; PositionData ground = new PositionData(); ground.rotation = new double[]{0, 0, 0}; ground.translation = new double[] {0, 3, 0}; ground.scale = new double[]{0.25, 0.25, 0.25}; PositionData right_3rd = new PositionData(); right_3rd.rotation = new double[]{75, 45, 0}; right_3rd.translation = new double[] {0, 2.5, 0}; right_3rd.scale = new double[]{0.375, 0.375, 0.375}; PositionData right_first = new PositionData(); right_first.rotation = new double[]{0, 45, 0}; right_first.translation = new double[] {0, 0, 0}; right_first.scale = new double[]{0.4, 0.4, 0.4}; defaultDisplays.put("gui", gui); defaultDisplays.put("ground", ground); defaultDisplays.put("thirdperson_righthand", right_3rd); defaultDisplays.put("firstperson_righthand", right_first); } public BlockCube[] blockCubes = new BlockCube[0];
protected ModelData modelData;
1
2023-11-16 01:10:52+00:00
24k
AntonyCheng/ai-bi
src/test/java/top/sharehome/springbootinittemplate/redisson/TestRedisson.java
[ { "identifier": "CustomizeReturnException", "path": "src/main/java/top/sharehome/springbootinittemplate/exception/customize/CustomizeReturnException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class CustomizeReturnException extends RuntimeException {\n\n private ReturnCode ...
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ThreadUtils; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.lock.LockUtils; import top.sharehome.springbootinittemplate.utils.redisson.lock.function.SuccessFunction; import top.sharehome.springbootinittemplate.utils.redisson.lock.function.VoidFunction; import top.sharehome.springbootinittemplate.utils.redisson.rateLimit.RateLimitUtils; import java.time.Duration; import java.util.*;
14,689
package top.sharehome.springbootinittemplate.redisson; /** * 测试缓存类 * * @author AntonyCheng */ @SpringBootTest @Slf4j public class TestRedisson { /** * 测试缓存工具类 */ @Test void testCacheUtils() { // 测试字符串 CacheUtils.putString("test", "test"); System.out.println(CacheUtils.getString("test")); System.out.println(CacheUtils.existsString("test")); CacheUtils.deleteString("test"); // 测试数字 CacheUtils.putNumber("test", 9999999999L); System.out.println(CacheUtils.getNumberDoubleValue("test")); System.out.println(CacheUtils.existsNumber("test")); CacheUtils.deleteNumber("test"); // 测试List List<String> l = new ArrayList<String>() { { add("test1"); add("test2"); } }; CacheUtils.putList("test", l); System.out.println(CacheUtils.getList("test")); System.out.println(CacheUtils.existsList("test")); CacheUtils.deleteList("test"); // 测试Set Set<String> s = new HashSet<String>() { { add("test1"); add("test2"); } }; CacheUtils.putSet("test", s); System.out.println(CacheUtils.getSet("test")); System.out.println(CacheUtils.existsSet("test")); CacheUtils.deleteSet("test"); // 测试Map Map<String, String> m = new HashMap<String, String>() { { put("test1", "test1"); put("test2", "test2"); } }; CacheUtils.putMap("test", m); System.out.println(CacheUtils.getMap("test")); System.out.println(CacheUtils.existsMap("test")); CacheUtils.deleteMap("test"); // 测试使用通配符模糊操作 for (int i = 0; i < 100; i++) { HashMap<String, String> stringStringHashMap = new HashMap<>(); stringStringHashMap.put("test" + i, "test" + i); CacheUtils.put("test" + i, stringStringHashMap); } List<String> keysByPattern = CacheUtils.getKeysByPattern("test*"); Map<String, Object> keyValuesByPattern = CacheUtils.getKeyValuesByPattern("test*"); CacheUtils.deleteByPattern("test*"); } /** * 测试限流工具类 */ @Test void testRateLimitUtils() throws InterruptedException { for (int i = 0; i < 5; i++) { try { RateLimitUtils.doRateLimit("test"); System.out.println(i);
package top.sharehome.springbootinittemplate.redisson; /** * 测试缓存类 * * @author AntonyCheng */ @SpringBootTest @Slf4j public class TestRedisson { /** * 测试缓存工具类 */ @Test void testCacheUtils() { // 测试字符串 CacheUtils.putString("test", "test"); System.out.println(CacheUtils.getString("test")); System.out.println(CacheUtils.existsString("test")); CacheUtils.deleteString("test"); // 测试数字 CacheUtils.putNumber("test", 9999999999L); System.out.println(CacheUtils.getNumberDoubleValue("test")); System.out.println(CacheUtils.existsNumber("test")); CacheUtils.deleteNumber("test"); // 测试List List<String> l = new ArrayList<String>() { { add("test1"); add("test2"); } }; CacheUtils.putList("test", l); System.out.println(CacheUtils.getList("test")); System.out.println(CacheUtils.existsList("test")); CacheUtils.deleteList("test"); // 测试Set Set<String> s = new HashSet<String>() { { add("test1"); add("test2"); } }; CacheUtils.putSet("test", s); System.out.println(CacheUtils.getSet("test")); System.out.println(CacheUtils.existsSet("test")); CacheUtils.deleteSet("test"); // 测试Map Map<String, String> m = new HashMap<String, String>() { { put("test1", "test1"); put("test2", "test2"); } }; CacheUtils.putMap("test", m); System.out.println(CacheUtils.getMap("test")); System.out.println(CacheUtils.existsMap("test")); CacheUtils.deleteMap("test"); // 测试使用通配符模糊操作 for (int i = 0; i < 100; i++) { HashMap<String, String> stringStringHashMap = new HashMap<>(); stringStringHashMap.put("test" + i, "test" + i); CacheUtils.put("test" + i, stringStringHashMap); } List<String> keysByPattern = CacheUtils.getKeysByPattern("test*"); Map<String, Object> keyValuesByPattern = CacheUtils.getKeyValuesByPattern("test*"); CacheUtils.deleteByPattern("test*"); } /** * 测试限流工具类 */ @Test void testRateLimitUtils() throws InterruptedException { for (int i = 0; i < 5; i++) { try { RateLimitUtils.doRateLimit("test"); System.out.println(i);
} catch (CustomizeReturnException e) {
0
2023-11-12 07:49:59+00:00
24k
Shushandr/offroad
src/net/osmand/plus/render/TextRenderer.java
[ { "identifier": "PlatformUtil", "path": "src/net/osmand/PlatformUtil.java", "snippet": "public class PlatformUtil {\n\t\n\tpublic static Log getLog(Class<?> cl){\n\t\treturn LogFactory.getLog(cl);\n\t}\n\t\n\tpublic static XmlPullParser newXMLPullParser() throws XmlPullParserException{\n\t\treturn new o...
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.logging.Log; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TIntObjectProcedure; import net.osmand.PlatformUtil; import net.osmand.binary.BinaryMapDataObject; import net.osmand.binary.BinaryMapIndexReader.TagValuePair; import net.osmand.data.QuadRect; import net.osmand.data.QuadTree; import net.osmand.plus.render.OsmandRenderer.RenderingContext; import net.osmand.plus.render.OsmandRenderer.TextInfo; import net.osmand.render.RenderingRuleSearchRequest; import net.osmand.render.RenderingRulesStorage; import net.osmand.util.Algorithms; import net.sf.junidecode.Junidecode; import net.sourceforge.offroad.TextStroke; import net.sourceforge.offroad.ui.ColorUtils;
21,378
if(text.bold && text.italic) { fontStyle = Font.BOLD | Font.ITALIC; } else if(text.bold) { fontStyle = Font.BOLD; } else if(text.italic) { fontStyle = Font.ITALIC; } else { fontStyle = Font.PLAIN; } Font textFont = newGraphics.getFont().deriveFont(fontStyle, textSize); newGraphics.setFont(textFont); // paintText.setFakeBoldText(text.bold); newGraphics.setColor(createColor(text.textColor)); // align center y FontMetrics metr = newGraphics.getFontMetrics(); text.centerY += - metr.getAscent(); // calculate if there is intersection boolean intersects = findTextIntersection(newGraphics, rc, nonIntersectedBounds, text); if (!intersects) { if (text.drawOnPath != null) { float vOffset = text.vOffset - ( metr.getAscent()/2 + metr.getDescent()); if (text.textShadow > 0) { newGraphics.setColor(createColor(text.textShadowColor)); newGraphics.setStroke(new TextStroke(text.text, textFont, false, false, -vOffset)); newGraphics.draw(text.drawOnPath); } newGraphics.setColor(createColor(text.textColor)); newGraphics.setStroke(new TextStroke(text.text, textFont, false, false, -vOffset)); newGraphics.draw(text.drawOnPath); newGraphics.setStroke(new BasicStroke(0f)); } else { drawShieldIcon(rc, newGraphics, text, text.shieldRes); drawShieldIcon(rc, newGraphics, text, text.shieldResIcon); drawWrappedText(newGraphics, text, textSize); } } } } newGraphics.dispose(); } public Color createColor(int colorInt) { return ColorUtils.create(colorInt); } private void drawShieldIcon(RenderingContext rc, Graphics2D pGraphics2d, TextDrawInfo text, String sr) { if (sr != null) { float coef = rc.getDensityValue(rc.screenDensityRatio * rc.textScale); BufferedImage ico = RenderingIcons.getIcon(sr, true); if (ico != null) { log.debug("Got shield icon " + sr + ":" + ico.getWidth()+"x" + ico.getHeight()); float left = text.centerX - ico.getWidth() / 2 * coef - 0.5f; float top = text.centerY - ico.getHeight() / 2 * coef - pGraphics2d.getFontMetrics().getDescent() - 0.5f; if(rc.screenDensityRatio != 1f){ Rectangle2D rf = new Rectangle2D.Float(left, top, left + ico.getWidth() * coef, top + ico.getHeight() * coef); Rectangle2D src = new Rectangle2D.Float(0, 0, ico.getWidth(), ico .getHeight()); pGraphics2d.drawImage(ico, (int) rf.getX(), (int) rf.getY(), (int) rf.getMaxX(), (int) rf.getMaxY(), (int) src.getMinX(), (int) src.getMinY(), (int) src.getMaxX(), (int) src.getMaxY(), null); } else { pGraphics2d.drawImage(ico, (int)left, (int)top, null); } } } } private void drawWrappedText(Graphics2D pGraphics2d, TextDrawInfo text, float textSize) { if (text.textWrap == 0) { // set maximum for all text text.textWrap = 40; } if (text.text.length() > text.textWrap) { int start = 0; int end = text.text.length(); int lastSpace = -1; int line = 0; int pos = 0; int limit = 0; while (pos < end) { lastSpace = -1; limit += text.textWrap; while (pos < limit && pos < end) { if (!Character.isLetterOrDigit(text.text.charAt(pos))) { lastSpace = pos; } pos++; } if (lastSpace == -1 || pos == end) { drawTextOnCanvas(pGraphics2d, text.text.substring(start, pos), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = pos; } else { drawTextOnCanvas(pGraphics2d, text.text.substring(start, lastSpace), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = lastSpace + 1; limit += (start - pos) - 1; } line++; } } else { drawTextOnCanvas(pGraphics2d, text.text, text.centerX, text.centerY, text.textShadowColor, text.textShadow); } } private void createTextDrawInfo(final BinaryMapDataObject o, RenderingRuleSearchRequest render, Graphics2D pGraphics2d, RenderingContext rc, TagValuePair pair, final double xMid, double yMid, Path2D pPath, final Point2D[] points, String name, String tagName) { render.setInitialTagValueZoom(pair.tag, pair.value, rc.zoom, o); render.setIntFilter(render.ALL.R_TEXT_LENGTH, name.length()); render.setStringFilter(render.ALL.R_NAME_TAG, tagName); if(render.search(RenderingRulesStorage.TEXT_RULES)){ if(render.getFloatPropertyValue(render.ALL.R_TEXT_SIZE) > 0){ final TextDrawInfo text = new TextDrawInfo(name); text.fillProperties(rc, render, (float)xMid, (float)yMid); final String tagName2 = render.getStringPropertyValue(render.ALL.R_NAME_TAG2);
package net.osmand.plus.render; public class TextRenderer { private static final int MINIMAL_DISTANCE_BETWEEN_SHIELDS_IN_PIXEL = 200; private final static Log log = PlatformUtil.getLog(TextRenderer.class); // private Paint paintText; // private Paint paintIcon; // private Typeface defaultTypeface; // private Typeface boldItalicTypeface; // private Typeface italicTypeface; // private Typeface boldTypeface; static class TextDrawInfo { public TextDrawInfo(String text) { this.text = text; } String text = null; Path2D drawOnPath = null; QuadRect bounds = null; float vOffset = 0; float centerX = 0; float pathRotate = 0; float centerY = 0; float textSize = 0; float minDistance = 0; int textColor = Color.BLACK.getRGB(); int textShadow = 0; int textWrap = 0; boolean bold = false; boolean italic = false; String shieldRes = null; String shieldResIcon = null; int textOrder = 100; int textShadowColor = Color.WHITE.getRGB(); public void fillProperties(RenderingContext rc, RenderingRuleSearchRequest render, float centerX, float centerY) { this.centerX = centerX; // used only for draw on path where centerY doesn't play role this.vOffset = (int) rc.getComplexValue(render, render.ALL.R_TEXT_DY); this.centerY = centerY + this.vOffset; textColor = render.getIntPropertyValue(render.ALL.R_TEXT_COLOR); if (textColor == 0) { textColor = Color.BLACK.getRGB(); } textSize = rc.getComplexValue(render, render.ALL.R_TEXT_SIZE) ; textShadow = (int) rc.getComplexValue(render, render.ALL.R_TEXT_HALO_RADIUS); textShadowColor = render.getIntPropertyValue(render.ALL.R_TEXT_HALO_COLOR); if(textShadowColor == 0) { textShadowColor = Color.WHITE.getRGB(); } textWrap = (int) rc.getComplexValue(render, render.ALL.R_TEXT_WRAP_WIDTH); bold = render.getIntPropertyValue(render.ALL.R_TEXT_BOLD, 0) > 0; italic = render.getIntPropertyValue(render.ALL.R_TEXT_ITALIC, 0) > 0; minDistance = rc.getComplexValue(render, render.ALL.R_TEXT_MIN_DISTANCE); if (render.isSpecified(render.ALL.R_TEXT_SHIELD)) { shieldRes = render.getStringPropertyValue(render.ALL.R_TEXT_SHIELD); } if (render.isSpecified(render.ALL.R_ICON)) { shieldResIcon = render.getStringPropertyValue(render.ALL.R_ICON); } textOrder = render.getIntPropertyValue(render.ALL.R_TEXT_ORDER, 100); } } public TextRenderer() { // paintText = new Paint(); // paintText.setStyle(Style.FILL); // paintText.setStrokeWidth(1); // paintText.setColor(Color.BLACK); // paintText.setTextAlign(Align.CENTER); // defaultTypeface = Typeface.create("Droid Serif", Typeface.NORMAL); // boldItalicTypeface = Typeface.create("Droid Serif", Typeface.BOLD_ITALIC); // italicTypeface = Typeface.create("Droid Serif", Typeface.ITALIC); // boldTypeface = Typeface.create("Droid Serif", Typeface.BOLD); // paintText.setTypeface(defaultTypeface); //$NON-NLS-1$ // paintText.setAntiAlias(true); // // paintIcon = new Paint(); // paintIcon.setStyle(Style.STROKE); } private double sqr(double a) { return a * a; } private double fsqr(double pD) { return pD * pD; } boolean intersects(QuadRect tRect, float tRot, QuadRect sRect, float sRot) { if (Math.abs(tRot) < Math.PI / 15 && Math.abs(sRot) < Math.PI / 15) { return QuadRect.intersects(tRect, sRect); } double dist = Math.sqrt(sqr(tRect.centerX() - sRect.centerX()) + sqr(tRect.centerY() - sRect.centerY())); if (dist < MINIMAL_DISTANCE_BETWEEN_SHIELDS_IN_PIXEL) { return true; } // difference close to 90/270 degrees if (Math.abs(Math.cos(tRot - sRot)) < 0.3) { // rotate one rectangle to 90 degrees tRot += Math.PI / 2; double l = tRect.centerX() - tRect.height() / 2; double t = tRect.centerY() - tRect.width() / 2; tRect = new QuadRect(l, t, l + tRect.height(), t + tRect.width()); } // determine difference close to 180/0 degrees if (Math.abs(Math.sin(tRot - sRot)) < 0.3) { // rotate t box // (calculate offset for t center suppose we rotate around s center) float diff = (float) (-Math.atan2(tRect.centerX() - sRect.centerX(), tRect.centerY() - sRect.centerY()) + Math.PI / 2); diff -= sRot; double left = sRect.centerX() + dist * Math.cos(diff) - tRect.width() / 2; double top = sRect.centerY() - dist * Math.sin(diff) - tRect.height() / 2; QuadRect nRect = new QuadRect(left, top, left + tRect.width(), top + tRect.height()); return QuadRect.intersects(nRect, sRect); } // TODO other cases not covered return QuadRect.intersects(tRect, sRect); } void drawTestBox(Graphics2D pGraphics2d, Rectangle2D r, float rot, String text) { Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); // cv.save(); newGraphics.translate(r.getCenterX(), r.getCenterY()); newGraphics.rotate((float) (rot * 180 / Math.PI)); Rectangle2D rs = new Rectangle2D.Double(-r.getWidth() / 2, -r.getHeight() / 2, r.getWidth() / 2, r.getHeight() / 2); newGraphics.drawRect((int)rs.getX(), (int)rs.getY(), (int)rs.getWidth(), (int)rs.getHeight()); if (text != null) { // paintText.setTextSize(paintText.getTextSize() - 4); // System.out.println("Text " + text+ "; c=( " + rs.getCenterX() + ", " + rs.getCenterY() + ")"); newGraphics.drawString(text, (int)rs.getCenterX(), (int)rs.getCenterY()); // paintText.setTextSize(paintText.getTextSize() + 4); } // cv.restore(); newGraphics.dispose(); } List<TextDrawInfo> tempSearch = new ArrayList<TextDrawInfo>(); private boolean findTextIntersection(Graphics2D pGraphics2d, RenderingContext rc, QuadTree<TextDrawInfo> boundIntersections, TextDrawInfo text) { // for test purposes // drawTestBox(cv, text.bounds, text.pathRotate, text.text); boundIntersections.queryInBox(text.bounds, tempSearch); for (int i = 0; i < tempSearch.size(); i++) { TextDrawInfo t = tempSearch.get(i); if (intersects(text.bounds, text.pathRotate, t.bounds, t.pathRotate)) { return true; } } if (text.minDistance > 0) { QuadRect boundsSearch = new QuadRect(text.bounds); boundsSearch.inset(-Math.max(rc.getDensityValue(5.0f), text.minDistance), -rc.getDensityValue(15)); boundIntersections.queryInBox(boundsSearch, tempSearch); // drawTestBox(cv, &boundsSearch, text.pathRotate, paintIcon, text.text, NULL/*paintText*/); for (int i = 0; i < tempSearch.size(); i++) { TextDrawInfo t = tempSearch.get(i); if (t.minDistance > 0 && t.text.equals(text.text) && intersects(boundsSearch, text.pathRotate, t.bounds, t.pathRotate)) { return true; } } } boundIntersections.insert(text, text.bounds); return false; } private void drawTextOnCanvas(Graphics2D pGraphics2d, String text, float centerX, float centerY, int shadowColor, float textShadow) { Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); centerX -= newGraphics.getFontMetrics().stringWidth(text)/2; if (textShadow > 0) { Color c = newGraphics.getColor(); // paintText.setStyle(Style.STROKE); newGraphics.setColor(createColor(shadowColor)); newGraphics.setStroke(new BasicStroke(2 + textShadow)); newGraphics.drawString(text, centerX, centerY); // reset newGraphics.setStroke(new BasicStroke(2f)); // paintText.setStrokeWidth(2); // paintText.setStyle(Style.FILL); // paintText.setColor(c); newGraphics.setColor(c); } newGraphics.drawString(text, centerX, centerY); newGraphics.dispose(); } public void drawTextOverCanvas(RenderingContext rc, Graphics2D pGraphics2d, String preferredLocale) { int size = rc.textToDraw.size(); Graphics2D newGraphics = (Graphics2D) pGraphics2d.create(); // 1. Sort text using text order Collections.sort(rc.textToDraw, new Comparator<TextDrawInfo>() { @Override public int compare(TextDrawInfo object1, TextDrawInfo object2) { return object1.textOrder - object2.textOrder; } }); QuadRect r = new QuadRect(0, 0, rc.width, rc.height); r.inset(-100, -100); QuadTree<TextDrawInfo> nonIntersectedBounds = new QuadTree<TextDrawInfo>(r, 4, 0.6f); for (int i = 0; i < size; i++) { TextDrawInfo text = rc.textToDraw.get(i); if (text.text != null && text.text.length() > 0) { if (preferredLocale.length() > 0) { text.text = Junidecode.unidecode(text.text); } // sest text size before finding intersection (it is used there) float textSize = text.textSize * rc.textScale; int fontStyle = 0; if(text.bold && text.italic) { fontStyle = Font.BOLD | Font.ITALIC; } else if(text.bold) { fontStyle = Font.BOLD; } else if(text.italic) { fontStyle = Font.ITALIC; } else { fontStyle = Font.PLAIN; } Font textFont = newGraphics.getFont().deriveFont(fontStyle, textSize); newGraphics.setFont(textFont); // paintText.setFakeBoldText(text.bold); newGraphics.setColor(createColor(text.textColor)); // align center y FontMetrics metr = newGraphics.getFontMetrics(); text.centerY += - metr.getAscent(); // calculate if there is intersection boolean intersects = findTextIntersection(newGraphics, rc, nonIntersectedBounds, text); if (!intersects) { if (text.drawOnPath != null) { float vOffset = text.vOffset - ( metr.getAscent()/2 + metr.getDescent()); if (text.textShadow > 0) { newGraphics.setColor(createColor(text.textShadowColor)); newGraphics.setStroke(new TextStroke(text.text, textFont, false, false, -vOffset)); newGraphics.draw(text.drawOnPath); } newGraphics.setColor(createColor(text.textColor)); newGraphics.setStroke(new TextStroke(text.text, textFont, false, false, -vOffset)); newGraphics.draw(text.drawOnPath); newGraphics.setStroke(new BasicStroke(0f)); } else { drawShieldIcon(rc, newGraphics, text, text.shieldRes); drawShieldIcon(rc, newGraphics, text, text.shieldResIcon); drawWrappedText(newGraphics, text, textSize); } } } } newGraphics.dispose(); } public Color createColor(int colorInt) { return ColorUtils.create(colorInt); } private void drawShieldIcon(RenderingContext rc, Graphics2D pGraphics2d, TextDrawInfo text, String sr) { if (sr != null) { float coef = rc.getDensityValue(rc.screenDensityRatio * rc.textScale); BufferedImage ico = RenderingIcons.getIcon(sr, true); if (ico != null) { log.debug("Got shield icon " + sr + ":" + ico.getWidth()+"x" + ico.getHeight()); float left = text.centerX - ico.getWidth() / 2 * coef - 0.5f; float top = text.centerY - ico.getHeight() / 2 * coef - pGraphics2d.getFontMetrics().getDescent() - 0.5f; if(rc.screenDensityRatio != 1f){ Rectangle2D rf = new Rectangle2D.Float(left, top, left + ico.getWidth() * coef, top + ico.getHeight() * coef); Rectangle2D src = new Rectangle2D.Float(0, 0, ico.getWidth(), ico .getHeight()); pGraphics2d.drawImage(ico, (int) rf.getX(), (int) rf.getY(), (int) rf.getMaxX(), (int) rf.getMaxY(), (int) src.getMinX(), (int) src.getMinY(), (int) src.getMaxX(), (int) src.getMaxY(), null); } else { pGraphics2d.drawImage(ico, (int)left, (int)top, null); } } } } private void drawWrappedText(Graphics2D pGraphics2d, TextDrawInfo text, float textSize) { if (text.textWrap == 0) { // set maximum for all text text.textWrap = 40; } if (text.text.length() > text.textWrap) { int start = 0; int end = text.text.length(); int lastSpace = -1; int line = 0; int pos = 0; int limit = 0; while (pos < end) { lastSpace = -1; limit += text.textWrap; while (pos < limit && pos < end) { if (!Character.isLetterOrDigit(text.text.charAt(pos))) { lastSpace = pos; } pos++; } if (lastSpace == -1 || pos == end) { drawTextOnCanvas(pGraphics2d, text.text.substring(start, pos), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = pos; } else { drawTextOnCanvas(pGraphics2d, text.text.substring(start, lastSpace), text.centerX, text.centerY + line * (textSize + 2), text.textShadowColor, text.textShadow); start = lastSpace + 1; limit += (start - pos) - 1; } line++; } } else { drawTextOnCanvas(pGraphics2d, text.text, text.centerX, text.centerY, text.textShadowColor, text.textShadow); } } private void createTextDrawInfo(final BinaryMapDataObject o, RenderingRuleSearchRequest render, Graphics2D pGraphics2d, RenderingContext rc, TagValuePair pair, final double xMid, double yMid, Path2D pPath, final Point2D[] points, String name, String tagName) { render.setInitialTagValueZoom(pair.tag, pair.value, rc.zoom, o); render.setIntFilter(render.ALL.R_TEXT_LENGTH, name.length()); render.setStringFilter(render.ALL.R_NAME_TAG, tagName); if(render.search(RenderingRulesStorage.TEXT_RULES)){ if(render.getFloatPropertyValue(render.ALL.R_TEXT_SIZE) > 0){ final TextDrawInfo text = new TextDrawInfo(name); text.fillProperties(rc, render, (float)xMid, (float)yMid); final String tagName2 = render.getStringPropertyValue(render.ALL.R_NAME_TAG2);
if (!Algorithms.isEmpty(tagName2)) {
9
2023-11-15 05:04:55+00:00
24k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/config/HrmConfigController.java
[ { "identifier": "OperationLog", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java", "snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu...
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import com.kakarote.common.log.annotation.OperateLog; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.log.entity.OperationResult; import com.kakarote.common.log.enums.ApplyEnum; import com.kakarote.common.log.enums.BehaviorEnum; import com.kakarote.common.log.enums.OperateObjectEnum; import com.kakarote.common.log.enums.OperateTypeEnum; import com.kakarote.core.common.Result; import com.kakarote.core.entity.BasePage; import com.kakarote.core.entity.PageEntity; import com.kakarote.hrm.common.LanguageFieldUtil; import com.kakarote.hrm.constant.ConfigType; import com.kakarote.hrm.constant.LabelGroupEnum; import com.kakarote.hrm.entity.BO.AddEmployeeFieldBO; import com.kakarote.hrm.entity.BO.AddInsuranceSchemeBO; import com.kakarote.hrm.entity.BO.DeleteRecruitChannelBO; import com.kakarote.hrm.entity.BO.SetAchievementTableBO; import com.kakarote.hrm.entity.PO.*; import com.kakarote.hrm.entity.VO.*; import com.kakarote.hrm.service.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
15,477
package com.kakarote.hrm.controller.config; @RestController @RequestMapping("/hrmConfig") @Api(tags = "人力资源后台配置接口") public class HrmConfigController { @Autowired private IHrmConfigService configService; @Autowired private IHrmEmployeeFieldService employeeFieldService; @Autowired private IHrmInsuranceSchemeService insuranceSchemeService; @Autowired private IHrmAchievementTableService achievementTableService; @Autowired private IHrmRecruitChannelService recruitChannelService; @Autowired private IHrmEmployeeService employeeService; @Autowired private IHrmRecruitCandidateService recruitCandidateService; /** * --------------招聘渠道--------------- */ @PostMapping("/saveRecruitChannel") @ApiOperation("保存招聘渠道") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_BUSINESS_PARAM_SETTING, behavior = BehaviorEnum.UPDATE) public Result saveRecruitChannel(@RequestBody List<HrmRecruitChannel> channelList) { recruitChannelService.saveOrUpdateBatch(channelList); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject("招聘渠道"); operationLog.setOperationInfo("编辑招聘渠道"); return OperationResult.ok(operationLog); } @PostMapping("/queryRecruitChannelList") @ApiOperation("查询招聘渠道配置列表") public Result<List<HrmRecruitChannel>> queryRecruitChannelList() { List<HrmRecruitChannel> list = recruitChannelService.list(); if (CollectionUtil.isNotEmpty(list)) { for (HrmRecruitChannel channel : list) { //添加语言包key channel.setLanguageKeyMap(LanguageFieldUtil.getFieldNameKeyMap("value_resourceKey", "admin.recruitChannel.", channel.getValue())); } } return Result.ok(list); } @PostMapping("/deleteRecruitChannel") @ApiOperation("删除招聘渠道") public Result deleteRecruitChannel(@RequestBody DeleteRecruitChannelBO deleteRecruitChannelBO) { employeeService.lambdaUpdate() .set(HrmEmployee::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmEmployee::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitCandidateService.lambdaUpdate() .set(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitChannelService.removeById(deleteRecruitChannelBO.getDeleteChannelId()); return Result.ok(); } /** * --------------淘汰原因--------------- */ @PostMapping("/saveRecruitEliminate") @ApiOperation("保存淘汰原因") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_BUSINESS_PARAM_SETTING, behavior = BehaviorEnum.UPDATE) public Result saveRecruitEliminate(@RequestBody List<String> data) { configService.lambdaUpdate().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).remove(); List<HrmConfig> collect = data.stream().map(value -> { HrmConfig hrmConfig = new HrmConfig(); hrmConfig.setType(ConfigType.ELIMINATION_REASONS.getValue()); hrmConfig.setValue(value); return hrmConfig; }).collect(Collectors.toList()); configService.saveBatch(collect); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject("淘汰原因"); operationLog.setOperationInfo("编辑淘汰原因"); return OperationResult.ok(operationLog); } @PostMapping("/queryRecruitEliminateList") @ApiOperation("查询淘汰原因") public Result<RecruitEliminateVO> queryRecruitEliminateList() { RecruitEliminateVO eliminateVO = new RecruitEliminateVO(); List<String> list = configService.lambdaQuery().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).list() .stream().map(HrmConfig::getValue).collect(Collectors.toList()); Map<String, String> keyMap = new HashMap<>(); if (CollectionUtil.isNotEmpty(list)) { for (int i = 0; i < list.size(); i++) { if (StrUtil.isNotBlank(list.get(i))) { //添加语言包key keyMap.putAll(LanguageFieldUtil.getFieldNameKeyMap(StrUtil.toString(i), "hrm.config.1.", list.get(i))); } } eliminateVO.setLanguageKeyMap(keyMap); } eliminateVO.setRecruit(list); eliminateVO.setLanguageKeyMap(keyMap); return Result.ok(eliminateVO); } /** * --------------自定义字段--------------- */ @PostMapping("/queryFields") @ApiOperation("查询后台配置自定义字段列表") public Result<List<FiledListVO>> queryFields() { List<FiledListVO> fieldList = employeeFieldService.queryFields(); return Result.ok(fieldList); } @PostMapping("/queryFieldByLabel/{labelGroup}") @ApiOperation("查询后台配置自定义字段列表") public Result<List<List<HrmEmployeeField>>> queryFieldByLabel(@ApiParam("1 个人信息 2 通讯信息 7 联系人信息 11 岗位信息") @PathVariable("labelGroup") Integer labelGroup) { List<List<HrmEmployeeField>> data = employeeFieldService.queryFieldByLabel(labelGroup); return Result.ok(data); } @PostMapping("/saveField") @ApiOperation("保存后台自定义字段") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.UPDATE, object = OperateObjectEnum.HUMAN_MANAGEMENT_CUSTOM_FIELD) public Result saveField(@RequestBody AddEmployeeFieldBO addEmployeeFieldBO) { employeeFieldService.saveField(addEmployeeFieldBO);
package com.kakarote.hrm.controller.config; @RestController @RequestMapping("/hrmConfig") @Api(tags = "人力资源后台配置接口") public class HrmConfigController { @Autowired private IHrmConfigService configService; @Autowired private IHrmEmployeeFieldService employeeFieldService; @Autowired private IHrmInsuranceSchemeService insuranceSchemeService; @Autowired private IHrmAchievementTableService achievementTableService; @Autowired private IHrmRecruitChannelService recruitChannelService; @Autowired private IHrmEmployeeService employeeService; @Autowired private IHrmRecruitCandidateService recruitCandidateService; /** * --------------招聘渠道--------------- */ @PostMapping("/saveRecruitChannel") @ApiOperation("保存招聘渠道") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_BUSINESS_PARAM_SETTING, behavior = BehaviorEnum.UPDATE) public Result saveRecruitChannel(@RequestBody List<HrmRecruitChannel> channelList) { recruitChannelService.saveOrUpdateBatch(channelList); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject("招聘渠道"); operationLog.setOperationInfo("编辑招聘渠道"); return OperationResult.ok(operationLog); } @PostMapping("/queryRecruitChannelList") @ApiOperation("查询招聘渠道配置列表") public Result<List<HrmRecruitChannel>> queryRecruitChannelList() { List<HrmRecruitChannel> list = recruitChannelService.list(); if (CollectionUtil.isNotEmpty(list)) { for (HrmRecruitChannel channel : list) { //添加语言包key channel.setLanguageKeyMap(LanguageFieldUtil.getFieldNameKeyMap("value_resourceKey", "admin.recruitChannel.", channel.getValue())); } } return Result.ok(list); } @PostMapping("/deleteRecruitChannel") @ApiOperation("删除招聘渠道") public Result deleteRecruitChannel(@RequestBody DeleteRecruitChannelBO deleteRecruitChannelBO) { employeeService.lambdaUpdate() .set(HrmEmployee::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmEmployee::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitCandidateService.lambdaUpdate() .set(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getChangeChannelId()) .eq(HrmRecruitCandidate::getChannelId, deleteRecruitChannelBO.getDeleteChannelId()) .update(); recruitChannelService.removeById(deleteRecruitChannelBO.getDeleteChannelId()); return Result.ok(); } /** * --------------淘汰原因--------------- */ @PostMapping("/saveRecruitEliminate") @ApiOperation("保存淘汰原因") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.HUMAN_BUSINESS_PARAM_SETTING, behavior = BehaviorEnum.UPDATE) public Result saveRecruitEliminate(@RequestBody List<String> data) { configService.lambdaUpdate().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).remove(); List<HrmConfig> collect = data.stream().map(value -> { HrmConfig hrmConfig = new HrmConfig(); hrmConfig.setType(ConfigType.ELIMINATION_REASONS.getValue()); hrmConfig.setValue(value); return hrmConfig; }).collect(Collectors.toList()); configService.saveBatch(collect); OperationLog operationLog = new OperationLog(); operationLog.setOperationObject("淘汰原因"); operationLog.setOperationInfo("编辑淘汰原因"); return OperationResult.ok(operationLog); } @PostMapping("/queryRecruitEliminateList") @ApiOperation("查询淘汰原因") public Result<RecruitEliminateVO> queryRecruitEliminateList() { RecruitEliminateVO eliminateVO = new RecruitEliminateVO(); List<String> list = configService.lambdaQuery().eq(HrmConfig::getType, ConfigType.ELIMINATION_REASONS.getValue()).list() .stream().map(HrmConfig::getValue).collect(Collectors.toList()); Map<String, String> keyMap = new HashMap<>(); if (CollectionUtil.isNotEmpty(list)) { for (int i = 0; i < list.size(); i++) { if (StrUtil.isNotBlank(list.get(i))) { //添加语言包key keyMap.putAll(LanguageFieldUtil.getFieldNameKeyMap(StrUtil.toString(i), "hrm.config.1.", list.get(i))); } } eliminateVO.setLanguageKeyMap(keyMap); } eliminateVO.setRecruit(list); eliminateVO.setLanguageKeyMap(keyMap); return Result.ok(eliminateVO); } /** * --------------自定义字段--------------- */ @PostMapping("/queryFields") @ApiOperation("查询后台配置自定义字段列表") public Result<List<FiledListVO>> queryFields() { List<FiledListVO> fieldList = employeeFieldService.queryFields(); return Result.ok(fieldList); } @PostMapping("/queryFieldByLabel/{labelGroup}") @ApiOperation("查询后台配置自定义字段列表") public Result<List<List<HrmEmployeeField>>> queryFieldByLabel(@ApiParam("1 个人信息 2 通讯信息 7 联系人信息 11 岗位信息") @PathVariable("labelGroup") Integer labelGroup) { List<List<HrmEmployeeField>> data = employeeFieldService.queryFieldByLabel(labelGroup); return Result.ok(data); } @PostMapping("/saveField") @ApiOperation("保存后台自定义字段") @OperateLog(apply = ApplyEnum.HUMAN_RESOURCE_MANAGEMENT, type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.UPDATE, object = OperateObjectEnum.HUMAN_MANAGEMENT_CUSTOM_FIELD) public Result saveField(@RequestBody AddEmployeeFieldBO addEmployeeFieldBO) { employeeFieldService.saveField(addEmployeeFieldBO);
LabelGroupEnum parse = LabelGroupEnum.parse(addEmployeeFieldBO.getLabelGroup());
11
2023-10-17 05:49:52+00:00
24k
ballerina-platform/module-ballerinax-copybook
commons/src/main/java/io/ballerina/lib/copybook/commons/schema/SchemaBuilder.java
[ { "identifier": "CopybookVisitor", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/generated/CopybookVisitor.java", "snippet": "public interface CopybookVisitor<T> extends ParseTreeVisitor<T> {\n\t/**\n\t * Visit a parse tree produced by {@link CopybookParser#startRule}.\n\t * @param ct...
import io.ballerina.lib.copybook.commons.generated.CopybookVisitor; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.BooleanLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhRespLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CicsDfhValueLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.CobolWordContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.ConditionNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataBlankWhenZeroClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryClausesContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat1Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat2Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataDescriptionEntryFormat3Context; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataExternalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataGlobalClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataJustifiedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursSortContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataOccursToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataPictureClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRedefinesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataRenamesClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSignClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataSynchronizedClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataUsageClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueClauseContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalFromContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.DataValueIntervalToContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.FigurativeConstantContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IdentifierContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IndexNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.IntegerLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.LiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.NumericLiteralContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCardinalityContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureCharsContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.PictureStringContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.QualifiedDataNameContext; import static io.ballerina.lib.copybook.commons.generated.CopybookParser.StartRuleContext;
19,898
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0); DataOccursClauseContext occursClause = ctx.dataDescriptionEntryClauses().dataOccursClause(0); int occurs = Utils.getOccurringCount(occursClause); if (pictureClause == null || pictureClause.pictureString() == null) { return new GroupItem(level, name, occurs, redefinedItemName, getParent(level)); } PictureStringContext pictureType = pictureClause.pictureString(); validatePicture(pictureType); return new DataItem(level, name, Utils.getPictureString(pictureType), Utils.isNumeric(pictureType), Utils.getReadLength(pictureType), occurs, Utils.getFloatingPointLength(pictureType), redefinedItemName, getParent(level)); } private void validatePicture(PictureStringContext pictureType) { String pictureString = Utils.getPictureString(pictureType); if (PictureStringValidator.isSupportedPictureString(pictureString)) { return; } String errorMsg = "Unsupported picture string '" + pictureString + "' found in copybook schema"; this.addError(pictureType.start.getLine(), pictureType.start.getCharPositionInLine(), errorMsg); } private void addError(int line, int charPositionInLine, String msg) { this.errors.add("Error at line " + line + ", column " + charPositionInLine + ": " + msg); } @Override public CopybookNode visitDataDescriptionEntryClauses(DataDescriptionEntryClausesContext ctx) { return null; } private GroupItem getParent(int currentLevel) { GroupItem parent = this.possibleParent; while (parent != null && parent.getLevel() >= currentLevel) { parent = parent.getParent(); } return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override public CopybookNode visitDataGlobalClause(DataGlobalClauseContext ctx) { return null; } @Override
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class SchemaBuilder implements CopybookVisitor<CopybookNode> { private final Schema schema = new Schema(); private GroupItem possibleParent; private final Set<String> redefinedItemNames = new HashSet<>(); private final List<String> errors = new ArrayList<>(); Schema getSchema() { return this.schema; } @Override public CopybookNode visitStartRule(StartRuleContext ctx) { this.possibleParent = null; visitDataDescription(ctx.dataDescription()); for (CopybookNode typedef : this.schema.getTypeDefinitions()) { addRedefinedItems(typedef); } this.schema.addErrors(this.errors); return null; } private void addRedefinedItems(CopybookNode item) { if (this.redefinedItemNames.contains(item.getName())) { this.schema.addRedefinedItem(item); return; } if (item instanceof GroupItem groupItem) { groupItem.getChildren().forEach(this::addRedefinedItems); } } @Override public CopybookNode visitDataDescription(DataDescriptionContext ctx) { for (int i = 0; i < ctx.getChildCount(); i++) { CopybookNode copybookNode = visitDataDescriptionEntry(ctx.dataDescriptionEntry(i)); if (copybookNode instanceof GroupItem groupItem) { this.possibleParent = groupItem; } if (isRootLevelNode(copybookNode)) { this.schema.addTypeDefinition(copybookNode); } } return null; } private boolean isRootLevelNode(CopybookNode copybookNode) { return copybookNode != null && copybookNode.getLevel() == 1; } @Override public CopybookNode visitDataDescriptionEntry(DataDescriptionEntryContext ctx) { if (ctx.dataDescriptionEntryFormat1() != null) { return visitDataDescriptionEntryFormat1(ctx.dataDescriptionEntryFormat1()); } // skipping level 66 and 88 return null; } @Override public CopybookNode visitDataDescriptionEntryFormat1(DataDescriptionEntryFormat1Context ctx) { if (ctx.LEVEL_NUMBER_77() != null) { // skipping level 77 return null; } boolean redefines = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0) != null; String redefinedItemName = null; if (redefines) { redefinedItemName = ctx.dataDescriptionEntryClauses().dataRedefinesClause(0).dataName().getText(); this.redefinedItemNames.add(redefinedItemName); } int level = Integer.parseInt(ctx.INTEGERLITERAL().getText()); String name = ctx.dataName() != null ? ctx.dataName().getText() : ctx.FILLER().getText(); DataPictureClauseContext pictureClause = ctx.dataDescriptionEntryClauses().dataPictureClause(0); DataOccursClauseContext occursClause = ctx.dataDescriptionEntryClauses().dataOccursClause(0); int occurs = Utils.getOccurringCount(occursClause); if (pictureClause == null || pictureClause.pictureString() == null) { return new GroupItem(level, name, occurs, redefinedItemName, getParent(level)); } PictureStringContext pictureType = pictureClause.pictureString(); validatePicture(pictureType); return new DataItem(level, name, Utils.getPictureString(pictureType), Utils.isNumeric(pictureType), Utils.getReadLength(pictureType), occurs, Utils.getFloatingPointLength(pictureType), redefinedItemName, getParent(level)); } private void validatePicture(PictureStringContext pictureType) { String pictureString = Utils.getPictureString(pictureType); if (PictureStringValidator.isSupportedPictureString(pictureString)) { return; } String errorMsg = "Unsupported picture string '" + pictureString + "' found in copybook schema"; this.addError(pictureType.start.getLine(), pictureType.start.getCharPositionInLine(), errorMsg); } private void addError(int line, int charPositionInLine, String msg) { this.errors.add("Error at line " + line + ", column " + charPositionInLine + ": " + msg); } @Override public CopybookNode visitDataDescriptionEntryClauses(DataDescriptionEntryClausesContext ctx) { return null; } private GroupItem getParent(int currentLevel) { GroupItem parent = this.possibleParent; while (parent != null && parent.getLevel() >= currentLevel) { parent = parent.getParent(); } return parent; } @Override public CopybookNode visitDataDescriptionEntryFormat2(DataDescriptionEntryFormat2Context ctx) { return null; } @Override public CopybookNode visitDataDescriptionEntryFormat3(DataDescriptionEntryFormat3Context ctx) { return null; } @Override public CopybookNode visitDataBlankWhenZeroClause(DataBlankWhenZeroClauseContext ctx) { return null; } @Override public CopybookNode visitDataExternalClause(DataExternalClauseContext ctx) { return null; } @Override public CopybookNode visitDataGlobalClause(DataGlobalClauseContext ctx) { return null; } @Override
public CopybookNode visitDataJustifiedClause(DataJustifiedClauseContext ctx) {
15
2023-10-24 04:51:53+00:00
24k
zhaoeryu/eu-backend
eu-admin/src/main/java/cn/eu/security/controller/AuthController.java
[ { "identifier": "Constants", "path": "eu-common-core/src/main/java/cn/eu/common/constants/Constants.java", "snippet": "public class Constants {\n\n /** 当前登录账号是否管理的字段KEY */\n public static final String IS_ADMIN_KEY = \"isAdmin\";\n /** 当前登录账号信息的字段KEY */\n public static final String USER_KEY =...
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.annotation.SaIgnore; import cn.dev33.satoken.session.SaSession; import cn.dev33.satoken.session.TokenSign; import cn.dev33.satoken.stp.StpUtil; import cn.eu.common.annotation.Log; import cn.eu.common.constants.Constants; import cn.eu.common.enums.BusinessType; import cn.eu.common.model.PageResult; import cn.eu.common.model.ResultBody; import cn.eu.common.utils.RedisUtil; import cn.eu.security.SecurityUtil; import cn.eu.security.model.AuthUser; import cn.eu.security.model.LoginBody; import cn.eu.security.model.OnlineUserVo; import cn.eu.security.service.LoginService; import cn.eu.system.domain.SysUser; import cn.eu.system.service.ISysUserService; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.PageUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.wf.captcha.ArithmeticCaptcha; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
17,522
package cn.eu.security.controller; /** * @author zhaoeryu * @since 2023/6/3 */ @Slf4j @RequestMapping("/auth") @RestController public class AuthController { @Autowired LoginService loginService; @Autowired ISysUserService sysUserService; @Autowired RedisUtil redisUtil; @Log(title = "登录", businessType = BusinessType.LOGIN, isSaveResponseData = false, excludeParamNames = { "password" }) @SaIgnore @PostMapping("/login") public ResultBody login(@Validated @RequestBody LoginBody loginBody) { String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getUuid(), loginBody.getVerifyCode()); return ResultBody.ok().data(token); } @GetMapping("/info") public ResultBody info() { AuthUser user = SecurityUtil.getLoginUser(); List<String> permissions = StpUtil.getPermissionList(); List<String> roles = StpUtil.getRoleList(); Map<String, Object> respMap = new HashMap<>(); respMap.put("user", user); respMap.put("permissions", permissions); respMap.put("roles", roles); // 更新用户活跃时间 LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<SysUser>() .eq(SysUser::getId, StpUtil.getLoginIdAsString()) .set(SysUser::getLastActiveTime, LocalDateTime.now()); sysUserService.update(updateWrapper); return ResultBody.ok().data(respMap); } @Log(title = "登出", businessType = BusinessType.LOGOUT) @SaIgnore @PostMapping("/logout") public ResultBody logout() { StpUtil.logout(); return ResultBody.ok(); } @SaIgnore @GetMapping("/captcha") public ResultBody captcha() { String uuid = IdUtil.fastSimpleUUID(); // 算术类型 ArithmeticCaptcha captcha = new ArithmeticCaptcha(150, 38); // 几位数运算,默认是两位 captcha.setLen(2); // 获取运算的公式:3+2=? captcha.getArithmeticString(); // 获取运算的结果:5 captcha.text(); // 保存验证码到redis redisUtil.setEx(Constants.CAPTCHA_REDIS_KEY + uuid, captcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.SECONDS); log.info("uuid: {}, captcha: {}", uuid, captcha.text()); return ResultBody.ok() .putValue("uuid", uuid) .putValue("img", captcha.toBase64()); } /** * 在线用户列表 */ @Log(title = "查看在线用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false) @SaCheckPermission("monitor:online:list") @GetMapping("/online") public ResultBody online(@RequestParam(required = false, value = "nickname") String nickname, @PageableDefault(page = 1) Pageable pageable) { // 获取所有已登录的会话id(如果系统使用的用户比较多,此处会有内存压力,这些限制最多99条数据) List<String> sessionIdList = StpUtil.searchSessionId("", 0, 99, true);
package cn.eu.security.controller; /** * @author zhaoeryu * @since 2023/6/3 */ @Slf4j @RequestMapping("/auth") @RestController public class AuthController { @Autowired LoginService loginService; @Autowired ISysUserService sysUserService; @Autowired RedisUtil redisUtil; @Log(title = "登录", businessType = BusinessType.LOGIN, isSaveResponseData = false, excludeParamNames = { "password" }) @SaIgnore @PostMapping("/login") public ResultBody login(@Validated @RequestBody LoginBody loginBody) { String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getUuid(), loginBody.getVerifyCode()); return ResultBody.ok().data(token); } @GetMapping("/info") public ResultBody info() { AuthUser user = SecurityUtil.getLoginUser(); List<String> permissions = StpUtil.getPermissionList(); List<String> roles = StpUtil.getRoleList(); Map<String, Object> respMap = new HashMap<>(); respMap.put("user", user); respMap.put("permissions", permissions); respMap.put("roles", roles); // 更新用户活跃时间 LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<SysUser>() .eq(SysUser::getId, StpUtil.getLoginIdAsString()) .set(SysUser::getLastActiveTime, LocalDateTime.now()); sysUserService.update(updateWrapper); return ResultBody.ok().data(respMap); } @Log(title = "登出", businessType = BusinessType.LOGOUT) @SaIgnore @PostMapping("/logout") public ResultBody logout() { StpUtil.logout(); return ResultBody.ok(); } @SaIgnore @GetMapping("/captcha") public ResultBody captcha() { String uuid = IdUtil.fastSimpleUUID(); // 算术类型 ArithmeticCaptcha captcha = new ArithmeticCaptcha(150, 38); // 几位数运算,默认是两位 captcha.setLen(2); // 获取运算的公式:3+2=? captcha.getArithmeticString(); // 获取运算的结果:5 captcha.text(); // 保存验证码到redis redisUtil.setEx(Constants.CAPTCHA_REDIS_KEY + uuid, captcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.SECONDS); log.info("uuid: {}, captcha: {}", uuid, captcha.text()); return ResultBody.ok() .putValue("uuid", uuid) .putValue("img", captcha.toBase64()); } /** * 在线用户列表 */ @Log(title = "查看在线用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false) @SaCheckPermission("monitor:online:list") @GetMapping("/online") public ResultBody online(@RequestParam(required = false, value = "nickname") String nickname, @PageableDefault(page = 1) Pageable pageable) { // 获取所有已登录的会话id(如果系统使用的用户比较多,此处会有内存压力,这些限制最多99条数据) List<String> sessionIdList = StpUtil.searchSessionId("", 0, 99, true);
List<OnlineUserVo> list = new ArrayList<>();
8
2023-10-20 07:08:37+00:00
24k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BlockRegister.java
[ { "identifier": "BasicBlocks", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java", "snippet": "public class BasicBlocks {\n\n public static final Block MetaBlock01 = new BlockBase01(\"MetaBlock01\", \"MetaBlock01\");\n public static final Block PhotonControllerUpgr...
import static com.Nxer.TwistSpaceTechnology.common.block.BasicBlocks.*; import static com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor.NuclearReactorBlockMeta; import com.Nxer.TwistSpaceTechnology.common.GTCMItemList; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockStar; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasingItemBlock; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.ItemBlockBase01; import com.Nxer.TwistSpaceTechnology.common.tile.TileStar; import com.Nxer.TwistSpaceTechnology.config.Config; import cpw.mods.fml.common.registry.GameRegistry;
18,856
package com.Nxer.TwistSpaceTechnology.common.block; public class BlockRegister { public static void registryBlocks() { GameRegistry.registerBlock(MetaBlock01, ItemBlockBase01.class, MetaBlock01.getUnlocalizedName()); GameRegistry.registerBlock( PhotonControllerUpgrade, PhotonControllerUpgradeCasingItemBlock.class, PhotonControllerUpgrade.getUnlocalizedName()); GameRegistry.registerBlock( spaceStationStructureBlock, SpaceStationStructureCasingItemBlock.class, spaceStationStructureBlock.getUnlocalizedName()); GameRegistry.registerBlock( SpaceStationAntiGravityBlock, SpaceStationAntiGravityCasingItemBlock.class, SpaceStationAntiGravityBlock.getUnlocalizedName()); GameRegistry.registerBlock( NuclearReactorBlock,
package com.Nxer.TwistSpaceTechnology.common.block; public class BlockRegister { public static void registryBlocks() { GameRegistry.registerBlock(MetaBlock01, ItemBlockBase01.class, MetaBlock01.getUnlocalizedName()); GameRegistry.registerBlock( PhotonControllerUpgrade, PhotonControllerUpgradeCasingItemBlock.class, PhotonControllerUpgrade.getUnlocalizedName()); GameRegistry.registerBlock( spaceStationStructureBlock, SpaceStationStructureCasingItemBlock.class, spaceStationStructureBlock.getUnlocalizedName()); GameRegistry.registerBlock( SpaceStationAntiGravityBlock, SpaceStationAntiGravityCasingItemBlock.class, SpaceStationAntiGravityBlock.getUnlocalizedName()); GameRegistry.registerBlock( NuclearReactorBlock,
BlockNuclearReactor.innerItemBlock.class,
4
2023-10-16 09:57:15+00:00
24k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java
[ { "identifier": "GoCallback", "path": "GoRouter-Api/src/main/java/com/wyjson/router/callback/GoCallback.java", "snippet": "public interface GoCallback {\n\n /**\n * 当找到目的地的回调\n *\n * @param card\n */\n void onFound(Card card);\n\n /**\n * 迷路后的回调。\n *\n * @param card\...
import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityOptionsCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Observer; import com.wyjson.router.callback.GoCallback; import com.wyjson.router.callback.InterceptorCallback; import com.wyjson.router.core.ApplicationModuleCenter; import com.wyjson.router.core.EventCenter; import com.wyjson.router.core.InterceptorCenter; import com.wyjson.router.core.InterceptorServiceImpl; import com.wyjson.router.core.RouteCenter; import com.wyjson.router.core.RouteModuleCenter; import com.wyjson.router.core.ServiceCenter; import com.wyjson.router.core.interfaces.IInterceptorService; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IApplicationModule; import com.wyjson.router.interfaces.IDegradeService; import com.wyjson.router.interfaces.IInterceptor; import com.wyjson.router.interfaces.IPretreatmentService; import com.wyjson.router.interfaces.IService; import com.wyjson.router.logger.DefaultLogger; import com.wyjson.router.logger.ILogger; import com.wyjson.router.model.Card; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.thread.DefaultPoolExecutor; import com.wyjson.router.utils.TextUtils; import java.util.concurrent.ThreadPoolExecutor;
16,577
inject(fragment, null, bundle, false); } @Deprecated public void injectCheck(Activity activity) throws ParamException { inject(activity, null, null, true); } @Deprecated public void injectCheck(Activity activity, Intent intent) throws ParamException { inject(activity, intent, null, true); } @Deprecated public void injectCheck(Activity activity, Bundle bundle) throws ParamException { inject(activity, null, bundle, true); } @Deprecated public void injectCheck(Fragment fragment) throws ParamException { inject(fragment, null, null, true); } @Deprecated public void injectCheck(Fragment fragment, Intent intent) throws ParamException { inject(fragment, intent, null, true); } @Deprecated public void injectCheck(Fragment fragment, Bundle bundle) throws ParamException { inject(fragment, null, bundle, true); } @Deprecated private <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { RouteCenter.inject(target, intent, bundle, isCheck); } @Nullable public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { card.setContext(context == null ? mApplication : context); card.setInterceptorException(null); logger.debug(null, "[go] " + card); IPretreatmentService pretreatmentService = getService(IPretreatmentService.class); if (pretreatmentService != null) { if (!pretreatmentService.onPretreatment(card.getContext(), card)) { // 预处理失败,导航取消 logger.debug(null, "[go] IPretreatmentService Failure!"); return null; } } else { logger.warning(null, "[go] This [IPretreatmentService] was not found!"); } try { RouteCenter.assembleRouteCard(card); } catch (NoFoundRouteException e) { logger.warning(null, e.getMessage()); if (isDebug()) { runInMainThread(() -> Toast.makeText(card.getContext(), "There's no route matched!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_LONG).show()); } onLost(card.getContext(), card, callback); return null; } runInMainThread(() -> { logger.debug(null, "[go] [onFound] " + card); if (callback != null) { callback.onFound(card); } }); if (isDebug() && card.isDeprecated()) { logger.warning(null, "[go] This page has been marked as deprecated. path[" + card.getPath() + "]"); runInMainThread(() -> Toast.makeText(card.getContext(), "This page has been marked as deprecated!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_SHORT).show()); } switch (card.getType()) { case ACTIVITY: IInterceptorService interceptorService = getService(IInterceptorService.class); if (interceptorService != null && !card.isGreenChannel()) { interceptorService.doInterceptions(card, new InterceptorCallback() { @Override public void onContinue(Card card) { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } @Override public void onInterrupt(Card card, @NonNull Throwable exception) { runInMainThread(() -> { if (callback != null) { callback.onInterrupt(card, exception); } }); } }); } else { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } break; case FRAGMENT: return goFragment(card, callback); } return null; } private void onLost(Context context, Card card, GoCallback callback) { runInMainThread(() -> { logger.error(null, "[onLost] There is no route. path[" + card.getPath() + "]"); if (callback != null) { callback.onLost(card); } else {
package com.wyjson.router; public final class GoRouter { private final Handler mHandler = new Handler(Looper.getMainLooper()); private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance(); public static ILogger logger = new DefaultLogger(); private volatile static boolean isDebug = false; private static Application mApplication; private GoRouter() { InterceptorCenter.clearInterceptors(); ServiceCenter.addService(InterceptorServiceImpl.class); } private static class InstanceHolder { private static final GoRouter mInstance = new GoRouter(); } public static GoRouter getInstance() { return InstanceHolder.mInstance; } /** * 自动加载模块路由 * * @param application */ public static synchronized void autoLoadRouteModule(Application application) { setApplication(application); logger.info(null, "[GoRouter] autoLoadRouteModule!"); RouteModuleCenter.load(application); } /** * 获取路由注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isRouteRegisterMode() { return RouteModuleCenter.isRegisterByPlugin(); } public static synchronized void openDebug() { isDebug = true; logger.showLog(isDebug); logger.info(null, "[openDebug]"); } public static void setApplication(Application application) { mApplication = application; } public static boolean isDebug() { return isDebug; } public static synchronized void printStackTrace() { logger.showStackTrace(true); logger.info(null, "[printStackTrace]"); } public static synchronized void setExecutor(ThreadPoolExecutor tpe) { executor = tpe; } public ThreadPoolExecutor getExecutor() { return executor; } public static void setLogger(ILogger userLogger) { if (userLogger != null) { logger = userLogger; } } /** * 获取模块application注册模式 * * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file] */ public boolean isAMRegisterMode() { return ApplicationModuleCenter.isRegisterByPlugin(); } public static void callAMOnCreate(Application application) { setApplication(application); ApplicationModuleCenter.callOnCreate(application); } public static void callAMOnTerminate() { ApplicationModuleCenter.callOnTerminate(); } public static void callAMOnConfigurationChanged(@NonNull Configuration newConfig) { ApplicationModuleCenter.callOnConfigurationChanged(newConfig); } public static void callAMOnLowMemory() { ApplicationModuleCenter.callOnLowMemory(); } public static void callAMOnTrimMemory(int level) { ApplicationModuleCenter.callOnTrimMemory(level); } /** * 动态注册模块application * * @param am */ public static void registerAM(Class<? extends IApplicationModule> am) { ApplicationModuleCenter.register(am); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class */ public void addService(Class<? extends IService> service) { ServiceCenter.addService(service); } /** * 实现相同接口的service会被覆盖(更新) * * @param service 实现类.class * @param alias 别名 */ public void addService(Class<? extends IService> service, String alias) { ServiceCenter.addService(service, alias); } /** * 获取service接口的实现 * * @param service 接口.class * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service) { return ServiceCenter.getService(service); } /** * 获取service接口的实现 * * @param service * @param alias 别名 * @param <T> * @return */ @Nullable public <T> T getService(Class<? extends T> service, String alias) { return ServiceCenter.getService(service, alias); } /** * 重复添加相同序号会catch * * @param ordinal * @param interceptor */ public void addInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) { InterceptorCenter.addInterceptor(ordinal, interceptor, false); } /** * 重复添加相同序号会覆盖(更新) * * @param ordinal * @param interceptor */ public void setInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) { InterceptorCenter.setInterceptor(ordinal, interceptor); } /** * 动态添加路由分组,按需加载路由 */ public void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { RouteCenter.addRouterGroup(group, routeModuleGroup); } private void runInMainThread(Runnable runnable) { if (Looper.getMainLooper().getThread() != Thread.currentThread()) { mHandler.post(runnable); } else { runnable.run(); } } public Card build(String path) { return build(path, null); } public Card build(String path, Bundle bundle) { return new Card(path, bundle); } public Card build(Uri uri) { return new Card(uri); } /** * 获取原始的URI * * @param activity */ public String getRawURI(Activity activity) { return RouteCenter.getRawURI(activity); } /** * 获取原始的URI * * @param fragment */ public String getRawURI(Fragment fragment) { return RouteCenter.getRawURI(fragment); } /** * 获取当前页面路径 * * @param activity */ public String getCurrentPath(Activity activity) { return RouteCenter.getCurrentPath(activity); } /** * 获取当前页面路径 * * @param fragment */ public String getCurrentPath(Fragment fragment) { return RouteCenter.getCurrentPath(fragment); } @Deprecated public void inject(Activity activity) { inject(activity, null, null, false); } @Deprecated public void inject(Activity activity, Intent intent) { inject(activity, intent, null, false); } @Deprecated public void inject(Activity activity, Bundle bundle) { inject(activity, null, bundle, false); } @Deprecated public void inject(Fragment fragment) { inject(fragment, null, null, false); } @Deprecated public void inject(Fragment fragment, Intent intent) { inject(fragment, intent, null, false); } @Deprecated public void inject(Fragment fragment, Bundle bundle) { inject(fragment, null, bundle, false); } @Deprecated public void injectCheck(Activity activity) throws ParamException { inject(activity, null, null, true); } @Deprecated public void injectCheck(Activity activity, Intent intent) throws ParamException { inject(activity, intent, null, true); } @Deprecated public void injectCheck(Activity activity, Bundle bundle) throws ParamException { inject(activity, null, bundle, true); } @Deprecated public void injectCheck(Fragment fragment) throws ParamException { inject(fragment, null, null, true); } @Deprecated public void injectCheck(Fragment fragment, Intent intent) throws ParamException { inject(fragment, intent, null, true); } @Deprecated public void injectCheck(Fragment fragment, Bundle bundle) throws ParamException { inject(fragment, null, bundle, true); } @Deprecated private <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { RouteCenter.inject(target, intent, bundle, isCheck); } @Nullable public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) { card.setContext(context == null ? mApplication : context); card.setInterceptorException(null); logger.debug(null, "[go] " + card); IPretreatmentService pretreatmentService = getService(IPretreatmentService.class); if (pretreatmentService != null) { if (!pretreatmentService.onPretreatment(card.getContext(), card)) { // 预处理失败,导航取消 logger.debug(null, "[go] IPretreatmentService Failure!"); return null; } } else { logger.warning(null, "[go] This [IPretreatmentService] was not found!"); } try { RouteCenter.assembleRouteCard(card); } catch (NoFoundRouteException e) { logger.warning(null, e.getMessage()); if (isDebug()) { runInMainThread(() -> Toast.makeText(card.getContext(), "There's no route matched!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_LONG).show()); } onLost(card.getContext(), card, callback); return null; } runInMainThread(() -> { logger.debug(null, "[go] [onFound] " + card); if (callback != null) { callback.onFound(card); } }); if (isDebug() && card.isDeprecated()) { logger.warning(null, "[go] This page has been marked as deprecated. path[" + card.getPath() + "]"); runInMainThread(() -> Toast.makeText(card.getContext(), "This page has been marked as deprecated!\n" + " Path = [" + card.getPath() + "]\n" + " Group = [" + card.getGroup() + "]", Toast.LENGTH_SHORT).show()); } switch (card.getType()) { case ACTIVITY: IInterceptorService interceptorService = getService(IInterceptorService.class); if (interceptorService != null && !card.isGreenChannel()) { interceptorService.doInterceptions(card, new InterceptorCallback() { @Override public void onContinue(Card card) { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } @Override public void onInterrupt(Card card, @NonNull Throwable exception) { runInMainThread(() -> { if (callback != null) { callback.onInterrupt(card, exception); } }); } }); } else { goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback); } break; case FRAGMENT: return goFragment(card, callback); } return null; } private void onLost(Context context, Card card, GoCallback callback) { runInMainThread(() -> { logger.error(null, "[onLost] There is no route. path[" + card.getPath() + "]"); if (callback != null) { callback.onLost(card); } else {
IDegradeService degradeService = getService(IDegradeService.class);
14
2023-10-18 13:52:07+00:00
24k
trpc-group/trpc-java
trpc-proto/trpc-proto-standard/src/main/java/com/tencent/trpc/proto/standard/stream/client/StreamConsumerInvoker.java
[ { "identifier": "BackendConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/BackendConfig.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class BackendConfig extends BaseProtocolConfig {\n\n protected static final AtomicLong NAME_GENERATOR_INDEX = new AtomicLong(...
import com.tencent.trpc.core.common.config.BackendConfig; import com.tencent.trpc.core.common.config.ConsumerConfig; import com.tencent.trpc.core.common.config.ProtocolConfig; import com.tencent.trpc.core.exception.ErrorCode; import com.tencent.trpc.core.exception.TRpcException; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.core.rpc.ConsumerInvoker; import com.tencent.trpc.core.rpc.InvokeMode; import com.tencent.trpc.core.rpc.Request; import com.tencent.trpc.core.rpc.Response; import com.tencent.trpc.core.rpc.RpcContext; import com.tencent.trpc.core.rpc.RpcContextValueKeys; import com.tencent.trpc.core.rpc.RpcInvocation; import com.tencent.trpc.core.rpc.def.DefResponse; import com.tencent.trpc.core.stream.transport.ClientTransport; import com.tencent.trpc.core.stream.transport.RpcConnection; import com.tencent.trpc.core.utils.RpcContextUtils; import com.tencent.trpc.proto.standard.stream.TRpcStreamRequester; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.SignalType; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer;
19,532
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.proto.standard.stream.client; /** * Invoker that supports streaming calls * * @param <T> service interface type */ public class StreamConsumerInvoker<T> implements ConsumerInvoker<T> { private static final Logger logger = LoggerFactory.getLogger(StreamConsumerInvoker.class); private static final int STREAM_CLOSE_COUNT_BOTH_DIRECTION = 2; /** * Client interface related configuration */ private final ConsumerConfig<T> consumerConfig; /** * Client related configuration */ private final BackendConfig backendConfig; /** * Protocol related configuration */ private final ProtocolConfig protocolConfig; /** * Client transport */ private final ClientTransport clientTransport; public StreamConsumerInvoker(ConsumerConfig<T> consumerConfig, ProtocolConfig protocolConfig, ClientTransport clientTransport) { this.consumerConfig = Objects.requireNonNull(consumerConfig, "consumerConfig is null"); this.backendConfig = Objects .requireNonNull(consumerConfig.getBackendConfig(), "backendConfig is null"); this.protocolConfig = Objects.requireNonNull(protocolConfig, "protocolConfig is null"); this.clientTransport = Objects.requireNonNull(clientTransport, "clientTransport is null"); } @Override public ConsumerConfig<T> getConfig() { return consumerConfig; } @Override public ProtocolConfig getProtocolConfig() { return protocolConfig; } @Override @SuppressWarnings("unchecked") public Class<T> getInterface() { return (Class<T>) backendConfig.getServiceInterface(); } @Override public CompletionStage<Response> invoke(Request request) { CompletableFuture<Response> future = new CompletableFuture<>(); // create a link and perform a remote call clientTransport .connect() .subscribe(conn -> { try {
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.proto.standard.stream.client; /** * Invoker that supports streaming calls * * @param <T> service interface type */ public class StreamConsumerInvoker<T> implements ConsumerInvoker<T> { private static final Logger logger = LoggerFactory.getLogger(StreamConsumerInvoker.class); private static final int STREAM_CLOSE_COUNT_BOTH_DIRECTION = 2; /** * Client interface related configuration */ private final ConsumerConfig<T> consumerConfig; /** * Client related configuration */ private final BackendConfig backendConfig; /** * Protocol related configuration */ private final ProtocolConfig protocolConfig; /** * Client transport */ private final ClientTransport clientTransport; public StreamConsumerInvoker(ConsumerConfig<T> consumerConfig, ProtocolConfig protocolConfig, ClientTransport clientTransport) { this.consumerConfig = Objects.requireNonNull(consumerConfig, "consumerConfig is null"); this.backendConfig = Objects .requireNonNull(consumerConfig.getBackendConfig(), "backendConfig is null"); this.protocolConfig = Objects.requireNonNull(protocolConfig, "protocolConfig is null"); this.clientTransport = Objects.requireNonNull(clientTransport, "clientTransport is null"); } @Override public ConsumerConfig<T> getConfig() { return consumerConfig; } @Override public ProtocolConfig getProtocolConfig() { return protocolConfig; } @Override @SuppressWarnings("unchecked") public Class<T> getInterface() { return (Class<T>) backendConfig.getServiceInterface(); } @Override public CompletionStage<Response> invoke(Request request) { CompletableFuture<Response> future = new CompletableFuture<>(); // create a link and perform a remote call clientTransport .connect() .subscribe(conn -> { try {
TRpcStreamRequester requester = new TRpcStreamRequester(protocolConfig, conn,
18
2023-10-19 10:54:11+00:00
24k
eclipse-jgit/jgit
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/revwalk/PedestrianReachabilityCheckerTest.java
[ { "identifier": "FileRepository", "path": "org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/FileRepository.java", "snippet": "public class FileRepository extends Repository {\n\tprivate static final Logger LOG = LoggerFactory\n\t\t\t.getLogger(FileRepository.class);\n\tprivate static final St...
import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.revwalk.ReachabilityChecker;
18,138
/* * Copyright (C) 2019, Google LLC. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.internal.revwalk; public class PedestrianReachabilityCheckerTest extends ReachabilityCheckerTestCase { @Override protected ReachabilityChecker getChecker(
/* * Copyright (C) 2019, Google LLC. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.internal.revwalk; public class PedestrianReachabilityCheckerTest extends ReachabilityCheckerTestCase { @Override protected ReachabilityChecker getChecker(
TestRepository<FileRepository> repository) {
1
2023-10-20 15:09:17+00:00
24k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/UninstalledRecyclerListFragment.java
[ { "identifier": "DBHelper", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/DBHelper.java", "snippet": "public class DBHelper extends SQLiteOpenHelper {\n\tprivate static final String DB_NAME = \"actions.db\";\n\tprivate static final int DB_VERSION = 10;\n\tpublic static final String ACTION_TA...
import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.DBHelper; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.recyclerview.base.RecyclerListFragment;
14,767
} @Override protected List<UninstallEntry> doInBackground(Void... params) { SQLiteDatabase db = DBHelper.getInstance(mContext).getReadableDatabase(); Cursor cursor = db.query("uninstalled", null, null, null, null, null, null); List<UninstallEntry> result = new ArrayList<>(); if (cursor != null) { UninstallEntry entry; while (cursor.moveToNext()) { entry = new UninstallEntry(); entry.label = cursor.getString(cursor.getColumnIndex("appName")); entry.packageName = cursor.getString(cursor.getColumnIndex("packageName")); entry.sourcePath = cursor.getString(cursor.getColumnIndex("sourcePath")); entry.backupPath = cursor.getString(cursor.getColumnIndex("backupPath")); byte[] bytes = cursor.getBlob(cursor.getColumnIndex("icon")); if (bytes != null) { entry.bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } result.add(entry); } cursor.close(); } return result; } } private class UninstallAdapter extends RecyclerView.Adapter<VHolder> { private List<UninstallEntry> mList; private Context mContext; public UninstallAdapter(Context context) { super(); mList = new ArrayList<>(); mContext = context; } public void delete(int position) { UninstallEntry entry = mList.remove(position); SQLiteDatabase db = DBHelper.getInstance(mContext).getWritableDatabase(); db.delete("uninstalled", "packageName=?", new String[]{entry.packageName}); notifyItemRemoved(position); } public void addData(List<UninstallEntry> list) { if (mList.size() > 0) { mList.clear(); } mList.addAll(list); notifyDataSetChanged(); } public Object getItem(int position) { return mList.get(position); } @Override public VHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new VHolder(LayoutInflater.from(mContext).inflate( R.layout.item_app_manage_list, parent, false)); } @Override public void onBindViewHolder(VHolder holder, int position) { final UninstallEntry entry = mList.get(position); holder.icon.setImageBitmap(entry.bitmap); holder.label.setText(entry.label); holder.packageName.setText(entry.packageName); } @Override public int getItemCount() { return mList.size(); } } private class VHolder extends RecyclerView.ViewHolder{ ImageView icon; TextView label, packageName; public VHolder(View itemView) { super(itemView); icon = (ImageView) itemView.findViewById(R.id.icon); label = (TextView) itemView.findViewById(R.id.label); packageName = (TextView) itemView .findViewById(R.id.packageName); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int position=getLayoutPosition(); final UninstallEntry entry = (UninstallEntry) mAdapter.getItem(position); PopupMenu popupMenu = new PopupMenu(getContext(), view, Gravity.BOTTOM | Gravity.CENTER); popupMenu.inflate(R.menu.uninstall); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.uninstall_delete: new Thread(new Runnable() { @Override public void run() { File file = new File(entry.backupPath); if (file.exists()) { file.delete(); } final String apkDir; final int splashPos = entry.sourcePath.lastIndexOf("/"); if (splashPos != -1) { apkDir = entry.sourcePath.substring(0, splashPos); } else { apkDir = entry.sourcePath; }
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class UninstalledRecyclerListFragment extends RecyclerListFragment implements AppManageParentFragment.FragmentSelectListener { private UninstallAdapter mAdapter; private LoadUninstalledTask mTask; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override public void onSelected() { mAdapter = new UninstallAdapter(getContext()); setAdapter(mAdapter); if (mTask != null) { mTask.cancel(true); } mTask = new LoadUninstalledTask(); mTask.execute(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty)); } private class LoadUninstalledTask extends AsyncTask<Void, Void, List<UninstallEntry>> { @Override protected void onPreExecute() { super.onPreExecute(); setListShown(false,true); } @Override protected void onPostExecute(List<UninstallEntry> localAppEntries) { super.onPostExecute(localAppEntries); mAdapter.addData(localAppEntries); setListShown(true,isResumed()); } @Override protected List<UninstallEntry> doInBackground(Void... params) { SQLiteDatabase db = DBHelper.getInstance(mContext).getReadableDatabase(); Cursor cursor = db.query("uninstalled", null, null, null, null, null, null); List<UninstallEntry> result = new ArrayList<>(); if (cursor != null) { UninstallEntry entry; while (cursor.moveToNext()) { entry = new UninstallEntry(); entry.label = cursor.getString(cursor.getColumnIndex("appName")); entry.packageName = cursor.getString(cursor.getColumnIndex("packageName")); entry.sourcePath = cursor.getString(cursor.getColumnIndex("sourcePath")); entry.backupPath = cursor.getString(cursor.getColumnIndex("backupPath")); byte[] bytes = cursor.getBlob(cursor.getColumnIndex("icon")); if (bytes != null) { entry.bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } result.add(entry); } cursor.close(); } return result; } } private class UninstallAdapter extends RecyclerView.Adapter<VHolder> { private List<UninstallEntry> mList; private Context mContext; public UninstallAdapter(Context context) { super(); mList = new ArrayList<>(); mContext = context; } public void delete(int position) { UninstallEntry entry = mList.remove(position); SQLiteDatabase db = DBHelper.getInstance(mContext).getWritableDatabase(); db.delete("uninstalled", "packageName=?", new String[]{entry.packageName}); notifyItemRemoved(position); } public void addData(List<UninstallEntry> list) { if (mList.size() > 0) { mList.clear(); } mList.addAll(list); notifyDataSetChanged(); } public Object getItem(int position) { return mList.get(position); } @Override public VHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new VHolder(LayoutInflater.from(mContext).inflate( R.layout.item_app_manage_list, parent, false)); } @Override public void onBindViewHolder(VHolder holder, int position) { final UninstallEntry entry = mList.get(position); holder.icon.setImageBitmap(entry.bitmap); holder.label.setText(entry.label); holder.packageName.setText(entry.packageName); } @Override public int getItemCount() { return mList.size(); } } private class VHolder extends RecyclerView.ViewHolder{ ImageView icon; TextView label, packageName; public VHolder(View itemView) { super(itemView); icon = (ImageView) itemView.findViewById(R.id.icon); label = (TextView) itemView.findViewById(R.id.label); packageName = (TextView) itemView .findViewById(R.id.packageName); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int position=getLayoutPosition(); final UninstallEntry entry = (UninstallEntry) mAdapter.getItem(position); PopupMenu popupMenu = new PopupMenu(getContext(), view, Gravity.BOTTOM | Gravity.CENTER); popupMenu.inflate(R.menu.uninstall); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.uninstall_delete: new Thread(new Runnable() { @Override public void run() { File file = new File(entry.backupPath); if (file.exists()) { file.delete(); } final String apkDir; final int splashPos = entry.sourcePath.lastIndexOf("/"); if (splashPos != -1) { apkDir = entry.sourcePath.substring(0, splashPos); } else { apkDir = entry.sourcePath; }
String unmountCommand = Utils.getUnmountSystemCommand(mContext);
1
2023-10-18 14:32:49+00:00
24k
A1anSong/jd_unidbg
unidbg-api/src/main/java/com/github/unidbg/arm/AbstractARMDebugger.java
[ { "identifier": "AssemblyCodeDumper", "path": "unidbg-api/src/main/java/com/github/unidbg/AssemblyCodeDumper.java", "snippet": "public class AssemblyCodeDumper implements CodeHook, TraceHook {\n\n private final Emulator<?> emulator;\n\n public AssemblyCodeDumper(Emulator<?> emulator, long begin, l...
import capstone.api.Instruction; import capstone.api.RegsAccess; import com.github.unidbg.AssemblyCodeDumper; import com.github.unidbg.Emulator; import com.github.unidbg.Family; import com.github.unidbg.Module; import com.github.unidbg.Symbol; import com.github.unidbg.TraceMemoryHook; import com.github.unidbg.Utils; import com.github.unidbg.arm.backend.Backend; import com.github.unidbg.arm.backend.BlockHook; import com.github.unidbg.arm.backend.ReadHook; import com.github.unidbg.arm.backend.UnHook; import com.github.unidbg.arm.backend.WriteHook; import com.github.unidbg.debugger.BreakPoint; import com.github.unidbg.debugger.BreakPointCallback; import com.github.unidbg.debugger.DebugListener; import com.github.unidbg.debugger.DebugRunnable; import com.github.unidbg.debugger.Debugger; import com.github.unidbg.debugger.FunctionCallListener; import com.github.unidbg.memory.MemRegion; import com.github.unidbg.memory.Memory; import com.github.unidbg.memory.MemoryMap; import com.github.unidbg.pointer.UnidbgPointer; import com.github.unidbg.thread.Task; import com.github.unidbg.unix.struct.StdString; import com.github.unidbg.unwind.Unwinder; import com.github.unidbg.utils.Inspector; import com.github.zhkl0228.demumble.DemanglerFactory; import com.github.zhkl0228.demumble.GccDemangler; import com.sun.jna.Pointer; import keystone.Keystone; import keystone.KeystoneEncoded; import keystone.exceptions.AssembleFailedKeystoneException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import unicorn.Arm64Const; import unicorn.ArmConst; import unicorn.UnicornConst; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern;
17,477
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; }
package com.github.unidbg.arm; public abstract class AbstractARMDebugger implements Debugger { private static final Log log = LogFactory.getLog(AbstractARMDebugger.class); private final Map<Long, BreakPoint> breakMap = new LinkedHashMap<>(); protected final Emulator<?> emulator; protected AbstractARMDebugger(Emulator<?> emulator) { this.emulator = emulator; }
private final List<UnHook> unHookList = new ArrayList<>();
10
2023-10-17 06:13:28+00:00
24k
robaho/httpserver
src/test/java/jdk/test/lib/Utils.java
[ { "identifier": "assertTrue", "path": "src/test/java/jdk/test/lib/Asserts.java", "snippet": "public static void assertTrue(boolean value) {\n assertTrue(value, null);\n}" }, { "identifier": "ProcessTools", "path": "src/test/java/jdk/test/lib/process/ProcessTools.java", "snippet": "pub...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.AclEntry; import java.nio.file.attribute.AclEntryType; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.FileAttribute; import java.nio.channels.SocketChannel; import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HexFormat; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.function.BooleanSupplier; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static jdk.test.lib.Asserts.assertTrue; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer;
16,073
/** * @param parent a class loader to be the parent for the returned one * @return an UrlClassLoader with urls made of the 'test.class.path' jtreg * property and with the given parent */ public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) { URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator)) .map(Paths::get) .map(Path::toUri) .map(x -> { try { return x.toURL(); } catch (MalformedURLException ex) { throw new Error("Test issue. JTREG property" + " 'test.class.path'" + " is not defined correctly", ex); } }).toArray(URL[]::new); return new URLClassLoader(urls, parent); } /** * Runs runnable and checks that it throws expected exception. If exceptionException is null it means * that we expect no exception to be thrown. * @param runnable what we run * @param expectedException expected exception */ public static void runAndCheckException(ThrowingRunnable runnable, Class<? extends Throwable> expectedException) { runAndCheckException(runnable, t -> { if (t == null) { if (expectedException != null) { throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName()); } } else { String message = "Got unexpected exception " + t.getClass().getSimpleName(); if (expectedException == null) { throw new AssertionError(message, t); } else if (!expectedException.isAssignableFrom(t.getClass())) { message += " instead of " + expectedException.getSimpleName(); throw new AssertionError(message, t); } } }); } /** * Runs runnable and makes some checks to ensure that it throws expected exception. * @param runnable what we run * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise */ public static void runAndCheckException(ThrowingRunnable runnable, Consumer<Throwable> checkException) { Throwable throwable = null; try { runnable.run(); } catch (Throwable t) { throwable = t; } checkException.accept(throwable); } /** * Converts to VM type signature * * @param type Java type to convert * @return string representation of VM type */ public static String toJVMTypeSignature(Class<?> type) { if (type.isPrimitive()) { if (type == boolean.class) { return "Z"; } else if (type == byte.class) { return "B"; } else if (type == char.class) { return "C"; } else if (type == double.class) { return "D"; } else if (type == float.class) { return "F"; } else if (type == int.class) { return "I"; } else if (type == long.class) { return "J"; } else if (type == short.class) { return "S"; } else if (type == void.class) { return "V"; } else { throw new Error("Unsupported type: " + type); } } String result = type.getName().replaceAll("\\.", "/"); if (!type.isArray()) { return "L" + result + ";"; } return result; } public static Object[] getNullValues(Class<?>... types) { Object[] result = new Object[types.length]; int i = 0; for (Class<?> type : types) { result[i++] = NULL_VALUES.get(type); } return result; } private static Map<Class<?>, Object> NULL_VALUES = new HashMap<>(); static { NULL_VALUES.put(boolean.class, false); NULL_VALUES.put(byte.class, (byte) 0); NULL_VALUES.put(short.class, (short) 0); NULL_VALUES.put(char.class, '\0'); NULL_VALUES.put(int.class, 0); NULL_VALUES.put(long.class, 0L); NULL_VALUES.put(float.class, 0.0f); NULL_VALUES.put(double.class, 0.0d); } /* * Run uname with specified arguments. */
/* * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.test.lib; /** * Common library for various test helper functions. */ public final class Utils { /** * Returns the value of 'test.class.path' system property. */ public static final String TEST_CLASS_PATH = System.getProperty("test.class.path", "."); /** * Returns the sequence used by operating system to separate lines. */ public static final String NEW_LINE = System.getProperty("line.separator"); /** * Returns the value of 'test.vm.opts' system property. */ public static final String VM_OPTIONS = System.getProperty("test.vm.opts", "").trim(); /** * Returns the value of 'test.java.opts' system property. */ public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim(); /** * Returns the value of 'test.src' system property. */ public static final String TEST_SRC = System.getProperty("test.src", "").trim(); /** * Returns the value of 'test.root' system property. */ public static final String TEST_ROOT = System.getProperty("test.root", "").trim(); /* * Returns the value of 'test.jdk' system property */ public static final String TEST_JDK = System.getProperty("test.jdk"); /* * Returns the value of 'compile.jdk' system property */ public static final String COMPILE_JDK = System.getProperty("compile.jdk", TEST_JDK); /** * Returns the value of 'test.classes' system property */ public static final String TEST_CLASSES = System.getProperty("test.classes", "."); /** * Returns the value of 'test.name' system property */ public static final String TEST_NAME = System.getProperty("test.name", "."); /** * Returns the value of 'test.nativepath' system property */ public static final String TEST_NATIVE_PATH = System.getProperty("test.nativepath", "."); /** * Defines property name for seed value. */ public static final String SEED_PROPERTY_NAME = "jdk.test.lib.random.seed"; /** * Returns the value of 'file.separator' system property */ public static final String FILE_SEPARATOR = System.getProperty("file.separator"); /** * Random generator with predefined seed. */ private static volatile Random RANDOM_GENERATOR; /** * Maximum number of attempts to get free socket */ private static final int MAX_SOCKET_TRIES = 10; /** * Contains the seed value used for {@link java.util.Random} creation. */ public static final long SEED; static { var seed = Long.getLong(SEED_PROPERTY_NAME); if (seed != null) { // use explicitly set seed SEED = seed; } else { var v = Runtime.version(); // promotable builds have build number, and it's greater than 0 if (v.build().orElse(0) > 0) { // promotable build -> use 1st 8 bytes of md5($version) try { var md = MessageDigest.getInstance("MD5"); var bytes = v.toString() .getBytes(StandardCharsets.UTF_8); bytes = md.digest(bytes); SEED = ByteBuffer.wrap(bytes).getLong(); } catch (NoSuchAlgorithmException e) { throw new Error(e); } } else { // "personal" build -> use random seed SEED = new Random().nextLong(); } } } /** * Returns the value of 'test.timeout.factor' system property * converted to {@code double}. */ public static final double TIMEOUT_FACTOR; static { String toFactor = System.getProperty("test.timeout.factor", "1.0"); TIMEOUT_FACTOR = Double.parseDouble(toFactor); } /** * Returns the value of JTREG default test timeout in milliseconds * converted to {@code long}. */ public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.SECONDS.toMillis(120); private Utils() { // Private constructor to prevent class instantiation } /** * Returns the list of VM options with -J prefix. * * @return The list of VM options with -J prefix */ public static List<String> getForwardVmOptions() { String[] opts = safeSplitString(VM_OPTIONS); for (int i = 0; i < opts.length; i++) { opts[i] = "-J" + opts[i]; } return Arrays.asList(opts); } /** * Returns the default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts. * @return An array of options, or an empty array if no options. */ public static String[] getTestJavaOpts() { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, safeSplitString(VM_OPTIONS)); Collections.addAll(opts, safeSplitString(JAVA_OPTIONS)); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] prependTestJavaOpts(String... userArgs) { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, getTestJavaOpts()); Collections.addAll(opts, userArgs); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] appendTestJavaOpts(String... userArgs) { List<String> opts = new ArrayList<String>(); Collections.addAll(opts, userArgs); Collections.addAll(opts, getTestJavaOpts()); return opts.toArray(new String[0]); } /** * Combines given arguments with default JTReg arguments for a jvm running a test. * This is the combination of JTReg arguments test.vm.opts and test.java.opts * @return The combination of JTReg test java options and user args. */ public static String[] addTestJavaOpts(String... userArgs) { return prependTestJavaOpts(userArgs); } private static final Pattern useGcPattern = Pattern.compile( "(?:\\-XX\\:[\\+\\-]Use.+GC)"); /** * Removes any options specifying which GC to use, for example "-XX:+UseG1GC". * Removes any options matching: -XX:(+/-)Use*GC * Used when a test need to set its own GC version. Then any * GC specified by the framework must first be removed. * @return A copy of given opts with all GC options removed. */ public static List<String> removeGcOpts(List<String> opts) { List<String> optsWithoutGC = new ArrayList<String>(); for (String opt : opts) { if (useGcPattern.matcher(opt).matches()) { System.out.println("removeGcOpts: removed " + opt); } else { optsWithoutGC.add(opt); } } return optsWithoutGC; } /** * Returns the default JTReg arguments for a jvm running a test without * options that matches regular expressions in {@code filters}. * This is the combination of JTReg arguments test.vm.opts and test.java.opts. * @param filters Regular expressions used to filter out options. * @return An array of options, or an empty array if no options. */ public static String[] getFilteredTestJavaOpts(String... filters) { String options[] = getTestJavaOpts(); if (filters.length == 0) { return options; } List<String> filteredOptions = new ArrayList<String>(options.length); Pattern patterns[] = new Pattern[filters.length]; for (int i = 0; i < filters.length; i++) { patterns[i] = Pattern.compile(filters[i]); } for (String option : options) { boolean matched = false; for (int i = 0; i < patterns.length && !matched; i++) { Matcher matcher = patterns[i].matcher(option); matched = matcher.find(); } if (!matched) { filteredOptions.add(option); } } return filteredOptions.toArray(new String[filteredOptions.size()]); } /** * Splits a string by white space. * Works like String.split(), but returns an empty array * if the string is null or empty. */ private static String[] safeSplitString(String s) { if (s == null || s.trim().isEmpty()) { return new String[] {}; } return s.trim().split("\\s+"); } /** * @return The full command line for the ProcessBuilder. */ public static String getCommandLine(ProcessBuilder pb) { StringBuilder cmd = new StringBuilder(); for (String s : pb.command()) { cmd.append(s).append(" "); } return cmd.toString(); } /** * Returns the socket address of an endpoint that refuses connections. The * endpoint is an InetSocketAddress where the address is the loopback address * and the port is a system port (1-1023 range). * This method is a better choice than getFreePort for tests that need * an endpoint that refuses connections. */ public static InetSocketAddress refusingEndpoint() { InetAddress lb = InetAddress.getLoopbackAddress(); int port = 1; while (port < 1024) { InetSocketAddress sa = new InetSocketAddress(lb, port); try { SocketChannel.open(sa).close(); } catch (IOException ioe) { return sa; } port++; } throw new RuntimeException("Unable to find system port that is refusing connections"); } /** * Returns local addresses with symbolic and numeric scopes */ public static List<InetAddress> getAddressesWithSymbolicAndNumericScopes() { List<InetAddress> result = new LinkedList<>(); try { NetworkConfiguration conf = NetworkConfiguration.probe(); conf.ip4Addresses().forEach(result::add); // Java reports link local addresses with symbolic scope, // but on Windows java.net.NetworkInterface generates its own scope names // which are incompatible with native Windows routines. // So on Windows test only addresses with numeric scope. // On other platforms test both symbolic and numeric scopes. conf.ip6Addresses() // test only IPv6 loopback and link-local addresses (JDK-8224775) .filter(addr -> addr.isLinkLocalAddress() || addr.isLoopbackAddress()) .forEach(addr6 -> { try { result.add(Inet6Address.getByAddress(null, addr6.getAddress(), addr6.getScopeId())); } catch (UnknownHostException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } if (!Platform.isWindows()) { result.add(addr6); } }); } catch (IOException e) { // cannot happen! throw new RuntimeException("Unexpected", e); } return result; } /** * Returns the free port on the loopback address. * * @return The port number * @throws IOException if an I/O error occurs when opening the socket */ public static int getFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0, 5, InetAddress.getLoopbackAddress());) { return serverSocket.getLocalPort(); } } /** * Returns the free unreserved port on the local host. * * @param reservedPorts reserved ports * @return The port number or -1 if failed to find a free port */ public static int findUnreservedFreePort(int... reservedPorts) { int numTries = 0; while (numTries++ < MAX_SOCKET_TRIES) { int port = -1; try { port = getFreePort(); } catch (IOException e) { e.printStackTrace(); } if (port > 0 && !isReserved(port, reservedPorts)) { return port; } } return -1; } private static boolean isReserved(int port, int[] reservedPorts) { for (int p : reservedPorts) { if (p == port) { return true; } } return false; } /** * Returns the name of the local host. * * @return The host name * @throws UnknownHostException if IP address of a host could not be determined */ public static String getHostname() throws UnknownHostException { InetAddress inetAddress = InetAddress.getLocalHost(); String hostName = inetAddress.getHostName(); assertTrue((hostName != null && !hostName.isEmpty()), "Cannot get hostname"); return hostName; } /** * Adjusts the provided timeout value for the TIMEOUT_FACTOR * @param tOut the timeout value to be adjusted * @return The timeout value adjusted for the value of "test.timeout.factor" * system property */ public static long adjustTimeout(long tOut) { return Math.round(tOut * Utils.TIMEOUT_FACTOR); } /** * Return the contents of the named file as a single String, * or null if not found. * @param filename name of the file to read * @return String contents of file, or null if file not found. * @throws IOException * if an I/O error occurs reading from the file or a malformed or * unmappable byte sequence is read */ public static String fileAsString(String filename) throws IOException { Path filePath = Paths.get(filename); if (!Files.exists(filePath)) return null; return new String(Files.readAllBytes(filePath)); } /** * Returns hex view of byte array * * @param bytes byte array to process * @return space separated hexadecimal string representation of bytes * @deprecated replaced by {@link java.util.HexFormat#ofDelimiter(String) * HexFormat.ofDelimiter(" ").format (byte[], char)}. */ @Deprecated public static String toHexString(byte[] bytes) { return HexFormat.ofDelimiter(" ").withUpperCase().formatHex(bytes); } /** * Returns byte array of hex view * * @param hex hexadecimal string representation * @return byte array */ public static byte[] toByteArray(String hex) { return HexFormat.of().parseHex(hex); } /** * Returns {@link java.util.Random} generator initialized with particular seed. * The seed could be provided via system property {@link Utils#SEED_PROPERTY_NAME}. * In case no seed is provided and the build under test is "promotable" * (its build number ({@code $BUILD} in {@link Runtime.Version}) is greater than 0, * the seed based on string representation of {@link Runtime#version()} is used. * Otherwise, the seed is randomly generated. * The used seed printed to stdout. * The printing is not in the synchronized block so as to prevent carrier threads starvation. * @return {@link java.util.Random} generator with particular seed. */ public static Random getRandomInstance() { if (RANDOM_GENERATOR == null) { synchronized (Utils.class) { if (RANDOM_GENERATOR == null) { RANDOM_GENERATOR = new Random(SEED); } else { return RANDOM_GENERATOR; } } System.out.printf("For random generator using seed: %d%n", SEED); System.out.printf("To re-run test with same seed value please add \"-D%s=%d\" to command line.%n", SEED_PROPERTY_NAME, SEED); } return RANDOM_GENERATOR; } /** * Returns random element of non empty collection * * @param <T> a type of collection element * @param collection collection of elements * @return random element of collection * @throws IllegalArgumentException if collection is empty */ public static <T> T getRandomElement(Collection<T> collection) throws IllegalArgumentException { if (collection.isEmpty()) { throw new IllegalArgumentException("Empty collection"); } Random random = getRandomInstance(); int elementIndex = 1 + random.nextInt(collection.size() - 1); Iterator<T> iterator = collection.iterator(); while (--elementIndex != 0) { iterator.next(); } return iterator.next(); } /** * Returns random element of non empty array * * @param <T> a type of array element * @param array array of elements * @return random element of array * @throws IllegalArgumentException if array is empty */ public static <T> T getRandomElement(T[] array) throws IllegalArgumentException { if (array == null || array.length == 0) { throw new IllegalArgumentException("Empty or null array"); } Random random = getRandomInstance(); return array[random.nextInt(array.length)]; } /** * Wait for condition to be true * * @param condition a condition to wait for */ public static final void waitForCondition(BooleanSupplier condition) { waitForCondition(condition, -1L, 100L); } /** * Wait until timeout for condition to be true * * @param condition a condition to wait for * @param timeout a time in milliseconds to wait for condition to be true * specifying -1 will wait forever * @return condition value, to determine if wait was successful */ public static final boolean waitForCondition(BooleanSupplier condition, long timeout) { return waitForCondition(condition, timeout, 100L); } /** * Wait until timeout for condition to be true for specified time * * @param condition a condition to wait for * @param timeout a time in milliseconds to wait for condition to be true, * specifying -1 will wait forever * @param sleepTime a time to sleep value in milliseconds * @return condition value, to determine if wait was successful */ public static final boolean waitForCondition(BooleanSupplier condition, long timeout, long sleepTime) { long startTime = System.currentTimeMillis(); while (!(condition.getAsBoolean() || (timeout != -1L && ((System.currentTimeMillis() - startTime) > timeout)))) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new Error(e); } } return condition.getAsBoolean(); } /** * Interface same as java.lang.Runnable but with * method {@code run()} able to throw any Throwable. */ public static interface ThrowingRunnable { void run() throws Throwable; } /** * Filters out an exception that may be thrown by the given * test according to the given filter. * * @param test method that is invoked and checked for exception. * @param filter function that checks if the thrown exception matches * criteria given in the filter's implementation. * @return exception that matches the filter if it has been thrown or * {@code null} otherwise. * @throws Throwable if test has thrown an exception that does not * match the filter. */ public static Throwable filterException(ThrowingRunnable test, Function<Throwable, Boolean> filter) throws Throwable { try { test.run(); } catch (Throwable t) { if (filter.apply(t)) { return t; } else { throw t; } } return null; } /** * Ensures a requested class is loaded * @param aClass class to load */ public static void ensureClassIsLoaded(Class<?> aClass) { if (aClass == null) { throw new Error("Requested null class"); } try { Class.forName(aClass.getName(), /* initialize = */ true, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { throw new Error("Class not found", e); } } /** * @param parent a class loader to be the parent for the returned one * @return an UrlClassLoader with urls made of the 'test.class.path' jtreg * property and with the given parent */ public static URLClassLoader getTestClassPathURLClassLoader(ClassLoader parent) { URL[] urls = Arrays.stream(TEST_CLASS_PATH.split(File.pathSeparator)) .map(Paths::get) .map(Path::toUri) .map(x -> { try { return x.toURL(); } catch (MalformedURLException ex) { throw new Error("Test issue. JTREG property" + " 'test.class.path'" + " is not defined correctly", ex); } }).toArray(URL[]::new); return new URLClassLoader(urls, parent); } /** * Runs runnable and checks that it throws expected exception. If exceptionException is null it means * that we expect no exception to be thrown. * @param runnable what we run * @param expectedException expected exception */ public static void runAndCheckException(ThrowingRunnable runnable, Class<? extends Throwable> expectedException) { runAndCheckException(runnable, t -> { if (t == null) { if (expectedException != null) { throw new AssertionError("Didn't get expected exception " + expectedException.getSimpleName()); } } else { String message = "Got unexpected exception " + t.getClass().getSimpleName(); if (expectedException == null) { throw new AssertionError(message, t); } else if (!expectedException.isAssignableFrom(t.getClass())) { message += " instead of " + expectedException.getSimpleName(); throw new AssertionError(message, t); } } }); } /** * Runs runnable and makes some checks to ensure that it throws expected exception. * @param runnable what we run * @param checkException a consumer which checks that we got expected exception and raises a new exception otherwise */ public static void runAndCheckException(ThrowingRunnable runnable, Consumer<Throwable> checkException) { Throwable throwable = null; try { runnable.run(); } catch (Throwable t) { throwable = t; } checkException.accept(throwable); } /** * Converts to VM type signature * * @param type Java type to convert * @return string representation of VM type */ public static String toJVMTypeSignature(Class<?> type) { if (type.isPrimitive()) { if (type == boolean.class) { return "Z"; } else if (type == byte.class) { return "B"; } else if (type == char.class) { return "C"; } else if (type == double.class) { return "D"; } else if (type == float.class) { return "F"; } else if (type == int.class) { return "I"; } else if (type == long.class) { return "J"; } else if (type == short.class) { return "S"; } else if (type == void.class) { return "V"; } else { throw new Error("Unsupported type: " + type); } } String result = type.getName().replaceAll("\\.", "/"); if (!type.isArray()) { return "L" + result + ";"; } return result; } public static Object[] getNullValues(Class<?>... types) { Object[] result = new Object[types.length]; int i = 0; for (Class<?> type : types) { result[i++] = NULL_VALUES.get(type); } return result; } private static Map<Class<?>, Object> NULL_VALUES = new HashMap<>(); static { NULL_VALUES.put(boolean.class, false); NULL_VALUES.put(byte.class, (byte) 0); NULL_VALUES.put(short.class, (short) 0); NULL_VALUES.put(char.class, '\0'); NULL_VALUES.put(int.class, 0); NULL_VALUES.put(long.class, 0L); NULL_VALUES.put(float.class, 0.0f); NULL_VALUES.put(double.class, 0.0d); } /* * Run uname with specified arguments. */
public static OutputAnalyzer uname(String... args) throws Throwable {
2
2023-10-15 15:56:58+00:00
24k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/room/SearchService.java
[ { "identifier": "GlobalConstant", "path": "src/main/java/com/moabam/global/common/util/GlobalConstant.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class GlobalConstant {\n\n\tpublic static final String BLANK = \"\";\n\tpublic static final String DELIMITER = \"/\";\n\tpubli...
import static com.moabam.global.common.util.GlobalConstant.*; import static com.moabam.global.error.model.ErrorMessage.*; import static org.apache.commons.lang3.StringUtils.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.notification.NotificationService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.application.room.mapper.ParticipantMapper; import com.moabam.api.application.room.mapper.RoomMapper; import com.moabam.api.application.room.mapper.RoutineMapper; import com.moabam.api.domain.item.Inventory; import com.moabam.api.domain.item.repository.InventorySearchRepository; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.Certification; import com.moabam.api.domain.room.DailyMemberCertification; import com.moabam.api.domain.room.DailyRoomCertification; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.RoomType; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.CertificationsSearchRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoomSearchRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CertificationImageResponse; import com.moabam.api.dto.room.CertificationImagesResponse; import com.moabam.api.dto.room.GetAllRoomResponse; import com.moabam.api.dto.room.GetAllRoomsResponse; import com.moabam.api.dto.room.ManageRoomResponse; import com.moabam.api.dto.room.MyRoomResponse; import com.moabam.api.dto.room.MyRoomsResponse; import com.moabam.api.dto.room.ParticipantResponse; import com.moabam.api.dto.room.RoomDetailsResponse; import com.moabam.api.dto.room.RoomHistoryResponse; import com.moabam.api.dto.room.RoomsHistoryResponse; import com.moabam.api.dto.room.RoutineResponse; import com.moabam.api.dto.room.TodayCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomCertificateRankResponse; import com.moabam.api.dto.room.UnJoinedRoomDetailsResponse; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.global.error.exception.NotFoundException; import jakarta.annotation.Nullable; import lombok.RequiredArgsConstructor;
15,259
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService {
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class SearchService {
private final RoomRepository roomRepository;
20
2023-10-20 06:15:43+00:00
24k
tuxming/xmfx
Example/src/main/java/com/xm2013/example/example/page/TextFieldPage.java
[ { "identifier": "XmCheckBox", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/checkbox/XmCheckBox.java", "snippet": "public class XmCheckBox<T> extends SelectableText implements XmToggle<T>{\n\n /* *************************************************************************\n * ...
import com.xm2013.jfx.control.base.*; import com.xm2013.jfx.control.checkbox.XmCheckBox; import com.xm2013.jfx.control.checkbox.XmToggleGroup; import com.xm2013.jfx.control.label.XmLabel; import com.xm2013.jfx.control.selector.SelectorCellFactory; import com.xm2013.jfx.control.selector.SelectorConvert; import com.xm2013.jfx.control.selector.SelectorType; import com.xm2013.jfx.control.selector.XmSelector; import com.xm2013.jfx.control.textfield.XmFieldDisplayType; import com.xm2013.jfx.control.textfield.XmTextField; import com.xm2013.jfx.control.textfield.XmTextInputType; import com.xm2013.jfx.control.icon.XmFontIcon; import javafx.beans.value.ChangeListener; import javafx.collections.*; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.layout.HBox; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import java.io.UnsupportedEncodingException; import java.util.Base64;
18,244
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * 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 com.xm2013.example.example.page; public class TextFieldPage extends BasePage { private final HBox showPasswordBox; private XmSelector<String> prefixs = null; private XmSelector<String> suffixs = null; private XmTextField labelField = null; private XmTextField echocharField = null; private XmSelector<XmAlignment> alignments = null; private XmSelector<XmFieldDisplayType> displays = null; private XmSelector<ColorType> colorTypes = null; private XmToggleGroup<RoundType> roundTypes = null; private XmToggleGroup<SizeType> sizeTypes = null; private XmToggleGroup<BorderType> borderTypes = null;
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * 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 com.xm2013.example.example.page; public class TextFieldPage extends BasePage { private final HBox showPasswordBox; private XmSelector<String> prefixs = null; private XmSelector<String> suffixs = null; private XmTextField labelField = null; private XmTextField echocharField = null; private XmSelector<XmAlignment> alignments = null; private XmSelector<XmFieldDisplayType> displays = null; private XmSelector<ColorType> colorTypes = null; private XmToggleGroup<RoundType> roundTypes = null; private XmToggleGroup<SizeType> sizeTypes = null; private XmToggleGroup<BorderType> borderTypes = null;
private XmToggleGroup<XmTextInputType> inputTypes = null;
9
2023-10-17 08:57:08+00:00
24k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/PCFGLA/UnaryCounterTable.java
[ { "identifier": "ArrayUtil", "path": "src/berkeley_parser/edu/berkeley/nlp/util/ArrayUtil.java", "snippet": "public class ArrayUtil {\r\n\r\n\t// ARITHMETIC FUNCTIONS\r\n\r\n\tpublic static double[] add(double[] a, double c) {\r\n\t\tdouble[] result = new double[a.length];\r\n\t\tfor (int i = 0; i < a.l...
import java.io.Serializable; import java.util.Map; import java.util.Set; import edu.berkeley.nlp.util.ArrayUtil; import edu.berkeley.nlp.util.MapFactory;
19,523
package edu.berkeley.nlp.PCFGLA; public class UnaryCounterTable implements Serializable { /** * Based on Counter. * * A map from objects to doubles. Includes convenience methods for getting, * setting, and incrementing element counts. Objects not in the counter will * return a count of zero. The counter is backed by a HashMap (unless * specified otherwise with the MapFactory constructor). * * @author Slav Petrov */ private static final long serialVersionUID = 1L; Map<UnaryRule, double[][]> entries; short[] numSubStates; UnaryRule searchKey; /** * The elements in the counter. * * @return set of keys */ public Set<UnaryRule> keySet() { return entries.keySet(); } /** * The number of entries in the counter (not the total count -- use * totalCount() instead). */ public int size() { return entries.size(); } /** * True if there are no entries in the counter (false does not mean * totalCount > 0) */ public boolean isEmpty() { return size() == 0; } /** * Returns whether the counter contains the given key. Note that this is the * way to distinguish keys which are in the counter with count zero, and * those which are not in the counter (and will therefore return count zero * from getCount(). * * @param key * @return whether the counter contains the key */ public boolean containsKey(UnaryRule key) { return entries.containsKey(key); } /** * Get the count of the element, or zero if the element is not in the * counter. Can return null! * * @param key * @return */ public double[][] getCount(UnaryRule key) { double[][] value = entries.get(key); return value; } public double[][] getCount(short pState, short cState) { searchKey.setNodes(pState, cState); double[][] value = entries.get(searchKey); return value; } /** * Set the count for the given key, clobbering any previous count. * * @param key * @param count */ public void setCount(UnaryRule key, double[][] counts) { entries.put(key, counts); } /** * Increment a key's count by the given amount. Assumes for efficiency that * the arrays have the same size. * * @param key * @param increment */ public void incrementCount(UnaryRule key, double[][] increment) { double[][] current = getCount(key); if (current == null) { setCount(key, increment); return; } for (int i = 0; i < current.length; i++) { // test if increment[i] is null or zero, in which case // we needn't add it if (increment[i] == null) continue; // allocate more space as needed if (current[i] == null) current[i] = new double[increment[i].length]; // if we've gotten here, then both current and increment // have correct arrays in index i for (int j = 0; j < current[i].length; j++) { current[i][j] += increment[i][j]; } } setCount(key, current); } public void incrementCount(UnaryRule key, double increment) { double[][] current = getCount(key); if (current == null) { double[][] tmp = key.getScores2(); current = new double[tmp.length][tmp[0].length];
package edu.berkeley.nlp.PCFGLA; public class UnaryCounterTable implements Serializable { /** * Based on Counter. * * A map from objects to doubles. Includes convenience methods for getting, * setting, and incrementing element counts. Objects not in the counter will * return a count of zero. The counter is backed by a HashMap (unless * specified otherwise with the MapFactory constructor). * * @author Slav Petrov */ private static final long serialVersionUID = 1L; Map<UnaryRule, double[][]> entries; short[] numSubStates; UnaryRule searchKey; /** * The elements in the counter. * * @return set of keys */ public Set<UnaryRule> keySet() { return entries.keySet(); } /** * The number of entries in the counter (not the total count -- use * totalCount() instead). */ public int size() { return entries.size(); } /** * True if there are no entries in the counter (false does not mean * totalCount > 0) */ public boolean isEmpty() { return size() == 0; } /** * Returns whether the counter contains the given key. Note that this is the * way to distinguish keys which are in the counter with count zero, and * those which are not in the counter (and will therefore return count zero * from getCount(). * * @param key * @return whether the counter contains the key */ public boolean containsKey(UnaryRule key) { return entries.containsKey(key); } /** * Get the count of the element, or zero if the element is not in the * counter. Can return null! * * @param key * @return */ public double[][] getCount(UnaryRule key) { double[][] value = entries.get(key); return value; } public double[][] getCount(short pState, short cState) { searchKey.setNodes(pState, cState); double[][] value = entries.get(searchKey); return value; } /** * Set the count for the given key, clobbering any previous count. * * @param key * @param count */ public void setCount(UnaryRule key, double[][] counts) { entries.put(key, counts); } /** * Increment a key's count by the given amount. Assumes for efficiency that * the arrays have the same size. * * @param key * @param increment */ public void incrementCount(UnaryRule key, double[][] increment) { double[][] current = getCount(key); if (current == null) { setCount(key, increment); return; } for (int i = 0; i < current.length; i++) { // test if increment[i] is null or zero, in which case // we needn't add it if (increment[i] == null) continue; // allocate more space as needed if (current[i] == null) current[i] = new double[increment[i].length]; // if we've gotten here, then both current and increment // have correct arrays in index i for (int j = 0; j < current[i].length; j++) { current[i][j] += increment[i][j]; } } setCount(key, current); } public void incrementCount(UnaryRule key, double increment) { double[][] current = getCount(key); if (current == null) { double[][] tmp = key.getScores2(); current = new double[tmp.length][tmp[0].length];
ArrayUtil.fill(current, increment);
0
2023-10-22 13:13:22+00:00
24k
neftalito/R-Info-Plus
form/Parser.java
[ { "identifier": "Iniciar", "path": "arbol/sentencia/primitiva/Iniciar.java", "snippet": "public class Iniciar extends Primitiva {\n RobotAST r;\n int x;\n int y;\n Identificador Ident;\n DeclaracionRobots robAST;\n DeclaracionVariable varAST;\n\n public Iniciar(final Identificador I...
import arbol.sentencia.primitiva.Iniciar; import arbol.sentencia.primitiva.AsignarArea; import arbol.DeclaracionAreas; import arbol.Programa; import arbol.ParametroFormal; import arbol.Proceso; import arbol.RobotAST; import arbol.DeclaracionProcesos; import arbol.Cuerpo; import arbol.sentencia.IteradorCondicional; import arbol.sentencia.IteradorIncondicional; import arbol.sentencia.Seleccion; import arbol.sentencia.primitiva.Random; import arbol.sentencia.primitiva.RecibirMensaje; import arbol.sentencia.primitiva.EnviarMensaje; import arbol.sentencia.primitiva.DepositarPapel; import arbol.sentencia.primitiva.DepositarFlor; import arbol.sentencia.primitiva.TomarPapel; import arbol.sentencia.primitiva.TomarFlor; import arbol.sentencia.primitiva.Derecha; import arbol.sentencia.primitiva.Izquierda; import arbol.sentencia.primitiva.Mover; import arbol.sentencia.primitiva.Leer; import arbol.sentencia.primitiva.BloquearEsquina; import arbol.sentencia.primitiva.LiberarEsquina; import arbol.sentencia.primitiva.Primitiva; import arbol.llamada.IdentificadorLlamada; import arbol.sentencia.Sentencia; import arbol.sentencia.Asignacion; import arbol.llamada.Pos; import arbol.llamada.Informar; import java.util.ArrayList; import arbol.sentencia.Invocacion; import javax.swing.JOptionPane; import arbol.DeclaracionRobots; import arbol.Tipo; import arbol.Variable; import arbol.Identificador; import arbol.expresion.ExpresionBinaria; import arbol.expresion.ExpresionUnaria; import java.util.Stack; import arbol.DeclaracionVariable; import arbol.expresion.ValorBooleano; import arbol.expresion.ValorNumerico; import arbol.expresion.operador.relacional.MenorIgual; import arbol.expresion.operador.relacional.Menor; import arbol.expresion.operador.relacional.MayorIgual; import arbol.expresion.operador.relacional.Mayor; import arbol.expresion.operador.relacional.Igual; import arbol.expresion.operador.relacional.Distinto; import arbol.expresion.operador.booleano.Not; import arbol.expresion.operador.booleano.Or; import arbol.expresion.operador.booleano.And; import arbol.expresion.operador.aritmetico.Suma; import arbol.expresion.operador.aritmetico.Resta; import arbol.expresion.operador.aritmetico.Multiplicacion; import arbol.expresion.operador.aritmetico.Division; import arbol.expresion.operador.aritmetico.Modulo; import arbol.expresion.operador.Operador; import arbol.expresion.HayObstaculo; import arbol.expresion.HayPapelEnLaEsquina; import arbol.expresion.HayFlorEnLaEsquina; import arbol.expresion.HayPapelEnLaBolsa; import arbol.expresion.HayFlorEnLaBolsa; import arbol.expresion.PosCa; import arbol.expresion.PosAv; import arbol.expresion.CantidadFloresBolsa; import arbol.expresion.CantidadPapelesBolsa; import arbol.expresion.Expresion;
20,872
package form; public class Parser { public Token currentToken; private Scanner scanner; Ciudad city; Parser(final String fuente, final Ciudad city) throws Exception { this.city = city; this.scanner = new Scanner(fuente); try { this.nextToken(); } catch (Exception e) { this.reportParseError("Error in Parser!"); } } public boolean isOperando(final Token token) { return token.kind == 23 || token.kind == 32 || token.kind == 33; } public boolean isVariableEntorno(final Token token) { switch (token.kind) { case 8: case 9: case 10: case 11: case 12: case 13: case 63: case 82: case 83: { return true; } default: { return false; } } } public boolean isOperador(final Token token) { boolean res = false; switch (token.kind) { case 30: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: { expAST = new PosCa(); break; } case 11: { expAST = new HayFlorEnLaBolsa(); break; } case 13: { expAST = new HayPapelEnLaBolsa(); break; } case 10: {
package form; public class Parser { public Token currentToken; private Scanner scanner; Ciudad city; Parser(final String fuente, final Ciudad city) throws Exception { this.city = city; this.scanner = new Scanner(fuente); try { this.nextToken(); } catch (Exception e) { this.reportParseError("Error in Parser!"); } } public boolean isOperando(final Token token) { return token.kind == 23 || token.kind == 32 || token.kind == 33; } public boolean isVariableEntorno(final Token token) { switch (token.kind) { case 8: case 9: case 10: case 11: case 12: case 13: case 63: case 82: case 83: { return true; } default: { return false; } } } public boolean isOperador(final Token token) { boolean res = false; switch (token.kind) { case 30: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 81: { res = true; break; } default: { res = false; break; } } return res; } public boolean isParentesis(final Token token) { boolean res = false; switch (token.kind) { case 21: case 22: { res = true; break; } default: { res = false; break; } } return res; } public boolean thereIsHighOrEqualPrecedence(final Object o) { boolean res = true; final Token t = (Token) o; if (t.kind == 21 || (this.currentToken.kind == 49 && t.kind == 50) || (this.currentToken.kind == 49 && t.kind == 51) || ((this.currentToken.kind == 48 || this.currentToken.kind == 47 || this.currentToken.kind == 81) && (t.kind == 45 || t.kind == 46))) { res = false; } return res; } public Expresion parseVariableEntorno(final Token t) { Expresion expAST = null; switch (t.kind) { case 8: { expAST = new PosAv(); break; } case 9: { expAST = new PosCa(); break; } case 11: { expAST = new HayFlorEnLaBolsa(); break; } case 13: { expAST = new HayPapelEnLaBolsa(); break; } case 10: {
expAST = new HayFlorEnLaEsquina();
58
2023-10-20 15:45:37+00:00
24k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthSubscriberAdapter.java
[ { "identifier": "EthRegistryProperties", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/config/EthRegistryProperties.java", "snippet": "@ConfigurationProperties(prefix = \"eth.registry\")\n@Data\npublic class EthRegistryProperties {\n public String contractAddress;\n}" }, ...
import java.util.List; import com.moonstoneid.aerocast.common.config.EthRegistryProperties; import com.moonstoneid.aerocast.common.eth.BaseEthAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedRegistry; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.CreateSubscriptionEventResponse; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber.RemoveSubscriptionEventResponse; import io.reactivex.disposables.Disposable; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.request.EthFilter;
18,084
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthSubscriberAdapter extends BaseEthAdapter { public interface EventCallback { void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr); void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr); } private final Credentials credentials; private final String regContractAddr; private final MultiValueMap<String, Disposable> eventSubscribers = new LinkedMultiValueMap<>(); public EthSubscriberAdapter(Web3j web3j, EthRegistryProperties ethRegistryProperties) { super(web3j); this.credentials = createDummyCredentials(); this.regContractAddr = ethRegistryProperties.getContractAddress(); } public String getSubscriberContractAddress(String subAccountAddr) { FeedRegistry contract = getRegistryContract(); try { String subContractAddr = contract.getSubscriberContractByAddress(subAccountAddr) .sendAsync().get(); if (!isValidAddress(subContractAddr)) { return null; } return subContractAddr; } catch (Exception e) { throw new RuntimeException(e); } } public void registerSubscriptionEventListener(String subContractAddr, String blockNumber, EventCallback callback) { log.debug("Adding event listener on subscriber contract '{}'.", EthUtil.shortenAddress(subContractAddr)); FeedSubscriber contract = getSubscriberContract(subContractAddr); EthFilter subEventFilter = createEventFilter(subContractAddr, blockNumber, FeedSubscriber.CREATESUBSCRIPTION_EVENT); Disposable subEventSubscriber = contract.createSubscriptionEventFlowable(subEventFilter) .subscribe(r -> handleSubscribeEvent(subContractAddr, r, callback)); eventSubscribers.add(subContractAddr, subEventSubscriber); EthFilter unsubEventFilter = createEventFilter(subContractAddr, blockNumber, FeedSubscriber.REMOVESUBSCRIPTION_EVENT); Disposable unsubEventSubscriber = contract.removeSubscriptionEventFlowable(unsubEventFilter) .subscribe(r -> handleUnsubscribeEvent(subContractAddr, r, callback)); eventSubscribers.add(subContractAddr, unsubEventSubscriber); } private void handleSubscribeEvent(String subContractAddr,
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j public class EthSubscriberAdapter extends BaseEthAdapter { public interface EventCallback { void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr); void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr); } private final Credentials credentials; private final String regContractAddr; private final MultiValueMap<String, Disposable> eventSubscribers = new LinkedMultiValueMap<>(); public EthSubscriberAdapter(Web3j web3j, EthRegistryProperties ethRegistryProperties) { super(web3j); this.credentials = createDummyCredentials(); this.regContractAddr = ethRegistryProperties.getContractAddress(); } public String getSubscriberContractAddress(String subAccountAddr) { FeedRegistry contract = getRegistryContract(); try { String subContractAddr = contract.getSubscriberContractByAddress(subAccountAddr) .sendAsync().get(); if (!isValidAddress(subContractAddr)) { return null; } return subContractAddr; } catch (Exception e) { throw new RuntimeException(e); } } public void registerSubscriptionEventListener(String subContractAddr, String blockNumber, EventCallback callback) { log.debug("Adding event listener on subscriber contract '{}'.", EthUtil.shortenAddress(subContractAddr)); FeedSubscriber contract = getSubscriberContract(subContractAddr); EthFilter subEventFilter = createEventFilter(subContractAddr, blockNumber, FeedSubscriber.CREATESUBSCRIPTION_EVENT); Disposable subEventSubscriber = contract.createSubscriptionEventFlowable(subEventFilter) .subscribe(r -> handleSubscribeEvent(subContractAddr, r, callback)); eventSubscribers.add(subContractAddr, subEventSubscriber); EthFilter unsubEventFilter = createEventFilter(subContractAddr, blockNumber, FeedSubscriber.REMOVESUBSCRIPTION_EVENT); Disposable unsubEventSubscriber = contract.removeSubscriptionEventFlowable(unsubEventFilter) .subscribe(r -> handleUnsubscribeEvent(subContractAddr, r, callback)); eventSubscribers.add(subContractAddr, unsubEventSubscriber); } private void handleSubscribeEvent(String subContractAddr,
CreateSubscriptionEventResponse response, EventCallback callback) {
5
2023-10-23 20:33:07+00:00
24k
JonnyOnlineYT/xenza
src/minecraft/net/augustus/material/button/values/BMode.java
[ { "identifier": "EventClickGui", "path": "src/minecraft/net/augustus/events/EventClickGui.java", "snippet": "public class EventClickGui extends Event {\n}" }, { "identifier": "UnicodeFontRenderer", "path": "src/minecraft/net/augustus/font/UnicodeFontRenderer.java", "snippet": "public cla...
import net.augustus.events.EventClickGui; import net.augustus.font.UnicodeFontRenderer; import net.augustus.material.Main; import net.augustus.material.Tab; import net.augustus.material.button.Button; import net.augustus.settings.Setting; import net.augustus.settings.StringValue; import net.augustus.utils.skid.tomorrow.RenderUtil; import net.lenni0451.eventapi.manager.EventManager; import org.lwjgl.input.Mouse; import java.awt.*;
17,690
package net.augustus.material.button.values; public class BMode extends Button { private static UnicodeFontRenderer arial18; private static UnicodeFontRenderer arial16; static { try { arial18 = new UnicodeFontRenderer(Font.createFont(0, BMode.class.getResourceAsStream("/ressources/arial.ttf")).deriveFont(18F)); } catch (Exception e) { e.printStackTrace(); } try { arial16 = new UnicodeFontRenderer(Font.createFont(0, BMode.class.getResourceAsStream("/ressources/arial.ttf")).deriveFont(16F)); } catch (Exception e) { e.printStackTrace(); } }
package net.augustus.material.button.values; public class BMode extends Button { private static UnicodeFontRenderer arial18; private static UnicodeFontRenderer arial16; static { try { arial18 = new UnicodeFontRenderer(Font.createFont(0, BMode.class.getResourceAsStream("/ressources/arial.ttf")).deriveFont(18F)); } catch (Exception e) { e.printStackTrace(); } try { arial16 = new UnicodeFontRenderer(Font.createFont(0, BMode.class.getResourceAsStream("/ressources/arial.ttf")).deriveFont(16F)); } catch (Exception e) { e.printStackTrace(); } }
public BMode(float x, float y, Setting v, Tab moduleTab) {
5
2023-10-15 00:21:15+00:00
24k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/query/QueryUtil.java
[ { "identifier": "ResultSetIterator", "path": "src/com/identityworksllc/iiq/common/iterators/ResultSetIterator.java", "snippet": "@SuppressWarnings(\"unused\")\npublic final class ResultSetIterator implements Iterator<Object[]>, AutoCloseable {\n\n\t/**\n\t * An interface to use for custom type handlers\...
import com.identityworksllc.iiq.common.iterators.ResultSetIterator; import com.identityworksllc.iiq.common.threads.PooledWorkerResults; import com.identityworksllc.iiq.common.threads.SailPointWorker; import com.identityworksllc.iiq.common.vo.Failure; import openconnector.Util; import org.apache.commons.logging.Log; import sailpoint.api.SailPointContext; import sailpoint.api.SailPointFactory; import sailpoint.object.Filter; import sailpoint.object.QueryOptions; import sailpoint.object.SailPointObject; import sailpoint.tools.GeneralException; import sailpoint.tools.ObjectNotFoundException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
14,712
this.logger = log; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public T getResult(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); T output = null; try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { if (results.next()) { output = processor.processResult(results); } else { processor.noResult(); } } } } return output; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public List<T> getResults(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); List<T> output = new ArrayList<>(); try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { boolean hasResults = false; while (results.next()) { hasResults = true; output.add(processor.processResult(results)); } if (!hasResults) { processor.noResult(); } } } } return output; } /** * Iterates a query by invoking a Beanshell callback for each method * @param inputs The inputs * @throws GeneralException if anything goes wrong */ public void iterateQuery(IterateQueryOptions inputs) throws GeneralException { try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); } ResultSetIterator rsi = new ResultSetIterator(results, columns, sailPointContext); while(rsi.hasNext()) { Map<String, Object> row = rsi.nextRow(); inputs.doCallback(row); } } } } catch(SQLException e) { throw new GeneralException(e); } } /** * Iterates over a query in parallel, making a call to the defined callback * in the input options. (NOTE: Beanshell is explicitly thread-safe, but you * should use the thread context provided and you should not access shared * resources without doing your own thread-safety stuff.) * * @param inputs The input options * @param threads The number of threads to use * @throws GeneralException if anything fails */ public PooledWorkerResults<Map<String, Object>> parallelIterateQuery(IterateQueryOptions inputs, int threads) throws GeneralException { PooledWorkerResults<Map<String, Object>> resultContainer = new PooledWorkerResults<>(); ExecutorService executor = Executors.newWorkStealingPool(threads); logger.info("Starting worker pool with " + threads + " threads"); try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); } ResultSetIterator rsi = new ResultSetIterator(results, columns, sailPointContext); while(rsi.hasNext() && Thread.currentThread().isInterrupted()) { final Map<String, Object> row = new HashMap<>(rsi.nextRow());
package com.identityworksllc.iiq.common.query; /** * Simplifies querying by automatically enclosing queries in a result processing loop. * This is copied from an older project. IIQ also provides a number of similar utilities * in their JdbcUtil class. * * @param <T> The type returned from the result processor */ @SuppressWarnings("unused") public class QueryUtil<T> { /** * Callback for processing the result * * @param <U> The type returned from the result processor, must extend T */ @FunctionalInterface public interface ResultProcessor<U> { /** * Callback to indicate that the result set had no results * * @throws SQLException on failures */ @SuppressWarnings("unused") default void noResult() throws SQLException { // Blank by default } /** * Called once per result. Do not call "next" on the ResultSet here. * * @param result The result set at the current point * @return An object of type T * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ U processResult(ResultSet result) throws GeneralException, SQLException; } /** * Static helper method to retrieve the first value from the result set as a long * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static Long getLongValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<Long>(Log).getResult(query, result -> result.getLong(resultColumn), parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. The column name is assumed to be 'id', which is the primary key in * most of the SailPoint tables. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final Log log, Object... parameters) throws Throwable { return getObjectByQuery(context, cls, query, "id", log, parameters); } /** * Retrieves the first string from the result set in the given column, then * queries for a sailPoint object of the given type based on that name or * ID. * * @param context The Sailpoint context to use to query * @param cls The class to query based on the ID being pulled * @param query The query to run * @param idColumn The column to grab from the results * @param log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static <T extends SailPointObject> T getObjectByQuery(final SailPointContext context, Class<T> cls, final String query, final String idColumn, final Log log, Object... parameters) throws Throwable { String id = getStringValue(query, idColumn, log, parameters); return context.getObject(cls, id); } /** * Static helper method ot retrieve values from the query as a list of strings * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static List<String> getStringList(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResults(query, result -> result.getString(resultColumn), parameters); } /** * Static helper method to retrieve the first string value from the result set * * @param query The query to run * @param resultColumn The column to grab from the results * @param Log logger * @param parameters Any parameters * @return A list of result strings * @throws Throwable On failures */ public static String getStringValue(final String query, final String resultColumn, Log Log, Object... parameters) throws Throwable { return new QueryUtil<String>(Log).getResult(query, result -> result.getString(resultColumn), parameters); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filterString The Filter string * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, String filterString) throws GeneralException { Filter filter = Filter.compile(filterString); return getUniqueObject(context, cls, filter); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param filter a Filter object * @param <T> The type of the object to query * @return The queried object * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, Filter filter) throws GeneralException { QueryOptions qo = new QueryOptions(); qo.add(filter); return getUniqueObject(context, cls, qo); } /** * Retrieves a unique object with the given Filter string * @param context The Sailpoint Context * @param cls The class to query for * @param queryOptions a QueryOptions object which will be cloned before querying * @param <T> The type of the object to query * @return The queried object * @throws ObjectNotFoundException if no matches are found * @throws GeneralException if too many or too few objects are found */ public static <T extends SailPointObject> T getUniqueObject(SailPointContext context, Class<T> cls, QueryOptions queryOptions) throws ObjectNotFoundException, GeneralException { QueryOptions qo = new QueryOptions(); qo.setFilters(queryOptions.getFilters()); qo.setCacheResults(queryOptions.isCacheResults()); qo.setDirtyRead(queryOptions.isDirtyRead()); qo.setDistinct(queryOptions.isDistinct()); qo.setFlushBeforeQuery(queryOptions.isFlushBeforeQuery()); qo.setGroupBys(queryOptions.getGroupBys()); qo.setOrderings(queryOptions.getOrderings()); qo.setScopeResults(queryOptions.getScopeResults()); qo.setTransactionLock(queryOptions.isTransactionLock()); qo.setUnscopedGloballyAccessible(queryOptions.getUnscopedGloballyAccessible()); qo.setResultLimit(2); List<T> results = context.getObjects(cls, qo); if (results == null || results.isEmpty()) { throw new ObjectNotFoundException(); } else if (results.size() > 1) { throw new GeneralException("Expected a unique result, got " + results.size() + " results"); } return results.get(0); } /** * Set up the given parameters in the prepared statmeent * @param stmt The statement * @param parameters The parameters * @throws SQLException if any failures occur setting parameters */ public static void setupParameters(PreparedStatement stmt, Object[] parameters) throws SQLException { Parameters.setupParameters(stmt, parameters); } /** * Logger */ private final Log logger; /** * Connection to SailPoint */ private final SailPointContext sailPointContext; /** * Constructor * @param Log logger * @throws GeneralException if there is an error getting the current thread's SailPoint context */ public QueryUtil(@SuppressWarnings("unused") Log Log) throws GeneralException { this(SailPointFactory.getCurrentContext(), Log); } /** * Constructor * @param context The SailPoint context * @param log The logger */ public QueryUtil(SailPointContext context, Log log) { this.sailPointContext = context; this.logger = log; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public T getResult(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); T output = null; try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { if (results.next()) { output = processor.processResult(results); } else { processor.noResult(); } } } } return output; } /** * @param query The query to execute * @param processor The class to call for every iteration of the loop * @param parameters The parameters for the query, if any * @return A list of results output by the ResultProcessor * @throws GeneralException on any Sailpoint failures * @throws SQLException on any database failures */ public List<T> getResults(String query, ResultProcessor<? extends T> processor, Object... parameters) throws GeneralException, SQLException { logger.debug("Query = " + query); List<T> output = new ArrayList<>(); try (Connection conn = ContextConnectionWrapper.getConnection(sailPointContext)) { try (PreparedStatement stmt = conn.prepareStatement(query)) { setupParameters(stmt, parameters); try (ResultSet results = stmt.executeQuery()) { boolean hasResults = false; while (results.next()) { hasResults = true; output.add(processor.processResult(results)); } if (!hasResults) { processor.noResult(); } } } } return output; } /** * Iterates a query by invoking a Beanshell callback for each method * @param inputs The inputs * @throws GeneralException if anything goes wrong */ public void iterateQuery(IterateQueryOptions inputs) throws GeneralException { try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); } ResultSetIterator rsi = new ResultSetIterator(results, columns, sailPointContext); while(rsi.hasNext()) { Map<String, Object> row = rsi.nextRow(); inputs.doCallback(row); } } } } catch(SQLException e) { throw new GeneralException(e); } } /** * Iterates over a query in parallel, making a call to the defined callback * in the input options. (NOTE: Beanshell is explicitly thread-safe, but you * should use the thread context provided and you should not access shared * resources without doing your own thread-safety stuff.) * * @param inputs The input options * @param threads The number of threads to use * @throws GeneralException if anything fails */ public PooledWorkerResults<Map<String, Object>> parallelIterateQuery(IterateQueryOptions inputs, int threads) throws GeneralException { PooledWorkerResults<Map<String, Object>> resultContainer = new PooledWorkerResults<>(); ExecutorService executor = Executors.newWorkStealingPool(threads); logger.info("Starting worker pool with " + threads + " threads"); try (Connection connection = inputs.openConnection()) { try (NamedParameterStatement stmt = new NamedParameterStatement(connection, inputs.getQuery())) { if (!Util.isEmpty(inputs.getQueryParams())) { stmt.setParameters(inputs.getQueryParams()); } try (ResultSet results = stmt.executeQuery()) { ResultSetMetaData rsmd = results.getMetaData(); List<String> columns = new ArrayList<>(); for(int c = 1; c <= rsmd.getColumnCount(); c++) { columns.add(rsmd.getColumnLabel(c)); } ResultSetIterator rsi = new ResultSetIterator(results, columns, sailPointContext); while(rsi.hasNext() && Thread.currentThread().isInterrupted()) { final Map<String, Object> row = new HashMap<>(rsi.nextRow());
SailPointWorker worker = setupWorker(inputs, resultContainer, row);
2
2023-10-20 15:20:16+00:00
24k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/TseServerApp.java
[ { "identifier": "FcdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java", "snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private...
import java.nio.file.Path; import java.nio.file.Paths; import com.dcaiti.mosaic.app.fxd.data.FcdRecord; import com.dcaiti.mosaic.app.fxd.data.FcdTraversal; import com.dcaiti.mosaic.app.fxd.messages.FcdUpdateMessage; import com.dcaiti.mosaic.app.tse.config.CTseServerApp; import com.dcaiti.mosaic.app.tse.persistence.FcdDataStorage; import com.dcaiti.mosaic.app.tse.persistence.FcdDatabaseHelper; import com.dcaiti.mosaic.app.tse.persistence.ScenarioDatabaseHelper; import com.dcaiti.mosaic.app.tse.processors.SpatioTemporalProcessor; import com.dcaiti.mosaic.app.tse.processors.ThresholdProcessor; import org.eclipse.mosaic.lib.database.Database; import org.eclipse.mosaic.lib.objects.v2x.V2xMessage; import org.eclipse.mosaic.lib.util.scheduling.EventManager; import com.google.common.collect.Lists;
15,787
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse; /** * An extension of {@link FxdReceiverApp} adding the data storage in the form of the {@link FcdDataStorage} and the * Network-{@link Database} and configuring default * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor FxdProcessors}. */ public class TseServerApp extends FxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage, CTseServerApp, TseKernel> { /** * Storage field, allowing to persist TSE results as well as data exchange between processors. * Default value will be a {@link FcdDatabaseHelper} */ private FcdDataStorage fcdDataStorage; public TseServerApp() { super(CTseServerApp.class); } @Override public void enableCellModule() { getOs().getCellModule().enable(); } /** * Initializes the {@link TseKernel} by * <ul> * <li>validating that processors for minimal function are configured,</li> * <li> reading the scenario database for access to network specific data,</li> * <li>and setting up the {@link #fcdDataStorage} to persist TSE metrics.</li> * </ul> * * @param eventManager the {@link EventManager} to enable the kernel with event handling capabilities * @param config configuration for the server * @return the initialized {@link TseKernel} */ @Override protected TseKernel initKernel(EventManager eventManager, CTseServerApp config) { addRequiredProcessors(config); Database networkDatabase = ScenarioDatabaseHelper.getNetworkDbFromFile(getOs()); String databaseDirectory = config.databasePath == null ? getOs().getConfigurationPath().getPath() : getConfiguration().databasePath; String databaseFileName = getConfiguration().databaseFileName == null ? "FcdData.sqlite" : getConfiguration().databaseFileName; Path databasePath = Paths.get(databaseDirectory, databaseFileName); // set data storage to configured type else use default FcdDatabaseHelper fcdDataStorage = config.fcdDataStorage == null ? new FcdDatabaseHelper() : config.fcdDataStorage; fcdDataStorage.initialize(databasePath, networkDatabase, config.isPersistent, getLog()); return new TseKernel(eventManager, getLog(), config, fcdDataStorage, networkDatabase); } private void addRequiredProcessors(CTseServerApp config) { if (config.traversalBasedProcessors == null) { config.traversalBasedProcessors = Lists.newArrayList(new SpatioTemporalProcessor()); } else if (config.traversalBasedProcessors.stream().noneMatch(processor -> processor instanceof SpatioTemporalProcessor)) { config.traversalBasedProcessors.add(new SpatioTemporalProcessor()); } if (config.timeBasedProcessors == null) {
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse; /** * An extension of {@link FxdReceiverApp} adding the data storage in the form of the {@link FcdDataStorage} and the * Network-{@link Database} and configuring default * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor FxdProcessors}. */ public class TseServerApp extends FxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage, CTseServerApp, TseKernel> { /** * Storage field, allowing to persist TSE results as well as data exchange between processors. * Default value will be a {@link FcdDatabaseHelper} */ private FcdDataStorage fcdDataStorage; public TseServerApp() { super(CTseServerApp.class); } @Override public void enableCellModule() { getOs().getCellModule().enable(); } /** * Initializes the {@link TseKernel} by * <ul> * <li>validating that processors for minimal function are configured,</li> * <li> reading the scenario database for access to network specific data,</li> * <li>and setting up the {@link #fcdDataStorage} to persist TSE metrics.</li> * </ul> * * @param eventManager the {@link EventManager} to enable the kernel with event handling capabilities * @param config configuration for the server * @return the initialized {@link TseKernel} */ @Override protected TseKernel initKernel(EventManager eventManager, CTseServerApp config) { addRequiredProcessors(config); Database networkDatabase = ScenarioDatabaseHelper.getNetworkDbFromFile(getOs()); String databaseDirectory = config.databasePath == null ? getOs().getConfigurationPath().getPath() : getConfiguration().databasePath; String databaseFileName = getConfiguration().databaseFileName == null ? "FcdData.sqlite" : getConfiguration().databaseFileName; Path databasePath = Paths.get(databaseDirectory, databaseFileName); // set data storage to configured type else use default FcdDatabaseHelper fcdDataStorage = config.fcdDataStorage == null ? new FcdDatabaseHelper() : config.fcdDataStorage; fcdDataStorage.initialize(databasePath, networkDatabase, config.isPersistent, getLog()); return new TseKernel(eventManager, getLog(), config, fcdDataStorage, networkDatabase); } private void addRequiredProcessors(CTseServerApp config) { if (config.traversalBasedProcessors == null) { config.traversalBasedProcessors = Lists.newArrayList(new SpatioTemporalProcessor()); } else if (config.traversalBasedProcessors.stream().noneMatch(processor -> processor instanceof SpatioTemporalProcessor)) { config.traversalBasedProcessors.add(new SpatioTemporalProcessor()); } if (config.timeBasedProcessors == null) {
config.timeBasedProcessors = Lists.newArrayList(new ThresholdProcessor());
8
2023-10-23 16:39:40+00:00
24k
eclipse-egit/egit
org.eclipse.egit.gitflow/src/org/eclipse/egit/gitflow/op/InitOperation.java
[ { "identifier": "error", "path": "org.eclipse.egit.gitflow/src/org/eclipse/egit/gitflow/Activator.java", "snippet": "public static IStatus error(String message, Throwable throwable) {\n\treturn new Status(IStatus.ERROR, getPluginId(), 0, message, throwable);\n}" }, { "identifier": "DEVELOP_KEY",...
import static org.eclipse.egit.gitflow.Activator.error; import static org.eclipse.egit.gitflow.GitFlowConfig.DEVELOP_KEY; import static org.eclipse.egit.gitflow.GitFlowConfig.FEATURE_KEY; import static org.eclipse.egit.gitflow.GitFlowConfig.HOTFIX_KEY; import static org.eclipse.egit.gitflow.GitFlowConfig.MASTER_KEY; import static org.eclipse.egit.gitflow.GitFlowConfig.RELEASE_KEY; import static org.eclipse.egit.gitflow.GitFlowConfig.VERSION_TAG_KEY; import static org.eclipse.egit.gitflow.GitFlowDefaults.VERSION_TAG; import static org.eclipse.jgit.lib.Constants.R_HEADS; import java.io.IOException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.egit.core.op.BranchOperation; import org.eclipse.egit.core.op.CommitOperation; import org.eclipse.egit.core.op.CreateLocalBranchOperation; import org.eclipse.egit.gitflow.GitFlowConfig; import org.eclipse.egit.gitflow.GitFlowRepository; import org.eclipse.egit.gitflow.InitParameters; import org.eclipse.egit.gitflow.WrongGitFlowStateException; import org.eclipse.egit.gitflow.internal.CoreText; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.osgi.util.NLS;
14,445
/******************************************************************************* * Copyright (C) 2015, Max Hohenegger <eclipse@hohenegger.eu> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.gitflow.op; /** * git flow init */ public final class InitOperation extends GitFlowOperation { private String develop; private String master; private String feature; private String release; private String hotfix; private String versionTag; /** * @param jGitRepository * @param parameters * @since 4.1 */ public InitOperation(@NonNull Repository jGitRepository, @NonNull InitParameters parameters) { super(new GitFlowRepository(jGitRepository)); this.develop = parameters.getDevelop(); this.master = parameters.getMaster(); this.feature = parameters.getFeature(); this.release = parameters.getRelease(); this.hotfix = parameters.getHotfix(); this.versionTag = parameters.getVersionTag(); } /** * use default prefixes and names * * @param repository */ public InitOperation(Repository repository) { this(repository, new InitParameters()); } /** * @param repository * @param develop * @param master * @param featurePrefix * @param releasePrefix * @param hotfixPrefix */ public InitOperation(Repository repository, String develop, String master, String featurePrefix, String releasePrefix, String hotfixPrefix) { super(new GitFlowRepository(repository)); this.develop = develop; this.master = master; this.feature = featurePrefix; this.release = releasePrefix; this.hotfix = hotfixPrefix; this.versionTag = VERSION_TAG; } @Override public void execute(IProgressMonitor monitor) throws CoreException { try { setPrefixes(feature, release, hotfix, versionTag); setBranches(develop, master); repository.getRepository().getConfig().save(); } catch (IOException e) {
/******************************************************************************* * Copyright (C) 2015, Max Hohenegger <eclipse@hohenegger.eu> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.gitflow.op; /** * git flow init */ public final class InitOperation extends GitFlowOperation { private String develop; private String master; private String feature; private String release; private String hotfix; private String versionTag; /** * @param jGitRepository * @param parameters * @since 4.1 */ public InitOperation(@NonNull Repository jGitRepository, @NonNull InitParameters parameters) { super(new GitFlowRepository(jGitRepository)); this.develop = parameters.getDevelop(); this.master = parameters.getMaster(); this.feature = parameters.getFeature(); this.release = parameters.getRelease(); this.hotfix = parameters.getHotfix(); this.versionTag = parameters.getVersionTag(); } /** * use default prefixes and names * * @param repository */ public InitOperation(Repository repository) { this(repository, new InitParameters()); } /** * @param repository * @param develop * @param master * @param featurePrefix * @param releasePrefix * @param hotfixPrefix */ public InitOperation(Repository repository, String develop, String master, String featurePrefix, String releasePrefix, String hotfixPrefix) { super(new GitFlowRepository(repository)); this.develop = develop; this.master = master; this.feature = featurePrefix; this.release = releasePrefix; this.hotfix = hotfixPrefix; this.versionTag = VERSION_TAG; } @Override public void execute(IProgressMonitor monitor) throws CoreException { try { setPrefixes(feature, release, hotfix, versionTag); setBranches(develop, master); repository.getRepository().getConfig().save(); } catch (IOException e) {
throw new CoreException(error(e.getMessage(), e));
0
2023-10-20 15:17:51+00:00
24k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q12.java
[ { "identifier": "OrderLine", "path": "code/src/main/java/bean/OrderLine.java", "snippet": "@Getter\npublic class OrderLine {\n public Timestamp ol_delivery_d;\n public Timestamp ol_receipdate;\n public Timestamp ol_commitdate;\n\n public OrderLine(Timestamp ol_delivery_d, Timestamp ol_commit...
import bean.OrderLine; import bean.ReservoirSamplingSingleton; import benchmark.olap.OLAPTerminal; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import static benchmark.oltp.OLTPClient.gloabalSysCurrentTime; import static config.CommonConfig.DB_OCEANBASE; import static config.CommonConfig.DB_POSTGRES;
15,095
package benchmark.olap.query; public class Q12 extends baseQuery { private static Logger log = Logger.getLogger(Q12.class); public double k; public double b; private int dbType; public Q12(int dbType) throws ParseException { super(); this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.filterRate = benchmark.olap.OLAPClient.filterRate[11]; //ol_receipdate=0.1518 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.orderLineTableSize.get() * filterRate; // log.info("#12:filterRate" + filterRate); // log.info("#1:countNumber"); SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-02 00:00:00");//min date 1992-01-01,1994-01-01 Date start_d_1 = simFormat.parse("1992-01-01 00:00:00"); // log.info("#12: countNumber:" + countNumber + ",size:" + OLAPTerminal.orderlineTableNotNullSize); if (countNumber >= OLAPTerminal.orderlineTableRecipDateNotNullSize.get()) { int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q12-this.b" + this.b + ",this.k" + this.k); // log.info("Q12-1 s: " + s); return simFormat.format(super.getDateAfter(start_d, s)); } else { double historyNumber = OLAPTerminal.orderlineTableRecipDateNotNullSize.get() - countNumber; int s = (int) ((1 - historyNumber / OLAPTerminal.orderlineTableRecipDateNotNullSize.get()) * ((2405+OLTPClient.deltaDays2) * 24 * 60 * 60)); // log.info("Q12-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } // OrderLine orderLine = ReservoirSamplingSingleton.getInstance().getOrderLine(filterRate); // System.out.println(orderLine); // return orderLine.getOl_receipdate().toString(); } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query;
package benchmark.olap.query; public class Q12 extends baseQuery { private static Logger log = Logger.getLogger(Q12.class); public double k; public double b; private int dbType; public Q12(int dbType) throws ParseException { super(); this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.filterRate = benchmark.olap.OLAPClient.filterRate[11]; //ol_receipdate=0.1518 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { this.k = OLTPClient.k2; this.b = OLTPClient.b2; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException { double countNumber = OLAPTerminal.orderLineTableSize.get() * filterRate; // log.info("#12:filterRate" + filterRate); // log.info("#1:countNumber"); SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start_d = simFormat.parse("1998-08-02 00:00:00");//min date 1992-01-01,1994-01-01 Date start_d_1 = simFormat.parse("1992-01-01 00:00:00"); // log.info("#12: countNumber:" + countNumber + ",size:" + OLAPTerminal.orderlineTableNotNullSize); if (countNumber >= OLAPTerminal.orderlineTableRecipDateNotNullSize.get()) { int s = (int) (((countNumber - this.b) / this.k) / 1000); // log.info("Q12-this.b" + this.b + ",this.k" + this.k); // log.info("Q12-1 s: " + s); return simFormat.format(super.getDateAfter(start_d, s)); } else { double historyNumber = OLAPTerminal.orderlineTableRecipDateNotNullSize.get() - countNumber; int s = (int) ((1 - historyNumber / OLAPTerminal.orderlineTableRecipDateNotNullSize.get()) * ((2405+OLTPClient.deltaDays2) * 24 * 60 * 60)); // log.info("Q12-2 s: " + s); return simFormat.format(super.getDateAfter(start_d_1, s)); } // OrderLine orderLine = ReservoirSamplingSingleton.getInstance().getOrderLine(filterRate); // System.out.println(orderLine); // return orderLine.getOl_receipdate().toString(); } @Override public String getQuery() throws ParseException { // this.dynamicParam = getDeltaTimes(); String query;
if (this.dbType == CommonConfig.DB_TIDB) {
4
2023-10-22 11:22:32+00:00
24k
bowbahdoe/java-audio-stack
vorbisspi/src/main/java/dev/mccue/vorbisspi/vorbis/sampled/convert/DecodedVorbisAudioInputStream.java
[ { "identifier": "PropertiesContainer", "path": "vorbisspi/src/main/java/dev/mccue/vorbisspi/PropertiesContainer.java", "snippet": "public interface PropertiesContainer\r\n{\r\n\tpublic Map properties();\r\n}\r" }, { "identifier": "TDebug", "path": "tritonus-share/src/main/java/dev/mccue/trit...
import dev.mccue.vorbisspi.PropertiesContainer; import dev.mccue.tritonus.share.TDebug; import dev.mccue.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream; import dev.mccue.jogg.Packet; import dev.mccue.jogg.Page; import dev.mccue.jogg.StreamState; import dev.mccue.jogg.SyncState; import dev.mccue.jorbis.Block; import dev.mccue.jorbis.Comment; import dev.mccue.jorbis.DspState; import dev.mccue.jorbis.Info; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream;
20,309
/* * DecodedVorbisAudioInputStream * * JavaZOOM : vorbisspi@javazoom.net * http://www.javazoom.net * * ---------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * ---------------------------------------------------------------------------- */ package dev.mccue.vorbisspi.vorbis.sampled.convert; /** * This class implements the Vorbis decoding. */ @SuppressWarnings("unchecked") public class DecodedVorbisAudioInputStream extends TAsynchronousFilteredAudioInputStream implements PropertiesContainer { private InputStream oggBitStream_ = null; private SyncState oggSyncState_ = null; private StreamState oggStreamState_ = null; private Page oggPage_ = null; private Packet oggPacket_ = null; private Info vorbisInfo = null;
/* * DecodedVorbisAudioInputStream * * JavaZOOM : vorbisspi@javazoom.net * http://www.javazoom.net * * ---------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * ---------------------------------------------------------------------------- */ package dev.mccue.vorbisspi.vorbis.sampled.convert; /** * This class implements the Vorbis decoding. */ @SuppressWarnings("unchecked") public class DecodedVorbisAudioInputStream extends TAsynchronousFilteredAudioInputStream implements PropertiesContainer { private InputStream oggBitStream_ = null; private SyncState oggSyncState_ = null; private StreamState oggStreamState_ = null; private Page oggPage_ = null; private Packet oggPacket_ = null; private Info vorbisInfo = null;
private Comment vorbisComment = null;
8
2023-10-19 14:09:37+00:00
24k
AstroDev2023/2023-studio-1-but-better
source/core/src/main/com/csse3200/game/components/player/InventoryComponent.java
[ { "identifier": "Component", "path": "source/core/src/main/com/csse3200/game/components/Component.java", "snippet": "public class Component implements Json.Serializable {\n\tprivate static final Logger logger = LoggerFactory.getLogger(Component.class);\n\tprotected Entity entity;\n\tprotected boolean en...
import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.csse3200.game.components.Component; import com.csse3200.game.components.items.ItemComponent; import com.csse3200.game.entities.Entity; import com.csse3200.game.entities.EntityType; import com.csse3200.game.missions.MissionManager; import com.csse3200.game.services.FactoryService; import com.csse3200.game.services.ServiceLocator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;
16,212
package com.csse3200.game.components.player; /** * A component intended to be used by the player to track their inventory. * Currently untested, but forms the basis for the UI which will be implemented soon:tm: */ public class InventoryComponent extends Component { /** * Logger for InventoryComponent */ private static final Logger logger = LoggerFactory.getLogger(InventoryComponent.class); /** * HashMap of the String and the count of the item in the inventory */ private HashMap<String, Integer> itemCount = new HashMap<>(); /** * HashMap of the String and Entity of the item in the inventory */ private HashMap<String, Entity> heldItemsEntity = new HashMap<>(); /** * HashMap of the Position and the String of the item in the inventory */ private HashMap<Integer, String> itemPlace = new HashMap<>(); /** * Entity representing the item currently held by the player. */ private Entity heldItem = null; /** * String representing the event that the inventory has been updated */ public static final String UPDATE_INVENTORY = "updateInventory"; /** * Integer representing the index of the item currently held by the player. */ private int heldIndex = -1; /** * The maximum size of the inventory. */ private int maxInventorySize = 30; // default size 30 private static final List<String> forbiddenItems = Arrays.asList("shovel", "hoe", "watering_can", "scythe", "sword", "gun", "Fishing Rod"); public static List<String> getForbiddenItems() { return forbiddenItems; } /** * Creates a new InventoryComponent with a given list of items. * * @param items List of Entities to be added to inventory */ public InventoryComponent(List<Entity> items) { setInventory(items); } /** * Creates a new InventoryComponent with a given maximum size. */ public InventoryComponent() { newInventory(); } /** * Sets the maximum size of the inventory. * * @param size The new maximum size of the inventory. * @return true if the size was set successfully, false otherwise. */ public boolean setInventorySize(int size) { if (size > 0) { this.maxInventorySize = size; return true; } else { return false; } } /** * Returns the maximum size of the inventory. * * @return The maximum size of the inventory. */ public int getInventorySize() { return this.maxInventorySize; } /** * Checks if the inventory is full. * Currently holding 30 types of Items * * @return true if the inventory is full, false otherwise. */ public boolean isFull() { return this.itemCount.size() >= this.maxInventorySize; } /** * Returns the HashMap of the String and the count of the item in the inventory * * @return HashMap of items and their count */ public HashMap<String, Integer> getItemCount() { return this.itemCount; } /** * Returns the HashMap of the Position and the String of the item in the inventory * * @return HashMap of itemPlace */ public HashMap<Integer, String> getItemPlace() { return this.itemPlace; } /** * Returns the HashMap of the String and Entity of the item in the inventory * Created only for use in ItemSlot at the moment * * @return HashMap of held items */ public HashMap<String, Entity> getHeldItemsEntity() { return this.heldItemsEntity; } /** * Sets the HashMap of the Position and the String of the item in the inventory * * @param itemPlace HashMap of itemPlace */ public void setItemPlace(HashMap<Integer, String> itemPlace) { this.itemPlace = itemPlace; } /** * Sets the HashMap of the String and the count of the item in the inventory * * @param allCount */ public void setItemCount(HashMap<String, Integer> allCount) { this.itemCount = allCount; } /** * Sets the HashMap of the String and Entity of the item in the inventory * * @param heldItemsEntity */ public void setHeldItemsEntity(HashMap<String, Entity> heldItemsEntity) { this.heldItemsEntity = heldItemsEntity; } /** * Returns the count of an item in the inventory * * @param item Passing the Item name of the item * @return integer representation of count */ public int getItemCount(String item) { return this.itemCount.getOrDefault(item, 0); } /** * Returns if the player has a certain item or not. * * @param item Entity to be checked * @return boolean representing if the item is on the character */ public Boolean hasItem(Entity item) { if (item.getType() != EntityType.ITEM) { logger.info("Passed Entity is not an item"); return false; }
package com.csse3200.game.components.player; /** * A component intended to be used by the player to track their inventory. * Currently untested, but forms the basis for the UI which will be implemented soon:tm: */ public class InventoryComponent extends Component { /** * Logger for InventoryComponent */ private static final Logger logger = LoggerFactory.getLogger(InventoryComponent.class); /** * HashMap of the String and the count of the item in the inventory */ private HashMap<String, Integer> itemCount = new HashMap<>(); /** * HashMap of the String and Entity of the item in the inventory */ private HashMap<String, Entity> heldItemsEntity = new HashMap<>(); /** * HashMap of the Position and the String of the item in the inventory */ private HashMap<Integer, String> itemPlace = new HashMap<>(); /** * Entity representing the item currently held by the player. */ private Entity heldItem = null; /** * String representing the event that the inventory has been updated */ public static final String UPDATE_INVENTORY = "updateInventory"; /** * Integer representing the index of the item currently held by the player. */ private int heldIndex = -1; /** * The maximum size of the inventory. */ private int maxInventorySize = 30; // default size 30 private static final List<String> forbiddenItems = Arrays.asList("shovel", "hoe", "watering_can", "scythe", "sword", "gun", "Fishing Rod"); public static List<String> getForbiddenItems() { return forbiddenItems; } /** * Creates a new InventoryComponent with a given list of items. * * @param items List of Entities to be added to inventory */ public InventoryComponent(List<Entity> items) { setInventory(items); } /** * Creates a new InventoryComponent with a given maximum size. */ public InventoryComponent() { newInventory(); } /** * Sets the maximum size of the inventory. * * @param size The new maximum size of the inventory. * @return true if the size was set successfully, false otherwise. */ public boolean setInventorySize(int size) { if (size > 0) { this.maxInventorySize = size; return true; } else { return false; } } /** * Returns the maximum size of the inventory. * * @return The maximum size of the inventory. */ public int getInventorySize() { return this.maxInventorySize; } /** * Checks if the inventory is full. * Currently holding 30 types of Items * * @return true if the inventory is full, false otherwise. */ public boolean isFull() { return this.itemCount.size() >= this.maxInventorySize; } /** * Returns the HashMap of the String and the count of the item in the inventory * * @return HashMap of items and their count */ public HashMap<String, Integer> getItemCount() { return this.itemCount; } /** * Returns the HashMap of the Position and the String of the item in the inventory * * @return HashMap of itemPlace */ public HashMap<Integer, String> getItemPlace() { return this.itemPlace; } /** * Returns the HashMap of the String and Entity of the item in the inventory * Created only for use in ItemSlot at the moment * * @return HashMap of held items */ public HashMap<String, Entity> getHeldItemsEntity() { return this.heldItemsEntity; } /** * Sets the HashMap of the Position and the String of the item in the inventory * * @param itemPlace HashMap of itemPlace */ public void setItemPlace(HashMap<Integer, String> itemPlace) { this.itemPlace = itemPlace; } /** * Sets the HashMap of the String and the count of the item in the inventory * * @param allCount */ public void setItemCount(HashMap<String, Integer> allCount) { this.itemCount = allCount; } /** * Sets the HashMap of the String and Entity of the item in the inventory * * @param heldItemsEntity */ public void setHeldItemsEntity(HashMap<String, Entity> heldItemsEntity) { this.heldItemsEntity = heldItemsEntity; } /** * Returns the count of an item in the inventory * * @param item Passing the Item name of the item * @return integer representation of count */ public int getItemCount(String item) { return this.itemCount.getOrDefault(item, 0); } /** * Returns if the player has a certain item or not. * * @param item Entity to be checked * @return boolean representing if the item is on the character */ public Boolean hasItem(Entity item) { if (item.getType() != EntityType.ITEM) { logger.info("Passed Entity is not an item"); return false; }
return this.itemCount.containsKey(item.getComponent(ItemComponent.class).getItemName());
1
2023-10-17 22:34:04+00:00
24k
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/controller/ProjectControllerExecution.java
[ { "identifier": "ErrorCode", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/exception/ErrorCode.java", "snippet": "public class ErrorCode {\n\tpublic static final String AUTH_TOKEN_NOT_FOUND = \"AUTH_TOKEN_NOT_FOUND\";\n\tpublic static final String AUTH_TOKEN_INVALID = \"AUTH_TOKEN_INVAL...
import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nl.rrd.senseeact.client.exception.ErrorCode; import nl.rrd.senseeact.client.exception.HttpError; import nl.rrd.senseeact.client.exception.HttpFieldError; import nl.rrd.senseeact.client.model.*; import nl.rrd.senseeact.client.model.compat.ProjectV1; import nl.rrd.senseeact.client.model.compat.ProjectV2; import nl.rrd.senseeact.client.model.compat.ProjectV3; import nl.rrd.senseeact.client.model.sample.LocalTimeSample; import nl.rrd.senseeact.client.model.sample.Sample; import nl.rrd.senseeact.client.model.sample.UTCSample; import nl.rrd.senseeact.client.project.BaseProject; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.*; import nl.rrd.senseeact.service.*; import nl.rrd.senseeact.service.controller.model.SelectFilterParser; import nl.rrd.senseeact.service.exception.BadRequestException; import nl.rrd.senseeact.service.exception.ForbiddenException; import nl.rrd.senseeact.service.exception.HttpException; import nl.rrd.senseeact.service.exception.NotFoundException; import nl.rrd.senseeact.service.model.User; import nl.rrd.senseeact.service.model.*; import nl.rrd.utils.AppComponents; import nl.rrd.utils.beans.PropertyReader; import nl.rrd.utils.beans.PropertyWriter; import nl.rrd.utils.exception.DatabaseException; import nl.rrd.utils.exception.ParseException; import nl.rrd.utils.json.JsonAtomicToken; import nl.rrd.utils.json.JsonMapper; import nl.rrd.utils.json.JsonObjectStreamReader; import nl.rrd.utils.json.JsonParseException; import nl.rrd.utils.validation.TypeConversion; import org.slf4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.util.*;
20,336
else compatUser = subjectUser.getEmail(); PropertyWriter.writeProperty(record, "user", compatUser); } } /** * Runs the query getRecord. * * @param version the protocol version * @param authDb the authentication database * @param db the project database or null * @param user the user who is currently logged in * @param project the project * @param table the name of the table * @param recordId the record ID * @param subject the user ID or email address of the subject or an empty * string or null * @throws HttpException if the request is invalid * @throws Exception if any other error occurs */ public Map<?,?> getRecord(ProtocolVersion version, Database authDb, Database db, User user, BaseProject project, String table, String recordId, String subject) throws HttpException, Exception { DatabaseTableDef<?> tableDef = project.findTable(table); if (tableDef == null) { throw new NotFoundException(String.format( "Table \"%s\" not found in project \"%s\"", table, project.getCode())); } DatabaseCache cache = DatabaseCache.getInstance(); List<String> fields = cache.getTableFields(db, table); if (!fields.contains("user")) { throw new ForbiddenException(String.format( "Table \"%s\" is not a user table", table)); } ProjectUserAccess userAccess = User.findAccessibleProjectUser( version, subject, project.getCode(), table, AccessMode.R, authDb, user); User subjectUser = userAccess.getUser(); DatabaseCriteria criteria = new DatabaseCriteria.And( new DatabaseCriteria.Equal("user", subjectUser.getUserid()), new DatabaseCriteria.Equal("id", recordId)); DatabaseObject record = db.selectOne(tableDef, criteria, null); if (record == null) { throw new NotFoundException(String.format( "Record with ID \"%s\" not found for project %s, table %s, user %s", recordId, project.getCode(), table, subjectUser.getUserid(version))); } userAccess.checkMatchesRange(record); DatabaseObjectMapper mapper = new DatabaseObjectMapper(); return mapper.objectToMap(record, true); } /** * Result of {@link * #getTableSelectCriteria(ProtocolVersion, Database, User, BaseProject, String, String, String, String, HttpServletRequest, List) * getTableSelectCriteria()}. */ private static class TableSelectCriteria { public DatabaseTableDef<?> tableDef; public DatabaseCriteria criteria; public DatabaseSort[] sort; public int limit; public User subjectUser; public TableSelectCriteria(DatabaseTableDef<?> tableDef, DatabaseCriteria criteria, DatabaseSort[] sort, int limit, User subjectUser) { this.tableDef = tableDef; this.criteria = criteria; this.sort = sort; this.limit = limit; this.subjectUser = subjectUser; } } /** * Returns a table definition and database criteria for a select or delete * query. The specified table, subject, start and end come from user input. * This method will validate them and throw an HttpException in case of * invalid input. * * @param authDb the authentication database * @param user the user who is currently logged in * @param project the project * @param table the table name * @param subject the user ID or email address of the subject or an empty * string or null * @param start the start time as an ISO date/time string, or the start date * as an SQL date string, or an empty string or null * @param end the end time as an ISO date/time string, or the end date as an * SQL date string, or an empty string or null * @param request if a select/delete query was called with a filter, this is * the request with the filter in the content. Otherwise it's null. * @param allowedContentParams the allowed parameters in the request body. * This should be a set of "filter", "sort" and "limit". * @return the table definition and database criteria * @throws HttpException if the request is invalid * @throws DatabaseException if a database error occurs * @throws IOException if an error occurs while reading the request content */ private static TableSelectCriteria getTableSelectCriteria( ProtocolVersion version, Database authDb, User user, BaseProject project, String table, String subject, String start, String end, HttpServletRequest request, List<String> allowedContentParams) throws HttpException, DatabaseException, IOException { DatabaseTableDef<?> tableDef = project.findTable(table); if (tableDef == null) { throw new NotFoundException(String.format( "Table \"%s\" not found in project \"%s\"", table, project.getCode())); } List<String> fields = DatabaseFieldScanner.getDatabaseFieldNames( tableDef.getDataClass()); boolean isUserTable = fields.contains("user"); boolean isTimeTable = Sample.class.isAssignableFrom( tableDef.getDataClass());
package nl.rrd.senseeact.service.controller; public class ProjectControllerExecution { private static final int BATCH_SIZE = 1000; public static final int HANGING_GET_TIMEOUT = 60000; /** * Runs the list query. * * @param version the protocol version * @param authDb the authentication database * @param user the user * @return the project codes * @throws DatabaseException if a database error occurs */ public List<?> list(ProtocolVersion version, Database authDb, User user) throws DatabaseException { List<BaseProject> projects = getUserProjects(authDb, user); if (version.ordinal() >= ProtocolVersion.V6_0_8.ordinal()) { List<Project> result = new ArrayList<>(); for (BaseProject baseProject : projects) { Project project = new Project(); project.setCode(baseProject.getCode()); project.setName(baseProject.getName()); result.add(project); } return result; } else if (version.ordinal() >= ProtocolVersion.V6_0_4.ordinal()) { List<ProjectV3> result = new ArrayList<>(); for (BaseProject baseProject : projects) { ProjectV3 project = new ProjectV3(); project.setCode(baseProject.getCode()); result.add(project); } return result; } else if (version.ordinal() >= ProtocolVersion.V5_0_5.ordinal()) { List<ProjectV2> result = new ArrayList<>(); for (BaseProject baseProject : projects) { ProjectV2 project = new ProjectV2(); project.setCode(baseProject.getCode()); if (version.ordinal() >= ProtocolVersion.V6_0_0.ordinal()) project.setSyncUser(user.getUserid()); else project.setSyncUser(user.getEmail()); project.setSyncGroup(null); result.add(project); } return result; } else if (version.ordinal() >= ProtocolVersion.V5_0_4.ordinal()) { List<ProjectV1> result = new ArrayList<>(); for (BaseProject baseProject : projects) { ProjectV1 project = new ProjectV1(); project.setCode(baseProject.getCode()); project.setSyncUser(user.getEmail()); result.add(project); } return result; } else { List<String> result = new ArrayList<>(); for (BaseProject project : projects) { result.add(project.getCode()); } return result; } } /** * Runs the list all query. * * @return the project codes */ public List<String> listAll() { List<String> result = new ArrayList<>(); ProjectRepository projectRepo = AppComponents.get( ProjectRepository.class); List<BaseProject> projects = projectRepo.getProjects(); for (BaseProject project : projects) { result.add(project.getCode()); } Collections.sort(result); return result; } /** * Runs the query checkProject. * * @param version the protocol version * @param authDb the authentication database * @param user the user who is accessing the project * @param subject the user ID or email address of the user that is accessed * @throws HttpException if the request is invalid * @throws DatabaseException if a database error occurs */ public Object checkProject(ProtocolVersion version, Database authDb, User user, String subject) throws HttpException, DatabaseException { if (subject != null && !subject.isEmpty()) User.findAccessibleUser(version, subject, authDb, user); return null; } /** * Returns the projects that the specified user can access. If the user is * an admin, that is all projects. Otherwise it checks the {@link * UserProjectTable UserProjectTable}. The projects will be sorted by code. * * @param authDb the authentication database * @param user the user * @return the projects * @throws DatabaseException if a database error occurs */ private static List<BaseProject> getUserProjects(Database authDb, User user) throws DatabaseException { List<String> projectCodes = user.findProjects(authDb); List<BaseProject> projects = new ArrayList<>(); ProjectRepository projectRepo = AppComponents.get( ProjectRepository.class); for (String code : projectCodes) { projects.add(projectRepo.findProjectByCode(code)); } return projects; } /** * Runs the query addUser. * * @param version the protocol version * @param authDb the authentication database * @param user the user who is logged in * @param projectCode the code of the project to which the user should be * added * @param subject the "user" parameter containing the user ID or email * address of the user to add. This is preferred to the "email" parameter. * @param compatEmail the "email" parameter containing the email address of * the user to add * @param asRole the role as which the user should be added to the project * @throws HttpException if the request is invalid * @throws Exception if any other error occurs */ public Object addUser(ProtocolVersion version, Database authDb, User user, String projectCode, String subject, String compatEmail, String asRole) throws HttpException, Exception { User userToAdd; if (compatEmail != null && !compatEmail.isEmpty()) { userToAdd = User.findAccessibleUserByEmail(compatEmail, authDb, user); } else { userToAdd = User.findAccessibleUser(version, subject, authDb, user); } BaseProject project; if (user.getUserid().equals(userToAdd.getUserid())) project = findProject(projectCode); else project = findUserProject(projectCode, authDb, user); Role asRoleEnum; try { asRoleEnum = TypeConversion.getEnum(asRole, Role.class); } catch (ParseException ex) { String msg = "Invalid role: " + asRole; HttpError error = new HttpError(ErrorCode.INVALID_INPUT, msg); error.addFieldError(new HttpFieldError("asRole", msg)); throw new BadRequestException(error); } int userRoleIndex = userToAdd.getRole().ordinal(); int asRoleIndex = asRoleEnum.ordinal(); if (asRoleIndex < userRoleIndex) { throw new ForbiddenException( "Can't add users to project as higher role than their own role"); } DatabaseCriteria criteria = new DatabaseCriteria.And( new DatabaseCriteria.Equal("user", userToAdd.getUserid()), new DatabaseCriteria.Equal("projectCode", project.getCode()), new DatabaseCriteria.Equal("asRole", asRoleEnum.toString())); UserProject userProject = authDb.selectOne(new UserProjectTable(), criteria, null); if (userProject != null) return null; userProject = new UserProject(); userProject.setUser(userToAdd.getUserid()); userProject.setProjectCode(project.getCode()); userProject.setAsRole(asRoleEnum); authDb.insert(UserProjectTable.NAME, userProject); UserListenerRepository.getInstance().notifyUserAddedToProject(userToAdd, projectCode, asRoleEnum); return null; } public Object removeUser(ProtocolVersion version, Database authDb, User user, String projectCode, String subject, String compatEmail, String asRole) throws HttpException, Exception { User removeUser; if (compatEmail != null && !compatEmail.isEmpty()) { removeUser = User.findAccessibleUserByEmail(compatEmail, authDb, user); } else { removeUser = User.findAccessibleUser(version, subject, authDb, user); } BaseProject project; if (user.getUserid().equals(removeUser.getUserid())) project = findProject(projectCode); else project = findUserProject(projectCode, authDb, user); Role asRoleEnum = null; if (asRole != null && !asRole.isEmpty()) { try { asRoleEnum = TypeConversion.getEnum(asRole, Role.class); } catch (ParseException ex) { String msg = "Invalid role: " + asRole; HttpError error = new HttpError(ErrorCode.INVALID_INPUT, msg); error.addFieldError(new HttpFieldError("asRole", msg)); throw new BadRequestException(error); } } DatabaseCriteria criteria = new DatabaseCriteria.And( new DatabaseCriteria.Equal("user", removeUser.getUserid()), new DatabaseCriteria.Equal("projectCode", project.getCode()) ); List<UserProject> userProjects = authDb.select( new UserProjectTable(), criteria, 0, null); List<Role> oldRoles = new ArrayList<>(); for (UserProject userProject : userProjects) { oldRoles.add(userProject.getAsRole()); } List<Role> removedRoles; if (asRoleEnum == null) removedRoles = oldRoles; else if (oldRoles.contains(asRoleEnum)) removedRoles = Collections.singletonList(asRoleEnum); else removedRoles = new ArrayList<>(); if (!removedRoles.isEmpty()) { List<DatabaseCriteria> andList = new ArrayList<>(); andList.add(new DatabaseCriteria.Equal("user", removeUser.getUserid())); andList.add(new DatabaseCriteria.Equal("projectCode", project.getCode())); if (asRoleEnum != null) { andList.add(new DatabaseCriteria.Equal("asRole", asRoleEnum.toString())); } criteria = new DatabaseCriteria.And(andList.toArray( new DatabaseCriteria[0])); authDb.delete(new UserProjectTable(), criteria); for (Role removedRole : removedRoles) { UserListenerRepository.getInstance() .notifyUserRemovedFromProject(removeUser, projectCode, removedRole); } } criteria = new DatabaseCriteria.And( new DatabaseCriteria.Equal("project", project.getCode()), new DatabaseCriteria.Equal("subject", removeUser.getUserid()) ); authDb.delete(new ProjectUserAccessTable(), criteria); criteria = new DatabaseCriteria.And( new DatabaseCriteria.Equal("user", removeUser.getUserid()), new DatabaseCriteria.Equal("project", project.getCode()) ); authDb.delete(new SyncPushRegistrationTable(), criteria); PushNotificationService pushService = AppComponents.get( PushNotificationService.class); pushService.removeUserProject(user.getUserid(), project.getCode()); return null; } public List<DatabaseObject> getUsers(ProtocolVersion version, Database authDb, User user, BaseProject project, String forUserid, String roleStr, String includeInactiveStr) throws HttpException, Exception { User forUser = User.findAccessibleUser(version, forUserid, authDb, user); if (!forUser.getUserid().equals(user.getUserid()) && user.getRole() != Role.ADMIN) { throw new ForbiddenException(); } List<HttpFieldError> fieldErrors = new ArrayList<>(); Role role = null; if (roleStr != null && !roleStr.isEmpty()) { try { role = TypeConversion.getEnum(roleStr, Role.class); } catch (ParseException ex) { fieldErrors.add(new HttpFieldError("role", "Invalid role: " + roleStr)); } } boolean includeInactive = false; try { includeInactive = TypeConversion.getBoolean(includeInactiveStr); } catch (ParseException ex) { fieldErrors.add(new HttpFieldError("includeInactive", ex.getMessage())); } if (!fieldErrors.isEmpty()) throw BadRequestException.withInvalidInput(fieldErrors); if (role != null && role.ordinal() < forUser.getRole().ordinal()) { throw new ForbiddenException(new HttpError(String.format( "Role %s is higher than role %s of requested user %s", role, forUser.getRole(), forUser.getUserid(version)))); } List<User> users = User.findProjectUsers(project.getCode(), authDb, forUser, role, includeInactive); return UserController.getCompatUserList(version, users); } public List<DatabaseObject> getSubjects(ProtocolVersion version, Database authDb, User user, BaseProject project, String forUserid, String includeInactiveStr) throws HttpException, Exception { User forUser = User.findAccessibleUser(version, forUserid, authDb, user); if (!forUser.getUserid().equals(user.getUserid()) && user.getRole() != Role.ADMIN) { throw new ForbiddenException(); } boolean includeInactive; try { includeInactive = TypeConversion.getBoolean(includeInactiveStr); } catch (ParseException ex) { throw BadRequestException.withInvalidInput( new HttpFieldError("includeInactive", ex.getMessage())); } List<User> subjects = User.findProjectUsers(project.getCode(), authDb, forUser, Role.PATIENT, includeInactive); return UserController.getCompatUserList(version, subjects); } /** * Runs the query registerWatchSubjects. * * @param authDb the authentication database * @param user the user who is currently logged in * @param project the project * @return the registration ID * @throws HttpException if the request is invalid * @throws DatabaseException if a database error occurs */ public String registerWatchSubjects(Database authDb, User user, BaseProject project, boolean reset) throws HttpException, DatabaseException { return WatchSubjectListener.addRegistration(authDb, user, project.getCode(), reset); } /** * Runs the query watchSubjects. * * @param request the HTTP request * @param response the HTTP response * @param versionName the protocol version * @param project the project code * @param id the registration ID * @throws HttpException if the request is invalid * @throws Exception if any other error occurs */ public void watchSubjects(final HttpServletRequest request, HttpServletResponse response, String versionName, String project, String id) throws HttpException, Exception { long queryStart = System.currentTimeMillis(); long queryEnd = queryStart + HANGING_GET_TIMEOUT; // verify authentication and input WatchSubjectListener listener = QueryRunner.runProjectQuery( (version, authDb, projectDb, user, baseProject) -> parseWatchSubjectInput(authDb, id, user, baseProject), versionName, project, request, response); // watch listener Object currentWatch = new Object(); final Object lock = listener.getLock(); synchronized (lock) { listener.setCurrentWatch(currentWatch); long now = System.currentTimeMillis(); while (now < queryEnd && listener.getCurrentWatch() == currentWatch && listener.getSubjectEvents().isEmpty()) { lock.wait(queryEnd - now); now = System.currentTimeMillis(); } List<SubjectEvent> events; if (listener.getCurrentWatch() == currentWatch) events = listener.getSubjectEvents(); else events = new ArrayList<>(); response.setContentType("application/json;charset=UTF-8"); try (Writer writer = new OutputStreamWriter( response.getOutputStream(), StandardCharsets.UTF_8)) { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(events); writer.write(json); writer.flush(); } listener.clearSubjectEvents(); } } /** * Runs the query unregisterWatchSubjects. * * @param authDb the authentication database * @param user the user who is currently logged in * @param project the project * @param regId the registration ID * @throws HttpException if the request is invalid * @throws DatabaseException if a database error occurs */ public Object unregisterWatchSubjects(Database authDb, User user, BaseProject project, String regId) throws HttpException, DatabaseException { WatchSubjectListener listener; try { listener = findWatchSubjectListener(regId, user, project); } catch (NotFoundException ex) { return null; } WatchSubjectListener.removeRegistration(authDb, listener); return null; } private WatchSubjectListener parseWatchSubjectInput(Database authDb, String regId, User user, BaseProject project) throws HttpException, DatabaseException { WatchSubjectListener listener = findWatchSubjectListener(regId, user, project); if (!WatchSubjectListener.setRegistrationWatchTime(authDb, listener.getRegistration())) { throw new NotFoundException(); } return listener; } private WatchSubjectListener findWatchSubjectListener(String regId, User user, BaseProject project) throws NotFoundException { WatchSubjectListener listener = WatchSubjectListener.findListener( regId); if (listener == null) throw new NotFoundException(); WatchSubjectRegistration reg = listener.getRegistration(); // check if registration properties correspond to parameters if (!reg.getUser().equals(user.getUserid())) throw new NotFoundException(); if (!reg.getProject().equals(project.getCode())) throw new NotFoundException(); return listener; } /** * Runs the query getTableList. * * @param project the project * @return the names of the database tables * @throws HttpException if the request is invalid * @throws Exception if any other error occurs */ public List<String> getTableList(BaseProject project) throws HttpException, Exception { return project.getDatabaseTableNames(); } /** * Runs the query getTableSpec. * * @param project the project * @param table the table name * @return the table specification * @throws HttpException if the request is invalid * @throws Exception if any other error occurs */ public TableSpec getTableSpec(BaseProject project, String table) throws HttpException, Exception { DatabaseTableDef<?> tableDef = project.findTable(table); if (tableDef == null) { throw new NotFoundException(String.format( "Table \"%s\" not found in project \"%s\"", table, project.getCode())); } return TableSpec.fromDatabaseTableDef(tableDef); } /** * Runs the query getRecords or getRecordsWithFilter. * * @param authDb the authentication database * @param db the project database or null * @param user the user who is currently logged in * @param project the project * @param table the name of the table * @param subject the user ID or email address of the subject or an empty * string or null * @param start the start time or an empty string or null * @param end the end time or an empty string or null * @param request if getRecordsWithFilter was called, this is the request * with the filter in the content. Otherwise it's null. * @param response the HTTP response to which the records should be written * @throws HttpException if the request is invalid * @throws Exception if any other error occurs */ public Object getRecords(ProtocolVersion version, Database authDb, Database db, User user, BaseProject project, String table, String subject, String start, String end, HttpServletRequest request, HttpServletResponse response) throws HttpException, Exception { List<? extends DatabaseObject> records = getRecords(version, authDb, db, user, project, table, subject, start, end, request); response.setContentType("application/json"); try (Writer writer = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) { writer.write("["); DatabaseObjectMapper dbMapper = new DatabaseObjectMapper(); ObjectMapper jsonMapper = new ObjectMapper(); boolean first = true; for (DatabaseObject record : records) { if (!first) writer.write(","); else first = false; Map<String,Object> map = dbMapper.objectToMap(record, true); String json = jsonMapper.writeValueAsString(map); writer.write(json); } writer.write("]"); } return null; } public static List<? extends DatabaseObject> getRecords( ProtocolVersion version, Database authDb, Database db, User user, BaseProject project, String table, String subject, String start, String end, HttpServletRequest request) throws HttpException, Exception { TableSelectCriteria tableCriteria = getTableSelectCriteria(version, authDb, user, project, table, subject, start, end, request, Arrays.asList("filter", "sort", "limit")); // TODO stream to response, add Database.selectCursor() List<? extends DatabaseObject> result = db.select( tableCriteria.tableDef, tableCriteria.criteria, tableCriteria.limit, tableCriteria.sort); setCompatUser(version, subject, tableCriteria.subjectUser, result); return result; } private static void setCompatUser(ProtocolVersion version, String subjectName, User subjectUser, List<? extends DatabaseObject> records) { if (version.ordinal() >= ProtocolVersion.V6_0_0.ordinal()) return; for (DatabaseObject record : records) { List<String> fields = DatabaseFieldScanner.getDatabaseFieldNames( record.getClass()); if (!fields.contains("user")) return; String compatUser; if (subjectUser.getUserid().contains("@")) compatUser = subjectUser.getUserid(); else if (subjectName != null && !subjectName.isEmpty()) compatUser = subjectName; else compatUser = subjectUser.getEmail(); PropertyWriter.writeProperty(record, "user", compatUser); } } /** * Runs the query getRecord. * * @param version the protocol version * @param authDb the authentication database * @param db the project database or null * @param user the user who is currently logged in * @param project the project * @param table the name of the table * @param recordId the record ID * @param subject the user ID or email address of the subject or an empty * string or null * @throws HttpException if the request is invalid * @throws Exception if any other error occurs */ public Map<?,?> getRecord(ProtocolVersion version, Database authDb, Database db, User user, BaseProject project, String table, String recordId, String subject) throws HttpException, Exception { DatabaseTableDef<?> tableDef = project.findTable(table); if (tableDef == null) { throw new NotFoundException(String.format( "Table \"%s\" not found in project \"%s\"", table, project.getCode())); } DatabaseCache cache = DatabaseCache.getInstance(); List<String> fields = cache.getTableFields(db, table); if (!fields.contains("user")) { throw new ForbiddenException(String.format( "Table \"%s\" is not a user table", table)); } ProjectUserAccess userAccess = User.findAccessibleProjectUser( version, subject, project.getCode(), table, AccessMode.R, authDb, user); User subjectUser = userAccess.getUser(); DatabaseCriteria criteria = new DatabaseCriteria.And( new DatabaseCriteria.Equal("user", subjectUser.getUserid()), new DatabaseCriteria.Equal("id", recordId)); DatabaseObject record = db.selectOne(tableDef, criteria, null); if (record == null) { throw new NotFoundException(String.format( "Record with ID \"%s\" not found for project %s, table %s, user %s", recordId, project.getCode(), table, subjectUser.getUserid(version))); } userAccess.checkMatchesRange(record); DatabaseObjectMapper mapper = new DatabaseObjectMapper(); return mapper.objectToMap(record, true); } /** * Result of {@link * #getTableSelectCriteria(ProtocolVersion, Database, User, BaseProject, String, String, String, String, HttpServletRequest, List) * getTableSelectCriteria()}. */ private static class TableSelectCriteria { public DatabaseTableDef<?> tableDef; public DatabaseCriteria criteria; public DatabaseSort[] sort; public int limit; public User subjectUser; public TableSelectCriteria(DatabaseTableDef<?> tableDef, DatabaseCriteria criteria, DatabaseSort[] sort, int limit, User subjectUser) { this.tableDef = tableDef; this.criteria = criteria; this.sort = sort; this.limit = limit; this.subjectUser = subjectUser; } } /** * Returns a table definition and database criteria for a select or delete * query. The specified table, subject, start and end come from user input. * This method will validate them and throw an HttpException in case of * invalid input. * * @param authDb the authentication database * @param user the user who is currently logged in * @param project the project * @param table the table name * @param subject the user ID or email address of the subject or an empty * string or null * @param start the start time as an ISO date/time string, or the start date * as an SQL date string, or an empty string or null * @param end the end time as an ISO date/time string, or the end date as an * SQL date string, or an empty string or null * @param request if a select/delete query was called with a filter, this is * the request with the filter in the content. Otherwise it's null. * @param allowedContentParams the allowed parameters in the request body. * This should be a set of "filter", "sort" and "limit". * @return the table definition and database criteria * @throws HttpException if the request is invalid * @throws DatabaseException if a database error occurs * @throws IOException if an error occurs while reading the request content */ private static TableSelectCriteria getTableSelectCriteria( ProtocolVersion version, Database authDb, User user, BaseProject project, String table, String subject, String start, String end, HttpServletRequest request, List<String> allowedContentParams) throws HttpException, DatabaseException, IOException { DatabaseTableDef<?> tableDef = project.findTable(table); if (tableDef == null) { throw new NotFoundException(String.format( "Table \"%s\" not found in project \"%s\"", table, project.getCode())); } List<String> fields = DatabaseFieldScanner.getDatabaseFieldNames( tableDef.getDataClass()); boolean isUserTable = fields.contains("user"); boolean isTimeTable = Sample.class.isAssignableFrom( tableDef.getDataClass());
boolean isUtcTable = UTCSample.class.isAssignableFrom(
8
2023-10-24 09:36:50+00:00
24k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/cases/casemove/CaseOnTreatMoveService.java
[ { "identifier": "DateUtils", "path": "src/main/java/org/msh/etbm/commons/date/DateUtils.java", "snippet": "public class DateUtils {\n\n /**\n * Private method to avoid creation of instances of this class\n */\n private DateUtils() {\n super();\n }\n\n /**\n * Return the nu...
import org.msh.etbm.commons.date.DateUtils; import org.msh.etbm.commons.date.Period; import org.msh.etbm.commons.entities.EntityValidationException; import org.msh.etbm.db.entities.PrescribedMedicine; import org.msh.etbm.db.entities.TbCase; import org.msh.etbm.db.entities.Tbunit; import org.msh.etbm.db.entities.TreatmentHealthUnit; import org.msh.etbm.db.enums.CaseState; import org.msh.etbm.services.cases.CaseActionEvent; import org.msh.etbm.services.session.usersession.UserRequestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID;
16,794
package org.msh.etbm.services.cases.casemove; /** * Created by Mauricio on 14/09/2016. */ @Service public class CaseOnTreatMoveService { @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired ApplicationContext applicationContext; /** * Execute the transfer of an on treat case to another health unit */ @Transactional public CaseMoveResponse transferOut(CaseMoveRequest req) { TbCase tbcase = entityManager.find(TbCase.class, req.getTbcaseId()); Tbunit unitTo = entityManager.find(Tbunit.class, req.getUnitToId()); Date moveDate = req.getMoveDate(); // get the current treatment unit TreatmentHealthUnit currentTreatUnit = findTransferOutTreatUnit(tbcase); if (currentTreatUnit == null) { throw new EntityNotFoundException(); } // check state if (!tbcase.getState().equals(CaseState.ONTREATMENT)) { throw new EntityValidationException(tbcase, "state", "Case state should be On Treatment", null); } // checks if date is before beginning treatment date if (!currentTreatUnit.getPeriod().isDateInside(moveDate)) { throw new EntityValidationException(req, "moveDate", null, "cases.move.errortreatdate"); } // checks if units are different if (currentTreatUnit.getTbunit().equals(unitTo)) { throw new EntityValidationException(req, "unitTo", null, "cases.move.errorunit"); } // create the period of treatment for the new health unit
package org.msh.etbm.services.cases.casemove; /** * Created by Mauricio on 14/09/2016. */ @Service public class CaseOnTreatMoveService { @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired ApplicationContext applicationContext; /** * Execute the transfer of an on treat case to another health unit */ @Transactional public CaseMoveResponse transferOut(CaseMoveRequest req) { TbCase tbcase = entityManager.find(TbCase.class, req.getTbcaseId()); Tbunit unitTo = entityManager.find(Tbunit.class, req.getUnitToId()); Date moveDate = req.getMoveDate(); // get the current treatment unit TreatmentHealthUnit currentTreatUnit = findTransferOutTreatUnit(tbcase); if (currentTreatUnit == null) { throw new EntityNotFoundException(); } // check state if (!tbcase.getState().equals(CaseState.ONTREATMENT)) { throw new EntityValidationException(tbcase, "state", "Case state should be On Treatment", null); } // checks if date is before beginning treatment date if (!currentTreatUnit.getPeriod().isDateInside(moveDate)) { throw new EntityValidationException(req, "moveDate", null, "cases.move.errortreatdate"); } // checks if units are different if (currentTreatUnit.getTbunit().equals(unitTo)) { throw new EntityValidationException(req, "unitTo", null, "cases.move.errorunit"); } // create the period of treatment for the new health unit
Period newPeriod = new Period(DateUtils.incDays(moveDate, 1), tbcase.getTreatmentPeriod().getEndDate());
1
2023-10-23 13:47:54+00:00
24k
toel--/ocpp-backend-emulator
src/org/java_websocket/server/WebSocketServer.java
[ { "identifier": "AbstractWebSocket", "path": "src/org/java_websocket/AbstractWebSocket.java", "snippet": "public abstract class AbstractWebSocket extends WebSocketAdapter {\n\n /**\n * Logger instance\n *\n * @since 1.4.0\n */\n private final Logger log = LoggerFactory.getLogger(AbstractWebSoc...
import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.java_websocket.AbstractWebSocket; import org.java_websocket.SocketChannelIOHelper; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketFactory; import org.java_websocket.WebSocketImpl; import org.java_websocket.WebSocketServerFactory; import org.java_websocket.WrappedByteChannel; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.WebsocketNotConnectedException; import org.java_websocket.exceptions.WrappedIOException; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
21,599
} } public void stop() throws InterruptedException { stop(0); } /** * Returns all currently connected clients. This collection does not allow any modification e.g. * removing a client. * * @return A unmodifiable collection of all currently connected clients * @since 1.3.8 */ @Override public Collection<WebSocket> getConnections() { synchronized (connections) { return Collections.unmodifiableCollection(new ArrayList<>(connections)); } } public InetSocketAddress getAddress() { return this.address; } /** * Gets the port number that this server listens on. * * @return The port number. */ public int getPort() { int port = getAddress().getPort(); if (port == 0 && server != null) { port = server.socket().getLocalPort(); } return port; } /** * Get the list of active drafts * * @return the available drafts for this server */ public List<Draft> getDraft() { return Collections.unmodifiableList(drafts); } /** * Set the requested maximum number of pending connections on the socket. The exact semantics are * implementation specific. The value provided should be greater than 0. If it is less than or * equal to 0, then an implementation specific default will be used. This option will be passed as * "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} * * @since 1.5.0 * @param numberOfConnections the new number of allowed pending connections */ public void setMaxPendingConnections(int numberOfConnections) { maxPendingConnections = numberOfConnections; } /** * Returns the currently configured maximum number of pending connections. * * @see #setMaxPendingConnections(int) * @since 1.5.0 * @return the maximum number of pending connections */ public int getMaxPendingConnections() { return maxPendingConnections; } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { if (!doEnsureSingleThread()) { return; } if (!doSetupSelectorAndServerThread()) { return; } try { int shutdownCount = 5; int selectTimeout = 0; while (!selectorthread.isInterrupted() && shutdownCount != 0) { SelectionKey key = null; try { if (isclosed.get()) { selectTimeout = 5; } int keyCount = selector.select(selectTimeout); if (keyCount == 0 && isclosed.get()) { shutdownCount--; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { key = i.next(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { doAccept(key, i); continue; } if (key.isReadable() && !doRead(key, i)) { continue; } if (key.isWritable()) { doWrite(key); } } doAdditionalRead(); } catch (CancelledKeyException e) { // an other thread may cancel the key } catch (ClosedByInterruptException e) { return; // do the same stuff as when InterruptedException is thrown
/* * Copyright (c) 2010-2020 Nathan Rajlich * * 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 org.java_websocket.server; /** * <tt>WebSocketServer</tt> is an abstract class that only takes care of the * HTTP handshake portion of WebSockets. It's up to a subclass to add functionality/purpose to the * server. */ public abstract class WebSocketServer extends AbstractWebSocket implements Runnable { private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); /** * Logger instance * * @since 1.4.0 */ private final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * Holds the list of active WebSocket connections. "Active" means WebSocket handshake is complete * and socket can be written to, or read from. */ private final Collection<WebSocket> connections; /** * The port number that this WebSocket server should listen on. Default is * WebSocketImpl.DEFAULT_PORT. */ private final InetSocketAddress address; /** * The socket channel for this WebSocket server. */ private ServerSocketChannel server; /** * The 'Selector' used to get event keys from the underlying socket. */ private Selector selector; /** * The Draft of the WebSocket protocol the Server is adhering to. */ private List<Draft> drafts; private Thread selectorthread; private final AtomicBoolean isclosed = new AtomicBoolean(false); protected List<WebSocketWorker> decoders; private List<WebSocketImpl> iqueue; private BlockingQueue<ByteBuffer> buffers; private int queueinvokes = 0; private final AtomicInteger queuesize = new AtomicInteger(0); private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory(); /** * Attribute which allows you to configure the socket "backlog" parameter which determines how * many client connections can be queued. * * @since 1.5.0 */ private int maxPendingConnections = -1; /** * Creates a WebSocketServer that will attempt to listen on port <var>WebSocketImpl.DEFAULT_PORT</var>. * * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer() { this(new InetSocketAddress(WebSocketImpl.DEFAULT_PORT), AVAILABLE_PROCESSORS, null); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>. * * @param address The address to listen to * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address) { this(address, AVAILABLE_PROCESSORS, null); } /** * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code> * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, int decodercount) { this(address, decodercount, null); } /** * @param address The address (host:port) this server should listen on. * @param drafts The versions of the WebSocket protocol that this server instance should comply * to. Clients that use an other protocol version will be rejected. * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, List<Draft> drafts) { this(address, AVAILABLE_PROCESSORS, drafts); } /** * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process the * incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code> * @param drafts The versions of the WebSocket protocol that this server instance should * comply to. Clients that use an other protocol version will be rejected. * @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here */ public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts) { this(address, decodercount, drafts, new HashSet<WebSocket>()); } /** * Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>, and * comply with <tt>Draft</tt> version <var>draft</var>. * * @param address The address (host:port) this server should listen on. * @param decodercount The number of {@link WebSocketWorker}s that will be used to process * the incoming network data. By default this will be * <code>Runtime.getRuntime().availableProcessors()</code> * @param drafts The versions of the WebSocket protocol that this server instance * should comply to. Clients that use an other protocol version will * be rejected. * @param connectionscontainer Allows to specify a collection that will be used to store the * websockets in. <br> If you plan to often iterate through the * currently connected websockets you may want to use a collection * that does not require synchronization like a {@link * CopyOnWriteArraySet}. In that case make sure that you overload * {@link #removeConnection(WebSocket)} and {@link * #addConnection(WebSocket)}.<br> By default a {@link HashSet} will * be used. * @see #removeConnection(WebSocket) for more control over syncronized operation * @see <a href="https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts" > more about * drafts</a> */ public WebSocketServer(InetSocketAddress address, int decodercount, List<Draft> drafts, Collection<WebSocket> connectionscontainer) { if (address == null || decodercount < 1 || connectionscontainer == null) { throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder"); } if (drafts == null) { this.drafts = Collections.emptyList(); } else { this.drafts = drafts; } this.address = address; this.connections = connectionscontainer; setTcpNoDelay(false); setReuseAddr(false); iqueue = new LinkedList<>(); decoders = new ArrayList<>(decodercount); buffers = new LinkedBlockingQueue<>(); for (int i = 0; i < decodercount; i++) { WebSocketWorker ex = new WebSocketWorker(); decoders.add(ex); } } /** * Starts the server selectorthread that binds to the currently set port number and listeners for * WebSocket connection requests. Creates a fixed thread pool with the size {@link * WebSocketServer#AVAILABLE_PROCESSORS}<br> May only be called once. * <p> * Alternatively you can call {@link WebSocketServer#run()} directly. * * @throws IllegalStateException Starting an instance again */ public void start() { if (selectorthread != null) { throw new IllegalStateException(getClass().getName() + " can only be started once."); } new Thread(this).start(); } public void stop(int timeout) throws InterruptedException { stop(timeout, ""); } /** * Closes all connected clients sockets, then closes the underlying ServerSocketChannel, * effectively killing the server socket selectorthread, freeing the port the server was bound to * and stops all internal workerthreads. * <p> * If this method is called before the server is started it will never start. * * @param timeout Specifies how many milliseconds the overall close handshaking may take * altogether before the connections are closed without proper close * handshaking. * @param closeMessage Specifies message for remote client<br> * @throws InterruptedException Interrupt */ public void stop(int timeout, String closeMessage) throws InterruptedException { if (!isclosed.compareAndSet(false, true)) { // this also makes sure that no further connections will be added to this.connections return; } List<WebSocket> socketsToClose; // copy the connections in a list (prevent callback deadlocks) synchronized (connections) { socketsToClose = new ArrayList<>(connections); } for (WebSocket ws : socketsToClose) { ws.close(CloseFrame.GOING_AWAY, closeMessage); } wsf.close(); synchronized (this) { if (selectorthread != null && selector != null) { selector.wakeup(); selectorthread.join(timeout); } } } public void stop() throws InterruptedException { stop(0); } /** * Returns all currently connected clients. This collection does not allow any modification e.g. * removing a client. * * @return A unmodifiable collection of all currently connected clients * @since 1.3.8 */ @Override public Collection<WebSocket> getConnections() { synchronized (connections) { return Collections.unmodifiableCollection(new ArrayList<>(connections)); } } public InetSocketAddress getAddress() { return this.address; } /** * Gets the port number that this server listens on. * * @return The port number. */ public int getPort() { int port = getAddress().getPort(); if (port == 0 && server != null) { port = server.socket().getLocalPort(); } return port; } /** * Get the list of active drafts * * @return the available drafts for this server */ public List<Draft> getDraft() { return Collections.unmodifiableList(drafts); } /** * Set the requested maximum number of pending connections on the socket. The exact semantics are * implementation specific. The value provided should be greater than 0. If it is less than or * equal to 0, then an implementation specific default will be used. This option will be passed as * "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)} * * @since 1.5.0 * @param numberOfConnections the new number of allowed pending connections */ public void setMaxPendingConnections(int numberOfConnections) { maxPendingConnections = numberOfConnections; } /** * Returns the currently configured maximum number of pending connections. * * @see #setMaxPendingConnections(int) * @since 1.5.0 * @return the maximum number of pending connections */ public int getMaxPendingConnections() { return maxPendingConnections; } // Runnable IMPLEMENTATION ///////////////////////////////////////////////// public void run() { if (!doEnsureSingleThread()) { return; } if (!doSetupSelectorAndServerThread()) { return; } try { int shutdownCount = 5; int selectTimeout = 0; while (!selectorthread.isInterrupted() && shutdownCount != 0) { SelectionKey key = null; try { if (isclosed.get()) { selectTimeout = 5; } int keyCount = selector.select(selectTimeout); if (keyCount == 0 && isclosed.get()) { shutdownCount--; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while (i.hasNext()) { key = i.next(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { doAccept(key, i); continue; } if (key.isReadable() && !doRead(key, i)) { continue; } if (key.isWritable()) { doWrite(key); } } doAdditionalRead(); } catch (CancelledKeyException e) { // an other thread may cancel the key } catch (ClosedByInterruptException e) { return; // do the same stuff as when InterruptedException is thrown
} catch (WrappedIOException ex) {
9
2023-10-16 23:10:55+00:00
24k
weibocom/rill-flow
rill-flow-dag/olympicene-spring-boot-starter/src/main/java/com/weibo/rill/flow/olympicene/spring/boot/OlympiceneAutoConfiguration.java
[ { "identifier": "Callback", "path": "rill-flow-dag/olympicene-core/src/main/java/com/weibo/rill/flow/olympicene/core/event/Callback.java", "snippet": "public interface Callback<T> {\n\n void onEvent(Event<T> event);\n}" }, { "identifier": "TaskCategory", "path": "rill-flow-dag/olympicene-...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.weibo.rill.flow.olympicene.core.event.Callback; import com.weibo.rill.flow.olympicene.core.model.task.TaskCategory; import com.weibo.rill.flow.olympicene.core.result.DAGResultHandler; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.olympicene.ddl.parser.DAGStringParser; import com.weibo.rill.flow.olympicene.ddl.serialize.YAMLSerializer; import com.weibo.rill.flow.olympicene.ddl.validation.dag.impl.FlowDAGValidator; import com.weibo.rill.flow.olympicene.ddl.validation.dag.impl.ResourceDAGValidator; import com.weibo.rill.flow.olympicene.spring.boot.exception.OlympicenceStarterException; import com.weibo.rill.flow.olympicene.traversal.DAGOperations; import com.weibo.rill.flow.olympicene.traversal.DAGTraversal; import com.weibo.rill.flow.olympicene.traversal.Olympicene; import com.weibo.rill.flow.olympicene.traversal.callback.DAGCallbackInfo; import com.weibo.rill.flow.olympicene.traversal.checker.DefaultTimeChecker; import com.weibo.rill.flow.olympicene.traversal.checker.TimeChecker; import com.weibo.rill.flow.olympicene.traversal.dispatcher.DAGDispatcher; import com.weibo.rill.flow.olympicene.traversal.helper.*; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPathInputOutputMapping; import com.weibo.rill.flow.olympicene.traversal.runners.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureOrder; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; import java.util.concurrent.ExecutorService;
14,961
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.spring.boot; @Slf4j @Configuration @AutoConfigureOrder(Integer.MIN_VALUE) public class OlympiceneAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "dagInfoStorage") public DAGInfoStorage dagInfoStorage() { throw new OlympicenceStarterException("need customized DAGInfoStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagContextStorage") public DAGContextStorage dagContextStorage() { throw new OlympicenceStarterException("need customized DAGContextStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagStorageProcedure") public DAGStorageProcedure dagStorageProcedure() { throw new OlympicenceStarterException("need customized DAGStorageProcedure type bean"); } @Bean @ConditionalOnMissingBean(name = "dagCallback")
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.spring.boot; @Slf4j @Configuration @AutoConfigureOrder(Integer.MIN_VALUE) public class OlympiceneAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "dagInfoStorage") public DAGInfoStorage dagInfoStorage() { throw new OlympicenceStarterException("need customized DAGInfoStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagContextStorage") public DAGContextStorage dagContextStorage() { throw new OlympicenceStarterException("need customized DAGContextStorage type bean"); } @Bean @ConditionalOnMissingBean(name = "dagStorageProcedure") public DAGStorageProcedure dagStorageProcedure() { throw new OlympicenceStarterException("need customized DAGStorageProcedure type bean"); } @Bean @ConditionalOnMissingBean(name = "dagCallback")
public Callback<DAGCallbackInfo> dagCallback() {
0
2023-11-03 03:46:01+00:00
24k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/home/HomeFragment.java
[ { "identifier": "ClassAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/group/ClassAdapter.java", "snippet": "public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {\n private final Context context;\n private final ArrayList<Group> classes;\n\n pub...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.daominh.quickmem.adapter.group.ClassAdapter; import com.daominh.quickmem.adapter.folder.FolderAdapter; import com.daominh.quickmem.adapter.flashcard.SetsAdapter; import com.daominh.quickmem.data.dao.FlashCardDAO; import com.daominh.quickmem.data.dao.FolderDAO; import com.daominh.quickmem.data.dao.GroupDAO; import com.daominh.quickmem.data.model.FlashCard; import com.daominh.quickmem.data.model.Folder; import com.daominh.quickmem.data.model.Group; import com.daominh.quickmem.databinding.FragmentHomeBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateSetActivity; import com.daominh.quickmem.ui.activities.search.ViewSearchActivity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
14,708
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter; private ArrayList<FlashCard> flashCards; private ArrayList<Folder> folders; private ArrayList<Group> classes; private FlashCardDAO flashCardDAO; private FolderDAO folderDAO; private GroupDAO groupDAO; private String idUser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); flashCardDAO = new FlashCardDAO(requireActivity()); folderDAO = new FolderDAO(requireActivity()); groupDAO = new GroupDAO(requireActivity()); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); setupFlashCards(); setupFolders(); setupClasses(); setupVisibility(); setupSwipeRefreshLayout(); setupSearchBar(); setupCreateSetsButton(); binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); Toast.makeText(requireActivity(), "Refreshed", Toast.LENGTH_SHORT).show(); }); } @SuppressLint("NotifyDataSetChanged") private void setupFlashCards() { flashCards = flashCardDAO.getAllFlashCardByUserId(idUser); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.setsRv.setLayoutManager(linearLayoutManager); setsAdapter = new SetsAdapter(requireActivity(), flashCards, false); binding.setsRv.setAdapter(setsAdapter); setsAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupFolders() { folders = folderDAO.getAllFolderByUserId(idUser); folderAdapter = new FolderAdapter(requireActivity(), folders); LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.foldersRv.setLayoutManager(linearLayoutManager1); binding.foldersRv.setAdapter(folderAdapter); folderAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupClasses() { classes = groupDAO.getClassesOwnedByUser(idUser); classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser)); classAdapter = new ClassAdapter(requireActivity(), classes); LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.classesRv.setLayoutManager(linearLayoutManager2); binding.classesRv.setAdapter(classAdapter); classAdapter.notifyDataSetChanged(); } private void setupVisibility() { if (flashCards.isEmpty()) { binding.setsCl.setVisibility(View.GONE); } else { binding.setsCl.setVisibility(View.VISIBLE); } if (folders.isEmpty()) { binding.folderCl.setVisibility(View.GONE); } else { binding.folderCl.setVisibility(View.VISIBLE); } if (classes.isEmpty()) { binding.classCl.setVisibility(View.GONE); } else { binding.classCl.setVisibility(View.VISIBLE); } } private void setupSwipeRefreshLayout() { binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); }); } private void setupSearchBar() { binding.searchBar.setOnClickListener(v -> {
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter; private ArrayList<FlashCard> flashCards; private ArrayList<Folder> folders; private ArrayList<Group> classes; private FlashCardDAO flashCardDAO; private FolderDAO folderDAO; private GroupDAO groupDAO; private String idUser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); flashCardDAO = new FlashCardDAO(requireActivity()); folderDAO = new FolderDAO(requireActivity()); groupDAO = new GroupDAO(requireActivity()); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); setupFlashCards(); setupFolders(); setupClasses(); setupVisibility(); setupSwipeRefreshLayout(); setupSearchBar(); setupCreateSetsButton(); binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); Toast.makeText(requireActivity(), "Refreshed", Toast.LENGTH_SHORT).show(); }); } @SuppressLint("NotifyDataSetChanged") private void setupFlashCards() { flashCards = flashCardDAO.getAllFlashCardByUserId(idUser); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.setsRv.setLayoutManager(linearLayoutManager); setsAdapter = new SetsAdapter(requireActivity(), flashCards, false); binding.setsRv.setAdapter(setsAdapter); setsAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupFolders() { folders = folderDAO.getAllFolderByUserId(idUser); folderAdapter = new FolderAdapter(requireActivity(), folders); LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.foldersRv.setLayoutManager(linearLayoutManager1); binding.foldersRv.setAdapter(folderAdapter); folderAdapter.notifyDataSetChanged(); } @SuppressLint("NotifyDataSetChanged") private void setupClasses() { classes = groupDAO.getClassesOwnedByUser(idUser); classes.addAll(groupDAO.getClassesUserIsMemberOf(idUser)); classAdapter = new ClassAdapter(requireActivity(), classes); LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false); binding.classesRv.setLayoutManager(linearLayoutManager2); binding.classesRv.setAdapter(classAdapter); classAdapter.notifyDataSetChanged(); } private void setupVisibility() { if (flashCards.isEmpty()) { binding.setsCl.setVisibility(View.GONE); } else { binding.setsCl.setVisibility(View.VISIBLE); } if (folders.isEmpty()) { binding.folderCl.setVisibility(View.GONE); } else { binding.folderCl.setVisibility(View.VISIBLE); } if (classes.isEmpty()) { binding.classCl.setVisibility(View.GONE); } else { binding.classCl.setVisibility(View.VISIBLE); } } private void setupSwipeRefreshLayout() { binding.swipeRefreshLayout.setOnRefreshListener(() -> { refreshData(); binding.swipeRefreshLayout.setRefreshing(false); }); } private void setupSearchBar() { binding.searchBar.setOnClickListener(v -> {
Intent intent = new Intent(requireActivity(), ViewSearchActivity.class);
11
2023-11-07 16:56:39+00:00
24k
dlsc-software-consulting-gmbh/PhoneNumberFX
phonenumberfx-demo/src/main/java/com/dlsc/phonenumberfx/demo/PhoneNumberFieldSamples.java
[ { "identifier": "PhoneNumberField", "path": "phonenumberfx/src/main/java/com/dlsc/phonenumberfx/PhoneNumberField.java", "snippet": "public class PhoneNumberField extends CustomTextField {\n\n private static final Map<Country, Image> FLAG_IMAGES = new HashMap<>();\n\n static {\n for (Country...
import com.dlsc.phonenumberfx.PhoneNumberField; import com.dlsc.phonenumberfx.PhoneNumberField.Country; import com.dlsc.phonenumberfx.PhoneNumberLabel; import com.google.i18n.phonenumbers.PhoneNumberUtil; import javafx.beans.binding.Bindings; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import java.util.function.Function;
18,570
package com.dlsc.phonenumberfx.demo; public final class PhoneNumberFieldSamples { private static final Function<Object, String> COUNTRY_CODE_CONVERTER = c -> { if (c == null) { return null; }
package com.dlsc.phonenumberfx.demo; public final class PhoneNumberFieldSamples { private static final Function<Object, String> COUNTRY_CODE_CONVERTER = c -> { if (c == null) { return null; }
Country code = (Country) c;
1
2023-11-09 16:10:00+00:00
24k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/es9plus/Es9PlusInterface.java
[ { "identifier": "AuthenticateClientRequest", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/AuthenticateClientRequest.java", "snippet": "public class AuthenticateClientRequest implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic stati...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.gsma.sgp.messages.rspdefinitions.AuthenticateClientRequest; import com.gsma.sgp.messages.rspdefinitions.AuthenticateClientResponseEs9; import com.gsma.sgp.messages.rspdefinitions.CancelSessionRequestEs9; import com.gsma.sgp.messages.rspdefinitions.CancelSessionResponseEs9; import com.gsma.sgp.messages.rspdefinitions.GetBoundProfilePackageRequest; import com.gsma.sgp.messages.rspdefinitions.GetBoundProfilePackageResponse; import com.gsma.sgp.messages.rspdefinitions.InitiateAuthenticationRequest; import com.gsma.sgp.messages.rspdefinitions.InitiateAuthenticationResponse; import com.gsma.sgp.messages.rspdefinitions.PendingNotification; import com.infineon.esim.lpa.core.es9plus.messages.HttpResponse; import com.infineon.esim.lpa.core.es9plus.messages.request.AuthenticateClientReq; import com.infineon.esim.lpa.core.es9plus.messages.request.CancelSessionReq; import com.infineon.esim.lpa.core.es9plus.messages.request.GetBoundProfilePackageReq; import com.infineon.esim.lpa.core.es9plus.messages.request.HandleNotificationReq; import com.infineon.esim.lpa.core.es9plus.messages.request.InitiateAuthenticationReq; import com.infineon.esim.lpa.core.es9plus.messages.response.AuthenticateClientResp; import com.infineon.esim.lpa.core.es9plus.messages.response.CancelSessionResp; import com.infineon.esim.lpa.core.es9plus.messages.response.GetBoundProfilePackageResp; import com.infineon.esim.lpa.core.es9plus.messages.response.InitiateAuthenticationResp; import com.infineon.esim.lpa.core.es9plus.messages.response.base.FunctionExecutionStatus; import com.infineon.esim.lpa.core.es9plus.messages.response.base.ResponseMsgBody; import com.infineon.esim.util.Log; import javax.net.ssl.HttpsURLConnection;
18,913
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es9plus; public class Es9PlusInterface { private static final String TAG = Es9PlusInterface.class.getName(); private static final Gson GS = new GsonBuilder().disableHtmlEscaping().create(); private static final String INITIATE_AUTHENTICATION_PATH = "/gsma/rsp2/es9plus/initiateAuthentication"; private static final String AUTHENTICATE_CLIENT_PATH = "/gsma/rsp2/es9plus/authenticateClient"; private static final String GET_BOUND_PROFILE_PACKAGE_PATH = "/gsma/rsp2/es9plus/getBoundProfilePackage"; private static final String HANDLE_NOTIFICATION_PATH = "/gsma/rsp2/es9plus/handleNotification"; private static final String CANCEL_SESSION_PATH = "/gsma/rsp2/es9plus/cancelSession"; private final HttpsClient httpsClient; private String smdpAddress; private FunctionExecutionStatus lastFunctionExecutionStatus = null; public Es9PlusInterface() { this.httpsClient = new HttpsClient(); } public void setSmdpAddress(String smdpAddress) { this.smdpAddress = smdpAddress; } public InitiateAuthenticationResponse initiateAuthentication(InitiateAuthenticationRequest initiateAuthenticationRequest) throws Exception { ensureSmdpAddressIsAvailable(); Log.debug(TAG, "ES9+ -> : " + initiateAuthenticationRequest); InitiateAuthenticationReq initiateAuthenticationReq = new InitiateAuthenticationReq(); initiateAuthenticationReq.setRequest(initiateAuthenticationRequest);
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es9plus; public class Es9PlusInterface { private static final String TAG = Es9PlusInterface.class.getName(); private static final Gson GS = new GsonBuilder().disableHtmlEscaping().create(); private static final String INITIATE_AUTHENTICATION_PATH = "/gsma/rsp2/es9plus/initiateAuthentication"; private static final String AUTHENTICATE_CLIENT_PATH = "/gsma/rsp2/es9plus/authenticateClient"; private static final String GET_BOUND_PROFILE_PACKAGE_PATH = "/gsma/rsp2/es9plus/getBoundProfilePackage"; private static final String HANDLE_NOTIFICATION_PATH = "/gsma/rsp2/es9plus/handleNotification"; private static final String CANCEL_SESSION_PATH = "/gsma/rsp2/es9plus/cancelSession"; private final HttpsClient httpsClient; private String smdpAddress; private FunctionExecutionStatus lastFunctionExecutionStatus = null; public Es9PlusInterface() { this.httpsClient = new HttpsClient(); } public void setSmdpAddress(String smdpAddress) { this.smdpAddress = smdpAddress; } public InitiateAuthenticationResponse initiateAuthentication(InitiateAuthenticationRequest initiateAuthenticationRequest) throws Exception { ensureSmdpAddressIsAvailable(); Log.debug(TAG, "ES9+ -> : " + initiateAuthenticationRequest); InitiateAuthenticationReq initiateAuthenticationReq = new InitiateAuthenticationReq(); initiateAuthenticationReq.setRequest(initiateAuthenticationRequest);
HttpResponse httpResponse = httpsClient.sendRequest(GS.toJson(initiateAuthenticationReq), smdpAddress, INITIATE_AUTHENTICATION_PATH, true);
9
2023-11-06 02:41:13+00:00
24k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/vod/service/impl/VodServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": ...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.PreUploadDTO; import com.jerry.pilipala.application.dto.VideoPostDTO; import com.jerry.pilipala.application.vo.bvod.BVodVO; import com.jerry.pilipala.application.vo.bvod.PreviewBVodVO; import com.jerry.pilipala.application.vo.user.PreviewUserVO; import com.jerry.pilipala.application.vo.vod.*; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.MessageService; import com.jerry.pilipala.domain.user.entity.mongo.Permission; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.Quality; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.VodDistributeInfo; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionEvent; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionRecord; import com.jerry.pilipala.domain.vod.entity.mongo.statitics.VodStatistics; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.Thumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.VodThumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.vod.BVod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.Vod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodInfo; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodProfiles; import com.jerry.pilipala.domain.vod.entity.neo4j.VodInfoEntity; import com.jerry.pilipala.domain.vod.repository.VodInfoRepository; import com.jerry.pilipala.domain.vod.service.FileService; import com.jerry.pilipala.domain.vod.service.VodService; import com.jerry.pilipala.domain.vod.service.media.UGCSchema; import com.jerry.pilipala.domain.vod.service.media.encoder.Encoder; import com.jerry.pilipala.domain.vod.service.media.profiles.Profile; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.ActionStatusEnum; import com.jerry.pilipala.infrastructure.enums.Qn; import com.jerry.pilipala.infrastructure.enums.VodHandleActionEnum; import com.jerry.pilipala.infrastructure.enums.VodStatusEnum; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.VodCacheKeyEnum; import com.jerry.pilipala.infrastructure.enums.video.Resolution; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.SecurityTool; import lombok.extern.slf4j.Slf4j; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.builder.FFmpegOutputBuilder; import net.bramp.ffmpeg.probe.FFmpegFormat; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.InputStreamResource; import org.springframework.core.task.TaskExecutor; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
14,967
Double realDuration = vod.getVideo().getDuration(); int duration = realDuration.intValue(); List<Thumbnails> thumbnails = new ArrayList<>(); for (int i = 0; i <= duration; i += 2) { Thumbnails thumbnailsPng = new Thumbnails(); thumbnailsPng.setTime(i).setUrl("%s/%05d.png".formatted(fileService.filePathRemoveWorkspace(thumbnailsDirPath), i)); thumbnails.add(thumbnailsPng); } // 上传七牛 fileService.uploadDirToOss(thumbnailsDirPath); fileService.deleteDirOfWorkSpace(thumbnailsDirPath); VodThumbnails vodThumbnails = new VodThumbnails() .setCid(cid) .setThumbnails(thumbnails); mongoTemplate.save(vodThumbnails); log.info("cid: {},thumbnails generate completed.", cid); } catch (Exception e) { log.error("缩略图转码失败,cause ", e); log.error("缩略图转码失败"); } }).get(); } catch (Exception e) { log.error("缩略图转码任务失败,", e); } } /** * 视频转码任务 * * @param profile 需要转出的视频规格 * @param vod 稿件素材信息 * @param originFilePath 原始素材文件地址 */ private void transcodeTask(Profile profile, Vod vod, String originFilePath) { Long cid = vod.getCid(); // f2023101502380651aed32d88f9984f5cb2f264e26c85b9/16 String saveTo = profile.getSaveTo(); String outputDir = fileService.generateTranscodeResSaveToPath(saveTo); // 16.mpd String outputFilename = "%s.%s".formatted( profile.getEncoder().quality().getQn(), profile.getFormat().getExt() ); String outputPath = "%s/%s".formatted(outputDir, outputFilename); Encoder encoder = profile.getEncoder(); encoder.fitInput(vod); Resolution resolution = encoder.getResolution(); // ffmpeg -i input.mp4 -c copy -f dash output.mpd FFmpegOutputBuilder builder = fFmpeg.builder() .setInput(originFilePath) .overrideOutputFiles(true) .addOutput(outputPath) .setFormat(profile.getFormat().getValue()) .setAudioCodec(encoder.getAudioCodec()) .setAudioBitRate(encoder.getAudioBitrate()) .setVideoCodec(encoder.getVideoCodec()) .setVideoFrameRate(encoder.getFrameRate()) .setVideoBitRate(encoder.getVideoBitrate()) .setVideoResolution(resolution.getWidth(), resolution.getHeight()) .setStrict(FFmpegBuilder.Strict.EXPERIMENTAL); if (!profile.isEnableAudio()) { builder.disableAudio(); } if (!profile.isEnableVideo()) { builder.disableVideo(); } if (profile.getDuration() > 0) { long duration = Math.min(vod.getVideo().getDuration().longValue(), profile.getDuration()); builder.setDuration(duration, TimeUnit.SECONDS); } FFmpegExecutor executor = new FFmpegExecutor(fFmpeg, fFprobe); executor.createJob(builder.done()).run(); log.info("cid: {}, resolution: {}x{} transcode completed.", cid, resolution.getWidth(), resolution.getHeight()); distribute(cid, vod.getFilename(), profile.getSaveTo(), encoder.quality(), profile.getFormat().getExt()); } /** * 转码后的稿件分发 * * @param cid 稿件唯一ID * @param filename 稿件文件名 * @param saveTo 转码后文件存储目录 * @param qn 清晰度代号 * @param ext 转码后文件拓展名 */ private void distribute(Long cid, String filename, String saveTo, Qn qn, String ext) { String saveToDir = fileService.generateTranscodeResSaveToPath(saveTo); fileService.uploadDirToOss(saveToDir); fileService.deleteDirOfWorkSpace(saveToDir); Query queryDistributeInfo = new Query(Criteria.where("_id").is(cid)); Update update = new Update() .set("filename", filename) .set("ready", false) .set("qualityMap." + qn.getQn() + ".qn", qn.getQn()) .set("qualityMap." + qn.getQn() + ".saveTo", saveTo) .set("qualityMap." + qn.getQn() + ".ext", ext) .set("qualityMap." + qn.getQn() + ".type", "auto"); mongoTemplate.upsert(queryDistributeInfo, update, VodDistributeInfo.class); log.info("cid: {} distribute format {} successfully.", cid, qn.getDescription()); } /** * 转码任务重置 * * @param taskId 任务ID */ @Override public void reset(String taskId) { Query query = new Query(Criteria.where("_id").is(taskId));
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service public class VodServiceImpl implements VodService { private final FFprobe fFprobe; private final FFmpeg fFmpeg; private final MongoTemplate mongoTemplate; private final RedisTemplate<String, Object> redisTemplate; private final Snowflake snowflake = IdUtil.getSnowflake(); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private final ApplicationEventPublisher applicationEventPublisher; private final UGCSchema ugcSchema; private final TaskExecutor taskExecutor; private final VodInfoRepository vodInfoRepository; private final UserEntityRepository userEntityRepository; private final JsonHelper jsonHelper; private final FileService fileService; private final MessageTrigger messageTrigger; public VodServiceImpl(MongoTemplate mongoTemplate, RedisTemplate<String, Object> redisTemplate, ApplicationEventPublisher applicationEventPublisher, UGCSchema ugcSchema, @Qualifier("asyncServiceExecutor") TaskExecutor taskExecutor, VodInfoRepository vodInfoRepository, UserEntityRepository userEntityRepository, MessageService messageService, JsonHelper jsonHelper, FileService fileService, MessageTrigger messageTrigger1) { this.mongoTemplate = mongoTemplate; this.redisTemplate = redisTemplate; this.applicationEventPublisher = applicationEventPublisher; this.ugcSchema = ugcSchema; this.taskExecutor = taskExecutor; this.vodInfoRepository = vodInfoRepository; this.userEntityRepository = userEntityRepository; this.jsonHelper = jsonHelper; this.fileService = fileService; this.messageTrigger = messageTrigger1; } { try { fFprobe = new FFprobe(); fFmpeg = new FFmpeg(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void ffprobe(String filepath) { try { FFmpegProbeResult probeResult = fFprobe.probe(filepath); FFmpegFormat format = probeResult.getFormat(); System.out.println(probeResult.getStreams()); } catch (IOException e) { throw new RuntimeException(e); } } /** * 生成全局唯一的 filename * * @param preUploadDTO 预上传稿件素材信息 * @return filename */ @Override public String genFilename(PreUploadDTO preUploadDTO) { try { String json = jsonHelper.as(preUploadDTO); String now = DATE_TIME_FORMATTER.format(LocalDateTime.now()); String md5 = SecurityTool.getMd5(json); return "f%s%s".formatted(now, md5); } catch (Exception e) { throw new BusinessException("文件名生成失败", StandardResponse.ERROR); } } /** * 预上传稿件 * * @param preUploadDTO 稿件素材信息 * @return 预上传结果 */ @Override @Transactional(rollbackFor = Exception.class, value = "multiTransactionManager") public PreUploadVO preUpload(PreUploadDTO preUploadDTO) { String bvId = preUploadDTO.getBvId(); String filename = genFilename(preUploadDTO); Long cid = snowflake.nextId(); // 触发初始化开始 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.init, cid)); BVod bVod; if (StringUtils.isNotBlank(bvId)) { Query query = new Query(Criteria.where("_id").is(bvId)); bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("bvid 不存在", StandardResponse.ERROR); } } else { bvId = "BV" + UUID.randomUUID().toString().replace("-", "").toUpperCase(); bVod = new BVod() .setBvId(bvId) .setUid((String) StpUtil.getLoginId()) .setCidList(new ArrayList<>()); } mongoTemplate.save(bVod); Vod vod = new Vod() .setCid(cid) .setBvId(bvId) .setFilename(filename) .setContainer(preUploadDTO.getContainer()) .setVideo(preUploadDTO.getVideo()) .setAudio(preUploadDTO.getAudio()) .setExtra(preUploadDTO.getExtra()); mongoTemplate.save(vod); // 触发初始化结束 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.finished, cid)); return new PreUploadVO().setBvId(bvId).setCid(cid).setFilename(filename); } /** * 投递稿件 * * @param videoPostDTO 稿件信息 */ public void post(VideoPostDTO videoPostDTO) { Query query = new Query(Criteria.where("_id").is(videoPostDTO.getBvId())); BVod bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("稿件不存在,请重新投稿", StandardResponse.ERROR); } bVod.getCidList().add(videoPostDTO.getCid()); bVod.setReady(true); mongoTemplate.save(bVod); Vod vod = mongoTemplate.findById(videoPostDTO.getCid(), Vod.class); if (Objects.isNull(vod)) { throw BusinessException.businessError("稿件不存在"); } VodInfo vodInfo = new VodInfo(); vodInfo.setBvId(videoPostDTO.getBvId()) .setCid(videoPostDTO.getCid()) .setUid((String) StpUtil.getLoginId()) .setStatus(VodStatusEnum.HANDING) .setCoverUrl(videoPostDTO.getCoverUrl()) .setTitle(videoPostDTO.getTitle()) .setGcType(videoPostDTO.getGcType()) .setPartition(videoPostDTO.getPartition()) .setSubPartition(videoPostDTO.getSubPartition()) .setLabels(videoPostDTO.getLabels()) .setDesc(videoPostDTO.getDesc()) .setDuration(vod.getContainer().getDuration()) .setMtime(System.currentTimeMillis()); mongoTemplate.save(vodInfo); VodHandleActionEvent actionEvent = new VodHandleActionEvent( VodHandleActionEnum.SUBMIT, ActionStatusEnum.finished, videoPostDTO.getCid() ); // 触发提交结束 applicationEventPublisher.publishEvent(actionEvent); // 推送站内信 User author = mongoTemplate.findById(new ObjectId(bVod.getUid()), User.class); if (Objects.isNull(author)) { log.error("消息推送失败,稿件作者信息异常."); return; } Map<String, String> variables = new HashMap<>(); variables.put("username", author.getNickname()); variables.put("title", vodInfo.getTitle()); variables.put("bvid", vodInfo.getBvId()); variables.put("cid", vodInfo.getCid().toString()); messageTrigger.triggerSystemMessage( TemplateNameEnum.POST_VOD_NOTIFY, bVod.getUid(), variables ); } /** * 规划需要转出的视频规格 * * @param cid 稿件唯一ID * @param vod 稿件素材信息 * @return 视频规格列表 * @throws JsonProcessingException 打印视频规格信息时可能产生的序列化异常 */ @Override public List<Profile> schema(Long cid, Vod vod) throws JsonProcessingException { Query query = new Query(Criteria.where("_id").is(cid)); VodProfiles vodProfiles = mongoTemplate.findOne(query, VodProfiles.class); List<Profile> profiles; if (Objects.isNull(vodProfiles)) { profiles = ugcSchema.selectAvProfiles(vod); vodProfiles = new VodProfiles().setCid(cid).setProfiles(profiles).setCompleted(false); mongoTemplate.save(vodProfiles); } else { profiles = vodProfiles.getProfiles(); } log.info("cid [{}] -> select profiles: {}", cid, jsonHelper.as(profiles)); return profiles; } /** * 视频转码 * * @param cid 稿件唯一ID * @throws ExecutionException ffmpeg 执行可能出现的异常 * @throws InterruptedException ffmpeg 执行可能出现的异常 * @throws JsonProcessingException 打印视频规格信息时可能产生的序列化异常 */ @Override public void transcode(Long cid) throws ExecutionException, InterruptedException, JsonProcessingException { Query query = new Query(Criteria.where("_id").is(cid)); Vod vod = mongoTemplate.findOne(query, Vod.class); if (Objects.isNull(vod)) { throw new BusinessException("稿件不存在", StandardResponse.ERROR); } String originFilePath = fileService.downloadVideo(vod.getFilename(), vod.getExt()); // 规划转码规格 List<Profile> profiles = schema(cid, vod); CompletableFuture<?>[] tasks = new CompletableFuture[profiles.size()]; for (int i = 0; i < profiles.size(); i++) { final Profile profile = profiles.get(i); tasks[i] = CompletableFuture.runAsync(() -> transcodeTask(profile, vod, originFilePath), taskExecutor); } CompletableFuture.allOf(tasks).get(); // 转码结束,删除本地临时文件 fileService.deleteVideoOfWorkSpace(vod.getFilename(), vod.getExt()); } /** * 转出缩略图 * * @param cid 稿件唯一ID */ @Override public void transcodeThumbnails(Long cid) { try { CompletableFuture.runAsync(() -> { try { // 每两秒抽一帧 // ffmpeg -i f2023102822062151aed32d88f9984f5cb2f264e26c85b9.mp4 -vf "fps=0.5,scale=56:32" "thumbnails_%05d.png Query query = new Query(Criteria.where("_id").is(cid)); Vod vod = mongoTemplate.findOne(query, Vod.class); if (Objects.isNull(vod)) { throw new BusinessException("稿件不存在", StandardResponse.ERROR); } String originVideoPath = fileService.downloadVideo(vod.getFilename(), vod.getExt()); String thumbnailsDirPath = fileService.generateThumbnailsDirPath(vod.getFilename()); String thumbnailsNamePattern = "%s/%s".formatted(thumbnailsDirPath, "%05d.png"); FFmpegOutputBuilder builder = fFmpeg.builder() .setInput(originVideoPath) .overrideOutputFiles(true) .setVideoFilter("fps=0.5,scale=56:32") .addOutput(thumbnailsNamePattern); FFmpegExecutor executor = new FFmpegExecutor(fFmpeg, fFprobe); executor.createJob(builder.done()).run(); Double realDuration = vod.getVideo().getDuration(); int duration = realDuration.intValue(); List<Thumbnails> thumbnails = new ArrayList<>(); for (int i = 0; i <= duration; i += 2) { Thumbnails thumbnailsPng = new Thumbnails(); thumbnailsPng.setTime(i).setUrl("%s/%05d.png".formatted(fileService.filePathRemoveWorkspace(thumbnailsDirPath), i)); thumbnails.add(thumbnailsPng); } // 上传七牛 fileService.uploadDirToOss(thumbnailsDirPath); fileService.deleteDirOfWorkSpace(thumbnailsDirPath); VodThumbnails vodThumbnails = new VodThumbnails() .setCid(cid) .setThumbnails(thumbnails); mongoTemplate.save(vodThumbnails); log.info("cid: {},thumbnails generate completed.", cid); } catch (Exception e) { log.error("缩略图转码失败,cause ", e); log.error("缩略图转码失败"); } }).get(); } catch (Exception e) { log.error("缩略图转码任务失败,", e); } } /** * 视频转码任务 * * @param profile 需要转出的视频规格 * @param vod 稿件素材信息 * @param originFilePath 原始素材文件地址 */ private void transcodeTask(Profile profile, Vod vod, String originFilePath) { Long cid = vod.getCid(); // f2023101502380651aed32d88f9984f5cb2f264e26c85b9/16 String saveTo = profile.getSaveTo(); String outputDir = fileService.generateTranscodeResSaveToPath(saveTo); // 16.mpd String outputFilename = "%s.%s".formatted( profile.getEncoder().quality().getQn(), profile.getFormat().getExt() ); String outputPath = "%s/%s".formatted(outputDir, outputFilename); Encoder encoder = profile.getEncoder(); encoder.fitInput(vod); Resolution resolution = encoder.getResolution(); // ffmpeg -i input.mp4 -c copy -f dash output.mpd FFmpegOutputBuilder builder = fFmpeg.builder() .setInput(originFilePath) .overrideOutputFiles(true) .addOutput(outputPath) .setFormat(profile.getFormat().getValue()) .setAudioCodec(encoder.getAudioCodec()) .setAudioBitRate(encoder.getAudioBitrate()) .setVideoCodec(encoder.getVideoCodec()) .setVideoFrameRate(encoder.getFrameRate()) .setVideoBitRate(encoder.getVideoBitrate()) .setVideoResolution(resolution.getWidth(), resolution.getHeight()) .setStrict(FFmpegBuilder.Strict.EXPERIMENTAL); if (!profile.isEnableAudio()) { builder.disableAudio(); } if (!profile.isEnableVideo()) { builder.disableVideo(); } if (profile.getDuration() > 0) { long duration = Math.min(vod.getVideo().getDuration().longValue(), profile.getDuration()); builder.setDuration(duration, TimeUnit.SECONDS); } FFmpegExecutor executor = new FFmpegExecutor(fFmpeg, fFprobe); executor.createJob(builder.done()).run(); log.info("cid: {}, resolution: {}x{} transcode completed.", cid, resolution.getWidth(), resolution.getHeight()); distribute(cid, vod.getFilename(), profile.getSaveTo(), encoder.quality(), profile.getFormat().getExt()); } /** * 转码后的稿件分发 * * @param cid 稿件唯一ID * @param filename 稿件文件名 * @param saveTo 转码后文件存储目录 * @param qn 清晰度代号 * @param ext 转码后文件拓展名 */ private void distribute(Long cid, String filename, String saveTo, Qn qn, String ext) { String saveToDir = fileService.generateTranscodeResSaveToPath(saveTo); fileService.uploadDirToOss(saveToDir); fileService.deleteDirOfWorkSpace(saveToDir); Query queryDistributeInfo = new Query(Criteria.where("_id").is(cid)); Update update = new Update() .set("filename", filename) .set("ready", false) .set("qualityMap." + qn.getQn() + ".qn", qn.getQn()) .set("qualityMap." + qn.getQn() + ".saveTo", saveTo) .set("qualityMap." + qn.getQn() + ".ext", ext) .set("qualityMap." + qn.getQn() + ".type", "auto"); mongoTemplate.upsert(queryDistributeInfo, update, VodDistributeInfo.class); log.info("cid: {} distribute format {} successfully.", cid, qn.getDescription()); } /** * 转码任务重置 * * @param taskId 任务ID */ @Override public void reset(String taskId) { Query query = new Query(Criteria.where("_id").is(taskId));
VodHandleActionRecord actionRecord = mongoTemplate.findOne(query, VodHandleActionRecord.class);
15
2023-11-03 10:05:02+00:00
24k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
14,560
NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败
if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
2
2023-11-03 02:29:57+00:00
24k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/util/MoneyGiver.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.by1337.bauction.Main; import org.by1337.bauction.db.kernel.MysqlDb; import org.by1337.bauction.network.PacketConnection; import org.by1337.bauction.network.PacketType; import org.by1337.bauction.network.WaitNotifyCallBack; import org.by1337.bauction.network.in.PlayInGiveMoneyRequest; import org.by1337.bauction.network.in.PlayInGiveMoneyResponse; import org.by1337.bauction.network.out.PlayOutGiveMoneyRequest; import org.by1337.bauction.network.out.PlayOutGiveMoneyResponse; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.UUID; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger;
14,798
package org.by1337.bauction.util; public class MoneyGiver { private final PacketConnection connection; private final MysqlDb mysqlDb; private final String currentServer; private final AtomicInteger counter = new AtomicInteger();
package org.by1337.bauction.util; public class MoneyGiver { private final PacketConnection connection; private final MysqlDb mysqlDb; private final String currentServer; private final AtomicInteger counter = new AtomicInteger();
private final Map<Integer, WaitNotifyCallBack<Status>> waiters = new ConcurrentHashMap<>();
4
2023-11-08 18:25:18+00:00
24k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
14,560
NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId"); List<SystemTypeList> typeList = typeDao.findByTypeModel("inform"); List<SystemStatusList> statusList = statusDao.findByStatusModel("inform"); if (!StringUtils.isEmpty(req.getAttribute("errormess"))) { req.setAttribute("errormess", req.getAttribute("errormess")); } if (!StringUtils.isEmpty(req.getAttribute("success"))) { req.setAttribute("success", "数据保存成功"); } req.setAttribute("typeList", typeList); req.setAttribute("statusList", statusList); if (!StringUtils.isEmpty(req.getParameter("id"))) { Long noticeId = Long.parseLong(req.getParameter("id")); NoticesList noticeList = informDao.findOne(noticeId); model.addAttribute("noticeList", noticeList); model.addAttribute("typeName", typeDao.findOne(noticeList.getTypeId()).getTypeName()); model.addAttribute("statusName", statusDao.findOne(noticeList.getStatusId()).getStatusName()); session.setAttribute("noticeId", noticeId); } return "inform/informedit"; } /** * 详细通知显示 */ @RequestMapping("informshow") public String informShow(HttpServletRequest req, Model model) { Long noticeId = Long.parseLong(req.getParameter("id")); if (!StringUtils.isEmpty(req.getParameter("read"))) { if (("0").equals(req.getParameter("read"))) { Long relationId = Long.parseLong(req.getParameter("relationid")); NoticeUserRelation relation = informrelationDao.findOne(relationId); relation.setRead(true); informrelationservice.save(relation); } } NoticesList notice = informDao.findOne(noticeId); User user = uDao.findOne(notice.getUserId()); model.addAttribute("notice", notice); model.addAttribute("userName", user.getUserName()); return "inform/informshow"; } /** * 系统管理表单验证 * * @param req * @param menu * @param br * 后台校验表单数据,不通过则回填数据,显示错误信息;通过则直接执行业务,例如新增、编辑等; * @return */ @RequestMapping("informcheck") public String testMess(HttpServletRequest req, @Valid NoticesList menu, BindingResult br) { HttpSession session = req.getSession(); Long menuId = null; req.setAttribute("menuObj", menu); Long userId = Long.parseLong(session.getAttribute("userId") + ""); menu.setUserId(userId); // 这里返回ResultVO对象,如果校验通过,ResultEnum.SUCCESS.getCode()返回的值为200;否则就是没有通过; ResultVO res = BindingResultVOUtil.hasErrors(br); // 校验失败
if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
2
2023-11-03 02:08:22+00:00
24k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/task/JarFuseTask.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.actions.JarMergeAction; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.plugin.ModFusionerPlugin; import com.hypherionmc.modfusioner.utils.FileChecks; import com.hypherionmc.modfusioner.utils.FileTools; import org.apache.commons.io.FileUtils; import org.gradle.api.Project; import org.gradle.api.internal.file.copy.CopyAction; import org.gradle.api.tasks.WorkResults; import org.gradle.jvm.tasks.Jar; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.rootProject;
14,925
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis(); ModFusionerPlugin.logger.lifecycle("Start Fusing Jars"); // Get settings from extension FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration(); FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration(); FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration(); List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations(); // Try to resolve the projects specific in the extension config Project forgeProject = null; Project fabricProject = null; Project quiltProject = null; Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>(); List<Boolean> validation = new ArrayList<>(); if (forgeConfiguration != null) { try { forgeProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(forgeConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (fabricConfiguration != null) { try { fabricProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(fabricConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (quiltConfiguration != null) { try { quiltProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(quiltConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (customConfigurations != null) { for (FusionerExtension.CustomConfiguration customSettings : customConfigurations) { try { customProjects.put(rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equals(customSettings.getProjectName())).findFirst().get(), customSettings); validation.add(true); } catch (NoSuchElementException ignored) { } } } // Check that at least 2 projects are defined if (validation.size() < 2) { if (validation.size() == 1) ModFusionerPlugin.logger.error("Only one project was found. Skipping fusejars task."); if (validation.size() == 0) ModFusionerPlugin.logger.error("No projects were found. Skipping fusejars task."); return; } validation.clear(); // Try to automatically determine the input jar from the projects File forgeJar = null; File fabricJar = null; File quiltJar = null; Map<FusionerExtension.CustomConfiguration, File> customJars = new HashMap<>(); if (forgeProject != null && forgeConfiguration != null) { forgeJar = getInputFile(forgeConfiguration.getInputFile(), forgeConfiguration.getInputTaskName(), forgeProject); } if (fabricProject != null && fabricConfiguration != null) { fabricJar = getInputFile(fabricConfiguration.getInputFile(), fabricConfiguration.getInputTaskName(), fabricProject); } if (quiltProject != null && quiltConfiguration != null) { quiltJar = getInputFile(quiltConfiguration.getInputFile(), quiltConfiguration.getInputTaskName(), quiltProject); } for (Map.Entry<Project, FusionerExtension.CustomConfiguration> entry : customProjects.entrySet()) { File f = getInputFile(entry.getValue().getInputFile(), entry.getValue().getInputTaskName(), entry.getKey()); if (f != null) customJars.put(entry.getValue(), f); } // Set up the final output jar if (mergedJar.exists()) FileUtils.forceDelete(mergedJar); if (!mergedJar.getParentFile().exists()) mergedJar.getParentFile().mkdirs(); // Set up the jar merge action JarMergeAction mergeAction = JarMergeAction.of( customJars, modFusionerExtension.getDuplicateRelocations(), modFusionerExtension.getPackageGroup(), new File(rootProject.getRootDir(), ".gradle" + File.separator + "fusioner"), getArchiveFileName().get() ); // Forge mergeAction.setForgeInput(forgeJar); mergeAction.setForgeRelocations(forgeConfiguration == null ? new HashMap<>() : forgeConfiguration.getRelocations()); mergeAction.setForgeMixins(forgeConfiguration == null ? new ArrayList<>() : forgeConfiguration.getMixins()); // Fabric mergeAction.setFabricInput(fabricJar); mergeAction.setFabricRelocations(fabricConfiguration == null ? new HashMap<>() : fabricConfiguration.getRelocations()); // Quilt mergeAction.setQuiltInput(quiltJar); mergeAction.setQuiltRelocations(quiltConfiguration == null ? new HashMap<>() : quiltConfiguration.getRelocations()); // Merge them jars Path tempMergedJarPath = mergeAction.mergeJars(false).toPath(); // Move the merged jar to the specified output directory Files.move(tempMergedJarPath, mergedJar.toPath(), StandardCopyOption.REPLACE_EXISTING); try { Files.setPosixFilePermissions(mergedJar.toPath(), Constants.filePerms); } catch (UnsupportedOperationException | IOException | SecurityException ignored) { } // Cleanup mergeAction.clean(); ModFusionerPlugin.logger.lifecycle("Fused jar created in " + (System.currentTimeMillis() - time) / 1000.0 + " seconds."); hasRun.set(true); } /** * Run the main task logic and copy the files to the correct locations * @return - Just returns true to say the task executed */ @Override protected @NotNull CopyAction createCopyAction() { return copyActionProcessingStream -> { copyActionProcessingStream.process(fileCopyDetailsInternal -> { if (!hasRun.get()) try { fuseJars(); } catch (IOException e) { throw new RuntimeException(e); } }); return WorkResults.didWork(true); }; } /** * Try to determine the input jar of a project * @param jarLocation - The user defined jar location * @param inProject - The project the file should be for or from * @return - The jar file or null */ @Nullable private File getInputFile(@Nullable String jarLocation, String inputTaskName, Project inProject) { if (jarLocation != null && !jarLocation.isEmpty()) { return new File(inProject.getProjectDir(), jarLocation); } else if (inputTaskName != null && !inputTaskName.isEmpty()) {
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis(); ModFusionerPlugin.logger.lifecycle("Start Fusing Jars"); // Get settings from extension FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration(); FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration(); FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration(); List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations(); // Try to resolve the projects specific in the extension config Project forgeProject = null; Project fabricProject = null; Project quiltProject = null; Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>(); List<Boolean> validation = new ArrayList<>(); if (forgeConfiguration != null) { try { forgeProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(forgeConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (fabricConfiguration != null) { try { fabricProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(fabricConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (quiltConfiguration != null) { try { quiltProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(quiltConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (customConfigurations != null) { for (FusionerExtension.CustomConfiguration customSettings : customConfigurations) { try { customProjects.put(rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equals(customSettings.getProjectName())).findFirst().get(), customSettings); validation.add(true); } catch (NoSuchElementException ignored) { } } } // Check that at least 2 projects are defined if (validation.size() < 2) { if (validation.size() == 1) ModFusionerPlugin.logger.error("Only one project was found. Skipping fusejars task."); if (validation.size() == 0) ModFusionerPlugin.logger.error("No projects were found. Skipping fusejars task."); return; } validation.clear(); // Try to automatically determine the input jar from the projects File forgeJar = null; File fabricJar = null; File quiltJar = null; Map<FusionerExtension.CustomConfiguration, File> customJars = new HashMap<>(); if (forgeProject != null && forgeConfiguration != null) { forgeJar = getInputFile(forgeConfiguration.getInputFile(), forgeConfiguration.getInputTaskName(), forgeProject); } if (fabricProject != null && fabricConfiguration != null) { fabricJar = getInputFile(fabricConfiguration.getInputFile(), fabricConfiguration.getInputTaskName(), fabricProject); } if (quiltProject != null && quiltConfiguration != null) { quiltJar = getInputFile(quiltConfiguration.getInputFile(), quiltConfiguration.getInputTaskName(), quiltProject); } for (Map.Entry<Project, FusionerExtension.CustomConfiguration> entry : customProjects.entrySet()) { File f = getInputFile(entry.getValue().getInputFile(), entry.getValue().getInputTaskName(), entry.getKey()); if (f != null) customJars.put(entry.getValue(), f); } // Set up the final output jar if (mergedJar.exists()) FileUtils.forceDelete(mergedJar); if (!mergedJar.getParentFile().exists()) mergedJar.getParentFile().mkdirs(); // Set up the jar merge action JarMergeAction mergeAction = JarMergeAction.of( customJars, modFusionerExtension.getDuplicateRelocations(), modFusionerExtension.getPackageGroup(), new File(rootProject.getRootDir(), ".gradle" + File.separator + "fusioner"), getArchiveFileName().get() ); // Forge mergeAction.setForgeInput(forgeJar); mergeAction.setForgeRelocations(forgeConfiguration == null ? new HashMap<>() : forgeConfiguration.getRelocations()); mergeAction.setForgeMixins(forgeConfiguration == null ? new ArrayList<>() : forgeConfiguration.getMixins()); // Fabric mergeAction.setFabricInput(fabricJar); mergeAction.setFabricRelocations(fabricConfiguration == null ? new HashMap<>() : fabricConfiguration.getRelocations()); // Quilt mergeAction.setQuiltInput(quiltJar); mergeAction.setQuiltRelocations(quiltConfiguration == null ? new HashMap<>() : quiltConfiguration.getRelocations()); // Merge them jars Path tempMergedJarPath = mergeAction.mergeJars(false).toPath(); // Move the merged jar to the specified output directory Files.move(tempMergedJarPath, mergedJar.toPath(), StandardCopyOption.REPLACE_EXISTING); try { Files.setPosixFilePermissions(mergedJar.toPath(), Constants.filePerms); } catch (UnsupportedOperationException | IOException | SecurityException ignored) { } // Cleanup mergeAction.clean(); ModFusionerPlugin.logger.lifecycle("Fused jar created in " + (System.currentTimeMillis() - time) / 1000.0 + " seconds."); hasRun.set(true); } /** * Run the main task logic and copy the files to the correct locations * @return - Just returns true to say the task executed */ @Override protected @NotNull CopyAction createCopyAction() { return copyActionProcessingStream -> { copyActionProcessingStream.process(fileCopyDetailsInternal -> { if (!hasRun.get()) try { fuseJars(); } catch (IOException e) { throw new RuntimeException(e); } }); return WorkResults.didWork(true); }; } /** * Try to determine the input jar of a project * @param jarLocation - The user defined jar location * @param inProject - The project the file should be for or from * @return - The jar file or null */ @Nullable private File getInputFile(@Nullable String jarLocation, String inputTaskName, Project inProject) { if (jarLocation != null && !jarLocation.isEmpty()) { return new File(inProject.getProjectDir(), jarLocation); } else if (inputTaskName != null && !inputTaskName.isEmpty()) {
return FileTools.resolveFile(inProject, inputTaskName);
5
2023-11-03 23:19:08+00:00
24k
momentohq/momento-dynamodb-lock-client
src/main/java/com/amazonaws/services/dynamodbv2/MomentoDynamoDBLockClient.java
[ { "identifier": "LockItemUtils", "path": "src/main/java/momento/lock/client/LockItemUtils.java", "snippet": "public class LockItemUtils {\n\n private static final ObjectMapper MAPPER = new ObjectMapper();\n\n public static byte[] serialize(final MomentoLockItem lockItem) {\n try {\n ...
import com.amazonaws.services.dynamodbv2.model.LockCurrentlyUnavailableException; import com.amazonaws.services.dynamodbv2.model.LockNotGrantedException; import com.amazonaws.services.dynamodbv2.util.LockClientUtils; import momento.lock.client.LockItemUtils; import momento.lock.client.LockStorage; import momento.lock.client.MomentoDynamoDBLockClientOptions; import momento.lock.client.MomentoLockClient; import momento.lock.client.MomentoLockClientHeartbeatHandler; import momento.lock.client.MomentoLockItem; import momento.lock.client.NoopDynamoDbClient; import momento.lock.client.model.MomentoClientException; import momento.sdk.CacheClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import software.amazon.awssdk.core.exception.SdkClientException; import java.io.Closeable; import java.io.IOException; import java.time.Duration; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Stream;
20,706
/** * <p> * Attempts to acquire a lock until it either acquires the lock, or a specified {@code additionalTimeToWaitForLock} is * reached. This method will poll Momento based on the {@code refreshPeriod}. If it does not see the lock in Momento, it * will immediately return the lock to the caller. If it does see the lock, it waits for as long as {@code additionalTimeToWaitForLock} * without acquiring the lock, then it will throw a {@code LockNotGrantedException}. * </p> * <p> * Note that this method will wait for at least as long as the {@code leaseDuration} in order to acquire a lock that already * exists. If the lock is not acquired in that time, it will wait an additional amount of time specified in * {@code additionalTimeToWaitForLock} before giving up. * </p> * <p> * See the defaults set when constructing a new {@code AcquireLockOptions} object for any fields that you do not set * explicitly. * </p> * * @param options A combination of optional arguments that may be passed in for acquiring the lock * @return the lock * @throws InterruptedException in case the Thread.sleep call was interrupted while waiting to refresh. */ public LockItem acquireLock(final AcquireLockOptions options) throws LockNotGrantedException, InterruptedException { try { final String partitionKey = options.getPartitionKey(); final Optional<String> sortKey = options.getSortKey(); String cacheKey = generateCacheKey(partitionKey, sortKey); if (options.getReentrant()) { Optional<LockItem> localLock = lockStorage.getLock(cacheKey); if (localLock.isPresent()) { Optional<MomentoLockItem> lockFromMomento = momentoLockClient.getLockFromMomento(cacheKey); if (lockFromMomento.isPresent() && lockFromMomento.get().getOwner().equals(this.owner)) { return localLock.get(); } } } validateAttributes(options, partitionKey, sortKey); long millisecondsToWait = DEFAULT_BUFFER_MS; if (options.getAdditionalTimeToWaitForLock() != null) { Objects.requireNonNull(options.getTimeUnit(), "timeUnit must not be null if additionalTimeToWaitForLock is non-null"); millisecondsToWait = options.getTimeUnit().toMillis(options.getAdditionalTimeToWaitForLock()); } // ddb lock client does this too for default case millisecondsToWait += this.leaseDurationMillis; long refreshPeriodInMilliseconds = DEFAULT_BUFFER_MS; if (options.getRefreshPeriod() != null) { Objects.requireNonNull(options.getTimeUnit(), "timeUnit must not be null if refreshPeriod is non-null"); refreshPeriodInMilliseconds = options.getTimeUnit().toMillis(options.getRefreshPeriod()); } final Optional<SessionMonitor> sessionMonitor = options.getSessionMonitor(); if (sessionMonitor.isPresent()) { sessionMonitorArgsValidate(sessionMonitor.get().getSafeTimeMillis(), this.heartbeatPeriodInMilliseconds, this.leaseDurationMillis); } return acquireLockWithRetries(options, cacheKey, millisecondsToWait, refreshPeriodInMilliseconds); } catch (ExecutionException e) { Throwable t = e.getCause(); if (t instanceof LockCurrentlyUnavailableException) { throw new LockCurrentlyUnavailableException(e.getMessage()); } if (t instanceof LockNotGrantedException) { throw new LockNotGrantedException(e.getMessage()); } throw SdkClientException.create(t.getMessage(), t.getCause()); } catch (InterruptedException e) { throw SdkClientException.create(e.getMessage(), e.getCause()); } } private static String generateCacheKey(String partitionKey, Optional<String> sortKey) { String cacheKey = partitionKey; if (sortKey.isPresent()) { cacheKey = cacheKey + "_" + sortKey.get(); } return cacheKey; } private LockItem acquireLockWithRetries(final AcquireLockOptions options, final String cacheKey, final long totalWaitTime, final long waitTimeIfLockAcquired) throws InterruptedException, ExecutionException { final long startTimeMillis = LockClientUtils.INSTANCE.millisecondTime(); // supported rvn is constant cacheKey for now final LockItem lockItem = new LockItem(this, options.getPartitionKey(), options.getSortKey(), options.getData(), options.getDeleteLockOnRelease(), owner, leaseDurationMillis, startTimeMillis, cacheKey /* rvn */, false /* isReleased */, options.getSessionMonitor(), options.getAdditionalAttributes()); long delay = 0; while (true) { // we simply schedule tasks starting with a 0 delay to implement our custom retries. final ScheduledFuture<LockItem> future = executorService.schedule(() -> { logger.trace("Call Momento Get to see if the lock for key = " + cacheKey + "exists in the cache"); final Optional<MomentoLockItem> lockFromMomento = momentoLockClient.getLockFromMomento(cacheKey); if (!lockFromMomento.isPresent() && options.getAcquireOnlyIfLockAlreadyExists()) { throw new LockNotGrantedException("Lock does not exist."); } if (lockFromMomento.isPresent()) { if (options.shouldSkipBlockingWait()) { /* * The lock is being held by someone else, and the caller explicitly said not to perform a blocking wait; * We will throw back a lock not grant exception, so that the caller can retry if needed. */ throw new LockCurrentlyUnavailableException("The lock being requested is being held by another client."); } }
/* * This Java source file was generated by the Gradle 'init' task. */ package com.amazonaws.services.dynamodbv2; /** * <p> * Provides a simple library for using DynamoDB's consistent read/write feature to use it for managing distributed locks. * </p> * <p> * In order to use this library, the client must create a cache in Momento, although the library provides a convenience method * for creating that cache (createLockCache.) * </p> * <p> * Here is some example code for how to use the lock client for leader election to work on a resource called "host-2" (it * assumes you already have a Momento cache named lockCache, which can be created with the * {@code createLockCache} helper method): * </p> * <pre> * {@code * AmazonDynamoDBLockClient lockClient = new MomentoDynamoDBLockClient( * MomentoDynamoDBLockClientOptions.builder(dynamoDBClient, "lockTable").build(); * try { * // Attempt to acquire the lock indefinitely, polling Momento every 2 seconds for the lock * LockItem lockItem = lockClient.acquireLock( * AcquireLockOptions.builder("host-2") * .withRefreshPeriod(120L) * .withAdditionalTimeToWaitForLock(Long.MAX_VALUE / 2L) * .withTimeUnit(TimeUnit.MILLISECONDS) * .build()); * if (!lockItem.isExpired()) { * // do business logic, you can call lockItem.isExpired() to periodically check to make sure you still have the lock * // the background thread will keep the lock valid for you by sending heartbeats (default is every 5 seconds) * } * } catch (LockNotGrantedException x) { * // Should only be thrown if the lock could not be acquired for Long.MAX_VALUE / 2L milliseconds. * } * } * </pre> */ public class MomentoDynamoDBLockClient extends AmazonDynamoDBLockClient implements Closeable { private static final Log logger = LogFactory.getLog(MomentoDynamoDBLockClient.class); private final String lockCacheName; private final CacheClient cacheClient; private static final long DEFAULT_BUFFER_MS = 1000; private static final int TTL_GRACE_MILLIS = 200; private final long leaseDurationMillis; private final long heartbeatPeriodInMilliseconds; private final String owner; private final ConcurrentHashMap<String, Thread> sessionMonitors; private final LockStorage lockStorage; private final Function<String, ThreadFactory> namedThreadCreator; private ScheduledExecutorService heartbeatExecutor; private MomentoLockClientHeartbeatHandler heartbeatHandler; private final MomentoLockClient momentoLockClient; private final Boolean holdLockOnServiceUnavailable; private final ScheduledExecutorService executorService; public MomentoDynamoDBLockClient(final MomentoDynamoDBLockClientOptions lockClientOptions) { super(AmazonDynamoDBLockClientOptions.builder(new NoopDynamoDbClient(), lockClientOptions.getCacheName()).build()); Objects.requireNonNull(lockClientOptions.getTableName(), "Table name cannot be null"); Objects.requireNonNull(lockClientOptions.getCacheName(), "Cache name cannot be null"); Objects.requireNonNull(lockClientOptions.getOwnerName(), "Owner name cannot be null"); Objects.requireNonNull(lockClientOptions.getTimeUnit(), "Time unit cannot be null"); Objects.requireNonNull(lockClientOptions.getPartitionKeyName(), "Partition Key Name cannot be null"); Objects.requireNonNull(lockClientOptions.getSortKeyName(), "Sort Key Name cannot be null (use Optional.absent())"); Objects.requireNonNull(lockClientOptions.getNamedThreadCreator(), "Named thread creator cannot be null"); this.lockCacheName = lockClientOptions.getCacheName(); this.sessionMonitors = new ConcurrentHashMap<>(); this.owner = lockClientOptions.getOwnerName(); this.leaseDurationMillis = lockClientOptions.getTimeUnit().toMillis(lockClientOptions.getLeaseDuration()); this.heartbeatPeriodInMilliseconds = lockClientOptions.getTimeUnit().toMillis(lockClientOptions.getHeartbeatPeriod()); this.namedThreadCreator = lockClientOptions.getNamedThreadCreator(); this.holdLockOnServiceUnavailable = lockClientOptions.getHoldLockOnServiceUnavailable(); this.cacheClient = CacheClient.create(lockClientOptions.getCredentialProvider(), lockClientOptions.getConfiguration(), Duration.ofMillis(this.leaseDurationMillis)); this.momentoLockClient = new MomentoLockClient(cacheClient, lockCacheName); this.lockStorage = new LockStorage(); this.heartbeatHandler = new MomentoLockClientHeartbeatHandler(this.lockStorage, this.cacheClient, this.lockCacheName, Duration.ofMillis(leaseDurationMillis), holdLockOnServiceUnavailable, lockClientOptions.getTotalNumBackgroundThreadsForHeartbeating()); if (lockClientOptions.getCreateHeartbeatBackgroundThread()) { if (this.leaseDurationMillis < 2 * this.heartbeatPeriodInMilliseconds) { throw new IllegalArgumentException("Heartbeat period must be no more than half the length of the Lease Duration, " + "or locks might expire due to the heartbeat thread taking too long to update them (recommendation is to make it much greater, for example " + "4+ times greater)"); } this.heartbeatExecutor = new ScheduledThreadPoolExecutor(1); heartbeatExecutor.scheduleAtFixedRate(this.heartbeatHandler, 0, heartbeatPeriodInMilliseconds, TimeUnit.MILLISECONDS); } this.executorService = new ScheduledThreadPoolExecutor(lockClientOptions.getTotalNumThreadsForAcquiringLocks()); } public Stream<LockItem> getAllLocksFromDynamoDB(final boolean deleteOnRelease) { throw new UnsupportedOperationException("This operation is not available on" + " Momento DynamoDB lock client"); } public Stream<LockItem> getLocksByPartitionKey(String key, final boolean deleteOnRelease) { throw new UnsupportedOperationException("This operation is not available on" + " Momento DynamoDB lock client"); } public void createLockCache(final String cacheName) { try { momentoLockClient.createLockCache(cacheName); } catch (MomentoClientException e) { throw SdkClientException.create(e.getMessage(), e.getCause()); } } /** * <p> * Attempts to acquire a lock until it either acquires the lock, or a specified {@code additionalTimeToWaitForLock} is * reached. This method will poll Momento based on the {@code refreshPeriod}. If it does not see the lock in Momento, it * will immediately return the lock to the caller. If it does see the lock, it waits for as long as {@code additionalTimeToWaitForLock} * without acquiring the lock, then it will throw a {@code LockNotGrantedException}. * </p> * <p> * Note that this method will wait for at least as long as the {@code leaseDuration} in order to acquire a lock that already * exists. If the lock is not acquired in that time, it will wait an additional amount of time specified in * {@code additionalTimeToWaitForLock} before giving up. * </p> * <p> * See the defaults set when constructing a new {@code AcquireLockOptions} object for any fields that you do not set * explicitly. * </p> * * @param options A combination of optional arguments that may be passed in for acquiring the lock * @return the lock * @throws InterruptedException in case the Thread.sleep call was interrupted while waiting to refresh. */ public LockItem acquireLock(final AcquireLockOptions options) throws LockNotGrantedException, InterruptedException { try { final String partitionKey = options.getPartitionKey(); final Optional<String> sortKey = options.getSortKey(); String cacheKey = generateCacheKey(partitionKey, sortKey); if (options.getReentrant()) { Optional<LockItem> localLock = lockStorage.getLock(cacheKey); if (localLock.isPresent()) { Optional<MomentoLockItem> lockFromMomento = momentoLockClient.getLockFromMomento(cacheKey); if (lockFromMomento.isPresent() && lockFromMomento.get().getOwner().equals(this.owner)) { return localLock.get(); } } } validateAttributes(options, partitionKey, sortKey); long millisecondsToWait = DEFAULT_BUFFER_MS; if (options.getAdditionalTimeToWaitForLock() != null) { Objects.requireNonNull(options.getTimeUnit(), "timeUnit must not be null if additionalTimeToWaitForLock is non-null"); millisecondsToWait = options.getTimeUnit().toMillis(options.getAdditionalTimeToWaitForLock()); } // ddb lock client does this too for default case millisecondsToWait += this.leaseDurationMillis; long refreshPeriodInMilliseconds = DEFAULT_BUFFER_MS; if (options.getRefreshPeriod() != null) { Objects.requireNonNull(options.getTimeUnit(), "timeUnit must not be null if refreshPeriod is non-null"); refreshPeriodInMilliseconds = options.getTimeUnit().toMillis(options.getRefreshPeriod()); } final Optional<SessionMonitor> sessionMonitor = options.getSessionMonitor(); if (sessionMonitor.isPresent()) { sessionMonitorArgsValidate(sessionMonitor.get().getSafeTimeMillis(), this.heartbeatPeriodInMilliseconds, this.leaseDurationMillis); } return acquireLockWithRetries(options, cacheKey, millisecondsToWait, refreshPeriodInMilliseconds); } catch (ExecutionException e) { Throwable t = e.getCause(); if (t instanceof LockCurrentlyUnavailableException) { throw new LockCurrentlyUnavailableException(e.getMessage()); } if (t instanceof LockNotGrantedException) { throw new LockNotGrantedException(e.getMessage()); } throw SdkClientException.create(t.getMessage(), t.getCause()); } catch (InterruptedException e) { throw SdkClientException.create(e.getMessage(), e.getCause()); } } private static String generateCacheKey(String partitionKey, Optional<String> sortKey) { String cacheKey = partitionKey; if (sortKey.isPresent()) { cacheKey = cacheKey + "_" + sortKey.get(); } return cacheKey; } private LockItem acquireLockWithRetries(final AcquireLockOptions options, final String cacheKey, final long totalWaitTime, final long waitTimeIfLockAcquired) throws InterruptedException, ExecutionException { final long startTimeMillis = LockClientUtils.INSTANCE.millisecondTime(); // supported rvn is constant cacheKey for now final LockItem lockItem = new LockItem(this, options.getPartitionKey(), options.getSortKey(), options.getData(), options.getDeleteLockOnRelease(), owner, leaseDurationMillis, startTimeMillis, cacheKey /* rvn */, false /* isReleased */, options.getSessionMonitor(), options.getAdditionalAttributes()); long delay = 0; while (true) { // we simply schedule tasks starting with a 0 delay to implement our custom retries. final ScheduledFuture<LockItem> future = executorService.schedule(() -> { logger.trace("Call Momento Get to see if the lock for key = " + cacheKey + "exists in the cache"); final Optional<MomentoLockItem> lockFromMomento = momentoLockClient.getLockFromMomento(cacheKey); if (!lockFromMomento.isPresent() && options.getAcquireOnlyIfLockAlreadyExists()) { throw new LockNotGrantedException("Lock does not exist."); } if (lockFromMomento.isPresent()) { if (options.shouldSkipBlockingWait()) { /* * The lock is being held by someone else, and the caller explicitly said not to perform a blocking wait; * We will throw back a lock not grant exception, so that the caller can retry if needed. */ throw new LockCurrentlyUnavailableException("The lock being requested is being held by another client."); } }
boolean acquired = momentoLockClient.acquireLockInMomento(LockItemUtils.toMomentoLockItem(lockItem));
0
2023-11-07 03:56:11+00:00
24k
FallenDeity/GameEngine2DJava
src/main/java/engine/scenes/LevelEditorScene.java
[ { "identifier": "Sprite", "path": "src/main/java/engine/components/sprites/Sprite.java", "snippet": "public class Sprite {\n\tprivate Texture texture = null;\n\tprivate float width = 0, height = 0;\n\tprivate Vector2f[] texCoords =\n\t\t\tnew Vector2f[]{\n\t\t\t\t\tnew Vector2f(1, 1), new Vector2f(1, 0)...
import engine.components.*; import engine.components.sprites.Sprite; import engine.components.sprites.SpriteSheet; import engine.editor.JImGui; import engine.physics2d.components.Box2DCollider; import engine.physics2d.components.RigidBody2D; import engine.physics2d.enums.BodyType; import engine.renderer.Sound; import engine.ruby.Window; import engine.util.AssetPool; import engine.util.CONSTANTS; import engine.util.PipeDirection; import engine.util.Prefabs; import imgui.ImGui; import imgui.ImVec2; import org.joml.Vector2f; import java.io.File; import java.util.ArrayList; import java.util.List;
16,342
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) { GameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue()); if (!decoration) { RigidBody2D rb = new RigidBody2D(); rb.setBodyType(BodyType.STATIC); ob.addComponent(rb); Box2DCollider collider = new Box2DCollider(); collider.setHalfSize(new Vector2f(CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue())); ob.addComponent(collider); ob.addComponent(new Ground()); if (i == 12 || i == 33) ob.addComponent(new BreakableBrick()); } editor.getComponent(MouseControls.class).setActiveGameObject(ob); } ImGui.popID(); ImVec2 lastButtonPos = ImGui.getItemRectMax(); float lastButtonX = lastButtonPos.x; float nextButtonX = lastButtonX + itemSpacing.x + sprite.getWidth() * 3; if (i + 1 < blocks.getNumSprites() && nextButtonX < windowX + windowSize.x - 30) { ImGui.sameLine(); } } @Override public void imGui() { ImGui.begin("Editor");
package engine.scenes; public class LevelEditorScene extends Scene { private final SpriteSheet blocks; private final GameObject editor; public LevelEditorScene() { editor = createGameObject("Editor"); editor.setNotSerializable(); editor.addComponent(new MouseControls()); editor.addComponent(new KeyControls()); editor.addComponent(new GridLines()); editor.addComponent(new EditorCamera(camera)); editor.addComponent(new GizmoSystem(this, editor)); blocks = AssetPool.getSpriteSheet(CONSTANTS.BLOCK_SHEET_PATH.getValue(), 16, 16, 0, 81); addGameObjectToScene(editor); AssetPool.getSound(CONSTANTS.SOUNDS_PATH.getValue() + "main-theme-overworld.ogg").stop(); } public boolean gizmoActive() { GizmoSystem gizmoSystem = editor.getComponent(GizmoSystem.class); return gizmoSystem.gizmoActive(); } private List<Sound> loadSounds() { String sound_dir = CONSTANTS.SOUNDS_PATH.getValue(); File[] files = new File(sound_dir).listFiles(); if (files != null) { for (File file : files) { if (file.isFile() && file.getName().endsWith(".ogg")) { String path = file.getAbsolutePath(); AssetPool.getSound(path, false); } } } return new ArrayList<>(AssetPool.getSounds()); } private void addBlock(SpriteSheet sheet, int i, ImVec2 windowSize, ImVec2 itemSpacing, float windowX, boolean decoration) { Sprite sprite = sheet.getSprite(i); float spriteWidth = sprite.getWidth() * 3, spriteHeight = sprite.getHeight() * 3; Vector2f[] texCoords = sprite.getTexCoords(); int id = sprite.getTextureID(); ImGui.pushID(i); if (ImGui.imageButton( id, spriteWidth, spriteHeight, texCoords[2].x, texCoords[0].y, texCoords[0].x, texCoords[2].y)) { GameObject ob = Prefabs.generateSpriteObject(sprite, CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue()); if (!decoration) { RigidBody2D rb = new RigidBody2D(); rb.setBodyType(BodyType.STATIC); ob.addComponent(rb); Box2DCollider collider = new Box2DCollider(); collider.setHalfSize(new Vector2f(CONSTANTS.GRID_WIDTH.getIntValue(), CONSTANTS.GRID_HEIGHT.getIntValue())); ob.addComponent(collider); ob.addComponent(new Ground()); if (i == 12 || i == 33) ob.addComponent(new BreakableBrick()); } editor.getComponent(MouseControls.class).setActiveGameObject(ob); } ImGui.popID(); ImVec2 lastButtonPos = ImGui.getItemRectMax(); float lastButtonX = lastButtonPos.x; float nextButtonX = lastButtonX + itemSpacing.x + sprite.getWidth() * 3; if (i + 1 < blocks.getNumSprites() && nextButtonX < windowX + windowSize.x - 30) { ImGui.sameLine(); } } @Override public void imGui() { ImGui.begin("Editor");
Window.getScene().setDefaultScene(JImGui.inputText("Scene Name", Window.getScene().getDefaultScene()));
7
2023-11-04 13:19:21+00:00
24k
RezaGooner/University-food-ordering
Frames/LoginFrame.java
[ { "identifier": "CustomRendererLoginHistory", "path": "Classes/Theme/CustomRendererLoginHistory.java", "snippet": "public class CustomRendererLoginHistory extends DefaultTableCellRenderer {\r\n private static final long serialVersionUID = 1L;\r\n\r\n @Override\r\n public Component getTableCellR...
import Classes.Theme.CustomRendererLoginHistory; import Classes.Theme.CustomRendererOrderCount; import Classes.Theme.StyledButtonUI; import Frames.Order.UniversitySelfRestaurant; import Frames.Profile.ChangePasswordFrame; import Frames.Profile.ForgotPassword; import Frames.Profile.NewUserFrame; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Scanner; import static Classes.Pathes.FilesPath.*; import static Classes.Theme.SoundEffect.*; import static Frames.Admin.AdminWindow.OpenAdminWindow;
20,830
idField.setBackground(Color.RED); idField.setForeground(Color.WHITE); passwordField.setBackground(Color.RED); passwordField.setForeground(Color.WHITE); } } return isValid; } private class LoginButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String id = idField.getText(); String password = new String(passwordField.getPassword()); statusLabel.setForeground(Color.black); idField.setBackground(Color.white); idField.setForeground(Color.black); passwordField.setBackground(Color.white); passwordField.setForeground(Color.black); if (isValidLogin(id, password)) { writeLog("موفق"); if (gender.equals("MALE")) { try { wellcomeSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null , "آقای " + name + " " + lastName + " خوش آمدید!"); dispose(); try { new UniversitySelfRestaurant(id, name + " " + lastName , organization); } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } } else { try { wellcomeSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null , "خانم " + name + " " + lastName + " خوش آمدید!"); dispose(); UniversitySelfRestaurant frame = null; try { frame = new UniversitySelfRestaurant(id, name + " " + lastName , organization); } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } frame.setVisible(true); } } } } private class ShowPasswordCheckboxListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (showPasswordCheckbox.isSelected()) { passwordField.setEchoChar((char) 0); } else { passwordField.setEchoChar('\u25cf'); } } } public static void writeLog(String message) { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date dateTime = new Date(); String datetime = dateTime.toString(); try { FileWriter writer = new FileWriter(LogPath, true); writer.write(idField.getText() + " , " + datetime + " , " + message + "\n"); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public void showLoginHistory() throws UnsupportedAudioFileException, LineUnavailableException, IOException { String input = (JOptionPane.showInputDialog(null , "لطفا کد دانشجویی خود را وارد کنید")); boolean isFind = false; String[] columnNames = {" تاریخ ", " نتیجه ورود "}; ArrayList<Object[]> dataList = new ArrayList<>(); Scanner scanner; try { scanner = new Scanner(new File(LogPath)); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] fields = line.split(" , "); if (fields[0].equals(input)) { String datetime = fields[1]; String result = fields[2]; dataList.add(new Object[]{datetime, result}); isFind = true; } } scanner.close(); } catch (FileNotFoundException e) { errorSound(); JOptionPane.showMessageDialog(null , " خطا در خواندن فایل " + e.getMessage() , "خطا !" , JOptionPane.ERROR_MESSAGE); } if (isFind) { Object[][] data = new Object[dataList.size()][]; for (int i = 0; i < dataList.size(); i++) { data[i] = dataList.get(i); } JTable table = new JTable(data, columnNames); table.setBackground(colorBackground);
package Frames; /* این کد یک فریم ورود به برنامه است که به کاربران اجازه می‌دهد شماره دانشجویی و رمز عبور خود را وارد کنند و سپس توسط برنامه بررسی شود که این اطلاعات معتبر هستند یا خیر. برای بررسی صحت اطلاعات، برنامه از یک فایل متنی استفاده می‌کند که شماره دانشجویی و رمز عبور کاربران را در خود نگه می‌دارد. در صورتی که اطلاعات وارد شده توسط کاربر با اطلاعات موجود در فایل مطابقت داشته باشد، کاربر به صفحه اصلی برنامه برای سفارش غذا هدایت می‌شود. در غیر این صورت، پیام خطا به کاربر نمایش داده می‌شود و از کاربر خواسته می‌شود تا اطلاعات خود را بررسی کرده و مجدداً وارد کند یا در صورت لزوم، از طریق گزینه هایی که برای او نمایش داده می‌شود، اقدام به بازیابی رمز عبور یا ساخت حساب جدید کند. */ public class LoginFrame extends JFrame { public static boolean isNumeric(String str) { if (str == null || str.length() == 0) { return false; } try { Long.parseLong(str); } catch (NumberFormatException nfe) { return false; } return true; } private static JTextField idField; private final JPasswordField passwordField; private final JLabel statusLabel; private final JCheckBox showPasswordCheckbox; private String name , lastName , gender , organization; public static Color colorButton = new Color(255,255,255); public static Color colorBackground = new Color(241,255,85); private String tempID; public LoginFrame() { setTitle("ورود"); setIconImage(icon.getImage()); setSize(375, 175); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setBackground(colorBackground); JLabel idLabel = new JLabel(": شماره دانشجویی"); idLabel.setHorizontalAlignment(SwingConstants.CENTER); idField = new JTextField(10); JLabel passwordLabel = new JLabel(": کلمـــه عبــور"); passwordLabel.setHorizontalAlignment(SwingConstants.CENTER); passwordField = new JPasswordField(10); passwordField.setEchoChar('\u25cf'); showPasswordCheckbox = new JCheckBox("نمایش کلمه عبور"); showPasswordCheckbox.setBackground(colorBackground); JButton loginButton = new JButton("ورود"); loginButton.setUI(new StyledButtonUI()); loginButton.setBackground(colorButton); statusLabel = new JLabel(""); JPanel panel = new JPanel(new GridLayout(4, 1)); panel.setBackground(colorBackground); panel.add(idLabel); panel.add(idField); panel.add(passwordLabel); panel.add(passwordField); panel.add(showPasswordCheckbox); panel.add(loginButton); panel.add(statusLabel); JButton helpButton = new JButton("اطلاعیه ها"); panel.add(helpButton); helpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame subWindow = new JFrame(); setIconImage(icon.getImage()); subWindow.setTitle(""); subWindow.setSize(300, 200); subWindow.setVisible(true); try { FileReader fileReader = new FileReader(HelpPath); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); while ((line = bufferedReader.readLine()) != null) { if (line.equals("***")) { panel.add(new JSeparator(JSeparator.HORIZONTAL)); } else { JLabel label = new JLabel(line); label.setFont(new Font("Arial", Font.BOLD, 20)); label.setForeground(Color.RED); panel.add(label); } } JScrollPane scrollPane = new JScrollPane(panel); subWindow.add(scrollPane); bufferedReader.close(); } catch (IOException exception) { } JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(helpButton, BorderLayout.CENTER); panel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { subWindow.setVisible(true); } }); add(panel); FontMetrics fm = helpButton.getFontMetrics(helpButton.getFont()); int textWidth = fm.stringWidth(helpButton.getText()); int textHeight = fm.getHeight(); helpButton.setPreferredSize(new Dimension(textWidth, textHeight)); } }); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(colorButton); setJMenuBar(menuBar); JMenu menu = new JMenu("حساب کاربری"); menu.setBackground(colorButton); menuBar.add(menu); JMenuItem adminItem = new JMenuItem("ورود مدیریت"); adminItem.setBackground(colorButton); menu.add(adminItem); JMenuItem forgotItem = new JMenuItem("فراموشی رمز"); forgotItem.setBackground(colorButton); menu.add(forgotItem); JMenuItem changePassword = new JMenuItem("تغییر رمز"); changePassword.setBackground(colorButton); menu.add(changePassword); JMenuItem historyLoginButton = new JMenuItem("سابقه ورود"); historyLoginButton.setBackground(colorButton); menu.add(historyLoginButton); JMenuItem newUserItem = new JMenuItem("جدید"); newUserItem.setBackground(colorButton); menu.add(newUserItem); JMenuItem exitItem = new JMenuItem("خروج"); exitItem.setBackground(colorButton); menuBar.add(exitItem); adminItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { OpenAdminWindow(); } catch (Exception ex) { } } }); historyLoginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { showLoginHistory(); } catch (Exception ex) { } } }); changePassword.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); new ChangePasswordFrame(); } }); forgotItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); new ForgotPassword(); } }); newUserItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); new NewUserFrame(); } }); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(panel, "آیا خارج می شوید؟", "خروج", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) dispose(); } }); add(panel); loginButton.addActionListener(new LoginButtonListener()); showPasswordCheckbox.addActionListener(new ShowPasswordCheckboxListener()); setResizable(false); setVisible(true); } private boolean isValidLogin(String id, String password) { boolean isValid = false; if (id.length() == 0 ) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("لطفا شماره دانشجویی را وارد نمایید"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); }else if (! isNumeric(id) ) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("شماره دانشجویی باید فقط شامل عدد باشد"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); } else if (!isNumeric(id) || id.length() != 10) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("شماره دانشجویی باید 10 رقمی باشد"); statusLabel.setForeground(Color.red); idField.setBackground(Color.YELLOW); idField.setForeground(Color.black); } else if (password.length() == 0 ){ try { errorSound(); } catch (Exception ex) { } statusLabel.setText("لطفا کلمه عبور را وارد نمایید"); statusLabel.setForeground(Color.red); passwordField.setBackground(Color.YELLOW); passwordField.setForeground(Color.black); } else if ((password.length() < 8 )||(password.length() > 16) ) { try { errorSound(); } catch (Exception ex) { } statusLabel.setText("کلمه عبور باید بین 8 تا 16 کاراکتر باشد"); statusLabel.setForeground(Color.red); passwordField.setBackground(Color.YELLOW); passwordField.setForeground(Color.black); } else { try { BufferedReader reader = new BufferedReader(new FileReader(UserPassPath)); String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(","); tempID = parts[0] ; if (tempID.equals(id) && parts[1].equals(password)) { name = parts[2]; lastName = parts[3]; gender = parts[4]; organization = parts[6]; isValid = true; break; } } reader.close(); } catch (IOException e) { try { errorSound(); } catch (Exception ex) { } } if (!isValid) { try { errorSound(); } catch (Exception ex) { } writeLog("ناموفق"); statusLabel.setText("شماره دانشجویی یا کلمه عبور اشتباه است"); statusLabel.setForeground(Color.red); Object[] options = { "خیر", "بله","ساخت حساب کاربری جدید"}; int noFoundUser = JOptionPane.showOptionDialog(this,"کاربری با این اطلاعات یافت نشد.\nآیا مایل هستید رمز خود را بازیابی کنید؟" , "خروج", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null , options , options[0]); if (noFoundUser == JOptionPane.NO_OPTION){ dispose(); new ForgotPassword(); } else if (noFoundUser == JOptionPane.CANCEL_OPTION){ dispose(); NewUserFrame frame = new NewUserFrame(); frame.setVisible(true); } idField.setBackground(Color.RED); idField.setForeground(Color.WHITE); passwordField.setBackground(Color.RED); passwordField.setForeground(Color.WHITE); } } return isValid; } private class LoginButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String id = idField.getText(); String password = new String(passwordField.getPassword()); statusLabel.setForeground(Color.black); idField.setBackground(Color.white); idField.setForeground(Color.black); passwordField.setBackground(Color.white); passwordField.setForeground(Color.black); if (isValidLogin(id, password)) { writeLog("موفق"); if (gender.equals("MALE")) { try { wellcomeSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null , "آقای " + name + " " + lastName + " خوش آمدید!"); dispose(); try { new UniversitySelfRestaurant(id, name + " " + lastName , organization); } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } } else { try { wellcomeSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null , "خانم " + name + " " + lastName + " خوش آمدید!"); dispose(); UniversitySelfRestaurant frame = null; try { frame = new UniversitySelfRestaurant(id, name + " " + lastName , organization); } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } frame.setVisible(true); } } } } private class ShowPasswordCheckboxListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (showPasswordCheckbox.isSelected()) { passwordField.setEchoChar((char) 0); } else { passwordField.setEchoChar('\u25cf'); } } } public static void writeLog(String message) { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date dateTime = new Date(); String datetime = dateTime.toString(); try { FileWriter writer = new FileWriter(LogPath, true); writer.write(idField.getText() + " , " + datetime + " , " + message + "\n"); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public void showLoginHistory() throws UnsupportedAudioFileException, LineUnavailableException, IOException { String input = (JOptionPane.showInputDialog(null , "لطفا کد دانشجویی خود را وارد کنید")); boolean isFind = false; String[] columnNames = {" تاریخ ", " نتیجه ورود "}; ArrayList<Object[]> dataList = new ArrayList<>(); Scanner scanner; try { scanner = new Scanner(new File(LogPath)); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] fields = line.split(" , "); if (fields[0].equals(input)) { String datetime = fields[1]; String result = fields[2]; dataList.add(new Object[]{datetime, result}); isFind = true; } } scanner.close(); } catch (FileNotFoundException e) { errorSound(); JOptionPane.showMessageDialog(null , " خطا در خواندن فایل " + e.getMessage() , "خطا !" , JOptionPane.ERROR_MESSAGE); } if (isFind) { Object[][] data = new Object[dataList.size()][]; for (int i = 0; i < dataList.size(); i++) { data[i] = dataList.get(i); } JTable table = new JTable(data, columnNames); table.setBackground(colorBackground);
table.setDefaultRenderer(Object.class, new CustomRendererLoginHistory());
0
2023-11-03 08:35:22+00:00
24k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/main/KifParser.java
[ { "identifier": "GameAnalyser", "path": "src/main/java/com/chadfield/shogiexplorer/objects/GameAnalyser.java", "snippet": "public class GameAnalyser {\n\n private Process process;\n private OutputStream stdin;\n private BufferedReader bufferedReader;\n private String lastScore = \"\";\n p...
import com.chadfield.shogiexplorer.objects.GameAnalyser; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.LinkedList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import com.chadfield.shogiexplorer.objects.Board; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.objects.Coordinate; import com.chadfield.shogiexplorer.objects.Game; import com.chadfield.shogiexplorer.objects.Koma; import com.chadfield.shogiexplorer.objects.Notation; import com.chadfield.shogiexplorer.objects.Position; import com.chadfield.shogiexplorer.utils.NotationUtils; import com.chadfield.shogiexplorer.utils.ParserUtils; import com.ibm.icu.text.Transliterator; import java.io.StringReader; import java.nio.charset.Charset; import java.nio.charset.MalformedInputException; import java.nio.charset.StandardCharsets; import java.util.List;
17,890
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.main; public class KifParser { private static final String DATE = "開始日時:"; private static final String PLACE = "場所:"; private static final String TIME_LIMIT = "持ち時間:"; private static final String TOURNAMENT = "棋戦:"; private static final String SENTE = "先手:"; private static final String GOTE = "後手:"; private static final String MOVE_HEADER = "手数----指手---------消費時間-"; private static final String MULTI_WHITESPACE = "\\s+|\\u3000"; private static final String HANDICAP = "手合割:"; private KifParser() { throw new IllegalStateException("Utility class"); }
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.main; public class KifParser { private static final String DATE = "開始日時:"; private static final String PLACE = "場所:"; private static final String TIME_LIMIT = "持ち時間:"; private static final String TOURNAMENT = "棋戦:"; private static final String SENTE = "先手:"; private static final String GOTE = "後手:"; private static final String MOVE_HEADER = "手数----指手---------消費時間-"; private static final String MULTI_WHITESPACE = "\\s+|\\u3000"; private static final String HANDICAP = "手合割:"; private KifParser() { throw new IllegalStateException("Utility class"); }
public static Game parseKif(DefaultListModel<String> moveListModel, File kifFile, String clipboardStr, boolean shiftFile, List<List<Position>> analysisPositionList) throws IOException {
4
2023-11-08 09:24:57+00:00
24k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/config/strategy/login/AbstractLoginStrategy.java
[ { "identifier": "LoginAboutAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/LoginAboutAdapt.java", "snippet": "public class LoginAboutAdapt {\n\n public static final int USE_NAME_LENGTH = 8;\n\n /**\n * 构造token信息类\n *\n * @param saTokenInfo s...
import cn.dev33.satoken.secure.SaSecureUtil; import cn.dev33.satoken.stp.SaLoginModel; import cn.dev33.satoken.stp.StpUtil; import com.qingmeng.config.adapt.LoginAboutAdapt; import com.qingmeng.constant.RedisConstant; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dto.login.LoginParamDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.enums.system.BannedEnum; import com.qingmeng.service.SysUserService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.RedisUtils; import com.qingmeng.valid.AccountGroup; import com.qingmeng.vo.login.TokenInfoVO; import org.springframework.stereotype.Component; import javax.annotation.Resource;
19,621
package com.qingmeng.config.strategy.login; /** * @author 清梦 * @version 1.0.0 * @Description 登陆抽象实现类 * @createTime 2023年11月10日 22:41:00 */ @Component public abstract class AbstractLoginStrategy implements LoginStrategy{ @Resource private SysUserService sysUserService; /** * 校验参数 * * @param loginParamDTO 登陆参数 * @author qingmeng * @createTime: 2023/11/11 11:16:16 */ protected void checkParam(LoginParamDTO loginParamDTO){ AssertUtils.validateEntity(loginParamDTO,true, AccountGroup.class);
package com.qingmeng.config.strategy.login; /** * @author 清梦 * @version 1.0.0 * @Description 登陆抽象实现类 * @createTime 2023年11月10日 22:41:00 */ @Component public abstract class AbstractLoginStrategy implements LoginStrategy{ @Resource private SysUserService sysUserService; /** * 校验参数 * * @param loginParamDTO 登陆参数 * @author qingmeng * @createTime: 2023/11/11 11:16:16 */ protected void checkParam(LoginParamDTO loginParamDTO){ AssertUtils.validateEntity(loginParamDTO,true, AccountGroup.class);
String captchaCode = RedisUtils.get(RedisConstant.CAPTCHA_CODE_KEY + loginParamDTO.getCodeId());
1
2023-11-07 16:04:55+00:00
24k
Griefed/AddEmAll
common/src/main/java/de/griefed/addemall/CommonClass.java
[ { "identifier": "GeneratedModBlocks", "path": "common/src/main/java/de/griefed/addemall/block/GeneratedModBlocks.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GeneratedModBlocks {\n public static final RegistrationProvider<Block> BLOCKS = RegistrationProvider.get(Registry.BLOCK_REGIS...
import de.griefed.addemall.block.GeneratedModBlocks; import de.griefed.addemall.item.GeneratedModItems; import de.griefed.addemall.platform.Services; import net.minecraft.network.chat.Component; import net.minecraft.world.food.FoodProperties; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import java.util.List;
19,674
package de.griefed.addemall; // This class is part of the common project meaning it is shared between all supported loaders. Code written here can only // import and access the vanilla codebase, libraries used by vanilla, and optionally third party libraries that provide // common compatible binaries. This means common code can not directly use loader specific concepts such as Forge events // however it will be compatible with all supported mod loaders. public class CommonClass { // The loader specific projects are able to import and use any code from the common project. This allows you to // write the majority of your code here and load it from your loader specific projects. This example has some // code that gets invoked by the entry point of the loader specific projects. public static void init() {
package de.griefed.addemall; // This class is part of the common project meaning it is shared between all supported loaders. Code written here can only // import and access the vanilla codebase, libraries used by vanilla, and optionally third party libraries that provide // common compatible binaries. This means common code can not directly use loader specific concepts such as Forge events // however it will be compatible with all supported mod loaders. public class CommonClass { // The loader specific projects are able to import and use any code from the common project. This allows you to // write the majority of your code here and load it from your loader specific projects. This example has some // code that gets invoked by the entry point of the loader specific projects. public static void init() {
Constants.LOG.info("Hello from Common init on {}! we are currently in a {} environment!", Services.PLATFORM.getPlatformName(), Services.PLATFORM.getEnvironmentName());
2
2023-11-06 12:50:10+00:00
24k
dingodb/dingo-expr
test/src/test/java/io/dingodb/expr/test/cases/EvalConstProvider.java
[ { "identifier": "Types", "path": "runtime/src/main/java/io/dingodb/expr/runtime/type/Types.java", "snippet": "public final class Types {\n public static final NullType NULL = new NullType();\n public static final IntType INT = new IntType();\n public static final LongType LONG = new LongType();...
import com.google.common.collect.ImmutableMap; import io.dingodb.expr.runtime.type.Types; import io.dingodb.expr.runtime.utils.DateTimeUtils; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static io.dingodb.expr.runtime.expr.Exprs.ABS; import static io.dingodb.expr.runtime.expr.Exprs.ABS_C; import static io.dingodb.expr.runtime.expr.Exprs.ACOS; import static io.dingodb.expr.runtime.expr.Exprs.ADD; import static io.dingodb.expr.runtime.expr.Exprs.AND; import static io.dingodb.expr.runtime.expr.Exprs.AND_FUN; import static io.dingodb.expr.runtime.expr.Exprs.ARRAY; import static io.dingodb.expr.runtime.expr.Exprs.ASIN; import static io.dingodb.expr.runtime.expr.Exprs.ATAN; import static io.dingodb.expr.runtime.expr.Exprs.CASE; import static io.dingodb.expr.runtime.expr.Exprs.CEIL; import static io.dingodb.expr.runtime.expr.Exprs.CHAR_LENGTH; import static io.dingodb.expr.runtime.expr.Exprs.CONCAT; import static io.dingodb.expr.runtime.expr.Exprs.COS; import static io.dingodb.expr.runtime.expr.Exprs.COSH; import static io.dingodb.expr.runtime.expr.Exprs.DATEDIFF; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.DATE_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.DIV; import static io.dingodb.expr.runtime.expr.Exprs.EQ; import static io.dingodb.expr.runtime.expr.Exprs.EXP; import static io.dingodb.expr.runtime.expr.Exprs.FLOOR; import static io.dingodb.expr.runtime.expr.Exprs.FORMAT; import static io.dingodb.expr.runtime.expr.Exprs.FROM_UNIXTIME; import static io.dingodb.expr.runtime.expr.Exprs.GE; import static io.dingodb.expr.runtime.expr.Exprs.GT; import static io.dingodb.expr.runtime.expr.Exprs.HEX; import static io.dingodb.expr.runtime.expr.Exprs.INDEX; import static io.dingodb.expr.runtime.expr.Exprs.IS_FALSE; import static io.dingodb.expr.runtime.expr.Exprs.IS_NULL; import static io.dingodb.expr.runtime.expr.Exprs.IS_TRUE; import static io.dingodb.expr.runtime.expr.Exprs.LE; import static io.dingodb.expr.runtime.expr.Exprs.LEFT; import static io.dingodb.expr.runtime.expr.Exprs.LIST; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE2; import static io.dingodb.expr.runtime.expr.Exprs.LOCATE3; import static io.dingodb.expr.runtime.expr.Exprs.LOG; import static io.dingodb.expr.runtime.expr.Exprs.LOWER; import static io.dingodb.expr.runtime.expr.Exprs.LT; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.LTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.MAP; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES; import static io.dingodb.expr.runtime.expr.Exprs.MATCHES_NC; import static io.dingodb.expr.runtime.expr.Exprs.MAX; import static io.dingodb.expr.runtime.expr.Exprs.MID2; import static io.dingodb.expr.runtime.expr.Exprs.MID3; import static io.dingodb.expr.runtime.expr.Exprs.MIN; import static io.dingodb.expr.runtime.expr.Exprs.MOD; import static io.dingodb.expr.runtime.expr.Exprs.MUL; import static io.dingodb.expr.runtime.expr.Exprs.NE; import static io.dingodb.expr.runtime.expr.Exprs.NEG; import static io.dingodb.expr.runtime.expr.Exprs.NOT; import static io.dingodb.expr.runtime.expr.Exprs.OR; import static io.dingodb.expr.runtime.expr.Exprs.OR_FUN; import static io.dingodb.expr.runtime.expr.Exprs.POS; import static io.dingodb.expr.runtime.expr.Exprs.POW; import static io.dingodb.expr.runtime.expr.Exprs.REPEAT; import static io.dingodb.expr.runtime.expr.Exprs.REPLACE; import static io.dingodb.expr.runtime.expr.Exprs.REVERSE; import static io.dingodb.expr.runtime.expr.Exprs.RIGHT; import static io.dingodb.expr.runtime.expr.Exprs.ROUND1; import static io.dingodb.expr.runtime.expr.Exprs.ROUND2; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM1; import static io.dingodb.expr.runtime.expr.Exprs.RTRIM2; import static io.dingodb.expr.runtime.expr.Exprs.SIN; import static io.dingodb.expr.runtime.expr.Exprs.SINH; import static io.dingodb.expr.runtime.expr.Exprs.SLICE; import static io.dingodb.expr.runtime.expr.Exprs.SUB; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR2; import static io.dingodb.expr.runtime.expr.Exprs.SUBSTR3; import static io.dingodb.expr.runtime.expr.Exprs.TAN; import static io.dingodb.expr.runtime.expr.Exprs.TANH; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIMESTAMP_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT1; import static io.dingodb.expr.runtime.expr.Exprs.TIME_FORMAT2; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_ARRAY_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BOOL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_BYTES; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DATE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DECIMAL; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_DOUBLE; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_FLOAT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_INT_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_LIST_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG; import static io.dingodb.expr.runtime.expr.Exprs.TO_LONG_C; import static io.dingodb.expr.runtime.expr.Exprs.TO_STRING; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIME; import static io.dingodb.expr.runtime.expr.Exprs.TO_TIMESTAMP; import static io.dingodb.expr.runtime.expr.Exprs.TRIM1; import static io.dingodb.expr.runtime.expr.Exprs.TRIM2; import static io.dingodb.expr.runtime.expr.Exprs.UNIX_TIMESTAMP1; import static io.dingodb.expr.runtime.expr.Exprs.UPPER; import static io.dingodb.expr.runtime.expr.Exprs._CP1; import static io.dingodb.expr.runtime.expr.Exprs._CP2; import static io.dingodb.expr.runtime.expr.Exprs._CTF; import static io.dingodb.expr.runtime.expr.Exprs.op; import static io.dingodb.expr.runtime.expr.Exprs.val; import static io.dingodb.expr.runtime.expr.Val.NULL; import static io.dingodb.expr.runtime.expr.Val.NULL_BOOL; import static io.dingodb.expr.runtime.expr.Val.NULL_BYTES; import static io.dingodb.expr.runtime.expr.Val.NULL_DATE; import static io.dingodb.expr.runtime.expr.Val.NULL_DECIMAL; import static io.dingodb.expr.runtime.expr.Val.NULL_DOUBLE; import static io.dingodb.expr.runtime.expr.Val.NULL_FLOAT; import static io.dingodb.expr.runtime.expr.Val.NULL_INT; import static io.dingodb.expr.runtime.expr.Val.NULL_LONG; import static io.dingodb.expr.runtime.expr.Val.NULL_STRING; import static io.dingodb.expr.runtime.expr.Val.NULL_TIME; import static io.dingodb.expr.runtime.expr.Val.NULL_TIMESTAMP; import static io.dingodb.expr.test.ExprsHelper.bytes; import static io.dingodb.expr.test.ExprsHelper.date; import static io.dingodb.expr.test.ExprsHelper.dec; import static io.dingodb.expr.test.ExprsHelper.sec; import static io.dingodb.expr.test.ExprsHelper.time; import static io.dingodb.expr.test.ExprsHelper.ts; import static org.junit.jupiter.params.provider.Arguments.arguments;
15,827
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.test.cases; public class EvalConstProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( // Values arguments(val(1), 1), arguments(val(2L), 2L), arguments(val(3.3f), 3.3f), arguments(val(4.4), 4.4), arguments(val(true), true), arguments(val(false), false), arguments(dec(5.5), BigDecimal.valueOf(5.5)), arguments(val("abc"), "abc"), arguments(bytes("123"), "123".getBytes(StandardCharsets.UTF_8)), arguments(date(1L), new Date(sec(1L))), arguments(time(2L), new Time(sec(2L))), arguments(ts(3L), new Timestamp(sec(3L))), arguments(val(null), null), // Castings arguments(op(TO_INT, 1), 1), arguments(op(TO_INT, 1L), 1), arguments(op(TO_INT_C, 1L), 1), arguments(op(TO_INT, 1.4f), 1), arguments(op(TO_INT_C, 1.4f), 1), arguments(op(TO_INT, 1.5f), 2), arguments(op(TO_INT_C, 1.5f), 2), arguments(op(TO_INT, 1.4), 1), arguments(op(TO_INT, 1.5), 2), arguments(op(TO_INT, true), 1), arguments(op(TO_INT, false), 0), arguments(op(TO_INT, dec(1.4)), 1), arguments(op(TO_INT_C, dec(1.4)), 1), arguments(op(TO_INT, dec(1.5)), 2), arguments(op(TO_INT_C, dec(1.5)), 2), arguments(op(TO_INT, "10"), 10), arguments(op(TO_LONG, 1), 1L), arguments(op(TO_LONG, 1L), 1L), arguments(op(TO_LONG, 1.4f), 1L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.5f), 2L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.4), 1L), arguments(op(TO_LONG, 1.5), 2L), arguments(op(TO_LONG, true), 1L), arguments(op(TO_LONG, false), 0L), arguments(op(TO_LONG, dec(1.4)), 1L), arguments(op(TO_LONG, dec(1.5)), 2L), arguments(op(TO_LONG, "10"), 10L), arguments(op(TO_FLOAT, 1), 1.0f), arguments(op(TO_FLOAT, 1L), 1.0f), arguments(op(TO_FLOAT, 1.4f), 1.4f), arguments(op(TO_FLOAT, 1.4), 1.4f), arguments(op(TO_FLOAT, true), 1.0f), arguments(op(TO_FLOAT, false), 0.0f), arguments(op(TO_FLOAT, dec(1.4)), 1.4f), arguments(op(TO_FLOAT, "12.3"), 12.3f), arguments(op(TO_DOUBLE, 1), 1.0), arguments(op(TO_DOUBLE, 1L), 1.0), arguments(op(TO_DOUBLE, 1.4f), 1.4), arguments(op(TO_DOUBLE, 1.4), 1.4), arguments(op(TO_DOUBLE, true), 1.0), arguments(op(TO_DOUBLE, false), 0.0), arguments(op(TO_DOUBLE, dec(1.4)), 1.4), arguments(op(TO_DOUBLE, "12.3"), 12.3), arguments(op(TO_BOOL, 1), true), arguments(op(TO_BOOL, 0), false), arguments(op(TO_BOOL, 1L), true), arguments(op(TO_BOOL, 0L), false), arguments(op(TO_BOOL, 1.4f), true), arguments(op(TO_BOOL, 0.0f), false), arguments(op(TO_BOOL, 1.4), true), arguments(op(TO_BOOL, 0.0), false), arguments(op(TO_BOOL, true), true), arguments(op(TO_BOOL, false), false), arguments(op(TO_BOOL, val(BigDecimal.ONE)), true), arguments(op(TO_BOOL, val(BigDecimal.ZERO)), false), arguments(op(TO_DECIMAL, 1), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1L), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1.4f), BigDecimal.valueOf(1.4f)), arguments(op(TO_DECIMAL, 1.4), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, true), BigDecimal.ONE), arguments(op(TO_DECIMAL, false), BigDecimal.ZERO), arguments(op(TO_DECIMAL, dec(1.4)), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, "12.3"), BigDecimal.valueOf(12.3)), arguments(op(TO_STRING, 1), "1"), arguments(op(TO_STRING, 1L), "1"), arguments(op(TO_STRING, 1.4f), "1.4"), arguments(op(TO_STRING, 1.4), "1.4"), arguments(op(TO_STRING, true), "true"), arguments(op(TO_STRING, false), "false"), arguments(op(TO_STRING, dec(12.3)), "12.3"), arguments(op(TO_STRING, "abc"), "abc"), arguments(op(TO_BYTES, bytes("abc")), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_BYTES, "abc"), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_DATE, 1), new Date(sec(1L))), arguments(op(TO_DATE, 1L), new Date(sec(1L))), arguments(op(TO_DATE, "1970-01-01"), new Date(sec(0L))), arguments(op(TO_DATE, date(1L)), new Date(sec(1L))), arguments(op(TO_TIME, 1), new Time(sec(1L))), arguments(op(TO_TIME, 1L), new Time(sec(1L))), arguments(op(TO_TIME, "00:00:00"), new Time(sec(0L))), arguments(op(TO_TIME, time(1L)), new Time(sec(1L))),
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.test.cases; public class EvalConstProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( // Values arguments(val(1), 1), arguments(val(2L), 2L), arguments(val(3.3f), 3.3f), arguments(val(4.4), 4.4), arguments(val(true), true), arguments(val(false), false), arguments(dec(5.5), BigDecimal.valueOf(5.5)), arguments(val("abc"), "abc"), arguments(bytes("123"), "123".getBytes(StandardCharsets.UTF_8)), arguments(date(1L), new Date(sec(1L))), arguments(time(2L), new Time(sec(2L))), arguments(ts(3L), new Timestamp(sec(3L))), arguments(val(null), null), // Castings arguments(op(TO_INT, 1), 1), arguments(op(TO_INT, 1L), 1), arguments(op(TO_INT_C, 1L), 1), arguments(op(TO_INT, 1.4f), 1), arguments(op(TO_INT_C, 1.4f), 1), arguments(op(TO_INT, 1.5f), 2), arguments(op(TO_INT_C, 1.5f), 2), arguments(op(TO_INT, 1.4), 1), arguments(op(TO_INT, 1.5), 2), arguments(op(TO_INT, true), 1), arguments(op(TO_INT, false), 0), arguments(op(TO_INT, dec(1.4)), 1), arguments(op(TO_INT_C, dec(1.4)), 1), arguments(op(TO_INT, dec(1.5)), 2), arguments(op(TO_INT_C, dec(1.5)), 2), arguments(op(TO_INT, "10"), 10), arguments(op(TO_LONG, 1), 1L), arguments(op(TO_LONG, 1L), 1L), arguments(op(TO_LONG, 1.4f), 1L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.5f), 2L), arguments(op(TO_LONG_C, 1.4f), 1L), arguments(op(TO_LONG, 1.4), 1L), arguments(op(TO_LONG, 1.5), 2L), arguments(op(TO_LONG, true), 1L), arguments(op(TO_LONG, false), 0L), arguments(op(TO_LONG, dec(1.4)), 1L), arguments(op(TO_LONG, dec(1.5)), 2L), arguments(op(TO_LONG, "10"), 10L), arguments(op(TO_FLOAT, 1), 1.0f), arguments(op(TO_FLOAT, 1L), 1.0f), arguments(op(TO_FLOAT, 1.4f), 1.4f), arguments(op(TO_FLOAT, 1.4), 1.4f), arguments(op(TO_FLOAT, true), 1.0f), arguments(op(TO_FLOAT, false), 0.0f), arguments(op(TO_FLOAT, dec(1.4)), 1.4f), arguments(op(TO_FLOAT, "12.3"), 12.3f), arguments(op(TO_DOUBLE, 1), 1.0), arguments(op(TO_DOUBLE, 1L), 1.0), arguments(op(TO_DOUBLE, 1.4f), 1.4), arguments(op(TO_DOUBLE, 1.4), 1.4), arguments(op(TO_DOUBLE, true), 1.0), arguments(op(TO_DOUBLE, false), 0.0), arguments(op(TO_DOUBLE, dec(1.4)), 1.4), arguments(op(TO_DOUBLE, "12.3"), 12.3), arguments(op(TO_BOOL, 1), true), arguments(op(TO_BOOL, 0), false), arguments(op(TO_BOOL, 1L), true), arguments(op(TO_BOOL, 0L), false), arguments(op(TO_BOOL, 1.4f), true), arguments(op(TO_BOOL, 0.0f), false), arguments(op(TO_BOOL, 1.4), true), arguments(op(TO_BOOL, 0.0), false), arguments(op(TO_BOOL, true), true), arguments(op(TO_BOOL, false), false), arguments(op(TO_BOOL, val(BigDecimal.ONE)), true), arguments(op(TO_BOOL, val(BigDecimal.ZERO)), false), arguments(op(TO_DECIMAL, 1), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1L), BigDecimal.ONE), arguments(op(TO_DECIMAL, 1.4f), BigDecimal.valueOf(1.4f)), arguments(op(TO_DECIMAL, 1.4), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, true), BigDecimal.ONE), arguments(op(TO_DECIMAL, false), BigDecimal.ZERO), arguments(op(TO_DECIMAL, dec(1.4)), BigDecimal.valueOf(1.4)), arguments(op(TO_DECIMAL, "12.3"), BigDecimal.valueOf(12.3)), arguments(op(TO_STRING, 1), "1"), arguments(op(TO_STRING, 1L), "1"), arguments(op(TO_STRING, 1.4f), "1.4"), arguments(op(TO_STRING, 1.4), "1.4"), arguments(op(TO_STRING, true), "true"), arguments(op(TO_STRING, false), "false"), arguments(op(TO_STRING, dec(12.3)), "12.3"), arguments(op(TO_STRING, "abc"), "abc"), arguments(op(TO_BYTES, bytes("abc")), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_BYTES, "abc"), "abc".getBytes(StandardCharsets.UTF_8)), arguments(op(TO_DATE, 1), new Date(sec(1L))), arguments(op(TO_DATE, 1L), new Date(sec(1L))), arguments(op(TO_DATE, "1970-01-01"), new Date(sec(0L))), arguments(op(TO_DATE, date(1L)), new Date(sec(1L))), arguments(op(TO_TIME, 1), new Time(sec(1L))), arguments(op(TO_TIME, 1L), new Time(sec(1L))), arguments(op(TO_TIME, "00:00:00"), new Time(sec(0L))), arguments(op(TO_TIME, time(1L)), new Time(sec(1L))),
arguments(op(TO_TIMESTAMP, 1), new Timestamp(sec(1L))),
117
2023-11-04 08:43:49+00:00
24k
conductor-oss/conductor
grpc-server/src/main/java/com/netflix/conductor/grpc/server/service/TaskServiceImpl.java
[ { "identifier": "Task", "path": "common/src/main/java/com/netflix/conductor/common/metadata/tasks/Task.java", "snippet": "@ProtoMessage\npublic class Task {\n\n @ProtoEnum\n public enum Status {\n IN_PROGRESS(false, true, true),\n CANCELED(true, false, false),\n FAILED(true, f...
import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskExecLog; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.TaskSummary; import com.netflix.conductor.grpc.ProtoMapper; import com.netflix.conductor.grpc.SearchPb; import com.netflix.conductor.grpc.TaskServiceGrpc; import com.netflix.conductor.grpc.TaskServicePb; import com.netflix.conductor.proto.TaskPb; import com.netflix.conductor.service.ExecutionService; import com.netflix.conductor.service.TaskService; import io.grpc.Status; import io.grpc.stub.StreamObserver;
21,501
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.grpc.server.service; @Service("grpcTaskService") public class TaskServiceImpl extends TaskServiceGrpc.TaskServiceImplBase { private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class); private static final ProtoMapper PROTO_MAPPER = ProtoMapper.INSTANCE; private static final GRPCHelper GRPC_HELPER = new GRPCHelper(LOGGER); private static final int POLL_TIMEOUT_MS = 100; private static final int MAX_POLL_TIMEOUT_MS = 5000; private final TaskService taskService; private final int maxSearchSize; private final ExecutionService executionService; public TaskServiceImpl( ExecutionService executionService, TaskService taskService, @Value("${workflow.max.search.size:5000}") int maxSearchSize) { this.executionService = executionService; this.taskService = taskService; this.maxSearchSize = maxSearchSize; } @Override public void poll( TaskServicePb.PollRequest req, StreamObserver<TaskServicePb.PollResponse> response) { try {
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.grpc.server.service; @Service("grpcTaskService") public class TaskServiceImpl extends TaskServiceGrpc.TaskServiceImplBase { private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class); private static final ProtoMapper PROTO_MAPPER = ProtoMapper.INSTANCE; private static final GRPCHelper GRPC_HELPER = new GRPCHelper(LOGGER); private static final int POLL_TIMEOUT_MS = 100; private static final int MAX_POLL_TIMEOUT_MS = 5000; private final TaskService taskService; private final int maxSearchSize; private final ExecutionService executionService; public TaskServiceImpl( ExecutionService executionService, TaskService taskService, @Value("${workflow.max.search.size:5000}") int maxSearchSize) { this.executionService = executionService; this.taskService = taskService; this.maxSearchSize = maxSearchSize; } @Override public void poll( TaskServicePb.PollRequest req, StreamObserver<TaskServicePb.PollResponse> response) { try {
List<Task> tasks =
0
2023-12-08 06:06:09+00:00
24k
10cks/fofaEX
src/main/java/Main.java
[ { "identifier": "CommonExecute", "path": "src/main/java/plugins/CommonExecute.java", "snippet": "public class CommonExecute {\n\n public static JTable table = new JTable(); // 表格\n\n public static void exportTableToExcel(JTable table) {\n XSSFWorkbook workbook = new XSSFWorkbook();\n\n ...
import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import javax.swing.BorderFactory; import javax.swing.event.*; import java.awt.Color; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import org.apache.commons.text.StringEscapeUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import plugins.CommonExecute; import plugins.CommonTemplate; import plugins.FofaHack; import tableInit.HighlightRenderer; import tableInit.RightClickFunctions; import javax.swing.table.*; import javax.swing.text.Document; import javax.swing.undo.UndoManager; import static java.awt.BorderLayout.*; import static java.lang.Thread.sleep; import static plugins.CommonTemplate.saveTableData; import static plugins.CommonTemplate.switchTab; import static tableInit.GetjTableHeader.adjustColumnWidths; import static tableInit.GetjTableHeader.getjTableHeader; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors;
14,619
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径
public class Main { // 创建输入框 private static JTextField fofaUrl = createTextField("https://fofa.info"); private static JTextField fofaEmail = createTextField("当前版本不需要输入邮箱"); private static JTextField fofaKey = createTextField("请输入API key"); private static String rulesPath = "rules.txt"; private static String accountsPath = "accounts.json"; // 设置 field 规则 private static boolean hostMark = true; private static boolean ipMark = true; private static boolean portMark = true; private static boolean protocolMark = true; private static boolean titleMark = true; private static boolean domainMark = true; private static boolean linkMark = true; private static boolean icpMark = false; private static boolean cityMark = false; private static boolean countryMark = false; /* 下面未完成 */ private static boolean country_nameMark = false; private static boolean regionMark = false; private static boolean longitudeMark = false; private static boolean latitudeMark = false; private static boolean asNumberMark = false; private static boolean asOrganizationMark = false; private static boolean osMark = false; private static boolean serverMark = false; private static boolean jarmMark = false; private static boolean headerMark = false; private static boolean bannerMark = false; private static boolean baseProtocolMark = false; private static boolean certsIssuerOrgMark = false; private static boolean certsIssuerCnMark = false; private static boolean certsSubjectOrgMark = false; private static boolean certsSubjectCnMark = false; private static boolean tlsJa3sMark = false; private static boolean tlsVersionMark = false; private static boolean productMark = false; private static boolean productCategoryMark = false; private static boolean versionMark = false; private static boolean lastupdatetimeMark = false; private static boolean cnameMark = false; private static boolean iconHashMark = false; private static boolean certsValidMark = false; private static boolean cnameDomainMark = false; private static boolean bodyMark = false; private static boolean iconMark = false; private static boolean fidMark = false; private static boolean structinfoMark = false; private static boolean scrollPaneMark = true; // 标记 private static boolean exportButtonAdded = false; private static boolean timeAdded = false; private static JLabel timeLabel; private static int queryTotalNumber; private static int numberOfItems; private static int currentPage = 1; private static boolean setFull = true; private static int sizeSetting = 10000; private static boolean openFileMark = false; // 创建全局数据表 private static JTable table; // 在类的成员变量中创建弹出菜单 private static JPopupMenu popupMenu = new JPopupMenu(); private static JMenuItem itemSelectColumn = new JMenuItem("选择当前整列"); private static JMenuItem itemDeselectColumn = new JMenuItem("取消选择整列"); private static JMenuItem itemOpenLink = new JMenuItem("打开链接"); static JMenuItem itemCopy = new JMenuItem("复制"); private static JMenuItem itemSearch = new JMenuItem("表格搜索"); private static File lastOpenedPath; // 添加一个成员变量来保存上次打开的文件路径
static TableCellRenderer highlightRenderer = new HighlightRenderer();
3
2023-12-07 13:46:27+00:00
24k
kaifangqian/open-sign
src/main/java/com/resrun/controller/OpenSignController.java
[ { "identifier": "SignTypeEnum", "path": "src/main/java/com/resrun/enums/SignTypeEnum.java", "snippet": "public enum SignTypeEnum {\n\n\n POSITION(1,\"位置签署\"),\n KEYWORD(2,\"关键字签署\"),\n\n ;\n\n private String msg;\n private Integer code;\n\n\n SignTypeEnum(Integer code,String msg){\n ...
import com.resrun.enums.SignTypeEnum; import com.resrun.service.pojo.CertificateProperty; import com.resrun.service.pojo.GenerateCertificateInfo; import com.resrun.service.pojo.RealPositionProperty; import com.resrun.service.pojo.SourcePositionProperty; import com.resrun.service.cert.CertService; import com.resrun.service.image.EntSealClipService; import com.resrun.service.image.EntSealGenerateService; import com.resrun.service.pdf.CalculatePositionService; import com.resrun.service.pdf.SignService; import com.resrun.service.verify.SignVerifyService; import com.resrun.utils.Base64; import com.resrun.controller.vo.base.Result; import com.resrun.controller.vo.request.*; import com.resrun.controller.vo.response.SealResponse; import com.resrun.controller.vo.response.SignResponse; import com.resrun.controller.vo.response.VerifyResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import java.io.*; import java.util.ArrayList; import java.util.List;
14,559
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST) public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){ if(request.getImage() == null || request.getImage().length() == 0){ return Result.error("图片数据为空",null); } byte[] decode = Base64.decode(request.getImage()); if(decode == null || decode.length == 0){ return Result.error("签章制作失败",null); } byte[] entSealByte = entSealClipService.clip(decode, request.getColorRange()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("生成企业签章-参数生成") @RequestMapping(value = "/generate/seal",method = RequestMethod.POST) public Result<SealResponse> seal(@RequestBody GenerateSealRequest request){ if(request == null || request.getMiddleText() == null || request.getTopText() == null){ return Result.error("参数缺失",null) ; } byte[] entSealByte = entSealGenerateService.generateEntSeal(request.getTopText(), request.getMiddleText()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("签署") @RequestMapping(value = "/sign",method = RequestMethod.POST) public Result<SignResponse> sign(@RequestBody SignRequest request){ String fileName = "开源工具版说明.pdf" ; byte[] signFileBytes = null ; byte[] entSealBytes = null ; byte[] personalBytes = null ; CertificateProperty entCert = null ; CertificateProperty personalCert = null ; List<RealPositionProperty> entPositionList = null; List<RealPositionProperty> personalPositionList = null; int entSealWidth = 200 ; int entSealHeight = 200 ; int personalSealWidth = 150 ; int personalSealHeight = 70 ; //获取本地签署文件 try { signFileBytes = getResourceFiles(fileName); } catch (Exception e) { e.printStackTrace(); } if(signFileBytes == null){ return Result.error("签署失败",null); } //生成企业证书和个人证书 try { if(request.getEntName() != null && request.getEntName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getEntName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ entCert = new CertificateProperty(); entCert.setCertType("PKCS12"); entCert.setCertFile(generateCertificateInfo.getPfx()); entCert.setPassword(generateCertificateInfo.getPassword()); } if(entCert == null){ return Result.error("签署失败",null); } } if(request.getPersonalName() != null && request.getPersonalName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getPersonalName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ personalCert = new CertificateProperty(); personalCert.setCertType("PKCS12"); personalCert.setCertFile(generateCertificateInfo.getPfx()); personalCert.setPassword(generateCertificateInfo.getPassword()); } if(personalCert == null){ return Result.error("签署失败",null); } } } catch (Exception e) { e.printStackTrace(); } //生成企业签章和个人签章 if(request.getEntSeal() != null){ entSealBytes = Base64.decode(request.getEntSeal()); } if(request.getPersonalSeal() != null){ personalBytes = Base64.decode(request.getPersonalSeal()); } //计算企业签署位置和个人签署位置 if(SignTypeEnum.POSITION.getCode().equals(request.getSignType())){ if((request.getEntPositionList() == null || request.getEntPositionList().size() == 0 ) && (request.getPersonalPositionList() == null || request.getPersonalPositionList().size() == 0)){ return Result.error("签署失败",null); } //计算企业签署位置 if(request.getEntPositionList() != null && request.getEntPositionList().size() > 0){
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST) public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){ if(request.getImage() == null || request.getImage().length() == 0){ return Result.error("图片数据为空",null); } byte[] decode = Base64.decode(request.getImage()); if(decode == null || decode.length == 0){ return Result.error("签章制作失败",null); } byte[] entSealByte = entSealClipService.clip(decode, request.getColorRange()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("生成企业签章-参数生成") @RequestMapping(value = "/generate/seal",method = RequestMethod.POST) public Result<SealResponse> seal(@RequestBody GenerateSealRequest request){ if(request == null || request.getMiddleText() == null || request.getTopText() == null){ return Result.error("参数缺失",null) ; } byte[] entSealByte = entSealGenerateService.generateEntSeal(request.getTopText(), request.getMiddleText()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("签署") @RequestMapping(value = "/sign",method = RequestMethod.POST) public Result<SignResponse> sign(@RequestBody SignRequest request){ String fileName = "开源工具版说明.pdf" ; byte[] signFileBytes = null ; byte[] entSealBytes = null ; byte[] personalBytes = null ; CertificateProperty entCert = null ; CertificateProperty personalCert = null ; List<RealPositionProperty> entPositionList = null; List<RealPositionProperty> personalPositionList = null; int entSealWidth = 200 ; int entSealHeight = 200 ; int personalSealWidth = 150 ; int personalSealHeight = 70 ; //获取本地签署文件 try { signFileBytes = getResourceFiles(fileName); } catch (Exception e) { e.printStackTrace(); } if(signFileBytes == null){ return Result.error("签署失败",null); } //生成企业证书和个人证书 try { if(request.getEntName() != null && request.getEntName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getEntName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ entCert = new CertificateProperty(); entCert.setCertType("PKCS12"); entCert.setCertFile(generateCertificateInfo.getPfx()); entCert.setPassword(generateCertificateInfo.getPassword()); } if(entCert == null){ return Result.error("签署失败",null); } } if(request.getPersonalName() != null && request.getPersonalName().length() > 0){ String subject = "C=CN,ST=北京,L=北京,O=开放签 CA,OU=产品部,CN=开放签@" + request.getPersonalName(); GenerateCertificateInfo generateCertificateInfo = certService.generateCertificate(null, subject, 10); if(generateCertificateInfo != null){ personalCert = new CertificateProperty(); personalCert.setCertType("PKCS12"); personalCert.setCertFile(generateCertificateInfo.getPfx()); personalCert.setPassword(generateCertificateInfo.getPassword()); } if(personalCert == null){ return Result.error("签署失败",null); } } } catch (Exception e) { e.printStackTrace(); } //生成企业签章和个人签章 if(request.getEntSeal() != null){ entSealBytes = Base64.decode(request.getEntSeal()); } if(request.getPersonalSeal() != null){ personalBytes = Base64.decode(request.getPersonalSeal()); } //计算企业签署位置和个人签署位置 if(SignTypeEnum.POSITION.getCode().equals(request.getSignType())){ if((request.getEntPositionList() == null || request.getEntPositionList().size() == 0 ) && (request.getPersonalPositionList() == null || request.getPersonalPositionList().size() == 0)){ return Result.error("签署失败",null); } //计算企业签署位置 if(request.getEntPositionList() != null && request.getEntPositionList().size() > 0){
List<SourcePositionProperty> convert = convert(request.getEntPositionList());
4
2023-12-14 06:53:32+00:00
24k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/ui/fragments/ColorsFragment.java
[ { "identifier": "MANUAL_OVERRIDE_COLORS", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MANUAL_OVERRIDE_COLORS = \"manualOverrideColors\";" }, { "identifier": "MONET_ACCENT_SATURATION", "path": "app/src/main/java/com/drdisagr...
import static com.drdisagree.colorblendr.common.Const.MANUAL_OVERRIDE_COLORS; import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_LAST_UPDATED; import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR; import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR_ENABLED; import static com.drdisagree.colorblendr.common.Const.MONET_STYLE; import static com.drdisagree.colorblendr.common.Const.WALLPAPER_COLOR_LIST; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.common.Const; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.databinding.FragmentColorsBinding; import com.drdisagree.colorblendr.ui.viewmodels.SharedViewModel; import com.drdisagree.colorblendr.ui.views.WallColorPreview; import com.drdisagree.colorblendr.utils.ColorSchemeUtil; import com.drdisagree.colorblendr.utils.ColorUtil; import com.drdisagree.colorblendr.utils.MiscUtil; import com.drdisagree.colorblendr.utils.OverlayManager; import com.drdisagree.colorblendr.utils.WallpaperUtil; import com.google.android.material.snackbar.Snackbar; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import me.jfenn.colorpickerdialog.dialogs.ColorPickerDialog; import me.jfenn.colorpickerdialog.views.picker.ImagePickerView;
18,524
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel;
package com.drdisagree.colorblendr.ui.fragments; @SuppressWarnings("deprecation") public class ColorsFragment extends Fragment { private static final String TAG = ColorsFragment.class.getSimpleName(); private FragmentColorsBinding binding; private int[] monetSeedColor; private LinearLayout[] colorTableRows; private SharedViewModel sharedViewModel;
private final String[][] colorNames = ColorUtil.getColorNames();
16
2023-12-06 13:20:16+00:00
24k
lxs2601055687/contextAdminRuoYi
ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java
[ { "identifier": "Constants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java", "snippet": "public interface Constants {\n\n /**\n * UTF-8 字符集\n */\n String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n String GBK = \"GBK\";\n\n /**\n * www主域...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.lang.Dict; import cn.hutool.core.util.ObjectUtil; import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.JsonUtils; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.file.FileUtils; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; import com.ruoyi.generator.mapper.GenTableColumnMapper; import com.ruoyi.generator.mapper.GenTableMapper; import com.ruoyi.generator.util.GenUtils; import com.ruoyi.generator.util.VelocityInitializer; import com.ruoyi.generator.util.VelocityUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
20,017
package com.ruoyi.generator.service; /** * 业务 服务层实现 * * @author Lion Li */ @DS("#header.datasource") @Slf4j @RequiredArgsConstructor @Service public class GenTableServiceImpl implements IGenTableService { private final GenTableMapper baseMapper; private final GenTableColumnMapper genTableColumnMapper; private final IdentifierGenerator identifierGenerator; /** * 查询业务字段列表 * * @param tableId 业务字段编号 * @return 业务字段集合 */ @Override public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) { return genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>() .eq(GenTableColumn::getTableId, tableId) .orderByAsc(GenTableColumn::getSort)); } /** * 查询业务信息 * * @param id 业务ID * @return 业务信息 */ @Override public GenTable selectGenTableById(Long id) { GenTable genTable = baseMapper.selectGenTableById(id); setTableFromOptions(genTable); return genTable; } @Override public TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery) { Page<GenTable> page = baseMapper.selectPage(pageQuery.build(), this.buildGenTableQueryWrapper(genTable)); return TableDataInfo.build(page); } private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) { Map<String, Object> params = genTable.getParams(); QueryWrapper<GenTable> wrapper = Wrappers.query();
package com.ruoyi.generator.service; /** * 业务 服务层实现 * * @author Lion Li */ @DS("#header.datasource") @Slf4j @RequiredArgsConstructor @Service public class GenTableServiceImpl implements IGenTableService { private final GenTableMapper baseMapper; private final GenTableColumnMapper genTableColumnMapper; private final IdentifierGenerator identifierGenerator; /** * 查询业务字段列表 * * @param tableId 业务字段编号 * @return 业务字段集合 */ @Override public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) { return genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>() .eq(GenTableColumn::getTableId, tableId) .orderByAsc(GenTableColumn::getSort)); } /** * 查询业务信息 * * @param id 业务ID * @return 业务信息 */ @Override public GenTable selectGenTableById(Long id) { GenTable genTable = baseMapper.selectGenTableById(id); setTableFromOptions(genTable); return genTable; } @Override public TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery) { Page<GenTable> page = baseMapper.selectPage(pageQuery.build(), this.buildGenTableQueryWrapper(genTable)); return TableDataInfo.build(page); } private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) { Map<String, Object> params = genTable.getParams(); QueryWrapper<GenTable> wrapper = Wrappers.query();
wrapper.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName()))
8
2023-12-07 12:06:21+00:00
24k
DantSu/studio
web-ui/src/main/java/studio/webui/service/StoryTellerService.java
[ { "identifier": "PackFormat", "path": "core/src/main/java/studio/core/v1/utils/PackFormat.java", "snippet": "public enum PackFormat {\n\n ARCHIVE(new ArchiveStoryPackReader(), new ArchiveStoryPackWriter()),\n\n RAW(new BinaryStoryPackReader(), new BinaryStoryPackWriter()),\n\n FS(new FsStoryPac...
import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.usb4java.Device; import io.vertx.core.eventbus.EventBus; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import studio.core.v1.utils.PackFormat; import studio.core.v1.utils.SecurityUtils; import studio.core.v1.utils.exception.StoryTellerException; import studio.driver.StoryTellerAsyncDriver; import studio.driver.fs.FsStoryTellerAsyncDriver; import studio.driver.model.StoryPackInfos; import studio.driver.model.fs.FsDeviceInfos; import studio.driver.model.fs.FsStoryPackInfos; import studio.driver.model.raw.RawDeviceInfos; import studio.driver.model.raw.RawStoryPackInfos; import studio.driver.raw.LibUsbMassStorageHelper; import studio.driver.raw.RawStoryTellerAsyncDriver; import studio.metadata.DatabaseMetadataService;
18,692
/* * 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 studio.webui.service; public class StoryTellerService implements IStoryTellerService { private static final Logger LOGGER = LogManager.getLogger(StoryTellerService.class); private final EventBus eventBus;
/* * 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 studio.webui.service; public class StoryTellerService implements IStoryTellerService { private static final Logger LOGGER = LogManager.getLogger(StoryTellerService.class); private final EventBus eventBus;
private final DatabaseMetadataService databaseMetadataService;
12
2023-12-14 15:08:35+00:00
24k
conductor-oss/conductor-community
persistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/config/PostgresConfiguration.java
[ { "identifier": "PostgresExecutionDAO", "path": "persistence/postgres-persistence/src/main/java/com/netflix/conductor/postgres/dao/PostgresExecutionDAO.java", "snippet": "public class PostgresExecutionDAO extends PostgresBaseDAO\n implements ExecutionDAO, RateLimitingDAO, PollDataDAO, ConcurrentE...
import java.sql.SQLException; import java.util.Optional; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.*; import org.springframework.retry.RetryContext; import org.springframework.retry.backoff.NoBackOffPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import com.netflix.conductor.postgres.dao.PostgresExecutionDAO; import com.netflix.conductor.postgres.dao.PostgresIndexDAO; import com.netflix.conductor.postgres.dao.PostgresMetadataDAO; import com.netflix.conductor.postgres.dao.PostgresQueueDAO; import com.fasterxml.jackson.databind.ObjectMapper;
19,732
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.postgres.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(PostgresProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "postgres") // Import the DataSourceAutoConfiguration when postgres database is selected. // By default, the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class PostgresConfiguration { DataSource dataSource; private final PostgresProperties properties; public PostgresConfiguration(DataSource dataSource, PostgresProperties properties) { this.dataSource = dataSource; this.properties = properties; } @Bean(initMethod = "migrate") @PostConstruct public Flyway flywayForPrimaryDb() { return Flyway.configure() .locations("classpath:db/migration_postgres") .schemas(properties.getSchema()) .dataSource(dataSource) .baselineOnMigrate(true) .load(); } @Bean @DependsOn({"flywayForPrimaryDb"})
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.postgres.config; @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(PostgresProperties.class) @ConditionalOnProperty(name = "conductor.db.type", havingValue = "postgres") // Import the DataSourceAutoConfiguration when postgres database is selected. // By default, the datasource configuration is excluded in the main module. @Import(DataSourceAutoConfiguration.class) public class PostgresConfiguration { DataSource dataSource; private final PostgresProperties properties; public PostgresConfiguration(DataSource dataSource, PostgresProperties properties) { this.dataSource = dataSource; this.properties = properties; } @Bean(initMethod = "migrate") @PostConstruct public Flyway flywayForPrimaryDb() { return Flyway.configure() .locations("classpath:db/migration_postgres") .schemas(properties.getSchema()) .dataSource(dataSource) .baselineOnMigrate(true) .load(); } @Bean @DependsOn({"flywayForPrimaryDb"})
public PostgresMetadataDAO postgresMetadataDAO(
2
2023-12-08 06:06:20+00:00
24k
Ispirer/COBOL-to-Java-Conversion-Samples
IspirerFramework/com/ispirer/sw/strings/StringUtil.java
[ { "identifier": "PictureType", "path": "IspirerFramework/com/ispirer/sw/types/PictureType.java", "snippet": "public class PictureType<T extends Object> implements Comparable<Object> {\n\n\tprivate static Logger LOGGER = LoggerFactory.getLogger(PictureType.class);\n\tprivate static final char[] HEX_ARRAY...
import com.ispirer.sw.types.PictureType; import com.ispirer.sw.types.StructureModel; import org.apache.commons.lang3.StringUtils; import java.math.BigDecimal; import java.util.List;
14,832
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.strings; public class StringUtil { /** * replases searchString to replacement in the str first time * * @param str * @param searchString * @param replacement * @return result of replacing */ public static String replaceLeading(String str, String searchString, String replacement) { if (str.indexOf(searchString) == 0) { String newStr = ""; while (str.indexOf(searchString) == 0) { newStr += str.substring(0, searchString.length()); str = str.substring(searchString.length(), str.length()); } newStr = newStr.replaceAll(searchString, replacement); return newStr + str; } return str; } public static Integer tallyingLeading(String str, String searchString) { Integer res = 0; while (str.indexOf(searchString) == 0) { res++; str = str.substring(searchString.length()); } return res; } /** * fills List variable by String value * * @param array to fill * @param str to fill by * @return filled list */ public static List<?> initializeArray(List<?> array, String str) { Object firstel = array.get(0); int sizeOneVariable = 0;
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.strings; public class StringUtil { /** * replases searchString to replacement in the str first time * * @param str * @param searchString * @param replacement * @return result of replacing */ public static String replaceLeading(String str, String searchString, String replacement) { if (str.indexOf(searchString) == 0) { String newStr = ""; while (str.indexOf(searchString) == 0) { newStr += str.substring(0, searchString.length()); str = str.substring(searchString.length(), str.length()); } newStr = newStr.replaceAll(searchString, replacement); return newStr + str; } return str; } public static Integer tallyingLeading(String str, String searchString) { Integer res = 0; while (str.indexOf(searchString) == 0) { res++; str = str.substring(searchString.length()); } return res; } /** * fills List variable by String value * * @param array to fill * @param str to fill by * @return filled list */ public static List<?> initializeArray(List<?> array, String str) { Object firstel = array.get(0); int sizeOneVariable = 0;
if (firstel instanceof StructureModel) {
1
2023-12-13 14:56:32+00:00
24k
i-moonlight/Suricate
src/main/java/com/michelin/suricate/controllers/ProjectController.java
[ { "identifier": "USER_NOT_ALLOWED_PROJECT", "path": "src/main/java/com/michelin/suricate/utils/exceptions/constants/ErrorMessage.java", "snippet": "public static final String USER_NOT_ALLOWED_PROJECT = \"The user is not allowed to modify this project\";" }, { "identifier": "ApiErrorDto", "pa...
import static com.michelin.suricate.utils.exceptions.constants.ErrorMessage.USER_NOT_ALLOWED_PROJECT; import com.michelin.suricate.model.dto.api.error.ApiErrorDto; import com.michelin.suricate.model.dto.api.project.ProjectRequestDto; import com.michelin.suricate.model.dto.api.project.ProjectResponseDto; import com.michelin.suricate.model.dto.api.projectwidget.ProjectWidgetPositionRequestDto; import com.michelin.suricate.model.dto.api.user.UserResponseDto; import com.michelin.suricate.model.dto.websocket.WebsocketClient; import com.michelin.suricate.model.entities.Project; import com.michelin.suricate.model.entities.User; import com.michelin.suricate.model.enums.ApiErrorEnum; import com.michelin.suricate.security.LocalUser; import com.michelin.suricate.services.api.ProjectGridService; import com.michelin.suricate.services.api.ProjectService; import com.michelin.suricate.services.api.ProjectWidgetService; import com.michelin.suricate.services.api.UserService; import com.michelin.suricate.services.mapper.ProjectGridMapper; import com.michelin.suricate.services.mapper.ProjectMapper; import com.michelin.suricate.services.mapper.UserMapper; import com.michelin.suricate.services.websocket.DashboardWebSocketService; import com.michelin.suricate.utils.exceptions.ApiException; import com.michelin.suricate.utils.exceptions.InvalidFileException; import com.michelin.suricate.utils.exceptions.ObjectNotFoundException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.annotation.security.PermitAll; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; import java.util.Optional; import org.springdoc.core.converters.models.PageableAsQueryParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
16,667
/* * * * Copyright 2012-2021 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.michelin.suricate.controllers; /** * Project controller. */ @RestController @RequestMapping("/api")
/* * * * Copyright 2012-2021 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.michelin.suricate.controllers; /** * Project controller. */ @RestController @RequestMapping("/api")
@Tag(name = "Project", description = "Project Controller")
7
2023-12-11 11:28:37+00:00
24k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/lib/HttpFunc.java
[ { "identifier": "FiberException", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/FiberException.java", "snippet": "public class FiberException extends Exception {\n private int code;\n private final String errorName;\n\n public FiberException(String message, int code, String er...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.IntNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.fiber.net.common.FiberException; import io.fiber.net.common.HttpExchange; import io.fiber.net.common.HttpMethod; import io.fiber.net.common.async.internal.SerializeJsonObservable; import io.fiber.net.common.utils.ArrayUtils; import io.fiber.net.common.utils.Constant; import io.fiber.net.common.utils.JsonUtil; import io.fiber.net.common.utils.StringUtils; import io.fiber.net.http.ClientExchange; import io.fiber.net.http.HttpClient; import io.fiber.net.http.HttpHost; import io.fiber.net.http.util.UrlEncoded; import io.fiber.net.script.ExecutionContext; import io.fiber.net.script.Library; import io.fiber.net.script.ScriptExecException; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
14,466
package io.fiber.net.proxy.lib; public class HttpFunc implements Library.DirectiveDef { private final HttpHost httpHost; private final HttpClient httpClient; private final Map<String, HttpDynamicFunc> fc = new HashMap<>(); public HttpFunc(HttpHost httpHost, HttpClient httpClient) { this.httpHost = httpHost; this.httpClient = httpClient; fc.put("request", new SendFunc()); fc.put("proxyPass", new ProxyFunc()); } @Override public Library.Function findFunc(String directive, String function) { return fc.get(function); } private class SendFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { JsonNode param = ArrayUtils.isNotEmpty(args) ? args[0] : NullNode.getInstance(); ClientExchange exchange = httpClient.refer(httpHost);
package io.fiber.net.proxy.lib; public class HttpFunc implements Library.DirectiveDef { private final HttpHost httpHost; private final HttpClient httpClient; private final Map<String, HttpDynamicFunc> fc = new HashMap<>(); public HttpFunc(HttpHost httpHost, HttpClient httpClient) { this.httpHost = httpHost; this.httpClient = httpClient; fc.put("request", new SendFunc()); fc.put("proxyPass", new ProxyFunc()); } @Override public Library.Function findFunc(String directive, String function) { return fc.get(function); } private class SendFunc implements HttpDynamicFunc { @Override public void call(ExecutionContext context, JsonNode... args) { JsonNode param = ArrayUtils.isNotEmpty(args) ? args[0] : NullNode.getInstance(); ClientExchange exchange = httpClient.refer(httpHost);
setMethod(param, HttpMethod.GET, exchange);
2
2023-12-08 15:18:05+00:00
24k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/id3/ID3v23Tag.java
[ { "identifier": "FileConstants", "path": "android/src/main/java/org/jaudiotagger/FileConstants.java", "snippet": "public interface FileConstants\n{\n /**\n * defined for convenience\n */\n int BIT7 = 0x80;\n /**\n * defined for convenience\n */\n int BIT6 = 0x40;\n /**\n ...
import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.*; import java.util.logging.Level; import org.jaudiotagger.FileConstants; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.logging.ErrorMessage; import org.jaudiotagger.tag.*; import org.jaudiotagger.tag.datatype.DataTypes; import org.jaudiotagger.tag.datatype.Pair; import org.jaudiotagger.tag.datatype.PairedTextEncodedStringNullTerminated; import org.jaudiotagger.tag.id3.framebody.*; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.images.ArtworkFactory; import org.jaudiotagger.tag.reference.PictureTypes; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException;
19,513
super.createStructureBody(); MP3File.getStructureFormatter().closeHeadingElement(TYPE_TAG); } /** * @return is tag unsynchronized */ public boolean isUnsynchronization() { return unsynchronization; } public ID3v23Frame createFrame(String id) { return new ID3v23Frame(id); } /** * Create Frame for Id3 Key * * Only textual data supported at the moment, should only be used with frames that * support a simple string argument. * * @param id3Key * @param value * @return * @throws KeyNotFoundException * @throws FieldDataInvalidException */ public TagField createField(ID3v23FieldKey id3Key, String value) throws KeyNotFoundException, FieldDataInvalidException { if (id3Key == null) { throw new KeyNotFoundException(); } return super.doCreateTagField(new FrameAndSubId(null, id3Key.getFrameId(), id3Key.getSubId()), value); } /** * Retrieve the first value that exists for this id3v23key * * @param id3v23FieldKey * @return * @throws org.jaudiotagger.tag.KeyNotFoundException */ public String getFirst(ID3v23FieldKey id3v23FieldKey) throws KeyNotFoundException { if (id3v23FieldKey == null) { throw new KeyNotFoundException(); } FieldKey genericKey = ID3v23Frames.getInstanceOf().getGenericKeyFromId3(id3v23FieldKey); if(genericKey!=null) { return super.getFirst(genericKey); } else { FrameAndSubId frameAndSubId = new FrameAndSubId(null, id3v23FieldKey.getFrameId(), id3v23FieldKey.getSubId()); return super.doGetValueAtIndex(frameAndSubId, 0); } } /** * Delete fields with this id3v23FieldKey * * @param id3v23FieldKey * @throws org.jaudiotagger.tag.KeyNotFoundException */ public void deleteField(ID3v23FieldKey id3v23FieldKey) throws KeyNotFoundException { if (id3v23FieldKey == null) { throw new KeyNotFoundException(); } super.doDeleteTagField(new FrameAndSubId(null, id3v23FieldKey.getFrameId(), id3v23FieldKey.getSubId())); } /** * Delete fields with this (frame) id * @param id */ public void deleteField(String id) { super.doDeleteTagField(new FrameAndSubId(null, id,null)); } protected FrameAndSubId getFrameAndSubIdFromGenericKey(FieldKey genericKey) { if (genericKey == null) { throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg()); } ID3v23FieldKey id3v23FieldKey = ID3v23Frames.getInstanceOf().getId3KeyFromGenericKey(genericKey); if (id3v23FieldKey == null) { throw new KeyNotFoundException(genericKey.name()); } return new FrameAndSubId(genericKey, id3v23FieldKey.getFrameId(), id3v23FieldKey.getSubId()); } protected ID3Frames getID3Frames() { return ID3v23Frames.getInstanceOf(); } /** * @return comparator used to order frames in preferred order for writing to file * so that most important frames are written first. */ public Comparator getPreferredFrameOrderComparator() { return ID3v23PreferredFrameOrderComparator.getInstanceof(); } /** * {@inheritDoc} */
/* * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can getFields a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.tag.id3; /** * Represents an ID3v2.3 tag. * * @author : Paul Taylor * @author : Eric Farng * @version $Id$ */ public class ID3v23Tag extends AbstractID3v2Tag { protected static final String TYPE_CRCDATA = "crcdata"; protected static final String TYPE_EXPERIMENTAL = "experimental"; protected static final String TYPE_EXTENDED = "extended"; protected static final String TYPE_PADDINGSIZE = "paddingsize"; protected static final String TYPE_UNSYNCHRONISATION = "unsyncronisation"; protected static int TAG_EXT_HEADER_LENGTH = 10; protected static int TAG_EXT_HEADER_CRC_LENGTH = 4; protected static int FIELD_TAG_EXT_SIZE_LENGTH = 4; protected static int TAG_EXT_HEADER_DATA_LENGTH = TAG_EXT_HEADER_LENGTH - FIELD_TAG_EXT_SIZE_LENGTH; /** * ID3v2.3 Header bit mask */ public static final int MASK_V23_UNSYNCHRONIZATION = FileConstants.BIT7; /** * ID3v2.3 Header bit mask */ public static final int MASK_V23_EXTENDED_HEADER = FileConstants.BIT6; /** * ID3v2.3 Header bit mask */ public static final int MASK_V23_EXPERIMENTAL = FileConstants.BIT5; /** * ID3v2.3 Extended Header bit mask */ public static final int MASK_V23_CRC_DATA_PRESENT = FileConstants.BIT7; /** * ID3v2.3 RBUF frame bit mask */ public static final int MASK_V23_EMBEDDED_INFO_FLAG = FileConstants.BIT1; /** * CRC Checksum calculated */ protected boolean crcDataFlag = false; /** * Experiemntal tag */ protected boolean experimental = false; /** * Contains extended header */ protected boolean extended = false; /** * Crcdata Checksum in extended header */ private int crc32; /** * Tag padding */ private int paddingSize = 0; /** * All frames in the tag uses unsynchronisation */ protected boolean unsynchronization = false; /** * The tag is compressed */ protected boolean compression = false; public static final byte RELEASE = 2; public static final byte MAJOR_VERSION = 3; public static final byte REVISION = 0; /** * Retrieve the Release */ public byte getRelease() { return RELEASE; } /** * Retrieve the Major Version */ public byte getMajorVersion() { return MAJOR_VERSION; } /** * Retrieve the Revision */ public byte getRevision() { return REVISION; } /** * @return Cyclic Redundancy Check 32 Value */ public int getCrc32() { return crc32; } /** * Creates a new empty ID3v2_3 datatype. */ public ID3v23Tag() { frameMap = new LinkedHashMap(); encryptedFrameMap = new LinkedHashMap(); } /** * Copy primitives applicable to v2.3 */ protected void copyPrimitives(AbstractID3v2Tag copyObj) { logger.config("Copying primitives"); super.copyPrimitives(copyObj); if (copyObj instanceof ID3v23Tag) { ID3v23Tag copyObject = (ID3v23Tag) copyObj; this.crcDataFlag = copyObject.crcDataFlag; this.experimental = copyObject.experimental; this.extended = copyObject.extended; this.crc32 = copyObject.crc32; this.paddingSize = copyObject.paddingSize; } } /** * Override to merge TIPL/TMCL into single IPLS frame * * @param newFrame * @param existingFrame */ @Override protected void processDuplicateFrame(AbstractID3v2Frame newFrame, AbstractID3v2Frame existingFrame) { //We dont add this new frame we just add the contents to existing frame if(newFrame.getIdentifier().equals(ID3v23Frames.FRAME_ID_V3_INVOLVED_PEOPLE)) { PairedTextEncodedStringNullTerminated.ValuePairs oldVps = ((FrameBodyIPLS)(existingFrame).getBody()).getPairing(); PairedTextEncodedStringNullTerminated.ValuePairs newVps = ((FrameBodyIPLS)newFrame.getBody()).getPairing(); for(Pair next:newVps.getMapping()) { oldVps.add(next); } } else { List<AbstractID3v2Frame> list = new ArrayList<AbstractID3v2Frame>(); list.add(existingFrame); list.add(newFrame); frameMap.put(newFrame.getIdentifier(), list); } } @Override public void addFrame(AbstractID3v2Frame frame) { try { if (frame instanceof ID3v23Frame) { copyFrameIntoMap(frame.getIdentifier(), frame); } else { List<AbstractID3v2Frame> frames = convertFrame(frame); for(AbstractID3v2Frame next:frames) { copyFrameIntoMap(next.getIdentifier(), next); } } } catch (InvalidFrameException ife) { logger.log(Level.SEVERE, "Unable to convert frame:" + frame.getIdentifier()); } } @Override protected List<AbstractID3v2Frame> convertFrame(AbstractID3v2Frame frame) throws InvalidFrameException { List<AbstractID3v2Frame> frames = new ArrayList<AbstractID3v2Frame>(); if ((frame.getIdentifier().equals(ID3v24Frames.FRAME_ID_YEAR)) && (frame.getBody() instanceof FrameBodyTDRC)) { //TODO will overwrite any existing TYER or TIME frame, do we ever want multiples of these FrameBodyTDRC tmpBody = (FrameBodyTDRC) frame.getBody(); tmpBody.findMatchingMaskAndExtractV3Values(); ID3v23Frame newFrame; if (!tmpBody.getYear().equals("")) { newFrame = new ID3v23Frame(ID3v23Frames.FRAME_ID_V3_TYER); ((FrameBodyTYER) newFrame.getBody()).setText(tmpBody.getYear()); frames.add(newFrame); } if (!tmpBody.getDate().equals("")) { newFrame = new ID3v23Frame(ID3v23Frames.FRAME_ID_V3_TDAT); ((FrameBodyTDAT) newFrame.getBody()).setText(tmpBody.getDate()); ((FrameBodyTDAT) newFrame.getBody()).setMonthOnly(tmpBody.isMonthOnly()); frames.add(newFrame); } if (!tmpBody.getTime().equals("")) { newFrame = new ID3v23Frame(ID3v23Frames.FRAME_ID_V3_TIME); ((FrameBodyTIME) newFrame.getBody()).setText(tmpBody.getTime()); ((FrameBodyTIME) newFrame.getBody()).setHoursOnly(tmpBody.isHoursOnly()); frames.add(newFrame); } } //If at later stage we have multiple IPLS frames we have to merge else if ((frame.getIdentifier().equals(ID3v24Frames.FRAME_ID_INVOLVED_PEOPLE)) && (frame.getBody() instanceof FrameBodyTIPL)) { List<Pair> pairs= ((FrameBodyTIPL)frame.getBody()).getPairing().getMapping(); AbstractID3v2Frame ipls = new ID3v23Frame((ID3v24Frame)frame,ID3v23Frames.FRAME_ID_V3_INVOLVED_PEOPLE); FrameBodyIPLS iplsBody = new FrameBodyIPLS(frame.getBody().getTextEncoding(),pairs); ipls.setBody(iplsBody); frames.add(ipls); } else if ((frame.getIdentifier().equals(ID3v24Frames.FRAME_ID_MUSICIAN_CREDITS)) && (frame.getBody() instanceof FrameBodyTMCL)) { List<Pair> pairs= ((FrameBodyTMCL)frame.getBody()).getPairing().getMapping(); AbstractID3v2Frame ipls = new ID3v23Frame((ID3v24Frame)frame,ID3v23Frames.FRAME_ID_V3_INVOLVED_PEOPLE); FrameBodyIPLS iplsBody = new FrameBodyIPLS(frame.getBody().getTextEncoding(),pairs); ipls.setBody(iplsBody); frames.add(ipls); } else { frames.add(new ID3v23Frame(frame)); } return frames; } /** * Copy Constructor, creates a new ID3v2_3 Tag based on another ID3v2_3 Tag * @param copyObject */ public ID3v23Tag(ID3v23Tag copyObject) { //This doesn't do anything. super(copyObject); logger.config("Creating tag from another tag of same type"); copyPrimitives(copyObject); copyFrames(copyObject); } /** * Constructs a new tag based upon another tag of different version/type * @param mp3tag */ public ID3v23Tag(AbstractTag mp3tag) { logger.config("Creating tag from a tag of a different version"); frameMap = new LinkedHashMap(); encryptedFrameMap = new LinkedHashMap(); if (mp3tag != null) { ID3v24Tag convertedTag; //Should use simpler copy constructor if (mp3tag instanceof ID3v23Tag) { throw new UnsupportedOperationException("Copy Constructor not called. Please type cast the argument"); } if (mp3tag instanceof ID3v24Tag) { convertedTag = (ID3v24Tag) mp3tag; } //All tags types can be converted to v2.4 so do this to simplify things else { convertedTag = new ID3v24Tag(mp3tag); } this.setLoggingFilename(convertedTag.getLoggingFilename()); //Copy Primitives copyPrimitives(convertedTag); //Copy Frames copyFrames(convertedTag); logger.config("Created tag from a tag of a different version"); } } /** * Creates a new ID3v2_3 datatype. * * @param buffer * @param loggingFilename * @throws TagException */ public ID3v23Tag(ByteBuffer buffer, String loggingFilename) throws TagException { setLoggingFilename(loggingFilename); this.read(buffer); } /** * Creates a new ID3v2_3 datatype. * * @param buffer * @throws TagException * @deprecated use {@link #ID3v23Tag(ByteBuffer,String)} instead */ public ID3v23Tag(ByteBuffer buffer) throws TagException { this(buffer, ""); } /** * @return textual tag identifier */ public String getIdentifier() { return "ID3v2.30"; } /** * Return frame size based upon the sizes of the tags rather than the physical * no of bytes between start of ID3Tag and start of Audio Data. * * TODO this is incorrect, because of subclasses * * @return size of tag */ public int getSize() { int size = TAG_HEADER_LENGTH; if (extended) { size += TAG_EXT_HEADER_LENGTH; if (crcDataFlag) { size += TAG_EXT_HEADER_CRC_LENGTH; } } size += super.getSize(); return size; } /** * Is Tag Equivalent to another tag * * @param obj * @return true if tag is equivalent to another */ public boolean equals(Object obj) { if (!(obj instanceof ID3v23Tag)) { return false; } ID3v23Tag object = (ID3v23Tag) obj; if (this.crc32 != object.crc32) { return false; } if (this.crcDataFlag != object.crcDataFlag) { return false; } if (this.experimental != object.experimental) { return false; } if (this.extended != object.extended) { return false; } return this.paddingSize == object.paddingSize && super.equals(obj); } /** * Read header flags * * <p>Log info messages for flags that have been set and log warnings when bits have been set for unknown flags * @param buffer * @throws TagException */ private void readHeaderFlags(ByteBuffer buffer) throws TagException { //Allowable Flags byte flags = buffer.get(); unsynchronization = (flags & MASK_V23_UNSYNCHRONIZATION) != 0; extended = (flags & MASK_V23_EXTENDED_HEADER) != 0; experimental = (flags & MASK_V23_EXPERIMENTAL) != 0; //Not allowable/Unknown Flags if ((flags & FileConstants.BIT4) != 0) { logger.warning(ErrorMessage.ID3_INVALID_OR_UNKNOWN_FLAG_SET.getMsg(getLoggingFilename(), FileConstants.BIT4)); } if ((flags & FileConstants.BIT3) != 0) { logger.warning(ErrorMessage.ID3_INVALID_OR_UNKNOWN_FLAG_SET.getMsg(getLoggingFilename(), FileConstants.BIT3)); } if ((flags & FileConstants.BIT2) != 0) { logger.warning(ErrorMessage.ID3_INVALID_OR_UNKNOWN_FLAG_SET.getMsg(getLoggingFilename(), FileConstants.BIT2)); } if ((flags & FileConstants.BIT1) != 0) { logger.warning(ErrorMessage.ID3_INVALID_OR_UNKNOWN_FLAG_SET.getMsg(getLoggingFilename(), FileConstants.BIT1)); } if ((flags & FileConstants.BIT0) != 0) { logger.warning(ErrorMessage.ID3_INVALID_OR_UNKNOWN_FLAG_SET.getMsg(getLoggingFilename(), FileConstants.BIT0)); } if (isUnsynchronization()) { logger.config(ErrorMessage.ID3_TAG_UNSYNCHRONIZED.getMsg(getLoggingFilename())); } if (extended) { logger.config(ErrorMessage.ID3_TAG_EXTENDED.getMsg(getLoggingFilename())); } if (experimental) { logger.config(ErrorMessage.ID3_TAG_EXPERIMENTAL.getMsg(getLoggingFilename())); } } /** * Read the optional extended header * * @param buffer * @param size */ private void readExtendedHeader(ByteBuffer buffer, int size) { // Int is 4 bytes. int extendedHeaderSize = buffer.getInt(); // Extended header without CRC Data if (extendedHeaderSize == TAG_EXT_HEADER_DATA_LENGTH) { //Flag should not be setField , if is log a warning byte extFlag = buffer.get(); crcDataFlag = (extFlag & MASK_V23_CRC_DATA_PRESENT) != 0; if (crcDataFlag) { logger.warning(ErrorMessage.ID3_TAG_CRC_FLAG_SET_INCORRECTLY.getMsg(getLoggingFilename())); } //2nd Flag Byte (not used) buffer.get(); //Take padding and ext header size off the size to be read paddingSize=buffer.getInt(); if(paddingSize>0) { logger.config(ErrorMessage.ID3_TAG_PADDING_SIZE.getMsg(getLoggingFilename(),paddingSize)); } size = size - ( paddingSize + TAG_EXT_HEADER_LENGTH); } else if (extendedHeaderSize == TAG_EXT_HEADER_DATA_LENGTH + TAG_EXT_HEADER_CRC_LENGTH) { logger.config(ErrorMessage.ID3_TAG_CRC.getMsg(getLoggingFilename())); //Flag should be setField, if nor just act as if it is byte extFlag = buffer.get(); crcDataFlag = (extFlag & MASK_V23_CRC_DATA_PRESENT) != 0; if (!crcDataFlag) { logger.warning(ErrorMessage.ID3_TAG_CRC_FLAG_SET_INCORRECTLY.getMsg(getLoggingFilename())); } //2nd Flag Byte (not used) buffer.get(); //Take padding size of size to be read paddingSize = buffer.getInt(); if(paddingSize>0) { logger.config(ErrorMessage.ID3_TAG_PADDING_SIZE.getMsg(getLoggingFilename(),paddingSize)); } size = size - (paddingSize + TAG_EXT_HEADER_LENGTH + TAG_EXT_HEADER_CRC_LENGTH); //CRC Data crc32 = buffer.getInt(); logger.config(ErrorMessage.ID3_TAG_CRC_SIZE.getMsg(getLoggingFilename(),crc32)); } //Extended header size is only allowed to be six or ten bytes so this is invalid but instead //of giving up lets guess its six bytes and carry on and see if we can read file ok else { logger.warning(ErrorMessage.ID3_EXTENDED_HEADER_SIZE_INVALID.getMsg(getLoggingFilename(), extendedHeaderSize)); buffer.position(buffer.position() - FIELD_TAG_EXT_SIZE_LENGTH); } } /** * {@inheritDoc} */ @Override public void read(ByteBuffer buffer) throws TagException { int size; if (!seek(buffer)) { throw new TagNotFoundException(getIdentifier() + " tag not found"); } logger.config(getLoggingFilename() + ":" + "Reading ID3v23 tag"); readHeaderFlags(buffer); // Read the size, this is size of tag not including the tag header size = ID3SyncSafeInteger.bufferToValue(buffer); logger.config(ErrorMessage.ID_TAG_SIZE.getMsg(getLoggingFilename(),size)); //Extended Header if (extended) { readExtendedHeader(buffer, size); } //Slice Buffer, so position markers tally with size (i.e do not include tagHeader) ByteBuffer bufferWithoutHeader = buffer.slice(); //We need to synchronize the buffer if (isUnsynchronization()) { bufferWithoutHeader = ID3Unsynchronization.synchronize(bufferWithoutHeader); } readFrames(bufferWithoutHeader, size); logger.config(getLoggingFilename() + ":Loaded Frames,there are:" + frameMap.keySet().size()); } /** * Read the frames * * Read from byteBuffer upto size * * @param byteBuffer * @param size */ protected void readFrames(ByteBuffer byteBuffer, int size) { //Now start looking for frames ID3v23Frame next; frameMap = new LinkedHashMap(); encryptedFrameMap = new LinkedHashMap(); //Read the size from the Tag Header this.fileReadSize = size; logger.finest(getLoggingFilename() + ":Start of frame body at:" + byteBuffer.position() + ",frames data size is:" + size); // Read the frames until got to up to the size as specified in header or until // we hit an invalid frame identifier or padding while (byteBuffer.position() < size) { String id; try { //Read Frame int posBeforeRead = byteBuffer.position(); logger.config(getLoggingFilename() + ":Looking for next frame at:" + posBeforeRead); next = new ID3v23Frame(byteBuffer, getLoggingFilename()); id = next.getIdentifier(); logger.config(getLoggingFilename() + ":Found "+ id+ " at frame at:" + posBeforeRead); loadFrameIntoMap(id, next); } //Found Padding, no more frames catch (PaddingException ex) { logger.config(getLoggingFilename() + ":Found padding starting at:" + byteBuffer.position()); break; } //Found Empty Frame, log it - empty frames should not exist catch (EmptyFrameException ex) { logger.warning(getLoggingFilename() + ":Empty Frame:" + ex.getMessage()); this.emptyFrameBytes += ID3v23Frame.FRAME_HEADER_SIZE; } catch (InvalidFrameIdentifierException ifie) { logger.warning(getLoggingFilename() + ":Invalid Frame Identifier:" + ifie.getMessage()); this.invalidFrames++; //Don't try and find any more frames break; } //Problem trying to find frame, often just occurs because frameHeader includes padding //and we have reached padding catch (InvalidFrameException ife) { logger.warning(getLoggingFilename() + ":Invalid Frame:" + ife.getMessage()); this.invalidFrames++; //Don't try and find any more frames break; } //Failed reading frame but may just have invalid data but correct length so lets carry on //in case we can read the next frame catch(InvalidDataTypeException idete) { logger.warning(getLoggingFilename() + ":Corrupt Frame:" + idete.getMessage()); this.invalidFrames++; continue; } } } /** * Write the ID3 header to the ByteBuffer. * * TODO Calculate the CYC Data Check * TODO Reintroduce Extended Header * * @param padding is the size of the padding portion of the tag * @param size is the size of the body data * @return ByteBuffer * @throws IOException */ private ByteBuffer writeHeaderToBuffer(int padding, int size) throws IOException { // Flags,currently we never calculate the CRC // and if we dont calculate them cant keep orig values. Tags are not // experimental and we never createField extended header to keep things simple. extended = false; experimental = false; crcDataFlag = false; // Create Header Buffer,allocate maximum possible size for the header ByteBuffer headerBuffer = ByteBuffer. allocate(TAG_HEADER_LENGTH + TAG_EXT_HEADER_LENGTH + TAG_EXT_HEADER_CRC_LENGTH); //TAGID headerBuffer.put(TAG_ID); //Major Version headerBuffer.put(getMajorVersion()); //Minor Version headerBuffer.put(getRevision()); //Flags byte flagsByte = 0; if (isUnsynchronization()) { flagsByte |= MASK_V23_UNSYNCHRONIZATION; } if (extended) { flagsByte |= MASK_V23_EXTENDED_HEADER; } if (experimental) { flagsByte |= MASK_V23_EXPERIMENTAL; } headerBuffer.put(flagsByte); //Additional Header Size,(for completeness we never actually write the extended header) int additionalHeaderSize = 0; if (extended) { additionalHeaderSize += TAG_EXT_HEADER_LENGTH; if (crcDataFlag) { additionalHeaderSize += TAG_EXT_HEADER_CRC_LENGTH; } } //Size As Recorded in Header, don't include the main header length headerBuffer.put(ID3SyncSafeInteger.valueToBuffer(padding + size + additionalHeaderSize)); //Write Extended Header if (extended) { byte extFlagsByte1 = 0; byte extFlagsByte2 = 0; //Contains CRCData if (crcDataFlag) { headerBuffer.putInt(TAG_EXT_HEADER_DATA_LENGTH + TAG_EXT_HEADER_CRC_LENGTH); extFlagsByte1 |= MASK_V23_CRC_DATA_PRESENT; headerBuffer.put(extFlagsByte1); headerBuffer.put(extFlagsByte2); headerBuffer.putInt(paddingSize); headerBuffer.putInt(crc32); } //Just extended Header else { headerBuffer.putInt(TAG_EXT_HEADER_DATA_LENGTH); headerBuffer.put(extFlagsByte1); headerBuffer.put(extFlagsByte2); //Newly Calculated Padding As Recorded in Extended Header headerBuffer.putInt(padding); } } headerBuffer.flip(); return headerBuffer; } /** * Write tag to file * * TODO:we currently never write the Extended header , but if we did the size calculation in this * method would be slightly incorrect * * @param file The file to write to * @throws IOException */ public long write(File file, long audioStartLocation) throws IOException { setLoggingFilename(file.getName()); logger.config("Writing tag to file:"+getLoggingFilename()); //Write Body Buffer byte[] bodyByteBuffer = writeFramesToBuffer().toByteArray(); logger.config(getLoggingFilename() + ":bodybytebuffer:sizebeforeunsynchronisation:" + bodyByteBuffer.length); // Unsynchronize if option enabled and unsync required unsynchronization = TagOptionSingleton.getInstance().isUnsyncTags() && ID3Unsynchronization.requiresUnsynchronization(bodyByteBuffer); if (isUnsynchronization()) { bodyByteBuffer = ID3Unsynchronization.unsynchronize(bodyByteBuffer); logger.config(getLoggingFilename() + ":bodybytebuffer:sizeafterunsynchronisation:" + bodyByteBuffer.length); } int sizeIncPadding = calculateTagSize(bodyByteBuffer.length + TAG_HEADER_LENGTH, (int) audioStartLocation); int padding = sizeIncPadding - (bodyByteBuffer.length + TAG_HEADER_LENGTH); logger.config(getLoggingFilename() + ":Current audiostart:" + audioStartLocation); logger.config(getLoggingFilename() + ":Size including padding:" + sizeIncPadding); logger.config(getLoggingFilename() + ":Padding:" + padding); ByteBuffer headerBuffer = writeHeaderToBuffer(padding, bodyByteBuffer.length); writeBufferToFile(file, headerBuffer, bodyByteBuffer, padding, sizeIncPadding, audioStartLocation); return sizeIncPadding; } /** * {@inheritDoc} */ @Override public void write(WritableByteChannel channel, int currentTagSize) throws IOException { logger.config(getLoggingFilename() + ":Writing tag to channel"); byte[] bodyByteBuffer = writeFramesToBuffer().toByteArray(); logger.config(getLoggingFilename() + ":bodybytebuffer:sizebeforeunsynchronisation:" + bodyByteBuffer.length); // Unsynchronize if option enabled and unsync required unsynchronization = TagOptionSingleton.getInstance().isUnsyncTags() && ID3Unsynchronization.requiresUnsynchronization(bodyByteBuffer); if (isUnsynchronization()) { bodyByteBuffer = ID3Unsynchronization.unsynchronize(bodyByteBuffer); logger.config(getLoggingFilename() + ":bodybytebuffer:sizeafterunsynchronisation:" + bodyByteBuffer.length); } int padding = 0; if(currentTagSize > 0) { int sizeIncPadding = calculateTagSize(bodyByteBuffer.length + TAG_HEADER_LENGTH, (int) currentTagSize); padding = sizeIncPadding - (bodyByteBuffer.length + TAG_HEADER_LENGTH); logger.config(getLoggingFilename() + ":Padding:"+padding); } ByteBuffer headerBuffer = writeHeaderToBuffer(padding, bodyByteBuffer.length); channel.write(headerBuffer); channel.write(ByteBuffer.wrap(bodyByteBuffer)); writePadding(channel, padding); } /** * For representing the MP3File in an XML Format */ public void createStructure() { MP3File.getStructureFormatter().openHeadingElement(TYPE_TAG, getIdentifier()); super.createStructureHeader(); //Header MP3File.getStructureFormatter().openHeadingElement(TYPE_HEADER, ""); MP3File.getStructureFormatter().addElement(TYPE_UNSYNCHRONISATION, this.isUnsynchronization()); MP3File.getStructureFormatter().addElement(TYPE_EXTENDED, this.extended); MP3File.getStructureFormatter().addElement(TYPE_EXPERIMENTAL, this.experimental); MP3File.getStructureFormatter().addElement(TYPE_CRCDATA, this.crc32); MP3File.getStructureFormatter().addElement(TYPE_PADDINGSIZE, this.paddingSize); MP3File.getStructureFormatter().closeHeadingElement(TYPE_HEADER); //Body super.createStructureBody(); MP3File.getStructureFormatter().closeHeadingElement(TYPE_TAG); } /** * @return is tag unsynchronized */ public boolean isUnsynchronization() { return unsynchronization; } public ID3v23Frame createFrame(String id) { return new ID3v23Frame(id); } /** * Create Frame for Id3 Key * * Only textual data supported at the moment, should only be used with frames that * support a simple string argument. * * @param id3Key * @param value * @return * @throws KeyNotFoundException * @throws FieldDataInvalidException */ public TagField createField(ID3v23FieldKey id3Key, String value) throws KeyNotFoundException, FieldDataInvalidException { if (id3Key == null) { throw new KeyNotFoundException(); } return super.doCreateTagField(new FrameAndSubId(null, id3Key.getFrameId(), id3Key.getSubId()), value); } /** * Retrieve the first value that exists for this id3v23key * * @param id3v23FieldKey * @return * @throws org.jaudiotagger.tag.KeyNotFoundException */ public String getFirst(ID3v23FieldKey id3v23FieldKey) throws KeyNotFoundException { if (id3v23FieldKey == null) { throw new KeyNotFoundException(); } FieldKey genericKey = ID3v23Frames.getInstanceOf().getGenericKeyFromId3(id3v23FieldKey); if(genericKey!=null) { return super.getFirst(genericKey); } else { FrameAndSubId frameAndSubId = new FrameAndSubId(null, id3v23FieldKey.getFrameId(), id3v23FieldKey.getSubId()); return super.doGetValueAtIndex(frameAndSubId, 0); } } /** * Delete fields with this id3v23FieldKey * * @param id3v23FieldKey * @throws org.jaudiotagger.tag.KeyNotFoundException */ public void deleteField(ID3v23FieldKey id3v23FieldKey) throws KeyNotFoundException { if (id3v23FieldKey == null) { throw new KeyNotFoundException(); } super.doDeleteTagField(new FrameAndSubId(null, id3v23FieldKey.getFrameId(), id3v23FieldKey.getSubId())); } /** * Delete fields with this (frame) id * @param id */ public void deleteField(String id) { super.doDeleteTagField(new FrameAndSubId(null, id,null)); } protected FrameAndSubId getFrameAndSubIdFromGenericKey(FieldKey genericKey) { if (genericKey == null) { throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg()); } ID3v23FieldKey id3v23FieldKey = ID3v23Frames.getInstanceOf().getId3KeyFromGenericKey(genericKey); if (id3v23FieldKey == null) { throw new KeyNotFoundException(genericKey.name()); } return new FrameAndSubId(genericKey, id3v23FieldKey.getFrameId(), id3v23FieldKey.getSubId()); } protected ID3Frames getID3Frames() { return ID3v23Frames.getInstanceOf(); } /** * @return comparator used to order frames in preferred order for writing to file * so that most important frames are written first. */ public Comparator getPreferredFrameOrderComparator() { return ID3v23PreferredFrameOrderComparator.getInstanceof(); } /** * {@inheritDoc} */
public List<Artwork> getArtworkList()
6
2023-12-11 05:58:19+00:00
24k
xhtcode/xht-cloud-parent
xht-cloud-framework/xht-cloud-framework-file/xht-cloud-framework-file-core/src/main/java/com/xht/cloud/framework/file/oss/core/OssObjectOperations.java
[ { "identifier": "DeleteObjectsDTO", "path": "xht-cloud-framework/xht-cloud-framework-file/xht-cloud-framework-file-core/src/main/java/com/xht/cloud/framework/file/oss/dto/DeleteObjectsDTO.java", "snippet": "@Data\npublic class DeleteObjectsDTO implements Serializable {\n\n @Serial\n private static...
import com.xht.cloud.framework.file.oss.dto.DeleteObjectsDTO; import com.xht.cloud.framework.file.oss.dto.GetObjectDTO; import com.xht.cloud.framework.file.oss.dto.ListObjectsDTO; import com.xht.cloud.framework.file.oss.dto.PutObjectDTO; import com.xht.cloud.framework.file.oss.dto.StatObjectDTO; import com.xht.cloud.framework.file.oss.dto.UploadObjectDTO; import com.xht.cloud.framework.file.oss.dto.cmd.DeleteObjectCmd; import com.xht.cloud.framework.file.oss.dto.cmd.DeleteObjectsCmd; import com.xht.cloud.framework.file.oss.dto.cmd.DownloadObjectCmd; import com.xht.cloud.framework.file.oss.dto.cmd.GetObjectCmd; import com.xht.cloud.framework.file.oss.dto.cmd.GetPreSignedObjectUrlCmd; import com.xht.cloud.framework.file.oss.dto.cmd.GetStatObjectCmd; import com.xht.cloud.framework.file.oss.dto.cmd.ListObjectCmd; import com.xht.cloud.framework.file.oss.dto.cmd.PutObjectCmd; import com.xht.cloud.framework.file.oss.dto.cmd.UploadObjectCmd; import java.util.List;
14,859
package com.xht.cloud.framework.file.oss.core; /** * 描述 :对象存储操作 * * @author : 小糊涂 **/ public interface OssObjectOperations { /** * 将文件中的内容作为存储桶中的对象上传 * * @param objectCmd {@link UploadObjectCmd} * @return {@link UploadObjectDTO} */ UploadObjectDTO uploadObject(UploadObjectCmd objectCmd); /** * 上传文件 * <p> * · 默认情况下,如果已存在同名Object且对该Object有访问权限,则新添加的Object将覆盖原有的Object,并返回200 OK。 * · OSS没有文件夹的概念,所有资源都是以文件来存储,但您可以通过创建一个以正斜线(/)结尾,大小为0的Object来创建模拟文件夹。 * * @param objectCmd {@link PutObjectCmd} * @return {@link PutObjectDTO} */ PutObjectDTO putObject(PutObjectCmd objectCmd); /** * listObjects列出桶里面的对象信息 * * @param objectCmd {@link ListObjectCmd} * @return ListObjectsDTO */ ListObjectsDTO listObjects(ListObjectCmd objectCmd); /** * 删除一个对象 * * @param objectCmd {@link DeleteObjectCmd} */
package com.xht.cloud.framework.file.oss.core; /** * 描述 :对象存储操作 * * @author : 小糊涂 **/ public interface OssObjectOperations { /** * 将文件中的内容作为存储桶中的对象上传 * * @param objectCmd {@link UploadObjectCmd} * @return {@link UploadObjectDTO} */ UploadObjectDTO uploadObject(UploadObjectCmd objectCmd); /** * 上传文件 * <p> * · 默认情况下,如果已存在同名Object且对该Object有访问权限,则新添加的Object将覆盖原有的Object,并返回200 OK。 * · OSS没有文件夹的概念,所有资源都是以文件来存储,但您可以通过创建一个以正斜线(/)结尾,大小为0的Object来创建模拟文件夹。 * * @param objectCmd {@link PutObjectCmd} * @return {@link PutObjectDTO} */ PutObjectDTO putObject(PutObjectCmd objectCmd); /** * listObjects列出桶里面的对象信息 * * @param objectCmd {@link ListObjectCmd} * @return ListObjectsDTO */ ListObjectsDTO listObjects(ListObjectCmd objectCmd); /** * 删除一个对象 * * @param objectCmd {@link DeleteObjectCmd} */
void removeObject(DeleteObjectCmd objectCmd);
6
2023-12-12 08:16:30+00:00
24k
serendipitk/LunarCore
src/main/java/emu/lunarcore/server/packet/recv/HandlerGetRogueInitialScoreCsReq.java
[ { "identifier": "GameSession", "path": "src/main/java/emu/lunarcore/server/game/GameSession.java", "snippet": "@Getter\npublic class GameSession {\n private final GameServer server;\n private final Int2LongMap packetCooldown;\n private InetSocketAddress address;\n\n private Account account;\...
import emu.lunarcore.server.game.GameSession; import emu.lunarcore.server.packet.CmdId; import emu.lunarcore.server.packet.Opcodes; import emu.lunarcore.server.packet.PacketHandler;
19,900
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetRogueInitialScoreCsReq) public class HandlerGetRogueInitialScoreCsReq extends PacketHandler { @Override
package emu.lunarcore.server.packet.recv; @Opcodes(CmdId.GetRogueInitialScoreCsReq) public class HandlerGetRogueInitialScoreCsReq extends PacketHandler { @Override
public void handle(GameSession session, byte[] data) throws Exception {
0
2023-12-08 14:13:04+00:00
24k
quentin452/Garden-Stuff-Continuation
src/main/java/com/jaquadro/minecraft/gardencontainers/block/BlockLargePot.java
[ { "identifier": "GardenContainers", "path": "src/main/java/com/jaquadro/minecraft/gardencontainers/GardenContainers.java", "snippet": "@Mod(\n modid = \"GardenContainers\",\n name = \"Garden Containers\",\n version = \"1.7.10-1.7.0\",\n dependencies = \"required-after:GardenCore\")\npublic c...
import com.InfinityRaider.AgriCraft.api.v1.ISoilContainer; import com.jaquadro.minecraft.gardencontainers.GardenContainers; import com.jaquadro.minecraft.gardencontainers.block.tile.TileEntityLargePot; import com.jaquadro.minecraft.gardencontainers.config.PatternConfig; import com.jaquadro.minecraft.gardencontainers.core.ClientProxy; import com.jaquadro.minecraft.gardencore.api.block.IChainAttachable; import com.jaquadro.minecraft.gardencore.api.block.IGardenBlock; import com.jaquadro.minecraft.gardencore.api.plant.PlantItem; import com.jaquadro.minecraft.gardencore.api.plant.PlantSize; import com.jaquadro.minecraft.gardencore.api.plant.PlantType; import com.jaquadro.minecraft.gardencore.block.BlockGardenContainer; import com.jaquadro.minecraft.gardencore.block.support.BasicSlotProfile; import com.jaquadro.minecraft.gardencore.block.support.ContainerConnectionProfile; import com.jaquadro.minecraft.gardencore.block.support.Slot14ProfileBounded; import com.jaquadro.minecraft.gardencore.block.support.SlotShare8Profile; import com.jaquadro.minecraft.gardencore.block.tile.TileEntityGarden; import com.jaquadro.minecraft.gardencore.core.ModBlocks; import com.jaquadro.minecraft.gardencore.core.ModCreativeTabs; import cpw.mods.fml.common.Optional.Interface; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.util.ForgeDirection; import java.util.ArrayList; import java.util.List;
15,982
return true; } if (item.getItem() == Items.water_bucket) { this.applyWaterToSubstrate(world, x, y, z, garden, player); return true; } if (item.getItem() instanceof ItemHoe) { this.applyHoeToSubstrate(world, x, y, z, garden, player); return true; } } return super.applyItemToGarden(world, x, y, z, player, itemStack, hitX, hitY, hitZ, hitValid); } } protected void applyWaterToSubstrate(World world, int x, int y, int z, TileEntityGarden tile, EntityPlayer player) { if (Block.getBlockFromItem( tile.getSubstrate() .getItem()) == Blocks.dirt) { tile.setSubstrate( new ItemStack(Blocks.farmland, 1, 7), new ItemStack( Blocks.dirt, 1, tile.getSubstrate() .getItemDamage())); tile.markDirty(); world.markBlockForUpdate(x, y, z); } } protected boolean applyHoeToSubstrate(World world, int x, int y, int z, TileEntityGarden tile, EntityPlayer player) { Block substrate = Block.getBlockFromItem( tile.getSubstrate() .getItem()); if (substrate != Blocks.dirt && substrate != Blocks.grass) { if (substrate != ModBlocks.gardenSoil) { return false; } tile.setSubstrate(new ItemStack(ModBlocks.gardenFarmland), new ItemStack(ModBlocks.gardenSoil)); } else { tile.setSubstrate( new ItemStack(Blocks.farmland, 1, 7), new ItemStack( Blocks.dirt, 1, tile.getSubstrate() .getItemDamage())); } tile.markDirty(); world.markBlockForUpdate(x, y, z); world.playSoundEffect( (double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), Blocks.farmland.stepSound.getStepResourcePath(), (Blocks.farmland.stepSound.getVolume() + 1.0F) / 2.0F, Blocks.farmland.stepSound.getPitch() * 0.8F); return true; } public boolean applyHoe(World world, int x, int y, int z) { TileEntityGarden te = this.getTileEntity(world, x, y, z); return te != null && te.isEmpty() ? this.applyHoeToSubstrate(world, x, y, z, te, (EntityPlayer) null) : false; } public TileEntityLargePot getTileEntity(IBlockAccess world, int x, int y, int z) { TileEntity te = world.getTileEntity(x, y, z); return te != null && te instanceof TileEntityLargePot ? (TileEntityLargePot) te : null; } public TileEntityLargePot createNewTileEntity(World world, int data) { return new TileEntityLargePot(); } public Vec3[] getChainAttachPoints(int side) { return side == 1 ? chainAttachPoints : null; } @SideOnly(Side.CLIENT) public IIcon getOverlayIcon(int data) { return this.iconOverlayArray[data] != null ? this.iconOverlayArray[data] : null; } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { this.iconOverlayArray = new IIcon[256]; for (int i = 1; i < this.iconOverlayArray.length; ++i) { PatternConfig pattern = GardenContainers.config.getPattern(i); if (pattern != null && pattern.getOverlay() != null) { this.iconOverlayArray[i] = iconRegister.registerIcon("GardenContainers:" + pattern.getOverlay()); } } } public Block getSoil(World world, int x, int y, int z) { ItemStack substrate = this.getGardenSubstrate(world, x, y, z, this.getDefaultSlot()); return substrate != null && substrate.getItem() != null && substrate.getItem() instanceof ItemBlock ? ((ItemBlock) substrate.getItem()).field_150939_a : null; } public int getSoilMeta(World world, int x, int y, int z) { ItemStack substrate = this.getGardenSubstrate(world, x, y, z, this.getDefaultSlot()); return substrate != null && substrate.getItem() != null && substrate.getItem() instanceof ItemBlock ? substrate.getItemDamage() : -1; }
package com.jaquadro.minecraft.gardencontainers.block; @Interface(modid = "AgriCraft", iface = "com.InfinityRaider.AgriCraft.api.v1.ISoilContainer") public abstract class BlockLargePot extends BlockGardenContainer implements IChainAttachable, ISoilContainer { @SideOnly(Side.CLIENT) private IIcon[] iconOverlayArray; private static final Vec3[] chainAttachPoints = new Vec3[] { Vec3.createVectorHelper(0.03625D, 1.0D, 0.03125D), Vec3.createVectorHelper(0.03125D, 1.0D, 0.96375D), Vec3.createVectorHelper(0.96875D, 1.0D, 0.03625D), Vec3.createVectorHelper(0.96375D, 1.0D, 0.96875D) }; public BlockLargePot(String blockName) { super(blockName, Material.clay); this.setCreativeTab(ModCreativeTabs.tabGardenCore); this.setHardness(0.5F); this.setResistance(5.0F); this.setStepSound(Block.soundTypeStone); this.connectionProfile = new ContainerConnectionProfile(); this.slotShareProfile = new SlotShare8Profile(6, 7, 8, 9, 10, 11, 12, 13); PlantType[] commonType = new PlantType[] { PlantType.GROUND, PlantType.AQUATIC_COVER, PlantType.AQUATIC_SURFACE }; PlantSize[] commonSize = new PlantSize[] { PlantSize.LARGE, PlantSize.MEDIUM, PlantSize.SMALL }; PlantSize[] allSize = new PlantSize[] { PlantSize.FULL, PlantSize.LARGE, PlantSize.MEDIUM, PlantSize.SMALL }; this.slotProfile = new BlockLargePot.LocalSlotProfile( this, new BasicSlotProfile.Slot[] { new BasicSlotProfile.Slot(0, commonType, allSize), new BasicSlotProfile.Slot(1, new PlantType[] { PlantType.GROUND_COVER }, allSize), new BasicSlotProfile.Slot(2, commonType, commonSize), new BasicSlotProfile.Slot(3, commonType, commonSize), new BasicSlotProfile.Slot(4, commonType, commonSize), new BasicSlotProfile.Slot(5, commonType, commonSize), new BasicSlotProfile.Slot(6, commonType, commonSize), new BasicSlotProfile.Slot(7, commonType, commonSize), new BasicSlotProfile.Slot(8, commonType, commonSize), new BasicSlotProfile.Slot(9, commonType, commonSize), new BasicSlotProfile.Slot(10, commonType, commonSize), new BasicSlotProfile.Slot(11, commonType, commonSize), new BasicSlotProfile.Slot(12, commonType, commonSize), new BasicSlotProfile.Slot(13, commonType, commonSize) }); } public abstract String[] getSubTypes(); public int getDefaultSlot() { return 0; } protected int getSlot(World world, int x, int y, int z, EntityPlayer player, float hitX, float hitY, float hitZ) { return 0; } protected int getEmptySlotForPlant(World world, int x, int y, int z, EntityPlayer player, PlantItem plant) { TileEntityGarden garden = this.getTileEntity(world, x, y, z); if (plant.getPlantTypeClass() == PlantType.GROUND_COVER) { return garden.getStackInSlot(1) == null ? 1 : -1; } else if (plant.getPlantSizeClass() == PlantSize.FULL) { return garden.getStackInSlot(0) == null ? 0 : -1; } else if (garden.getStackInSlot(0) == null) { return 0; } else { int[] var8; int var9; int var10; int slot; if (plant.getPlantSizeClass() == PlantSize.SMALL) { var8 = new int[] { 3, 4, 2, 5 }; var9 = var8.length; for (var10 = 0; var10 < var9; ++var10) { slot = var8[var10]; if (garden.getStackInSlot(slot) == null) { return slot; } } } var8 = new int[] { 13, 9, 7, 11, 6, 10, 8, 12 }; var9 = var8.length; for (var10 = 0; var10 < var9; ++var10) { slot = var8[var10]; if (garden.isSlotValid(slot) && garden.getStackInSlot(slot) == null) { return slot; } } return -1; } } public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB mask, List list, Entity colliding) { float dim = 0.0625F; TileEntityLargePot te = this.getTileEntity(world, x, y, z); if (te != null && te.getSubstrate() != null && this.isSubstrateSolid( te.getSubstrate() .getItem())) { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F - dim, 1.0F); } else { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, dim, 1.0F); } super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding); if (!te.isAttachedNeighbor(x - 1, y, z)) { this.setBlockBounds(0.0F, 0.0F, 0.0F, dim, 1.0F, 1.0F); super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding); } if (!te.isAttachedNeighbor(x, y, z - 1)) { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, dim); super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding); } if (!te.isAttachedNeighbor(x + 1, y, z)) { this.setBlockBounds(1.0F - dim, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding); } if (!te.isAttachedNeighbor(x, y, z + 1)) { this.setBlockBounds(0.0F, 0.0F, 1.0F - dim, 1.0F, 1.0F, 1.0F); super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding); } this.setBlockBoundsForItemRender(); } public void setBlockBoundsForItemRender() { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } public int getRenderType() { return ClientProxy.largePotRenderID; } public int getRenderBlockPass() { return 1; } public boolean canRenderInPass(int pass) { ClientProxy.renderPass = pass; return true; } public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side) { return side != ForgeDirection.UP; } public boolean shouldSideBeRendered(IBlockAccess blockAccess, int x, int y, int z, int side) { int nx = x; int nz = z; switch (side) { case 0: ++y; break; case 1: --y; break; case 2: ++z; break; case 3: --z; break; case 4: ++x; break; case 5: --x; } if (side >= 2 && side < 6) { TileEntityGarden te = this.getTileEntity(blockAccess, x, y, z); if (te != null) { return !te.isAttachedNeighbor(nx, y, nz); } } return side != 1; } public ArrayList getDrops(World world, int x, int y, int z, int metadata, int fortune) { TileEntityLargePot te = this.getTileEntity(world, x, y, z); ArrayList items = new ArrayList(); int count = this.quantityDropped(metadata, fortune, world.rand); for (int i = 0; i < count; ++i) { Item item = this.getItemDropped(metadata, world.rand, fortune); int packedMeta = metadata | (te != null ? te.getCarving() << 8 : 0); if (item != null) { items.add(new ItemStack(item, 1, packedMeta)); } } return items; } public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) { return willHarvest ? true : super.removedByPlayer(world, player, x, y, z, willHarvest); } public void harvestBlock(World world, EntityPlayer player, int x, int y, int z, int meta) { super.harvestBlock(world, player, x, y, z, meta); world.setBlockToAir(x, y, z); } private boolean isSubstrateSolid(Item item) { Block block = Block.getBlockFromItem(item); return block != Blocks.water; } public boolean canSustainPlant(IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plantable) { TileEntityGarden gardenTile = this.getTileEntity(world, x, y, z); EnumPlantType plantType = plantable.getPlantType(world, x, y, z); return plantType == EnumPlantType.Crop ? this.substrateSupportsCrops(gardenTile.getSubstrate()) : false; } protected boolean substrateSupportsCrops(ItemStack substrate) { if (substrate != null && substrate.getItem() != null) { if (Block.getBlockFromItem(substrate.getItem()) == ModBlocks.gardenFarmland) { return true; } else { return Block.getBlockFromItem(substrate.getItem()) == Blocks.farmland; } } else { return false; } } protected boolean applySubstrateToGarden(World world, int x, int y, int z, EntityPlayer player, int slot, ItemStack itemStack) { if (this.getGardenSubstrate(world, x, y, z, slot) != null) { return false; } else if (itemStack.getItem() == Items.water_bucket) { TileEntityGarden garden = this.getTileEntity(world, x, y, z); garden.setSubstrate(new ItemStack(Blocks.water)); garden.markDirty(); if (player != null && !player.capabilities.isCreativeMode) { player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.bucket)); } world.markBlockForUpdate(x, y, z); return true; } else { return super.applySubstrateToGarden(world, x, y, z, player, slot, itemStack); } } protected boolean applyItemToGarden(World world, int x, int y, int z, EntityPlayer player, ItemStack itemStack, float hitX, float hitY, float hitZ, boolean hitValid) { ItemStack item = itemStack == null ? player.inventory.getCurrentItem() : itemStack; if (item == null) { return false; } else { TileEntityGarden garden = this.getTileEntity(world, x, y, z); if (garden.getSubstrate() != null) { if (item.getItem() == Items.bucket) { if (Block.getBlockFromItem( garden.getSubstrate() .getItem()) == Blocks.water) { player.inventory .setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.water_bucket)); garden.setSubstrate((ItemStack) null); garden.markDirty(); world.markBlockForUpdate(x, y, z); } return true; } if (item.getItem() == Items.water_bucket) { this.applyWaterToSubstrate(world, x, y, z, garden, player); return true; } if (item.getItem() instanceof ItemHoe) { this.applyHoeToSubstrate(world, x, y, z, garden, player); return true; } } return super.applyItemToGarden(world, x, y, z, player, itemStack, hitX, hitY, hitZ, hitValid); } } protected void applyWaterToSubstrate(World world, int x, int y, int z, TileEntityGarden tile, EntityPlayer player) { if (Block.getBlockFromItem( tile.getSubstrate() .getItem()) == Blocks.dirt) { tile.setSubstrate( new ItemStack(Blocks.farmland, 1, 7), new ItemStack( Blocks.dirt, 1, tile.getSubstrate() .getItemDamage())); tile.markDirty(); world.markBlockForUpdate(x, y, z); } } protected boolean applyHoeToSubstrate(World world, int x, int y, int z, TileEntityGarden tile, EntityPlayer player) { Block substrate = Block.getBlockFromItem( tile.getSubstrate() .getItem()); if (substrate != Blocks.dirt && substrate != Blocks.grass) { if (substrate != ModBlocks.gardenSoil) { return false; } tile.setSubstrate(new ItemStack(ModBlocks.gardenFarmland), new ItemStack(ModBlocks.gardenSoil)); } else { tile.setSubstrate( new ItemStack(Blocks.farmland, 1, 7), new ItemStack( Blocks.dirt, 1, tile.getSubstrate() .getItemDamage())); } tile.markDirty(); world.markBlockForUpdate(x, y, z); world.playSoundEffect( (double) ((float) x + 0.5F), (double) ((float) y + 0.5F), (double) ((float) z + 0.5F), Blocks.farmland.stepSound.getStepResourcePath(), (Blocks.farmland.stepSound.getVolume() + 1.0F) / 2.0F, Blocks.farmland.stepSound.getPitch() * 0.8F); return true; } public boolean applyHoe(World world, int x, int y, int z) { TileEntityGarden te = this.getTileEntity(world, x, y, z); return te != null && te.isEmpty() ? this.applyHoeToSubstrate(world, x, y, z, te, (EntityPlayer) null) : false; } public TileEntityLargePot getTileEntity(IBlockAccess world, int x, int y, int z) { TileEntity te = world.getTileEntity(x, y, z); return te != null && te instanceof TileEntityLargePot ? (TileEntityLargePot) te : null; } public TileEntityLargePot createNewTileEntity(World world, int data) { return new TileEntityLargePot(); } public Vec3[] getChainAttachPoints(int side) { return side == 1 ? chainAttachPoints : null; } @SideOnly(Side.CLIENT) public IIcon getOverlayIcon(int data) { return this.iconOverlayArray[data] != null ? this.iconOverlayArray[data] : null; } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { this.iconOverlayArray = new IIcon[256]; for (int i = 1; i < this.iconOverlayArray.length; ++i) { PatternConfig pattern = GardenContainers.config.getPattern(i); if (pattern != null && pattern.getOverlay() != null) { this.iconOverlayArray[i] = iconRegister.registerIcon("GardenContainers:" + pattern.getOverlay()); } } } public Block getSoil(World world, int x, int y, int z) { ItemStack substrate = this.getGardenSubstrate(world, x, y, z, this.getDefaultSlot()); return substrate != null && substrate.getItem() != null && substrate.getItem() instanceof ItemBlock ? ((ItemBlock) substrate.getItem()).field_150939_a : null; } public int getSoilMeta(World world, int x, int y, int z) { ItemStack substrate = this.getGardenSubstrate(world, x, y, z, this.getDefaultSlot()); return substrate != null && substrate.getItem() != null && substrate.getItem() instanceof ItemBlock ? substrate.getItemDamage() : -1; }
private class LocalSlotProfile extends Slot14ProfileBounded {
12
2023-12-12 08:13:16+00:00
24k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java
[ { "identifier": "CommonStatusEnum", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/CommonStatusEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CommonStatusEnum implements IntArrayValuable {\n\n ENABLE(0, \"开启\"),\n DISABLE(1, \"关闭\");\...
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.tenant.config.TenantProperties; import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO; import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantPackageDO; import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper; import cn.iocoder.yudao.module.system.enums.permission.RoleCodeEnum; import cn.iocoder.yudao.module.system.enums.permission.RoleTypeEnum; import cn.iocoder.yudao.module.system.service.permission.MenuService; import cn.iocoder.yudao.module.system.service.permission.PermissionService; import cn.iocoder.yudao.module.system.service.permission.RoleService; import cn.iocoder.yudao.module.system.service.tenant.handler.TenantInfoHandler; import cn.iocoder.yudao.module.system.service.tenant.handler.TenantMenuHandler; import cn.iocoder.yudao.module.system.service.user.AdminUserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO.PACKAGE_ID_SYSTEM; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*;
15,931
package cn.iocoder.yudao.module.system.service.tenant; /** * {@link TenantServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(TenantServiceImpl.class) public class TenantServiceImplTest extends BaseDbUnitTest { @Resource private TenantServiceImpl tenantService; @Resource private TenantMapper tenantMapper; @MockBean
package cn.iocoder.yudao.module.system.service.tenant; /** * {@link TenantServiceImpl} 的单元测试类 * * @author 芋道源码 */ @Import(TenantServiceImpl.class) public class TenantServiceImplTest extends BaseDbUnitTest { @Resource private TenantServiceImpl tenantService; @Resource private TenantMapper tenantMapper; @MockBean
private TenantProperties tenantProperties;
2
2023-12-08 02:48:42+00:00
24k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/stages/GameStage.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.senetboom.game.SenetBoom; import com.senetboom.game.backend.Board; import com.senetboom.game.backend.Coordinate; import com.senetboom.game.backend.Piece; import com.senetboom.game.backend.Tile; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import static com.senetboom.game.SenetBoom.*; import static com.senetboom.game.backend.Board.getBoard; import static com.senetboom.game.backend.Board.setAllowedTile;
19,537
package com.senetboom.game.frontend.stages; public class GameStage { public static Stage drawMap() { Stage stage = new Stage(); // create a root table for the tiles Table root = new Table(); root.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createMapStacks(board, root, i); } root.row(); // second row for(int i=19; i>=10; i--) { createMapStacks(board, root, i); } root.row(); // third row for(int i=20; i<30; i++) { createMapStacks(board, root, i); } stage.addActor(root); return stage; } public static Stage drawBoard() { inGame = true; Stage stage = new Stage(); // create a root table for the pawns Table pawnRoot = new Table(); pawnRoot.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // second row for(int i=19; i>=10; i--) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // third row for(int i=20; i<30; i++) { createStacks(board, pawnRoot, i); } stage.addActor(pawnRoot); // add a Table with a single EXIT and OPTION Button Table exitTable = new Table(); // HELP BUTTON THAT SWITCHES THE BOOLEAN displayHelp TextButton helpButton = new TextButton("HELP", skin); helpButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHelp = !displayHelp; } }); exitTable.add(helpButton).padBottom(tileSize/4); // in the same row, add a hint button TextButton hintButton = new TextButton("HINT", skin); hintButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHint = !displayHint; needRender = true; } }); exitTable.add(hintButton).padBottom(tileSize/4).padLeft(tileSize/8); exitTable.row(); // add a skipTurn button TextButton skipTurnButton = new TextButton("END TURN", skin); skipTurnButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { skipTurn = true; } }); exitTable.add(skipTurnButton).padBottom(tileSize/4); exitTable.row(); // add the Options button TextButton optionsButton = new TextButton("OPTIONS", skin); optionsButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { // TODO } }); exitTable.add(optionsButton).padBottom(tileSize/4); exitTable.row(); // add the exit button TextButton exitButton = new TextButton("EXIT", skin); exitButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { createMenu(); } }); exitTable.add(exitButton).padBottom(tileSize/4); exitTable.setPosition(Gdx.graphics.getWidth()-tileSize*3, tileSize*1.5f); stage.addActor(exitTable); return stage; } public static void createStacks(final Tile[] board, Table pawnRoot, final int i){ final Tile tile = board[i]; // ----------------- Pawn Stack ----------------- // for the stack above being the pawn on the tile final Stack pawnStack = new Stack(); pawnStack.setSize(80, 80); // EMPTY Texture Image empty = new Image(emptyTexture); empty.setSize(80, 80); pawnStack.addActor(empty); // if the tile has a piece, draw the piece if(tile.hasPiece()) { if(!(emptyVariable == tile.getPosition())) { // if tile not the empty currently bot move pawn position Image piece;
package com.senetboom.game.frontend.stages; public class GameStage { public static Stage drawMap() { Stage stage = new Stage(); // create a root table for the tiles Table root = new Table(); root.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createMapStacks(board, root, i); } root.row(); // second row for(int i=19; i>=10; i--) { createMapStacks(board, root, i); } root.row(); // third row for(int i=20; i<30; i++) { createMapStacks(board, root, i); } stage.addActor(root); return stage; } public static Stage drawBoard() { inGame = true; Stage stage = new Stage(); // create a root table for the pawns Table pawnRoot = new Table(); pawnRoot.setFillParent(true); // iterate through the board, at each tile final Tile[] board = getBoard(); // first row for(int i=0; i<10; i++) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // second row for(int i=19; i>=10; i--) { createStacks(board, pawnRoot, i); } pawnRoot.row(); // third row for(int i=20; i<30; i++) { createStacks(board, pawnRoot, i); } stage.addActor(pawnRoot); // add a Table with a single EXIT and OPTION Button Table exitTable = new Table(); // HELP BUTTON THAT SWITCHES THE BOOLEAN displayHelp TextButton helpButton = new TextButton("HELP", skin); helpButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHelp = !displayHelp; } }); exitTable.add(helpButton).padBottom(tileSize/4); // in the same row, add a hint button TextButton hintButton = new TextButton("HINT", skin); hintButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { displayHint = !displayHint; needRender = true; } }); exitTable.add(hintButton).padBottom(tileSize/4).padLeft(tileSize/8); exitTable.row(); // add a skipTurn button TextButton skipTurnButton = new TextButton("END TURN", skin); skipTurnButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { skipTurn = true; } }); exitTable.add(skipTurnButton).padBottom(tileSize/4); exitTable.row(); // add the Options button TextButton optionsButton = new TextButton("OPTIONS", skin); optionsButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { // TODO } }); exitTable.add(optionsButton).padBottom(tileSize/4); exitTable.row(); // add the exit button TextButton exitButton = new TextButton("EXIT", skin); exitButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { createMenu(); } }); exitTable.add(exitButton).padBottom(tileSize/4); exitTable.setPosition(Gdx.graphics.getWidth()-tileSize*3, tileSize*1.5f); stage.addActor(exitTable); return stage; } public static void createStacks(final Tile[] board, Table pawnRoot, final int i){ final Tile tile = board[i]; // ----------------- Pawn Stack ----------------- // for the stack above being the pawn on the tile final Stack pawnStack = new Stack(); pawnStack.setSize(80, 80); // EMPTY Texture Image empty = new Image(emptyTexture); empty.setSize(80, 80); pawnStack.addActor(empty); // if the tile has a piece, draw the piece if(tile.hasPiece()) { if(!(emptyVariable == tile.getPosition())) { // if tile not the empty currently bot move pawn position Image piece;
if(tile.getPiece().getColour() == Piece.Color.BLACK) {
3
2023-12-05 22:19:00+00:00
24k
sinbad-navigator/erp-crm
center/src/main/java/com/ec/web/controller/system/SysDictTypeController.java
[ { "identifier": "UserConstants", "path": "common/src/main/java/com/ec/common/constant/UserConstants.java", "snippet": "public class UserConstants {\n /**\n * 平台内系统用户的唯一标志\n */\n public static final String SYS_USER = \"SYS_USER\";\n\n /**\n * 正常状态\n */\n public static final St...
import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; 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 com.ec.common.annotation.Log; import com.ec.common.constant.UserConstants; import com.ec.common.core.controller.BaseController; import com.ec.common.core.domain.AjaxResult; import com.ec.common.core.domain.entity.SysDictType; import com.ec.common.core.page.TableDataInfo; import com.ec.common.enums.BusinessType; import com.ec.common.utils.poi.ExcelUtil; import com.ec.sys.service.ISysDictTypeService;
14,652
package com.ec.web.controller.system; /** * 数据字典信息 * * @author ec */ @RestController @RequestMapping("/system/dict/type") public class SysDictTypeController extends BaseController { @Autowired private ISysDictTypeService dictTypeService; @PreAuthorize("@ss.hasPermi('system:dict:list')") @GetMapping("/list") public TableDataInfo list(SysDictType dictType) { startPage(); List<SysDictType> list = dictTypeService.selectDictTypeList(dictType); return getDataTable(list); } @Log(title = "字典类型", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:dict:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysDictType dictType) { List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
package com.ec.web.controller.system; /** * 数据字典信息 * * @author ec */ @RestController @RequestMapping("/system/dict/type") public class SysDictTypeController extends BaseController { @Autowired private ISysDictTypeService dictTypeService; @PreAuthorize("@ss.hasPermi('system:dict:list')") @GetMapping("/list") public TableDataInfo list(SysDictType dictType) { startPage(); List<SysDictType> list = dictTypeService.selectDictTypeList(dictType); return getDataTable(list); } @Log(title = "字典类型", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:dict:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysDictType dictType) { List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
6
2023-12-07 14:23:12+00:00
24k
Crydsch/the-one
src/report/NodeDensityReport.java
[ { "identifier": "Coord", "path": "src/core/Coord.java", "snippet": "public class Coord implements Cloneable, Comparable<Coord> {\n\tprivate double x;\n\tprivate double y;\n\n\t/**\n\t * Constructor.\n\t * @param x Initial X-coordinate\n\t * @param y Initial Y-coordinate\n\t */\n\tpublic Coord(double x, ...
import core.Coord; import core.DTNHost; import core.Settings; import core.SettingsError; import core.SimScenario; import java.util.ArrayList; import java.util.List;
17,711
package report; /** * <p>Sampling report that counts the number of nodes in grid over the * simulation area. Output format is: G_x G_y average count_1, count_2, ... * Where G_x and G_y are the coordinates of the grid square [0, 1, ...] and * count_n is the count during the nth sample. * * <p>The report can be configured to output a gnuplot script file that * produces a heat map graph of the node densities. * * @author teemuk */ public class NodeDensityReport extends SamplingReport { //========================================================================// // Settings //========================================================================// /** Number of divisions along the x-axis ({@value}). */ public static final String X_COUNT_SETTING = "xCount"; /** Number of divisions along the y-axis ({@value}). */ public static final String Y_COUNT_SETTING = "yCount"; /** Boolean setting to output gnuplot file ({@value}). */ public static final String GNUPLOT_SETTING = "outputGnuplot"; /** Setting for gnuplot terminal, i.e., terminal set X ({@value}). */ public static final String GNUPLOT_TERMINAL_SETTING = "gnuplotTerminal"; /** Setting for file extension for files generated by gnuplot ({@value}). */ public static final String GNUPLOT_FILE_EXTENSION_SETTING = "gnuplotFileExtension"; /** Boolean setting to output only the average ({@value}). */ public static final String ONLY_AVERAGE_SETTING = "onlyAverage"; /** Default number of divisions along the x-axis ({@value}). */ public static final int DEFAULT_X_COUNT = 10; /** Default number of divisions along the y-axis ({@value}). */ public static final int DEFAULT_Y_COUNT = 10; /** Default value for outputting gnuplot instead of raw data ({@value}). */ public static final boolean DEFAULT_GNUPLOT = false; /** Default value for gnuplot terminal ({@value}). */ public static final String DEFAULT_GNUPLOT_TERMINAL = "png size 1024,768"; public static final String DEFAULT_GNUPLOT_FILE_EXTENSION = "png"; /** Default value for outputting only the average density ({@value}). */ public static final boolean DEFAULT_ONLY_AVERAGE = false; //========================================================================// //========================================================================// // Instance vars //========================================================================// private final int horizontalCount; private final int verticalCount; private final double divisionWidth; private final double divisionHeight; private final boolean gnuplot; private final String gnuplotTerminal; private final String gnuplotFileExtension; private final boolean onlyAverage; private final String runName; private final List<int[][]> samples; //========================================================================// //========================================================================// // Constructor //========================================================================// public NodeDensityReport() { super();
package report; /** * <p>Sampling report that counts the number of nodes in grid over the * simulation area. Output format is: G_x G_y average count_1, count_2, ... * Where G_x and G_y are the coordinates of the grid square [0, 1, ...] and * count_n is the count during the nth sample. * * <p>The report can be configured to output a gnuplot script file that * produces a heat map graph of the node densities. * * @author teemuk */ public class NodeDensityReport extends SamplingReport { //========================================================================// // Settings //========================================================================// /** Number of divisions along the x-axis ({@value}). */ public static final String X_COUNT_SETTING = "xCount"; /** Number of divisions along the y-axis ({@value}). */ public static final String Y_COUNT_SETTING = "yCount"; /** Boolean setting to output gnuplot file ({@value}). */ public static final String GNUPLOT_SETTING = "outputGnuplot"; /** Setting for gnuplot terminal, i.e., terminal set X ({@value}). */ public static final String GNUPLOT_TERMINAL_SETTING = "gnuplotTerminal"; /** Setting for file extension for files generated by gnuplot ({@value}). */ public static final String GNUPLOT_FILE_EXTENSION_SETTING = "gnuplotFileExtension"; /** Boolean setting to output only the average ({@value}). */ public static final String ONLY_AVERAGE_SETTING = "onlyAverage"; /** Default number of divisions along the x-axis ({@value}). */ public static final int DEFAULT_X_COUNT = 10; /** Default number of divisions along the y-axis ({@value}). */ public static final int DEFAULT_Y_COUNT = 10; /** Default value for outputting gnuplot instead of raw data ({@value}). */ public static final boolean DEFAULT_GNUPLOT = false; /** Default value for gnuplot terminal ({@value}). */ public static final String DEFAULT_GNUPLOT_TERMINAL = "png size 1024,768"; public static final String DEFAULT_GNUPLOT_FILE_EXTENSION = "png"; /** Default value for outputting only the average density ({@value}). */ public static final boolean DEFAULT_ONLY_AVERAGE = false; //========================================================================// //========================================================================// // Instance vars //========================================================================// private final int horizontalCount; private final int verticalCount; private final double divisionWidth; private final double divisionHeight; private final boolean gnuplot; private final String gnuplotTerminal; private final String gnuplotFileExtension; private final boolean onlyAverage; private final String runName; private final List<int[][]> samples; //========================================================================// //========================================================================// // Constructor //========================================================================// public NodeDensityReport() { super();
final Settings settings = super.getSettings();
2
2023-12-10 15:51:41+00:00
24k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/TiltSensor.java
[ { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java", "snippet": "public class Emulator {\n\n\t//gets\n\tfinal static public int IN_MENU = 1;\n\tfinal static public int IN_GAME = 2;\n\tfinal static public int NUMBTNS = 3;\n\tfinal static public ...
import java.text.DecimalFormat; import android.annotation.SuppressLint; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Build; import android.view.Surface; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.helpers.PrefsHelper;
14,759
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ //http://code.google.com/p/andengine/source/diff?spec=svn029966d918208057cef0cffcb84d0e32c3beb646&r=029966d918208057cef0cffcb84d0e32c3beb646&format=side&path=/src/org/anddev/andengine/sensor/orientation/OrientationData.java //NOTAS: usar acelerometro es suficiente, package com.seleuco.mame4droid.input; public class TiltSensor { DecimalFormat df = new DecimalFormat("000.00");
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ //http://code.google.com/p/andengine/source/diff?spec=svn029966d918208057cef0cffcb84d0e32c3beb646&r=029966d918208057cef0cffcb84d0e32c3beb646&format=side&path=/src/org/anddev/andengine/sensor/orientation/OrientationData.java //NOTAS: usar acelerometro es suficiente, package com.seleuco.mame4droid.input; public class TiltSensor { DecimalFormat df = new DecimalFormat("000.00");
protected MAME4droid mm = null;
1
2023-12-18 11:16:18+00:00
24k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/sbmenu/storage/GUIStorageIconSelection.java
[ { "identifier": "DataHandler", "path": "generic/src/main/java/net/swofty/types/generic/data/DataHandler.java", "snippet": "public class DataHandler {\n public static Map<UUID, DataHandler> userCache = new HashMap<>();\n @Getter\n private UUID uuid;\n private final Map<String, Datapoint> data...
import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.swofty.types.generic.data.DataHandler; import net.swofty.types.generic.data.datapoints.DatapointStorage; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.SkyBlockPaginatedGUI; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.item.ItemType; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.utility.PaginationList; import net.swofty.types.generic.utility.StringUtility; import java.util.ArrayList; import java.util.List;
20,393
package net.swofty.types.generic.gui.inventory.inventories.sbmenu.storage; public class GUIStorageIconSelection extends SkyBlockPaginatedGUI<Material> { private int page; private SkyBlockInventoryGUI previous; protected GUIStorageIconSelection(int page, SkyBlockInventoryGUI previous) { super(InventoryType.CHEST_6_ROW); this.page = page; this.previous = previous; } @Override public boolean allowHotkeying() { return false; } @Override public void onClose(InventoryCloseEvent e, CloseReason reason) { } @Override public void suddenlyQuit(Inventory inventory, SkyBlockPlayer player) { } @Override public void onBottomClick(InventoryPreClickEvent e) { e.setCancelled(true); } @Override protected int[] getPaginatedSlots() { return new int[]{ 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43 }; } @Override protected PaginationList<Material> fillPaged(SkyBlockPlayer player, PaginationList<Material> paged) { paged.add(Material.BARRIER); List<Material> vanilla = new ArrayList<>(Material.values().stream().toList()); vanilla.removeIf((element) -> ItemType.isVanillaReplaced(element.name())); paged.addAll(vanilla); return paged; } @Override protected boolean shouldFilterFromSearch(String query, Material item) { return !item.name().toLowerCase().contains(query.replaceAll(" ", "_").toLowerCase()); } @Override protected void performSearch(SkyBlockPlayer player, String query, int page, int maxPage) { border(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE, "")); set(GUIClickableItem.getCloseItem(49)); if (previous != null) set(GUIClickableItem.getGoBackItem(48, previous)); set(createSearchItem(this, 50, query)); if (page > 1) { set(createNavigationButton(this, 45, query, page, false)); } if (page < maxPage) { set(createNavigationButton(this, 53, query, page, true)); } } @Override protected String getTitle(SkyBlockPlayer player, String query, int page, PaginationList<Material> paged) { return "Choose an Icon (" + page + "/" + paged.getPageCount() + ")"; } @Override protected GUIClickableItem createItemFor(Material item, int slot, SkyBlockPlayer player) { return new GUIClickableItem(slot) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { DatapointStorage.PlayerStorage storage = player.getDataHandler().get(DataHandler.Data.STORAGE, DatapointStorage.class).getValue(); if (item == Material.BARRIER) { storage.setDisplay(page, Material.PURPLE_STAINED_GLASS_PANE); new GUIStorage().open(player); return; } storage.setDisplay(page, item); new GUIStorage().open(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack( (item == Material.BARRIER ? "§cReset" :
package net.swofty.types.generic.gui.inventory.inventories.sbmenu.storage; public class GUIStorageIconSelection extends SkyBlockPaginatedGUI<Material> { private int page; private SkyBlockInventoryGUI previous; protected GUIStorageIconSelection(int page, SkyBlockInventoryGUI previous) { super(InventoryType.CHEST_6_ROW); this.page = page; this.previous = previous; } @Override public boolean allowHotkeying() { return false; } @Override public void onClose(InventoryCloseEvent e, CloseReason reason) { } @Override public void suddenlyQuit(Inventory inventory, SkyBlockPlayer player) { } @Override public void onBottomClick(InventoryPreClickEvent e) { e.setCancelled(true); } @Override protected int[] getPaginatedSlots() { return new int[]{ 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43 }; } @Override protected PaginationList<Material> fillPaged(SkyBlockPlayer player, PaginationList<Material> paged) { paged.add(Material.BARRIER); List<Material> vanilla = new ArrayList<>(Material.values().stream().toList()); vanilla.removeIf((element) -> ItemType.isVanillaReplaced(element.name())); paged.addAll(vanilla); return paged; } @Override protected boolean shouldFilterFromSearch(String query, Material item) { return !item.name().toLowerCase().contains(query.replaceAll(" ", "_").toLowerCase()); } @Override protected void performSearch(SkyBlockPlayer player, String query, int page, int maxPage) { border(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE, "")); set(GUIClickableItem.getCloseItem(49)); if (previous != null) set(GUIClickableItem.getGoBackItem(48, previous)); set(createSearchItem(this, 50, query)); if (page > 1) { set(createNavigationButton(this, 45, query, page, false)); } if (page < maxPage) { set(createNavigationButton(this, 53, query, page, true)); } } @Override protected String getTitle(SkyBlockPlayer player, String query, int page, PaginationList<Material> paged) { return "Choose an Icon (" + page + "/" + paged.getPageCount() + ")"; } @Override protected GUIClickableItem createItemFor(Material item, int slot, SkyBlockPlayer player) { return new GUIClickableItem(slot) { @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { DatapointStorage.PlayerStorage storage = player.getDataHandler().get(DataHandler.Data.STORAGE, DatapointStorage.class).getValue(); if (item == Material.BARRIER) { storage.setDisplay(page, Material.PURPLE_STAINED_GLASS_PANE); new GUIStorage().open(player); return; } storage.setDisplay(page, item); new GUIStorage().open(player); } @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack( (item == Material.BARRIER ? "§cReset" :
StringUtility.toNormalCase(item.name().replace("minecraft:", ""))),
10
2023-12-14 09:51:15+00:00
24k
Tianscar/uxgl
base/src/main/java/unrefined/nio/Allocator.java
[ { "identifier": "Environment", "path": "base/src/main/java/unrefined/context/Environment.java", "snippet": "public class Environment implements Map<Object, Object> {\n\n private static final Environment system = new Environment(() -> new ConcurrentHashMap<>(System.getenv()), \"SYSTEM ENVIRONMENT VARI...
import unrefined.context.Environment; import unrefined.math.FastMath; import unrefined.util.foreign.Foreign; import java.io.IOException; import java.math.BigInteger; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.MappedByteBuffer; import java.nio.ShortBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset;
20,184
package unrefined.nio; /** * Provides facilities to directly access memory from Java. */ public abstract class Allocator { private static volatile Allocator INSTANCE; private static final Object INSTANCE_LOCK = new Object(); public static Allocator defaultInstance() { if (INSTANCE == null) synchronized (INSTANCE_LOCK) {
package unrefined.nio; /** * Provides facilities to directly access memory from Java. */ public abstract class Allocator { private static volatile Allocator INSTANCE; private static final Object INSTANCE_LOCK = new Object(); public static Allocator defaultInstance() { if (INSTANCE == null) synchronized (INSTANCE_LOCK) {
if (INSTANCE == null) INSTANCE = Environment.global().get("unrefined.runtime.allocator", Allocator.class);
0
2023-12-15 19:03:31+00:00
24k
litongjava/next-jfinal
src/main/java/com/jfinal/plugin/ehcache/CacheInterceptor.java
[ { "identifier": "Interceptor", "path": "src/main/java/com/jfinal/aop/Interceptor.java", "snippet": "public interface Interceptor {\n\tvoid intercept(Invocation inv);\n}" }, { "identifier": "Invocation", "path": "src/main/java/com/jfinal/aop/Invocation.java", "snippet": "@SuppressWarnings...
import com.jfinal.render.Render; import com.jfinal.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.core.Controller; import com.jfinal.plugin.cache.CacheName;
16,342
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.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.jfinal.plugin.ehcache; /** * CacheInterceptor. */ public class CacheInterceptor implements Interceptor { private static final String renderKey = "_renderKey"; private static ConcurrentHashMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<String, ReentrantLock>(512); private ReentrantLock getLock(String key) { ReentrantLock lock = lockMap.get(key); if (lock != null) { return lock; } lock = new ReentrantLock(); ReentrantLock previousLock = lockMap.putIfAbsent(key, lock); return previousLock == null ? lock : previousLock; } final public void intercept(Invocation inv) { Controller controller = inv.getController(); String cacheName = buildCacheName(inv, controller); String cacheKey = buildCacheKey(inv, controller); Map<String, Object> cacheData = CacheKit.get(cacheName, cacheKey); if (cacheData == null) { Lock lock = getLock(cacheName); lock.lock(); // prevent cache snowslide try { cacheData = CacheKit.get(cacheName, cacheKey); if (cacheData == null) { inv.invoke(); cacheAction(cacheName, cacheKey, controller); return ; } } finally { lock.unlock(); } } useCacheDataAndRender(cacheData, controller); } // TODO 考虑与 EvictInterceptor 一样强制使用 @CacheName protected String buildCacheName(Invocation inv, Controller controller) { CacheName cacheName = inv.getMethod().getAnnotation(CacheName.class); if (cacheName != null) return cacheName.value(); cacheName = controller.getClass().getAnnotation(CacheName.class); return (cacheName != null) ? cacheName.value() : inv.getActionKey(); } protected String buildCacheKey(Invocation inv, Controller controller) { StringBuilder sb = new StringBuilder(inv.getActionKey()); String urlPara = controller.getPara(); if (urlPara != null) sb.append('/').append(urlPara); String queryString = controller.getRequest().getQueryString(); if (queryString != null) sb.append('?').append(queryString); return sb.toString(); } /** * 通过继承 CacheInterceptor 并覆盖此方法支持更多类型的 Render */ protected RenderInfo createRenderInfo(Render render) { return new RenderInfo(render); } protected void cacheAction(String cacheName, String cacheKey, Controller controller) {
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.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.jfinal.plugin.ehcache; /** * CacheInterceptor. */ public class CacheInterceptor implements Interceptor { private static final String renderKey = "_renderKey"; private static ConcurrentHashMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<String, ReentrantLock>(512); private ReentrantLock getLock(String key) { ReentrantLock lock = lockMap.get(key); if (lock != null) { return lock; } lock = new ReentrantLock(); ReentrantLock previousLock = lockMap.putIfAbsent(key, lock); return previousLock == null ? lock : previousLock; } final public void intercept(Invocation inv) { Controller controller = inv.getController(); String cacheName = buildCacheName(inv, controller); String cacheKey = buildCacheKey(inv, controller); Map<String, Object> cacheData = CacheKit.get(cacheName, cacheKey); if (cacheData == null) { Lock lock = getLock(cacheName); lock.lock(); // prevent cache snowslide try { cacheData = CacheKit.get(cacheName, cacheKey); if (cacheData == null) { inv.invoke(); cacheAction(cacheName, cacheKey, controller); return ; } } finally { lock.unlock(); } } useCacheDataAndRender(cacheData, controller); } // TODO 考虑与 EvictInterceptor 一样强制使用 @CacheName protected String buildCacheName(Invocation inv, Controller controller) { CacheName cacheName = inv.getMethod().getAnnotation(CacheName.class); if (cacheName != null) return cacheName.value(); cacheName = controller.getClass().getAnnotation(CacheName.class); return (cacheName != null) ? cacheName.value() : inv.getActionKey(); } protected String buildCacheKey(Invocation inv, Controller controller) { StringBuilder sb = new StringBuilder(inv.getActionKey()); String urlPara = controller.getPara(); if (urlPara != null) sb.append('/').append(urlPara); String queryString = controller.getRequest().getQueryString(); if (queryString != null) sb.append('?').append(queryString); return sb.toString(); } /** * 通过继承 CacheInterceptor 并覆盖此方法支持更多类型的 Render */ protected RenderInfo createRenderInfo(Render render) { return new RenderInfo(render); } protected void cacheAction(String cacheName, String cacheKey, Controller controller) {
HttpServletRequest request = controller.getRequest();
4
2023-12-19 10:58:33+00:00
24k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/listener/EventListenerRegister.java
[ { "identifier": "ConfigGUI", "path": "src/java/xyz/apfelmus/cheeto/client/clickgui/ConfigGUI.java", "snippet": "@Metadata(mv={1, 6, 0}, k=1, xi=48, d1={\"\\u0000X\\n\\u0002\\u0018\\u0002\\n\\u0002\\u0018\\u0002\\n\\u0002\\b\\u0002\\n\\u0002\\u0018\\u0002\\n\\u0002\\b\\b\\n\\u0002\\u0018\\u0002\\n\\u0002...
import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiChat; import net.minecraft.entity.EntityLivingBase; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.client.event.RenderLivingEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import xyz.apfelmus.cheeto.client.clickgui.ConfigGUI; import xyz.apfelmus.cheeto.client.events.BackgroundDrawnEvent; import xyz.apfelmus.cheeto.client.events.ClientTickEvent; import xyz.apfelmus.cheeto.client.events.EntityInteractEvent; import xyz.apfelmus.cheeto.client.events.MouseInputEvent; import xyz.apfelmus.cheeto.client.events.PlayerInteractEvent; import xyz.apfelmus.cheeto.client.events.Render2DEvent; import xyz.apfelmus.cheeto.client.events.Render3DEvent; import xyz.apfelmus.cheeto.client.events.RenderLivingEventPre; import xyz.apfelmus.cheeto.client.events.WorldUnloadEvent;
15,660
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.gui.GuiChat * net.minecraft.entity.EntityLivingBase * net.minecraftforge.client.event.ClientChatReceivedEvent * net.minecraftforge.client.event.GuiOpenEvent * net.minecraftforge.client.event.GuiScreenEvent$BackgroundDrawnEvent * net.minecraftforge.client.event.RenderLivingEvent$Pre * net.minecraftforge.client.event.RenderWorldLastEvent * net.minecraftforge.event.entity.player.EntityInteractEvent * net.minecraftforge.event.entity.player.PlayerInteractEvent * net.minecraftforge.event.world.WorldEvent$Unload * net.minecraftforge.fml.common.eventhandler.SubscribeEvent * net.minecraftforge.fml.common.gameevent.InputEvent$MouseInputEvent * net.minecraftforge.fml.common.gameevent.TickEvent$ClientTickEvent * net.minecraftforge.fml.common.gameevent.TickEvent$Phase * net.minecraftforge.fml.common.gameevent.TickEvent$RenderTickEvent */ package xyz.apfelmus.cheeto.client.listener; public class EventListenerRegister { private static Minecraft mc = Minecraft.func_71410_x(); @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.END || EventListenerRegister.mc.field_71439_g == null || EventListenerRegister.mc.field_71441_e == null) { return; } new ClientTickEvent().call(); } @SubscribeEvent public void onRenderGui(TickEvent.RenderTickEvent event) { if (EventListenerRegister.mc.field_71439_g == null || EventListenerRegister.mc.field_71441_e == null || EventListenerRegister.mc.field_71474_y.field_74330_P || EventListenerRegister.mc.field_71462_r != null && !(EventListenerRegister.mc.field_71462_r instanceof GuiChat) && !(EventListenerRegister.mc.field_71462_r instanceof ConfigGUI)) { return; } new Render2DEvent().call(); } @SubscribeEvent public void onRenderWorld(RenderWorldLastEvent event) {
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.gui.GuiChat * net.minecraft.entity.EntityLivingBase * net.minecraftforge.client.event.ClientChatReceivedEvent * net.minecraftforge.client.event.GuiOpenEvent * net.minecraftforge.client.event.GuiScreenEvent$BackgroundDrawnEvent * net.minecraftforge.client.event.RenderLivingEvent$Pre * net.minecraftforge.client.event.RenderWorldLastEvent * net.minecraftforge.event.entity.player.EntityInteractEvent * net.minecraftforge.event.entity.player.PlayerInteractEvent * net.minecraftforge.event.world.WorldEvent$Unload * net.minecraftforge.fml.common.eventhandler.SubscribeEvent * net.minecraftforge.fml.common.gameevent.InputEvent$MouseInputEvent * net.minecraftforge.fml.common.gameevent.TickEvent$ClientTickEvent * net.minecraftforge.fml.common.gameevent.TickEvent$Phase * net.minecraftforge.fml.common.gameevent.TickEvent$RenderTickEvent */ package xyz.apfelmus.cheeto.client.listener; public class EventListenerRegister { private static Minecraft mc = Minecraft.func_71410_x(); @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.END || EventListenerRegister.mc.field_71439_g == null || EventListenerRegister.mc.field_71441_e == null) { return; } new ClientTickEvent().call(); } @SubscribeEvent public void onRenderGui(TickEvent.RenderTickEvent event) { if (EventListenerRegister.mc.field_71439_g == null || EventListenerRegister.mc.field_71441_e == null || EventListenerRegister.mc.field_71474_y.field_74330_P || EventListenerRegister.mc.field_71462_r != null && !(EventListenerRegister.mc.field_71462_r instanceof GuiChat) && !(EventListenerRegister.mc.field_71462_r instanceof ConfigGUI)) { return; } new Render2DEvent().call(); } @SubscribeEvent public void onRenderWorld(RenderWorldLastEvent event) {
new Render3DEvent(event.partialTicks).call();
7
2023-12-21 16:22:25+00:00
24k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/dexbacked/instruction/DexBackedInstruction3rc.java
[ { "identifier": "Opcode", "path": "app/src/main/java/org/jf/dexlib2/Opcode.java", "snippet": "public enum Opcode {\n NOP(0x00, \"nop\", ReferenceType.NONE, Format.Format10x, Opcode.CAN_CONTINUE),\n MOVE(0x01, \"move\", ReferenceType.NONE, Format.Format12x, Opcode.CAN_CONTINUE | Opcode.SETS_REGISTE...
import androidx.annotation.NonNull; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.dexbacked.DexBackedDexFile; import org.jf.dexlib2.dexbacked.reference.DexBackedReference; import org.jf.dexlib2.iface.UpdateReference; import org.jf.dexlib2.iface.instruction.formats.Instruction3rc; import org.jf.dexlib2.iface.reference.Reference; import org.jf.dexlib2.writer.builder.DexBuilder;
20,403
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked.instruction; public class DexBackedInstruction3rc extends DexBackedInstruction implements Instruction3rc, UpdateReference { private Reference reference = null; public DexBackedInstruction3rc(@NonNull DexBackedDexFile dexFile,
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked.instruction; public class DexBackedInstruction3rc extends DexBackedInstruction implements Instruction3rc, UpdateReference { private Reference reference = null; public DexBackedInstruction3rc(@NonNull DexBackedDexFile dexFile,
@NonNull Opcode opcode,
0
2023-12-16 11:11:16+00:00
24k
123yyh123/xiaofanshu
xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/impl/UserServiceImpl.java
[ { "identifier": "Result", "path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java", "snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yyh.xfs.common.domain.Result; import com.yyh.xfs.common.myEnum.ExceptionMsgEnum; import com.yyh.xfs.common.redis.constant.RedisConstant; import com.yyh.xfs.common.redis.utils.RedisCache; import com.yyh.xfs.common.redis.utils.RedisKey; import com.yyh.xfs.common.utils.CodeUtil; import com.yyh.xfs.common.utils.Md5Util; import com.yyh.xfs.common.utils.ResultUtil; import com.yyh.xfs.common.utils.TimeUtil; import com.yyh.xfs.common.web.exception.BusinessException; import com.yyh.xfs.common.web.exception.SystemException; import com.yyh.xfs.common.web.properties.JwtProperties; import com.yyh.xfs.common.web.utils.IPUtils; import com.yyh.xfs.common.web.utils.JWTUtil; import com.yyh.xfs.user.domain.UserAttentionDO; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.mapper.UserAttentionMapper; import com.yyh.xfs.user.mapper.UserFansMapper; import com.yyh.xfs.user.service.UserService; import com.yyh.xfs.user.mapper.UserMapper; import com.yyh.xfs.user.vo.RegisterInfoVO; import com.yyh.xfs.user.vo.UserTrtcVO; import com.yyh.xfs.user.vo.UserVO; import com.yyh.xfs.user.vo.ViewUserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.sql.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects;
15,596
* 修改用户昵称 * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateNickname(UserVO userVO) { checkField(userVO.getId(),userVO.getNickname()); if (userVO.getNickname().length() > 12 || userVO.getNickname().length() < 2) { return ResultUtil.errorPost("昵称长度为2-12位"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "nickname", userVO.getNickname() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改昵称成功", null); } /** * 修改用户简介 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateIntroduction(UserVO userVO) { checkField(userVO.getId(),userVO.getSelfIntroduction()); if (userVO.getSelfIntroduction().length() > 100) { return ResultUtil.errorPost("简介长度不能超过100字"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "selfIntroduction", userVO.getSelfIntroduction() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改简介成功", null); } /** * 修改用户性别 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateSex(UserVO userVO) { checkField(userVO.getId(),String.valueOf(userVO.getSex())); if (userVO.getSex() < 0 || userVO.getSex() > 1) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "sex", userVO.getSex() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改性别成功", null); } /** * 修改用户生日 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<Integer> updateBirthday(UserVO userVO) { checkField(userVO.getId(),userVO.getBirthday()); Date date = Date.valueOf(userVO.getBirthday()); // 判断生日是否合法,不能大于当前时间 long currentTimeMillis = System.currentTimeMillis(); if (date.getTime() > currentTimeMillis) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } int age = TimeUtil.calculateAge(date.toLocalDate()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "birthday", userVO.getBirthday() ); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "age", age ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改生日成功", age); } /** * 修改用户地区 * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateArea(UserVO userVO) { checkField(userVO.getId(),userVO.getArea()); // 判断地区是否合法,如果不合法则抛出异常,格式为:省 市 区 String[] split = userVO.getArea().split(" "); if (split.length != 3) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } String area; if (split[0].equals(split[1])) { area = split[0] + " " + split[2]; } else { area = userVO.getArea(); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "area", area ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改地区成功", null); } @Override
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override public Result<UserVO> login(String phoneNumber, String password) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); // 利用MD5加密密码,并且通过手机号给密码加盐 // String md5Password = Md5Util.getMd5(phoneNumber + password); // TODO 暂时使用死密码,方便测试 String md5Password = "@yangyahao5036"; queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber).eq(UserDO::getPassword, md5Password); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PASSWORD_ERROR); } return generateUserVO(userDO); } /** * 第三方登录验证 * * @param type 登录类型 * @param code 第三方账号的唯一标识 * @return UserDO */ @Override public Result<UserVO> otherLogin(Integer type, String code) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(LOGIN_TYPE_MAP.get(type), code); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { return ResultUtil.errorPost("该第三方账号未绑定"); } return generateUserVO(userDO); } /** * 第三方登录并绑定手机号 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<UserVO> bindPhone(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_BIND_PHONE_CODE, registerInfoVO.getPhoneNumber()), registerInfoVO.getSmsCode()); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, registerInfoVO.getPhoneNumber()); UserDO userDO = this.getOne(queryWrapper); if (Objects.nonNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_EXIST); } // 注册 UserDO newUserDO = registerAccountByThird(registerInfoVO); return generateUserVO(newUserDO); } /** * 重置密码 * * @param phoneNumber 手机号 * @param password 密码 * @param smsCode 验证码 * @return Result<?> */ @Override public Result<?> resetPassword(String phoneNumber, String password, String smsCode) { boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_RESET_PASSWORD_PHONE_CODE, phoneNumber), smsCode); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_NOT_REGISTER); } // 利用MD5加密密码,并且通过手机号给密码加盐 String md5 = Md5Util.getMd5(phoneNumber + password); userDO.setPassword(md5); try { this.updateById(userDO); } catch (Exception e) { throw new SystemException(ExceptionMsgEnum.DB_ERROR, e); } return ResultUtil.successPost("重置密码成功", null); } /** * 通过手机号注册 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<?> register(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_REGISTER_PHONE_CODE, registerInfoVO.getPhoneNumber()), registerInfoVO.getSmsCode()); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, registerInfoVO.getPhoneNumber()); UserDO userDO = this.getOne(queryWrapper); if (Objects.nonNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_EXIST); } // 注册 UserDO newUserDO = initAccount(registerInfoVO); try { this.save(newUserDO); } catch (Exception e) { throw new SystemException(ExceptionMsgEnum.DB_ERROR, e); } return ResultUtil.successPost("注册成功", null); } /** * 获取用户信息 * @param userId 用户id * @return UserVO */ @Override public Result<UserVO> getUserInfo(Long userId) { if (Objects.isNull(userId)) { throw new BusinessException(ExceptionMsgEnum.NOT_LOGIN); } String ipAddr = IPUtils.getRealIpAddr(request); String addr = IPUtils.getAddrByIp(ipAddr); String address = IPUtils.splitAddress(addr); if (redisCache.hasKey(RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userId)))) { Map<String, Object> map = redisCache.hmget(RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userId))); UserVO userVO = new UserVO(map); userVO.setIpAddr(address); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userId)), "ipAddr", address); return ResultUtil.successGet("获取用户信息成功", userVO); } UserDO userDO = this.getById(userId); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.TOKEN_INVALID); } UserVO userVO = new UserVO(); BeanUtils.copyProperties(userDO, userVO); if (Objects.nonNull(userDO.getBirthday())) { userVO.setBirthday(userDO.getBirthday().toString()); } userVO.setIpAddr(address); Integer attentionNum = userAttentionMapper.getCountById(userDO.getId()); Integer fansNum = userFansMapper.getCountById(userDO.getId()); if (Objects.isNull(attentionNum)) { attentionNum = 0; } if (Objects.isNull(fansNum)) { fansNum = 0; } userVO.setAttentionNum(attentionNum); userVO.setFansNum(fansNum); redisCache.hmset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userDO.getId())), UserVO.toMap(userVO) ); return ResultUtil.successGet("获取用户信息成功", userVO); } /** * 修改用户头像 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateAvatarUrl(UserVO userVO) { checkField(userVO.getId(),userVO.getAvatarUrl()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "avatarUrl", userVO.getAvatarUrl() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改头像成功", null); } /** * 修改用户背景图片 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateBackgroundImage(UserVO userVO) { checkField(userVO.getId(),userVO.getHomePageBackground()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "homePageBackground", userVO.getHomePageBackground() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改背景成功", null); } /** * 修改用户昵称 * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateNickname(UserVO userVO) { checkField(userVO.getId(),userVO.getNickname()); if (userVO.getNickname().length() > 12 || userVO.getNickname().length() < 2) { return ResultUtil.errorPost("昵称长度为2-12位"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "nickname", userVO.getNickname() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改昵称成功", null); } /** * 修改用户简介 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateIntroduction(UserVO userVO) { checkField(userVO.getId(),userVO.getSelfIntroduction()); if (userVO.getSelfIntroduction().length() > 100) { return ResultUtil.errorPost("简介长度不能超过100字"); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "selfIntroduction", userVO.getSelfIntroduction() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改简介成功", null); } /** * 修改用户性别 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateSex(UserVO userVO) { checkField(userVO.getId(),String.valueOf(userVO.getSex())); if (userVO.getSex() < 0 || userVO.getSex() > 1) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "sex", userVO.getSex() ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改性别成功", null); } /** * 修改用户生日 * * @param userVO 用户信息 * @return Result<?> */ @Override public Result<Integer> updateBirthday(UserVO userVO) { checkField(userVO.getId(),userVO.getBirthday()); Date date = Date.valueOf(userVO.getBirthday()); // 判断生日是否合法,不能大于当前时间 long currentTimeMillis = System.currentTimeMillis(); if (date.getTime() > currentTimeMillis) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } int age = TimeUtil.calculateAge(date.toLocalDate()); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "birthday", userVO.getBirthday() ); redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "age", age ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改生日成功", age); } /** * 修改用户地区 * @param userVO 用户信息 * @return Result<?> */ @Override public Result<?> updateArea(UserVO userVO) { checkField(userVO.getId(),userVO.getArea()); // 判断地区是否合法,如果不合法则抛出异常,格式为:省 市 区 String[] split = userVO.getArea().split(" "); if (split.length != 3) { throw new BusinessException(ExceptionMsgEnum.PARAMETER_ERROR); } String area; if (split[0].equals(split[1])) { area = split[0] + " " + split[2]; } else { area = userVO.getArea(); } redisCache.hset( RedisKey.build(RedisConstant.REDIS_KEY_USER_LOGIN_INFO, String.valueOf(userVO.getId())), "area", area ); redisCache.addZSet(RedisConstant.REDIS_KEY_USER_INFO_UPDATE_LIST, userVO.getId()); return ResultUtil.successPost("修改地区成功", null); } @Override
public Result<ViewUserVO> viewUserInfo(Long userId) {
23
2023-12-15 08:13:42+00:00
24k
Blawuken/MicroG-Extended
play-services-core/src/main/java/org/microg/gms/auth/loginservice/AccountAuthenticator.java
[ { "identifier": "AskPermissionActivity", "path": "play-services-core/src/main/java/org/microg/gms/auth/AskPermissionActivity.java", "snippet": "public class AskPermissionActivity extends AccountAuthenticatorActivity {\n public static final String EXTRA_FROM_ACCOUNT_MANAGER = \"from_account_manager\";...
import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.AccountManager; import android.accounts.NetworkErrorException; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Base64; import android.util.Log; import com.google.android.gms.R; import org.microg.gms.auth.AskPermissionActivity; import org.microg.gms.auth.AuthConstants; import org.microg.gms.auth.AuthManager; import org.microg.gms.auth.AuthResponse; import org.microg.gms.auth.login.LoginActivity; import org.microg.gms.common.PackageUtils; import java.util.Arrays; import java.util.List; import static android.accounts.AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE; import static android.accounts.AccountManager.KEY_ACCOUNT_NAME; import static android.accounts.AccountManager.KEY_ACCOUNT_TYPE; import static android.accounts.AccountManager.KEY_ANDROID_PACKAGE_NAME; import static android.accounts.AccountManager.KEY_AUTHTOKEN; import static android.accounts.AccountManager.KEY_BOOLEAN_RESULT; import static android.accounts.AccountManager.KEY_CALLER_PID; import static android.accounts.AccountManager.KEY_CALLER_UID; import static android.accounts.AccountManager.KEY_INTENT;
14,867
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.gms.auth.loginservice; class AccountAuthenticator extends AbstractAccountAuthenticator { private static final String TAG = "GmsAuthenticator"; private final Context context; private final String accountType; public AccountAuthenticator(Context context) { super(context); this.context = context;
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.gms.auth.loginservice; class AccountAuthenticator extends AbstractAccountAuthenticator { private static final String TAG = "GmsAuthenticator"; private final Context context; private final String accountType; public AccountAuthenticator(Context context) { super(context); this.context = context;
this.accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE;
1
2023-12-17 16:14:53+00:00
24k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/minecraft/level/tile/f.java
[ { "identifier": "Level", "path": "src/com/mojang/minecraft/level/Level.java", "snippet": "public class Level implements Serializable {\r\n\r\n public static final long serialVersionUID = 0L;\r\n public int width;\r\n public int height;\r\n public int depth;\r\n public byte[] blocks;\r\n publ...
import com.mojang.minecraft.level.Level; import com.mojang.minecraft.level.liquid.LiquidType; import com.mojang.minecraft.level.tile.a;
16,690
package com.mojang.minecraft.level.tile; public final class f extends a { public f(int var1, int var2) { super(var1, var2); }
package com.mojang.minecraft.level.tile; public final class f extends a { public f(int var1, int var2) { super(var1, var2); }
public final void a(Level var1, int var2, int var3, int var4) {
0
2023-12-18 15:38:59+00:00
24k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/controller/AcquistoController.java
[ { "identifier": "Utils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/Utils.java", "snippet": "public class Utils {\n\n /**\n * Metodo che converte una stringa contente un tempo, in secondi.\n *\n * @param time in formato \"ore:minuti:secondi\"\n * @return Integer, i sec...
import it.unipv.po.aioobe.trenissimo.model.Utils; import it.unipv.po.aioobe.trenissimo.model.acquisto.Acquisto; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.TitoloViaggioEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.TitoloViaggioService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.VoucherService; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.CorsaSingola; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.TipoTitoloViaggio; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.utils.TicketBuilder; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio; import it.unipv.po.aioobe.trenissimo.view.HomePage; import it.unipv.po.aioobe.trenissimo.view.ViaggioControl; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.net.URL; import java.util.*;
16,521
@FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private Label lblCartaOK; @FXML private Button btnConferma; @FXML private Label lblDatiOK; private ObservableList<Viaggio> _viaggi; private TicketBuilder titoloViaggio; private boolean isIdVoucherOK; private Double subtotale; private Double iva; private boolean acquistoSoloVoucher; private boolean isRiscattoUsed; private File biglietto; /** * Metodo d'Inizializzazione * * @param location * @param resources * @see #checkIdRealTime() * @see #checkPagamentoRealTime() * @see #checkDatiRealTime() * @see Account * @see ViaggioControl */ @Override public void initialize(URL location, ResourceBundle resources) { _viaggi = FXCollections.observableArrayList(); _viaggi.addListener((ListChangeListener<Viaggio>) c -> { boxViaggi.getChildren().setAll(_viaggi.stream().map(x -> new ViaggioControl(x, null)).toList()); }); this.subtotale = 0.0; this.iva = 0.0; this.isRiscattoUsed = false; checkIdRealTime(); checkPagamentoRealTime(); checkDatiRealTime(); if (Account.getLoggedIn()) { txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } } /** * Verifica per abilitazione del tasto acquista dopo la conferma dei dati personali e dei dati di pagamento/riscatto voucher */ private void check() { if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); else if ((lblDatiOK.isVisible() && acquistoSoloVoucher)) btnAcquisto.setDisable(false); } /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) {
package it.unipv.po.aioobe.trenissimo.controller; /** * Controller class per acquistoView.fxml * * @author ArrayIndexOutOfBoundsException * @see it.unipv.po.aioobe.trenissimo.view.acquistoView * @see javafx.fxml.Initializable */ public class AcquistoController implements Initializable { @FXML private BorderPane root; @FXML private VBox boxViaggi; @FXML private Button btnAcquisto; @FXML private TextField txtNumCarta; @FXML private TextField txtDataScadenza; @FXML private TextField txtCVV; @FXML private Label lblRiscattoOK; @FXML private Label lblErroreRiscatto; @FXML private Button btnRiscatta; @FXML private TextField txtVoucher; @FXML private Label lblSubtotale; @FXML private Label lblIVA; @FXML private Label lblSconto; @FXML private Label lblTotale; @FXML private TextField txtNome; @FXML private TextField txtCognome; @FXML private DatePicker dtpDataNascita; @FXML private TextField txtEmail; @FXML private TextField txtVia; @FXML private TextField txtCivico; @FXML private TextField txtCitta; @FXML private TextField txtCAP; @FXML private Button btnAggiungiPagamento; @FXML private Label lblErroreNumCarta; @FXML private Label lblErroreData; @FXML private Label lblErroreCVV; @FXML private Label lblErroreCAP; @FXML private Label lblErroreEmail; @FXML private Label lblErroreDataNascita; @FXML private Label lblErroreNome; @FXML private Label lblErroreCognome; @FXML private Label lblErroreVia; @FXML private Label lblErroreCivico; @FXML private Label lblErroreCitta; @FXML private Label lblCartaOK; @FXML private Button btnConferma; @FXML private Label lblDatiOK; private ObservableList<Viaggio> _viaggi; private TicketBuilder titoloViaggio; private boolean isIdVoucherOK; private Double subtotale; private Double iva; private boolean acquistoSoloVoucher; private boolean isRiscattoUsed; private File biglietto; /** * Metodo d'Inizializzazione * * @param location * @param resources * @see #checkIdRealTime() * @see #checkPagamentoRealTime() * @see #checkDatiRealTime() * @see Account * @see ViaggioControl */ @Override public void initialize(URL location, ResourceBundle resources) { _viaggi = FXCollections.observableArrayList(); _viaggi.addListener((ListChangeListener<Viaggio>) c -> { boxViaggi.getChildren().setAll(_viaggi.stream().map(x -> new ViaggioControl(x, null)).toList()); }); this.subtotale = 0.0; this.iva = 0.0; this.isRiscattoUsed = false; checkIdRealTime(); checkPagamentoRealTime(); checkDatiRealTime(); if (Account.getLoggedIn()) { txtNome.setText(Account.getInstance().getDatiPersonali().getNome()); txtCognome.setText(Account.getInstance().getDatiPersonali().getCognome()); dtpDataNascita.setValue(Account.getInstance().getDatiPersonali().getDataNascita().toLocalDate()); txtEmail.setText(Account.getInstance().getDatiPersonali().getMail()); txtVia.setText(Account.getInstance().getDatiPersonali().getVia()); txtCivico.setText(Account.getInstance().getDatiPersonali().getCivico()); txtCitta.setText(Account.getInstance().getDatiPersonali().getCitta()); txtCAP.setText(Account.getInstance().getDatiPersonali().getCap().toString()); } } /** * Verifica per abilitazione del tasto acquista dopo la conferma dei dati personali e dei dati di pagamento/riscatto voucher */ private void check() { if ((lblDatiOK.isVisible() && lblCartaOK.isVisible())) btnAcquisto.setDisable(false); else if ((lblDatiOK.isVisible() && acquistoSoloVoucher)) btnAcquisto.setDisable(false); } /** * Imposta i dati dell'acquisto e la lista dei viaggi * * @param viaggi * @see Viaggio */ public void set_viaggi(@NotNull List<Viaggio> viaggi) { for (Viaggio v : viaggi) { subtotale = subtotale + v.getPrezzoTot(); iva = iva + v.getPrezzoIva(); } lblSubtotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); lblIVA.setText("€ " + String.format(Locale.US, "%.2f", iva)); lblTotale.setText("€ " + String.format(Locale.US, "%.2f", subtotale)); _viaggi.setAll(viaggi); } /** * Gestisce il pagamento e il download del biglietto PDF * * @throws Exception * @see #onScaricaBigliettoPDF(Acquisto) * @see HomePage * @see Acquisto * @see Viaggio * @see CorsaSingola * @see TipoTitoloViaggio * @see Account */ @FXML protected void onPaga() throws Exception { onAlert("Acquisto avvenuto con successo!"); List<Acquisto> biglietti = new ArrayList<>(); for (Viaggio v : _viaggi) {
biglietti.add(new CorsaSingola(TipoTitoloViaggio.BIGLIETTOCORSASINGOLA, v));
5
2023-12-21 10:41:11+00:00
24k
green-code-initiative/ecoCode-java
src/main/java/fr/greencodeinitiative/java/JavaCheckRegistrar.java
[ { "identifier": "ArrayCopyCheck", "path": "src/main/java/fr/greencodeinitiative/java/checks/ArrayCopyCheck.java", "snippet": "@Rule(key = \"EC27\")\n@DeprecatedRuleKey(repositoryKey = \"greencodeinitiative-java\", ruleKey = \"GRPS0027\")\npublic class ArrayCopyCheck extends IssuableSubscriptionVisitor {...
import java.util.Collections; import java.util.List; import fr.greencodeinitiative.java.checks.ArrayCopyCheck; import fr.greencodeinitiative.java.checks.AvoidConcatenateStringsInLoop; import fr.greencodeinitiative.java.checks.AvoidFullSQLRequest; import fr.greencodeinitiative.java.checks.AvoidGettingSizeCollectionInLoop; import fr.greencodeinitiative.java.checks.AvoidMultipleIfElseStatement; import fr.greencodeinitiative.java.checks.AvoidRegexPatternNotStatic; import fr.greencodeinitiative.java.checks.AvoidSQLRequestInLoop; import fr.greencodeinitiative.java.checks.AvoidSetConstantInBatchUpdate; import fr.greencodeinitiative.java.checks.AvoidSpringRepositoryCallInLoopOrStreamCheck; import fr.greencodeinitiative.java.checks.AvoidStatementForDMLQueries; import fr.greencodeinitiative.java.checks.AvoidUsageOfStaticCollections; import fr.greencodeinitiative.java.checks.AvoidUsingGlobalVariablesCheck; import fr.greencodeinitiative.java.checks.FreeResourcesOfAutoCloseableInterface; import fr.greencodeinitiative.java.checks.IncrementCheck; import fr.greencodeinitiative.java.checks.InitializeBufferWithAppropriateSize; import fr.greencodeinitiative.java.checks.NoFunctionCallWhenDeclaringForLoop; import fr.greencodeinitiative.java.checks.OptimizeReadFileExceptions; import fr.greencodeinitiative.java.checks.UnnecessarilyAssignValuesToVariables; import fr.greencodeinitiative.java.checks.UseCorrectForLoop; import org.sonar.plugins.java.api.CheckRegistrar; import org.sonar.plugins.java.api.JavaCheck; import org.sonarsource.api.sonarlint.SonarLintSide;
14,690
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of(
/* * ecoCode - Java language - Provides rules to reduce the environmental footprint of your Java programs * Copyright © 2023 Green Code Initiative (https://www.ecocode.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.greencodeinitiative.java; /** * Provide the "checks" (implementations of rules) classes that are going be executed during * source code analysis. * <p> * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. */ @SonarLintSide public class JavaCheckRegistrar implements CheckRegistrar { private static final List<Class<? extends JavaCheck>> ANNOTATED_RULE_CLASSES = List.of(
ArrayCopyCheck.class,
0
2023-12-19 20:38:40+00:00
24k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/datagen/GunGen.java
[ { "identifier": "Reference", "path": "src/main/java/com/mrcrayfish/guns/Reference.java", "snippet": "public class Reference\n{\n\tpublic static final String MOD_ID = \"cgm\";\n}" }, { "identifier": "GripType", "path": "src/main/java/com/mrcrayfish/guns/common/GripType.java", "snippet": "...
import com.mrcrayfish.guns.Reference; import com.mrcrayfish.guns.common.GripType; import com.mrcrayfish.guns.common.Gun; import com.mrcrayfish.guns.init.ModItems; import com.mrcrayfish.guns.init.ModSounds; import net.minecraft.data.DataGenerator; import net.minecraft.resources.ResourceLocation;
17,391
package com.mrcrayfish.guns.datagen; /** * Author: MrCrayfish */ public class GunGen extends GunProvider { public GunGen(DataGenerator generator) { super(generator); } @Override protected void registerGuns() {
package com.mrcrayfish.guns.datagen; /** * Author: MrCrayfish */ public class GunGen extends GunProvider { public GunGen(DataGenerator generator) { super(generator); } @Override protected void registerGuns() {
this.addGun(new ResourceLocation(Reference.MOD_ID, "assault_rifle"), Gun.Builder.create()
0
2023-12-18 15:04:35+00:00
24k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/module/app/SystemFramework.java
[ { "identifier": "logLevelDesc", "path": "app/src/main/java/com/sevtinge/hyperceiler/utils/log/LogManager.java", "snippet": "public static String logLevelDesc() {\n return switch (logLevel) {\n case 0 -> (\"Disable\");\n case 1 -> (\"Error\");\n case 2 -> (\"Warn\");\n case...
import static com.sevtinge.hyperceiler.utils.api.VoyagerApisKt.isPad; import static com.sevtinge.hyperceiler.utils.devicesdk.SystemSDKKt.isMoreAndroidVersion; import static com.sevtinge.hyperceiler.utils.log.LogManager.logLevelDesc; import com.sevtinge.hyperceiler.module.base.BaseModule; import com.sevtinge.hyperceiler.module.hook.systemframework.AllowUntrustedTouch; import com.sevtinge.hyperceiler.module.hook.systemframework.AllowUntrustedTouchForU; import com.sevtinge.hyperceiler.module.hook.systemframework.AppLinkVerify; import com.sevtinge.hyperceiler.module.hook.systemframework.CleanOpenMenu; import com.sevtinge.hyperceiler.module.hook.systemframework.CleanShareMenu; import com.sevtinge.hyperceiler.module.hook.systemframework.ClipboardWhitelist; import com.sevtinge.hyperceiler.module.hook.systemframework.DeleteOnPostNotification; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableCleaner; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableFreeformBlackList; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableLowApiCheckForU; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableMiuiLite; import com.sevtinge.hyperceiler.module.hook.systemframework.DisablePinVerifyPer72h; import com.sevtinge.hyperceiler.module.hook.systemframework.DisableVerifyCanBeDisabled; import com.sevtinge.hyperceiler.module.hook.systemframework.FlagSecure; import com.sevtinge.hyperceiler.module.hook.systemframework.FreeFormCount; import com.sevtinge.hyperceiler.module.hook.systemframework.FreeformBubble; import com.sevtinge.hyperceiler.module.hook.systemframework.HookEntry; import com.sevtinge.hyperceiler.module.hook.systemframework.MultiFreeFormSupported; import com.sevtinge.hyperceiler.module.hook.systemframework.PackagePermissions; import com.sevtinge.hyperceiler.module.hook.systemframework.QuickScreenshot; import com.sevtinge.hyperceiler.module.hook.systemframework.RemoveSmallWindowRestrictions; import com.sevtinge.hyperceiler.module.hook.systemframework.ScreenRotation; import com.sevtinge.hyperceiler.module.hook.systemframework.SpeedInstall; import com.sevtinge.hyperceiler.module.hook.systemframework.StickyFloatingWindows; import com.sevtinge.hyperceiler.module.hook.systemframework.ThermalBrightness; import com.sevtinge.hyperceiler.module.hook.systemframework.UseOriginalAnimation; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeDefaultStream; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeDisableSafe; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeFirstPress; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeMediaSteps; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeSeparateControl; import com.sevtinge.hyperceiler.module.hook.systemframework.VolumeSteps; import com.sevtinge.hyperceiler.module.hook.systemframework.corepatch.BypassSignCheckForT; import com.sevtinge.hyperceiler.module.hook.systemframework.display.AllDarkMode; import com.sevtinge.hyperceiler.module.hook.systemframework.display.DisplayCutout; import com.sevtinge.hyperceiler.module.hook.systemframework.display.ToastTime; import com.sevtinge.hyperceiler.module.hook.systemframework.freeform.OpenAppInFreeForm; import com.sevtinge.hyperceiler.module.hook.systemframework.freeform.UnForegroundPin; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.IgnoreStylusKeyGesture; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.NoMagicPointer; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.RemoveStylusBluetoothRestriction; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.RestoreEsc; import com.sevtinge.hyperceiler.module.hook.systemframework.mipad.SetGestureNeedFingerNum; import com.sevtinge.hyperceiler.module.hook.systemframework.network.DualNRSupport; import com.sevtinge.hyperceiler.module.hook.systemframework.network.DualSASupport; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N1Band; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N28Band; import com.sevtinge.hyperceiler.module.hook.systemframework.network.N5N8Band; import com.sevtinge.hyperceiler.module.hook.various.NoAccessDeviceLogsRequest; import de.robv.android.xposed.XposedBridge;
20,185
package com.sevtinge.hyperceiler.module.app; public class SystemFramework extends BaseModule { @Override public void handleLoadPackage() { XposedBridge.log("[HyperCeiler][I]: Log level is " + logLevelDesc()); // 小窗 initHook(new FreeFormCount(), mPrefsMap.getBoolean("system_framework_freeform_count")); initHook(new FreeformBubble(), mPrefsMap.getBoolean("system_framework_freeform_bubble")); initHook(new DisableFreeformBlackList(), mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(RemoveSmallWindowRestrictions.INSTANCE, mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(new StickyFloatingWindows(), mPrefsMap.getBoolean("system_framework_freeform_sticky")); initHook(MultiFreeFormSupported.INSTANCE, mPrefsMap.getBoolean("system_framework_freeform_recents_to_small_freeform")); initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); initHook(new UnForegroundPin(), mPrefsMap.getBoolean("system_framework_freeform_foreground_pin")); // initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); // 音量 initHook(new VolumeDefaultStream()); initHook(new VolumeFirstPress(), mPrefsMap.getBoolean("system_framework_volume_first_press")); initHook(new VolumeSeparateControl(), mPrefsMap.getBoolean("system_framework_volume_separate_control")); initHook(new VolumeSteps(), mPrefsMap.getInt("system_framework_volume_steps", 0) > 0); initHook(new VolumeMediaSteps(), mPrefsMap.getBoolean("system_framework_volume_media_steps_enable")); initHook(new VolumeDisableSafe(), mPrefsMap.getBoolean("system_framework_volume_disable_safe")); // initHook(new ClockShowSecond(), mPrefsMap.getBoolean("system_ui_statusbar_clock_show_second")); // 其他 initHook(new ScreenRotation(), mPrefsMap.getBoolean("system_framework_screen_all_rotations")); initHook(new CleanShareMenu(), mPrefsMap.getBoolean("system_framework_clean_share_menu")); initHook(new CleanOpenMenu(), mPrefsMap.getBoolean("system_framework_clean_open_menu")); initHook(new AllowUntrustedTouch(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); if (isMoreAndroidVersion(34)) initHook(new AllowUntrustedTouchForU(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); initHook(new FlagSecure(), mPrefsMap.getBoolean("system_other_flag_secure")); initHook(new AppLinkVerify(), mPrefsMap.getBoolean("system_framework_disable_app_link_verify")); initHook(new UseOriginalAnimation(), mPrefsMap.getBoolean("system_framework_other_use_original_animation")); initHook(new SpeedInstall(), mPrefsMap.getBoolean("system_framework_other_speed_install")); initHook(DeleteOnPostNotification.INSTANCE, mPrefsMap.getBoolean("system_other_delete_on_post_notification")); initHook(NoAccessDeviceLogsRequest.INSTANCE, mPrefsMap.getBoolean("various_disable_access_device_logs")); initHook(new DisableMiuiLite(), mPrefsMap.getBoolean("system_framework_disablt_miuilite_check")); initHook(new HookEntry(), mPrefsMap.getBoolean("system_framework_hook_entry")); // 允许应用后台读取剪切板 initHook(new ClipboardWhitelist(), mPrefsMap.getBoolean("system_framework_clipboard_whitelist")); // 显示 initHook(DisplayCutout.INSTANCE, mPrefsMap.getBoolean("system_ui_display_hide_cutout_enable")); initHook(new ToastTime(), mPrefsMap.getBoolean("system_ui_display_toast_times_enable")); initHook(new AllDarkMode(), mPrefsMap.getBoolean("system_framework_allow_all_dark_mode")); // initHook(new AutoBrightness(), mPrefsMap.getBoolean("system_control_center_auto_brightness")); // 位置模拟 // initHook(new LocationSimulation(), false); // 小米/红米平板设置相关 if (isPad()) { initHook(IgnoreStylusKeyGesture.INSTANCE, mPrefsMap.getBoolean("mipad_input_ingore_gesture")); initHook(NoMagicPointer.INSTANCE, mPrefsMap.getBoolean("mipad_input_close_magic")); initHook(RemoveStylusBluetoothRestriction.INSTANCE, mPrefsMap.getBoolean("mipad_input_disable_bluetooth")); initHook(RestoreEsc.INSTANCE, mPrefsMap.getBoolean("mipad_input_restore_esc")); initHook(SetGestureNeedFingerNum.INSTANCE, mPrefsMap.getBoolean("mipad_input_need_finger_num")); } // 核心破解 if (isMoreAndroidVersion(33)) initHook(BypassSignCheckForT.INSTANCE, mPrefsMap.getBoolean("system_framework_core_patch_auth_creak") || mPrefsMap.getBoolean("system_framework_core_patch_disable_integrity")); // 网络 initHook(DualNRSupport.INSTANCE, mPrefsMap.getBoolean("phone_double_5g_nr")); initHook(DualSASupport.INSTANCE, mPrefsMap.getBoolean("phone_double_5g_sa")); initHook(N1Band.INSTANCE, mPrefsMap.getBoolean("phone_n1")); initHook(N5N8Band.INSTANCE, mPrefsMap.getBoolean("phone_n5_n8")); initHook(N28Band.INSTANCE, mPrefsMap.getBoolean("phone_n28")); // Other initHook(new PackagePermissions()); initHook(new GlobalActions(), mLoadPackageParam.processName.equals("android")); initHook(new ThermalBrightness(), mPrefsMap.getBoolean("system_framework_other_thermal_brightness")); initHook(DisableCleaner.INSTANCE, mPrefsMap.getBoolean("system_framework_other_disable_cleaner")); initHook(new DisablePinVerifyPer72h(), mPrefsMap.getBoolean("system_framework_disable_72h_verify"));
package com.sevtinge.hyperceiler.module.app; public class SystemFramework extends BaseModule { @Override public void handleLoadPackage() { XposedBridge.log("[HyperCeiler][I]: Log level is " + logLevelDesc()); // 小窗 initHook(new FreeFormCount(), mPrefsMap.getBoolean("system_framework_freeform_count")); initHook(new FreeformBubble(), mPrefsMap.getBoolean("system_framework_freeform_bubble")); initHook(new DisableFreeformBlackList(), mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(RemoveSmallWindowRestrictions.INSTANCE, mPrefsMap.getBoolean("system_framework_disable_freeform_blacklist")); initHook(new StickyFloatingWindows(), mPrefsMap.getBoolean("system_framework_freeform_sticky")); initHook(MultiFreeFormSupported.INSTANCE, mPrefsMap.getBoolean("system_framework_freeform_recents_to_small_freeform")); initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); initHook(new UnForegroundPin(), mPrefsMap.getBoolean("system_framework_freeform_foreground_pin")); // initHook(new OpenAppInFreeForm(), mPrefsMap.getBoolean("system_framework_freeform_jump")); // 音量 initHook(new VolumeDefaultStream()); initHook(new VolumeFirstPress(), mPrefsMap.getBoolean("system_framework_volume_first_press")); initHook(new VolumeSeparateControl(), mPrefsMap.getBoolean("system_framework_volume_separate_control")); initHook(new VolumeSteps(), mPrefsMap.getInt("system_framework_volume_steps", 0) > 0); initHook(new VolumeMediaSteps(), mPrefsMap.getBoolean("system_framework_volume_media_steps_enable")); initHook(new VolumeDisableSafe(), mPrefsMap.getBoolean("system_framework_volume_disable_safe")); // initHook(new ClockShowSecond(), mPrefsMap.getBoolean("system_ui_statusbar_clock_show_second")); // 其他 initHook(new ScreenRotation(), mPrefsMap.getBoolean("system_framework_screen_all_rotations")); initHook(new CleanShareMenu(), mPrefsMap.getBoolean("system_framework_clean_share_menu")); initHook(new CleanOpenMenu(), mPrefsMap.getBoolean("system_framework_clean_open_menu")); initHook(new AllowUntrustedTouch(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); if (isMoreAndroidVersion(34)) initHook(new AllowUntrustedTouchForU(), mPrefsMap.getBoolean("system_framework_allow_untrusted_touch")); initHook(new FlagSecure(), mPrefsMap.getBoolean("system_other_flag_secure")); initHook(new AppLinkVerify(), mPrefsMap.getBoolean("system_framework_disable_app_link_verify")); initHook(new UseOriginalAnimation(), mPrefsMap.getBoolean("system_framework_other_use_original_animation")); initHook(new SpeedInstall(), mPrefsMap.getBoolean("system_framework_other_speed_install")); initHook(DeleteOnPostNotification.INSTANCE, mPrefsMap.getBoolean("system_other_delete_on_post_notification")); initHook(NoAccessDeviceLogsRequest.INSTANCE, mPrefsMap.getBoolean("various_disable_access_device_logs")); initHook(new DisableMiuiLite(), mPrefsMap.getBoolean("system_framework_disablt_miuilite_check")); initHook(new HookEntry(), mPrefsMap.getBoolean("system_framework_hook_entry")); // 允许应用后台读取剪切板 initHook(new ClipboardWhitelist(), mPrefsMap.getBoolean("system_framework_clipboard_whitelist")); // 显示 initHook(DisplayCutout.INSTANCE, mPrefsMap.getBoolean("system_ui_display_hide_cutout_enable")); initHook(new ToastTime(), mPrefsMap.getBoolean("system_ui_display_toast_times_enable")); initHook(new AllDarkMode(), mPrefsMap.getBoolean("system_framework_allow_all_dark_mode")); // initHook(new AutoBrightness(), mPrefsMap.getBoolean("system_control_center_auto_brightness")); // 位置模拟 // initHook(new LocationSimulation(), false); // 小米/红米平板设置相关 if (isPad()) { initHook(IgnoreStylusKeyGesture.INSTANCE, mPrefsMap.getBoolean("mipad_input_ingore_gesture")); initHook(NoMagicPointer.INSTANCE, mPrefsMap.getBoolean("mipad_input_close_magic")); initHook(RemoveStylusBluetoothRestriction.INSTANCE, mPrefsMap.getBoolean("mipad_input_disable_bluetooth")); initHook(RestoreEsc.INSTANCE, mPrefsMap.getBoolean("mipad_input_restore_esc")); initHook(SetGestureNeedFingerNum.INSTANCE, mPrefsMap.getBoolean("mipad_input_need_finger_num")); } // 核心破解 if (isMoreAndroidVersion(33)) initHook(BypassSignCheckForT.INSTANCE, mPrefsMap.getBoolean("system_framework_core_patch_auth_creak") || mPrefsMap.getBoolean("system_framework_core_patch_disable_integrity")); // 网络 initHook(DualNRSupport.INSTANCE, mPrefsMap.getBoolean("phone_double_5g_nr")); initHook(DualSASupport.INSTANCE, mPrefsMap.getBoolean("phone_double_5g_sa")); initHook(N1Band.INSTANCE, mPrefsMap.getBoolean("phone_n1")); initHook(N5N8Band.INSTANCE, mPrefsMap.getBoolean("phone_n5_n8")); initHook(N28Band.INSTANCE, mPrefsMap.getBoolean("phone_n28")); // Other initHook(new PackagePermissions()); initHook(new GlobalActions(), mLoadPackageParam.processName.equals("android")); initHook(new ThermalBrightness(), mPrefsMap.getBoolean("system_framework_other_thermal_brightness")); initHook(DisableCleaner.INSTANCE, mPrefsMap.getBoolean("system_framework_other_disable_cleaner")); initHook(new DisablePinVerifyPer72h(), mPrefsMap.getBoolean("system_framework_disable_72h_verify"));
initHook(new DisableVerifyCanBeDisabled(), mPrefsMap.getBoolean("system_framework_disable_verify_can_ve_disabled"));
12
2023-10-27 17:17:42+00:00
24k
sgware/sabre
src/edu/uky/cs/nil/sabre/hg/UtilityNode.java
[ { "identifier": "Character", "path": "src/edu/uky/cs/nil/sabre/Character.java", "snippet": "public class Character extends Entity {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\n\t/**\n\t * Constructs a new character.\n\t * \n\t * @param univers...
import java.util.Iterator; import edu.uky.cs.nil.sabre.Character; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.logic.Clause; import edu.uky.cs.nil.sabre.logic.Comparison.Operator; import edu.uky.cs.nil.sabre.logic.Conditional; import edu.uky.cs.nil.sabre.logic.Conjunction; import edu.uky.cs.nil.sabre.logic.Disjunction; import edu.uky.cs.nil.sabre.logic.Expression; import edu.uky.cs.nil.sabre.logic.Precondition; import edu.uky.cs.nil.sabre.logic.Unknown; import edu.uky.cs.nil.sabre.logic.Value;
18,308
package edu.uky.cs.nil.sabre.hg; /** * A {@link CostSet cost set} {@link FormulaNode node} that represents a * utility expression. When a utility node's {@link #character character} is * null, it represents the {@link edu.uky.cs.nil.sabre.Problem#utility author's * utility}; otherwise, it represents {@link * edu.uky.cs.nil.sabre.Problem#utilities that character's utility}. Each {@link * Conditional#branches branch} of the {@link Conditional conditional} utility * expression is represented by a {@link GoalNode goal node}. * * @author Stephen G. Ware */ public class UtilityNode extends FormulaNode { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * The character whose utility this node represents, or null for the * author's utility */ public final Character character; /** * The conditional numeric expression that defines a utility value depending * on the situation */ public final Conditional<Disjunction<Clause<Precondition>>> label; /** * A list of {@link GoalNode goal nodes} that correspond to the {@link * Conditional#branches branches} of the {@link #label conditional utility * expression} and which can cause this node to have different values */ public final List<GoalNode> goals = new List<>(); /** * The set of possible values this utility expression can have and their * associated costs */ protected final Range range; /** * Constructs a new utility node that belongs to a given graph and * represents a given utility. * * @param graph the graph this node belongs to * @param character the character whose utility this node represents, or * null for the author * @param label the numeric utility expression this node represents */ protected UtilityNode(HeuristicGraph graph, Character character, Conditional<Disjunction<Clause<Precondition>>> label) { super(graph, label); this.character = character; this.label = label; for(int i=0; i<label.branches.size(); i++) { Conditional<Disjunction<Clause<Precondition>>> branch = serialize(label, i); goals.add(graph.makeGoalNode(this, branch)); } this.range = graph.makeRange(label); } private static final Conditional<Disjunction<Clause<Precondition>>> serialize(Conditional<Disjunction<Clause<Precondition>>> utility, int branch) { Expression condition = utility.getCondition(branch); for(int i=0; i<branch; i++) condition = new Conjunction<>(condition, utility.getCondition(i).negate());
package edu.uky.cs.nil.sabre.hg; /** * A {@link CostSet cost set} {@link FormulaNode node} that represents a * utility expression. When a utility node's {@link #character character} is * null, it represents the {@link edu.uky.cs.nil.sabre.Problem#utility author's * utility}; otherwise, it represents {@link * edu.uky.cs.nil.sabre.Problem#utilities that character's utility}. Each {@link * Conditional#branches branch} of the {@link Conditional conditional} utility * expression is represented by a {@link GoalNode goal node}. * * @author Stephen G. Ware */ public class UtilityNode extends FormulaNode { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** * The character whose utility this node represents, or null for the * author's utility */ public final Character character; /** * The conditional numeric expression that defines a utility value depending * on the situation */ public final Conditional<Disjunction<Clause<Precondition>>> label; /** * A list of {@link GoalNode goal nodes} that correspond to the {@link * Conditional#branches branches} of the {@link #label conditional utility * expression} and which can cause this node to have different values */ public final List<GoalNode> goals = new List<>(); /** * The set of possible values this utility expression can have and their * associated costs */ protected final Range range; /** * Constructs a new utility node that belongs to a given graph and * represents a given utility. * * @param graph the graph this node belongs to * @param character the character whose utility this node represents, or * null for the author * @param label the numeric utility expression this node represents */ protected UtilityNode(HeuristicGraph graph, Character character, Conditional<Disjunction<Clause<Precondition>>> label) { super(graph, label); this.character = character; this.label = label; for(int i=0; i<label.branches.size(); i++) { Conditional<Disjunction<Clause<Precondition>>> branch = serialize(label, i); goals.add(graph.makeGoalNode(this, branch)); } this.range = graph.makeRange(label); } private static final Conditional<Disjunction<Clause<Precondition>>> serialize(Conditional<Disjunction<Clause<Precondition>>> utility, int branch) { Expression condition = utility.getCondition(branch); for(int i=0; i<branch; i++) condition = new Conjunction<>(condition, utility.getCondition(i).negate());
return new Conditional<>(condition.toPrecondition(), utility.getBranch(branch), Unknown.UNKNOWN);
9
2023-10-26 18:14:19+00:00
24k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/renderer/task/UpdateSettingsData.java
[ { "identifier": "Pl3xMap", "path": "core/src/main/java/net/pl3x/map/core/Pl3xMap.java", "snippet": "public abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.configuration.Config; import net.pl3x.map.core.configuration.Lang; import net.pl3x.map.core.configuration.PlayersLayerConfig; import net.pl3x.map.core.configuration.WorldConfig; import net.pl3x.map.core.image.io.IO; import net.pl3x.map.core.markers.Point; import net.pl3x.map.core.scheduler.Task; import net.pl3x.map.core.util.FileUtil; import net.pl3x.map.core.world.World; import org.jetbrains.annotations.NotNull;
16,560
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.core.renderer.task; public class UpdateSettingsData extends Task { private final Gson gson = new GsonBuilder() //.setPrettyPrinting() .disableHtmlEscaping() .serializeNulls() .setLenient() .create(); public UpdateSettingsData() { super(1, true); } @Override public void run() { try { parseSettings(); } catch (Throwable t) { t.printStackTrace(); } } private @NotNull List<@NotNull Object> parsePlayers() {
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.core.renderer.task; public class UpdateSettingsData extends Task { private final Gson gson = new GsonBuilder() //.setPrettyPrinting() .disableHtmlEscaping() .serializeNulls() .setLenient() .create(); public UpdateSettingsData() { super(1, true); } @Override public void run() { try { parseSettings(); } catch (Throwable t) { t.printStackTrace(); } } private @NotNull List<@NotNull Object> parsePlayers() {
if (!PlayersLayerConfig.ENABLED) {
3
2023-10-26 01:14:31+00:00
24k
kandybaby/S3mediaArchival
backend/src/test/java/com/example/mediaarchival/MediaArchivalApplicationTests.java
[ { "identifier": "MediaObjectTransferListenerTest", "path": "backend/src/test/java/com/example/mediaarchival/consumers/MediaObjectTransferListenerTest.java", "snippet": "public class MediaObjectTransferListenerTest {\n\n @Mock private MediaRepository mediaRepository;\n\n @Mock private MediaController m...
import com.example.mediaarchival.consumers.MediaObjectTransferListenerTest; import com.example.mediaarchival.controllers.LibraryControllerTest; import com.example.mediaarchival.controllers.MediaControllerTest; import com.example.mediaarchival.controllers.UserControllerTest; import com.example.mediaarchival.converters.StringToArchivedStatusConverterTest; import com.example.mediaarchival.converters.StringToMediaTypeConverterTest; import com.example.mediaarchival.deserializers.ArchivedStatusDeserializerTest; import com.example.mediaarchival.deserializers.MediaCategoryDeserializerTest; import com.example.mediaarchival.filters.JwtValidationFilterTest; import com.example.mediaarchival.tasks.S3CleanupTaskTest; import com.example.mediaarchival.tasks.StartupResetTasksTest; import com.example.mediaarchival.utils.TarUtilsTest; import com.example.mediaarchival.utils.TokenUtilsTest; import com.example.mediaarchival.tasks.RestoreCheckerTest; import com.example.mediaarchival.utils.DirectoryUtilsTest; import com.example.mediaarchival.consumers.LibraryUpdateConsumerTest; import com.example.mediaarchival.consumers.RestoreConsumerTest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance;
16,964
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JwtValidationFilterTests extends JwtValidationFilterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToMediaTypeConverterTests extends StringToMediaTypeConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaCategoryDeserializerTests extends MediaCategoryDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToArchivedStatusConverterTests extends StringToArchivedStatusConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ArchivedStatusDeserializerTests extends ArchivedStatusDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserControllerTests extends UserControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
package com.example.mediaarchival; @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaArchivalApplicationTests { @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaControllerTests extends MediaControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LibraryControllerTests extends LibraryControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JwtValidationFilterTests extends JwtValidationFilterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToMediaTypeConverterTests extends StringToMediaTypeConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class MediaCategoryDeserializerTests extends MediaCategoryDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class StringToArchivedStatusConverterTests extends StringToArchivedStatusConverterTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ArchivedStatusDeserializerTests extends ArchivedStatusDeserializerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS) class UserControllerTests extends UserControllerTest {} @Nested @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TokenUtilsTests extends TokenUtilsTest {}
12
2023-10-27 01:54:57+00:00
24k
siam1026/siam-cloud
siam-user/user-provider/src/main/java/com/siam/package_user/service_impl/internal/VipRechargeRecordServiceImpl.java
[ { "identifier": "Quantity", "path": "siam-common/src/main/java/com/siam/package_common/constant/Quantity.java", "snippet": "public class Quantity {\n\n public static final byte BYTE_0 = (byte) 0;\n public static final byte BYTE_1 = (byte) 1;\n public static final byte BYTE_2 = (byte) 2;\n pu...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.constant.Quantity; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_common.util.GsonUtils; import com.siam.package_promotion.entity.Coupons; import com.siam.package_promotion.entity.CouponsMemberRelation; import com.siam.package_promotion.feign.CouponsFeignApi; import com.siam.package_promotion.feign.CouponsMemberRelationFeignApi; import com.siam.package_user.entity.Member; import com.siam.package_user.entity.MemberBillingRecord; import com.siam.package_user.entity.internal.VipRechargeDenomination; import com.siam.package_user.entity.internal.VipRechargeDenominationCouponsRelation; import com.siam.package_user.entity.internal.VipRechargeRecord; import com.siam.package_user.feign.MemberBillingRecordFeignApi; import com.siam.package_user.feign.MemberFeignApi; import com.siam.package_user.mapper.internal.VipRechargeRecordMapper; import com.siam.package_user.model.example.internal.VipRechargeDenominationCouponsRelationExample; import com.siam.package_user.service.internal.VipRechargeDenominationCouponsRelationService; import com.siam.package_user.service.internal.VipRechargeDenominationService; import com.siam.package_user.service.internal.VipRechargeRecordService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.*;
16,278
package com.siam.package_user.service_impl.internal; @Slf4j @Service public class VipRechargeRecordServiceImpl implements VipRechargeRecordService { @Autowired
package com.siam.package_user.service_impl.internal; @Slf4j @Service public class VipRechargeRecordServiceImpl implements VipRechargeRecordService { @Autowired
private VipRechargeRecordMapper vipRechargeRecordMapper;
14
2023-10-26 10:45:10+00:00
24k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/CandidateWordView.java
[ { "identifier": "BackgroundDrawableFactory", "path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/BackgroundDrawableFactory.java", "snippet": "public class BackgroundDrawableFactory {\n /** Drawable to create. */\n public enum DrawableType {\n // Key background for twelvekeys layout.\n TWE...
import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityManager; import android.widget.EdgeEffect; import androidx.core.view.ViewCompat; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import javax.annotation.Nullable; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateList; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateWord; import sh.eliza.japaneseinput.accessibility.CandidateWindowAccessibilityDelegate; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory; import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory.DrawableType; import sh.eliza.japaneseinput.ui.CandidateLayout; import sh.eliza.japaneseinput.ui.CandidateLayout.Row; import sh.eliza.japaneseinput.ui.CandidateLayout.Span; import sh.eliza.japaneseinput.ui.CandidateLayoutRenderer; import sh.eliza.japaneseinput.ui.CandidateLayouter; import sh.eliza.japaneseinput.ui.SnapScroller; import sh.eliza.japaneseinput.view.Skin;
14,942
return false; } } /** Polymorphic behavior based on scroll orientation. */ // TODO(hidehiko): rename OrientationTrait to OrientationTraits. interface OrientationTrait { /** * @return scroll position of which direction corresponds to the orientation. */ int getScrollPosition(View view); /** * @return the projected value. */ float projectVector(float x, float y); /** Scrolls to {@code position}. {@code position} is applied to corresponding axis. */ void scrollTo(View view, int position); /** * @return left or top position based on the orientation. */ float getCandidatePosition(Row row, Span span); /** * @return width or height based on the orientation. */ float getCandidateLength(Row row, Span span); /** * @return view's width or height based on the orientation. */ int getViewLength(View view); /** * @return the page size of the layout for the scroll orientation. */ int getPageSize(CandidateLayouter layouter); /** * @return the content size for the scroll orientation of the layout. 0 for absent. */ float getContentSize(Optional<CandidateLayout> layout); } enum Orientation implements OrientationTrait { VERTICAL { @Override public int getScrollPosition(View view) { return view.getScrollY(); } @Override public void scrollTo(View view, int position) { view.scrollTo(0, position); } @Override public float getCandidatePosition(Row row, Span span) { return row.getTop(); } @Override public float getCandidateLength(Row row, Span span) { return row.getHeight(); } @Override public int getViewLength(View view) { return view.getHeight(); } @Override public float projectVector(float x, float y) { return y; } @Override public int getPageSize(CandidateLayouter layouter) { return Preconditions.checkNotNull(layouter).getPageHeight(); } @Override public float getContentSize(Optional<CandidateLayout> layout) { return layout.isPresent() ? layout.get().getContentHeight() : 0; } } } private CandidateSelectListener candidateSelectListener; // Finally, we only need vertical scrolling. // TODO(hidehiko): Remove horizontal scrolling related codes. private final EdgeEffect topEdgeEffect = new EdgeEffect(getContext()); private final EdgeEffect bottomEdgeEffect = new EdgeEffect(getContext()); // The Scroller which manages the status of scrolling the view. // Default behavior of ScrollView does not suffice our UX design // so we introduced this Scroller. // TODO(matsuzakit): The parameter is TBD (needs UX study?). protected final SnapScroller scroller = new SnapScroller(); // The CandidateLayouter which calculates the layout of candidate words. // This fields is not final but must be set in initialization in the subclasses. protected CandidateLayouter layouter; // The calculated layout, created by this.layouter. protected CandidateLayout calculatedLayout; // The CandidateList which is currently shown on the view. protected CandidateList currentCandidateList; protected final CandidateLayoutRenderer candidateLayoutRenderer = new CandidateLayoutRenderer(); final CandidateWordGestureDetector candidateWordGestureDetector = new CandidateWordGestureDetector(getContext()); // Scroll orientation. private final OrientationTrait orientationTrait; protected final BackgroundDrawableFactory backgroundDrawableFactory = new BackgroundDrawableFactory(getResources());
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package sh.eliza.japaneseinput; /** A view for candidate words. */ // TODO(matsuzakit): Optional is introduced partially. Complete introduction. abstract class CandidateWordView extends View implements MemoryManageable { /** Handles gestures to scroll candidate list and choose a candidate. */ class CandidateWordGestureDetector { class CandidateWordViewGestureListener extends SimpleOnGestureListener { @Override public boolean onFling( MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { float velocity = orientationTrait.projectVector(velocityX, velocityY); // As fling is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Fling makes scrolling. scroller.fling(-(int) velocity); invalidate(); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float distance = orientationTrait.projectVector(distanceX, distanceY); int oldScrollPosition = scroller.getScrollPosition(); int oldMaxScrollPosition = scroller.getMaxScrollPosition(); scroller.scrollBy((int) distance); orientationTrait.scrollTo(CandidateWordView.this, scroller.getScrollPosition()); // As scroll is started, current action is not tapping. // Reset pressing state so that candidate selection is not triggered at touch up event. reset(); // Edge effect. Now, in production, we only support vertical scroll. if (oldScrollPosition + distance < 0) { topEdgeEffect.onPull(distance / getHeight()); if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); } } else if (oldScrollPosition + distance > oldMaxScrollPosition) { bottomEdgeEffect.onPull(distance / getHeight()); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); } } invalidate(); return true; } } // GestureDetector cannot handle all complex gestures which we need. // But we use GestureDetector for some gesture recognition // because implementing whole gesture detection logic by ourselves is a bit tedious. private final GestureDetector gestureDetector; /** * Points to an instance of currently pressed candidate word. Or {@code null} if any candidates * aren't pressed. */ @Nullable private CandidateWord pressedCandidate; private final RectF candidateRect = new RectF(); private Optional<Integer> pressedRowIndex = Optional.absent(); public CandidateWordGestureDetector(Context context) { gestureDetector = new GestureDetector(context, new CandidateWordViewGestureListener()); } private void pressCandidate(int rowIndex, Span span) { Row row = calculatedLayout.getRowList().get(rowIndex); pressedRowIndex = Optional.of(rowIndex); pressedCandidate = span.getCandidateWord().orNull(); // TODO(yamaguchi):maybe better to make this rect larger by several pixels to avoid that // users fail to select a candidate by unconscious small movement of tap point. // (i.e. give hysterisis for noise reduction) // Needs UX study. candidateRect.set( span.getLeft(), row.getTop(), span.getRight(), row.getTop() + row.getHeight()); } void reset() { pressedCandidate = null; pressedRowIndex = Optional.absent(); // NOTE: candidateRect doesn't need reset. } CandidateWord getPressedCandidate() { return pressedCandidate; } /** * Checks if a down event is fired inside a candidate rectangle. If so, begin pressing it. * * <p>It is assumed that rows are stored in up-to-down order, and spans are in left-to-right * order. * * @param scrolledX X coordinate of down event point including scroll offset * @param scrolledY Y coordinate of down event point including scroll offset * @return true if the down event is fired inside a candidate rectangle. */ private boolean findCandidateAndPress(float scrolledX, float scrolledY) { if (calculatedLayout == null) { return false; } for (int rowIndex = 0; rowIndex < calculatedLayout.getRowList().size(); ++rowIndex) { Row row = calculatedLayout.getRowList().get(rowIndex); if (scrolledY < row.getTop()) { break; } if (scrolledY >= row.getTop() + row.getHeight()) { continue; } for (Span span : row.getSpanList()) { if (scrolledX < span.getLeft()) { break; } if (scrolledX >= span.getRight()) { continue; } pressCandidate(rowIndex, span); invalidate(); return true; } return false; } return false; } boolean onTouchEvent(MotionEvent event) { // Before delegation to gesture detector, handle ACTION_UP event // in order to release edge effect. if (event.getAction() == MotionEvent.ACTION_UP) { topEdgeEffect.onRelease(); bottomEdgeEffect.onRelease(); invalidate(); } if (gestureDetector.onTouchEvent(event)) { return true; } float scrolledX = event.getX() + getScrollX(); float scrolledY = event.getY() + getScrollY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: findCandidateAndPress(scrolledX, scrolledY); scroller.stopScrolling(); if (!topEdgeEffect.isFinished()) { topEdgeEffect.onRelease(); invalidate(); } if (!bottomEdgeEffect.isFinished()) { bottomEdgeEffect.onRelease(); invalidate(); } return true; case MotionEvent.ACTION_MOVE: if (pressedCandidate != null) { // Turn off highlighting if contact point gets out of the candidate. if (!candidateRect.contains(scrolledX, scrolledY)) { reset(); invalidate(); } } return true; case MotionEvent.ACTION_CANCEL: if (pressedCandidate != null) { reset(); invalidate(); } return true; case MotionEvent.ACTION_UP: if (pressedCandidate != null) { if (candidateRect.contains(scrolledX, scrolledY) && candidateSelectListener != null) { candidateSelectListener.onCandidateSelected( CandidateWordView.this, pressedCandidate, pressedRowIndex); } reset(); invalidate(); } return true; } return false; } } /** Polymorphic behavior based on scroll orientation. */ // TODO(hidehiko): rename OrientationTrait to OrientationTraits. interface OrientationTrait { /** * @return scroll position of which direction corresponds to the orientation. */ int getScrollPosition(View view); /** * @return the projected value. */ float projectVector(float x, float y); /** Scrolls to {@code position}. {@code position} is applied to corresponding axis. */ void scrollTo(View view, int position); /** * @return left or top position based on the orientation. */ float getCandidatePosition(Row row, Span span); /** * @return width or height based on the orientation. */ float getCandidateLength(Row row, Span span); /** * @return view's width or height based on the orientation. */ int getViewLength(View view); /** * @return the page size of the layout for the scroll orientation. */ int getPageSize(CandidateLayouter layouter); /** * @return the content size for the scroll orientation of the layout. 0 for absent. */ float getContentSize(Optional<CandidateLayout> layout); } enum Orientation implements OrientationTrait { VERTICAL { @Override public int getScrollPosition(View view) { return view.getScrollY(); } @Override public void scrollTo(View view, int position) { view.scrollTo(0, position); } @Override public float getCandidatePosition(Row row, Span span) { return row.getTop(); } @Override public float getCandidateLength(Row row, Span span) { return row.getHeight(); } @Override public int getViewLength(View view) { return view.getHeight(); } @Override public float projectVector(float x, float y) { return y; } @Override public int getPageSize(CandidateLayouter layouter) { return Preconditions.checkNotNull(layouter).getPageHeight(); } @Override public float getContentSize(Optional<CandidateLayout> layout) { return layout.isPresent() ? layout.get().getContentHeight() : 0; } } } private CandidateSelectListener candidateSelectListener; // Finally, we only need vertical scrolling. // TODO(hidehiko): Remove horizontal scrolling related codes. private final EdgeEffect topEdgeEffect = new EdgeEffect(getContext()); private final EdgeEffect bottomEdgeEffect = new EdgeEffect(getContext()); // The Scroller which manages the status of scrolling the view. // Default behavior of ScrollView does not suffice our UX design // so we introduced this Scroller. // TODO(matsuzakit): The parameter is TBD (needs UX study?). protected final SnapScroller scroller = new SnapScroller(); // The CandidateLayouter which calculates the layout of candidate words. // This fields is not final but must be set in initialization in the subclasses. protected CandidateLayouter layouter; // The calculated layout, created by this.layouter. protected CandidateLayout calculatedLayout; // The CandidateList which is currently shown on the view. protected CandidateList currentCandidateList; protected final CandidateLayoutRenderer candidateLayoutRenderer = new CandidateLayoutRenderer(); final CandidateWordGestureDetector candidateWordGestureDetector = new CandidateWordGestureDetector(getContext()); // Scroll orientation. private final OrientationTrait orientationTrait; protected final BackgroundDrawableFactory backgroundDrawableFactory = new BackgroundDrawableFactory(getResources());
private DrawableType backgroundDrawableType = null;
1
2023-10-25 07:33:25+00:00
24k
PlayReissLP/Continuity
src/main/java/me/pepperbell/continuity/client/processor/CompactCTMQuadProcessor.java
[ { "identifier": "QuadProcessor", "path": "src/main/java/me/pepperbell/continuity/api/client/QuadProcessor.java", "snippet": "public interface QuadProcessor {\n\tProcessingResult processQuad(MutableQuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier<Random> r...
import java.util.List; import java.util.Random; import java.util.function.Function; import java.util.function.Supplier; import org.apache.commons.lang3.ArrayUtils; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; import it.unimi.dsi.fastutil.objects.ObjectSet; import me.pepperbell.continuity.api.client.QuadProcessor; import me.pepperbell.continuity.api.client.QuadProcessorFactory; import me.pepperbell.continuity.client.ContinuityClient; import me.pepperbell.continuity.client.processor.simple.CTMSpriteProvider; import me.pepperbell.continuity.client.properties.BaseCTMProperties; import me.pepperbell.continuity.client.properties.CompactConnectingCTMProperties; import me.pepperbell.continuity.client.util.DirectionMaps; import me.pepperbell.continuity.client.util.MathUtil; import me.pepperbell.continuity.client.util.QuadUtil; import me.pepperbell.continuity.client.util.TextureUtil; import net.fabricmc.fabric.api.renderer.v1.material.RenderMaterial; import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder; import net.fabricmc.fabric.api.renderer.v1.mesh.MutableQuadView; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter; import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView; import net.minecraft.block.BlockState; import net.minecraft.client.texture.Sprite; import net.minecraft.client.util.SpriteIdentifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.util.math.MathHelper; import net.minecraft.world.BlockRenderView;
15,784
quadEmitter.material(material); quadEmitter.cullFace(cullFace); vertexContainer.lerpedVertices[(id + 1) % 4].writeToQuad(quadEmitter, (id + 2) % 4); int id3 = (id + 3) % 4; vertexContainer.lerpedVertices[id3].writeToQuad(quadEmitter, id3); tryInterpolate(quadEmitter, sprite, spriteIndex); quadEmitter.emit(); } protected void splitQuadrant(QuadView quad, Sprite sprite, RenderMaterial material, Direction cullFace, VertexContainer vertexContainer, int id, QuadEmitter quadEmitter, int spriteIndex) { quad.copyTo(quadEmitter); quadEmitter.material(material); quadEmitter.cullFace(cullFace); vertexContainer.lerpedVertices[id].writeToQuad(quadEmitter, (id + 1) % 4); vertexContainer.vertex4.writeToQuad(quadEmitter, (id + 2) % 4); int id3 = (id + 3) % 4; vertexContainer.lerpedVertices[id3].writeToQuad(quadEmitter, id3); tryInterpolate(quadEmitter, sprite, spriteIndex); quadEmitter.emit(); } public static class Vertex { public float x; public float y; public float z; public int color; public int light; public float u; public float v; public boolean hasNormal; public float normalX; public float normalY; public float normalZ; public void readFromQuad(QuadView quad, int vertexIndex) { x = quad.x(vertexIndex); y = quad.y(vertexIndex); z = quad.z(vertexIndex); color = quad.spriteColor(vertexIndex, 0); light = quad.lightmap(vertexIndex); u = quad.spriteU(vertexIndex, 0); v = quad.spriteV(vertexIndex, 0); hasNormal = quad.hasNormal(vertexIndex); if (hasNormal) { normalX = quad.normalX(vertexIndex); normalY = quad.normalY(vertexIndex); normalZ = quad.normalZ(vertexIndex); } } public void writeToQuad(MutableQuadView quad, int vertexIndex) { quad.pos(vertexIndex, x, y, z); quad.spriteColor(vertexIndex, 0, color); quad.lightmap(vertexIndex, light); quad.sprite(vertexIndex, 0, u, v); if (hasNormal) { quad.normal(vertexIndex, normalX, normalY, normalZ); } } public void set(Vertex other) { x = other.x; y = other.y; z = other.z; color = other.color; light = other.light; u = other.u; v = other.v; hasNormal = other.hasNormal; if (hasNormal) { normalX = other.normalX; normalY = other.normalY; normalZ = other.normalZ; } } public void setLerped(float delta, Vertex vertexA, Vertex vertexB) { x = MathHelper.lerp(delta, vertexA.x, vertexB.x); y = MathHelper.lerp(delta, vertexA.y, vertexB.y); z = MathHelper.lerp(delta, vertexA.z, vertexB.z); color = MathUtil.lerpColor(delta, vertexA.color, vertexB.color); light = MathUtil.lerpLight(delta, vertexA.light, vertexB.light); u = MathHelper.lerp(delta, vertexA.u, vertexB.u); v = MathHelper.lerp(delta, vertexA.v, vertexB.v); if (vertexA.hasNormal && vertexB.hasNormal) { normalX = MathHelper.lerp(delta, vertexA.normalX, vertexB.normalX); normalY = MathHelper.lerp(delta, vertexA.normalY, vertexB.normalY); normalZ = MathHelper.lerp(delta, vertexA.normalZ, vertexB.normalZ); float scale = 1 / (float) Math.sqrt(normalX * normalX + normalY * normalY + normalZ * normalZ); normalX *= scale; normalY *= scale; normalZ *= scale; } } } public static class VertexContainer { public final Vertex vertex0 = new Vertex(); public final Vertex vertex1 = new Vertex(); public final Vertex vertex2 = new Vertex(); public final Vertex vertex3 = new Vertex(); public final Vertex vertex01 = new Vertex(); public final Vertex vertex12 = new Vertex(); public final Vertex vertex23 = new Vertex(); public final Vertex vertex30 = new Vertex(); public final Vertex vertex4 = new Vertex(); public final Vertex[] lerpedVertices = new Vertex[] { vertex01, vertex12, vertex23, vertex30 }; public void fillBaseVertices(QuadView quad) { vertex0.readFromQuad(quad, 0); vertex1.readFromQuad(quad, 1); vertex2.readFromQuad(quad, 2); vertex3.readFromQuad(quad, 3); } } // TODO
package me.pepperbell.continuity.client.processor; public class CompactCTMQuadProcessor extends ConnectingQuadProcessor { protected static int[][] QUAD_INDEX_MAP = new int[8][]; static { int[][] map = QUAD_INDEX_MAP; map[0] = new int[] { 0, 1, 2, 3 }; // 0 - 0 1 2 3 map[1] = map[0].clone(); // 1 - 3 0 1 2 ArrayUtils.shift(map[1], 1); map[2] = map[1].clone(); // 2 - 2 3 0 1 ArrayUtils.shift(map[2], 1); map[3] = map[2].clone(); // 3 - 1 2 3 0 ArrayUtils.shift(map[3], 1); map[4] = map[3].clone(); // 4 - 0 3 2 1 ArrayUtils.reverse(map[4]); map[5] = map[4].clone(); // 5 - 1 0 3 2 ArrayUtils.shift(map[5], 1); map[6] = map[5].clone(); // 6 - 2 1 0 3 ArrayUtils.shift(map[6], 1); map[7] = map[6].clone(); // 7 - 3 2 1 0 ArrayUtils.shift(map[7], 1); } protected boolean innerSeams; protected Sprite[] replacementSprites; public CompactCTMQuadProcessor(Sprite[] sprites, ProcessingPredicate processingPredicate, ConnectionPredicate connectionPredicate, boolean innerSeams, Sprite[] replacementSprites) { super(sprites, processingPredicate, connectionPredicate); this.innerSeams = innerSeams; this.replacementSprites = replacementSprites; } @Override public ProcessingResult processQuadInner(MutableQuadView quad, Sprite sprite, BlockRenderView blockView, BlockState state, BlockPos pos, Supplier<Random> randomSupplier, int pass, int processorIndex, ProcessingContext context) { int orientation = QuadUtil.getTextureOrientation(quad); Direction[] directions = DirectionMaps.getMap(quad.lightFace())[orientation]; BlockPos.Mutable mutablePos = context.getData(ProcessingDataKeys.MUTABLE_POS_KEY); int connections = CTMSpriteProvider.getConnections(connectionPredicate, innerSeams, directions, mutablePos, blockView, state, pos, quad.lightFace(), sprite); // if (replacementSprites != null) { int ctmIndex = CTMSpriteProvider.SPRITE_INDEX_MAP[connections]; Sprite replacementSprite = replacementSprites[ctmIndex]; if (replacementSprite != null) { if (!TextureUtil.isMissingSprite(replacementSprite)) { QuadUtil.interpolate(quad, sprite, replacementSprite); } return ProcessingResult.STOP; } } // // UVs normalized to the sprite dimensions and centered at the middle of the sprite float un0 = MathUtil.getLerpProgress(quad.spriteU(0, 0), sprite.getMinU(), sprite.getMaxU()) - 0.5f; float vn0 = MathUtil.getLerpProgress(quad.spriteV(0, 0), sprite.getMinV(), sprite.getMaxV()) - 0.5f; float un1 = MathUtil.getLerpProgress(quad.spriteU(1, 0), sprite.getMinU(), sprite.getMaxU()) - 0.5f; float vn1 = MathUtil.getLerpProgress(quad.spriteV(1, 0), sprite.getMinV(), sprite.getMaxV()) - 0.5f; float un2 = MathUtil.getLerpProgress(quad.spriteU(2, 0), sprite.getMinU(), sprite.getMaxU()) - 0.5f; float vn2 = MathUtil.getLerpProgress(quad.spriteV(2, 0), sprite.getMinV(), sprite.getMaxV()) - 0.5f; float un3 = MathUtil.getLerpProgress(quad.spriteU(3, 0), sprite.getMinU(), sprite.getMaxU()) - 0.5f; float vn3 = MathUtil.getLerpProgress(quad.spriteV(3, 0), sprite.getMinV(), sprite.getMaxV()) - 0.5f; // Signums representing which side of the splitting line the U or V coordinate lies on int uSignum0 = (int) Math.signum(un0); int vSignum0 = (int) Math.signum(vn0); int uSignum1 = (int) Math.signum(un1); int vSignum1 = (int) Math.signum(vn1); int uSignum2 = (int) Math.signum(un2); int vSignum2 = (int) Math.signum(vn2); int uSignum3 = (int) Math.signum(un3); int vSignum3 = (int) Math.signum(vn3); boolean uSplit01 = shouldSplitUV(uSignum0, uSignum1); boolean vSplit01 = shouldSplitUV(vSignum0, vSignum1); boolean uSplit12 = shouldSplitUV(uSignum1, uSignum2); boolean vSplit12 = shouldSplitUV(vSignum1, vSignum2); boolean uSplit23 = shouldSplitUV(uSignum2, uSignum3); boolean vSplit23 = shouldSplitUV(vSignum2, vSignum3); boolean uSplit30 = shouldSplitUV(uSignum3, uSignum0); boolean vSplit30 = shouldSplitUV(vSignum3, vSignum0); // Cannot split across U and V at the same time if (uSplit01 & vSplit01 || uSplit12 & vSplit12 || uSplit23 & vSplit23 || uSplit30 & vSplit30) { return ProcessingResult.CONTINUE; } // Cannot split across U twice in a row if (uSplit01 & uSplit12 || uSplit12 & uSplit23 || uSplit23 & uSplit30 || uSplit30 & uSplit01) { return ProcessingResult.CONTINUE; } // Cannot split across V twice in a row if (vSplit01 & vSplit12 || vSplit12 & vSplit23 || vSplit23 & vSplit30 || vSplit30 & vSplit01) { return ProcessingResult.CONTINUE; } // boolean uSplit = ((uSplit01 ? 1 : 0) + (uSplit12 ? 1 : 0) + (uSplit23 ? 1 : 0) + (uSplit30 ? 1 : 0)) == 2; boolean vSplit = ((vSplit01 ? 1 : 0) + (vSplit12 ? 1 : 0) + (vSplit23 ? 1 : 0) + (vSplit30 ? 1 : 0)) == 2; if (!uSplit && !vSplit) { return ProcessingResult.ABORT_AND_RENDER_QUAD; } int[] quadIndices = QUAD_INDEX_MAP[orientation]; if (uSplit && vSplit) { int spriteIndex0 = getSpriteIndex(quadIndices[0], connections); int spriteIndex1 = getSpriteIndex(quadIndices[1], connections); int spriteIndex2 = getSpriteIndex(quadIndices[2], connections); int spriteIndex3 = getSpriteIndex(quadIndices[3], connections); boolean split01 = spriteIndex0 != spriteIndex1; boolean split12 = spriteIndex1 != spriteIndex2; boolean split23 = spriteIndex2 != spriteIndex3; boolean split30 = spriteIndex3 != spriteIndex0; if (!(split01 | split12 | split23 | split30)) { tryInterpolate(quad, sprite, spriteIndex0); return ProcessingResult.ABORT_AND_RENDER_QUAD; } VertexContainer vertexContainer = context.getData(ProcessingDataKeys.VERTEX_CONTAINER_KEY); vertexContainer.fillBaseVertices(quad); MeshBuilder meshBuilder = context.getData(ProcessingDataKeys.MESH_BUILDER_KEY); QuadEmitter quadEmitter = meshBuilder.getEmitter(); RenderMaterial material = quad.material(); Direction cullFace = quad.cullFace(); if (split01 & split12 & split23 & split30) { float delta01; float delta23; float delta12; float delta30; float delta4; if (uSplit01) { delta01 = MathUtil.getLerpProgress(0, un0, un1); delta23 = MathUtil.getLerpProgress(0, un2, un3); delta12 = MathUtil.getLerpProgress(0, vn1, vn2); delta30 = MathUtil.getLerpProgress(0, vn3, vn0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta01, vn0, vn1), MathHelper.lerp(delta23, vn2, vn3)); } else { delta01 = MathUtil.getLerpProgress(0, vn0, vn1); delta23 = MathUtil.getLerpProgress(0, vn2, vn3); delta12 = MathUtil.getLerpProgress(0, un1, un2); delta30 = MathUtil.getLerpProgress(0, un3, un0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta01, un0, un1), MathHelper.lerp(delta23, un2, un3)); } vertexContainer.vertex01.setLerped(delta01, vertexContainer.vertex0, vertexContainer.vertex1); vertexContainer.vertex12.setLerped(delta12, vertexContainer.vertex1, vertexContainer.vertex2); vertexContainer.vertex23.setLerped(delta23, vertexContainer.vertex2, vertexContainer.vertex3); vertexContainer.vertex30.setLerped(delta30, vertexContainer.vertex3, vertexContainer.vertex0); vertexContainer.vertex4.setLerped(delta4, vertexContainer.vertex01, vertexContainer.vertex23); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 0, quadEmitter, spriteIndex0); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 1, quadEmitter, spriteIndex1); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 2, quadEmitter, spriteIndex2); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 3, quadEmitter, spriteIndex3); } else { if (!(split01 | split12)) { split12 = true; } else if (!(split12 | split23)) { split23 = true; } else if (!(split23 | split30)) { split30 = true; } else if (!(split30 | split01)) { split01 = true; } int splits = (split01 ? 1 : 0) + (split12 ? 1 : 0) + (split23 ? 1 : 0) + (split30 ? 1 : 0); if (splits == 2) { if (split01) { float delta01; float delta23; if (uSplit01) { delta01 = MathUtil.getLerpProgress(0, un0, un1); delta23 = MathUtil.getLerpProgress(0, un2, un3); } else { delta01 = MathUtil.getLerpProgress(0, vn0, vn1); delta23 = MathUtil.getLerpProgress(0, vn2, vn3); } vertexContainer.vertex01.setLerped(delta01, vertexContainer.vertex0, vertexContainer.vertex1); vertexContainer.vertex23.setLerped(delta23, vertexContainer.vertex2, vertexContainer.vertex3); splitHalf(quad, sprite, material, cullFace, vertexContainer, 1, quadEmitter, spriteIndex1); splitHalf(quad, sprite, material, cullFace, vertexContainer, 3, quadEmitter, spriteIndex3); } else { float delta12; float delta30; if (uSplit01) { delta12 = MathUtil.getLerpProgress(0, vn1, vn2); delta30 = MathUtil.getLerpProgress(0, vn3, vn0); } else { delta12 = MathUtil.getLerpProgress(0, un1, un2); delta30 = MathUtil.getLerpProgress(0, un3, un0); } vertexContainer.vertex12.setLerped(delta12, vertexContainer.vertex1, vertexContainer.vertex2); vertexContainer.vertex30.setLerped(delta30, vertexContainer.vertex3, vertexContainer.vertex0); splitHalf(quad, sprite, material, cullFace, vertexContainer, 0, quadEmitter, spriteIndex0); splitHalf(quad, sprite, material, cullFace, vertexContainer, 2, quadEmitter, spriteIndex2); } } else { // 3 if (!split01) { float delta23; float delta12; float delta30; float delta4; if (uSplit01) { delta23 = MathUtil.getLerpProgress(0, un2, un3); delta12 = MathUtil.getLerpProgress(0, vn1, vn2); delta30 = MathUtil.getLerpProgress(0, vn3, vn0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta12, un1, un2), MathHelper.lerp(delta30, un3, un0)); } else { delta23 = MathUtil.getLerpProgress(0, vn2, vn3); delta12 = MathUtil.getLerpProgress(0, un1, un2); delta30 = MathUtil.getLerpProgress(0, un3, un0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta12, vn1, vn2), MathHelper.lerp(delta30, vn3, vn0)); } vertexContainer.vertex23.setLerped(delta23, vertexContainer.vertex2, vertexContainer.vertex3); vertexContainer.vertex12.setLerped(delta12, vertexContainer.vertex1, vertexContainer.vertex2); vertexContainer.vertex30.setLerped(delta30, vertexContainer.vertex3, vertexContainer.vertex0); vertexContainer.vertex4.setLerped(delta4, vertexContainer.vertex12, vertexContainer.vertex30); splitHalf(quad, sprite, material, cullFace, vertexContainer, 0, quadEmitter, spriteIndex0); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 2, quadEmitter, spriteIndex2); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 3, quadEmitter, spriteIndex3); } else if (!split12) { float delta01; float delta23; float delta30; float delta4; if (uSplit01) { delta01 = MathUtil.getLerpProgress(0, un0, un1); delta23 = MathUtil.getLerpProgress(0, un2, un3); delta30 = MathUtil.getLerpProgress(0, vn3, vn0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta01, vn0, vn1), MathHelper.lerp(delta23, vn2, vn3)); } else { delta01 = MathUtil.getLerpProgress(0, vn0, vn1); delta23 = MathUtil.getLerpProgress(0, vn2, vn3); delta30 = MathUtil.getLerpProgress(0, un3, un0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta01, un0, un1), MathHelper.lerp(delta23, un2, un3)); } vertexContainer.vertex01.setLerped(delta01, vertexContainer.vertex0, vertexContainer.vertex1); vertexContainer.vertex23.setLerped(delta23, vertexContainer.vertex2, vertexContainer.vertex3); vertexContainer.vertex30.setLerped(delta30, vertexContainer.vertex3, vertexContainer.vertex0); vertexContainer.vertex4.setLerped(delta4, vertexContainer.vertex01, vertexContainer.vertex23); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 0, quadEmitter, spriteIndex0); splitHalf(quad, sprite, material, cullFace, vertexContainer, 1, quadEmitter, spriteIndex1); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 3, quadEmitter, spriteIndex3); } else if (!split23) { float delta01; float delta12; float delta30; float delta4; if (uSplit01) { delta01 = MathUtil.getLerpProgress(0, un0, un1); delta12 = MathUtil.getLerpProgress(0, vn1, vn2); delta30 = MathUtil.getLerpProgress(0, vn3, vn0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta12, un1, un2), MathHelper.lerp(delta30, un3, un0)); } else { delta01 = MathUtil.getLerpProgress(0, vn0, vn1); delta12 = MathUtil.getLerpProgress(0, un1, un2); delta30 = MathUtil.getLerpProgress(0, un3, un0); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta12, vn1, vn2), MathHelper.lerp(delta30, vn3, vn0)); } vertexContainer.vertex01.setLerped(delta01, vertexContainer.vertex0, vertexContainer.vertex1); vertexContainer.vertex12.setLerped(delta12, vertexContainer.vertex1, vertexContainer.vertex2); vertexContainer.vertex30.setLerped(delta30, vertexContainer.vertex3, vertexContainer.vertex0); vertexContainer.vertex4.setLerped(delta4, vertexContainer.vertex12, vertexContainer.vertex30); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 0, quadEmitter, spriteIndex0); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 1, quadEmitter, spriteIndex1); splitHalf(quad, sprite, material, cullFace, vertexContainer, 2, quadEmitter, spriteIndex2); } else { float delta01; float delta23; float delta12; float delta4; if (uSplit01) { delta01 = MathUtil.getLerpProgress(0, un0, un1); delta23 = MathUtil.getLerpProgress(0, un2, un3); delta12 = MathUtil.getLerpProgress(0, vn1, vn2); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta01, vn0, vn1), MathHelper.lerp(delta23, vn2, vn3)); } else { delta01 = MathUtil.getLerpProgress(0, vn0, vn1); delta23 = MathUtil.getLerpProgress(0, vn2, vn3); delta12 = MathUtil.getLerpProgress(0, un1, un2); delta4 = MathUtil.getLerpProgress(0, MathHelper.lerp(delta01, un0, un1), MathHelper.lerp(delta23, un2, un3)); } vertexContainer.vertex01.setLerped(delta01, vertexContainer.vertex0, vertexContainer.vertex1); vertexContainer.vertex12.setLerped(delta12, vertexContainer.vertex1, vertexContainer.vertex2); vertexContainer.vertex23.setLerped(delta23, vertexContainer.vertex2, vertexContainer.vertex3); vertexContainer.vertex4.setLerped(delta4, vertexContainer.vertex01, vertexContainer.vertex23); splitHalf(quad, sprite, material, cullFace, vertexContainer, 3, quadEmitter, spriteIndex3); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 1, quadEmitter, spriteIndex1); splitQuadrant(quad, sprite, material, cullFace, vertexContainer, 2, quadEmitter, spriteIndex2); } } } context.addMesh(meshBuilder.build()); return ProcessingResult.ABORT_AND_CANCEL_QUAD; } else { boolean firstSplit; boolean firstHalf; if (uSplit) { firstSplit = uSplit01; firstHalf = (vSignum0 + vSignum1 + vSignum2 + vSignum3) <= 0; if (orientation == 2 || orientation == 3 || orientation == 5 || orientation == 6) { firstHalf = !firstHalf; } } else { firstSplit = vSplit01; firstHalf = (uSignum0 + uSignum1 + uSignum2 + uSignum3) <= 0; if (orientation == 1 || orientation == 2 || orientation == 6 || orientation == 7) { firstHalf = !firstHalf; } } int spriteIndexA; int spriteIndexB; if (firstHalf) { spriteIndexA = getSpriteIndex(quadIndices[0], connections); spriteIndexB = getSpriteIndex(quadIndices[firstSplit ? 1 : 3], connections); } else { spriteIndexA = getSpriteIndex(quadIndices[firstSplit ? 3 : 1], connections); spriteIndexB = getSpriteIndex(quadIndices[2], connections); } if (spriteIndexA == spriteIndexB) { tryInterpolate(quad, sprite, spriteIndexA); return ProcessingResult.ABORT_AND_RENDER_QUAD; } VertexContainer vertexContainer = context.getData(ProcessingDataKeys.VERTEX_CONTAINER_KEY); vertexContainer.fillBaseVertices(quad); MeshBuilder meshBuilder = context.getData(ProcessingDataKeys.MESH_BUILDER_KEY); QuadEmitter quadEmitter = meshBuilder.getEmitter(); RenderMaterial material = quad.material(); Direction cullFace = quad.cullFace(); if (firstSplit) { float delta01; float delta23; if (uSplit) { delta01 = MathUtil.getLerpProgress(0, un0, un1); delta23 = MathUtil.getLerpProgress(0, un2, un3); } else { delta01 = MathUtil.getLerpProgress(0, vn0, vn1); delta23 = MathUtil.getLerpProgress(0, vn2, vn3); } vertexContainer.vertex01.setLerped(delta01, vertexContainer.vertex0, vertexContainer.vertex1); vertexContainer.vertex23.setLerped(delta23, vertexContainer.vertex2, vertexContainer.vertex3); splitHalf(quad, sprite, material, cullFace, vertexContainer, 3, quadEmitter, spriteIndexA); splitHalf(quad, sprite, material, cullFace, vertexContainer, 1, quadEmitter, spriteIndexB); } else { float delta12; float delta30; if (uSplit) { delta12 = MathUtil.getLerpProgress(0, un1, un2); delta30 = MathUtil.getLerpProgress(0, un3, un0); } else { delta12 = MathUtil.getLerpProgress(0, vn1, vn2); delta30 = MathUtil.getLerpProgress(0, vn3, vn0); } vertexContainer.vertex12.setLerped(delta12, vertexContainer.vertex1, vertexContainer.vertex2); vertexContainer.vertex30.setLerped(delta30, vertexContainer.vertex3, vertexContainer.vertex0); splitHalf(quad, sprite, material, cullFace, vertexContainer, 0, quadEmitter, spriteIndexA); splitHalf(quad, sprite, material, cullFace, vertexContainer, 2, quadEmitter, spriteIndexB); } context.addMesh(meshBuilder.build()); return ProcessingResult.ABORT_AND_CANCEL_QUAD; } } // True only if one argument is 1 and the other is -1 protected static boolean shouldSplitUV(int signumA, int signumB) { return (signumA ^ signumB) == -2; } /* 0 - Unconnected 1 - Fully connected 2 - Up and down / vertical 3 - Left and right / horizontal 4 - Unconnected corners */ protected int getSpriteIndex(int quadIndex, int connections) { int index1 = quadIndex; int index2 = (quadIndex + 3) % 4; boolean connected1 = ((connections >> index1 * 2) & 1) == 1; boolean connected2 = ((connections >> index2 * 2) & 1) == 1; if (connected1 && connected2) { if (((connections >> (index2 * 2 + 1)) & 1) == 1) { return 1; } return 4; } if (connected1) { // 0 - h, 1 - v, 2 - h, 3 - v return 3 - quadIndex % 2; } if (connected2) { // 0 - v, 1 - h, 2 - v, 3 - h return 2 + quadIndex % 2; } return 0; } protected void tryInterpolate(MutableQuadView quad, Sprite oldSprite, int spriteIndex) { Sprite newSprite = sprites[spriteIndex]; if (!TextureUtil.isMissingSprite(newSprite)) { QuadUtil.interpolate(quad, oldSprite, newSprite); } } protected void splitHalf(QuadView quad, Sprite sprite, RenderMaterial material, Direction cullFace, VertexContainer vertexContainer, int id, QuadEmitter quadEmitter, int spriteIndex) { quad.copyTo(quadEmitter); quadEmitter.material(material); quadEmitter.cullFace(cullFace); vertexContainer.lerpedVertices[(id + 1) % 4].writeToQuad(quadEmitter, (id + 2) % 4); int id3 = (id + 3) % 4; vertexContainer.lerpedVertices[id3].writeToQuad(quadEmitter, id3); tryInterpolate(quadEmitter, sprite, spriteIndex); quadEmitter.emit(); } protected void splitQuadrant(QuadView quad, Sprite sprite, RenderMaterial material, Direction cullFace, VertexContainer vertexContainer, int id, QuadEmitter quadEmitter, int spriteIndex) { quad.copyTo(quadEmitter); quadEmitter.material(material); quadEmitter.cullFace(cullFace); vertexContainer.lerpedVertices[id].writeToQuad(quadEmitter, (id + 1) % 4); vertexContainer.vertex4.writeToQuad(quadEmitter, (id + 2) % 4); int id3 = (id + 3) % 4; vertexContainer.lerpedVertices[id3].writeToQuad(quadEmitter, id3); tryInterpolate(quadEmitter, sprite, spriteIndex); quadEmitter.emit(); } public static class Vertex { public float x; public float y; public float z; public int color; public int light; public float u; public float v; public boolean hasNormal; public float normalX; public float normalY; public float normalZ; public void readFromQuad(QuadView quad, int vertexIndex) { x = quad.x(vertexIndex); y = quad.y(vertexIndex); z = quad.z(vertexIndex); color = quad.spriteColor(vertexIndex, 0); light = quad.lightmap(vertexIndex); u = quad.spriteU(vertexIndex, 0); v = quad.spriteV(vertexIndex, 0); hasNormal = quad.hasNormal(vertexIndex); if (hasNormal) { normalX = quad.normalX(vertexIndex); normalY = quad.normalY(vertexIndex); normalZ = quad.normalZ(vertexIndex); } } public void writeToQuad(MutableQuadView quad, int vertexIndex) { quad.pos(vertexIndex, x, y, z); quad.spriteColor(vertexIndex, 0, color); quad.lightmap(vertexIndex, light); quad.sprite(vertexIndex, 0, u, v); if (hasNormal) { quad.normal(vertexIndex, normalX, normalY, normalZ); } } public void set(Vertex other) { x = other.x; y = other.y; z = other.z; color = other.color; light = other.light; u = other.u; v = other.v; hasNormal = other.hasNormal; if (hasNormal) { normalX = other.normalX; normalY = other.normalY; normalZ = other.normalZ; } } public void setLerped(float delta, Vertex vertexA, Vertex vertexB) { x = MathHelper.lerp(delta, vertexA.x, vertexB.x); y = MathHelper.lerp(delta, vertexA.y, vertexB.y); z = MathHelper.lerp(delta, vertexA.z, vertexB.z); color = MathUtil.lerpColor(delta, vertexA.color, vertexB.color); light = MathUtil.lerpLight(delta, vertexA.light, vertexB.light); u = MathHelper.lerp(delta, vertexA.u, vertexB.u); v = MathHelper.lerp(delta, vertexA.v, vertexB.v); if (vertexA.hasNormal && vertexB.hasNormal) { normalX = MathHelper.lerp(delta, vertexA.normalX, vertexB.normalX); normalY = MathHelper.lerp(delta, vertexA.normalY, vertexB.normalY); normalZ = MathHelper.lerp(delta, vertexA.normalZ, vertexB.normalZ); float scale = 1 / (float) Math.sqrt(normalX * normalX + normalY * normalY + normalZ * normalZ); normalX *= scale; normalY *= scale; normalZ *= scale; } } } public static class VertexContainer { public final Vertex vertex0 = new Vertex(); public final Vertex vertex1 = new Vertex(); public final Vertex vertex2 = new Vertex(); public final Vertex vertex3 = new Vertex(); public final Vertex vertex01 = new Vertex(); public final Vertex vertex12 = new Vertex(); public final Vertex vertex23 = new Vertex(); public final Vertex vertex30 = new Vertex(); public final Vertex vertex4 = new Vertex(); public final Vertex[] lerpedVertices = new Vertex[] { vertex01, vertex12, vertex23, vertex30 }; public void fillBaseVertices(QuadView quad) { vertex0.readFromQuad(quad, 0); vertex1.readFromQuad(quad, 1); vertex2.readFromQuad(quad, 2); vertex3.readFromQuad(quad, 3); } } // TODO
public static class Factory implements QuadProcessorFactory<CompactConnectingCTMProperties> {
1
2023-10-29 00:08:50+00:00
24k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs3/F3.java
[ { "identifier": "YaaInfo", "path": "src/main/java/yaa/pojos/YaaInfo.java", "snippet": "public class YaaInfo implements Serializable {\r\n public String codeName;\r\n public int privacy = 0;\r\n public YaaClz typeParam;\r\n public int column;\r\n public int startLine;\r\n public String name;\r\n p...
import yaa.ast.*; import yaa.pojos.YaaInfo; import yaa.pojos.FileState; import yaa.pojos.GlobalData; import yaa.pojos.YaaClz; import yaa.pojos.YaaError; import java.util.List; import static yaa.pojos.GlobalData.*; import static yaa.pojos.GlobalData.nothing;
19,931
package yaa.semantic.passes.fs3; public class F3 extends FileState { public F3(List<Stmt> stmts, String filePath) { super(stmts, filePath); } @Override public YaaInfo $programOut(ProgramOut programOut) { fs = null; fs3 = null; return nothing; } @Override public YaaInfo $programIn(ProgramIn in) { this.tables = GlobalData.tables4File.get(in.path); this.table = tables.get(in); fs3 = this; fs = this;
package yaa.semantic.passes.fs3; public class F3 extends FileState { public F3(List<Stmt> stmts, String filePath) { super(stmts, filePath); } @Override public YaaInfo $programOut(ProgramOut programOut) { fs = null; fs3 = null; return nothing; } @Override public YaaInfo $programIn(ProgramIn in) { this.tables = GlobalData.tables4File.get(in.path); this.table = tables.get(in); fs3 = this; fs = this;
YaaError.filePath = in.path;
4
2023-10-26 17:41:13+00:00
24k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/factory/testcase/writer/PendingStatement.java
[ { "identifier": "ParameterNameFactory", "path": "src/main/java/com/insidious/plugin/client/ParameterNameFactory.java", "snippet": "public class ParameterNameFactory {\n\n private final Map<String, String> nameByIdMap = new HashMap<>();\n private final Map<String, Parameter> nameToParameterMap = ne...
import com.insidious.common.weaver.DataInfo; import com.insidious.common.weaver.EventType; import com.insidious.plugin.client.ParameterNameFactory; import com.insidious.plugin.client.pojo.DataEventWithSessionId; import com.insidious.plugin.factory.testcase.TestGenerationState; import com.insidious.plugin.factory.testcase.expression.*; import com.insidious.plugin.factory.testcase.parameter.VariableContainer; import com.insidious.plugin.pojo.MethodCallExpression; import com.insidious.plugin.pojo.Parameter; import com.insidious.plugin.pojo.ResourceEmbedMode; import com.insidious.plugin.pojo.frameworks.JsonFramework; import com.insidious.plugin.ui.TestCaseGenerationConfiguration; import com.insidious.plugin.util.ClassTypeUtils; import com.insidious.plugin.util.ParameterUtils; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeName; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.insidious.plugin.util.ClassTypeUtils.createTypeFromTypeDeclaration;
17,718
makeValueForOtherClasses(parameterStringBuilder, parameter); } private static boolean handleValueBlockString( StringBuilder parameterStringBuilder, Parameter parameter, TestGenerationState testGenerationState ) { String serializedValue = ""; if (parameter.getProb() != null && parameter.getProb().getSerializedValue().length > 0) serializedValue = new String(parameter.getProb().getSerializedValue()); if (parameter.getType() != null && parameter.getType().endsWith("[]")) { // if the type of parameter is array like int[], long[] (i.e J[]) String nameUsed = testGenerationState.getParameterNameFactory().getNameForUse(parameter, null); parameterStringBuilder.append(nameUsed == null ? "any()" : nameUsed); return true; } if (serializedValue.equals("null")) { // if the serialized value is null just append null parameterStringBuilder.append("null"); return true; } if (parameter.isBooleanType()) { long value = parameter.getValue(); parameterStringBuilder.append(value == 1L ? "true" : "false"); return true; } if (parameter.isPrimitiveType()) { parameterStringBuilder.append(handlePrimitiveParameter(parameter, serializedValue)); return true; } return false; } private static String handlePrimitiveParameter(Parameter parameter, String serializedValue) { StringBuilder valueBuilder = new StringBuilder(); if (parameter.isBoxedPrimitiveType() && !serializedValue.isEmpty()) { serializedValue = ParameterUtils.addParameterTypeSuffix(serializedValue, parameter.getType()); valueBuilder.append(serializedValue); } else { if (serializedValue.isEmpty()) { valueBuilder.append(ParameterUtils.makeParameterValueForPrimitiveType(parameter)); } else { valueBuilder.append(serializedValue); } } return valueBuilder.toString(); } private static String createMethodParametersString(List<Parameter> variableContainer, TestGenerationState testGenerationState) { if (variableContainer == null) { return ""; } StringBuilder parameterStringBuilder = new StringBuilder(); for (int i = 0; i < variableContainer.size(); i++) { Parameter parameter = variableContainer.get(i); if (i > 0) { parameterStringBuilder.append(", "); } makeParameterValueString(parameterStringBuilder, parameter, testGenerationState); } return parameterStringBuilder.toString(); } // handling order: [ array(name), null, boolean, primitive,] name, all , private static void makeParameterValueString( StringBuilder parameterStringBuilder, Parameter parameter, TestGenerationState testGenerationState ) { if (handleValueBlockString(parameterStringBuilder, parameter, testGenerationState)) { return; } String nameUsed = testGenerationState.getParameterNameFactory().getNameForUse(parameter, null); if (nameUsed != null) { parameterStringBuilder.append(nameUsed); return; } makeValueForOtherClasses(parameterStringBuilder, parameter); } private static void makeValueForOtherClasses(StringBuilder parameterStringBuilder, Parameter parameter) { Object parameterValue; parameterValue = parameter.getValue(); String stringValue = parameter.getStringValue(); if (stringValue == null) { if (!parameter.isPrimitiveType() && parameter.getValue() == 0) { parameterValue = "null"; } parameterStringBuilder.append(parameterValue); } else { parameterStringBuilder.append(stringValue); } } private void writeCallStatement( MethodCallExpression methodCallExpression, StringBuilder statementBuilder, List<Object> statementParameters, int chainedCallNumber ) { String parameterString = createMethodParametersString(methodCallExpression.getArguments(), testGenerationState);
package com.insidious.plugin.factory.testcase.writer; public class PendingStatement { private static final Pattern anyRegexPicker = Pattern.compile("[( ,]any\\(([^)]+.class)\\)"); private final ObjectRoutineScript objectRoutine; private final List<Expression> expressionList = new ArrayList<>(); private final TestGenerationState testGenerationState; private Parameter lhsExpression; public PendingStatement(ObjectRoutineScript objectRoutine, TestGenerationState testGenerationState) { this.objectRoutine = objectRoutine; this.testGenerationState = testGenerationState; } public static PendingStatement in(ObjectRoutineScript objectRoutine, TestGenerationState testGenerationState) { return new PendingStatement(objectRoutine, testGenerationState); } /** * @param variableContainer list of parameters to be arranged * @return a string which is comma separated values to be passed to a method */ public static String createMethodParametersStringWithNames( List<Parameter> variableContainer, TestGenerationState testGenerationState) { if (variableContainer == null) { return ""; } StringBuilder parameterStringBuilder = new StringBuilder(); for (int i = 0; i < variableContainer.size(); i++) { Parameter parameter = variableContainer.get(i); if (i > 0) { parameterStringBuilder.append(", "); } makeParameterNameString(parameterStringBuilder, parameter, testGenerationState); } return parameterStringBuilder.toString(); } //Handling order: name , [array, null , bool, , Primitive,] all private static void makeParameterNameString(StringBuilder parameterStringBuilder, Parameter parameter, TestGenerationState testGenerationState) { String nameUsed = testGenerationState.getParameterNameFactory() .getNameForUse(parameter, null); if (nameUsed != null) { parameterStringBuilder.append(nameUsed); return; } if (handleValueBlockString(parameterStringBuilder, parameter, testGenerationState)) { return; } makeValueForOtherClasses(parameterStringBuilder, parameter); } private static boolean handleValueBlockString( StringBuilder parameterStringBuilder, Parameter parameter, TestGenerationState testGenerationState ) { String serializedValue = ""; if (parameter.getProb() != null && parameter.getProb().getSerializedValue().length > 0) serializedValue = new String(parameter.getProb().getSerializedValue()); if (parameter.getType() != null && parameter.getType().endsWith("[]")) { // if the type of parameter is array like int[], long[] (i.e J[]) String nameUsed = testGenerationState.getParameterNameFactory().getNameForUse(parameter, null); parameterStringBuilder.append(nameUsed == null ? "any()" : nameUsed); return true; } if (serializedValue.equals("null")) { // if the serialized value is null just append null parameterStringBuilder.append("null"); return true; } if (parameter.isBooleanType()) { long value = parameter.getValue(); parameterStringBuilder.append(value == 1L ? "true" : "false"); return true; } if (parameter.isPrimitiveType()) { parameterStringBuilder.append(handlePrimitiveParameter(parameter, serializedValue)); return true; } return false; } private static String handlePrimitiveParameter(Parameter parameter, String serializedValue) { StringBuilder valueBuilder = new StringBuilder(); if (parameter.isBoxedPrimitiveType() && !serializedValue.isEmpty()) { serializedValue = ParameterUtils.addParameterTypeSuffix(serializedValue, parameter.getType()); valueBuilder.append(serializedValue); } else { if (serializedValue.isEmpty()) { valueBuilder.append(ParameterUtils.makeParameterValueForPrimitiveType(parameter)); } else { valueBuilder.append(serializedValue); } } return valueBuilder.toString(); } private static String createMethodParametersString(List<Parameter> variableContainer, TestGenerationState testGenerationState) { if (variableContainer == null) { return ""; } StringBuilder parameterStringBuilder = new StringBuilder(); for (int i = 0; i < variableContainer.size(); i++) { Parameter parameter = variableContainer.get(i); if (i > 0) { parameterStringBuilder.append(", "); } makeParameterValueString(parameterStringBuilder, parameter, testGenerationState); } return parameterStringBuilder.toString(); } // handling order: [ array(name), null, boolean, primitive,] name, all , private static void makeParameterValueString( StringBuilder parameterStringBuilder, Parameter parameter, TestGenerationState testGenerationState ) { if (handleValueBlockString(parameterStringBuilder, parameter, testGenerationState)) { return; } String nameUsed = testGenerationState.getParameterNameFactory().getNameForUse(parameter, null); if (nameUsed != null) { parameterStringBuilder.append(nameUsed); return; } makeValueForOtherClasses(parameterStringBuilder, parameter); } private static void makeValueForOtherClasses(StringBuilder parameterStringBuilder, Parameter parameter) { Object parameterValue; parameterValue = parameter.getValue(); String stringValue = parameter.getStringValue(); if (stringValue == null) { if (!parameter.isPrimitiveType() && parameter.getValue() == 0) { parameterValue = "null"; } parameterStringBuilder.append(parameterValue); } else { parameterStringBuilder.append(stringValue); } } private void writeCallStatement( MethodCallExpression methodCallExpression, StringBuilder statementBuilder, List<Object> statementParameters, int chainedCallNumber ) { String parameterString = createMethodParametersString(methodCallExpression.getArguments(), testGenerationState);
ParameterNameFactory nameFactory = testGenerationState.getParameterNameFactory();
0
2023-10-31 09:07:46+00:00
24k