hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
cbd9dc03f0da19a1fc7d4a82a5c01ee27f532ea0
4,145
package io.nlopez.smartlocation.geocoding.providers.android; import android.content.Context; import android.location.Geocoder; import android.location.Location; import androidx.annotation.NonNull; import java.util.List; import java.util.Locale; import io.nlopez.smartlocation.OnGeocodingListener; import io.nlopez.smartlocation.OnReverseGeocodingListener; import io.nlopez.smartlocation.common.Provider; import io.nlopez.smartlocation.geocoding.GeocodingProvider; import io.nlopez.smartlocation.geocoding.common.LocationAddress; import io.nlopez.smartlocation.utils.Logger; /** * Geocoding provider based on Android's Geocoder class. */ public class AndroidGeocodingProvider implements GeocodingProvider { @NonNull private final Provider.StatusListener mStatusListener; @NonNull private final Locale mLocale; @NonNull private final Context mContext; @NonNull private final Logger mLogger; private boolean mIsReleased; public AndroidGeocodingProvider( @NonNull Context context, @NonNull Provider.StatusListener statusListener, @NonNull Logger logger, @NonNull Locale locale) { mContext = context; mStatusListener = statusListener; mLogger = logger; mLocale = locale; } @Override public void findLocationByName(@NonNull String name, @NonNull final OnGeocodingListener listener, int maxResults) { if (!isValidEnvironment()) { mStatusListener.onProviderFailed(this); return; } final GeocodingTask geocodingTask = new GeocodingTask( mContext, mLogger, mLocale, new GeocodingTask.GeocodingTaskListener() { @Override public void onLocationFailed() { if (mIsReleased) { return; } mStatusListener.onProviderFailed(AndroidGeocodingProvider.this); } @Override public void onLocationResolved(String name, List<LocationAddress> results) { if (mIsReleased) { return; } listener.onLocationResolved(name, results); } }, maxResults); geocodingTask.execute(name); } @Override public void findNameByLocation(@NonNull Location location, @NonNull final OnReverseGeocodingListener listener, int maxResults) { if (!isValidEnvironment()) { mStatusListener.onProviderFailed(this); return; } final ReverseGeocodingTask reverseGeocodingTask = new ReverseGeocodingTask( mContext, mLogger, mLocale, new ReverseGeocodingTask.ReverseGeocodingTaskListener() { @Override public void onAddressFailed() { if (mIsReleased) { return; } mStatusListener.onProviderFailed(AndroidGeocodingProvider.this); } @Override public void onAddressResolved(Location original, List<LocationAddress> results) { if (mIsReleased) { return; } listener.onAddressResolved(original, results); } }, maxResults); reverseGeocodingTask.execute(location); } private boolean isValidEnvironment() { boolean isValid = true; if (mLocale == null) { mLogger.e("Locale is null for some reason"); isValid = false; } if (!Geocoder.isPresent()) { mLogger.e("Android Geocoder is not present"); isValid = false; } return isValid; } @Override public void release() { mIsReleased = true; } }
33.16
132
0.571291
b26264f7d580b0012409f49458e8e93f7115654e
1,349
package org.tmcw.fakesmtp; import java.net.BindException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subethamail.smtp.server.SMTPServer; /** * Starts and stops the SMTP server. */ public class SMTPServerHandler { private static final Logger LOGGER = LoggerFactory.getLogger(SMTPServerHandler.class); private final SMTPServer smtpServer; public SMTPServerHandler(final SMTPServer smtpServer) { this.smtpServer = smtpServer; } /** * Starts the server on the port and address specified in parameters. * * @throws IllegalArgumentException when port is out of range. */ public void startServer() { LOGGER.debug("Start listening on {}:{}", smtpServer.getBindAddress(), smtpServer.getPort()); try { smtpServer.start(); } catch (RuntimeException ex) { final Throwable causeEx = ex.getCause(); if (BindException.class.isInstance(causeEx)) { LOGGER.error("Port {}: {}", smtpServer.getPort(), ex.getMessage()); } else { LOGGER.error("Server startup failed due to an unexpected error!", ex); } } } /** * Stops the server. */ public void stopServer() { LOGGER.debug("Stopping server"); smtpServer.stop(); } }
27.530612
100
0.627131
c0946b9375f70f977292660d0505e298ce51865d
3,079
//Leetcode problem 131 Palindrome Partitioning //Solution written by Xuqiang Fang on 7 April, 2018 import java.util.ArrayList; import java.util.List; import java.util.Iterator; class Solution{ //Solution exceeded time limit public List<List<String>> partition_(String s){ List<List<String>> list = new ArrayList<>(); if(s == null || s.length() <= 0) return list; int n = s.length(); if(n == 1){ List<String> temp = new ArrayList<>(); temp.add(s); list.add(temp); return list; } List<List<String>> sub = partition(s.substring(0,n-1)); list.addAll(sub); String last = s.substring(n-1,n); for(List<String> l : list){ l.add(last); } List<List<String>> newList = new ArrayList<>(); for(List<String> l : list){ int size = l.size(); //System.out.println(size); for(int i=size-2; i>=0; i--){ if(isPalin(String.join("",l.subList(i,size)))){ List<String> one = new ArrayList<>(); //System.out.println(String.join("",l.subList(i,size))); one.addAll(l.subList(0,i)); one.add(String.join("",l.subList(i,size))); //System.out.println(one); newList.add(one); } } } for(List<String> l : newList){ if(!list.contains(l)){ list.add(l); } } return list; } //Very simple backtracking solution public List<List<String>> partition(String s){ List<List<String>> list = new ArrayList<>(); if(s == null || s.length() == 0) return list; dfs(list, new ArrayList<String>(), 0,s); return list; } private void dfs(List<List<String>> list, List<String> temp, int splitat, String s){ if(splitat == s.length()) list.add(new ArrayList<>(temp)); for(int i=splitat; i<s.length(); i++){ if(isPalin(s.substring(splitat, i+1))){ temp.add(s.substring(splitat, i+1)); dfs(list, temp, i+1, s); temp.remove(temp.size()-1); } } } public boolean isPalin(String s){ for(int m=0, n=s.length()-1; m<=n; m++,n--){ if(s.charAt(m) != s.charAt(n)) return false; } return true; } } public class PalindromePart{ public static void main(String[] args){ Solution s = new Solution(); //System.out.println(s.partition("ff")); //System.out.println(s.partition("aabcddc")); /* [["a","a","b","c","d","d","c"],["a","a","b","c","dd","c"], ["a","a","b","cddc"],["aa","b","c","d","d","c"],["aa","b","c","dd","c"], ["aa","b","cddc"]] */ //System.out.println(s.partition("aabcb")); /* [["a","a","b","c","b"],["a","a","bcb"],["aa","b","c","b"],["aa","bcb"]] */ } }
32.755319
88
0.47353
8bb0edf332a23dfb0c7fa789ee18a3e573108f66
326
package de.sswis; import de.sswis.model.*; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({CombinedStrategyTest.class, GameTest.class, HistoryTest.class, InitializationTest.class, MixedStrategyTest.class, SimulationTest.class}) public class ModelSuite { }
27.166667
109
0.791411
a5ce19210909f7ad7cdacbf5fe021091e0df6f84
4,137
package org.ospic.platform.accounting.statistics.service; import org.ospic.platform.accounting.bills.repository.BillsJpaRepository; import org.ospic.platform.accounting.statistics.data.BillSummations; import org.ospic.platform.accounting.statistics.data.BillsPerDay; import org.ospic.platform.accounting.statistics.data.TransactionSummations; import org.ospic.platform.accounting.statistics.data.TransactionsPerDay; import org.ospic.platform.accounting.statistics.rowmap.BillSummationsRowMap; import org.ospic.platform.accounting.statistics.rowmap.BillsPerDayRowMap; import org.ospic.platform.accounting.statistics.rowmap.TransactionSummationsRowMap; import org.ospic.platform.accounting.statistics.rowmap.TransactionsPerDayRowMap; import org.ospic.platform.accounting.transactions.repository.TransactionJpaRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.util.List; /** * This file was created by eli on 27/03/2021 for org.ospic.platform.accounting.statistics.service * -- * -- * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <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. */ @Repository public class AccountingStatisticsReadServiceImpl implements AccountingStatisticsReadService { private final TransactionJpaRepository transactionJpaRepository; private final BillsJpaRepository billsJpaRepository; private final JdbcTemplate jdbcTemplate; @Autowired public AccountingStatisticsReadServiceImpl(BillsJpaRepository billsJpaRepository, TransactionJpaRepository transactionJpaRepository, final DataSource dataSource) { this.transactionJpaRepository = transactionJpaRepository; this.billsJpaRepository = billsJpaRepository; this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public ResponseEntity<?> readBillsPerDayAccountingStatistics() { final BillsPerDayRowMap rm = new BillsPerDayRowMap(); final String sql = rm.schema(); List<BillsPerDay> bills= this.jdbcTemplate.query(sql, rm, new Object[]{}); return ResponseEntity.ok().body(bills); } @Override public ResponseEntity<?> readBillSummationAccountingStatistics() { final BillSummationsRowMap rm = new BillSummationsRowMap(); final String sql = rm.schema(); List<BillSummations> billSummations = this.jdbcTemplate.query(sql, rm, new Object[]{}); return ResponseEntity.ok().body(billSummations.get(0)); } @Override public ResponseEntity<?> readTransactionsPerDayAccountingStatistics() { final TransactionsPerDayRowMap rm = new TransactionsPerDayRowMap(); final String sql = rm.schema(); List<TransactionsPerDay> transactionsPerDayList = this.jdbcTemplate.query(sql, rm, new Object[]{}); return ResponseEntity.ok().body(transactionsPerDayList); } @Override public ResponseEntity<?> readTransactionSummationAccountingStatistics() { final TransactionSummationsRowMap rm = new TransactionSummationsRowMap(); final String sql = rm.schema(); List<TransactionSummations> transactionSummations = this.jdbcTemplate.query(sql, rm, new Object[]{}); return ResponseEntity.ok().body(transactionSummations.get(0)); } }
47.011364
109
0.773266
5f89ff268d9297c86b98936bc9b2a71e2c220548
717
package com.sasiddiqui.pseudodata.presentation.presenter; import com.sasiddiqui.pseudodata.domain.model.Post; import com.sasiddiqui.pseudodata.presentation.presenter.base.BasePresenter; import com.sasiddiqui.pseudodata.presentation.ui.BaseViewCallback; import java.util.List; /** * Created by shahrukhamd on 15/05/18. * <p> * An interface defining the main presenter methods. */ public interface PostsPresenter extends BasePresenter { interface ViewCallback extends BaseViewCallback { /** * On the retrieval of all the posts; */ void onPostsRetrieved(List<Post> postList); } /** * Instruct the presenter to get the post list. */ void getPosts(); }
25.607143
75
0.716876
e385897a74a49d49c71ae768d6b2c63a433f985a
17,381
package com.pg85.otg.spigot.materials; import com.pg85.otg.util.materials.LocalMaterials; import net.minecraft.server.v1_16_R3.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; public class SpigotMaterials extends LocalMaterials { // Default blocks in given tags // Tags aren't loaded until datapacks are loaded, on world creation. We mirror the vanilla copy of the tag to solve this. private static final Block[] CORAL_BLOCKS_TAG = { Blocks.TUBE_CORAL_BLOCK, Blocks.BRAIN_CORAL_BLOCK, Blocks.BUBBLE_CORAL_BLOCK, Blocks.FIRE_CORAL_BLOCK, Blocks.HORN_CORAL_BLOCK }; private static final Block[] WALL_CORALS_TAG = { Blocks.TUBE_CORAL_WALL_FAN, Blocks.BRAIN_CORAL_WALL_FAN, Blocks.BUBBLE_CORAL_WALL_FAN, Blocks.FIRE_CORAL_WALL_FAN, Blocks.HORN_CORAL_WALL_FAN }; private static final Block[] CORALS_TAG = { Blocks.TUBE_CORAL, Blocks.BRAIN_CORAL, Blocks.BUBBLE_CORAL, Blocks.FIRE_CORAL, Blocks.HORN_CORAL, Blocks.TUBE_CORAL_FAN, Blocks.BRAIN_CORAL_FAN, Blocks.BUBBLE_CORAL_FAN, Blocks.FIRE_CORAL_FAN, Blocks.HORN_CORAL_FAN }; public static final Map<String, Block[]> OTG_BLOCK_TAGS = new HashMap<>(); public static void init() { // Tags used for OTG configs // Since Spigot doesn't appear to allow registering custom tags, we have to implement our own tags logic :/. // TODO: We should be including these via datapack and make sure we don't use tags before datapacks are loaded. OTG_BLOCK_TAGS.put("stone", new Block[] { Blocks.STONE, Blocks.GRANITE, Blocks.DIORITE, Blocks.ANDESITE }); OTG_BLOCK_TAGS.put("dirt", new Block[] { Blocks.DIRT, Blocks.COARSE_DIRT, Blocks.PODZOL, }); OTG_BLOCK_TAGS.put("stained_clay", new Block[] { Blocks.WHITE_TERRACOTTA, Blocks.ORANGE_TERRACOTTA, Blocks.MAGENTA_TERRACOTTA, Blocks.LIGHT_BLUE_TERRACOTTA, Blocks.YELLOW_TERRACOTTA, Blocks.LIME_TERRACOTTA, Blocks.PINK_TERRACOTTA, Blocks.GRAY_TERRACOTTA, Blocks.LIGHT_GRAY_TERRACOTTA, Blocks.CYAN_TERRACOTTA, Blocks.PURPLE_TERRACOTTA, Blocks.BLUE_TERRACOTTA, Blocks.BROWN_TERRACOTTA, Blocks.GREEN_TERRACOTTA, Blocks.RED_TERRACOTTA, Blocks.BLACK_TERRACOTTA, }); OTG_BLOCK_TAGS.put("log", new Block[] { Blocks.DARK_OAK_LOG, Blocks.DARK_OAK_WOOD, Blocks.STRIPPED_DARK_OAK_LOG, Blocks.STRIPPED_DARK_OAK_WOOD, Blocks.OAK_LOG, Blocks.OAK_WOOD, Blocks.STRIPPED_OAK_LOG, Blocks.STRIPPED_OAK_WOOD, Blocks.ACACIA_LOG, Blocks.ACACIA_WOOD, Blocks.STRIPPED_ACACIA_LOG, Blocks.STRIPPED_ACACIA_WOOD, Blocks.BIRCH_LOG, Blocks.BIRCH_WOOD, Blocks.STRIPPED_BIRCH_LOG, Blocks.STRIPPED_BIRCH_WOOD, Blocks.JUNGLE_LOG, Blocks.STRIPPED_JUNGLE_LOG, Blocks.STRIPPED_JUNGLE_WOOD, Blocks.SPRUCE_LOG, Blocks.SPRUCE_WOOD, Blocks.STRIPPED_SPRUCE_LOG, Blocks.STRIPPED_SPRUCE_WOOD, Blocks.CRIMSON_STEM, Blocks.STRIPPED_CRIMSON_STEM, Blocks.CRIMSON_HYPHAE, Blocks.STRIPPED_CRIMSON_HYPHAE, Blocks.WARPED_STEM, Blocks.STRIPPED_WARPED_STEM, Blocks.WARPED_HYPHAE, Blocks.STRIPPED_WARPED_HYPHAE, }); OTG_BLOCK_TAGS.put("air", new Block[] { Blocks.AIR, Blocks.CAVE_AIR, }); OTG_BLOCK_TAGS.put("sandstone", new Block[] { Blocks.SANDSTONE, Blocks.CHISELED_SANDSTONE, Blocks.SMOOTH_SANDSTONE, }); OTG_BLOCK_TAGS.put("red_sandstone", new Block[] { Blocks.RED_SANDSTONE, Blocks.CHISELED_RED_SANDSTONE, Blocks.SMOOTH_RED_SANDSTONE, }); OTG_BLOCK_TAGS.put("long_grass", new Block[] { Blocks.DEAD_BUSH, Blocks.TALL_GRASS, Blocks.FERN, }); OTG_BLOCK_TAGS.put("red_flower", new Block[] { Blocks.POPPY, Blocks.BLUE_ORCHID, Blocks.ALLIUM, Blocks.AZURE_BLUET, Blocks.RED_TULIP, Blocks.ORANGE_TULIP, Blocks.WHITE_TULIP, Blocks.PINK_TULIP, Blocks.OXEYE_DAISY, }); OTG_BLOCK_TAGS.put("quartz_block", new Block[] { Blocks.QUARTZ_BLOCK, Blocks.CHISELED_QUARTZ_BLOCK, Blocks.QUARTZ_PILLAR, }); OTG_BLOCK_TAGS.put("prismarine", new Block[] { Blocks.PRISMARINE, Blocks.PRISMARINE_BRICKS, Blocks.DARK_PRISMARINE, }); OTG_BLOCK_TAGS.put("concrete", new Block[] { Blocks.WHITE_CONCRETE, Blocks.ORANGE_CONCRETE, Blocks.MAGENTA_CONCRETE, Blocks.LIGHT_BLUE_CONCRETE, Blocks.YELLOW_CONCRETE, Blocks.LIME_CONCRETE, Blocks.PINK_CONCRETE, Blocks.GRAY_CONCRETE, Blocks.LIGHT_GRAY_CONCRETE, Blocks.CYAN_CONCRETE, Blocks.PURPLE_CONCRETE, Blocks.BLUE_CONCRETE, Blocks.BROWN_CONCRETE, Blocks.GREEN_CONCRETE, Blocks.RED_CONCRETE, Blocks.BLACK_CONCRETE, }); // Coral CORAL_BLOCKS = Arrays.stream(CORAL_BLOCKS_TAG).map(block -> SpigotMaterialData.ofBlockData(block.getBlockData())).collect(Collectors.toList()); WALL_CORALS = Arrays.stream(WALL_CORALS_TAG).map(block -> SpigotMaterialData.ofBlockData(block.getBlockData())).collect(Collectors.toList()); CORALS = Arrays.stream(CORALS_TAG).map(block -> SpigotMaterialData.ofBlockData(block.getBlockData())).collect(Collectors.toList()); // Blocks used in OTG code AIR = SpigotMaterialData.ofBlockData(Blocks.AIR.getBlockData()); CAVE_AIR = SpigotMaterialData.ofBlockData(Blocks.CAVE_AIR.getBlockData()); STRUCTURE_VOID = SpigotMaterialData.ofBlockData(Blocks.STRUCTURE_VOID.getBlockData()); COMMAND_BLOCK = SpigotMaterialData.ofBlockData(Blocks.COMMAND_BLOCK.getBlockData()); STRUCTURE_BLOCK = SpigotMaterialData.ofBlockData(Blocks.STRUCTURE_BLOCK.getBlockData()); GRASS = SpigotMaterialData.ofBlockData(Blocks.GRASS_BLOCK.getBlockData()); DIRT = SpigotMaterialData.ofBlockData(Blocks.DIRT.getBlockData()); CLAY = SpigotMaterialData.ofBlockData(Blocks.CLAY.getBlockData()); TERRACOTTA = SpigotMaterialData.ofBlockData(Blocks.TERRACOTTA.getBlockData()); WHITE_TERRACOTTA = SpigotMaterialData.ofBlockData(Blocks.WHITE_TERRACOTTA.getBlockData()); ORANGE_TERRACOTTA = SpigotMaterialData.ofBlockData(Blocks.ORANGE_TERRACOTTA.getBlockData()); YELLOW_TERRACOTTA = SpigotMaterialData.ofBlockData(Blocks.YELLOW_TERRACOTTA.getBlockData()); BROWN_TERRACOTTA = SpigotMaterialData.ofBlockData(Blocks.BROWN_TERRACOTTA.getBlockData()); RED_TERRACOTTA = SpigotMaterialData.ofBlockData(Blocks.RED_TERRACOTTA.getBlockData()); SILVER_TERRACOTTA = SpigotMaterialData.ofBlockData(Blocks.LIGHT_GRAY_TERRACOTTA.getBlockData()); STONE = SpigotMaterialData.ofBlockData(Blocks.STONE.getBlockData()); SAND = SpigotMaterialData.ofBlockData(Blocks.SAND.getBlockData()); RED_SAND = SpigotMaterialData.ofBlockData(Blocks.RED_SAND.getBlockData()); SANDSTONE = SpigotMaterialData.ofBlockData(Blocks.SANDSTONE.getBlockData()); RED_SANDSTONE = SpigotMaterialData.ofBlockData(Blocks.RED_SANDSTONE.getBlockData()); GRAVEL = SpigotMaterialData.ofBlockData(Blocks.GRAVEL.getBlockData()); MOSSY_COBBLESTONE = SpigotMaterialData.ofBlockData(Blocks.MOSSY_COBBLESTONE.getBlockData()); SNOW = SpigotMaterialData.ofBlockData(Blocks.SNOW.getBlockData()); SNOW_BLOCK = SpigotMaterialData.ofBlockData(Blocks.SNOW_BLOCK.getBlockData()); TORCH = SpigotMaterialData.ofBlockData(Blocks.TORCH.getBlockData()); BEDROCK = SpigotMaterialData.ofBlockData(Blocks.BEDROCK.getBlockData()); MAGMA = SpigotMaterialData.ofBlockData(Blocks.MAGMA_BLOCK.getBlockData()); ICE = SpigotMaterialData.ofBlockData(Blocks.ICE.getBlockData()); PACKED_ICE = SpigotMaterialData.ofBlockData(Blocks.PACKED_ICE.getBlockData()); BLUE_ICE = SpigotMaterialData.ofBlockData(Blocks.BLUE_ICE.getBlockData()); FROSTED_ICE = SpigotMaterialData.ofBlockData(Blocks.FROSTED_ICE.getBlockData()); GLOWSTONE = SpigotMaterialData.ofBlockData(Blocks.GLOWSTONE.getBlockData()); MYCELIUM = SpigotMaterialData.ofBlockData(Blocks.MYCELIUM.getBlockData()); STONE_SLAB = SpigotMaterialData.ofBlockData(Blocks.STONE_SLAB.getBlockData()); // Liquids WATER = SpigotMaterialData.ofBlockData(Blocks.WATER.getBlockData()); LAVA = SpigotMaterialData.ofBlockData(Blocks.LAVA.getBlockData()); // Trees ACACIA_LOG = SpigotMaterialData.ofBlockData(Blocks.ACACIA_LOG.getBlockData()); BIRCH_LOG = SpigotMaterialData.ofBlockData(Blocks.BIRCH_LOG.getBlockData()); DARK_OAK_LOG = SpigotMaterialData.ofBlockData(Blocks.DARK_OAK_LOG.getBlockData()); OAK_LOG = SpigotMaterialData.ofBlockData(Blocks.OAK_LOG.getBlockData()); SPRUCE_LOG = SpigotMaterialData.ofBlockData(Blocks.SPRUCE_LOG.getBlockData()); ACACIA_WOOD = SpigotMaterialData.ofBlockData(Blocks.ACACIA_WOOD.getBlockData()); BIRCH_WOOD = SpigotMaterialData.ofBlockData(Blocks.BIRCH_WOOD.getBlockData()); DARK_OAK_WOOD = SpigotMaterialData.ofBlockData(Blocks.DARK_OAK_WOOD.getBlockData()); OAK_WOOD = SpigotMaterialData.ofBlockData(Blocks.OAK_WOOD.getBlockData()); SPRUCE_WOOD = SpigotMaterialData.ofBlockData(Blocks.SPRUCE_WOOD.getBlockData()); STRIPPED_ACACIA_LOG = SpigotMaterialData.ofBlockData(Blocks.STRIPPED_ACACIA_LOG.getBlockData()); STRIPPED_BIRCH_LOG = SpigotMaterialData.ofBlockData(Blocks.STRIPPED_BIRCH_LOG.getBlockData()); STRIPPED_DARK_OAK_LOG = SpigotMaterialData.ofBlockData(Blocks.STRIPPED_DARK_OAK_LOG.getBlockData()); STRIPPED_JUNGLE_LOG = SpigotMaterialData.ofBlockData(Blocks.STRIPPED_JUNGLE_LOG.getBlockData()); STRIPPED_OAK_LOG = SpigotMaterialData.ofBlockData(Blocks.STRIPPED_OAK_LOG.getBlockData()); STRIPPED_SPRUCE_LOG = SpigotMaterialData.ofBlockData(Blocks.STRIPPED_SPRUCE_LOG.getBlockData()); ACACIA_LEAVES = SpigotMaterialData.ofBlockData(Blocks.ACACIA_LEAVES.getBlockData()); BIRCH_LEAVES = SpigotMaterialData.ofBlockData(Blocks.BIRCH_LEAVES.getBlockData()); DARK_OAK_LEAVES = SpigotMaterialData.ofBlockData(Blocks.DARK_OAK_LEAVES.getBlockData()); JUNGLE_LEAVES = SpigotMaterialData.ofBlockData(Blocks.JUNGLE_LEAVES.getBlockData()); OAK_LEAVES = SpigotMaterialData.ofBlockData(Blocks.OAK_LEAVES.getBlockData()); SPRUCE_LEAVES = SpigotMaterialData.ofBlockData(Blocks.SPRUCE_LEAVES.getBlockData()); // Plants POPPY = SpigotMaterialData.ofBlockData(Blocks.POPPY.getBlockData()); BLUE_ORCHID = SpigotMaterialData.ofBlockData(Blocks.BLUE_ORCHID.getBlockData()); ALLIUM = SpigotMaterialData.ofBlockData(Blocks.ALLIUM.getBlockData()); AZURE_BLUET = SpigotMaterialData.ofBlockData(Blocks.AZURE_BLUET.getBlockData()); RED_TULIP = SpigotMaterialData.ofBlockData(Blocks.RED_TULIP.getBlockData()); ORANGE_TULIP = SpigotMaterialData.ofBlockData(Blocks.ORANGE_TULIP.getBlockData()); WHITE_TULIP = SpigotMaterialData.ofBlockData(Blocks.WHITE_TULIP.getBlockData()); PINK_TULIP = SpigotMaterialData.ofBlockData(Blocks.PINK_TULIP.getBlockData()); OXEYE_DAISY = SpigotMaterialData.ofBlockData(Blocks.OXEYE_DAISY.getBlockData()); YELLOW_FLOWER = SpigotMaterialData.ofBlockData(Blocks.DANDELION.getBlockData()); DEAD_BUSH = SpigotMaterialData.ofBlockData(Blocks.DEAD_BUSH.getBlockData()); FERN = SpigotMaterialData.ofBlockData(Blocks.FERN.getBlockData()); LONG_GRASS = SpigotMaterialData.ofBlockData(Blocks.GRASS.getBlockData()); RED_MUSHROOM_BLOCK = SpigotMaterialData.ofBlockData(Blocks.RED_MUSHROOM_BLOCK.getBlockData()); BROWN_MUSHROOM_BLOCK = SpigotMaterialData.ofBlockData(Blocks.BROWN_MUSHROOM_BLOCK.getBlockData()); RED_MUSHROOM = SpigotMaterialData.ofBlockData(Blocks.RED_MUSHROOM.getBlockData()); BROWN_MUSHROOM = SpigotMaterialData.ofBlockData(Blocks.BROWN_MUSHROOM.getBlockData()); DOUBLE_TALL_GRASS_LOWER = SpigotMaterialData.ofBlockData(Blocks.TALL_GRASS.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER)); DOUBLE_TALL_GRASS_UPPER = SpigotMaterialData.ofBlockData(Blocks.TALL_GRASS.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER)); LARGE_FERN_LOWER = SpigotMaterialData.ofBlockData(Blocks.LARGE_FERN.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER)); LARGE_FERN_UPPER = SpigotMaterialData.ofBlockData(Blocks.LARGE_FERN.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER)); LILAC_LOWER = SpigotMaterialData.ofBlockData(Blocks.LILAC.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER)); LILAC_UPPER = SpigotMaterialData.ofBlockData(Blocks.LILAC.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER)); PEONY_LOWER = SpigotMaterialData.ofBlockData(Blocks.PEONY.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER)); PEONY_UPPER = SpigotMaterialData.ofBlockData(Blocks.PEONY.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER)); ROSE_BUSH_LOWER = SpigotMaterialData.ofBlockData(Blocks.ROSE_BUSH.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER)); ROSE_BUSH_UPPER = SpigotMaterialData.ofBlockData(Blocks.ROSE_BUSH.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER)); SUNFLOWER_LOWER = SpigotMaterialData.ofBlockData(Blocks.SUNFLOWER.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.LOWER)); SUNFLOWER_UPPER = SpigotMaterialData.ofBlockData(Blocks.SUNFLOWER.getBlockData().set(BlockTallPlant.HALF, BlockPropertyDoubleBlockHalf.UPPER)); ACACIA_SAPLING = SpigotMaterialData.ofBlockData(Blocks.ACACIA_SAPLING.getBlockData().set(BlockSapling.STAGE, 1)); BAMBOO_SAPLING = SpigotMaterialData.ofBlockData(Blocks.BAMBOO_SAPLING.getBlockData()); BIRCH_SAPLING = SpigotMaterialData.ofBlockData(Blocks.BIRCH_SAPLING.getBlockData().set(BlockSapling.STAGE, 1)); DARK_OAK_SAPLING = SpigotMaterialData.ofBlockData(Blocks.DARK_OAK_SAPLING.getBlockData().set(BlockSapling.STAGE, 1)); JUNGLE_SAPLING = SpigotMaterialData.ofBlockData(Blocks.JUNGLE_SAPLING.getBlockData().set(BlockSapling.STAGE, 1)); OAK_SAPLING = SpigotMaterialData.ofBlockData(Blocks.OAK_SAPLING.getBlockData().set(BlockSapling.STAGE, 1)); SPRUCE_SAPLING = SpigotMaterialData.ofBlockData(Blocks.SPRUCE_SAPLING.getBlockData().set(BlockSapling.STAGE, 1)); PUMPKIN = SpigotMaterialData.ofBlockData(Blocks.PUMPKIN.getBlockData()); CACTUS = SpigotMaterialData.ofBlockData(Blocks.CACTUS.getBlockData()); MELON_BLOCK = SpigotMaterialData.ofBlockData(Blocks.MELON.getBlockData()); VINE = SpigotMaterialData.ofBlockData(Blocks.VINE.getBlockData()); WATER_LILY = SpigotMaterialData.ofBlockData(Blocks.LILY_PAD.getBlockData()); SUGAR_CANE_BLOCK = SpigotMaterialData.ofBlockData(Blocks.SUGAR_CANE.getBlockData()); IBlockData bambooState = Blocks.BAMBOO.getBlockData().set(BlockBamboo.d, 1).set(BlockBamboo.e, BlockPropertyBambooSize.NONE).set(BlockBamboo.f, 0); BAMBOO = SpigotMaterialData.ofBlockData(bambooState); BAMBOO_SMALL = SpigotMaterialData.ofBlockData(bambooState.set(BlockBamboo.e, BlockPropertyBambooSize.SMALL)); BAMBOO_LARGE = SpigotMaterialData.ofBlockData(bambooState.set(BlockBamboo.e, BlockPropertyBambooSize.LARGE)); BAMBOO_LARGE_GROWING = SpigotMaterialData.ofBlockData(bambooState.set(BlockBamboo.e, BlockPropertyBambooSize.LARGE).set(BlockBamboo.f, 1)); PODZOL = SpigotMaterialData.ofBlockData(Blocks.PODZOL.getBlockData()); SEAGRASS = SpigotMaterialData.ofBlockData(Blocks.SEAGRASS.getBlockData()); TALL_SEAGRASS_LOWER = SpigotMaterialData.ofBlockData(Blocks.TALL_SEAGRASS.getBlockData().set(BlockTallSeaGrass.b, BlockPropertyDoubleBlockHalf.LOWER)); TALL_SEAGRASS_UPPER = SpigotMaterialData.ofBlockData(Blocks.TALL_SEAGRASS.getBlockData().set(BlockTallSeaGrass.b, BlockPropertyDoubleBlockHalf.UPPER)); KELP = SpigotMaterialData.ofBlockData(Blocks.KELP.getBlockData()); KELP_PLANT = SpigotMaterialData.ofBlockData(Blocks.KELP_PLANT.getBlockData()); VINE_SOUTH = SpigotMaterialData.ofBlockData(Blocks.VINE.getBlockData().set(BlockVine.SOUTH, true)); VINE_NORTH = SpigotMaterialData.ofBlockData(Blocks.VINE.getBlockData().set(BlockVine.NORTH, true)); VINE_WEST = SpigotMaterialData.ofBlockData(Blocks.VINE.getBlockData().set(BlockVine.WEST, true)); VINE_EAST = SpigotMaterialData.ofBlockData(Blocks.VINE.getBlockData().set(BlockVine.EAST, true)); SEA_PICKLE = SpigotMaterialData.ofBlockData(Blocks.SEA_PICKLE.getBlockData()); // Ores COAL_ORE = SpigotMaterialData.ofBlockData(Blocks.PODZOL.getBlockData()); DIAMOND_ORE = SpigotMaterialData.ofBlockData(Blocks.DIAMOND_ORE.getBlockData()); EMERALD_ORE = SpigotMaterialData.ofBlockData(Blocks.EMERALD_ORE.getBlockData()); GOLD_ORE = SpigotMaterialData.ofBlockData(Blocks.GOLD_ORE.getBlockData()); IRON_ORE = SpigotMaterialData.ofBlockData(Blocks.IRON_ORE.getBlockData()); LAPIS_ORE = SpigotMaterialData.ofBlockData(Blocks.LAPIS_ORE.getBlockData()); QUARTZ_ORE = SpigotMaterialData.ofBlockData(Blocks.NETHER_QUARTZ_ORE.getBlockData()); REDSTONE_ORE = SpigotMaterialData.ofBlockData(Blocks.REDSTONE_ORE.getBlockData()); // Ore blocks GOLD_BLOCK = SpigotMaterialData.ofBlockData(Blocks.GOLD_BLOCK.getBlockData()); IRON_BLOCK = SpigotMaterialData.ofBlockData(Blocks.IRON_BLOCK.getBlockData()); REDSTONE_BLOCK = SpigotMaterialData.ofBlockData(Blocks.REDSTONE_BLOCK.getBlockData()); DIAMOND_BLOCK = SpigotMaterialData.ofBlockData(Blocks.DIAMOND_BLOCK.getBlockData()); LAPIS_BLOCK = SpigotMaterialData.ofBlockData(Blocks.LAPIS_BLOCK.getBlockData()); COAL_BLOCK = SpigotMaterialData.ofBlockData(Blocks.COAL_BLOCK.getBlockData()); QUARTZ_BLOCK = SpigotMaterialData.ofBlockData(Blocks.QUARTZ_BLOCK.getBlockData()); EMERALD_BLOCK = SpigotMaterialData.ofBlockData(Blocks.EMERALD_BLOCK.getBlockData()); } }
52.990854
262
0.805017
756da6c36d757a005fd0eaae34bad8a801db47fc
9,456
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.smithy.model.neighbor; import java.util.ArrayList; import java.util.List; import software.amazon.smithy.model.Model; import software.amazon.smithy.model.shapes.EntityShape; import software.amazon.smithy.model.shapes.ListShape; import software.amazon.smithy.model.shapes.MapShape; import software.amazon.smithy.model.shapes.MemberShape; import software.amazon.smithy.model.shapes.OperationShape; import software.amazon.smithy.model.shapes.ResourceShape; import software.amazon.smithy.model.shapes.ServiceShape; import software.amazon.smithy.model.shapes.SetShape; import software.amazon.smithy.model.shapes.Shape; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.shapes.ShapeVisitor; import software.amazon.smithy.model.shapes.StructureShape; import software.amazon.smithy.model.shapes.UnionShape; import software.amazon.smithy.utils.ListUtils; /** * Finds all neighbors of a shape, returning them as a list of * {@link Relationship} objects. * * <p>Each neighbor shape that is not in the provided model will * result in a relationship where the optional * {@link Relationship#getNeighborShape() neighbor shape} is empty. * * @see NeighborProvider#of */ final class NeighborVisitor extends ShapeVisitor.Default<List<Relationship>> implements NeighborProvider { private final Model model; NeighborVisitor(Model model) { this.model = model; } @Override public List<Relationship> getNeighbors(Shape shape) { return shape.accept(this); } @Override public List<Relationship> getDefault(Shape shape) { return ListUtils.of(); } @Override public List<Relationship> serviceShape(ServiceShape shape) { List<Relationship> result = new ArrayList<>(); // Add OPERATION from service -> operation. Add BINDING from operation -> service. for (ShapeId operation : shape.getOperations()) { addBinding(result, shape, operation, RelationshipType.OPERATION); } // Add RESOURCE from service -> resource. Add BINDING from resource -> service. for (ShapeId resource : shape.getResources()) { addBinding(result, shape, resource, RelationshipType.RESOURCE); } return result; } private void addBinding(List<Relationship> result, Shape container, ShapeId bindingTarget, RelationshipType type) { result.add(relationship(container, type, bindingTarget)); addBound(result, container, bindingTarget); } private void addBound(List<Relationship> result, Shape container, ShapeId bindingTarget) { model.getShape(bindingTarget) .ifPresent(op -> result.add(relationship(op, RelationshipType.BOUND, container.getId()))); } @Override public List<Relationship> resourceShape(ResourceShape shape) { List<Relationship> result = new ArrayList<>(); // Add IDENTIFIER relationships. shape.getIdentifiers().forEach((k, v) -> result.add(relationship(shape, RelationshipType.IDENTIFIER, v))); // Add RESOURCE from resourceA -> resourceB and BOUND from resourceB -> resourceA shape.getResources().forEach(id -> addBinding(result, shape, id, RelationshipType.RESOURCE)); // Add all operation BINDING relationships (resource -> operation) and BOUND relations (operation -> resource). shape.getAllOperations().forEach(id -> addBinding(result, shape, id, RelationshipType.OPERATION)); // Do the same, but for all of the lifecycle operations. Note: does not yet another BOUND relationships. // READ, UPDATE, DELETE, and PUT are all instance operations by definition shape.getRead().ifPresent(id -> { result.add(relationship(shape, RelationshipType.READ, id)); result.add(relationship(shape, RelationshipType.INSTANCE_OPERATION, id)); }); shape.getUpdate().ifPresent(id -> { result.add(relationship(shape, RelationshipType.UPDATE, id)); result.add(relationship(shape, RelationshipType.INSTANCE_OPERATION, id)); }); shape.getDelete().ifPresent(id -> { result.add(relationship(shape, RelationshipType.DELETE, id)); result.add(relationship(shape, RelationshipType.INSTANCE_OPERATION, id)); }); shape.getPut().ifPresent(id -> { result.add(relationship(shape, RelationshipType.PUT, id)); result.add(relationship(shape, RelationshipType.INSTANCE_OPERATION, id)); }); // LIST and CREATE are, by definition, collection operations shape.getCreate().ifPresent(id -> { result.add(relationship(shape, RelationshipType.CREATE, id)); result.add(relationship(shape, RelationshipType.COLLECTION_OPERATION, id)); }); shape.getList().ifPresent(id -> { result.add(relationship(shape, RelationshipType.LIST, id)); result.add(relationship(shape, RelationshipType.COLLECTION_OPERATION, id)); }); // Add in all the other collection operations shape.getCollectionOperations().forEach(id -> result.add( relationship(shape, RelationshipType.COLLECTION_OPERATION, id))); // Add in all the other instance operations shape.getOperations().forEach(id -> result.add( relationship(shape, RelationshipType.INSTANCE_OPERATION, id))); // Find resource shapes that bind this resource to it. for (ResourceShape resource : model.getResourceShapes()) { addServiceAndResourceBindings(result, shape, resource); } // Find service shapes that bind this resource to it. for (ServiceShape service : model.getServiceShapes()) { addServiceAndResourceBindings(result, shape, service); } return result; } private void addServiceAndResourceBindings(List<Relationship> result, ResourceShape resource, EntityShape entity) { if (entity.getResources().contains(resource.getId())) { addBinding(result, entity, resource.getId(), RelationshipType.RESOURCE); } } @Override public List<Relationship> operationShape(OperationShape shape) { List<Relationship> result = new ArrayList<>(); shape.getInput().ifPresent(id -> result.add(relationship(shape, RelationshipType.INPUT, id))); shape.getOutput().ifPresent(id -> result.add(relationship(shape, RelationshipType.OUTPUT, id))); for (ShapeId errorId : shape.getErrors()) { result.add(relationship(shape, RelationshipType.ERROR, errorId)); } return result; } @Override public List<Relationship> memberShape(MemberShape shape) { List<Relationship> result = new ArrayList<>(2); result.add(relationship(shape, RelationshipType.MEMBER_CONTAINER, shape.getContainer())); result.add(relationship(shape, RelationshipType.MEMBER_TARGET, shape.getTarget())); return result; } @Override public List<Relationship> listShape(ListShape shape) { return ListUtils.of(relationship(shape, RelationshipType.LIST_MEMBER, shape.getMember())); } @Override public List<Relationship> setShape(SetShape shape) { return ListUtils.of(relationship(shape, RelationshipType.SET_MEMBER, shape.getMember())); } @Override public List<Relationship> mapShape(MapShape shape) { List<Relationship> result = new ArrayList<>(2); result.add(relationship(shape, RelationshipType.MAP_KEY, shape.getKey())); result.add(relationship(shape, RelationshipType.MAP_VALUE, shape.getValue())); return result; } @Override public List<Relationship> structureShape(StructureShape shape) { List<Relationship> result = new ArrayList<>(); for (MemberShape member : shape.getAllMembers().values()) { result.add(Relationship.create(shape, RelationshipType.STRUCTURE_MEMBER, member)); } return result; } @Override public List<Relationship> unionShape(UnionShape shape) { List<Relationship> result = new ArrayList<>(); for (MemberShape member : shape.getAllMembers().values()) { result.add(Relationship.create(shape, RelationshipType.UNION_MEMBER, member)); } return result; } private Relationship relationship(Shape shape, RelationshipType type, MemberShape memberShape) { return Relationship.create(shape, type, memberShape); } private Relationship relationship(Shape shape, RelationshipType type, ShapeId neighborShapeId) { return model.getShape(neighborShapeId) .map(target -> Relationship.create(shape, type, target)) .orElseGet(() -> Relationship.createInvalid(shape, type, neighborShapeId)); } }
44.186916
119
0.693634
95c780787cb155c065acedc9722ba2b908ff4d97
4,439
package com.example.zstd.microblog.service; import com.example.zstd.microblog.model.BlogPost; import com.example.zstd.microblog.model.FollowData; import com.example.zstd.microblog.model.User; import com.example.zstd.microblog.repository.BlogPostRepo; import com.example.zstd.microblog.repository.FollowDataRepo; import com.example.zstd.microblog.repository.UserRepo; import com.example.zstd.microblog.utils.StringUtils; import com.example.zstd.microblog.utils.ValidationUtils; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; public class BlogPostService { private static final int DISCOVER_LIST_SIZE = 10; public static final String MENTION_PREFIX = "@"; public static final String TOPIC_PREFIX = "#"; private static final Logger LOG = Logger.getLogger(BlogPostService.class.getName()); private BlogPostRepo blogPostRepo() { return ServiceLocator.getInstance().getService(BlogPostRepo.class); } private UserRepo userRepo() { return ServiceLocator.getInstance().getService(UserRepo.class); } private FollowDataRepo followDataRepo() { return ServiceLocator.getInstance().getService(FollowDataRepo.class); } public BlogPost save(String username,String message) { ValidationUtils.checkArgument( StringUtils.isNullOrEmpty(username), new IllegalArgumentException("No username")); ValidationUtils.checkArgument( StringUtils.isNullOrEmpty(message), new IllegalArgumentException("No message")); ValidationUtils.checkArgument( StringUtils.exceedsLength(message, BlogPost.MAX_LENGTH), new IllegalArgumentException("Message too long")); String[] tokens = message.split(" "); List<String> mentions = extractMentions(tokens); List<String> topics = extractTopics(tokens); BlogPost toSave = new BlogPost(username,message, StringUtils.join(",", topics.toArray(new String[0])), StringUtils.join(",", mentions.toArray(new String[0]))); return blogPostRepo().save(toSave); } public List<BlogPost> getListForTopic(String topic) { List<BlogPost> posts = getList(); return posts.stream() .filter(post -> post.getTopics() != null && Arrays.asList(post.getTopics().split(",")).contains(topic)) .collect(Collectors.toList()); } public List<BlogPost> getListForUser(String user) { List<BlogPost> posts = getList(); return posts.stream() .filter(p -> p.getCreator().equals(user)) .collect(Collectors.toList()); } public List<BlogPost> getListOfOtherUser(String user) { List<BlogPost> posts = getList(); return posts.stream() .filter(p -> !p.getCreator().equals(user)) .collect(Collectors.toList()); } public List<BlogPost> getList() { List<BlogPost> posts = blogPostRepo().listAll(); return posts; } private List<String> extractTopics(String[] tokens) { return Arrays.stream(tokens) .filter(t -> t.startsWith(TOPIC_PREFIX)) .map(t -> t.replaceAll(TOPIC_PREFIX,"")) .collect(Collectors.toList()); } private List<String> extractMentions(String[] tokens) { return Arrays.stream(tokens) .filter(t -> t.startsWith(MENTION_PREFIX)) .map(t -> t.replaceAll(MENTION_PREFIX,"")) .filter(this::isValidUsername) .collect(Collectors.toList()); } private boolean isValidUsername(String username) { return !userRepo().findByField(User.DB_FIELD_USERNAME, username).isEmpty(); } public List<BlogPost> discoverMessagesForUser(String name) { List<BlogPost> data = getListOfOtherUser(name); Map<String, Long> followingData = userRepo().getUserFollowingData(); Comparator<BlogPost> comparator = BlogPost.createPriorityComparator(followingData); return data.stream() .sorted(comparator) .limit(DISCOVER_LIST_SIZE) .collect(Collectors.toList()); } public List<BlogPost> getMessagesOfUserFollowers(String name) { List<String> followers = getFollowersNames(name); LOG.info(name + " followers " + followers); List<BlogPost> allPosts = getList(); return allPosts.stream() .filter(p -> followers.contains(p.getCreator())) .collect(Collectors.toList()); } private List<String> getFollowersNames(String name) { List<FollowData> followData = followDataRepo().findByField(FollowData.DB_FIELD_FOLLOWING, name); return followData.stream() .map(FollowData::getFollower) .collect(Collectors.toList()); } }
33.628788
111
0.723136
2e34388c9eef556f9f7b88e4534147cf80b9efe3
897
package com.google.refine.tests.process; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.refine.process.Process; import com.google.refine.process.ProcessManager; import com.google.refine.tests.util.TestUtils; import com.google.refine.util.JSONUtilities; public class ProcessManagerTests { ProcessManager processManager; Process process; @BeforeMethod public void setUp() { processManager = new ProcessManager(); process = new LongRunningProcessTests.LongRunningProcessStub("some description"); } @Test public void serializeProcessManager() throws Exception { processManager.queueProcess(process); String processJson = JSONUtilities.serialize(process); TestUtils.isSerializedTo(processManager, "{" + "\"processes\":["+processJson+"]}"); } }
28.935484
89
0.717949
e16391b98c4b14cfa41c99a49103327984dae40a
23,450
package com.rockhoppertech.music.fx.app2; /* * #%L * rockymusic-fx * %% * Copyright (C) 1996 - 2013 Rockhopper Technologies * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javafx.application.Application; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.SceneBuilder; import javafx.scene.control.Button; import javafx.scene.control.ButtonBuilder; import javafx.scene.control.ComboBox; import javafx.scene.control.ComboBoxBuilder; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.Slider; import javafx.scene.control.SliderBuilder; import javafx.scene.control.Tab; import javafx.scene.control.TabBuilder; import javafx.scene.control.TabPane; import javafx.scene.control.TabPaneBuilder; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableColumnBuilder; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextAreaBuilder; import javafx.scene.control.cell.ComboBoxTableCell; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.BorderPaneBuilder; import javafx.scene.layout.VBox; import javafx.scene.layout.VBoxBuilder; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.StringConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rockhoppertech.music.Pitch; import com.rockhoppertech.music.PitchFormat; import com.rockhoppertech.music.midi.gm.MIDIGMPatch; import com.rockhoppertech.music.midi.js.MIDINote; import com.rockhoppertech.music.midi.js.MIDINoteBuilder; import com.rockhoppertech.music.midi.js.MIDISender; import com.rockhoppertech.music.midi.js.MIDITrack; import com.rockhoppertech.music.midi.js.MIDITrackBuilder; /** * @author <a href="mailto:[email protected]">Gene De Lisa</a> * */ public class App2 extends Application { private static final Logger logger = LoggerFactory.getLogger(App2.class); Stage stage; Scene scene; BorderPane root; Controller controller; private static ObservableList<MIDINote> tableDataList; private static ObservableList<MIDIGMPatch> midiPatchList; private static ObservableList<Integer> programList; public static void main(String[] args) throws Exception { launch(args); } @Override public void start(Stage stage) throws Exception { this.stage = stage; this.controller = new Controller(); this.configureScene(); this.configureStage(); logger.debug("started"); } private void configureStage() { stage.setTitle("App 2"); // make it full screen stage.setX(0); stage.setY(0); stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth()); stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight()); stage.setScene(this.scene); controller.setStage(this.stage); stage.show(); } private void configureScene() { // Image bgimage = new Image(getClass().getResourceAsStream( // "/images/background.jpg")); // ImageView imageView = ImageViewBuilder.create() // .image(bgimage) // .build(); Button b = ButtonBuilder.create() .id("someButton") .text("Button") .style("-fx-font: 22 arial; -fx-base: #b6e7c9;") // .onAction(new EventHandler<ActionEvent>() { // @Override // public void handle(ActionEvent e) { // logger.debug("local button pressed {}", e); // } // }) .build(); // not a singleton: logger.debug("button builder {}", // ButtonBuilder.create()); // the controller has the action handler this.controller.setButton(b); BorderPane.setAlignment(b, Pos.CENTER); root = BorderPaneBuilder .create() .id("rootpane") .padding(new Insets(20)) // .style("-fx-padding: 30") .center(b) .build(); this.scene = SceneBuilder.create() .root(root) .fill(Color.web("#103000")) .stylesheets("/styles/app2styles.css") .build(); configureCombo(); // configureTabs(); MIDITrack track = MIDITrackBuilder.create() .noteString("C D E") .build(); track.sequential(); TableView<MIDINote> table = createTable(track); BorderPane.setAlignment(table, Pos.CENTER); this.root.setCenter(table); } void configureCombo() { programList = FXCollections.observableArrayList(); for (int i = 0; i < 128; i++) { programList.add(i); } midiPatchList = FXCollections.observableArrayList(); for (MIDIGMPatch p : MIDIGMPatch.getAllPitched()) { midiPatchList.add(p); } final ComboBox<MIDIGMPatch> combo = ComboBoxBuilder .<MIDIGMPatch> create() .promptText("Select") .items(midiPatchList) .style("-fx-border-color: black; -fx-border-width: 1") .build(); combo.getSelectionModel().selectedItemProperty() .addListener(new ChangeListener<MIDIGMPatch>() { public void changed( ObservableValue<? extends MIDIGMPatch> source, MIDIGMPatch oldValue, MIDIGMPatch newValue) { logger.debug("You selected: " + newValue); } }); combo.valueProperty().addListener(new ChangeListener<MIDIGMPatch>() { @Override public void changed(ObservableValue<? extends MIDIGMPatch> ov, MIDIGMPatch oldValue, MIDIGMPatch newValue) { logger.debug("changed to: " + newValue); } }); combo.setCellFactory( new Callback<ListView<MIDIGMPatch>, ListCell<MIDIGMPatch>>() { @Override public ListCell<MIDIGMPatch> call( ListView<MIDIGMPatch> param) { final ListCell<MIDIGMPatch> cell = new ListCell<MIDIGMPatch>() { @Override public void updateItem(MIDIGMPatch item, boolean empty) { super.updateItem(item, empty); if (item != null) { setText(item.getName()); } else { setText(null); } } }; return cell; } }); // combo.getSelectionModel().select(0); BorderPane.setAlignment(combo, Pos.CENTER); this.root.setTop(combo); } void configureTabs() { TextArea content = TextAreaBuilder.create() .text("Here is some\ncontent") .build(); Tab tab = TabBuilder.create() .text("A tab") .content(content) .build(); TabPane tp = TabPaneBuilder.create() .tabs(tab) .build(); BorderPane.setAlignment(tp, Pos.CENTER); this.root.setBottom(tp); } /** * @param track * the MIDITrack to display * @return a TableView */ public static TableView<MIDINote> createTable(MIDITrack track) { tableDataList = FXCollections.observableArrayList(); for (MIDINote note : track) { tableDataList.add(note); } ObservableList<Integer> midiValues; midiValues = FXCollections.observableArrayList(); for (int i = 0; i < 128; i++) { midiValues.add(i); } ObservableList<String> pitchList = FXCollections.observableArrayList(); for (int i = 0; i < 128; i++) { pitchList.add(PitchFormat .midiNumberToString(i)); } // if it's an int, i.e. midiNumber property // Callback<TableColumn<MIDINote, Integer>, TableCell<MIDINote, // Integer>> pitchCellFactory = // new Callback<TableColumn<MIDINote, Integer>, TableCell<MIDINote, // Integer>>() { // @Override // public TableCell<MIDINote, Integer> call( // TableColumn<MIDINote, Integer> arg) { // final TableCell<MIDINote, Integer> cell = new TableCell<MIDINote, // Integer>() { // @Override // protected void updateItem(Integer midiNumber, // boolean empty) { // super.updateItem(midiNumber, empty); // if (empty) { // setText(null); // } else { // // all this nonsense just to do this: // setText(PitchFormat // .midiNumberToString(midiNumber)); // } // } // }; // return cell; // } // }; TableColumn<MIDINote, Double> beatColumn = TableColumnBuilder .<MIDINote, Double> create() .text("Start Beat") .cellValueFactory( new PropertyValueFactory<MIDINote, Double>("startBeat")) .build(); TableColumn<MIDINote, String> pitchColumn = TableColumnBuilder .<MIDINote, String> create() .text("Pitch") .editable(true) .cellValueFactory( new PropertyValueFactory<MIDINote, String>( "pitchString")) // .cellFactory(pitchCellFactory) .cellFactory( ComboBoxTableCell.<MIDINote, String> forTableColumn( pitchList)) .build(); TableColumn<MIDINote, Double> durationColumn = TableColumnBuilder .<MIDINote, Double> create() .text("Duration") .cellValueFactory( new PropertyValueFactory<MIDINote, Double>( "duration")) .build(); ObservableList<Integer> channelList = FXCollections .observableArrayList(); for (int i = 0; i < 16; i++) { channelList.add(i); } TableColumn<MIDINote, Integer> channelColumn = TableColumnBuilder .<MIDINote, Integer> create() .text("Channel") .cellValueFactory( new PropertyValueFactory<MIDINote, Integer>( "channel")) .cellFactory( ComboBoxTableCell.<MIDINote, Integer> forTableColumn( channelList)) .build(); TableColumn<MIDINote, Integer> velocityColumn = TableColumnBuilder .<MIDINote, Integer> create() .text("Velocity") .cellValueFactory( new PropertyValueFactory<MIDINote, Integer>( "velocity")) .cellFactory( ComboBoxTableCell.<MIDINote, Integer> forTableColumn( midiValues)) .build(); velocityColumn .setCellFactory(new Callback<TableColumn<MIDINote, Integer>, TableCell<MIDINote, Integer>>() { @Override public TableCell<MIDINote, Integer> call( TableColumn<MIDINote, Integer> velocityColumn) { return new TableCell<MIDINote, Integer>() { final Slider slider = SliderBuilder .create() .min(0d) .max(127d) .blockIncrement(16d) .minorTickCount(16) .majorTickUnit(32d) .showTickLabels(true) .showTickMarks(false) .build(); { slider.valueProperty().addListener(new ChangeListener<Number>() { public void changed( ObservableValue<? extends Number> ov, Number oldValue, Number newValue) { logger.debug( "new velocity {} ov {}", newValue, ov); if (getTableRow() != null) { MIDINote note = (MIDINote) getTableRow() .getItem(); if (note != null) { logger.debug( "Table row {}", note); note.setVelocity(newValue .intValue()); } } } }); } @Override public void updateItem(final Integer vel, boolean empty) { super.updateItem(vel, empty); if (vel != null) { setGraphic(slider); slider.setValue(vel); } else { setGraphic(null); } } }; } }); TableColumn<MIDINote, String> programColumn = new TableColumn<>(); programColumn.setText("Program"); programColumn.setEditable(true); programColumn .setCellFactory(new Callback<TableColumn<MIDINote, String>, TableCell<MIDINote, String>>() { @Override public TableCell<MIDINote, String> call( TableColumn<MIDINote, String> theColumn) { return new ProgramStringListCell(); } }); programColumn.setCellValueFactory( new PropertyValueFactory<MIDINote, String>( "programName")); // also, pan, pitchBend TableColumn<MIDINote, MIDINote> buttonColumn = TableColumnBuilder .<MIDINote, MIDINote> create() .text("Action") .editable(true) .cellValueFactory( new Callback<CellDataFeatures<MIDINote, MIDINote>, ObservableValue<MIDINote>>() { @Override public ObservableValue<MIDINote> call( CellDataFeatures<MIDINote, MIDINote> features) { return new ReadOnlyObjectWrapper<MIDINote>( features .getValue()); } } ) .build(); buttonColumn .setCellFactory(new Callback<TableColumn<MIDINote, MIDINote>, TableCell<MIDINote, MIDINote>>() { @Override public TableCell<MIDINote, MIDINote> call( TableColumn<MIDINote, MIDINote> btnCol) { return new TableCell<MIDINote, MIDINote>() { final ImageView buttonGraphic = new ImageView(); final Button button = new Button(); { button.setGraphic(buttonGraphic); button.setMinWidth(130); } @Override public void updateItem(final MIDINote note, boolean empty) { super.updateItem(note, empty); if (note != null) { button.setText("Play"); setGraphic(button); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { logger.debug("note {}", note); MIDISender sender = new MIDISender(); sender.play(note); } }); } else { setGraphic(null); } } }; } }); // TableView<MIDINote> table = // TableViewBuilder // .<MIDINote> create() // .items(tableDataList) // .columns( // beatColumn, // pitchColumn, // durationColumn, // velocityColumn, // channelColumn, // programColumn, // buttonColumn) // .editable(true) // .styleClass("midiTrackTable") // .columnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY) // .build(); TableView<MIDINote> table = new TableView<>(); table.setItems(tableDataList); table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); table.getColumns().add(beatColumn); table.getColumns().add(pitchColumn); table.getColumns().add(durationColumn); table.getColumns().add(velocityColumn); table.getColumns().add(channelColumn); table.getColumns().add(programColumn); table.getColumns().add(buttonColumn); // you get the generic problem // table2.getColumns().addAll(beatColumn, // pitchColumn, // durationColumn, // velocityColumn, // channelColumn, // programColumn, // buttonColumn); table.setEditable(true); // table2.setStyleClass("midiTrackTable"); return table; } static class ProgramStringListCell extends ComboBoxTableCell<MIDINote, String> { static ObservableList<String> patchNames; static { patchNames = FXCollections.observableArrayList(); for (MIDIGMPatch p : MIDIGMPatch.getAllPitched()) { patchNames.add(p.getName()); } } public ProgramStringListCell() { super(patchNames); } public ProgramStringListCell(ObservableList<String> programStrings) { super(programStrings); } @Override public void updateItem(String patchName, boolean empty) { super.updateItem(patchName, empty); if (patchName != null) { setText(MIDIGMPatch.getPatch(patchName).getName()); logger.debug("patch name {}", patchName); if (getTableRow() != null) { MIDINote note = (MIDINote) getTableRow().getItem(); if (note != null) { logger.debug("Table row {}", note); int program = MIDIGMPatch.getPatch(patchName) .getProgram(); note.setProgram(program); } } } } } Node foo() { Button btn = new Button("Add"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { tableDataList.add(MIDINoteBuilder.create().pitch(Pitch.C5) .build()); } }); VBox vb = VBoxBuilder.create() .spacing(5) .padding(new Insets(10, 0, 0, 10)) .build(); Label lbl = new Label("MIDI Track"); lbl.setFont(new Font("Arial", 20)); vb.getChildren().addAll(lbl, btn); return vb; } // public static class ComboBoxTableCell2<S, T> extends TableCell<S, T> { // private final ComboBox<MIDIGMPatch> comboBox; // // public ComboBoxTableCell2(ObservableList<MIDIGMPatch> patchList) { // this.comboBox = new ComboBox<MIDIGMPatch>(); // comboBox.setItems(patchList); // // setAlignment(Pos.CENTER); // setGraphic(comboBox); // } // // @Override // public void updateItem(T item, boolean empty) { // super.updateItem(item, empty); // if (empty) { // setText(null); // setGraphic(null); // } else { // if (getTableRow() != null) { // Object o = getTableRow().getItem(); // // } // } // } // } }
37.460064
112
0.493518
f21d4b9c89e07e497de111f3ffca4187e7486344
4,524
/* ***************** * * created by gparap * * ***************** */ package dmn.games.platformer.physics; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.objects.PolylineMapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.ChainShape; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import dmn.games.platformer.Platformer; public class BodyFactory { public static void createBody(World world, MapObject mapObject, Array<Body> worldBodies, boolean isCurrentLevelWorldBody) { //if it is an object of type "wall" (rectangle) if (mapObject.getProperties().get("type").equals("platform")) { //create and add the body to the game world BodyDef bodyDefinition = new BodyDef(); bodyDefinition.type = BodyDef.BodyType.StaticBody; bodyDefinition.position.set(((RectangleMapObject) mapObject).getRectangle().x * Platformer.SCALE_FACTOR, ((RectangleMapObject) mapObject).getRectangle().y * Platformer.SCALE_FACTOR); Body body = world.createBody(bodyDefinition); //create the shape of the fixture of the body PolygonShape shape = new PolygonShape(); shape.setAsBox(((RectangleMapObject) mapObject).getRectangle().width / 2f * Platformer.SCALE_FACTOR, ((RectangleMapObject) mapObject).getRectangle().height / 2f * Platformer.SCALE_FACTOR, new Vector2(((RectangleMapObject) mapObject).getRectangle().width / 2f * Platformer.SCALE_FACTOR, ((RectangleMapObject) mapObject).getRectangle().height / 2f * Platformer.SCALE_FACTOR), 0); //create the fixture of the body and add to it a shape FixtureDef fixtureDefinition = new FixtureDef(); fixtureDefinition.shape = shape; body.createFixture(fixtureDefinition); shape.dispose(); //don't need the shape anymore //add body to current level world bodies if (isCurrentLevelWorldBody) { worldBodies.add(body); } } //if it is an object of type "ground" or "slope" (polyline) else if (mapObject.getProperties().get("type").equals("ground") || mapObject.getProperties().get("type").equals("slope")) { //create and add the body to the game world BodyDef bodyDefinition = new BodyDef(); bodyDefinition.type = BodyDef.BodyType.StaticBody; bodyDefinition.position.set( ((PolylineMapObject) mapObject).getPolyline().getX() * Platformer.SCALE_FACTOR, ((PolylineMapObject) mapObject).getPolyline().getY() * Platformer.SCALE_FACTOR); Body body = world.createBody(bodyDefinition); //create the shape of the fixture of the body ChainShape shape = new ChainShape(); //scale the vertices of the shape int scaledVerticesLength = ((PolylineMapObject) mapObject).getPolyline().getVertices().length; float[] scaledVertices = new float[scaledVerticesLength]; for (int i = 0; i < scaledVerticesLength; i++) { scaledVertices[i] = ((PolylineMapObject) mapObject).getPolyline().getVertices()[i] * Platformer.SCALE_FACTOR; } shape.createChain(scaledVertices); //create the fixture of the body and add to it a shape FixtureDef fixtureDefinition = new FixtureDef(); fixtureDefinition.shape = shape; Fixture fixture = body.createFixture(fixtureDefinition); if (mapObject.getProperties().get("type").equals("ground")) { fixture.setUserData("ground"); } else if (mapObject.getProperties().get("type").equals("slope")) { fixture.setUserData("slope"); } shape.dispose(); //don't need the shape anymore //add body to current level world bodies if (isCurrentLevelWorldBody) { worldBodies.add(body); } } } }
53.223529
127
0.629752
672c97921d88b7cb79eac08da3590ddce7c3d623
4,005
package net.voxelindustry.voidheart.common.content.altar; import net.minecraft.block.Block; import net.minecraft.block.BlockEntityProvider; import net.minecraft.block.BlockState; import net.minecraft.block.Material; import net.minecraft.block.ShapeContext; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityTicker; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.sound.BlockSoundGroup; import net.minecraft.state.StateManager; import net.minecraft.state.property.Properties; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.ItemScatterer; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; import net.minecraft.util.shape.VoxelShapes; import net.minecraft.world.BlockView; import net.minecraft.world.World; import net.voxelindustry.steamlayer.common.utils.ItemUtils; import net.voxelindustry.voidheart.common.setup.VoidHeartTiles; import org.jetbrains.annotations.Nullable; import static net.minecraft.block.BlockWithEntity.checkType; public class VoidAltarBlock extends Block implements BlockEntityProvider { private static final VoxelShape SHAPE = VoxelShapes.union( createCuboidShape(0, 0, 0, 16, 4, 16), createCuboidShape(1, 4, 1, 15, 8, 15), createCuboidShape(0, 8, 0, 16, 14, 16), createCuboidShape(5, 14, 5, 11, 16, 11) ); public VoidAltarBlock() { super(Settings.of(Material.STONE) .strength(3F) .sounds(BlockSoundGroup.STONE) .luminance(state -> state.get(Properties.LIT) ? 11 : 0)); setDefaultState(getStateManager().getDefaultState() .with(Properties.LIT, false)); } @Override public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { return SHAPE; } @Override public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { VoidAltarTile altar = (VoidAltarTile) world.getBlockEntity(pos); if (altar == null) return ActionResult.SUCCESS; if (altar.getStack().isEmpty()) { altar.setStack(player, ItemUtils.copyWithSize(player.getStackInHand(hand), 1)); if (!player.isCreative()) player.getStackInHand(hand).decrement(1); } else { if (!player.giveItemStack(altar.getStack())) player.dropItem(altar.getStack(), false); altar.setStack(player, ItemStack.EMPTY); } return ActionResult.SUCCESS; } @Override public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) { if (!state.isOf(newState.getBlock())) { VoidAltarTile tile = (VoidAltarTile) world.getBlockEntity(pos); if (tile != null) { tile.removeItself(); ItemScatterer.spawn(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, tile.getStack()); tile.dropAteItems(); } } super.onStateReplaced(state, world, pos, newState, moved); } @Override protected void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(Properties.LIT); } @Nullable @Override public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { return new VoidAltarTile(pos, state); } @Nullable @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker(World world, BlockState state, BlockEntityType<T> type) { return checkType(type, VoidHeartTiles.VOID_ALTAR, VoidAltarTile::tick); } }
33.940678
126
0.680899
d9e3869765f4512bd435dfb179d27bdd251603e6
518
package net.collaud.hashcode.data; import lombok.Data; @Data public class Topping { private final boolean tomato; private boolean used; public Topping(boolean tomato) { this.tomato = tomato; this.used = false; } @Override public String toString() { if(used){ return "."; // if(tomato){ // return "t"; // } // return "m"; } if(tomato){ return "T"; } return "M"; } public Topping clone(){ Topping topping = new Topping(tomato); topping.setUsed(used); return topping; } }
14.388889
40
0.633205
8e0cf6ce958f935ff506af42285b77932e05c871
5,324
package org.smoothbuild.acceptance.lang.assign.convert; import static com.google.common.truth.Truth.assertThat; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.BLOB; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.BLOB_ARRAY; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.BLOB_ARRAY2; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.BOOL; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.BOOL_ARRAY; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.BOOL_ARRAY2; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.NOTHING_ARRAY; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.NOTHING_ARRAY2; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.STRING; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.STRING_ARRAY; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.STRING_ARRAY2; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.STRUCT_WITH_STRING; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.STRUCT_WITH_STRING_ARRAY; import static org.smoothbuild.acceptance.lang.assign.spec.TestedType.STRUCT_WITH_STRING_ARRAY2; import static org.smoothbuild.util.Lists.list; import java.io.IOException; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.smoothbuild.acceptance.AcceptanceTestCase; import org.smoothbuild.acceptance.lang.assign.spec.TestSpec; import org.smoothbuild.acceptance.lang.assign.spec.TestedType; import org.smoothbuild.acceptance.testing.ReportError; public abstract class AbstractConversionTestCase extends AcceptanceTestCase { @ParameterizedTest @MethodSource("conversion_test_specs") public void conversion_is_verified(ConversionTestSpec testSpec) throws IOException { createNativeJar(ReportError.class); createUserModule(createTestScript(testSpec)); runSmoothBuild("result"); assertFinishedWithSuccess(); Object expected = testSpec.expectedResult; // Currently it is not possible to read artifact of a struct so we are not testing that. if (expected != null) { assertThat(stringifiedArtifact("result")) .isEqualTo(expected); } } protected abstract String createTestScript(ConversionTestSpec testSpec); public static Stream<ConversionTestSpec> conversion_test_specs() { return Stream.of( // Blob allowedConversion(BLOB, BLOB), // Bool allowedConversion(BOOL, BOOL), // Nothing // String allowedConversion(STRING, STRING), allowedConversion(STRING, STRUCT_WITH_STRING, "John"), // Struct allowedConversion(STRUCT_WITH_STRING, STRUCT_WITH_STRING), // [Blob] allowedConversion(BLOB_ARRAY, BLOB_ARRAY), allowedConversion(BLOB_ARRAY, NOTHING_ARRAY), // [Bool] allowedConversion(BOOL_ARRAY, BOOL_ARRAY), allowedConversion(BOOL_ARRAY, NOTHING_ARRAY), // [Nothing] allowedConversion(NOTHING_ARRAY, NOTHING_ARRAY), // [String] allowedConversion(STRING_ARRAY, NOTHING_ARRAY), allowedConversion(STRING_ARRAY, STRUCT_WITH_STRING_ARRAY, list("John")), allowedConversion(STRING_ARRAY, STRING_ARRAY), // [Struct] allowedConversion(STRUCT_WITH_STRING_ARRAY, NOTHING_ARRAY), allowedConversion(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_STRING_ARRAY), // [[Blob]] allowedConversion(BLOB_ARRAY2, NOTHING_ARRAY), allowedConversion(BLOB_ARRAY2, BLOB_ARRAY2), allowedConversion(BLOB_ARRAY2, NOTHING_ARRAY2), // [[Bool]] allowedConversion(BOOL_ARRAY2, NOTHING_ARRAY), allowedConversion(BOOL_ARRAY2, BOOL_ARRAY2), allowedConversion(BOOL_ARRAY2, NOTHING_ARRAY2), // [[Nothing]] allowedConversion(NOTHING_ARRAY2, NOTHING_ARRAY), allowedConversion(NOTHING_ARRAY2, NOTHING_ARRAY2), // [[String]] allowedConversion(STRING_ARRAY2, NOTHING_ARRAY), allowedConversion(STRING_ARRAY2, NOTHING_ARRAY2), allowedConversion(STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY2, list(list("John"))), allowedConversion(STRING_ARRAY2, STRING_ARRAY2), // [[Struct]] allowedConversion(STRUCT_WITH_STRING_ARRAY2, NOTHING_ARRAY), allowedConversion(STRUCT_WITH_STRING_ARRAY2, NOTHING_ARRAY2), allowedConversion(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY2.value) ); } public static ConversionTestSpec allowedConversion(TestedType target, TestedType source) { return new ConversionTestSpec(target, source, source.value); } public static ConversionTestSpec allowedConversion(TestedType target, TestedType source, Object expectedResult) { return new ConversionTestSpec(target, source, expectedResult); } public static class ConversionTestSpec extends TestSpec { public final Object expectedResult; private ConversionTestSpec(TestedType target, TestedType source, Object expectedResult) { super(target, source); this.expectedResult = expectedResult; } } }
38.861314
95
0.761082
cc451f294f22ccc8829a2413fe7b55d7784c9d60
860
package com.jeiker.demo.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.Map; /** * @Author : xiao * @Date : 17/9/18 下午3:09 */ @RestController @RequestMapping("/test") public class HelloController { private static final Logger log = LoggerFactory.getLogger(HelloController.class); @GetMapping("/hello") public Map<String, String> hello() { for (int i = 0; i < 10; i++) { log.info("===> 输出info日志。"); log.debug("===> 输出debug日志。"); log.error("===> 输出error日志。"); } return Collections.singletonMap("message", "Hello World"); } }
26.875
85
0.673256
4f0f45a3a346ceac8774d959912f41a583bdba66
8,331
package mx.cecyt9.ipn.calculator_hevc; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button bUno, bDos, bTres, bCuatro, bCinco, bSeis, bSiete, bOcho, bNueve, bCero; Button bMas, bMenos, bPor, bEntre, bIgual, bPunto, bLimpiar, bRetroceso; TextView texto; Double numero1 = 0.0, numero2 = 0.0, resultado = 0.0; String operador = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); texto = (TextView)findViewById(R.id.texto); bUno = (Button)findViewById(R.id.uno); bDos = (Button)findViewById(R.id.dos); bTres = (Button)findViewById(R.id.tres); bCuatro = (Button)findViewById(R.id.cuatro); bCinco = (Button)findViewById(R.id.cinco); bSeis = (Button)findViewById(R.id.seis); bSiete = (Button)findViewById(R.id.siete); bOcho = (Button)findViewById(R.id.ocho); bNueve = (Button)findViewById(R.id.nueve); bCero = (Button)findViewById(R.id.cero); bMas = (Button)findViewById(R.id.mas); bMenos = (Button)findViewById(R.id.menos); bPor = (Button)findViewById(R.id.por); bEntre = (Button)findViewById(R.id.entre); bIgual = (Button)findViewById(R.id.igual); bPunto = (Button)findViewById(R.id.punto); bLimpiar = (Button)findViewById(R.id.limpiar); bRetroceso = (Button)findViewById(R.id.restroceso); bUno.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("1"); } }); bDos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("2"); } }); bTres.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("3"); } }); bCuatro.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("4"); } }); bCinco.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("5"); } }); bSeis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("6"); } }); bSiete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("7"); } }); bOcho.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("8"); } }); bNueve.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("9"); } }); bCero.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("0"); } }); bMas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { suma(); } }); bMenos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { resta(); } }); bPor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { multiplicacion(); } }); bEntre.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { division(); } }); bIgual.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { calcular(); } }); bPunto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { concatenarNumeros("."); } }); bLimpiar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { limpiar(); } }); bRetroceso.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { borrar(); } }); } public void concatenarNumeros(String numero){ texto = (TextView) findViewById(R.id.texto); texto.setText(texto.getText() + numero); } public void suma(){ operador = "+"; capturarNumero1(); } public void resta(){ operador = "-"; capturarNumero1(); } public void multiplicacion(){ operador = "*"; capturarNumero1(); } public void division(){ operador = "/"; capturarNumero1(); } public void calcular(){ texto = (TextView) findViewById(R.id.texto); numero2 = Double.parseDouble(texto.getText().toString()); switch(operador){ case "+": resultado = numero1 + numero2; break; case "-": resultado = numero1 - numero2; break; case "*": resultado = numero1 * numero2; break; case "/": resultado = numero1 / numero2; break; } texto.setText(resultado.toString()); } public void capturarNumero1(){ texto = (TextView) findViewById(R.id.texto); numero1 = Double.parseDouble(texto.getText().toString()); texto.setText(""); } public void limpiar(){ numero1 = 0.0; numero2 = 0.0; operador = ""; texto = (TextView) findViewById(R.id.texto); texto.setText(""); } public void borrar(){ texto = (TextView) findViewById(R.id.texto); String txt = texto.getText().toString(); if(!txt.equals("")){ txt = txt.substring(0, txt.length() -1); texto.setText(txt); } } public void calcularSeno(View view) { texto = (TextView) findViewById(R.id.texto); String txt = texto.getText().toString(); if(txt.equals("")){ txt = "0"; } double numero = Double.parseDouble(txt); double resultado = Math.sin(Math.toRadians(numero)); texto.setText(String.valueOf(resultado)); } public void calcularCoseno(View view) { texto = (TextView) findViewById(R.id.texto); String txt = texto.getText().toString(); if(txt.equals("")){ txt = "0"; } double numero = Double.parseDouble(txt); double resultado = Math.cos(Math.toRadians(numero)); texto.setText(String.valueOf(resultado)); } public void calcularTangente(View view) { texto = (TextView) findViewById(R.id.texto); String txt = texto.getText().toString(); if(txt.equals("")){ txt = "0"; } double numero = Double.parseDouble(txt); double resultado = Math.tan(Math.toRadians(numero)); texto.setText(String.valueOf(resultado)); } public void calcularCuadrado(View view) { texto = (TextView) findViewById(R.id.texto); String txt = texto.getText().toString(); if(txt.equals("")){ txt = "0"; } double numero = Double.parseDouble(txt); double resultado = Math.pow(numero, 2); texto.setText(String.valueOf(resultado)); } }
29.647687
83
0.539431
aaa0d7daa1fc2935bca59fd2e312cc314745ccc7
3,291
/* Class216 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.jagex; import java.awt.Canvas; class Class216 implements Interface44 { Class217 this$0; public static Class472 aClass472_2271; public float method339() { return ((float) Class449.aClass523_Sub33_4946.aClass687_Sub22_10651.method16930(1529347143) / 255.0F); } public float method338(short i) { return ((float) Class449.aClass523_Sub33_4946.aClass687_Sub22_10651.method16930(1782296830) / 255.0F); } public float method337() { return ((float) Class449.aClass523_Sub33_4946.aClass687_Sub22_10651.method16930(1674463738) / 255.0F); } Class216(Class217 class217) { this$0 = class217; } public float method336() { return ((float) Class449.aClass523_Sub33_4946.aClass687_Sub22_10651.method16930(1941407749) / 255.0F); } static final void method3847(Class669 class669, byte i) { class669.anInt8558 -= -17422498; int i_0_ = class669.anIntArray8557[class669.anInt8558 * 1357652815]; int i_1_ = class669.anIntArray8557[1 + class669.anInt8558 * 1357652815]; class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = client.aClass220_11301.method4107(i_0_, -2066395635).method4051(i_1_, 1358925136) ? 1 : 0; } static final void method3848(Class669 class669, byte i) { Class449.aClass523_Sub33_4946.method16240(Class449.aClass523_Sub33_4946.aClass687_Sub32_10644, (class669.anIntArray8557[(class669.anInt8558 -= 2138772399) * 1357652815]) != 0 ? 1 : 0, -803865516); Class211.method3824(1692685321); } static final void method3849(Class669 class669, byte i) { Class523_Sub27_Sub17 class523_sub27_sub17 = Class502.method8158((byte) 65); if (null != class523_sub27_sub17) { boolean bool = (class523_sub27_sub17.method18214(158908775 * Class575.anInt7691 + Class534.anInt7168, -217599855 * Class597.anInt7835 + Class534.anInt7159, Class663.anIntArray8517, -1422170026)); if (bool) { class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = Class663.anIntArray8517[1]; class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = Class663.anIntArray8517[2]; } else { class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = -1; class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = -1; } } else { class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = -1; class669.anIntArray8557[(class669.anInt8558 += 2138772399) * 1357652815 - 1] = -1; } } static final int method3850(Class73 class73, int i) { if (class73 == null) return 12; switch (class73.anInt809 * 1652964889) { case 1: return 20; default: return 12; } } public static int method3851(byte i) { Canvas canvas = new Canvas(); canvas.setSize(100, 100); Class178 class178 = Class236.method4290(0, canvas, null, null, null, null, null, null, 0, (byte) -87); long l = Class248.method4401(1516375036); for (int i_2_ = 0; i_2_ < 10000; i_2_++) class178.method3330(5, 10, 100.0F, 75, 50, 100.0F, 15, 90, 100.0F, -65536, -65536, -65536, 1); int i_3_ = (int) (Class248.method4401(1516375036) - l); class178.method3354(0, 0, 100, 100, -16777216, (byte) 54); class178.method3024(844296746); return i_3_; } }
38.717647
198
0.728654
701235c8cf93e8296f8280e846ed43decb2384ac
403
package org.zstack.header.rest; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by xing5 on 2016/12/9. */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface RestResponse { String allTo() default ""; String[] fieldsTo() default {}; }
23.705882
44
0.754342
5cbc8c40c39245eaab31521bf45f7da29ba58670
3,252
package com.ruoyi.web.controller.system; import java.util.List; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.system.domain.DrawItem; import com.ruoyi.system.service.IDrawItemService; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.common.core.page.TableDataInfo; /** * 物品Controller * * @author ruoyi * @date 2020-12-03 */ @RestController @RequestMapping("/system/item") public class DrawItemController extends BaseController { @Autowired private IDrawItemService drawItemService; /** * 查询物品列表 */ @PreAuthorize("@ss.hasPermi('system:item:list')") @GetMapping("/list") public TableDataInfo list(DrawItem drawItem) { startPage(); List<DrawItem> list = drawItemService.selectDrawItemList(drawItem); return getDataTable(list); } /** * 导出物品列表 */ @PreAuthorize("@ss.hasPermi('system:item:export')") @Log(title = "物品", businessType = BusinessType.EXPORT) @GetMapping("/export") public AjaxResult export(DrawItem drawItem) { List<DrawItem> list = drawItemService.selectDrawItemList(drawItem); ExcelUtil<DrawItem> util = new ExcelUtil<DrawItem>(DrawItem.class); return util.exportExcel(list, "item"); } /** * 获取物品详细信息 */ @PreAuthorize("@ss.hasPermi('system:item:query')") @GetMapping(value = "/{id}") public AjaxResult getInfo(@PathVariable("id") Long id) { return AjaxResult.success(drawItemService.selectDrawItemById(id)); } /** * 新增物品 */ @PreAuthorize("@ss.hasPermi('system:item:add')") @Log(title = "物品", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody DrawItem drawItem) { drawItem.setIcon("http://fuli.xiaoheigame.com/img/bean_500.png"); return toAjax(drawItemService.insertDrawItem(drawItem)); } /** * 修改物品 */ @PreAuthorize("@ss.hasPermi('system:item:edit')") @Log(title = "物品", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody DrawItem drawItem) { return toAjax(drawItemService.updateDrawItem(drawItem)); } /** * 删除物品 */ @PreAuthorize("@ss.hasPermi('system:item:remove')") @Log(title = "物品", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) { return toAjax(drawItemService.deleteDrawItemByIds(ids)); } }
30.971429
75
0.708487
e45d94bce777de3e74e846df34da9b35c6ad1f2d
4,649
package egov.casemanagement.service; import com.fasterxml.jackson.databind.ObjectMapper; import egov.casemanagement.config.Configuration; import egov.casemanagement.models.cova.CovaData; import egov.casemanagement.models.cova.CovaSearchResponse; import egov.casemanagement.models.user.User; import egov.casemanagement.producer.Producer; import egov.casemanagement.repository.ServiceRequestRepository; import egov.casemanagement.utils.SmsNotificationService; import egov.casemanagement.web.models.HealthdetailCreateRequest; import lombok.extern.slf4j.Slf4j; import org.egov.common.contract.request.RequestInfo; import org.egov.tracer.model.CustomException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import java.util.*; @Service @Slf4j public class CovaService { @Autowired private UserService userService; @Autowired private SmsNotificationService smsNotificationService; @Autowired private ServiceRequestRepository serviceRequestRepository; @Autowired private Producer producer; @Autowired private Configuration configuration; @Autowired private ObjectMapper mapper; public void createCovaCases(RequestInfo requestInfo,String date){ HttpHeaders headers = new HttpHeaders(); headers.set("authorization", configuration.getCovaAuthToken()); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Map> request = new HttpEntity<>(Collections.singletonMap("timestamp", date), headers); LinkedHashMap responseMap = (LinkedHashMap) serviceRequestRepository.fetchResult(configuration.getCovaFetchUrl(), request); CovaSearchResponse response = mapper.convertValue(responseMap, CovaSearchResponse.class); if(response.getResponse() == 1){ Set<String> mobileNumbers = new HashSet<>(); for (CovaData record: response.getData()) { mobileNumbers.add(record.getMobileNumber()); } Set<String> usersToCreate = userService.removeExistingUsers(mobileNumbers, requestInfo); for (String mobile: usersToCreate) { User user = userService.createCovaUser(requestInfo, mobile); if(user !=null && user.getUuid() != null){ log.info("User successfully created, sending on-boarding SMS."); smsNotificationService.sendCreateCaseSms(mobile); } } } } public void addHealthDetail(HealthdetailCreateRequest request){ if(request.getMobileNumber() == null ) throw new CustomException("INVALID_CREATE_REQUEST", "Mobile number or user identifier mandatory"); if( ! userService.userExists(request.getMobileNumber(), request.getRequestInfo())) throw new CustomException("INVALID_CREATE_REQUEST", "No COVA case registered against this number"); producer.push(configuration.getCovaHealthRecordTopic(), request.getMobileNumber(), request); HttpHeaders headers = new HttpHeaders(); headers.set("authorization", configuration.getCovaAuthToken()); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, Object> map = new HashMap<>(); map.put("inspection_type", "W"); map.put("mobile_no", request.getMobileNumber()); map.put("arrival_at_home", getValFromBool(true)); map.put("question_1", getValFromBool(request.getHealthDetails().at("/0/fever").asBoolean())); map.put("question_2", getValFromBool(request.getHealthDetails().at("/0/dryCough").asBoolean())); map.put("question_3", getValFromBool(request.getHealthDetails().at("/0/breathingIssues").asBoolean())); map.put("current_temp", request.getHealthDetails().at("/0/temperature").asText()); HttpEntity<Map> body = new HttpEntity<>(map, headers); LinkedHashMap responseMap = (LinkedHashMap) serviceRequestRepository.fetchResult(configuration.getCovaCreateHealthRecordUrl(), body); if((int) responseMap.get("response") != 1) { log.error("Error response received from API!"); log.error(responseMap.toString()); throw new CustomException("HEALTH_DETAILS_SUBMITTED", "You have already submitted Self-Quarantine " + "Inspection for the day."); } } private String getValFromBool(boolean flag){ if(flag) return "YES"; else return "NO"; } }
42.263636
141
0.708324
39a23999045234dbf60165d73ff6f98f5eff57e7
4,257
package gregpearce.archivorg.platform.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import butterknife.BindView; import butterknife.ButterKnife; import com.bluelinelabs.conductor.Conductor; import com.bluelinelabs.conductor.Router; import com.bluelinelabs.conductor.RouterTransaction; import gregpearce.archivorg.R; import gregpearce.archivorg.platform.BaseController; import gregpearce.archivorg.platform.bookmarks.BookmarkController; import gregpearce.archivorg.platform.discover.DiscoverController; import java.util.List; import timber.log.Timber; public class MainActivity extends AppCompatActivity implements DrawerLayoutProvider { @BindView(R.id.controller_container) ViewGroup container; @BindView(R.id.drawer_layout) DrawerLayout drawerLayout; private Router router; private enum RootController {Discover, Bookmarks, Downloads, Settings} private RootController rootController; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); // Set up the navigation drawer. drawerLayout.setStatusBarBackground(R.color.colorPrimaryDark); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); if (navigationView != null) { setupDrawerContent(navigationView); } router = Conductor.attachRouter(this, container, savedInstanceState); if (!router.hasRootController()) { rootController = RootController.Discover; navigationView.getMenu().findItem(R.id.drawer_discover).setChecked(true); router.setRoot(RouterTransaction.with(new DiscoverController())); } } private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener(menuItem -> { navigationView.getMenu().findItem(R.id.drawer_discover).setChecked(false); navigationView.getMenu().findItem(R.id.drawer_bookmarks).setChecked(false); navigationView.getMenu().findItem(R.id.drawer_downloads).setChecked(false); navigationView.getMenu().findItem(R.id.drawer_settings).setChecked(false); switch (menuItem.getItemId()) { case R.id.drawer_discover: if (rootController != RootController.Discover) { rootController = RootController.Discover; router.setRoot(RouterTransaction.with(new DiscoverController())); } break; case R.id.drawer_bookmarks: if (rootController != RootController.Bookmarks) { rootController = RootController.Bookmarks; router.setRoot(RouterTransaction.with(new BookmarkController())); } break; case R.id.drawer_downloads: if (rootController != RootController.Downloads) { rootController = RootController.Downloads; //router.setRoot(RouterTransaction.with(new DiscoverController())); } break; case R.id.drawer_settings: if (rootController != RootController.Settings) { rootController = RootController.Settings; //router.setRoot(RouterTransaction.with(new DiscoverController())); } break; default: Timber.e("Unknown drawer option"); break; } // Close the navigation drawer when an item is selected. menuItem.setChecked(true); drawerLayout.closeDrawers(); return true; }); } @Override public void onBackPressed() { if (drawerLayout != null && drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else if (!router.handleBack()) { super.onBackPressed(); } } public BaseController getActivityController() { List<RouterTransaction> backstack = router.getBackstack(); return (BaseController) backstack.get(backstack.size() - 1).controller(); } @Override public DrawerLayout getDrawerLayout() { return drawerLayout; } }
37.672566
85
0.726568
03969440799edece6cde97d12b07a0d7a234160a
4,231
package com.ogiqvo.clock; import java.util.ArrayList; import java.util.List; /** * The MIT License (MIT) Copyright (c) 2017 Izumi Kawashima 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. */ public class Clock { private long realUtcMilliseconds; private long floatingUtcMilliseconds; private long prevUtcMilliseconds; private double timePower; private List<ClockUpdateReceivable> tickEventDelegates; public Clock() { this.timePower = 1.0; this.realUtcMilliseconds = this.floatingUtcMilliseconds = this.prevUtcMilliseconds = System.currentTimeMillis(); this.tickEventDelegates = new ArrayList<>(); } public void addTickEventDelegate(ClockUpdateReceivable tickEventDelegate) { this.tickEventDelegates.add(tickEventDelegate); } public void start() { this.realUtcMilliseconds = System.currentTimeMillis(); this.floatingUtcMilliseconds = this.prevUtcMilliseconds; this.handleClockUpdateEvent(); } public void setUtcMilliseconds(long utcMilliseconds) { this.floatingUtcMilliseconds = utcMilliseconds; this.realUtcMilliseconds = System.currentTimeMillis(); } public long getUtcMilliseconds() { long realDelta = System.currentTimeMillis() - this.realUtcMilliseconds; long amplifiedRealDelta = (long) (realDelta * this.timePower); this.prevUtcMilliseconds = this.floatingUtcMilliseconds + amplifiedRealDelta; return this.prevUtcMilliseconds; } public long getPrevUtcMilliseconds() { return prevUtcMilliseconds; } public void setPrevUtcMilliseconds(long prevUtcMilliseconds) { this.prevUtcMilliseconds = prevUtcMilliseconds; } public long getRealUtcMilliseconds() { return realUtcMilliseconds; } public void setRealUtcMilliseconds(long realUtcMilliseconds) { this.realUtcMilliseconds = realUtcMilliseconds; } public long getFloatingUtcMilliseconds() { return floatingUtcMilliseconds; } public void setFloatingUtcMilliseconds(long floatingUtcMilliseconds) { this.floatingUtcMilliseconds = floatingUtcMilliseconds; } public double getTimePower() { return timePower; } public void setTimePower(double timePower) { boolean isTimePowerUpdated = this.timePower != timePower; this.timePower = timePower; if (isTimePowerUpdated) { handlePowerUpdateEvent(); } } public void handleClockUpdateEvent() { int length = this.tickEventDelegates.size(); long utcMilliseconds = this.getUtcMilliseconds(); for (int i = 0; i < length; i++) { ClockUpdateReceivable l = this.tickEventDelegates.get(i); l.onClockUpdate(utcMilliseconds); } } public void handlePowerUpdateEvent() { int length = this.tickEventDelegates.size(); for (int i = 0; i < length; i++) { ClockUpdateReceivable l = this.tickEventDelegates.get(i); l.onPowerUpdate(this.timePower); } } public interface ClockUpdateReceivable { void onClockUpdate(long utcMilliseconds); void onPowerUpdate(double power); } }
33.848
120
0.712834
d846582e144dc8d9444c7e5d93a5de31aa0a0044
626
package de.feffi.jnumber; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author feffi <[email protected]> */ public class EnumSerialErrorTest { /** * Test method for {@link de.feffi.jnumber.EnumSerialError#toString()}. */ @Test public void testToString() { assertEquals("Check digit failure!", EnumSerialError.CHECKDIGIT.toString()); assertEquals("Fake serial!", EnumSerialError.FAKE_SERIAL.toString()); assertEquals("Invalid serial chars!", EnumSerialError.INVALID_CHARS.toString()); assertEquals("Invalid serial length!", EnumSerialError.INVALID_LENGTH.toString()); } }
27.217391
84
0.739617
231ac28b2f03f76f9ba6aed764f3eb3b1f6042fe
1,129
package com.neusoft.oa.document.web.attachmentManage; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.neusoft.oa.core.OAException; import com.neusoft.oa.core.service.FunctionFactory; import com.neusoft.oa.core.web.servlet.CommonServlet; import com.neusoft.oa.document.function.AttachmentFunction; import com.neusoft.oa.document.function.DocumentFunction; import com.neusoft.oa.system.function.AdministratorFunction; @WebServlet("/attachmentManage/del.do") public class DelServlet extends CommonServlet { @Override protected String handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Throwable { // 1获取 String id = req.getParameter("id"); // 2调用业务方法 try { AttachmentFunction fun=FunctionFactory.getFunction(AttachmentFunction.class); fun.deleteAttachment(id); req.setAttribute("message", "删除成功!"); } catch (OAException e) { req.setAttribute("message", e.getMessage()); } // 3确认视图 req.setAttribute("nextUrl", "documentManage/list.do"); return "/jsp/message.jsp"; } }
29.710526
100
0.779451
8f544f1e70674003fccf712bc053d3eda58f4810
1,093
package net.apachegui.web; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.json.JSONObject; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.http.HttpStatus; @ControllerAdvice public class BaseControllerAdvice { private static Logger log = Logger.getLogger(BaseControllerAdvice.class); @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @RequestMapping(produces = "application/json;charset=UTF-8") @ResponseBody public String handleError(HttpServletResponse response, Exception exception) { log.error(exception.getMessage(), exception); JSONObject resultJSON = new JSONObject(); resultJSON.put("message", exception.getMessage()); return resultJSON.toString(); } }
33.121212
82
0.78774
a3a96299c5199e6a563fef0d310592eaafad061e
2,667
/* * * Copyright 2015 Netflix, 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.netflix.genie.common.util; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.util.ISO8601Utils; import com.netflix.genie.test.categories.UnitTest; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import java.io.IOException; import java.util.Date; /** * Test the TestJsonDateSerializer. * * @author tgianos * @since 2.0.0 */ @Category(UnitTest.class) public class JsonDateSerializerUnitTests { private static final long MILLISECONDS = 1405715627311L; private static final Date DATE = new Date(MILLISECONDS); private String expectedString; /** * Setup the tests. */ @Before public void setup() { this.expectedString = ISO8601Utils.format(DATE, true); } /** * Test the serialization method. * * @throws IOException When exception happens during serialization */ @Test public void testSerialize() throws IOException { final JsonGenerator gen = Mockito.mock(JsonGenerator.class); final SerializerProvider provider = Mockito.mock(SerializerProvider.class); final JsonDateSerializer serializer = new JsonDateSerializer(); serializer.serialize(DATE, gen, provider); Mockito.verify(gen, Mockito.times(1)).writeString(this.expectedString); } /** * Test the serialization method with a null date. * * @throws IOException When exception happens during serialization */ @Test public void testSerializeNull() throws IOException { final JsonGenerator gen = Mockito.mock(JsonGenerator.class); final SerializerProvider provider = Mockito.mock(SerializerProvider.class); final JsonDateSerializer serializer = new JsonDateSerializer(); serializer.serialize(null, gen, provider); Mockito.verify(gen, Mockito.times(1)).writeString((String) null); } }
32.13253
83
0.709411
acd2b252d8f9d780fec22da201c82dfd648d83f2
5,913
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.service; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteServices; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.util.typedef.PA; import org.apache.ignite.resources.LoggerResource; import org.apache.ignite.services.Service; import org.apache.ignite.services.ServiceContext; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; /** * */ public class IgniteServiceDynamicCachesSelfTest extends GridCommonAbstractTest { /** */ private static final int GRID_CNT = 4; /** */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); TcpDiscoverySpi discoSpi = new TcpDiscoverySpi(); discoSpi.setIpFinder(IP_FINDER); cfg.setDiscoverySpi(discoSpi); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { startGrids(GRID_CNT); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(); } /** * @throws Exception If failed. */ public void testDeployCalledAfterCacheStart() throws Exception { String cacheName = "cache"; CacheConfiguration ccfg = new CacheConfiguration(cacheName); ccfg.setBackups(1); Ignite ig = ignite(0); ig.createCache(ccfg); try { final IgniteServices svcs = ig.services(); final String svcName = "myService"; svcs.deployKeyAffinitySingleton(svcName, new TestService(), cacheName, primaryKey(ig.cache(cacheName))); boolean res = GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return svcs.service(svcName) != null; } }, 10 * 1000); assertTrue("Service was not deployed", res); ig.destroyCache(cacheName); res = GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return svcs.service(svcName) == null; } }, 10 * 1000); assertTrue("Service was not undeployed", res); } finally { ig.services().cancelAll(); ig.destroyCache(cacheName); } } /** * @throws Exception If failed. */ public void testDeployCalledBeforeCacheStart() throws Exception { String cacheName = "cache"; CacheConfiguration ccfg = new CacheConfiguration(cacheName); ccfg.setBackups(1); Ignite ig = ignite(0); final IgniteServices svcs = ig.services(); final String svcName = "myService"; ig.createCache(ccfg); Object key = primaryKey(ig.cache(cacheName)); ig.destroyCache(cacheName); awaitPartitionMapExchange(); svcs.deployKeyAffinitySingleton(svcName, new TestService(), cacheName, key); assert svcs.service(svcName) == null; ig.createCache(ccfg); try { boolean res = GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return svcs.service(svcName) != null; } }, 10 * 1000); assertTrue("Service was not deployed", res); info("stopping cache: " + cacheName); ig.destroyCache(cacheName); res = GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return svcs.service(svcName) == null; } }, 10 * 1000); assertTrue("Service was not undeployed", res); } finally { ig.services().cancelAll(); ig.destroyCache(cacheName); } } /** * */ private static class TestService implements Service { /** */ @LoggerResource private IgniteLogger log; /** {@inheritDoc} */ @Override public void cancel(ServiceContext ctx) { log.info("Service cancelled."); } /** {@inheritDoc} */ @Override public void init(ServiceContext ctx) throws Exception { log.info("Service deployed."); } /** {@inheritDoc} */ @Override public void execute(ServiceContext ctx) throws Exception { log.info("Service executed."); } } }
30.479381
116
0.636394
ee7c710e4e314cc71e6142cc564f8927db9461e6
154
/** * Package for junior.pack2.p9.ch4. JSP. * * @author Gureyev Ilya (mailto:[email protected]) * @version 1 * @since 2017-11-13 */ package ru.job4j.jsp;
17.111111
49
0.675325
fb7b1ae5f045c1f4cc821d5e180c50a11c80f795
1,409
package com.werdpressed.partisan.undoredo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.werdpressed.partisan.undoredo.activityexample.ActivityExampleActivity; import com.werdpressed.partisan.undoredo.fragmentexample.FragmentExampleActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button mActivityExampleButton = (Button) findViewById(R.id.activity_example_btn); Button mFragmentExampleButton = (Button) findViewById(R.id.fragment_example_btn); mActivityExampleButton.setOnClickListener(this); mFragmentExampleButton.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent; switch (v.getId()) { case R.id.activity_example_btn: intent = new Intent(this, ActivityExampleActivity.class); startActivity(intent); break; case R.id.fragment_example_btn: intent = new Intent(this, FragmentExampleActivity.class); startActivity(intent); break; } } }
29.978723
89
0.702626
752a8dad6f18c660004316de012c67d9cf53559b
2,705
package org.mvss.karta.framework.nodes; import org.mvss.karta.framework.enums.NodeType; import lombok.*; import java.io.Serializable; /** * This class groups the node configuration for a Karta node * * @author Manian */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Builder public class KartaNodeConfiguration implements Serializable { /** * */ private static final long serialVersionUID = 1L; /** * Name of the Karta node. This ideally should indicate the role of the node if not a minion. */ @Builder.Default private String name = "local"; /** * The host name/IP for the node. */ @Builder.Default private String host = "localhost"; /** * The TCP/IP port for the node. */ @Builder.Default private int port = 17171; /** * Indicates if SSL is to be used for connection. */ @Builder.Default private boolean enableSSL = true; /** * Indicates if the node is a minion. Minions are used for load sharing to run feature iterations. */ @Builder.Default private boolean minion = false; /** * The node type RMI or REST. */ @Builder.Default private NodeType nodeType = NodeType.RMI; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( enableSSL ? 1231 : 1237 ); result = prime * result + ( ( host == null ) ? 0 : host.hashCode() ); result = prime * result + ( minion ? 1231 : 1237 ); result = prime * result + ( ( name == null ) ? 0 : name.hashCode() ); result = prime * result + ( ( nodeType == null ) ? 0 : nodeType.hashCode() ); result = prime * result + port; return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; KartaNodeConfiguration other = (KartaNodeConfiguration) obj; if ( enableSSL != other.enableSSL ) return false; if ( host == null ) { if ( other.host != null ) return false; } else if ( !host.equals( other.host ) ) return false; if ( minion != other.minion ) return false; if ( name == null ) { if ( other.name != null ) return false; } else if ( !name.equals( other.name ) ) return false; if ( nodeType != other.nodeType ) return false; return port == other.port; } }
24.590909
102
0.556377
2b67951634c7f693a89eb6a585c18247042c498e
186
package cz.xtf.builder.builders.limits; public class MemoryResource extends ComputingResource { @Override public String resourceIdentifier() { return "memory"; } }
18.6
55
0.709677
a7d8c79896abce76cd022d267ec2e0c25d942be4
2,451
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|pdfbox operator|. name|util package|; end_package begin_comment comment|/** * A 2D vector. * * @author John Hewson */ end_comment begin_class specifier|public specifier|final class|class name|Vector block|{ specifier|private specifier|final name|float name|x decl_stmt|, name|y decl_stmt|; specifier|public name|Vector parameter_list|( name|float name|x parameter_list|, name|float name|y parameter_list|) block|{ name|this operator|. name|x operator|= name|x expr_stmt|; name|this operator|. name|y operator|= name|y expr_stmt|; block|} comment|/** * Returns the x magnitude. */ specifier|public name|float name|getX parameter_list|() block|{ return|return name|x return|; block|} comment|/** * Returns the y magnitude. */ specifier|public name|float name|getY parameter_list|() block|{ return|return name|y return|; block|} comment|/** * Returns a new vector scaled by both x and y. * * @param sxy x and y scale */ specifier|public name|Vector name|scale parameter_list|( name|float name|sxy parameter_list|) block|{ return|return operator|new name|Vector argument_list|( name|x operator|* name|sxy argument_list|, name|y operator|* name|sxy argument_list|) return|; block|} annotation|@ name|Override specifier|public name|String name|toString parameter_list|() block|{ return|return literal|"(" operator|+ name|x operator|+ literal|", " operator|+ name|y operator|+ literal|")" return|; block|} block|} end_class end_unit
19.608
810
0.747858
4f5b871b4c84d27e4656c54d1919d5067af02a30
5,831
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.integration; import org.testng.annotations.BeforeTest; import java.io.IOException; /** * Integration test class. */ public class ForEachCaseIT extends WorkflowIntegrationTestBase { public ForEachCaseIT() throws Exception { // setUpEnvironment(); } @BeforeTest public void setUp() throws Exception { // setupDescriptors(); } // @Test(groups = {"forEachGroup"}) // public void testForEachUsecases() throws Exception { // executeExperiment("src/test/resources/ForEachBasicWorkflow.xwf", Arrays.asList("10", "20"), Arrays.asList("10 20")); // executeExperiment("src/test/resources/ForEachBasicWorkflow.xwf", Arrays.asList("10", "20,30"), Arrays.asList("10 20", "10 30")); // executeExperiment("src/test/resources/ForEachBasicWorkflow.xwf", Arrays.asList("10,20", "30,40"), Arrays.asList("10 30", "20 40")); // // executeExperiment("src/test/resources/ForEachEchoWorkflow.xwf", Arrays.asList("10", "20"), Arrays.asList("10,20")); // executeExperiment("src/test/resources/ForEachEchoWorkflow.xwf", Arrays.asList("10", "20,30"), Arrays.asList("10,20", "10,30")); // executeExperiment("src/test/resources/ForEachEchoWorkflow.xwf", Arrays.asList("10,20", "30,40"), Arrays.asList("10,30", "20,40")); // } // private void setupDescriptors() throws AiravataAPIInvocationException, // DescriptorAlreadyExistsException, IOException { // DescriptorBuilder descriptorBuilder = airavataAPI.getDescriptorBuilder(); // HostDescription hostDescription = descriptorBuilder.buildHostDescription(HostDescriptionType.type, "localhost2", // "127.0.0.1"); // // log("Adding host description ...."); // addHostDescriptor(hostDescription); // Assert.assertTrue(airavataAPI.getApplicationManager().isHostDescriptorExists(hostDescription.getType().getHostName())); // // List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); // inputParameters.add(descriptorBuilder.buildInputParameterType("data1", "data1", DataType.STRING)); // inputParameters.add(descriptorBuilder.buildInputParameterType("data2", "data2", DataType.STRING)); // // List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); // outputParameters.add(descriptorBuilder.buildOutputParameterType("out", "out", DataType.STD_OUT)); // // ServiceDescription serviceDescription = descriptorBuilder.buildServiceDescription("comma_app", "comma_app", // inputParameters, outputParameters); // // ServiceDescription serviceDescription2 = descriptorBuilder.buildServiceDescription("echo_app", "echo_app", // inputParameters, outputParameters); // // log("Adding service description ..."); // addServiceDescriptor(serviceDescription, "comma_app"); // Assert.assertTrue(airavataAPI.getApplicationManager().isServiceDescriptorExists( // serviceDescription.getType().getName())); // // addServiceDescriptor(serviceDescription2, "echo_app"); // Assert.assertTrue(airavataAPI.getApplicationManager().isServiceDescriptorExists( // serviceDescription2.getType().getName())); // // // Deployment descriptor // File executable; // if (OsUtils.isWindows()) { // executable = getFile("src/test/resources/comma_data.bat"); // } else { // executable = getFile("src/test/resources/comma_data.sh"); // Runtime.getRuntime().exec("chmod +x " + executable.getAbsolutePath()); // } // // ApplicationDescription applicationDeploymentDescription = descriptorBuilder // .buildApplicationDeploymentDescription("comma_app_localhost", executable.getAbsolutePath(), OsUtils.getTempFolderPath()); // ApplicationDescription applicationDeploymentDescription2 = descriptorBuilder // .buildApplicationDeploymentDescription("echo_app_localhost", OsUtils.getEchoExecutable(), OsUtils.getTempFolderPath()); // // log("Adding deployment description ..."); // addApplicationDescriptor(applicationDeploymentDescription, serviceDescription, hostDescription, "comma_app_localhost"); // // Assert.assertTrue(airavataAPI.getApplicationManager().isApplicationDescriptorExists( // serviceDescription.getType().getName(), hostDescription.getType().getHostName(), // applicationDeploymentDescription.getType().getApplicationName().getStringValue())); // // addApplicationDescriptor(applicationDeploymentDescription2, serviceDescription2, hostDescription, "echo_app_localhost"); // Assert.assertTrue(airavataAPI.getApplicationManager().isApplicationDescriptorExists( // serviceDescription2.getType().getName(), hostDescription.getType().getHostName(), // applicationDeploymentDescription2.getType().getApplicationName().getStringValue())); // } }
52.0625
141
0.70794
7678d9ab92cfab96746a894910bf5ec1ebb0bab4
2,855
package nl.unimaas.ids.autorml.mappers; import java.io.PrintStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.lang3.StringUtils; import nl.unimaas.ids.util.PrefixPrintWriter; public abstract class AbstractMapper implements MapperInterface { Connection connection; final static String ROW_NUM_NAME = "autor2rml_rownum"; private String baseUri; private String graphUri; public AbstractMapper(String jdbcUrl, String userName, String passWord, String baseUri, String graphUri) { this.baseUri = StringUtils.appendIfMissing(baseUri, "/"); this.graphUri = graphUri; } @Override public void close() throws SQLException { if(connection != null && !connection.isClosed()) connection.close(); } void generateMappingForTable(String table, String[] columns, PrintStream ps, String label) throws Exception { generateMappingForTable(table, columns, ps, label, null); } @SuppressWarnings("resource") void generateMappingForTable(String table, String[] columns, PrintStream ps, String label, String prefix) throws Exception { PrintWriter upper = new PrefixPrintWriter(ps, prefix); PrintWriter lower = new PrefixPrintWriter(ps, prefix); upper.println("<#" + label + ">"); upper.println("rr:logicalTable [ rr:sqlQuery \"\"\""); lower.println("rr:subjectMap ["); lower.println(" rr:termType rr:IRI;"); lower.println(" rr:template \"" + this.baseUri + cleanTableNameForUri(table) + "/{" + ROW_NUM_NAME + "}\";"); lower.println(" rr:class <" + this.baseUri + cleanTableNameForUri(table) + ">;"); lower.println(" rr:graph <" + this.graphUri + ">;"); lower.println("];"); // System.out.println("before col loop"); upper.println(" select " + getSqlForRowNum()); for (int i = 0; i < columns.length; i++) { String column = columns[i]; // System.out.println("in loop"); upper.println(" , " + getSqlForColumn(column, i)); lower.println("rr:predicateObjectMap ["); lower.println(" rr:predicate <" + this.baseUri + "model/" + getColumnName(column) + ">;"); lower.println(" rr:objectMap [ rr:column \"" + getColumnName(column) + "\" ];"); lower.println(" rr:graph <" + this.graphUri + ">;"); lower.println("];"); } upper.println(" from " + table + ";"); upper.println("\"\"\"];"); // System.out.println("end loop"); lower.println("."); lower.println("\n"); upper.flush(); lower.flush(); } void generateNamespaces(PrintStream ps) { ps.println("@prefix rr: <http://www.w3.org/ns/r2rml#>."); } private String cleanTableNameForUri(String tableName) { if(!tableName.contains("`")) return tableName; int i1 = tableName.indexOf("`"); int i2 = tableName.indexOf("`", i1+1); tableName = tableName.substring(i1 + 1, i2); return StringUtils.removeStart(tableName, "/"); } }
32.078652
125
0.680911
4d6ff903bf08fb0eb02e06e8298251e6223e1e6a
18,379
/* * Licensed to Leidos, Inc. under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information regarding copyright ownership. * Leidos, Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.cloudkeeper.s3.io; import com.amazonaws.services.s3.model.CompleteMultipartUploadResult; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.UploadPartResult; import net.florianschoppmann.java.futures.Futures; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; /** * Buffered output stream for writing to S3. * * <p>This class implements an output stream that satisfies the requirements of * {@link S3Connection#newBufferedOutputStream(String, String)}. Data transfer to S3 occurs in parts of * size {@link S3Connection#getBufferSize()} (using Amazon S3 multi-part uploads), and the transfer of * each part is wrapped in a lightweight task that will be executed by * {@link S3Connection#getExecutorService()}. Up to * {@link S3Connection#getParallelConnectionsPerRequest()} part uploads may be active at the same time * (per stream). Accordingly, the maximum size of all buffers used for the returned stream may be up to the product of * {@link S3Connection#getParallelConnectionsPerRequest()} and * {@link S3Connection#getBufferSize()}. However, this class will use a * {@link QueuingOutputStream} for buffering the first {@link S3Connection#getBufferSize()} * bytes. Hence, this class is memory-efficient also for writing many small files to S3. * * <p>An output stream of this class will split the upload into multiple parts (using Amazon S3 multi-part uploads). It * is therefore crucial that this stream will be closed, that is, the {@link #close()} will be called eventually. * Otherwise, Amazon may keep an incomplete S3 multi-part upload, which will incur cost. Whenever possible, instances of * this class should therefore only be created in try-with-resources statements. Moreover, as a precaution, it is * recommended that users of this class periodically check for incomplete multi-part uploads and abort stale uploads. * * <p>Instances of this class maintain {@link S3Connection#getParallelConnectionsPerRequest()} buffers of size * {@link S3Connection#getBufferSize()} each. There is a (blocking) queue of available buffers, the first of which is * the <em>current</em> buffer. Any write operation is directed to the current buffer if there is one. Otherwise, the * write will block until a buffer becomes available again. When the current buffer is full, a new S3 part upload is * started as a parallel task, and the current buffer will become unavailable; that is, it is removed from the queue, * and it is no longer the current buffer. Once an upload completes, the associated buffer is returned to the queue. * * <p>Streams of this class are not intended to be written to from different threads (which holds for any * {@link OutputStream}, unless otherwise noted). However, instances of this class will submit futures to an * executor that is expected to complete these futures in different threads. This is safe because all futures submitted * from this class will only access volatile, final, or static fields. * * @see com.amazonaws.services.s3.AmazonS3#initiateMultipartUpload(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest) * * @author Florian Schoppmann */ final class S3BufferedOutputStream extends OutputStream { /** * Initial buffer size. This is the minimum size that will be allocated when the first byte is written. This * constant will be passed to {@link QueuingOutputStream#QueuingOutputStream(int, int)} as first * argument. */ private static final int INITIAL_BUFFER_SIZE = 256; private final Logger log = LoggerFactory.getLogger(getClass()); private final S3Connection s3Connection; private final Executor executorService; private final String bucketName; private final String key; private final int numBuffers; private final int bufferSize; private volatile boolean failure; @Nullable private QueuingOutputStream currentBuffer; private int posInBuffer = 0; private boolean closed = false; private int nextPartNumber = 1; /** * The number of byte arrays that have been explicitly created. This only happens in {@link #waitForBuffer()}. */ private int numByteArraysCreated = 0; /** * Blocking queue containing buffer to write to. If no buffer is currently available and a write method is called, * the operation will block until a buffer becomes available again. Note that {@link BlockingQueue} implementations * are always thread-safe. */ private final BlockingQueue<QueuingOutputStream> availableBuffers; /** * Set of part-upload futures. Note that this field is initially null, and will be initialized together with * {@link #uploadIdFuture} in {@link #getUploadIdFuture()}; */ @Nullable private List<CompletableFuture<PartETag>> partETagFutures; /** * This field is not written to from callback methods (but instead only when {@link OutputStream} methods * are on the call stack), hence we do not have to worry about the memory model. No need to make this field * volatile. */ @Nullable private CompletableFuture<String> uploadIdFuture; /** * This field exists for convenience. It is volatile because it is written to from a callback registered with * {@link #uploadIdFuture}. */ @Nullable private volatile String uploadId; /** * Constructor. * * @param s3Connection high-level connection to Amazon S3 * @param bucketName name of the bucket that will contain the new object * @param key key of the object to create and write to */ S3BufferedOutputStream(S3Connection s3Connection, String bucketName, String key) { Objects.requireNonNull(s3Connection); Objects.requireNonNull(bucketName); Objects.requireNonNull(key); this.s3Connection = s3Connection; executorService = s3Connection.getExecutorService(); this.bucketName = bucketName; this.key = key; bufferSize = s3Connection.getBufferSize(); numBuffers = s3Connection.getParallelConnectionsPerRequest(); availableBuffers = new ArrayBlockingQueue<>(numBuffers); currentBuffer = new QueuingOutputStream(INITIAL_BUFFER_SIZE, bufferSize); } /** * Enumeration of the conditions that will trigger uploading a new part, when * {@link #uploadPartToS3(WhenToUpload)} is called. */ enum WhenToUpload { /** * Indicates that a new part should only be uploaded if the buffer is full. */ WHEN_BUFFER_FULL, /** * Indicates that a new part should be uploaded if the buffer contains enough data to start a new part (that is, * if there are more than {@link S3Connection#MINIMUM_PART_SIZE} bytes in the buffer). */ WHEN_ENOUGH_FOR_NEW_PART, /** * Indicates that a new part should always be uploaded, because this part will be the last, and the stream will * be closed afterward. */ ALWAYS } private CompletableFuture<String> getUploadIdFuture() { if (uploadIdFuture == null) { uploadIdFuture = s3Connection.initiateMultipartUpload(bucketName, key) .thenApplyAsync(InitiateMultipartUploadResult::getUploadId, executorService); partETagFutures = new ArrayList<>(); } return uploadIdFuture; } /** * Uploads the current buffer to Amazon S3. * * <p>Depending on {@code whenToUpload}, this method will do nothing if the buffer contains only little data. In * particular,since S3 has minimum part sizes, this method will usually not do anything if less than * {@link S3Connection#MINIMUM_PART_SIZE} bytes are available. Only if the current content of the * buffer is guaranteed to be the last part, data would be uploaded. * * @param whenToUpload indicates under what conditions a new part should be uploaded */ private void uploadPartToS3(WhenToUpload whenToUpload) { // Necessary precondition assert currentBuffer != null; boolean uploadNow = whenToUpload == WhenToUpload.ALWAYS || (whenToUpload == WhenToUpload.WHEN_ENOUGH_FOR_NEW_PART && posInBuffer >= S3Connection.MINIMUM_PART_SIZE) || posInBuffer == bufferSize; if (!uploadNow) { return; } // We must not close over mutable instance fields, so we need to create local copies. In all callbacks below, // we only access final or volatile fields. final QueuingOutputStream buffer = currentBuffer; final int length = posInBuffer; final int partNumber = nextPartNumber; currentBuffer = null; posInBuffer = 0; ++nextPartNumber; // Sequence of steps: Get upload ID, upload new part, extract identifier from S3 upload result, register // callback for handling failures and returning the buffer. getUploadIdFuture(); assert uploadIdFuture != null && partETagFutures != null; CompletableFuture<PartETag> partETagFuture = uploadIdFuture .thenComposeAsync( newUploadId -> { // UploadId is volatile, so fine to write to. uploadId = newUploadId; return s3Connection.uploadPart(bucketName, key, newUploadId, partNumber, buffer.toInputStream(), length); }, executorService ) .thenApplyAsync(UploadPartResult::getPartETag, executorService) .whenCompleteAsync( (partETag, throwable) -> { if (throwable != null) { // failure is volatile, so fine to write to. failure = true; } // Return the buffer to the pool. Fine to do here, as BlockingQueue implementations are thread-safe. byte[][] bufferArrays = buffer.getArrays(); if (bufferArrays.length == 1 && bufferArrays[0].length == bufferSize) { // Reuse the buffer if it was backed by a single array of the correct size. availableBuffers.add(new QueuingOutputStream(bufferArrays[0])); } }, executorService ); partETagFutures.add(partETagFuture); } private IOException mapException(Exception exception) { Throwable cause = exception instanceof ExecutionException ? exception.getCause() : exception; if (cause instanceof IOException) { return (IOException) cause; } else { return new IOException(String.format("Writing s3://%s/%s failed.", bucketName, key), cause); } } private void waitForBuffer() throws IOException { if (closed) { throw new IOException("Write attempt after stream was closed."); } else if (failure) { // Note that exception != null implies that a future was completed with an exception, which means that // close() picks up the exception and throws it. close(); assert false : "Unreachable code"; } else if (currentBuffer == null) { if (availableBuffers.isEmpty() && numByteArraysCreated < numBuffers) { // In theory, a QueuingOutputStream could become available again right here. But it clearly does not // hurt to create a new buffer here. availableBuffers.add(new QueuingOutputStream(new byte[bufferSize])); ++numByteArraysCreated; } boolean interrupted = false; while (true) { try { // This cannot block indefinitely because eventually all buffers will be returned to // availableBuffers (either when a part upload completes or fails). See uploadPartToS3(). // Initially, availableBuffers is not empty. currentBuffer = availableBuffers.take(); if (interrupted) { Thread.currentThread().interrupt(); } break; } catch (InterruptedException ignored) { interrupted = true; } } } // Post-condition of this method upon successful completion. assert currentBuffer != null && posInBuffer < bufferSize; } @Override public void write(int singleByte) throws IOException { // See method for post-condition. waitForBuffer(); assert currentBuffer != null; posInBuffer++; currentBuffer.write(singleByte); uploadPartToS3(WhenToUpload.WHEN_BUFFER_FULL); } @Override public void write(byte[] newBytes, int offset, int length) throws IOException { Objects.requireNonNull(newBytes); if (offset < 0 || offset > newBytes.length || length < 0 || offset + length > newBytes.length || offset + length < 0) { throw new IndexOutOfBoundsException(String.format( "array length = %d, offset = %d, length = %d", newBytes.length, offset, length )); } else if (length == 0) { return; } int posInNewBytes = offset; int remaining = length; while (remaining > 0) { // See method for post-condition. waitForBuffer(); assert currentBuffer != null; int blockSize = Math.min(remaining, bufferSize - posInBuffer); currentBuffer.write(newBytes, posInNewBytes, blockSize); remaining -= blockSize; posInNewBytes += blockSize; posInBuffer += blockSize; uploadPartToS3(WhenToUpload.WHEN_BUFFER_FULL); } } @Override public void flush() throws IOException { uploadPartToS3(WhenToUpload.WHEN_ENOUGH_FOR_NEW_PART); } /** * Uploads the last part of the multi-part upload and then completes the request. * * <p>This method must only be called from {@link #close()} if a multi-part upload has been initiated previously * because a single buffer could not hold all the bytes written to this stream. */ private CompletableFuture<?> finishMultiPartUploadFuture() { assert uploadIdFuture != null; // There may be bytes in the buffer that have not been submitted to S3 yet. This may update partETagFutures. uploadPartToS3(WhenToUpload.ALWAYS); // Now partETagFutures contains all partETagFutures CompletableFuture<CompleteMultipartUploadResult> completionFuture = Futures .shortCircuitCollect(partETagFutures) .thenComposeAsync( partETags -> s3Connection.completeMultipartUpload(bucketName, key, uploadId, partETags), executorService ); // If anything goes wrong, it is crucial that we abort the multi-part upload. If the abort request also fails, // all we can do is write a log message. Exceptions occurring during the abort request will not otherwise be // propagated. completionFuture.whenCompleteAsync( (ignoredUploadResult, uploadThrowable) -> { if (uploadThrowable != null) { CompletableFuture<Void> abortFuture = s3Connection.abortMultipartUpload(bucketName, key, uploadId); abortFuture.whenCompleteAsync( (ignoredVoid, abortThrowable) -> { if (abortThrowable != null) { log.error(String.format( "Failed to abort multi-part upload for key '%s'. MANUAL CLEAN-UP REQUIRED!", key ), abortThrowable); } }, executorService ); } }, executorService ); return completionFuture; } @Override public void close() throws IOException { if (!closed) { closed = true; // If uploadIfFuture == null, then the number of written bytes is less than the buffer size. In this case, // no multi-part upload has been started. CompletableFuture<?> completionFuture = uploadIdFuture == null ? s3Connection.putObject(bucketName, key, currentBuffer.toInputStream(), posInBuffer) : finishMultiPartUploadFuture(); try { completionFuture.get(); } catch (ExecutionException | InterruptedException exception) { throw mapException(exception); } finally { // Release references and let garbage collector do its work partETagFutures = null; availableBuffers.clear(); } } } }
44.501211
130
0.654062
ec7ec382e1b1813bec19d881c3030d27add261e4
718
package org.basex.util.ft; import org.basex.util.options.*; /** * Full-text options. * * @author BaseX Team 2005-13, BSD License * @author Christian Gruen */ public final class FTOptions extends FTIndexOptions { /** Option: case. */ public static final EnumOption<FTCase> CASE = new EnumOption<FTCase>("case", FTCase.class); /** Option: case. */ public static final EnumOption<FTDiacritics> DIACRITICS = new EnumOption<FTDiacritics>("diacritics", FTDiacritics.INSENSITIVE); /** Option: stemming. */ public static final BooleanOption STEMMING = new BooleanOption("stemming", false); /** Option: language. */ public static final StringOption LANGUAGE = new StringOption("language", "en"); }
32.636364
93
0.714485
b2d100a28c438326cede3b966a8a661dd829e75c
698
package de.pxav.kelp.core.configuration.type; import de.pxav.kelp.core.configuration.ConfigurationAttribute; import de.pxav.kelp.core.configuration.KelpConfiguration; import java.util.Collection; /** * A class description goes here. * * @author pxav */ public class YamlConfigurationType implements ConfigurationType { @Override public String fileExtension() { return null; } @Override public void saveAttributes(Collection<ConfigurationAttribute> attributes, Class<? extends KelpConfiguration> configurationClass) { } @Override public Collection<ConfigurationAttribute> loadAttributes(Class<? extends KelpConfiguration> configurationClass) { return null; } }
22.516129
132
0.776504
15bf65ac88f8674d2f029be35be3d9bd7fb247fe
5,079
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.ccsu.solutions; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author cw1491 */ @WebServlet(name = "ReviewPersistingSolnServlet", urlPatterns = {"/ReviewPersistingSolnServlet", "*.reviewSoln"}) public class ReviewPersistingSolnServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ReviewPersistingServlet</title>"); out.println("</head>"); out.println("<body>"); // Get number of names across sessions (remember it may not have already been set Integer numNames = (Integer) getServletContext().getAttribute("numNamesSoln"); if (numNames == null) { numNames = new Integer(0); } // Get name from request String name = request.getParameter("fullname"); // if name is present it means it is not already on // the session so add it to the session if (name != null) { HttpSession session = request.getSession(); session.setAttribute("nameSoln", name); // update number of names entered across all sessions (context) // if it doesn't already exist in the session you will need to create // the attribute ServletContext context = getServletContext(); numNames = (Integer) context.getAttribute("numNamesSoln"); if (numNames == null) { numNames = new Integer(0); } numNames = new Integer(numNames.intValue() + 1); context.setAttribute("numNamesSoln", numNames); } else { name = (String) request.getSession().getAttribute("nameSoln"); } boolean nameInSession = request.getSession().getAttribute("nameSoln") != null; // if there is a name already in the session don't do this part if (!nameInSession) { out.println("<form action=\"ReviewPersistingSolnServlet\" method=\"GET\">"); out.println("<fieldset>"); out.println("<legend>Persisting Servlet</legend>"); out.println("name: <input type=\"text\" name=\"fullname\"/><br/>"); out.println("<input type=\"submit\" value=\"Submit\" />"); out.println("</fieldset>"); out.println("</form>"); } else { out.println("Name=" + name + "<br/>"); } // Print out the number of names entered across all sessions out.println("Number of names: " + numNames); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
38.477273
123
0.610159
92c293672aadfbe455b06aa89a37d503f6e69170
1,471
package club.lemos.common.utils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.lang.Nullable; import java.util.HashSet; import java.util.Set; /** * 对象工具类 */ public class ObjectUtil extends org.springframework.util.ObjectUtils { /** * 判断元素不为空 * * @param obj object * @return boolean */ public static boolean isNotEmpty(@Nullable Object obj) { return !ObjectUtil.isEmpty(obj); } /** * 获取非空的属性名称 * @param source Object * @return String[] */ public static String[] getNullPropertyNames(Object source) { final BeanWrapper src = new BeanWrapperImpl(source); java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set<String> emptyNames = new HashSet<>(); for (java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null) { emptyNames.add(pd.getName()); } else if (srcValue instanceof String) { if (StringUtil.isBlank((String) srcValue)) { emptyNames.add(pd.getName()); } } } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } public static boolean isArray(Object obj) { return obj!=null && obj.getClass().isArray(); } }
27.240741
75
0.611829
0989464904879eceaba984fed04ef8b8d64abfd3
1,090
package {{java_package}}.app.musart; import java.rmi.RemoteException; import java.util.Vector; import psdi.mbo.Mbo; import psdi.mbo.MboRemote; import psdi.mbo.MboSet; import psdi.mbo.MboSetRemote; import psdi.util.MXApplicationException; import psdi.util.MXException; public class {{addon_prefix}}Artist extends Mbo implements {{addon_prefix}}ArtistRemote { public {{addon_prefix}}Artist(MboSet ms) throws RemoteException { super(ms); } @Override public void canDelete() throws MXException, RemoteException { super.canDelete(); if (!this.getMboSet("{{addon_prefix}}MUSIC").isEmpty()){ Object[] params = new Object[]{this.getString("name")}; throw new MXApplicationException("{{addon_prefix}}artist", "CannotDeleteArtistWithMusic", params); } } public void associateSelectedMusic(MboSetRemote musicSet) throws MXException, RemoteException{ Vector selectedMusics = musicSet.getSelection(); for (Object music: selectedMusics){ ((MboRemote)music).setValue("artistnum", this.getString("artistnum"), NOACCESSCHECK); } } }
30.277778
102
0.734862
9f697759b7dfba50d3a1b4a4e949552a43808fd7
11,200
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams.processor.internals.metrics; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.common.metrics.Sensor.RecordingLevel; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.Map; import static org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.TASK_LEVEL_GROUP; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class TaskMetricsTest { private final static String THREAD_ID = "test-thread"; private final static String TASK_ID = "test-task"; private final StreamsMetricsImpl streamsMetrics = mock(StreamsMetricsImpl.class); private final Sensor expectedSensor = mock(Sensor.class); private final Map<String, String> tagMap = Collections.singletonMap("hello", "world"); @Test public void shouldGetActiveProcessRatioSensor() { final String operation = "active-process-ratio"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.INFO)) .thenReturn(expectedSensor); final String ratioDescription = "The fraction of time the thread spent " + "on processing this task among all assigned active tasks"; when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addValueMetricToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, ratioDescription ); final Sensor sensor = TaskMetrics.activeProcessRatioSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetActiveBufferCountSensor() { final String operation = "active-buffer-count"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)) .thenReturn(expectedSensor); final String countDescription = "The count of buffered records that are polled " + "from consumer and not yet processed for this active task"; when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addValueMetricToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, countDescription ); final Sensor sensor = TaskMetrics.activeBufferedRecordsSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetTotalBytesSensor() { final String operation = "input-buffer-bytes-total"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.INFO)) .thenReturn(expectedSensor); final String totalBytesDescription = "The total number of bytes accumulated in this task's input buffer"; when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addValueMetricToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, totalBytesDescription ); final Sensor sensor = TaskMetrics.totalInputBufferBytesSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetTotalCacheSizeInBytesSensor() { final String operation = "cache-size-bytes-total"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.INFO)) .thenReturn(expectedSensor); final String totalBytesDescription = "The total size in bytes of this task's cache."; when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addValueMetricToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, totalBytesDescription ); final Sensor sensor = TaskMetrics.totalCacheSizeBytesSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetProcessLatencySensor() { final String operation = "process-latency"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)) .thenReturn(expectedSensor); final String avgLatencyDescription = "The average latency of calls to process"; final String maxLatencyDescription = "The maximum latency of calls to process"; when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addAvgAndMaxToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, avgLatencyDescription, maxLatencyDescription ); final Sensor sensor = TaskMetrics.processLatencySensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetPunctuateSensor() { final String operation = "punctuate"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)) .thenReturn(expectedSensor); final String operationLatency = operation + StreamsMetricsImpl.LATENCY_SUFFIX; final String totalDescription = "The total number of calls to punctuate"; final String rateDescription = "The average number of calls to punctuate per second"; final String avgLatencyDescription = "The average latency of calls to punctuate"; final String maxLatencyDescription = "The maximum latency of calls to punctuate"; when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addInvocationRateAndCountToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, rateDescription, totalDescription ); StreamsMetricsImpl.addAvgAndMaxToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operationLatency, avgLatencyDescription, maxLatencyDescription ); final Sensor sensor = TaskMetrics.punctuateSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetCommitSensor() { final String operation = "commit"; final String totalDescription = "The total number of calls to commit"; final String rateDescription = "The average number of calls to commit per second"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)).thenReturn(expectedSensor); when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addInvocationRateAndCountToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, rateDescription, totalDescription ); final Sensor sensor = TaskMetrics.commitSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetEnforcedProcessingSensor() { final String operation = "enforced-processing"; final String totalDescription = "The total number of occurrences of enforced-processing operations"; final String rateDescription = "The average number of occurrences of enforced-processing operations per second"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)).thenReturn(expectedSensor); when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addInvocationRateAndCountToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, rateDescription, totalDescription ); final Sensor sensor = TaskMetrics.enforcedProcessingSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetRecordLatenessSensor() { final String operation = "record-lateness"; final String avgDescription = "The observed average lateness of records in milliseconds, measured by comparing the record timestamp with " + "the current stream time"; final String maxDescription = "The observed maximum lateness of records in milliseconds, measured by comparing the record timestamp with " + "the current stream time"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.DEBUG)).thenReturn(expectedSensor); when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addAvgAndMaxToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, avgDescription, maxDescription ); final Sensor sensor = TaskMetrics.recordLatenessSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } @Test public void shouldGetDroppedRecordsSensor() { final String operation = "dropped-records"; final String totalDescription = "The total number of dropped records"; final String rateDescription = "The average number of dropped records per second"; when(streamsMetrics.taskLevelSensor(THREAD_ID, TASK_ID, operation, RecordingLevel.INFO)).thenReturn(expectedSensor); when(streamsMetrics.taskLevelTagMap(THREAD_ID, TASK_ID)).thenReturn(tagMap); StreamsMetricsImpl.addInvocationRateAndCountToSensor( expectedSensor, TASK_LEVEL_GROUP, tagMap, operation, rateDescription, totalDescription ); final Sensor sensor = TaskMetrics.droppedRecordsSensor(THREAD_ID, TASK_ID, streamsMetrics); assertThat(sensor, is(expectedSensor)); } }
41.481481
125
0.688393
6e95333d649de77bf9238d98095871ec49b42891
377
package javax.annotation.sql; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @since Common Annotations 1.1 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DataSourceDefinitions { DataSourceDefinition[] value(); }
22.176471
44
0.793103
1ade44429ab43e1180003422407934e7617a0117
2,912
package com.example.wearablesensorbase.data; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import com.example.wearablesensorbase.R; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.ShareActionProvider; import android.widget.Toast; public class LogViewActivity extends Activity { public static String DEVICE_NAME = "com.example.wearablesensorbase.ble_device_name", FILE_NAME = "com.example.wearablesensorbase.file_name"; private String fileName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_view); String fileName = getIntent().getStringExtra(FILE_NAME); if (fileName != null) { this.fileName = fileName; } else { String deviceName = getIntent().getStringExtra(DEVICE_NAME); this.fileName = BufferedMeasurementSaver.getFileName(deviceName); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.log_view, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_refresh: load(); return true; case R.id.action_share: share(); return true; case R.id.action_delete: delete(); return true; } return super.onOptionsItemSelected(item); } private void load() { EditText text = (EditText) findViewById(R.id.log_text); text.setText(getTextInFile(fileName)); } private void delete() { } private void share() { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(getRealFile(fileName))); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, fileName)); } private File getRealFile(String fileName) { return new File(getExternalFilesDir(null), fileName); } private String getTextInFile(String fileName) { StringBuilder builder = new StringBuilder(); try { BufferedReader in = new BufferedReader(new FileReader(getRealFile(fileName))); String line = null; while ((line = in.readLine()) != null) { builder.append(line); builder.append('\n'); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return builder.toString(); } }
25.54386
81
0.736951
1080272d33dbf2b5b00908182d6e6eaa4f8594d2
3,061
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.uf.viz.grib.wizard.save; import java.io.IOException; import javax.xml.bind.JAXB; import com.raytheon.uf.common.localization.ILocalizationFile; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; import com.raytheon.uf.common.localization.SaveableOutputStream; import com.raytheon.uf.common.localization.exception.LocalizationPermissionDeniedException; import com.raytheon.uf.common.menus.vb.VbSourceList; /** * * Implementation of {@link GribWizardSave} which stores the data to * localization. * * <pre> * * SOFTWARE HISTORY * * Date Ticket# Engineer Description * ------------- -------- --------- ----------------- * Apr 26, 2016 5572 bsteffen Initial creation * * </pre> * * @author bsteffen */ public class LocalizationGribWizardSave extends GribWizardSave { private final IPathManager pathManager; private final LocalizationContext context; public LocalizationGribWizardSave(IPathManager pathManager, LocalizationContext context) { this.pathManager = pathManager; this.context = context; } @Override protected void save(String location, Object object) throws Exception { LocalizationContext context = this.context; if (object instanceof VbSourceList) { context = pathManager.getContext(LocalizationType.CAVE_STATIC, this.context.getLocalizationLevel()); } ILocalizationFile file = pathManager.getLocalizationFile(context, location); if (file.exists()) { throw new IOException(location + " already exists."); } try (SaveableOutputStream os = file.openOutputStream()) { JAXB.marshal(object, os); os.save(); } catch (IOException e) { Throwable root = e; while (root != null) { if (root instanceof LocalizationPermissionDeniedException) { throw new IOException(root.getLocalizedMessage(), root); } root = root.getCause(); } throw e; } } }
33.637363
91
0.654035
a0a90eac8bae29e8ed40f018a91e7e73e561ef34
2,151
package ru.shemplo.ml.lab2; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; public class RunF1 { public static void main (String ... args) throws Exception { try ( Reader r = new InputStreamReader (System.in); BufferedReader br = new BufferedReader (r); PrintWriter pw = new PrintWriter (System.out); ) { solve (br, pw); } } public static void solve (BufferedReader br, PrintWriter pw) throws IOException { String line = br.readLine ().trim (); int classes = Integer.parseInt (line); double [][] matrix = new double [classes][classes]; double [] columns = new double [classes], lines = new double [classes]; double total = 0; for (int i = 0; i < classes; i++) { StringTokenizer st = new StringTokenizer (br.readLine ().trim ()); for (int j = 0; j < classes; j++) { matrix [i][j] = Double.parseDouble (st.nextToken ()); columns [j] += matrix [i][j]; lines [i] += matrix [i][j]; total += matrix [i][j]; } } double sumP = 0, sumR = 0, score = 0; for (int i = 0; i < classes; i++) { double tp = matrix [i][i]; double precision = (tp == 0) ? 0 : (tp / columns [i]), recall = (tp == 0) ? 0 : (tp / lines [i]); score += f1 (precision, recall) * lines [i]; sumP += precision * lines [i]; sumR += recall * lines [i]; } System.out.println (f1 (sumP / total, sumR / total)); System.out.println (score / total); } public static double f1 (double p, double r) { if (Math.abs (p + r) >= 1e-4) { return 2 * (p * r) / (p + r); } return 0.0d; } }
32.104478
86
0.475128
2604ed5f663a9f03fc6eaa8c2fb5e0c3f84ba485
306
package com.bassoon.stockextractor.model; import java.util.List; public class StockListWrapper { private List<Stock> stockList; public List<Stock> getStockList() { return stockList; } public void setStockList(List<Stock> stockList) { this.stockList = stockList; } }
19.125
53
0.686275
2a0c3cbf1097ad64a7a4c97e74aaf273839eca04
729
// Copyright (c) 2003-2013, Jodd Team (jodd.org). All Rights Reserved. package jodd.typeconverter.impl; import jodd.upload.FileUpload; import jodd.typeconverter.TypeConversionException; import jodd.typeconverter.TypeConverter; /** * Converts given object to {@link FileUpload}. * Conversion rules: * <ul> * <li><code>null</code> value is returned as <code>null</code></li> * <li>object of destination type is simply casted</li> * </ul> */ public class FileUploadConverter implements TypeConverter<FileUpload> { public FileUpload convert(Object value) { if (value == null) { return null; } if (value instanceof FileUpload) { return (FileUpload) value; } throw new TypeConversionException(value); } }
24.3
71
0.72428
a1299ba95a037adfa984e88e3f99e14fb577c6b6
1,730
/* * MIT License * * Copyright (c) 2020 Zhixiao Yang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.sakigamiyang.exercise.graph; import org.junit.Test; public class GraphTest { @Test public void testConnect() { Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node node4 = new Node(4); Node node5 = new Node(5); Graph g = new Graph(); g.addNodes(node1, node2, node3, node4, node5); g.connect(node1, node2); g.connect(node2, node3); g.connect(node3, node1); g.connect(node2, node4); g.connect(node4, node5); System.out.println(g); } }
35.306122
81
0.692486
7a737d0119d7d1da4ff4d9c55dfcc3fe4fdd5f98
2,317
package com.example.yogesh16991.test_proj; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import org.json.JSONObject; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class EventDetailsJSon{ public static final String MyPREFERENCES = "MyPrefs"; SharedPreferences sharedpreferences; List<Map<String,?>> eventsList; public EventDetailsJSon(Context context){ eventsList = new ArrayList<Map<String,?>>(); sharedpreferences = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); } public List<Map<String, ?>> getEventsList() { return eventsList; } public int getSize(){ return eventsList.size(); } public HashMap getItem(int i){ if (i >=0 && i < eventsList.size()){ return (HashMap) eventsList.get(i); } else return null; } public void addEvent(String name,String desc,String marker,String category,String sdate,String edate){ eventsList.add(createEvent(name,desc,marker,category,sdate,edate)); } private HashMap<String, String> createEvent(String eventname,String eventdesc,String markertitle,String category,String sdate, String edate) { int size; HashMap<String, String> event = new HashMap<>(); event.put("EventName",eventname); event.put("EventDesc",eventdesc); event.put("MarkerTitle", markertitle); event.put("Category", category); event.put("Sdate",sdate); event.put("Edate",edate); SharedPreferences.Editor editor= sharedpreferences.edit(); size = sharedpreferences.getInt("size",0); saveMap(event, "event"+size); size++; editor.putInt("size",size).apply(); editor.putBoolean("Check",true); return event; } private void saveMap(HashMap<String,String> inputMap, String mapStr){ if (sharedpreferences!= null){ JSONObject jsonObject = new JSONObject(inputMap); String jsonString = jsonObject.toString(); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(mapStr, jsonString); editor.apply(); } } }
32.180556
146
0.666379
ad2c483bac7f74e59b295cc42192bf8ca813989b
269
package solid.ocp.conformance; import java.awt.Graphics; import java.util.List; public class Painter { private List<Drawable> drawables; public void paintComponent(Graphics g) { for(Drawable drawable : drawables) { drawable.draw(g); } } }
16.8125
42
0.687732
7e20fe61400c24da23cf470438a5efae47f8006a
3,570
package br.com.smallbi.rest; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import br.com.smallbi.business.PessoaBusiness; import br.com.smallbi.entity.Cliente; import br.com.smallbi.entity.Funcao; import br.com.smallbi.entity.Pessoa; @Path("/pessoa") public class PessoaWebService { PessoaBusiness pessoaBusiness = new PessoaBusiness(); Gson gson = new Gson(); Type type = new TypeToken<Pessoa>() {}.getType(); @GET @Path("/listar") @Produces(MediaType.APPLICATION_JSON) public String getPessoas(){ List<Pessoa> pessoas = pessoaBusiness.list(); List<Hashtable<String, Object>> hashPessoas = new ArrayList<>(); for(Pessoa p : pessoas){ hashPessoas.add(getHashFromObject(p)); } return gson.toJson(hashPessoas); } @POST @Path("/adicionar") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String addPessoa(String json) throws JSONException{ Pessoa pessoa = getObjectFromHash(json); return gson.toJson(pessoaBusiness.create(pessoa)); } @POST @Path("/alterar") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String setPessoa(String json) throws JSONException{ Pessoa pessoa = getObjectFromHash(json); return gson.toJson(pessoaBusiness.update(pessoa)); } @GET @Path("/deletar/{idPessoa}") //@Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String delPessoa(@PathParam("idPessoa") String idPessoa) throws JSONException{ /*JSONObject jsonObject = new JSONObject(json); Pessoa pessoa = new Pessoa(); pessoa.setIdPessoa(jsonObject.getInt("idPessoa")); return gson.toJson(pessoaBusiness.delete(pessoa.getIdPessoa()));*/ return gson.toJson(pessoaBusiness.delete(Integer.parseInt(idPessoa))); } @GET @Path("/getById/{idPessoa}") @Produces(MediaType.APPLICATION_JSON) public String getById(@PathParam("idPessoa") String idPessoa){ Pessoa pessoa = pessoaBusiness.getObjById(Integer.parseInt(idPessoa)); if(pessoa != null){ return gson.toJson(getHashFromObject(pessoa)); } return "Nenhum resultado foi encontrado na tabela Pessoa com o id {"+idPessoa+"}"; } public Hashtable<String, Object> getHashFromObject(Pessoa p){ Hashtable<String, Object> hash = new Hashtable<>(); hash.put("idPessoa", p.getIdPessoa()); hash.put("nome", p.getNome()); hash.put("cpf", p.getCpf()); hash.put("rg", p.getRg()); hash.put("cliente", p.getCliente().getNomeFantasia()); hash.put("funcao", p.getFuncao().getNomeFuncao()); return hash; } public Pessoa getObjectFromHash(String json) throws JSONException{ JSONObject jsonObject = new JSONObject(json); Pessoa p = new Pessoa(); if(!jsonObject.isNull("idPessoa")){ p.setIdPessoa(jsonObject.getInt("idPessoa")); } p.setUsuarioId(jsonObject.getInt("usuarioId")); p.setNome(jsonObject.getString("nome")); p.setCpf(jsonObject.getString("cpf")); p.setRg(jsonObject.getString("rg")); Cliente c = new Cliente(); c.setIdCliente(jsonObject.getInt("idCliente")); p.setCliente(c); Funcao f = new Funcao(); f.setIdFuncao(jsonObject.getInt("idFuncao")); p.setFuncao(f); return p; } }
29.75
86
0.740056
e685d400340a3961141b54fba0ae881e2e7860e7
797
package com.experiments.ai.huddler.utils; import org.apache.avro.Schema; import org.apache.avro.compiler.specific.SpecificCompiler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; public class AvroClassGenerator { Logger logger = LoggerFactory.getLogger(AvroClassGenerator.class); public void generateAvroClasses() throws IOException { File schemaFile = new File("C:\\Users\\bhupendm\\Development\\Fun\\item.schema.avsc"); Schema schema = new Schema.Parser().parse(schemaFile); logger.debug("{}", schema); SpecificCompiler compiler = new SpecificCompiler(schema); compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java")); } }
33.208333
98
0.713927
77cbd050f831d5ddd9d8a1f3599e5b08278c3a6b
246
package com.lingx.core.exception; public class LingxNoLoginException extends Exception { private static final long serialVersionUID = 4024446900049242387L; public LingxNoLoginException(String msg,Throwable e){ super(msg,e); } }
22.363636
68
0.768293
7b8b5cd2ba13cba6a53a2fd94521f07c53252a9e
7,407
/* Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved. 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.huawei.hms.rn.health.kits.account.util; import com.huawei.hms.rn.health.kits.account.HmsHealthAccount; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * {@link HmsHealthAccount} Constant Values. * * @since v.5.0.1 */ public interface AccountConstants { /** * {@link HmsHealthAccount} Activity Request types. */ enum RequestTypes { SIGN_IN(1022); private final int value; RequestTypes(int value) { this.value = value; } public int getValue() { return value; } } /** * {@link HmsHealthAccount} constants. */ enum AccConstants { MODULE_NAME("HmsHealthAccount"), /* Scopes */ HEALTHKIT_HEIGHTWEIGHT_READ("https://www.huawei.com/healthkit/heightweight.read"), HEALTHKIT_HEIGHTWEIGHT_WRITE("https://www.huawei.com/healthkit/heightweight.write"), HEALTHKIT_HEIGHTWEIGHT_BOTH("https://www.huawei.com/healthkit/heightweight.both"), HEALTHKIT_STEP_READ("https://www.huawei.com/healthkit/step.read"), HEALTHKIT_STEP_WRITE("https://www.huawei.com/healthkit/step.write"), HEALTHKIT_STEP_BOTH("https://www.huawei.com/healthkit/step.both"), HEALTHKIT_LOCATION_READ("https://www.huawei.com/healthkit/location.read"), HEALTHKIT_LOCATION_WRITE("https://www.huawei.com/healthkit/location.write"), HEALTHKIT_LOCATION_BOTH("https://www.huawei.com/healthkit/location.both"), HEALTHKIT_HEARTRATE_READ("https://www.huawei.com/healthkit/heartrate.read"), HEALTHKIT_HEARTRATE_WRITE("https://www.huawei.com/healthkit/heartrate.write"), HEALTHKIT_HEARTRATE_BOTH("https://www.huawei.com/healthkit/heartrate.both"), HEALTHKIT_BLOODGLUCOSE_READ("https://www.huawei.com/healthkit/bloodglucose.read"), HEALTHKIT_BLOODGLUCOSE_WRITE("https://www.huawei.com/healthkit/bloodglucose.write"), HEALTHKIT_BLOODGLUCOSE_BOTH("https://www.huawei.com/healthkit/bloodglucose.both"), HEALTHKIT_DISTANCE_READ("https://www.huawei.com/healthkit/distance.read"), HEALTHKIT_DISTANCE_WRITE("https://www.huawei.com/healthkit/distance.write"), HEALTHKIT_DISTANCE_BOTH("https://www.huawei.com/healthkit/distance.both"), HEALTHKIT_SPEED_READ("https://www.huawei.com/healthkit/speed.read"), HEALTHKIT_SPEED_WRITE("https://www.huawei.com/healthkit/speed.write"), HEALTHKIT_SPEED_BOTH("https://www.huawei.com/healthkit/speed.both"), HEALTHKIT_CALORIES_READ("https://www.huawei.com/healthkit/calories.read"), HEALTHKIT_CALORIES_WRITE("https://www.huawei.com/healthkit/calories.write"), HEALTHKIT_CALORIES_BOTH("https://www.huawei.com/healthkit/calories.both"), HEALTHKIT_PULMONARY_READ("https://www.huawei.com/healthkit/pulmonary.read"), HEALTHKIT_PULMONARY_WRITE("https://www.huawei.com/healthkit/pulmonary.write"), HEALTHKIT_PULMONARY_BOTH("https://www.huawei.com/healthkit/pulmonary.both"), HEALTHKIT_STRENGTH_READ("https://www.huawei.com/healthkit/strength.read"), HEALTHKIT_STRENGTH_WRITE("https://www.huawei.com/healthkit/strength.write"), HEALTHKIT_STRENGTH_BOTH("https://www.huawei.com/healthkit/strength.both"), HEALTHKIT_ACTIVITY_READ("https://www.huawei.com/healthkit/activity.read"), HEALTHKIT_ACTIVITY_WRITE("https://www.huawei.com/healthkit/activity.write"), HEALTHKIT_ACTIVITY_BOTH("https://www.huawei.com/healthkit/activity.both"), HEALTHKIT_BODYFAT_READ("https://www.huawei.com/healthkit/bodyfat.read"), HEALTHKIT_BODYFAT_WRITE("https://www.huawei.com/healthkit/bodyfat.write"), HEALTHKIT_BODYFAT_BOTH("https://www.huawei.com/healthkit/bodyfat.both"), HEALTHKIT_SLEEP_READ("https://www.huawei.com/healthkit/sleep.read"), HEALTHKIT_SLEEP_WRITE("https://www.huawei.com/healthkit/sleep.write"), HEALTHKIT_SLEEP_BOTH("https://www.huawei.com/healthkit/sleep.both"), HEALTHKIT_NUTRITION_READ("https://www.huawei.com/healthkit/nutrition.read"), HEALTHKIT_NUTRITION_WRITE("https://www.huawei.com/healthkit/nutrition.write"), HEALTHKIT_NUTRITION_BOTH("https://www.huawei.com/healthkit/nutrition.both"), HEALTHKIT_BLOODPRESSURE_READ("https://www.huawei.com/healthkit/bloodpressure.read"), HEALTHKIT_BLOODPRESSURE_WRITE("https://www.huawei.com/healthkit/bloodpressure.write"), HEALTHKIT_BLOODPRESSURE_BOTH("https://www.huawei.com/healthkit/bloodpressure.both"), HEALTHKIT_OXYGENSTATURATION_READ("https://www.huawei.com/healthkit/oxygensaturation.read"), HEALTHKIT_OXYGENSTATURATION_WRITE("https://www.huawei.com/healthkit/oxygensaturation.write"), HEALTHKIT_OXYGENSTATURATION_BOTH("https://www.huawei.com/healthkit/oxygensaturation.both"), HEALTHKIT_BODYTEMPERATURE_READ("https://www.huawei.com/healthkit/bodytemperature.read"), HEALTHKIT_BODYTEMPERATURE_WRITE("https://www.huawei.com/healthkit/bodytemperature.write"), HEALTHKIT_BODYTEMPERATURE_BOTH("https://www.huawei.com/healthkit/bodytemperature.both"), HEALTHKIT_REPRODUCTIVE_READ("https://www.huawei.com/healthkit/reproductive.read"), HEALTHKIT_REPRODUCTIVE_WRITE("https://www.huawei.com/healthkit/reproductive.write"), HEALTHKIT_REPRODUCTIVE_BOTH("https://www.huawei.com/healthkit/reproductive.both"), HEALTHKIT_ACTIVITY_RECORD_READ("https://www.huawei.com/healthkit/activityrecord.read"), HEALTHKIT_ACTIVITY_RECORD_WRITE("https://www.huawei.com/healthkit/activityrecord.write"), HEALTHKIT_ACTIVITY_RECORD_BOTH("https://www.huawei.com/healthkit/activityrecord.both"), HEALTHKIT_STRESS_READ("https://www.huawei.com/healthkit/stress.read"), HEALTHKIT_STRESS_WRITE("https://www.huawei.com/healthkit/stress.write"), HEALTHKIT_STRESS_BOTH("https://www.huawei.com/healthkit/stress.both"); private final String value; AccConstants(String value) { this.value = value; } public String getValue() { return value; } } /** * Whole base constants variables as Map **/ Map<String, Object> CONSTANTS_MAP = initMap(); /** * Initializes Account Constants Map. * * @return Constants map */ static Map<String, Object> initMap() { Map<String, Object> constantMap = new HashMap<>(); for (AccConstants variable : EnumSet.allOf(AccConstants.class)) { String key = variable.name(); String value = variable.getValue(); constantMap.put(key, value); } return Collections.unmodifiableMap(constantMap); } }
50.387755
101
0.710544
b4c7d1c1ca24bf8f977f3c9c985bf53f459637e7
5,013
/* * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.xml.ws.rx.rm.runtime; import com.oracle.webservices.oracle_internal_api.rm.RMRetryException; import com.sun.xml.ws.api.server.WSEndpoint; import com.sun.istack.logging.Logger; import com.sun.xml.ws.client.ClientTransportException; import com.sun.xml.ws.rx.RxException; import com.sun.xml.ws.rx.rm.localization.LocalizationMessages; // import com.sun.xml.ws.runtime.dev.Session; import com.sun.xml.ws.runtime.dev.SessionManager; import java.io.IOException; import jakarta.xml.ws.WebServiceException; /** * The non-instantiable utility class containing various common static utility methods * used for runtime processing. * * @author Marek Potociar (marek.potociar at sun.com) */ final class Utilities { private static final Logger LOGGER = Logger.getLogger(Utilities.class); /** * Non-instantiable constructor */ private Utilities() { // nothing to do } /** * Checks whether the actual sequence identifier value equals to the expected value * and throws a logged exception if th check fails. * * @param expected expected sequence identifier value * @param actual actual sequence identifier value * @throws java.lang.IllegalStateException if actual value does not equal to the expected value */ static void assertSequenceId(String expected, String actual) throws IllegalStateException { if (expected != null && !expected.equals(actual)) { throw LOGGER.logSevereException(new IllegalStateException(LocalizationMessages.WSRM_1105_SEQUENCE_ID_NOT_RECOGNIZED(actual, expected))); } } static String extractSecurityContextTokenId(com.sun.xml.ws.security.secext10.SecurityTokenReferenceType strType) throws RxException { com.sun.xml.ws.security.trust.elements.str.Reference strReference = com.sun.xml.ws.security.trust.WSTrustElementFactory.newInstance().createSecurityTokenReference( new com.sun.xml.ws.security.secext10.ObjectFactory().createSecurityTokenReference(strType)).getReference(); if (!(strReference instanceof com.sun.xml.ws.security.trust.elements.str.DirectReference)) { throw LOGGER.logSevereException( new RxException(LocalizationMessages.WSRM_1132_SECURITY_REFERENCE_ERROR(strReference.getClass().getName()))); } return ((com.sun.xml.ws.security.trust.elements.str.DirectReference) strReference).getURIAttr().toString(); } /** * Either creates a new <code>Session</code> for the * <code>InboundSequence</code> or returns one that has * already been created by the SC Pipe. * * @param endpoint endpoint instance * @param sessionId session identifier * @return The Session */ static Session startSession(WSEndpoint endpoint, String sessionId) { SessionManager manager = SessionManager.getSessionManager(endpoint,null); Session session = manager.getSession(sessionId); if (session == null) { session = manager.createSession(sessionId); } return session; } /** * Terminates the session associated with the sequence if * RM owns the lifetime of the session, i.e. if SC is not present. * * @param endpoint endpoint instance * @param sessionId session identifier */ static void endSessionIfExists(WSEndpoint endpoint, String sessionId) { SessionManager manager = SessionManager.getSessionManager(endpoint,null); if (manager.getSession(sessionId) != null) { manager.terminateSession(sessionId); } } /** * Based on the parameter, this utility method determines whether or not * it makes sense to try resending the message. * * @param throwable * @return {@code true} if this exception seems to be related to a connection * problem. */ static boolean isResendPossible(Throwable throwable) { if (throwable instanceof RMRetryException || throwable instanceof IOException) { return true; } else if (throwable instanceof WebServiceException) { if (throwable instanceof ClientTransportException) { return true; // if endpoint went down, let's try to resend, as it may come up again } // Unwrap exception and see if it makes sense to retry this request // (no need to check for null - handled by instanceof) if (throwable.getCause() instanceof RMRetryException || throwable.getCause() instanceof IOException) { return true; } } return false; } }
40.427419
171
0.692599
e0b2d0ac2eccd51a2458b687309772656a4e34c5
2,171
/* * Copyright (C) 2019 Rison Han * * 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.hitachivantara.hcp.standard.util.multipartupload; import com.hitachivantara.hcp.standard.util.multipartupload.MulitipartUploadException.Stage; public interface UploadEventHandler { // void partUploaded(int partNumber, long size, long startTime, long endTime); // void complete(String key, long size, long startTime, long endTime); void init(String namespace, String key, String uploadId); void beforePartUpload(String namespace, String key, String uploadId, int partNumber, long uploadPartsize, long startTime); // void caughtPartUploadException(String namespace, String key, String uploadId, int partNumber, long uploadPartsize, Exception e); void afterPartUpload(String namespace, String key, String uploadId, int partNumber, long uploadPartsize, long startTime, long endTime); void complete(String namespace, String key, String uploadId, Long uploadedSize, long startTime, long endTime); void caughtException(Stage stage, MulitipartUploadException e); }
58.675676
136
0.568862
7195a4c1975fae07d4e31ceaa17dd3ede6b87caf
1,861
package com.vk.api.sdk.objects; import com.google.gson.annotations.SerializedName; import java.util.Objects; public class UserAuthResponse { @SerializedName("access_token") private String accessToken; @SerializedName("user_id") private Integer userId; @SerializedName("expires_in") private Integer expiresIn; @SerializedName("email") private String email; @SerializedName("error") private String error; public String getAccessToken() { return accessToken; } public Integer getUserId() { return userId; } public Integer getExpiresIn() { return expiresIn; } public String getEmail() { return email; } public String getError() { return error; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserAuthResponse that = (UserAuthResponse) o; return Objects.equals(accessToken, that.accessToken) && Objects.equals(userId, that.userId) && Objects.equals(expiresIn, that.expiresIn) && Objects.equals(email, that.email) && Objects.equals(error, that.error); } @Override public int hashCode() { return Objects.hash(accessToken, userId, expiresIn, email, error); } @Override public String toString() { final StringBuilder sb = new StringBuilder("UserAuthResponse{"); sb.append("accessToken='").append(accessToken).append('\''); sb.append(", userId=").append(userId); sb.append(", expiresIn=").append(expiresIn); sb.append(", email=").append(email); sb.append(", error='").append(error).append('\''); sb.append('}'); return sb.toString(); } }
25.493151
74
0.6072
0fda80cb541c74808ed364e45adf65c1d31658c0
3,984
/* * JSweet transpiler - http://www.jsweet.org * Copyright (C) 2015 CINCHEO SAS <[email protected]> * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jsweet.transpiler.extension; import java.math.BigDecimal; import javax.lang.model.element.Element; import org.jsweet.transpiler.extension.PrinterAdapter; import org.jsweet.transpiler.model.MethodInvocationElement; import org.jsweet.transpiler.model.NewClassElement; /** * This optional adapter tunes the JavaScript generation to map the Java's * BigDecimal API to the Big JavaScript library. * * <p> * Warning: this adapter is not activated by default. See JSweet specifications * to know how to activate this adapter. * * <p> * This extension requires the big.js candy to be available in the JSweet * classpath: https://github.com/jsweet-candies/candy-bigjs. * * @author Renaud Pawlak */ public class BigDecimalAdapter extends PrinterAdapter { public BigDecimalAdapter(PrinterAdapter parent) { super(parent); // all BigDecimal types are mapped to Big addTypeMapping(BigDecimal.class.getName(), "Big"); } @Override public boolean substituteNewClass(NewClassElement newClass) { String className = newClass.getTypeAsElement().toString(); // map the BigDecimal constructors if (BigDecimal.class.getName().equals(className)) { print("new Big(").printArgList(newClass.getArguments()).print(")"); return true; } // delegate to the adapter chain return super.substituteNewClass(newClass); } @Override public boolean substituteMethodInvocation(MethodInvocationElement invocation) { if (invocation.getTargetExpression() != null) { Element targetType = invocation.getTargetExpression().getTypeAsElement(); if (BigDecimal.class.getName().equals(targetType.toString())) { // BigDecimal methods are mapped to their Big.js equivalent switch (invocation.getMethodName()) { case "multiply": printMacroName(invocation.getMethodName()); print(invocation.getTargetExpression()).print(".times(").printArgList(invocation.getArguments()) .print(")"); return true; case "add": printMacroName(invocation.getMethodName()); print(invocation.getTargetExpression()).print(".plus(").printArgList(invocation.getArguments()) .print(")"); return true; case "scale": printMacroName(invocation.getMethodName()); // we assume that we always have a scale of 2, which is a // good default if we deal with currencies... // to be changed/implemented further print("2"); return true; case "setScale": printMacroName(invocation.getMethodName()); print(invocation.getTargetExpression()).print(".round(").print(invocation.getArguments().get(0)) .print(")"); return true; case "compareTo": printMacroName(invocation.getMethodName()); print(invocation.getTargetExpression()).print(".cmp(").print(invocation.getArguments().get(0)) .print(")"); return true; case "equals": printMacroName(invocation.getMethodName()); print(invocation.getTargetExpression()).print(".eq(").print(invocation.getArguments().get(0)) .print(")"); return true; } } } // delegate to the adapter chain return super.substituteMethodInvocation(invocation); } }
35.891892
101
0.721135
306fef4f219ac8bb6a15cd4a5529c1a1a6ca688e
1,457
package com.njp.android.kuweather.utils; import android.Manifest; import android.content.Context; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import java.util.ArrayList; import java.util.List; /** * 百度定位工具类 */ public class BDLocationUtil { private static LocationClient sLocationClient; public static void init(Context context) { sLocationClient = new LocationClient(context); LocationClientOption option = new LocationClientOption(); option.setIsNeedAddress(true); sLocationClient.setLocOption(option); } public static void setListener(BDLocationListener locationListener) { sLocationClient.registerLocationListener(locationListener); } public static void removeListener(BDLocationListener locationListener) { sLocationClient.unRegisterLocationListener(locationListener); } public static void start() { sLocationClient.start(); } public static void stop() { sLocationClient.stop(); } public static List<String> getPermissionList() { List<String> permissionList = new ArrayList<>(); permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION); permissionList.add(Manifest.permission.READ_PHONE_STATE); permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); return permissionList; } }
27.490566
76
0.735072
5c4d468dd188ee70a9fef25b405d4c53fa3b5bb4
545
package com.senchuuhi.iweb.system.main.controller; import com.senchuuhi.iweb.base.controller.FrontBaseController; import com.senchuuhi.iweb.base.model.ViewModel; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/pages") public class PagesController extends FrontBaseController { @RequestMapping(value={"", "/"}) public ViewModel pages(Model model) { return super.getView("main/pages"); } }
28.684211
62
0.779817
716043ba2036f13c334a220de412728a7295951f
3,052
/* * Copyright © 2017 Cask Data, 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 co.cask.cdap.proto; import co.cask.cdap.api.dataset.lib.PartitionKey; import co.cask.cdap.api.dataset.lib.partitioned.PartitionKeyCodec; import co.cask.cdap.proto.id.DatasetId; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Notification for events, such as cron expression triggering or data being added to a dataset. */ public class Notification { public static final String DATASET_ID = "datasetId"; public static final String NUM_PARTITIONS = "numPartitions"; public static final String PARTITION_KEYS = "partitionKeys"; private static final Gson GSON = new GsonBuilder().registerTypeAdapter(PartitionKey.class, new PartitionKeyCodec()).create(); /** * The type of the notification. */ public enum Type { TIME, STREAM_SIZE, PARTITION, PROGRAM_STATUS, PROGRAM_HEART_BEAT } private final Type notificationType; private final Map<String, String> properties; public Notification(Type notificationType, Map<String, String> properties) { this.notificationType = notificationType; this.properties = properties; } public static Notification forPartitions(DatasetId datasetId, Collection<? extends PartitionKey> partitionKeys) { Map<String, String> properties = new HashMap<>(); properties.put(DATASET_ID, datasetId.toString()); properties.put(NUM_PARTITIONS, Integer.toString(partitionKeys.size())); properties.put(PARTITION_KEYS, GSON.toJson(partitionKeys)); return new Notification(Notification.Type.PARTITION, properties); } public Type getNotificationType() { return notificationType; } public Map<String, String> getProperties() { return properties; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Notification that = (Notification) o; return Objects.equals(notificationType, that.notificationType) && Objects.equals(properties, that.properties); } @Override public int hashCode() { return Objects.hash(notificationType, properties); } @Override public String toString() { return "Notification{" + "notificationType=" + notificationType + ", properties=" + properties + '}'; } }
28.792453
96
0.710682
22753710b4421ebe092b2bd34e3b5127be28b36d
6,529
package alu.linking.preprocessing.embeddings.posttraining; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import alu.linking.config.constants.FilePaths; import alu.linking.config.constants.Strings; import alu.linking.config.kg.EnumModelType; import alu.linking.preprocessing.embeddings.sentenceformatter.EmbeddingSentenceFormatter; import alu.linking.preprocessing.embeddings.sentenceformatter.RDF2VecEmbeddingSentenceFormatter; import alu.linking.utils.EmbeddingsUtils; /** * Class handling embeddings computed through graph walks (combining and * transforming existing embeddings) * * @author Kristian Noullet * */ public class GraphWalkHandler { final EnumModelType KG; public GraphWalkHandler(final EnumModelType KG) { this.KG = KG; } /** * Reads computed word embeddings and computes required entity embeddings based * on them. <br> * Entity Embeddings are combined through addition.<br> * <b>Note</b>: If you want to define a custom combination function, please use * {@link #computeRequiredEntityEmbeddings(BiFunction)} instead * * @Deprecated Done in python now (way more efficient RAM-wise) */ @Deprecated public void computeRequiredEntityEmbeddings() { computeRequiredEntityEmbeddings(EmbeddingsUtils::add); } /** * Reads computed word embeddings and computes required entity embeddings based * on them. <br> * Entity Embeddings are combined through use of the passed BiFunction * * @Deprecated Done in python now (way more efficient RAM-wise) */ @Deprecated public void computeRequiredEntityEmbeddings( BiFunction<List<Number>, List<Number>, List<Number>> embeddingCombineFunction) { try { // Reads the generated word embeddings final Map<String, List<Number>> word_embeddings = EmbeddingsUtils.readEmbeddings(new File(""));// FilePaths.FILE_EMBEDDINGS_GAPH_WALK_TRAINED_EMBEDDINGS.getPath(KG))); // Now rebuild all of the word embeddings into entity embeddings // Take the sentences and combine them as wanted for each entity (one line = one // entity) final String rdf2vec_embedding_rep = FilePaths.FILE_GRAPH_WALK_OUTPUT_SENTENCES.getPath(KG); final EmbeddingSentenceFormatter rdf2vec_formatter = new RDF2VecEmbeddingSentenceFormatter(); final int rdf2vec_key_index = 0; final String rdf2vec_sorted_delim = Strings.EMBEDDINGS_RDF2VEC_SPLIT_DELIM.val; final Map<String, List<Number>> entityEmbeddingMap = new HashMap<>(); int workedCounter = 0; try (final BufferedReader brIn = new BufferedReader(new FileReader(new File(rdf2vec_embedding_rep)))) { String line = null; while ((line = brIn.readLine()) != null) { final String[] words = line.split(rdf2vec_sorted_delim); final String key = rdf2vec_formatter.extractKey(line, rdf2vec_key_index, rdf2vec_sorted_delim); // Embeddings for this line's sentence or sentence part are computed and added // to what we already have // Note: Sentences may and likely do span multiple lines, hence our multi-line // sorted logic // EDIT: Can't remember why the above holds. Likely copied from sorting logic? final List<Number> left = entityEmbeddingMap.get(key);// (((left = entityEmbeddingMap.get(key)) == // null) ? Lists.newArrayList() : left); final List<Number> rebuiltSentence = EmbeddingsUtils.rebuildSentenceEmbedding(word_embeddings, Arrays.asList(words), embeddingCombineFunction); if (rebuiltSentence == null) { System.err.println("Words: " + Arrays.asList(words)); int foundEmbedding = 0; for (String word : words) { foundEmbedding += (word_embeddings.get(word) != null ? 1 : 0); } System.out.println("Found embeddings for " + foundEmbedding + " / " + words.length); throw new RuntimeException("A rebuilt sentence embedding should not be null..."); } final List<Number> embedding = embeddingCombineFunction.apply(left, rebuiltSentence); if (embedding != null && embedding.size() > 0) { workedCounter++; } // Overwrite the value we have as an embedding currently entityEmbeddingMap.put(key, embedding); } } // ------------------------------------------ // Now we should back up the proper entity // embeddings for easier access later on // ------------------------------------------ // Raw dump final ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(FilePaths.FILE_EMBEDDINGS_GRAPH_WALK_ENTITY_EMBEDDINGS_RAWMAP.getPath(KG))); oos.writeObject(entityEmbeddingMap); oos.close(); // Human-readable dump try (final BufferedWriter bwOut = new BufferedWriter( new FileWriter(new File(FilePaths.FILE_EMBEDDINGS_GRAPH_WALK_ENTITY_EMBEDDINGS.getPath(KG))))) { final String outDelim = Strings.EMBEDDINGS_ENTITY_EMBEDDINGS_DUMP_DELIMITER.val; for (Map.Entry<String, List<Number>> e : entityEmbeddingMap.entrySet()) { bwOut.write(e.getKey()); for (Number n : e.getValue()) { bwOut.write(outDelim); bwOut.write(n.toString()); } bwOut.newLine(); } } } catch (IOException e) { e.printStackTrace(); } } /** * Newer version of {@link #computeRequiredEntityEmbeddings()} Reads computed * entity embeddings (done via python) and constructs a HashMap based on it * which is dumped in its raw byte format for faster loading for disambiguation * * @throws FileNotFoundException * @throws IOException */ public void readPythonEntityEmbeddingsOutputHashMap() throws FileNotFoundException, IOException { final Map<String, List<Number>> entityEmbeddingMap = EmbeddingsUtils .readEmbeddings(new File(FilePaths.FILE_EMBEDDINGS_GRAPH_WALK_ENTITY_EMBEDDINGS.getPath(KG))); // ------------------------------------------ // Now we should back up the proper entity // embeddings for easier access later on // ------------------------------------------ // Raw dump try (FileOutputStream fos = new FileOutputStream( FilePaths.FILE_EMBEDDINGS_GRAPH_WALK_ENTITY_EMBEDDINGS_RAWMAP.getPath(KG))) { try (final ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(entityEmbeddingMap); } } } }
41.062893
170
0.720325
3e81a36c0fd11c4e26d55d90ff4a6dd88b7a2e27
6,631
package de.mennomax.astikorcarts.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.electronwill.nightconfig.core.Config; import com.electronwill.nightconfig.core.Config.Entry; import de.mennomax.astikorcarts.config.AstikorCartsConfig; import de.mennomax.astikorcarts.entity.PlowCartEntity; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.HoeItem; import net.minecraft.item.ItemStack; import net.minecraft.item.ShovelItem; import net.minecraft.tags.BlockTags; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import net.minecraftforge.registries.ForgeRegistries; public class PlowBlockHandler { private final List<PlowExecutor> executors = new ArrayList<>(2); private final ItemStack STACK; private final int SLOT; private final PlowCartEntity PLOW; /** * SupressWarnings because of cast from Object to List(String). Safe because the * object is a string list as defined in {@link AstikorCartsConfig} */ @SuppressWarnings("unchecked") public PlowBlockHandler(ItemStack stackIn, int slotIn, PlowCartEntity plowIn) { STACK = stackIn; SLOT = slotIn; PLOW = plowIn; String registryName = STACK.getItem().getRegistryName().toString(); Config itemReplaceMap = AstikorCartsConfig.COMMON.REPLACEMAP.get().get(registryName); if (itemReplaceMap == null) { // TODO: Remove once #6236 has been merged if (STACK.getItem() instanceof HoeItem) { itemReplaceMap = AstikorCartsConfig.COMMON.REPLACEMAP.get().get("#forge:tools/hoes"); } else if (STACK.getItem() instanceof ShovelItem) { itemReplaceMap = AstikorCartsConfig.COMMON.REPLACEMAP.get().get("#forge:tools/shovels"); } else { for (ResourceLocation rl : STACK.getItem().getTags()) { if ((itemReplaceMap = AstikorCartsConfig.COMMON.REPLACEMAP.get().get(rl.toString())) != null) { break; } } } } if (itemReplaceMap != null) { HashMap<ArrayList<Block>, Block> replaceMap = new HashMap<>(); for (Entry entry : itemReplaceMap.entrySet()) { ArrayList<Block> blockList = new ArrayList<>(); for (String blockId : ((List<String>) entry.getValue())) { Block toAdd = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(blockId)); if (toAdd == null) { for (Block block : BlockTags.getCollection().get(new ResourceLocation(blockId)).getAllElements()) { blockList.add(block); } } else { blockList.add(toAdd); } } replaceMap.put(blockList, ForgeRegistries.BLOCKS.getValue(new ResourceLocation(entry.getKey()))); } executors.add(new ReplaceHandler(replaceMap)); } // Config breakOrPlaceMap = // AstikorCartsConfig.COMMON.BREAKMAP.get().get(stack.getItem().getRegistryName().toString()); // if(breakOrPlaceMap == null) { // if((breakOrPlaceMap = AstikorCartsConfig.COMMON.PLACEMAP.get()) != null) { // executors.add(new ReplaceHandler(AstikorCartsConfig.COMMON.PLACEMAP.get())); // } // } } public void tillBlock(PlayerEntity player, BlockPos blockPos) { for (PlowExecutor exe : executors) { exe.tillBlock(player, blockPos); } } private class ReplaceHandler implements PlowExecutor { private final HashMap<ArrayList<Block>, Block> replaceMap; public ReplaceHandler(HashMap<ArrayList<Block>, Block> replaceMapIn) { this.replaceMap = replaceMapIn; } @Override public void tillBlock(PlayerEntity player, BlockPos pos) { BlockState toReplaceState = player.world.getBlockState(pos); Block replaceWith = getFirstMatch(replaceMap, toReplaceState); if (replaceWith != null) { BreakEvent event = new BlockEvent.BreakEvent(player.world, pos, toReplaceState, player); MinecraftForge.EVENT_BUS.post(event); if (!event.isCanceled()) { player.world.setBlockState(pos, replaceWith.getDefaultState()); handleStackDamage(player, STACK); } } } } // private class BreakHandler implements PlowExecutor { // // private List<Block> breakList; // // public BreakHandler(List<Block> breakListIn) { // this.breakList = breakListIn; // } // // @Override // public void plowBlock(PlayerEntity player, BlockPos pos) { // // } // // } // // private class PlaceHandler implements PlowExecutor { // // @Override // public void tillBlock(PlayerEntity player, BlockPos pos) { // // } // // } private void handleStackDamage(PlayerEntity player, ItemStack stack) { if (!player.isCreative()) { if (stack.isDamageable()) { ItemStack copy = stack.copy(); stack.damageItem(1, player, e -> {}); if (stack.isEmpty()) { ForgeEventFactory.onPlayerDestroyItem(player, copy, null); PLOW.updateSlot(SLOT); PLOW.world.playSound(PLOW.posX, PLOW.posY, PLOW.posZ, SoundEvents.ENTITY_ITEM_BREAK, PLOW.getSoundCategory(), 0.8F, 0.8F + PLOW.world.rand.nextFloat() * 0.4F, false); } } else { stack.shrink(1); if (stack.isEmpty()) { PLOW.updateSlot(SLOT); } } } } private Block getFirstMatch(HashMap<ArrayList<Block>, Block> replaceMap, BlockState toReplaceState) { for (ArrayList<Block> matchList : replaceMap.keySet()) { for (Block match : matchList) { if (match == toReplaceState.getBlock()) { return replaceMap.get(matchList); } } } return null; } }
38.552326
186
0.608355
83c4d626e30c5f08d4daedea38c4d35e609c841b
196
package ui; public interface UI { /** * Launch the maze game. */ public void launchGame(); /** * Display the winner of the maze game. */ public void displayWinner(); }
14
41
0.586735
de0f4dc084981413ac6e7416fe54705f74976cd9
1,782
package slidingWindow; import static org.junit.Assert.assertEquals; import org.junit.Test; import junit.framework.Assert; public class MinimumSizeSubarraySum_209 { public int minSubArrayLen(int s, int[] nums) { if (nums.length == 0) { return 0; } int left, right, minLen, sum; left = right = sum = 0; minLen = Integer.MAX_VALUE; while(right < nums.length) { //expand window while(sum < s && right < nums.length) { sum += nums[right]; right++; } if (sum >= s) { minLen = Math.min(minLen, right - left); } //shrink window while(sum >= s) { sum -= nums[left]; left++; if (sum >= s) { minLen = Math.min(minLen, right - left); } } } return minLen == Integer.MAX_VALUE ? 0 : minLen; } public int minSubArrayLen_refactored(int s, int[] nums) { if(nums.length == 0) return 0; int minLen = Integer.MAX_VALUE, left=0, right=0, sum=0; while(right < nums.length) { sum += nums[right++]; while(sum >= s) { minLen = Math.min(minLen, right-left); sum -= nums[left++]; } } return minLen==Integer.MAX_VALUE ? 0 : minLen; } @Test public void Test_01() { int[] nums = {2,3,1,2,4,3}; int s = 7; int expected = 2; assertEquals(expected, minSubArrayLen(s, nums)); assertEquals(expected, minSubArrayLen_refactored(s, nums)); } @Test public void Test_02() { int[] nums = {12,28,83,4,25,26,25,2,25,25,25,12}; int s = 213; int expected = 8; assertEquals(expected, minSubArrayLen(s, nums)); assertEquals(expected, minSubArrayLen_refactored(s, nums)); } @Test public void Test_03() { int[] nums = {1,1}; int s = 3; int expected = 0; assertEquals(expected, minSubArrayLen(s, nums)); assertEquals(expected, minSubArrayLen_refactored(s, nums)); } }
20.72093
61
0.625701
19893a3408bb88b7c5fac780ef9eede5544a0d85
2,996
package com.microsoft.appcenter.ingestion.models.one; import com.microsoft.appcenter.utils.AppCenterLog; import org.json.JSONException; import org.json.JSONObject; import java.util.Map; import static com.microsoft.appcenter.utils.AppCenterLog.LOG_TAG; /** * Populate Part C properties. */ public class PartCUtils { /** * Adds part C properties to a log. * * @param properties custom properties. * @param dest destination common schema log. */ public static void addPartCFromLog(Map<String, String> properties, CommonSchemaLog dest) { if (properties == null) { return; } try { /* Part C creates properties in a deep structure using dot as an object separator. */ Data data = new Data(); dest.setData(data); for (Map.Entry<String, String> entry : properties.entrySet()) { /* Validate key not null. */ String key = entry.getKey(); if (key == null) { AppCenterLog.warn(LOG_TAG, "Property key cannot be null."); continue; } /* Validate value not null. */ String value = entry.getValue(); if (value == null) { AppCenterLog.warn(LOG_TAG, "Value of property with key '" + key + "' cannot be null."); continue; } /* Validate key is not Part B. */ if (Data.BASE_DATA.equals(key) || Data.BASE_DATA_TYPE.equals(key)) { AppCenterLog.warn(LOG_TAG, "Property key '" + key + "' is reserved."); continue; } /* Split property name by dot. */ String[] keys = key.split("\\.", -1); int lastIndex = keys.length - 1; JSONObject destProperties = data.getProperties(); for (int i = 0; i < lastIndex; i++) { JSONObject subObject = destProperties.optJSONObject(keys[i]); if (subObject == null) { if (destProperties.has(keys[i])) { AppCenterLog.warn(LOG_TAG, "Property key '" + keys[i] + "' already has a value, the old value will be overridden."); } subObject = new JSONObject(); destProperties.put(keys[i], subObject); } destProperties = subObject; } if (destProperties.has(keys[lastIndex])) { AppCenterLog.warn(LOG_TAG, "Property key '" + keys[lastIndex] + "' already has a value, the old value will be overridden."); } destProperties.put(keys[lastIndex], value); } } catch (JSONException ignore) { /* Can only happen with NaN or Infinite but our values are String. */ } } }
37.45
144
0.515354
1490d183805edcb4c887d6414552f6d7f0672478
571
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 根据PID获取相关的开票资料 * * @author auto create * @since 1.0, 2018-11-27 21:31:19 */ public class AlipayBossFncUserinvoiceinfoQueryModel extends AlipayObject { private static final long serialVersionUID = 8599787923482538948L; /** * 开票pid/mid/ou,唯一标识商户信息/集团用户信息的ID */ @ApiField("pid") private String pid; public String getPid() { return this.pid; } public void setPid(String pid) { this.pid = pid; } }
19.033333
75
0.688266
5641e1ddffe4d585a42f787aa79b1938062d718f
3,044
package com.company.menu; import com.company.product.Drink; import com.company.product.RFood; import com.company.product.Sweet; import java.util.*; public class RMenu extends Menu { private List<Sweet> sweets; private List<RFood> rfoods; public RMenu(){ this.rfoods=new ArrayList<RFood>(); this.sweets=new ArrayList<Sweet>(); } public RMenu(String name, List<Drink> drinks, List<Sweet> sweets, List<RFood> rfoods) { super(name, drinks); this.sweets = sweets; this.rfoods = rfoods; //calcul pret double totalPrice=0; for(Drink it: drinks) totalPrice+=it.getPrice(); for(Sweet it: sweets) totalPrice+=it.getPrice(); for(RFood it: rfoods) totalPrice+=it.getPrice(); this.price=totalPrice; } @Override public void reader(){ Scanner var=new Scanner (System.in); System.out.print("Restaurant Menu name:"); String name=var.nextLine(); this.name=name; System.out.println("->Restaurant Menu list of drinks:"); System.out.print("How many drinks:"); int n=var.nextInt(); for(int i=0;i<n;i++) { System.out.println("->Introduce drink number "+i+": "); Drink drink=new Drink(); drink.reader(); this.drinks.add(drink); } System.out.println("->Restaurant Menu list of cakes:"); System.out.print("How many cakes:"); n=var.nextInt(); for(int i=0;i<n;i++) { System.out.println("->Introduce cake number "+i+": "); Sweet sweet=new Sweet(); sweet.reader(); sweets.add(sweet); } System.out.println("->Restaurant Menu list of meals:"); System.out.print("How many meals:"); n=var.nextInt(); for(int i=0;i<n;i++) { System.out.println("->Introduce meal number "+i+": "); RFood rfood=new RFood(); rfood.reader(); rfoods.add(rfood); } double totalPrice=0; for(Drink it: drinks) totalPrice+=it.getPrice(); for(Sweet it: sweets) totalPrice+=it.getPrice(); for(RFood it: rfoods) totalPrice+=it.getPrice(); this.price=totalPrice; } @Override public String toString() { String output="----Menu:Restaurant Menu-----\n"; output+="Name: "+this.name+"\n"; output+="Menu Price: "+this.price+"lei\n"; output+="->Desert Options:\n"; for(Sweet sweet : this.sweets) output+=sweet; output+="->Restaurant Food Options:\n"; for(RFood rFood: this.rfoods) output+=rFood; output+="->Drinks Options:\n"; for(Drink drink : this.drinks) output+=drink; return output; } public List<Sweet> getSweets() { return sweets; } public List<RFood> getRfoods() { return rfoods; } }
24.352
91
0.54435
fb5d0cfcc14724a4496263699398d1439896c980
1,074
package org.tandembrowsing.io.soap; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import java.util.logging.Logger; import org.jdom.JDOMException; import org.tandembrowsing.io.Event; import org.tandembrowsing.io.EventQueue; /** * LayoutManagerSOAP is a web service interface to external components to * send events to the LayoutManager component. * * @author tjh * */ public class LayoutManagerService { private static Logger logger = Logger.getLogger("org.tandembrowsing"); public static String processEvent(String payload) { try { EventQueue.getInstance().add(Event.parse(payload)); return "OK"; } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Failed to parse: "+payload, e); return "NOK:"+e.getMessage(); } catch (JDOMException e) { logger.log(Level.SEVERE, "Failed to parse: "+payload, e); return "NOK:"+e.getMessage(); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to parse: "+payload, e); return "NOK:"+e.getMessage(); } } }
26.195122
73
0.726257
b1e9f00fc2ae8e6a77fe00fd307c0653b02610f3
243
package cn.plutowu.entity; import lombok.Data; /** * 秒杀订单 * * @author PlutoWu * @date 2021/05/01 */ @Data public class SeckillOrder { private Long id; private Long userId; private Long orderId; private Long goodsId; }
12.15
27
0.658436
9c155700b77e3ad055d6183b53a1ca8b6ca97701
286
/* * This api interface will deal with everything in chatter file api */ public interface ChatterFileApiInterface { public String getFileWithFormatAvailability(String fileId, String formatType); public String insertFileInNewsFeed(ModelUploadFileRequestInNewsFeeds fileDetails); }
31.777778
83
0.828671
5de60ace7cb723eb27c179112172675ede9e33c4
771
package com.simon816.chatui.util; import org.spongepowered.api.service.permission.Subject; import org.spongepowered.api.service.permission.SubjectReference; import java.util.concurrent.CompletableFuture; public class ForwardingReference implements SubjectReference { protected ForwardingSource source; public ForwardingReference(ForwardingSource source) { this.source = source; } @Override public String getCollectionIdentifier() { return source.getContainingCollection().getIdentifier(); } @Override public String getSubjectIdentifier() { return source.getIdentifier(); } @Override public CompletableFuture<Subject> resolve() { return CompletableFuture.completedFuture(source); } }
24.870968
65
0.740597
841011d89f0ffd6bbfc8109a32e46b30ba297e2e
952
package com.amazonaws.services.schemaregistry.integration_tests.kafka; public class LocalKafkaClusterHelper implements KafkaClusterHelper { private static final String FAKE_CLUSTER_ARN = "FAKE_CLUSTER_ARN"; private static final String BOOTSTRAP_STRING = "127.0.0.1:9092"; private static final String ZOOKEEPER_STRING = "127.0.0.1:2181"; private static final int NUMBER_OF_PARTITIONS = 1; private static final short REPLICATION_FACTOR = 1; @Override public String getOrCreateCluster() { return FAKE_CLUSTER_ARN; } @Override public String getBootstrapString() { return BOOTSTRAP_STRING; } @Override public String getZookeeperConnectString() { return ZOOKEEPER_STRING; } @Override public int getNumberOfPartitions() { return NUMBER_OF_PARTITIONS; } @Override public short getReplicationFactor() { return REPLICATION_FACTOR; } }
26.444444
70
0.713235
de3a9a6688749b38c813a0f10a907a5b299f86df
92
package br.inatel.cdg.simple.factory.pizza; public class PizzaCalabresa extends Pizza { }
15.333333
43
0.793478
e3e7f100c5d3a9762a23c1994760ef8c15c0511b
1,459
/* * Copyright (C) 2010-2014 The MPDroid Project * * 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.namelessdev.mpdroid.models; import org.a0z.mpd.item.Music; public abstract class AbstractPlaylistMusic extends Music { private int mCurrentSongIconRefID; private boolean mForceCoverRefresh = false; protected AbstractPlaylistMusic(final Music music) { super(music); } public int getCurrentSongIconRefID() { return mCurrentSongIconRefID; } public abstract String getPlayListMainLine(); public abstract String getPlaylistSubLine(); public boolean isForceCoverRefresh() { return mForceCoverRefresh; } public void setCurrentSongIconRefID(final int currentSongIconRefID) { mCurrentSongIconRefID = currentSongIconRefID; } public void setForceCoverRefresh(final boolean forceCoverRefresh) { mForceCoverRefresh = forceCoverRefresh; } }
28.607843
75
0.73475
b4a02f64d59c42b5abffda90eb1d761413b52468
606
/* * Copyright (c) 2021, the hapjs-platform Project Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.hapjs.common.utils; public class StringUtils { private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); public static String byte2HexString(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } }
27.545455
77
0.594059
840e4723afa2a185332d5eca9b9e5fe1408e7f53
3,900
package com.py.common.lock.aop; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.py.common.lock.LockInterface; import com.py.common.lock.annotatiop.LockType; import com.py.common.lock.annotatiop.YLock; import com.py.common.lock.exception.LockException; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; import java.util.Map; /** * @Description: 分布式锁 * @author: li * @Date: Created in 2019/12/27 */ @Component @Aspect @Slf4j public class DistributedLockAop { @Autowired private LockInterface lockInstance; @Pointcut("@annotation(com.py.common.lock.annotatiop.YLock)") public void annotationPoinCut(){} /** * 先考虑正常的, TODO 再处理异常的 * @param joinPoint */ @Around(value = "annotationPoinCut()") public void around(ProceedingJoinPoint joinPoint) { //获得YLock注解中的值 MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); YLock yLock = methodSignature.getMethod().getAnnotation(YLock.class); int paramIndex = yLock.lockParamIndex(); String keyName = yLock.paramKeyName(); int exTime = yLock.existence(); LockType lockType = yLock.lockType(); try { if(!yLock.value()) { joinPoint.proceed(); return; } //获得请求的参数 Object[] args = joinPoint.getArgs(); //TODO 如果没有参数, yonyou设置的需要自定义 tenand_id if(args == null || args.length == 0 || args.length - 1 < paramIndex) { joinPoint.proceed(); return; } String keyValue = null; if(args[paramIndex].getClass().isPrimitive()||this.isBasePackage(args[paramIndex].getClass().getName())) { //基础类型 keyValue = args[paramIndex].toString(); }else if(args[paramIndex] instanceof Map) { //map Map map = (Map)args[paramIndex]; keyValue = map.get(keyName).toString(); }else { //自定义类型, 转json, 当前只能一层 String jsonStr = JSON.toJSONString(args[paramIndex]); JSONObject jsonObject = JSON.parseObject(jsonStr); keyValue = jsonObject.get(keyName).toString(); } //判断锁类型 if(LockType.IS_LOCKED == lockType) { boolean locked = lockInstance.isLocked(keyName); if(locked) { throw new LockException("获取锁失败, 请稍后重试."); }else { joinPoint.proceed(); return; } } boolean tryLock = lockInstance.tryLock(keyName, keyValue, exTime); if(!tryLock) { throw new LockException("获取锁失败, 请稍后重试."); } joinPoint.proceed(); } catch (Throwable throwable) { log.error("Distributed Locked Error. ", throwable); throw new RuntimeException(throwable.getMessage()); }finally { log.info("around finally."); //释放锁 if(LockType.TRY_LOCK == lockType) { lockInstance.unLock(keyName); } } log.info("around. after"); } /** * 〈是否为从基础包装类型〉 * @Param: [type] * @return : boolean */ private boolean isBasePackage(String type){ List<String> basePackages = Arrays.asList("java.lang.Integer","java.lang.Double","java.lang.Float","java.lang.Long", "java.lang.Short","java.lang.Boolean","java.lang.Char","java.math.BigDecimal","java.math.BigInteger"); return basePackages.contains(type); } /*@Before(value = "annotationPoinCut()") public void before(JoinPoint joinPoint) { log.info("before."); } @After(value = "annotationPoinCut()") public void after(JoinPoint joinPoint) { log.info("after."); } @AfterReturning(value = "annotationPoinCut()") public void afterReturning(JoinPoint joinPoint) { log.info("afterReturning."); } @AfterThrowing(value = "annotationPoinCut()") public void afterThrowing(JoinPoint joinPoint) { log.info("afterThrowing."); }*/ }
27.083333
118
0.706667
0afe71e11045549d4b5f6133b1d6830b976cfa76
11,825
package com.klemenz; import com.klemenz.Light.Light; import com.klemenz.Light.AmbientLight; import com.klemenz.Light.PointLight; import com.klemenz.Light.SpotLight; import com.klemenz.Light.ParallelLight; import com.klemenz.Surface.Sphere; import com.klemenz.Utility.Color; import com.klemenz.Utility.HitPoint; import com.klemenz.Utility.Ray; import com.klemenz.Utility.Vec3; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; public class RayTracer { private final double acneRemovalSensitivity = 0.001; public RayTracer() { } public void renderScene(Scene scene) { System.out.printf("\n\n===== Rendering %s =====%n", scene.getOutputFile()); render(scene, scene.getCamera()); } public void renderDefaultScene() { System.out.println("\n\n===== Rendering Default Scene ====="); Scene defaultScene = new Scene("defaultScene.png"); Camera camera = defaultScene.getCamera(); defaultScene.addSurface(new Sphere(new Vec3(-0.6,0.0,-1.0), 0.5, new Color(1.0, 0, 0))); defaultScene.addSurface(new Sphere(new Vec3(0.6,0.0,-1.0), 0.5, new Color(0, 0, 1.0))); defaultScene.addLight(new AmbientLight(new Color(1.0, 1.0, 1.0))); defaultScene.addLight(new ParallelLight(new Color(1.0, 1.0, 1.0), new Vec3(0.0, -1.0, 0.0))); render(defaultScene, camera); } public void renderBlackImage() { System.out.println("\n\n===== Rendering Empty Scene ====="); Scene emptyScene = new Scene("blackImage.png"); Camera camera = emptyScene.getCamera(); render(emptyScene, camera); } private void render(Scene scene, Camera camera) { int imageWidth = camera.getImageWidth(); int imageHeight = camera.getImageHeight(); int[][] pixelArray = new int[imageHeight][imageWidth]; // Calculate Pixel Values int lastPercentage = -1; for(int i = imageHeight - 1; i >= 0; i--) { // Calculate & print current progress int currentPercentage = Math.round((1 - ((float) i / (imageHeight - 1))) * 100); if(currentPercentage != lastPercentage) { lastPercentage = currentPercentage; System.out.printf("Progress: %s%%%n", currentPercentage); } // Calculate and set the color for the individual pixels for(int j = 0; j < imageWidth; j++) { // Inspired by the book "Ray Tracing in One Weekend" // https://raytracing.github.io/books/RayTracingInOneWeekend.html#rays,asimplecamera,andbackground/sendingraysintothescene // ##################################################################################################### double hOffset = (double) j / (imageWidth - 1); double vOffset = (double) i / (imageHeight - 1); Ray ray = camera.calculateRay(hOffset, vOffset); // ##################################################################################################### Color pixelColor = calculateRayColor(ray, scene, scene.getCamera().getMaxBounces()); pixelArray[(imageHeight - 1) - i][j] = pixelColor.getRGB(); } } // Export Pixel Array as Image exportPixelArrayAsImage(pixelArray, imageWidth, imageHeight, scene.getOutputFile()); } private Color calculateRayColor(Ray ray, Scene scene, int remainingBounces) { HitPoint hitPoint = new HitPoint(); if(scene.checkForIntersection(ray, hitPoint, acneRemovalSensitivity, Double.POSITIVE_INFINITY)) { /*// Debugging Code for visualizing the Surface Normals Vec3 temp = Vec3.scale(Vec3.add(hitPoint.normal, new Vec3(1.0, 1.0, 1.0)), 0.5); Color color = new Color(temp.getX(), temp.getY(), temp.getZ());*/ Color color = applyShading(ray.getDirection(), hitPoint, scene); color = Color.multiply(color, 1 - hitPoint.reflectance - hitPoint.transmittance); // Reflection if(hitPoint.reflectance > 0 && remainingBounces > 0) { Vec3 normal = Vec3.unitVector(hitPoint.normal); Vec3 reflectionDir = Vec3.subtract(ray.getDirection(), Vec3.scale(normal, 2 * Vec3.dot(ray.getDirection(), normal))); Ray reflectionRay = new Ray(hitPoint.position, reflectionDir); Color colorReflection = calculateRayColor(reflectionRay, scene, remainingBounces - 1); colorReflection = Color.multiply(colorReflection, hitPoint.reflectance); color = Color.add(color, colorReflection); } // Refraction if(hitPoint.transmittance > 0 && remainingBounces > 0) { Ray refractionRay; Vec3 v = Vec3.unitVector(ray.getDirection()); Vec3 n = Vec3.unitVector(hitPoint.normal); double c = Vec3.dot(v, n); double r = hitPoint.isOnFrontFace ? 1.0 / hitPoint.refractionIOF : hitPoint.refractionIOF; double D = 1 - Math.pow(r, 2) * (1 - Math.pow(c, 2)); if(D < 0) { // Total Internal Reflection // Need to calculate the reflection ray. Vec3 reflectionDir = Vec3.subtract(v, Vec3.scale(n, 2 * c)); refractionRay = new Ray(hitPoint.position, reflectionDir); } else { Vec3 refractionDir = Vec3.subtract(Vec3.scale(Vec3.add(Vec3.scale(n, -c), v), r), Vec3.scale(n, Math.sqrt(D))); refractionRay = new Ray(hitPoint.position, refractionDir); } Color colorRefraction = calculateRayColor(refractionRay, scene, remainingBounces - 1); colorRefraction = Color.multiply(colorRefraction, hitPoint.transmittance); color = Color.add(color, colorRefraction); } return color; } return scene.getBackgroundColor(); } private Color applyShading(Vec3 rayDirection, HitPoint hitPoint, Scene scene) { Vec3 pointColor = new Vec3(hitPoint.color.getR(), hitPoint.color.getG(), hitPoint.color.getB()); Vec3 finalColor; Vec3 ambient = new Vec3(); Vec3 diffuse = new Vec3(); Vec3 specular = new Vec3(); for(Light light : scene.getLights()) { Color lightColor = light.getColor(); Vec3 vLightColor = new Vec3(lightColor.getR(), lightColor.getG(), lightColor.getB()); if(!(light instanceof AmbientLight)) { Vec3 L; double distanceToLight; // Point Light if(light instanceof PointLight) { Vec3 pointToLight = Vec3.subtract(((PointLight) light).getPosition(), hitPoint.position); L = Vec3.unitVector(pointToLight); distanceToLight = Vec3.length(pointToLight); } // Spot Light else if(light instanceof SpotLight) { // TODO: Implement Phong Shading for spot lights L = new Vec3(); distanceToLight = 1; } // Parallel Light else { L = Vec3.negate(Vec3.unitVector(((ParallelLight) light).getDirection())); distanceToLight = Double.POSITIVE_INFINITY; } // Calculate Shading Components Ray shadowRay = new Ray(hitPoint.position, L); if (!scene.checkForIntersection(shadowRay, new HitPoint(), acneRemovalSensitivity, distanceToLight)) { Vec3 negatedL = Vec3.negate(L); Vec3 N = Vec3.unitVector(hitPoint.normal); Vec3 R = Vec3.unitVector(Vec3.subtract(negatedL, Vec3.scale(N, 2 * Vec3.dot(negatedL, N)))); Vec3 E = Vec3.unitVector(Vec3.negate(rayDirection)); diffuse = Vec3.add(diffuse, Vec3.multiply(Vec3.scale(vLightColor, Math.max(0.0, Vec3.dot(L, N))), pointColor)); specular = Vec3.add(specular, Vec3.scale(vLightColor, Math.pow(Math.max(Vec3.dot(R, E), 0.0), hitPoint.phongValues[3]))); } } // Ambient Light else { ambient = Vec3.multiply(vLightColor, pointColor); } } ambient = Vec3.scale(ambient, hitPoint.phongValues[0]); diffuse = Vec3.scale(diffuse, hitPoint.phongValues[1]); specular = Vec3.scale(specular, hitPoint.phongValues[2]); finalColor = Vec3.add(ambient, Vec3.add(diffuse, specular)); return new Color(Math.min(finalColor.getX(), 1.0), Math.min(finalColor.getY(), 1.0), Math.min(finalColor.getZ(), 1.0)); } private void exportPixelArrayAsImage(int[][] pixelArray, int width, int height, String filename) { // Flatten the Pixel Array int[] pixels = Arrays.stream(pixelArray) .flatMapToInt(Arrays::stream) .toArray(); // Inspired by the Answer from "Brendan Cashman" on StackOverflow // https://stackoverflow.com/a/125013/11889326 // ############################################################################################################# BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); WritableRaster raster = image.getRaster(); raster.setDataElements(0, 0, width, height, pixels); // ############################################################################################################# // Write BufferedImage to File try { String fileExtension = filename.split("\\.")[1]; File outputFile = new File(String.format("..%soutput%s%s", Main.osSeparator, Main.osSeparator, filename)); ImageIO.write(image, fileExtension, outputFile); } catch(IOException e) { e.printStackTrace(); } } // ######################################### // ######### Implemented Effects ########### // ######################################### private Color applyDepthOfField(Vec3 rayDirection, Scene scene, Color pixelColor) { int amountAdditionalRays = 4; Vec3 finalColor = new Vec3(pixelColor.getR(), pixelColor.getG(), pixelColor.getB()); //Vec3 direction = Vec3.scale(rayDirection, scene.getCamera().getFocalLength()); Vec3 direction = Vec3.scale(rayDirection, scene.getCamera().getFocalLength()); for(int i = 0; i < amountAdditionalRays; i++) { // Calculate random point "o" within a circle around the center of projection double r = Math.sqrt(Math.random()); double theta = Math.random() * 2 * Math.PI; double x = scene.getCamera().getPosition().getX() + r * Math.cos(theta); double y = scene.getCamera().getPosition().getY() + r * Math.sin(theta); Vec3 o = new Vec3(x, y, scene.getCamera().getPosition().getZ()); // Calculate new DoF ray Vec3 d = Vec3.subtract(direction, o); Ray rayDoF = new Ray(o, d); Color color = calculateRayColor(rayDoF, scene, scene.getCamera().getMaxBounces()); finalColor = Vec3.add(finalColor, new Vec3(color.getR(), color.getG(), color.getB())); } finalColor = Vec3.scale(finalColor, 1.0 / (amountAdditionalRays + 1)); return new Color(finalColor.getX(), finalColor.getY(), finalColor.getZ()); } }
44.622642
141
0.567357
bd3b4b7ce5f10be69a50f92b024918b358aeed47
990
package com.shiva.UploadFile.DaoImpl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.transaction.Transactional; import org.springframework.stereotype.Repository; import com.shiva.UploadFile.IDao.IUploadDao; import com.shiva.UploadFile.model.User; @Repository public class UploadDaoImpl implements IUploadDao { @PersistenceContext private EntityManager entityManager; @Transactional public void saveUser(User user) { entityManager.persist(user); } public List<User> getAllUsers() { TypedQuery<User> query = entityManager.createQuery("from User",User.class); List<User> userList =query.getResultList(); return userList; } @Transactional public void deleteUser(String id) { entityManager.remove(getUserById(id)); } public User getUserById(String id) { return entityManager.find(User.class, Integer.parseInt(id)); } }
17.678571
82
0.766667
8bb794661a7c934838223f1d34edb2a449bf6b05
2,073
package questao28; import java.util.Scanner; public class Questao28 { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); Scanner sc = new Scanner(System.in); int idade; int i = 1; float altura,peso; int qtd = 0; int qtd_altura = 0; int qtd_pena = 0; float soma_altura = 0; float media_altura = 0; float porcent = 0; String nome; do { System.out.print("Nome: "); nome = teclado.nextLine(); System.out.print("Idade: "); idade = sc.nextInt(); System.out.print("Altura: "); altura = sc.nextFloat(); System.out.print("Peso: "); peso = sc.nextFloat(); if (idade > 50) { qtd++; } else if ((idade >=10) && idade <= 20){ qtd_altura++; soma_altura += altura; media_altura = (soma_altura / qtd_altura); } else if (peso < 40) { qtd_pena++; porcent = (float)(qtd_pena * 0.01); } i++; } while (i <= 15) ; System.out.println("Quantidade de pessoas com mais de 50 anos: "+qtd); System.out.println(""); System.out.printf("Média das alturas das pessoas com idade entre 10 e 20 anos: %.2f \n",media_altura); System.out.println(""); System.out.println("Porcentagem de pessoas com peso inferior à 40kg: "+(int)(porcent*100)+"%"); System.out.println(""); } } /* Faça um algoritmo que receba a idade, a altura e o peso de 15 pessoas. Calcule e imprima: a) a quantidade de pessoas com idade superior a 50 anos; b) a média das alturas das pessoas com idade entre 10 e 20 anos; c) a porcentagem de pessoas com peso inferior a 40 quilos entre todas as pessoas analisadas. */
25.280488
110
0.499276
3609c3df0a3328cf83ae6bf56d7059b7a4572a77
6,086
/********************************************************************** Copyright (c) 2013 Andy Jefferson and others. All rights reserved. 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. Contributors: ... **********************************************************************/ package org.datanucleus.flush; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.datanucleus.ExecutionContext; import org.datanucleus.exceptions.NucleusOptimisticException; import org.datanucleus.state.ObjectProvider; import org.datanucleus.util.Localiser; import org.datanucleus.util.NucleusLogger; /** * Flush process that processes the objects in the order that they became dirty. * If a datastore uses referential integrity this is typically the best way of maintaining a valid update process. */ public class FlushOrdered implements FlushProcess { /* (non-Javadoc) * @see org.datanucleus.FlushProcess#execute(org.datanucleus.ExecutionContext, java.util.Collection, java.util.Collection, org.datanucleus.flush.OperationQueue) */ public List<NucleusOptimisticException> execute(ExecutionContext ec, Collection<ObjectProvider> primaryOPs, Collection<ObjectProvider> secondaryOPs, OperationQueue opQueue) { // Note that opQueue is not processed directly here, but instead will be processed via callbacks from the persistence of other objects // TODO The opQueue needs to be processed from here instead of via the callbacks, see NUCCORE-904 List<NucleusOptimisticException> optimisticFailures = null; // Make copy of ObjectProviders so we don't have ConcurrentModification issues Object[] toFlushPrimary = null; Object[] toFlushSecondary = null; try { if (ec.getMultithreaded()) // Why lock here? should be on overall flush { ec.getLock().lock(); } if (primaryOPs != null) { toFlushPrimary = primaryOPs.toArray(); primaryOPs.clear(); } if (secondaryOPs != null) { toFlushSecondary = secondaryOPs.toArray(); secondaryOPs.clear(); } } finally { if (ec.getMultithreaded()) { ec.getLock().unlock(); } } if (NucleusLogger.PERSISTENCE.isDebugEnabled()) { int total = 0; if (toFlushPrimary != null) { total += toFlushPrimary.length; } if (toFlushSecondary != null) { total += toFlushSecondary.length; } NucleusLogger.PERSISTENCE.debug(Localiser.msg("010003", total)); } Set<Class> classesToFlush = null; if (ec.getNucleusContext().getStoreManager().getQueryManager().getQueryResultsCache() != null) { classesToFlush = new HashSet(); } // a). primary dirty objects if (toFlushPrimary != null) { for (int i = 0; i < toFlushPrimary.length; i++) { ObjectProvider op = (ObjectProvider) toFlushPrimary[i]; try { op.flush(); if (classesToFlush != null && op.getObject() != null) { classesToFlush.add(op.getObject().getClass()); } } catch (NucleusOptimisticException oe) { if (optimisticFailures == null) { optimisticFailures = new ArrayList(); } optimisticFailures.add(oe); } } } // b). secondary dirty objects if (toFlushSecondary != null) { for (int i = 0; i < toFlushSecondary.length; i++) { ObjectProvider op = (ObjectProvider) toFlushSecondary[i]; try { op.flush(); if (classesToFlush != null && op.getObject() != null) { classesToFlush.add(op.getObject().getClass()); } } catch (NucleusOptimisticException oe) { if (optimisticFailures == null) { optimisticFailures = new ArrayList(); } optimisticFailures.add(oe); } } } if (opQueue != null) { if (!ec.getStoreManager().usesBackedSCOWrappers()) { // This ExecutionContext is not using backing store SCO wrappers, so process SCO Operations for cascade delete etc. opQueue.processOperationsForNoBackingStoreSCOs(ec); } opQueue.clearPersistDeleteUpdateOperations(); } if (classesToFlush != null) { // Flush any query results from cache for these types Iterator<Class> queryClsIter = classesToFlush.iterator(); while (queryClsIter.hasNext()) { Class cls = queryClsIter.next(); ec.getNucleusContext().getStoreManager().getQueryManager().evictQueryResultsForType(cls); } } return optimisticFailures; } }
35.590643
176
0.552251
1bf3dc6e8adaa17c478e0cf0af91da2b5045b57b
693
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package com.aws.greengrass.secretmanager; public class Result<T> { private boolean set; private T value; public Result() { } public Result(T t) { this.value = t; this.set = true; } /** * Set the value. * * @param t new value * @return this */ public synchronized Result<T> set(T t) { this.value = t; this.set = true; this.notifyAll(); return this; } public boolean isSet() { return set; } public T getValue() { return value; } }
16.902439
69
0.541126
4f8d6d6ecdad836d7de67ce151a42ca533abd1a0
5,757
package com.sheng.one_sheng.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.text.Html; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.sheng.one_sheng.R; import com.sheng.one_sheng.bean.Read; import com.sheng.one_sheng.ui.LoadDialog; import com.sheng.one_sheng.util.HttpCallbackListener; import com.sheng.one_sheng.util.HttpUtil; import com.sheng.one_sheng.util.Utilty; import static com.sheng.one_sheng.Contents.COMMENT_NEXT; import static com.sheng.one_sheng.Contents.READ_COMMENT_PRE; import static com.sheng.one_sheng.Contents.READ_DETAIL_NEXT; import static com.sheng.one_sheng.Contents.READ_DETAIL_PRE; public class ReadDetailActivity extends CommentActivity { private ScrollView mSlreadLayout; private TextView mTvTitle; private TextView mTvAuthor; private TextView mTvUpdateDate; private TextView mTvForward; private TextView mTvEssayContent; private TextView mTvAuthorName; private TextView mTvAuthorDesc; private TextView mTvAuthorFans; private TextView mTvPraiseNum; private TextView mTvShareNum; private TextView mTvCommentNum; private LoadDialog mDialog; /** * 用于启动这个活动的方法 * @param context */ public static void actionStart(Context context, String itemId){ Intent intent = new Intent(context, ReadDetailActivity.class); intent.putExtra("item_id", itemId); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_read_detail); changeStatusBar(); Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar.setTitle(""); //将原本的标题栏清空,而用一个新的TextView代替 setSupportActionBar(mToolbar); mDialog = LoadDialog.showDialog(ReadDetailActivity.this); mDialog.show(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null){ actionBar.setDisplayHomeAsUpEnabled(true); //显示返回按钮 actionBar.setHomeAsUpIndicator(R.drawable.ic_back); //显示返回图片 } //初始化各控件 mSlreadLayout = (ScrollView) findViewById(R.id.read_detail_layout); mTvTitle = (TextView) findViewById(R.id.tv_title); mTvAuthor = (TextView) findViewById(R.id.tv_author); mTvUpdateDate = (TextView) findViewById(R.id.tv_update_date); mTvForward = (TextView) findViewById(R.id.tv_forward); mTvEssayContent = (TextView) findViewById(R.id.tv_essay_content); mTvAuthorName = (TextView) findViewById(R.id.tv_author_name); mTvAuthorDesc = (TextView) findViewById(R.id.tv_author_desc); mTvAuthorFans = (TextView) findViewById(R.id.tv_fans_num); mTvPraiseNum = (TextView) findViewById(R.id.tv_praise_num); mTvShareNum = (TextView) findViewById(R.id.tv_share_num); mTvCommentNum = (TextView) findViewById(R.id.tv_comment_num); final String itemId; itemId = getIntent().getStringExtra("item_id"); mSlreadLayout.setVisibility(View.INVISIBLE); //请求数据的时候先将ScrollView隐藏,不然空数据的界面看上去会很奇怪 requestReadDetail(itemId); String url = READ_COMMENT_PRE + itemId + COMMENT_NEXT; requestCommentList(url); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: onBackPressed(); break; default: break; } return true; } /** * 根据itemId获取装有文章详细内容数据的对象 * @param itemId */ private void requestReadDetail(final String itemId){ Log.d("ReadDetailActivity", "传递之后详细内容id为:" + itemId); String url = READ_DETAIL_PRE + itemId + READ_DETAIL_NEXT; HttpUtil.sendHttpRequest(url, new HttpCallbackListener() { @Override public void onFinish(String response) { final String responseText = response; final Read read = Utilty.handleReadDetailResponse(responseText); runOnUiThread(new Runnable() { @Override public void run() { if (read != null){ showReadInfo(read); //内容显示 } else { Toast.makeText(ReadDetailActivity.this, "请求失败,请检查网络是否可用", Toast.LENGTH_SHORT).show(); } } }); } @Override public void onError(Exception e) { e.printStackTrace(); } }); } /** * 将数据展示在界面上 * @param read */ private void showReadInfo(Read read){ mTvTitle.setText(read.getTitle()); mTvAuthor.setText("文 / " + read.getUserName()); mTvUpdateDate.setText(read.getUpdateDate()); mTvForward.setText(read.getGuideWord()); mTvEssayContent.setText(Html.fromHtml(read.getContent())); mTvAuthorName.setText(read.getUserName()); mTvAuthorDesc.setText(read.getDes()); mTvAuthorFans.setText(read.getFansTotal() + "关注"); mTvPraiseNum.setText(read.getPraiseNum() + ""); mTvShareNum.setText(read.getShareNum() + ""); mTvCommentNum.setText(read.getCommentNum() + ""); mSlreadLayout.setVisibility(View.VISIBLE); mDialog.dismiss(); } }
35.757764
113
0.649991
3af1cf25eaab1b26cd4622bee14211d41985646a
4,478
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.service.modules.restli; import java.io.IOException; import java.util.Properties; import com.google.common.collect.Maps; import com.linkedin.data.template.StringMap; import org.apache.gobblin.service.FlowConfig; import org.apache.gobblin.service.FlowId; import org.apache.gobblin.service.Schedule; import org.apache.gobblin.util.PropertiesUtils; public class FlowConfigUtils { private static final String FLOWCONFIG = "fc"; private static final String FLOWCONFIG_ID = FLOWCONFIG + '-' + "id"; private static final String FLOWCONFIG_ID_NAME = FLOWCONFIG_ID + '-' + "name"; private static final String FLOWCONFIG_ID_GROUP = FLOWCONFIG_ID + '-' + "group"; private static final String FLOWCONFIG_SCHEDULE = FLOWCONFIG + '-' + "sch"; private static final String FLOWCONFIG_SCHEDULE_CRON = FLOWCONFIG_SCHEDULE + '-' + "cron"; private static final String FLOWCONFIG_SCHEDULE_RUN_IMMEDIATELY = FLOWCONFIG_SCHEDULE + '-' + "runImmediately"; private static final String FLOWCONFIG_TEMPLATEURIS = FLOWCONFIG + '-' + "templateUris"; public static String serializeFlowId(FlowId id) throws IOException { Properties properties = new Properties(); properties.setProperty(FLOWCONFIG_ID_NAME, id.getFlowName()); properties.setProperty(FLOWCONFIG_ID_GROUP, id.getFlowGroup()); return PropertiesUtils.serialize(properties); } public static FlowId deserializeFlowId(String serialized) throws IOException { Properties properties = PropertiesUtils.deserialize(serialized); FlowId id = new FlowId(); id.setFlowName(properties.getProperty(FLOWCONFIG_ID_NAME)); id.setFlowGroup(properties.getProperty(FLOWCONFIG_ID_GROUP)); return id; } public static String serializeFlowConfig(FlowConfig flowConfig) throws IOException { Properties properties = new Properties(); properties.putAll(flowConfig.getProperties()); properties.setProperty(FLOWCONFIG_ID_NAME, flowConfig.getId().getFlowName()); properties.setProperty(FLOWCONFIG_ID_GROUP, flowConfig.getId().getFlowGroup()); if (flowConfig.hasSchedule()) { properties.setProperty(FLOWCONFIG_SCHEDULE_CRON, flowConfig.getSchedule().getCronSchedule()); properties.setProperty(FLOWCONFIG_SCHEDULE_RUN_IMMEDIATELY, Boolean.toString(flowConfig.getSchedule().isRunImmediately())); } if (flowConfig.hasTemplateUris()) { properties.setProperty(FLOWCONFIG_TEMPLATEURIS, flowConfig.getTemplateUris()); } return PropertiesUtils.serialize(properties); } public static FlowConfig deserializeFlowConfig(String serialized) throws IOException { Properties properties = PropertiesUtils.deserialize(serialized); FlowConfig flowConfig = new FlowConfig().setId(new FlowId() .setFlowName(properties.getProperty(FLOWCONFIG_ID_NAME)) .setFlowGroup(properties.getProperty(FLOWCONFIG_ID_GROUP))); if (properties.containsKey(FLOWCONFIG_SCHEDULE_CRON)) { flowConfig.setSchedule(new Schedule() .setCronSchedule(properties.getProperty(FLOWCONFIG_SCHEDULE_CRON)) .setRunImmediately(Boolean.valueOf(properties.getProperty(FLOWCONFIG_SCHEDULE_RUN_IMMEDIATELY)))); } if (properties.containsKey(FLOWCONFIG_TEMPLATEURIS)) { flowConfig.setTemplateUris(properties.getProperty(FLOWCONFIG_TEMPLATEURIS)); } properties.remove(FLOWCONFIG_ID_NAME); properties.remove(FLOWCONFIG_ID_GROUP); properties.remove(FLOWCONFIG_SCHEDULE_CRON); properties.remove(FLOWCONFIG_SCHEDULE_RUN_IMMEDIATELY); properties.remove(FLOWCONFIG_TEMPLATEURIS); flowConfig.setProperties(new StringMap(Maps.fromProperties(properties))); return flowConfig; } }
42.647619
129
0.771773
4de6a66d168c5e685ee7228dd837c981b11229ec
745
package com.imooc.view; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class GuideFragment extends Fragment { final static String LAYOUT_ID = "layoutid"; public static GuideFragment newInstance(int layoutId) { GuideFragment pane = new GuideFragment(); Bundle args = new Bundle(); args.putInt(LAYOUT_ID, layoutId); pane.setArguments(args); return pane; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(getArguments().getInt(LAYOUT_ID, -1), container, false); return rootView; } }
24.833333
104
0.766443
d783f57ca0430bebb38e56e65cdf256fc72abb5a
589
package com.doc.manager.domain; import lombok.Data; import javax.persistence.*; import java.io.Serializable; @Entity(name = "TemplateDocument") @Table(name = "template_document") @Data public class TemplateDocument implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "file_name") private String fileName; @Column(name = "content_type") private String contentType; private String data; @ManyToOne @JoinColumn(name = "created_by") private Account createdBy; }
21.814815
55
0.709677
ac5755693867406ac894e863e9ed013865adf968
1,508
package com.softwareverde.bitcoin.transaction.input; import com.softwareverde.security.hash.sha256.Sha256Hash; import com.softwareverde.bitcoin.util.bytearray.ByteArrayReader; import com.softwareverde.util.Util; /** * Is functionally the same as a regular TransactionInputInflater, however additional checks are in place to assert * that the inflated transaction is indeed a coinbase transaction. * If these additional assertions fail, null is returned. */ public class CoinbaseTransactionInputInflater extends TransactionInputInflater { public static Boolean isCoinbaseInput(final TransactionInput transactionInput) { if (! Util.areEqual(transactionInput.getPreviousOutputTransactionHash(), Sha256Hash.EMPTY_HASH)) { return false; } // TODO: Validate the following rules are applied since BlockHeight 0... // if (transactionInput.getPreviousOutputIndex() != 0xFFFFFFFF) { return false; } // if (transactionInput.getUnlockingScript().getByteCount() > 100) { return false; } // TODO: Check if the signature script includes a blockHeight value (as of Transaction v2)... return true; } @Override protected MutableTransactionInput _fromByteArrayReader(final ByteArrayReader byteArrayReader) { final MutableTransactionInput transactionInput = super._fromByteArrayReader(byteArrayReader); if (! CoinbaseTransactionInputInflater.isCoinbaseInput(transactionInput)) { return null; } return transactionInput; } }
45.69697
122
0.763926
5c2e4b496e0c64419f1fee99e5f09506627358f3
1,179
package com.yffd.easy.bcap.workflow.service; import org.activiti.engine.FormService; import org.activiti.engine.HistoryService; import org.activiti.engine.RepositoryService; import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @Description 简单描述该类的功能(可选). * @Date 2018年7月24日 上午9:52:17 <br/> * @author zhangST * @version 1.0 * @since JDK 1.7+ * @see */ @Service public class WfBaseService { @Autowired private RepositoryService repositoryService; @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private FormService formService; @Autowired private HistoryService historyService; public RepositoryService getRepositoryService() { return repositoryService; } public RuntimeService getRuntimeService() { return runtimeService; } public TaskService getTaskService() { return taskService; } public FormService getFormService() { return formService; } public HistoryService getHistoryService() { return historyService; } }
23.117647
62
0.77693
1b6327c745514f4c0897dab4cbe9659d03e9c180
1,178
package com.xiwan.NettyGamer.cache; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.function.Consumer; import com.xiwan.NettyGamer.entity.RequestData; import io.netty.channel.ChannelHandlerContext; import lombok.Getter; import lombok.Setter; public class Actor { @Setter @Getter private String uniqueID; @Setter @Getter private Future<Boolean> currentTask; private final int REQUEST_QUEUE_LENGTH = 2048; @Getter private BlockingQueue<RequestData> requestQueue = new ArrayBlockingQueue<RequestData>(REQUEST_QUEUE_LENGTH); public void PushRequest(int ticket, int actionType, Consumer<RequestData> action, ChannelHandlerContext socketContext) { RequestData rd = new RequestData(); rd.setTicket(ticket); rd.setActionType(actionType); rd.setSocketContext(socketContext); PushRequest(rd); } public boolean PushRequest(RequestData rd) { if (requestQueue.remainingCapacity() < Math.round(REQUEST_QUEUE_LENGTH * 0.2)) { return false; } return requestQueue.offer(rd); } }
26.177778
122
0.766553
21f4a4589637dbc893303ed8e74c8b6d0a93bfc3
476
package com.ivan1pl.witchcraft.context.annotations; import java.lang.annotation.*; /** * Configuration value will be assigned to the parameter annotated with this annotation. If the assignment is not * possible, an exception will be thrown (in case of commands, the command will fail). */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ConfigurationValue { /** * Configuration key. */ String value(); }
26.444444
113
0.743697
8f7ac4ef9874cb57d9e03da9997050930cd299b2
2,588
package fr.moderncraft.sql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.bukkit.entity.Player; public class Main_Sql { private Connection conn; private Map_Sql map; public Main_Sql(String url, String user, String passwd, String bdd) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection("jdbc:mysql://"+url+"/"+bdd, user, passwd); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } map = new Map_Sql(this); } public boolean isNewPlayer(Player p){ Statement state; try { state = conn.createStatement(); ResultSet result = state.executeQuery("SELECT player FROM stats WHERE player = '"+p.getUniqueId().toString()+"'"); if(!result.next()){ return true; } } catch (SQLException e) { } return false; } public void addPlayer(Player p){ Statement state; try { state = conn.createStatement(); state.executeUpdate("INSERT INTO `stats` (`player`, `kills`, `deaths`) VALUES ('"+p.getUniqueId().toString()+"', '0', '0')"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public int getKills(Player p){ Statement state; try { state = conn.createStatement(); ResultSet result = state.executeQuery("SELECT kills FROM stats WHERE player = '"+p.getUniqueId().toString()+"'"); result.next(); return result.getInt("kills"); } catch (SQLException e) { } return 0; } public int getDeaths(Player p){ Statement state; try { state = conn.createStatement(); ResultSet result = state.executeQuery("SELECT death FROM stats WHERE player = '"+p.getUniqueId().toString()+"'"); result.next(); return result.getInt("death"); } catch (SQLException e) { } return 0; } public void playerKilled(Player p){ Statement state; String uuid = p.getUniqueId().toString(); int score = p.getScoreboard().getObjective("stats").getScore("kills").getScore(); try { state = conn.createStatement(); state.executeUpdate("UPDATE stats SET kills = "+getKills(p)+score+" WHERE player = '"+uuid+"'"); state.executeUpdate("UPDATE stats SET death = "+getDeaths(p)+1+" WHERE player = '"+uuid+"'"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Map_Sql getMap() { return map; } public Connection getConn() { return conn; } }
24.647619
128
0.668083
c37f60ddc633a328744487dbb35b0d34f42633c9
4,574
package com.barbearia; import java.time.LocalDate; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.barbearia.model.Agenda; import com.barbearia.model.Cliente; import com.barbearia.model.Fornecedor; import com.barbearia.model.Funcionario; import com.barbearia.model.Horario; import com.barbearia.model.Produto; import com.barbearia.model.Saida; import com.barbearia.model.Servico; import com.barbearia.repository.AgendaRepository; import com.barbearia.repository.ClienteRepositoy; import com.barbearia.repository.FornecedorRepository; import com.barbearia.repository.FuncionarioRepositoy; import com.barbearia.repository.HorarioRepository; import com.barbearia.repository.ProdutoRepository; import com.barbearia.repository.SaidaRepository; import com.barbearia.repository.ServicoRepository; @SpringBootApplication public class BarbeariaMdApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(BarbeariaMdApplication.class, args); } @Autowired AgendaRepository agendaRepository; @Autowired FuncionarioRepositoy funcionarioRepositoy; @Autowired HorarioRepository horarioRepository; @Autowired ServicoRepository servicoRepository; @Autowired ClienteRepositoy clienteRepository; @Autowired FornecedorRepository fornecedorRepository; @Autowired SaidaRepository saidaRepository; @Autowired ProdutoRepository produtoRepository; @Override public void run(String... args) throws Exception { Horario horario1 = new Horario("08:00"); Horario horario2 = new Horario("08:30"); Horario horario3 = new Horario("09:00"); Horario horario4 = new Horario("09:30"); horarioRepository.saveAll(Arrays.asList(horario1, horario2, horario3, horario4)); Funcionario funcionario1 = new Funcionario(100.2, "Dinho", "barbeiro", LocalDate.of(2020, 10, 27)); Funcionario funcionario2 = new Funcionario(50.0, "Marcelo", "barbeiro", LocalDate.of(2020, 10, 30)); funcionario1.getHorarios().addAll(Arrays.asList(horario1, horario2, horario3, horario4)); funcionarioRepositoy.saveAll(Arrays.asList(funcionario1, funcionario2)); Servico servico1 = new Servico("social", 20.00); servicoRepository.saveAll(Arrays.asList(servico1)); Servico servico2 = new Servico("degradê", 20.00); servicoRepository.saveAll(Arrays.asList(servico2)); Cliente cliente1 = new Cliente("Willian P", "Mora na facec", "44988888888", "[email protected]"); clienteRepository.saveAll(Arrays.asList(cliente1)); Cliente cliente2 = new Cliente("Osvaldo pescador", "Cianorte", "44998765843", "[email protected]"); clienteRepository.saveAll(Arrays.asList(cliente2)); Fornecedor fornecedor1 = new Fornecedor("Xaulim matador de porco", "Kotlin", "987848174", "[email protected]"); fornecedorRepository.saveAll(Arrays.asList(fornecedor1)); Fornecedor fornecedor2 = new Fornecedor("Zezin do pneu", "Kotlin", "987848174", "[email protected]"); fornecedorRepository.saveAll(Arrays.asList(fornecedor2)); Agenda agenda1 = new Agenda(funcionario1, cliente1, LocalDate.now(), horario1, servico1); Agenda agenda2 = new Agenda(funcionario1, cliente2, LocalDate.of(2021, 04, 24), horario2, servico1); Agenda agenda3 = new Agenda(funcionario2, cliente1, LocalDate.of(2021, 04, 24), horario3, servico1); Agenda agenda4 = new Agenda(funcionario1, cliente2, LocalDate.now(), horario4, servico1); Agenda agenda5 = new Agenda(funcionario1, cliente1, LocalDate.of(2021, 04, 24), horario1, servico1); Agenda agenda6 = new Agenda(funcionario2, cliente2, LocalDate.now(), horario1, servico1); Agenda agenda7 = new Agenda(funcionario1, cliente1, LocalDate.of(2021, 04, 24), horario1, servico1); Agenda agenda8 = new Agenda(funcionario2, cliente1, LocalDate.now(), horario1, servico1); agendaRepository.saveAll(Arrays.asList(agenda1, agenda2, agenda3, agenda4, agenda5, agenda6, agenda7, agenda8)); Produto produto1 = new Produto("Navalha"); produtoRepository.saveAll(Arrays.asList(produto1)); Produto produto2 = new Produto("Creme de barbear"); produtoRepository.saveAll(Arrays.asList(produto2)); Saida saida1 = new Saida(fornecedor1, produto1, 78.80, 3, (78.80 * 3), LocalDate.now()); saidaRepository.saveAll(Arrays.asList(saida1)); Saida saida2 = new Saida(fornecedor1, produto1, 20.80, 4, (20.80 * 4), LocalDate.now()); saidaRepository.saveAll(Arrays.asList(saida2)); } }
42.351852
114
0.783559
558a9925a4fafbe4f74394d9100d1666125e82bd
56
package inheritance; interface Foo { String foo(); }
9.333333
20
0.696429
00a5cfb9c1f5e2238a13782c109da6a8e66b030d
1,199
package org.facedamon.config; import com.netflix.loadbalancer.*; import org.springframework.cloud.netflix.ribbon.StaticServerList; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; /** * @author damon * @desc 手动指定listOfServers * @date 2021/6/16 */ @Configuration public class UserRibbonConfiguration { /** * @author damon * @desc 构建固定的服务器列表 * @date 13:54 2021/6/16 **/ @Bean public ServerList<Server> ribbonServerList() { List<Server> list = new ArrayList<>(); list.add(new Server("http://127.0.0.1:2100")); list.add(new Server("http://127.0.0.1:2110")); return new StaticServerList<>(list.toArray(new Server[0])); } /** * @author damon * @desc 将服务器存活探测策略更改为通过URL来判定 * @date 13:53 2021/6/16 **/ @Bean public IPing ribbonPing() { return new PingUrl(false, "/cs/hostRunning"); } /** * @author damon * @desc 负载均衡策略定义未区域感知策略 * @date 13:53 2021/6/16 **/ @Bean public IRule ribbonRule() { return new ZoneAvoidanceRule(); } }
23.057692
67
0.634696
824f70812c88c99e5efd4c737e372255496a5312
4,756
package dh.mygrades.view.activity; import android.os.Bundle; import android.os.Parcelable; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator; import com.h6ah4i.android.widget.advrecyclerview.animator.RefactoredDefaultItemAnimator; import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager; import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils; import dh.mygrades.R; import dh.mygrades.view.adapter.FaqExpandableItemAdapter; import dh.mygrades.view.adapter.dataprovider.FaqDataProvider; /** * Fragment to show Frequently Asked Questions in an expandable RecyclerView. */ public class FragmentFaq extends Fragment { private static final String SAVED_STATE_EXPANDABLE_ITEM_MANAGER = "RecyclerViewExpandableItemManager"; private RecyclerView recyclerView; private RecyclerView.LayoutManager layoutManager; private RecyclerView.Adapter wrappedAdapter; private RecyclerViewExpandableItemManager recyclerViewExpandableItemManager; // if this is set, the value (an integer) will be used // to determine which question should be expanded public static final String ARGUMENT_GO_TO_QUESTION = "attribute_go_to_question"; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_faq, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // restore state if necessary final Parcelable eimSavedState = (savedInstanceState != null) ? savedInstanceState.getParcelable(SAVED_STATE_EXPANDABLE_ITEM_MANAGER) : null; recyclerViewExpandableItemManager = new RecyclerViewExpandableItemManager(eimSavedState); // create data FaqDataProvider faqDataProvider = new FaqDataProvider(); faqDataProvider.populateData(getContext()); // create adapter FaqExpandableItemAdapter itemAdapter = new FaqExpandableItemAdapter(faqDataProvider); wrappedAdapter = recyclerViewExpandableItemManager.createWrappedAdapter(itemAdapter); // set animation stuff final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator(); animator.setSupportsChangeAnimations(false); // init recycler view layoutManager = new LinearLayoutManager(getContext()); recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(wrappedAdapter); // requires *wrapped* adapter recyclerView.setItemAnimator(animator); recyclerView.setHasFixedSize(false); // set divider // recyclerView.addItemDecoration(new SimpleListDividerDecorator(ContextCompat.getDrawable(getContext(), R.drawable.grade_divider), true)); // attach recycler view to item manager, necessary for touch listeners recyclerViewExpandableItemManager.attachRecyclerView(recyclerView); // jump to specific question if ARGUMENT_GO_TO_QUESTION is provided if (getArguments() != null) { int argumentQuestionId = getArguments().getInt(ARGUMENT_GO_TO_QUESTION); int groupId = faqDataProvider.getGroupId(argumentQuestionId); recyclerViewExpandableItemManager.expandGroup(groupId); recyclerView.scrollToPosition(groupId); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // save state if (recyclerViewExpandableItemManager != null) { outState.putParcelable(SAVED_STATE_EXPANDABLE_ITEM_MANAGER, recyclerViewExpandableItemManager.getSavedState()); } } @Override public void onDestroyView() { if (recyclerViewExpandableItemManager != null) { recyclerViewExpandableItemManager.release(); recyclerViewExpandableItemManager = null; } if (recyclerView != null) { recyclerView.setItemAnimator(null); recyclerView.setAdapter(null); recyclerView = null; } if (wrappedAdapter != null) { WrapperAdapterUtils.releaseAll(wrappedAdapter); } layoutManager = null; super.onDestroyView(); } }
39.633333
149
0.743482
111d4f63763e4c2acdfe0461bcf30af61ee36e42
7,005
package squarerock.hoot.fragments; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.codepath.apps.restclienttemplate.R; import com.loopj.android.http.TextHttpResponseHandler; import org.parceler.Parcels; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import cz.msebera.android.httpclient.Header; import squarerock.hoot.Hoot; import squarerock.hoot.TwitterClient; import squarerock.hoot.activities.SearchActivity; import squarerock.hoot.activities.TweetDetailActivity; import squarerock.hoot.activities.UserTimelineActivity; import squarerock.hoot.adapters.MentionsAdapter; import squarerock.hoot.adapters.TweetAdapter; import squarerock.hoot.listeners.EndlessRecyclerViewScrollListener; import squarerock.hoot.models.MentionsModel; import squarerock.hoot.models.TweetModel; import squarerock.hoot.models.TwitterTimeline; import squarerock.hoot.utils.Utility; /** * Created by pranavkonduru on 11/4/16. */ public class MentionsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, TweetAdapter.TweetClickCallback { @BindView(R.id.rv_mentions) RecyclerView rvMentions; @BindView(R.id.swipeMentions) SwipeRefreshLayout swipeRefreshLayout; private TwitterClient twitterClient; private MentionsAdapter adapter; private EndlessRecyclerViewScrollListener scrollListener; private Snackbar snackbar; private static final String TAG = "MentionsFragment"; public MentionsFragment() {} public static MentionsFragment getInstance(){ return new MentionsFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mentions, container, false); ButterKnife.bind(this, view); initRecyclerView(); swipeRefreshLayout.setOnRefreshListener(this); twitterClient = Hoot.getRestClient(); snackbar = Snackbar.make(rvMentions, "Network not available. Try again later", Snackbar.LENGTH_INDEFINITE); snackbar.setAction("OK",null); return view; } private void initRecyclerView() { adapter = new MentionsAdapter(new ArrayList<TweetModel>(), this); LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); scrollListener = new EndlessRecyclerViewScrollListener(layoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { Log.d(TAG, "onLoadMore: "+page); fetchMentions(-1, MentionsModel.getSinceId(), MentionsModel.getMaxId(), false); } }; rvMentions.setLayoutManager(layoutManager); rvMentions.addOnScrollListener(scrollListener); rvMentions.setAdapter(adapter); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated: "); fetchMentions(0, -1, -1, false); } private void fetchMentions(int page, long sinceId, long maxId, final boolean isRefreshing) { if(Utility.isNetworkAvailable(getContext())) { Log.d(TAG, "fetchMentions: Network available. Fetching mentions"); if(snackbar.isShown()) snackbar.dismiss(); if(!swipeRefreshLayout.isRefreshing()){ swipeRefreshLayout.setRefreshing(true); } twitterClient.getMentionTweets(page, sinceId, maxId, new TextHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { Log.e(TAG, "onFailure: ",throwable.getCause()); } @Override public void onSuccess(int statusCode, Header[] headers, String responseString) { List<TweetModel> tweets = TwitterTimeline.parseJSON(responseString).getTweets(); for (int i = 0; i < tweets.size(); i++) { tweets.get(i).user.save(); tweets.get(i).save(); // Save mentions new MentionsModel(tweets.get(i).id).save(); } if(isRefreshing){ adapter.clearAll(); } adapter.update(tweets); if(swipeRefreshLayout.isRefreshing()){ swipeRefreshLayout.setRefreshing(false); } } }); } else { if(swipeRefreshLayout.isRefreshing()){ swipeRefreshLayout.setRefreshing(false); } Log.d(TAG, "fetchTweets: Network unavailable. Fetching from database"); adapter.clearAll(); adapter.update(MentionsModel.getAllMentions()); snackbar.show(); } } @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume: "); } @Override public void onRefresh() { scrollListener.resetState(); fetchMentions(0, -1, -1, true); } @Override public void onTweetClicked(TweetModel tweet) { Log.d(TAG, "onTweetClicked: "+tweet.text); Intent intent = new Intent(getActivity(), TweetDetailActivity.class); intent.putExtra("Tweet", Parcels.wrap(TweetModel.class, tweet)); startActivity(intent); } @Override public void onUserProfileClicked(String screenName) { Log.d(TAG, "onUserProfileClicked: "+screenName); Intent intent = new Intent(getActivity(), UserTimelineActivity.class); intent.putExtra("screen_name", screenName); startActivity(intent); } @Override public void onHashTagClicked(String hashtag) { Log.d(TAG, "onHashTagClicked: "+hashtag); Intent intent = new Intent(getActivity(), SearchActivity.class); intent.putExtra("search_item", hashtag); startActivity(intent); } @Override public void onRetweet(int positionInAdapter, long tweetId, boolean isRetweeted) { Log.d(TAG, "onRetweet: "); } @Override public void onFavorite(int positionInAdapter, long tweetId, boolean isFavorited) { Log.d(TAG, "onFavorite: "); } }
34.678218
129
0.666809
7cfdfe4702c04751eb7cda54541235d7495f1490
5,289
package yuku.alkitab.yes2.compress; import yuku.alkitab.yes2.io.RandomAccessFileRandomInputStream; import yuku.alkitab.yes2.io.RandomInputStream; import yuku.bintex.ValueMap; import yuku.snappy.codec.Snappy; import java.io.IOException; public class SnappyInputStream extends RandomInputStream { public final String TAG = SnappyInputStream.class.getSimpleName(); private final RandomAccessFileRandomInputStream input; private final Snappy snappy; private final long baseOffset; private final int block_size; private final int[] compressed_block_sizes; private final int[] compressed_block_offsets; private int current_block_index = 0; private int current_block_skip = 0; private byte[] compressed_buf; private int uncompressed_block_index = -1; private byte[] uncompressed_buf; private int uncompressed_len = -1; // -1 means not initialized public SnappyInputStream(RandomAccessFileRandomInputStream input, long baseOffset, int block_size, int[] compressed_block_sizes, int[] compressed_block_offsets) throws IOException { this.input = input; this.block_size = block_size; this.snappy = new Snappy.Factory().newInstance(); this.baseOffset = baseOffset; this.compressed_block_sizes = compressed_block_sizes; this.compressed_block_offsets = compressed_block_offsets; this.compressed_buf = new byte[snappy.maxCompressedLength(block_size)]; this.uncompressed_buf = new byte[block_size]; } @Override public void seek(long n) throws IOException { int offset = (int) n; int block_index = offset / block_size; int block_skip = offset - (block_index * block_size); this.current_block_index = block_index; this.current_block_skip = block_skip; prepareBuffer(); } private void prepareBuffer() throws IOException { int block_index = current_block_index; // if uncompressed_block_index is already equal to the requested block_index // then we do not need to re-decompress again if (uncompressed_block_index != block_index) { input.seek(baseOffset + compressed_block_offsets[block_index]); input.read(compressed_buf, 0, compressed_block_sizes[block_index]); uncompressed_len = snappy.decompress(compressed_buf, 0, uncompressed_buf, 0, compressed_block_sizes[block_index]); if (uncompressed_len < 0) { throw new IOException("Error in decompressing: " + uncompressed_len); } uncompressed_block_index = block_index; } } @Override public int read() throws IOException { if (uncompressed_len == -1) { prepareBuffer(); } int can_read = uncompressed_len - current_block_skip; if (can_read == 0) { if (current_block_index >= compressed_block_sizes.length) { return -1; // EOF } else { // need to move to the next block current_block_index++; current_block_skip = 0; prepareBuffer(); } } int res = /* need to convert to uint8: */ 0xff & uncompressed_buf[current_block_skip]; current_block_skip++; return res; } @Override public int read(byte[] buffer, int offset, int length) throws IOException { if (uncompressed_len == -1) { prepareBuffer(); } int res = 0; int want_read = length; while (want_read > 0) { int can_read = uncompressed_len - current_block_skip; if (can_read == 0) { if (current_block_index >= compressed_block_sizes.length) { // EOF if (res == 0) return -1; // we didn't manage to read any return res; } else { // need to move to the next block current_block_index++; current_block_skip = 0; prepareBuffer(); can_read = uncompressed_len; } } int will_read = want_read > can_read? can_read: want_read; System.arraycopy(uncompressed_buf, current_block_skip, buffer, offset, will_read); current_block_skip += will_read; offset += will_read; want_read -= will_read; res += will_read; } return res; } @Override public int read(byte[] buffer) throws IOException { return read(buffer, 0, buffer.length); } @Override public long getFilePointer() throws IOException { return current_block_index * block_size + current_block_skip; } @Override public long skip(long n) throws IOException { seek(getFilePointer() + n); return n; } public static SnappyInputStream getInstanceFromAttributes(RandomAccessFileRandomInputStream input, ValueMap sectionAttributes, long sectionContentOffset) throws IOException { int compressionVersion = sectionAttributes.getInt("compression.version", 0); if (compressionVersion > 1) { throw new IOException("Compression version " + compressionVersion + " is not supported"); } ValueMap compressionInfo = sectionAttributes.getSimpleMap("compression.info"); int block_size = compressionInfo.getInt("block_size"); int[] compressed_block_sizes = compressionInfo.getIntArray("compressed_block_sizes"); int[] compressed_block_offsets = new int[compressed_block_sizes.length + 1]; { // convert compressed_block_sizes into offsets int c = 0; for (int i = 0, len = compressed_block_sizes.length; i < len; i++) { compressed_block_offsets[i] = c; c += compressed_block_sizes[i]; } compressed_block_offsets[compressed_block_sizes.length] = c; } return new SnappyInputStream(input, sectionContentOffset, block_size, compressed_block_sizes, compressed_block_offsets); } }
35.02649
182
0.744375
cdfd2566adfb4a075a27ca2f670858acc0939ecc
259
package LightQuestion; public class GarageDoorlightOffCommand implements Command { GarageDoor garagedoor; public GarageDoorlightOffCommand(GarageDoor garagedoor) { this.garagedoor = garagedoor; } public void execute() { garagedoor.lightOff(); } }
18.5
59
0.783784
dba4c2f408cccd2edbc97d0acbe0709769aa5f5d
642
package introwork; import org.junit.Test; import core.ChromeDriverTest; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.io.File; /** * 入門課題その5:「チェックボックスを選択してみよう」 * 解答例 */ public class IntroWork5Test extends ChromeDriverTest { @Test public void testClickCheckbox() throws Exception { File html = new File("introwork/introWork5.html"); String url = html.toURI().toString(); driver.get(url); WebElement allowedCheck = driver.findElement(By.id("allowed_check")); if (!allowedCheck.isSelected()) { allowedCheck.click(); } } }
23.777778
77
0.665109