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
1e448707630a69c36e29b36b15f3c6164a7c76e9
2,446
package seedu.address.testutil.batch; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.address.model.drink.Batch; import seedu.address.model.drink.UniqueBatchList; /** * A utility class containing a list of {@code Batch} objects to be used in tests. */ public class TypicalBatches { // In inventory list public static final Batch COKE1 = new BatchBuilder().withId("100000002").withQuantity("40") .withDate("01/10/2018").build(); public static final Batch COKE2 = new BatchBuilder().withId("100000003").withQuantity("20") .withDate("15/10/2018").build(); public static final Batch COKE3 = new BatchBuilder().withId("100000004").withQuantity("30") .withDate("01/11/2018").build(); public static final Batch COKE4 = new BatchBuilder().withId("100000005").withQuantity("50") .withDate("04/11/2018").build(); public static final Batch COKE5 = new BatchBuilder().withId("100000006").withQuantity("80") .withDate("11/11/2018").build(); public static final Batch COKE6 = new BatchBuilder().withId("100000007").withQuantity("90") .withDate("30/09/2018").build(); // Manually added // Same id as COKE4 to test for duplicates; public static final Batch COKE7 = new BatchBuilder().withId("100000005").withQuantity("70") .withDate("29/10/2018").build(); public static final Batch COKE8 = new BatchBuilder().withId("100000010").withQuantity("80") .withDate("28/10/2018").build(); // Same date as COKE4 to test for compiling of batches public static final Batch COKE9 = new BatchBuilder().withId("100000008").withQuantity("70") .withDate("04/11/2018").build(); // Batch with no quantity public static final Batch COKE10 = new BatchBuilder().withId("100000009").withQuantity("0") .withDate("05/11/2018").build(); private TypicalBatches() { } // prevents instantiation /** * Returns an {@code } with all the typical persons. */ public static UniqueBatchList getTypicalUniqueBatchList() { UniqueBatchList ubl = new UniqueBatchList(); for (Batch batch :getTypicalBatches()) { ubl.addBatch(batch); } return ubl; } public static List<Batch> getTypicalBatches() { return new ArrayList<>(Arrays.asList(COKE1, COKE2, COKE3, COKE4, COKE5, COKE6)); } }
41.457627
95
0.66067
f33e846e796ea832b5973c0846039682c0bf0954
2,551
package edu.udel.cis.vsl.abc.ast.type.IF; import edu.udel.cis.vsl.abc.ast.entity.IF.TaggedEntity; /** * An enumeration type. An enumeration type consists of a key, a tag, and a * sequence of enumerators. The key is used to determine when two enumeration * types are equal. Each enumerator consists of an identifier and an optional * constant expression. * * @author siegel */ public interface EnumerationType extends IntegerType, TaggedEntity { /** * Returns the key associated to this instance. The key is used in the * determination of equality of two instances of EnumerationType. * * @return the key */ Object getKey(); /** * Returns the tag of this enumeration type. This is the string used in the * declaration of the type, i.e., in "enum foo {...}", "foo" is the tag. * * @return the tag of this enumeration type */ String getTag(); /** * Returns the number of enumerators specified in this enumeration type. * * @exception RuntimeException * if the type is not complete, i.e., the enumerators have * not yet been specified * * @return the number of enumerators in the type */ int getNumEnumerators(); /** * Returns the index-th enumerator defined in the type. * * @param index * an integer between 0 and the number of enumerators minus 1, * inclusive * @return the index-th enumerator * * @exception RuntimeException * if the type is not complete */ Enumerator getEnumerator(int index); /** * Returns the sequence of enumerators for this enumerated type. Each * enumerator consists of a name and optional constant expression. If the * optional constant expression is absent, it will be null. * * This will return <code>null</code> if the type is incomplete, i.e., the * enumerators have not yet been specified * * @return the sequence node for the enumerators of this type, or * <code>null</code> */ Iterable<Enumerator> getEnumerators(); /** * Completes this enumeration type by specifying the contents of the type, * i.e., the list or enumerator constants. * * @param enumerators * an ordered list of enumerators which comprise the type * * @exception RuntimeException * if the type is already complete */ void complete(Iterable<Enumerator> enumerators); /** * Makes this type incomplete, i.e., sets the enumerators to * <code>null</code>. */ void clear(); @Override EnumerationType getType(); }
28.662921
77
0.674637
0c2ca2785b3d38c6fba6af9551dc4364841b7a4e
354
import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; @ObfuscatedName("j") public class class23 { @ObfuscatedName("s") @ObfuscatedGetter( intValue = -1564129527 ) static int field134; @ObfuscatedName("gm") @Export("regionMapArchives") static byte[][] regionMapArchives; }
22.125
45
0.771186
04d04af8757a1fe8467f785aec53afc54347175c
333
package io.kyberorg.example.dao; import io.kyberorg.example.model.Record; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * DAO object for {@link Record} model. * * @since 1.1 */ @Repository public interface RecordDao extends CrudRepository<Record, Integer> { }
22.2
68
0.777778
7e55ec99a676a9553cfb58c75cc39c721cc6164f
3,915
package ru.sonic.zabbix.pro.adapters; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import ru.sonic.zabbix.pro.R; import ru.sonic.zabbix.pro.base.Host; @SuppressWarnings("deprecation") class SliderAdapterView extends LinearLayout { public SliderAdapterView(Context context,int position, String host ) { super(context); //this.setOrientation(HORIZONTAL); this.setBackgroundColor(Color.DKGRAY); WindowManager mWinMgr = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); int displayWidth = mWinMgr.getDefaultDisplay().getWidth(); TextView hostControl = new TextView( context ); //hostControl.setTextAppearance( context, R.style.HostList ); hostControl.setPadding(40, 30, 10, 30); hostControl.setTextColor(Color.WHITE); hostControl.setTextSize(16); hostControl.setTypeface(null, Typeface.BOLD); hostControl.setText(host); /* LayoutParams imgParams = new LayoutParams(40, 40 ); imgParams.setMargins(10, 30, 5, 30); switch (position) { case 0: addView(getImage(context, R.drawable.attention), imgParams); break; case 1: addView(getImage(context, R.drawable.icon), imgParams); break; case 2: addView(getImage(context, R.drawable.config_bb), imgParams); break; case 3: addView(getImage(context, R.drawable.ic_drawer), imgParams); break; case 4: addView(getImage(context, R.drawable.chart), imgParams); break; case 5: addView(getImage(context, R.drawable.unknown_icon), imgParams); break; case 6: addView(getImage(context, R.drawable.map), imgParams); break; case 7: addView(getImage(context, R.drawable.graph), imgParams); break; } */ LayoutParams hostParams = new LayoutParams(displayWidth-128, LayoutParams.WRAP_CONTENT ); hostParams.setMargins(1, 1, 1, 1); addView( hostControl, hostParams); } public ImageView getImage(Context context, int id) { ImageView image = new ImageView(context); image.setImageResource(id); image.setAdjustViewBounds(true); image.setPadding(2, 1, 2, 1); image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); return image; } } public class SliderAdapter extends BaseAdapter { private Context context; private String[] hostList; public SliderAdapter(Context context, String[] hostList ) { this.context = context; this.hostList = hostList; } public int getCount() { return hostList.length; } public Object getItem(int position) { return hostList[position]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { String host = hostList[position]; return new SliderAdapterView(this.context, position, host); } }
34.646018
114
0.58825
8f183f2aa65b431f6cf23724665327f5689f53a1
1,621
package sonia.scm.api.v2.resources; import com.google.inject.util.Providers; import sonia.scm.repository.RepositoryManager; import javax.inject.Provider; public abstract class RepositoryTestBase { protected RepositoryToRepositoryDtoMapper repositoryToDtoMapper; protected RepositoryDtoToRepositoryMapper dtoToRepositoryMapper; protected RepositoryManager manager; protected Provider<TagRootResource> tagRootResource; protected Provider<BranchRootResource> branchRootResource; protected Provider<ChangesetRootResource> changesetRootResource; protected Provider<SourceRootResource> sourceRootResource; protected Provider<ContentResource> contentResource; protected Provider<RepositoryPermissionRootResource> permissionRootResource; protected Provider<DiffRootResource> diffRootResource; protected Provider<ModificationsRootResource> modificationsRootResource; protected Provider<FileHistoryRootResource> fileHistoryRootResource; protected Provider<RepositoryCollectionResource> repositoryCollectionResource; protected Provider<IncomingRootResource> incomingRootResource; RepositoryRootResource getRepositoryRootResource() { return new RepositoryRootResource(Providers.of(new RepositoryResource( repositoryToDtoMapper, dtoToRepositoryMapper, manager, tagRootResource, branchRootResource, changesetRootResource, sourceRootResource, contentResource, permissionRootResource, diffRootResource, modificationsRootResource, fileHistoryRootResource, incomingRootResource)), repositoryCollectionResource); } }
35.23913
80
0.82665
14a78409e0dc52823074b8a456a395c18c8c2718
285
package com.nekohit.neo.ozkens.model; public record SignedMessage( String message, // If other SDK cannot have this header // then we still need a public key to verify the signature byte header, String signature, String publicKey ) { }
23.75
66
0.645614
e5364c1dd69d06098c2f5dbd0f6ab955ed0b46ef
2,752
package com.nls.bank; import java.util.stream.IntStream; /** * Utility class to calculate the modulus */ public final class ModulusCalculator { private ModulusCalculator() { } /** * Calculate the modulus for a given set of digits and rule * @param digits the digits * @param rule the modulus alogrithm, weights and excpetions * @return the modulus */ public static int modulus(Digits digits, ModulusRule rule) { int[] weights = rule.getWeights(); return IntStream.range(0, 14) .flatMap(i -> rule.getMethod().getFunction().apply(digits.get(i) * weights[i])) .reduce(0, Integer::sum); } /** * Calculate the remainder of the modulus for a given set of digits and rule * @param digits the digits * @param rule the modulus alogrithm, weights and excpetions * @return the remainder */ public static int remainder(Digits digits, ModulusRule rule) { return remainder(digits, rule, 0); } /** * Calculate the remainder of the modulus for a given set of digits and rule * @param digits the digits * @param rule the modulus alogrithm, weights and excpetions * @param addToTotal a number to add to the modulus befor the remainder is taken * @return the remainder */ public static int remainder(Digits digits, ModulusRule rule, int addToTotal) { return (modulus(digits, rule) + addToTotal) % rule.getMethod().getModulus(); } /** * Calculate if the remainder is 0 for a given bank account and rule * @param bankAccount the bank account to validate * @param rule the modulus alogrithm, weights and excpetions * @return true if modulus remainder is 0, false otherwise */ public static boolean valid(BankAccount bankAccount, ModulusRule rule) { return valid(bankAccount.toDigits(), rule, 0); } /** * Calculate if the remainder is 0 for a given digits and rule * @param digits the digits * @param rule the modulus alogrithm, weights and excpetions * @return true if modulus remainder is 0, false otherwise */ public static boolean valid(Digits digits, ModulusRule rule) { return valid(digits, rule, 0); } /** * Calculate if the remainder is 0 for a given digits and rule * @param digits the digits * @param rule the modulus alogrithm, weights and excpetions * @param addToTotal a number to add to the modulus befor the remainder is taken * @return true if modulus remainder is 0, false otherwise */ public static boolean valid(Digits digits, ModulusRule rule, int addToTotal) { return remainder(digits, rule, addToTotal) == 0; } }
34.835443
95
0.663517
b05506d58bc73d3142029cd34241d38d704109cd
641
package com.neu.his.cloud.zuul.service.sms.impl; import com.neu.his.cloud.zuul.mapper.SmsRolePermissionDao; import com.neu.his.cloud.zuul.model.SmsPermission; import com.neu.his.cloud.zuul.service.sms.SmsRoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class SmsRoleServiceImpl implements SmsRoleService { @Autowired private SmsRolePermissionDao rolePermissionDao; @Override public List<SmsPermission> getPermissionList(Long roleId) { return rolePermissionDao.getPermissionList(roleId); } }
22.892857
63
0.795632
194f1a7a6ff7562f0d2e4bc07099e75c06c0a38b
3,359
/***************************************************************** * 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.cayenne.access; import org.apache.cayenne.di.Inject; import org.apache.cayenne.query.QueryCacheStrategy; import org.apache.cayenne.query.SelectQuery; import org.apache.cayenne.test.jdbc.DBHelper; import org.apache.cayenne.test.jdbc.TableHelper; import org.apache.cayenne.testdo.testmap.Artist; import org.apache.cayenne.unit.di.server.CayenneProjects; import org.apache.cayenne.unit.di.server.ServerCase; import org.apache.cayenne.unit.di.server.UseServerRuntime; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; @UseServerRuntime(CayenneProjects.TESTMAP_PROJECT) public class DataContextPaginatedQueryIT extends ServerCase { @Inject protected DataContext context; @Inject protected DBHelper dbHelper; protected TableHelper tArtist; @Before public void setUp() throws Exception { tArtist = new TableHelper(dbHelper, "ARTIST"); tArtist.setColumns("ARTIST_ID", "ARTIST_NAME"); } protected void createArtistsDataSet() throws Exception { tArtist.insert(33001, "artist1"); tArtist.insert(33002, "artist2"); tArtist.insert(33003, "artist3"); tArtist.insert(33004, "artist4"); tArtist.insert(33005, "artist5"); tArtist.insert(33006, "artist6"); tArtist.insert(33007, "artist7"); tArtist.insert(33008, "artist8"); tArtist.insert(33009, "artist9"); tArtist.insert(33010, "artist10"); } @Test public void testLocalCache() throws Exception { createArtistsDataSet(); SelectQuery<Artist> query = new SelectQuery<Artist>(Artist.class); query.addOrdering(Artist.ARTIST_NAME.asc()); query.setCacheStrategy(QueryCacheStrategy.LOCAL_CACHE); query.setPageSize(5); List<?> results1 = context.performQuery(query); assertNotNull(results1); List<?> results2 = context.performQuery(query); assertNotNull(results2); assertSame(results1, results2); results1.get(1); List<?> results3 = context.performQuery(query); assertNotNull(results3); assertSame(results1, results3); results1.get(7); List<?> results4 = context.performQuery(query); assertNotNull(results4); assertSame(results1, results4); } }
34.989583
74
0.682048
14c02da1adeaaf0316024710a5f62522ac47b51c
4,986
/** * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.http.signing.internal; import java.util.List; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; public class Constants { // Headers static final String AUTHORIZATION_HEADER = "authorization"; // Signing static final String REQUEST_TARGET = "(request-target)"; static final String DATE = "date"; static final String CONTENT_LENGTH = "content-length"; static final String CONTENT_TYPE = "content-type"; static final String X_CONTENT_SHA256 = "x-content-sha256"; public static final String HOST = "host"; // Optional public static final String CROSS_TENANCY_REQUEST_HEADER_NAME = "x-cross-tenancy-request"; static final String X_SUBSCRIPTION = "x-subscription"; public static final String OPC_OBO_TOKEN = "opc-obo-token"; static final String JSON_CONTENT_TYPE = "application/json"; public static final ImmutableList<String> GENERIC_HEADERS = ImmutableList.of(DATE, REQUEST_TARGET, HOST); public static final ImmutableList<String> BODY_HEADERS = ImmutableList.of(CONTENT_LENGTH, CONTENT_TYPE, X_CONTENT_SHA256); public static final ImmutableList<String> ALL_HEADERS = ImmutableList.<String>builder().addAll(GENERIC_HEADERS).addAll(BODY_HEADERS).build(); public static final ImmutableMap<String, List<String>> REQUIRED_SIGNING_HEADERS = createHeadersToSignMap( GENERIC_HEADERS, GENERIC_HEADERS, GENERIC_HEADERS, ALL_HEADERS, ALL_HEADERS, ALL_HEADERS); @Deprecated /** * A signing strategy that signs headers and body, except for PUT, where bodies are not signed * @deprecated use REQUIRED_EXCLUDE_BODY_SIGNING_HEADERS instead; Object Storage has migrated to using STANDARD, with EXCLUDE_BODY as a per-operation override. We therefore do not want to maintain a service-specific signing strategy. */ public static final ImmutableMap<String, List<String>> REQUIRED_OBJECTSTORAGE_SIGNING_HEADERS = createHeadersToSignMap( GENERIC_HEADERS, GENERIC_HEADERS, GENERIC_HEADERS, GENERIC_HEADERS, // PUT is special cased for object storage ALL_HEADERS, ALL_HEADERS); /** * A signing strategy that signs headers only. */ public static final ImmutableMap<String, List<String>> REQUIRED_EXCLUDE_BODY_SIGNING_HEADERS = createHeadersToSignMap( GENERIC_HEADERS, GENERIC_HEADERS, GENERIC_HEADERS, GENERIC_HEADERS, GENERIC_HEADERS, GENERIC_HEADERS); /** * Headers included in the signature if they are set. */ public static final ImmutableList<String> OPTIONAL_HEADERS_NAMES = ImmutableList.of(OPC_OBO_TOKEN, CROSS_TENANCY_REQUEST_HEADER_NAME, X_SUBSCRIPTION); public static final ImmutableMap<String, List<String>> OPTIONAL_SIGNING_HEADERS = createHeadersToSignMap( OPTIONAL_HEADERS_NAMES, OPTIONAL_HEADERS_NAMES, OPTIONAL_HEADERS_NAMES, OPTIONAL_HEADERS_NAMES, OPTIONAL_HEADERS_NAMES, OPTIONAL_HEADERS_NAMES); /** * Creates a map of headers to sign for each HTTP method. * @param getHeaders headers for GET requests * @param headHeaders headers for HEAD requests * @param deleteHeaders headers for DELETE requests * @param putHeaders headers for PUT requests * @param postHeaders headers for POST requests * @param patchHeaders headers for PATCH requests * @return A new immutable map of headers */ public static ImmutableMap<String, List<String>> createHeadersToSignMap( List<String> getHeaders, List<String> headHeaders, List<String> deleteHeaders, List<String> putHeaders, List<String> postHeaders, List<String> patchHeaders) { return ImmutableMap.<String, List<String>>builder() .put("get", getHeaders) .put("head", headHeaders) .put("delete", deleteHeaders) .put("put", putHeaders) .put("post", postHeaders) .put("patch", patchHeaders) .build(); } static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z"; }
42.254237
246
0.647413
24dfb27d9e66b7086d506ecdcb2322be1f51c359
2,629
package picard.illumina.parser.readers; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import picard.PicardException; import java.io.File; public class LocsFileReaderTest { private static final File TestDir = new File("testdata/picard/illumina/readerTests"); public static final File LocsFile = new File(TestDir, "s_1_6.locs"); public static final int ExpectedTile = 6; public static final int ExpectedLane = 1; public static final int NumValues = 200; public static final float [][] FloatCoords = { {1703.0117f, 64.01593f}, {1660.3038f, 64.08882f}, {1769.7501f, 65.12467f}, {1726.6725f, 68.367805f}, {1401.213f, 72.07282f}, {1358.2775f, 72.07892f}, {1370.5197f, 77.699715f}, {1661.5403f, 77.70719f}, {1682.0504f, 78.76725f}, {1563.8765f, 79.08009f} }; public static final int [][] QSeqCoords = { {18030, 1640}, {17603, 1641}, {18698, 1651}, {18267, 1684}, {15012, 1721}, {14583, 1721}, {14705, 1777}, {17615, 1777}, {17821, 1788}, {16639, 1791} }; public static final int [] Indices = { 0, 1, 19, 59, 100, 101, 179, 180, 198, 199 }; @Test public void passingFileTest() { final LocsFileReader reader = new LocsFileReader(LocsFile); int tdIndex = 0; int nextIndex = Indices[tdIndex]; for(int i = 0; i < NumValues; i++) { Assert.assertTrue(reader.hasNext()); final AbstractIlluminaPositionFileReader.PositionInfo piLocs = reader.next(); if(i == nextIndex) { PosFileReaderTest.comparePositionInfo(piLocs, FloatCoords[tdIndex][0], FloatCoords[tdIndex][1], QSeqCoords[tdIndex][0], QSeqCoords[tdIndex][1], ExpectedLane, ExpectedTile, i); if(tdIndex < Indices.length-1) { nextIndex = Indices[++tdIndex]; } } } Assert.assertFalse(reader.hasNext()); } @DataProvider(name = "invalidFiles") public Object[][]invalidFiles() { return new Object[][] { {"s_1_7.locs"}, {"s_1_8.locs"}, {"s_1_9.locs"}, {"s_1_10.locs"}, {"s_f2af.locs"} }; } @Test(expectedExceptions = PicardException.class, dataProvider = "invalidFiles") public void invalidFilesTest(final String fileName) { final LocsFileReader reader = new LocsFileReader(new File(TestDir, fileName)); } }
37.557143
134
0.585013
90c2ed3dd70f2a7227941221bf14e0dbcf9b1581
1,837
package com.lykke.tests.api.service.customer.model; import static com.lykke.tests.api.common.CommonConsts.EMPTY_PASSWORD_ERR_MSG; import static com.lykke.tests.api.common.CommonConsts.INVALID_PASSWORD_ERR; import static com.lykke.tests.api.common.CommonConsts.INVALID_PASSWORD_ERR_MSG; import static com.lykke.tests.api.common.CommonConsts.PASSWORD_REG_EX; import static com.lykke.tests.api.service.customer.model.VerificationCodeError.CUSTOMER_DOES_NOT_EXIST; import com.lykke.api.testing.annotations.NetClassName; import com.lykke.tests.api.common.model.ValidationErrorResponseModel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.val; import org.apache.commons.lang3.StringUtils; @AllArgsConstructor @Builder @Data @NetClassName("ResetPasswordRequestModel") public class ResetPasswordRequest { String password; String customerEmail; String resetIdentifier; private boolean isPasswordValid() { return password.matches(PASSWORD_REG_EX); } public ValidationErrorResponseModel getInvalidPasswordResponse() { val passwordErrMsg = StringUtils.EMPTY == password ? EMPTY_PASSWORD_ERR_MSG : INVALID_PASSWORD_ERR_MSG; val response = new ValidationErrorResponseModel(); response.setError(isPasswordValid() ? null : INVALID_PASSWORD_ERR); response.setMessage(isPasswordValid() ? null : passwordErrMsg); return response; } public ValidationErrorResponseModel getNonExistingCustomerResponse() { return ValidationErrorResponseModel .builder() .error(CUSTOMER_DOES_NOT_EXIST.getCode()) .message(CUSTOMER_DOES_NOT_EXIST.getMessage()) .build(); } }
34.660377
103
0.727273
d7478ad13dd884f314ef076b753aaad258b9cbf7
1,998
package lumien.randomthings.block; import java.util.Random; import lumien.randomthings.lib.ISuperLubricent; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockCompressedSlimeBlock extends BlockBase implements ISuperLubricent { protected static final AxisAlignedBB AABB = new AxisAlignedBB(0D, 0.0D, 0D, 1D, 0.5D, 1D); protected BlockCompressedSlimeBlock() { super("compressedSlimeBlock", Material.CLAY); this.setSoundType(SoundType.SLIME); } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return Item.getItemFromBlock(Blocks.SLIME_BLOCK); } @Override public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { return new ItemStack(Blocks.SLIME_BLOCK); } @Override public boolean isFullCube(IBlockState state) { return false; } @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public AxisAlignedBB getBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return AABB; } @Override @SideOnly(Side.CLIENT) public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos) { return AABB.offset(pos); } @Override public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { super.onEntityCollidedWithBlock(worldIn, pos, state, entityIn); if (entityIn.motionY < 1) { entityIn.onGround = false; entityIn.fallDistance = 0; entityIn.motionY = 1; } } }
24.666667
103
0.784284
b54280995eb9f8175fa7a277c5bb43308af50c82
473
package com.qingchi.server.model; import com.qingchi.base.model.user.UserImgDO; import lombok.Data; @Data public class UploadImgVO { private String src; private Double aspectRatio; public UploadImgVO(UserImgDO img) { this.src = img.getSrc(); this.aspectRatio = img.getAspectRatio(); } public UploadImgVO(String img, Integer width, Integer height) { this.src = img; this.aspectRatio = (double) width / height; } }
22.52381
67
0.672304
2e444752d0084032d5e51b923cd767793c88be23
1,462
package com.atlassian.clover.instr.java; import com.atlassian.clover.instr.Bindings; import com.atlassian.clover.registry.FixedSourceRegion; import com.atlassian.clover.registry.entities.FullMethodInfo; import com.atlassian.clover.registry.entities.MethodSignature; import com.atlassian.clover.spi.lang.LanguageConstruct; /** * Code emitter for lambda expressions declared as a code block in curly braces. * Emits code for the opening brace. */ public class LambdaBlockEntryEmitter extends Emitter { private MethodSignature signature; FullMethodInfo method; public LambdaBlockEntryEmitter(MethodSignature signature, int startLine, int startColumn) { super(startLine, startColumn); this.signature = signature; } @Override protected void init(InstrumentationState state) { if (state.isInstrEnabled()) { state.setDirty(); method = (FullMethodInfo) state.getSession().enterMethod(getElementContext(), new FixedSourceRegion(getLine(), getColumn()), signature, false, null, true, FullMethodInfo.DEFAULT_METHOD_COMPLEXITY, LanguageConstruct.Builtin.METHOD); StringBuilder instr = new StringBuilder(); instr.append(Bindings.$CoverageRecorder$inc(state.getRecorderPrefix(), Integer.toString(method.getDataIndex()))); instr.append(";"); setInstr(instr.toString()); } } }
37.487179
125
0.701778
bb6b07d2fd9b803d58663888df63e6c1fbf73cb4
129
package org.joda.time.convert; public interface DurationConverter extends Converter { long getDurationMillis(Object obj); }
21.5
54
0.79845
5318f733e573d2650c3529ff2bd14bd4712fe140
1,145
package uk.gov.cslearning.record.dto; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import uk.gov.cslearning.record.exception.UnknownStatusException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public enum CancellationReason { UNAVAILABLE("the event is no longer available"),VENUE("short notice unavailability of the venue"); private final String value; CancellationReason(String value) { this.value = value; } @JsonCreator public static CancellationReason forValue(String value) { return Arrays.stream(CancellationReason.values()) .filter(v -> v.value.equalsIgnoreCase(value)) .findAny() .orElseThrow(() -> new UnknownStatusException(value)); } public static Map<String, String> getKeyValuePairs(){ Map<String, String> map = new HashMap<>(); map.put("UNAVAILABLE", UNAVAILABLE.getValue()); map.put("VENUE", VENUE.getValue()); return map; } @JsonValue public String getValue() { return value; } }
27.926829
102
0.675109
90dece8947af4c451bf588cd01738931d4811651
1,272
package net.jackofalltrades.taterbot.service; import com.google.common.base.Strings; import org.springframework.jdbc.core.PreparedStatementSetter; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; class ChannelServiceInsertPreparedStatementSetter implements PreparedStatementSetter { private final ChannelService channelService; ChannelServiceInsertPreparedStatementSetter(ChannelService channelService) { this.channelService = channelService; } @Override public void setValues(PreparedStatement preparedStatement) throws SQLException { preparedStatement.setString(1, channelService.getChannelId()); preparedStatement.setString(2, channelService.getServiceCode()); preparedStatement.setString(3, channelService.getStatus().name().toLowerCase()); preparedStatement.setTimestamp(4, Timestamp.valueOf(channelService.getStatusDate())); if (Strings.isNullOrEmpty(channelService.getUserId())) { preparedStatement.setNull(5, Types.VARCHAR); } else { preparedStatement.setString(5, channelService.getUserId()); } } ChannelService getChannelService() { return channelService; } }
34.378378
93
0.753145
c17812a5c69675026a554ff2ee3ce9f3c23686ab
4,960
package me.legit.service; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.WriteBatch; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import me.legit.APICore; import me.legit.models.decoration.DecorationId; import me.legit.models.decoration.DecorationType; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DecorationService { private Map<Integer, JsonObject> decorations; private Map<Integer, JsonObject> structures; public DecorationService() { ClassLoader loader = getClass().getClassLoader(); this.decorations = new HashMap<>(); this.structures = new HashMap<>(); APICore.getLogger().info("Parsing decorations data..."); JsonArray decorationsJson = new JsonParser().parse(new InputStreamReader(loader.getResourceAsStream("Decorations.json"))).getAsJsonArray(); for (JsonElement decorationElement : decorationsJson) { JsonObject decorationObj = decorationElement.getAsJsonObject(); decorations.put(decorationObj.get("Id").getAsInt(), decorationObj); } APICore.getLogger().info("Parsing structures data..."); JsonArray structuresJson = new JsonParser().parse(new InputStreamReader(loader.getResourceAsStream("Structures.json"))).getAsJsonArray(); for (JsonElement structureElement : structuresJson) { JsonObject structureObj = structureElement.getAsJsonObject(); structures.put(structureObj.get("Id").getAsInt(), structureObj); } } public List<ApiFuture<String>> subtractDecorationCost(DocumentSnapshot snapshot, DecorationId decorationId, int count) { int cost = 0; DecorationType type = decorationId.getType(); if (!type.equals(DecorationType.DECORATION)) { if (type.equals(DecorationType.STRUCTURE)) { if (structures.containsKey(decorationId.getDefinitionId())) { cost = structures.get(decorationId.getDefinitionId()).get("Cost").getAsInt(); } } } else { if (decorations.containsKey(decorationId.getDefinitionId())) { cost = decorations.get(decorationId.getDefinitionId()).get("Cost").getAsInt(); } } List<ApiFuture<String>> transactions = new ArrayList<>(); Firestore db = snapshot.getReference().getFirestore(); WriteBatch batch = db.batch(); int newCost = cost * count; ApiFuture<String> coinTransaction = db.runTransaction(transaction -> { Long oldCoins = snapshot.getLong("assets.coins"); if (oldCoins != null) { if (oldCoins - newCost < 0) { transaction.update(snapshot.getReference(), "assets.coins", 0); return "assets.coins had a value of " + oldCoins + " but new coins will be negative (" + oldCoins + " - " + newCost + "), so updated with a new value of 0"; } else { transaction.update(snapshot.getReference(), "assets.coins", oldCoins - newCost); return "assets.coins had a value of " + oldCoins + ", updated with a new value of " + oldCoins + " - " + newCost + "!"; } } else { return "oldCoins == null (this should not happen) -- could not save new coin amount (" + newCost + ") for user " + snapshot.getId() + "!"; } }); transactions.add(coinTransaction); ApiFuture<String> currencyTransaction = db.runTransaction(transaction -> { Long oldCurrencyCoins = snapshot.getLong("assets.currency.coins"); if (oldCurrencyCoins != null) { if (oldCurrencyCoins - newCost < 0) { transaction.update(snapshot.getReference(), "assets.currency.coins", 0); return "assets.currency.coins had a value of " + oldCurrencyCoins + " but new coins will be negative (" + oldCurrencyCoins + " - " + newCost + "), so updated with a new value of 0"; } else { transaction.update(snapshot.getReference(), "assets.currency.coins", oldCurrencyCoins - newCost); return "assets.currency.coins had a value of " + oldCurrencyCoins + ", updated with a new value of " + oldCurrencyCoins + " - " + newCost + "!"; } } else { batch.update(snapshot.getReference(), "assets.currency.coins", newCost); return "assets.currency.coins was null, setting new value for coins = " + newCost; } }); transactions.add(currencyTransaction); return transactions; } }
46.792453
201
0.633065
d97d2f047cf4b5693ae01a11d6d9f46de1c31d1e
842
package com.easyt.constant; public class ApiMapping { public ApiMapping() {} public static final String API = "/api/"; public static final String CONTEXT = ""; public static final String PERMISSION = API + "permission"; public static final String MODERATOR = API + "moderator"; public static final String INSTITUTION = API + "institution"; public static final String DRIVER = API + "driver"; public static final String AUTHENTICATION = API + "authentication"; public static final String GENERAL_MANAGER = API + "generalManager"; public static final String NOTIFICATION = API + "notification"; public static final String SEND_MAIL = API + "sendMail"; public static final String STUDENT = API + "student"; public static final String USER = API + "user"; public static final String CROSS_ORIGEN = "*"; }
38.272727
70
0.719715
4b156019f466296a9cc38d78f77ebfd439f2fb6c
911
package org.gridkit.lab.jvm.attach; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import org.junit.Test; public class HeapDumpCheck { private int pid() { String name = ManagementFactory.getRuntimeMXBean().getName(); name = name.substring(0, name.indexOf("@")); return Integer.parseInt(name); } @Test public void checkAllDump() throws IOException { System.out.println(HeapDumper.dumpAll(pid(), "target/all-dump.hprof", 60000)); System.out.println("Dump size: " + (new File("target/all-dump.hprof").length() >> 10) + "k"); } @Test public void checkLiveDump() throws IOException { System.out.println(HeapDumper.dumpLive(pid(), "target/live-dump.hprof", 60000)); System.out.println("Dump size: " + (new File("target/live-dump.hprof").length() >> 10) + "k"); } }
30.366667
102
0.649835
4f1c8c2c468ef284485d1a20eb3a2de014401a1b
2,385
package org.onetwo.common.concurrent; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Executor; import java.util.stream.Stream; import com.google.common.collect.Lists; /***** * ConcurrentRunnable.create(parties, ()->{ //run task }) .start() .await(); * @author way * */ public class ConcurrentRunnable { public static ConcurrentRunnable create(int threadSize, Runnable runnable){ return create(null, threadSize, runnable); } public static ConcurrentRunnable create(Executor executor, int threadSize, Runnable runnable){ return new ConcurrentRunnable(executor).concurrentRun(threadSize, runnable); } /**** * 主线程等待一组线程里的每个线程countDown */ private CountDownLatch latch; /*** * 并通过CyclicBarrier把所有的线程阻塞到任务执行之前,直到所有线程都准备好 * 线程互相等待 */ private CyclicBarrier barrier; private volatile boolean started; private List<Runnable> runnables = Lists.newArrayList(); private Executor executor; private ConcurrentRunnable(Executor executor) { this.executor = executor; } public ConcurrentRunnable concurrentRun(int concurrentSize, Runnable runnable){ for (int i = 0; i < concurrentSize; i++) { this.runnables.add(runnable); } return this; } public ConcurrentRunnable addRunnables(Runnable... runnables){ Stream.of(runnables).forEach(r->this.runnables.add(r)); return this; } /**** * 启动所有线程 * @author wayshall * @return */ public ConcurrentRunnable start(){ int size = runnables.size(); latch = new CountDownLatch(size); barrier = new CyclicBarrier(size); runnables.stream().forEach(r->{ Runnable newRunable = ()->{ try { barrier.await(); } catch (Exception e) { throw new RuntimeException("barrier await error!", e); } r.run(); latch.countDown(); }; if(executor!=null){ executor.execute(newRunable); }else{ new Thread(newRunable).start(); } }); started = true; return this; } /**** * 等待所有线程任务执行完 * @author wayshall */ public void await(){ if(!started) throw new RuntimeException("ConcurrentRunnable has not started!"); try { // 调用CountDownLatch的await方法等待,CyclicBarrier没有类似方法,CyclicBarrier的await方法会减少计数 this.latch.await(); } catch (InterruptedException e) { throw new RuntimeException("CountDownLatch await error!", e); } } }
22.714286
95
0.703145
4df3732433fbb3ba2d4f672bbd023acb6da31ae0
9,270
/* * Copyright 2019-2020 The Polypheny 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. * * This file incorporates code covered by the following terms: * * 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.polypheny.db.sql.validate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.polypheny.db.rel.type.RelDataType; import org.polypheny.db.rel.type.RelDataTypeField; import org.polypheny.db.rel.type.StructKind; import org.polypheny.db.sql.SqlNode; import org.polypheny.db.util.Pair; import org.polypheny.db.util.Static; import org.polypheny.db.util.Util; /** * Abstract base for a scope which is defined by a list of child namespaces and which inherits from a parent scope. */ public abstract class ListScope extends DelegatingScope { /** * List of child {@link SqlValidatorNamespace} objects and their names. */ public final List<ScopeChild> children = new ArrayList<>(); public ListScope( SqlValidatorScope parent ) { super( parent ); } @Override public void addChild( SqlValidatorNamespace ns, String alias, boolean nullable ) { Objects.requireNonNull( alias ); children.add( new ScopeChild( children.size(), alias, ns, nullable ) ); } /** * Returns an immutable list of child namespaces. * * @return list of child namespaces */ public List<SqlValidatorNamespace> getChildren() { return Lists.transform( children, scopeChild -> scopeChild.namespace ); } /** * Returns an immutable list of child names. * * @return list of child namespaces */ List<String> getChildNames() { return Lists.transform( children, scopeChild -> scopeChild.name ); } private ScopeChild findChild( List<String> names, SqlNameMatcher nameMatcher ) { for ( ScopeChild child : children ) { String lastName = Util.last( names ); if ( child.name != null ) { if ( !nameMatcher.matches( child.name, lastName ) ) { // Alias does not match last segment. Don't consider the fully-qualified name. E.g. // SELECT sales.emp.name FROM sales.emp AS otherAlias continue; } if ( names.size() == 1 ) { return child; } } // Look up the 2 tables independently, in case one is qualified with catalog & schema and the other is not. final SqlValidatorTable table = child.namespace.getTable(); if ( table != null ) { final ResolvedImpl resolved = new ResolvedImpl(); resolveTable( names, nameMatcher, Path.EMPTY, resolved ); if ( resolved.count() == 1 && resolved.only().remainingNames.isEmpty() && resolved.only().namespace instanceof TableNamespace && resolved.only().namespace.getTable().getQualifiedName().equals( table.getQualifiedName() ) ) { return child; } } } return null; } @Override public void findAllColumnNames( List<SqlMoniker> result ) { for ( ScopeChild child : children ) { addColumnNames( child.namespace, result ); } parent.findAllColumnNames( result ); } @Override public void findAliases( Collection<SqlMoniker> result ) { for ( ScopeChild child : children ) { result.add( new SqlMonikerImpl( child.name, SqlMonikerType.TABLE ) ); } parent.findAliases( result ); } @Override public Pair<String, SqlValidatorNamespace> findQualifyingTableName( final String columnName, SqlNode ctx ) { final SqlNameMatcher nameMatcher = validator.catalogReader.nameMatcher(); final Map<String, ScopeChild> map = findQualifyingTableNames( columnName, ctx, nameMatcher ); switch ( map.size() ) { case 0: throw validator.newValidationError( ctx, Static.RESOURCE.columnNotFound( columnName ) ); case 1: final Map.Entry<String, ScopeChild> entry = map.entrySet().iterator().next(); return Pair.of( entry.getKey(), entry.getValue().namespace ); default: throw validator.newValidationError( ctx, Static.RESOURCE.columnAmbiguous( columnName ) ); } } @Override public Map<String, ScopeChild> findQualifyingTableNames( String columnName, SqlNode ctx, SqlNameMatcher nameMatcher ) { final Map<String, ScopeChild> map = new HashMap<>(); for ( ScopeChild child : children ) { final ResolvedImpl resolved = new ResolvedImpl(); resolve( ImmutableList.of( child.name, columnName ), nameMatcher, true, resolved ); if ( resolved.count() > 0 ) { map.put( child.name, child ); } } switch ( map.size() ) { case 0: return parent.findQualifyingTableNames( columnName, ctx, nameMatcher ); default: return map; } } @Override public void resolve( List<String> names, SqlNameMatcher nameMatcher, boolean deep, Resolved resolved ) { // First resolve by looking through the child namespaces. final ScopeChild child0 = findChild( names, nameMatcher ); if ( child0 != null ) { final Step path = Path.EMPTY.plus( child0.namespace.getRowType(), child0.ordinal, child0.name, StructKind.FULLY_QUALIFIED ); resolved.found( child0.namespace, child0.nullable, this, path, null ); return; } // Recursively look deeper into the record-valued fields of the namespace, if it allows skipping fields. if ( deep ) { for ( ScopeChild child : children ) { // If identifier starts with table alias, remove the alias. final List<String> names2 = nameMatcher.matches( child.name, names.get( 0 ) ) ? names.subList( 1, names.size() ) : names; resolveInNamespace( child.namespace, child.nullable, names2, nameMatcher, Path.EMPTY, resolved ); } if ( resolved.count() > 0 ) { return; } } // Then call the base class method, which will delegate to the parent scope. super.resolve( names, nameMatcher, deep, resolved ); } @Override public RelDataType resolveColumn( String columnName, SqlNode ctx ) { final SqlNameMatcher nameMatcher = validator.catalogReader.nameMatcher(); int found = 0; RelDataType type = null; for ( ScopeChild child : children ) { SqlValidatorNamespace childNs = child.namespace; final RelDataType childRowType = childNs.getRowType(); final RelDataTypeField field = nameMatcher.field( childRowType, columnName ); if ( field != null ) { found++; type = field.getType(); } } switch ( found ) { case 0: return null; case 1: return type; default: throw validator.newValidationError( ctx, Static.RESOURCE.columnAmbiguous( columnName ) ); } } }
36.640316
121
0.598706
9498a93a23ff7f4be11c01eb5348900baabf85fd
4,914
// 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 com.cloud.api.commands; import javax.inject.Inject; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.agent.manager.SimulatorManager; import com.cloud.api.response.MockResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.simulator.MockConfigurationVO; import com.cloud.user.Account; @APICommand(name = "configureSimulator", description = "configure simulator", responseObject = MockResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ConfigureSimulatorCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ConfigureSimulatorCmd.class.getName()); private static final String s_name = "configuresimulatorresponse"; @Inject SimulatorManager _simMgr; @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, description="configure range: in a zone") private Long zoneId; @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, description="configure range: in a pod") private Long podId; @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, description="configure range: in a cluster") private Long clusterId; @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, description="configure range: in a host") private Long hostId; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "which command needs to be configured") private String command; @Parameter(name = ApiConstants.VALUE, type = CommandType.STRING, required = true, description = "configuration options for this command, which is seperated by ;") private String values; @Parameter(name=ApiConstants.COUNT, type=CommandType.INTEGER, description="number of times the mock is active") private Integer count; @Parameter(name="jsonresponse", type=CommandType.STRING, description="agent command response to be returned") private String jsonResponse; @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { Long id = _simMgr.configureSimulator(zoneId, podId, clusterId, hostId, command, values, count, jsonResponse); if (id == null) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to configure simulator"); } MockConfigurationVO config = _simMgr.querySimulatorMock(id); if (config == null) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to query simulator mock"); } MockResponse response = new MockResponse(); response.setId(config.getId()); response.setZoneId(config.getDataCenterId()); response.setPodId(config.getPodId()); response.setClusterId(config.getClusterId()); response.setHostId(config.getHostId()); response.setName(config.getName()); response.setCount(config.getCount()); response.setResponseName("simulatormock"); this.setResponseObject(response); } @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } }
44.27027
166
0.760277
c434dcb0db6bfb326eba0e55f0716a4bd921eef4
173
package io.github.hulang1024.chess.games.chinesechess; import io.github.hulang1024.chess.games.GameSettings; public class ChineseChessGameSettings extends GameSettings { }
28.833333
60
0.849711
5f40c52794d62729527a0361a94c80e0eb8f8a65
987
/* * Copyright (C) 1999-2011 University of Connecticut Health Center * * Licensed under the MIT License (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.opensource.org/licenses/mit-license.php */ package cbit.image.gui; import cbit.image.Command; /** * This type was created in VisualAge. */ public class SliceCommand extends Command { private int sliceOffset = -1; /** * SliceCommand constructor comment. * @param id int */ public SliceCommand(int sliceOffset) { super(); this.sliceOffset = sliceOffset; } /** * This method was created in VisualAge. * @return int */ public int getSliceOffset() { return sliceOffset; } /** * This method was created in VisualAge. * @param oldCommand cbit.image.Command */ public void integrateOldCommand(Command oldCommand) { sliceOffset += ((SliceCommand)oldCommand).getSliceOffset(); } }
22.953488
68
0.688956
55dcd71ee476cd5cfdcd0d236a23f221a151d166
2,940
import java.util.Arrays; import java.util.Stack; import com.sun.tools.hat.internal.util.ArraySorter; import com.sun.tools.javac.code.Attribute.Array; public class BinaryTree { BinaryTree LeftTree = null; BinaryTree RightTree = null; BinaryTree parent = null; public static Stack<Tuple<Integer,Integer,Integer>> printer = new Stack<Tuple<Integer,Integer,Integer>>(); int data; public BinaryTree(int data1) { data = data1; } public double MaxDepth(BinaryTree bt) { if (bt==null) return 0; else return 1 + Math.max(MaxDepth(bt.LeftTree), MaxDepth(bt.RightTree)); } public void SetLeft(BinaryTree left) { LeftTree = left; LeftTree.parent = this; } public void SetRight(BinaryTree right) { RightTree = right; RightTree.parent = this; } public void InorderPrint(BinaryTree bt) { if (bt.LeftTree != null) InorderPrint(bt.LeftTree); System.out.print(bt.data + "-"); if (bt.RightTree != null) InorderPrint(bt.RightTree); } public static int GetNextP() { int x = -1; int y = 1000; int z = 1000; int index = 0; for(int i = 0; i < BinaryTree.printer.size(); i++) { Tuple<Integer,Integer,Integer> t = BinaryTree.printer.elementAt(i); if (t.y < y) { x = t.x; y = t.y; z = t.z; index = i; } if (t.y == y) { if (t.z > z) { x = t.x; y = t.y; z = t.z; index = i; } } } BinaryTree.printer.removeElementAt(index); return x; } public void VerticalPrint(BinaryTree bt, int column , int level) { if (bt.LeftTree != null) { int i = column - 1; int l = level-1; VerticalPrint(bt.LeftTree,i,l); } BinaryTree.printer.push(new Tuple<Integer,Integer,Integer>(bt.data,column,level)); if (bt.RightTree != null) { int i = column + 1; int l = level-1; VerticalPrint(bt.RightTree,i,l); } } public static void main(final String[] args) { BinaryTree t0 = new BinaryTree(0); BinaryTree t1 = new BinaryTree(1); BinaryTree t2 = new BinaryTree(2); BinaryTree t3 = new BinaryTree(3); BinaryTree t4 = new BinaryTree(4); BinaryTree t5 = new BinaryTree(5); BinaryTree t6 = new BinaryTree(6); BinaryTree t7 = new BinaryTree(7); BinaryTree t8 = new BinaryTree(8); BinaryTree t9 = new BinaryTree(9); t6.LeftTree = t3; t6.RightTree = t4; t3.LeftTree = t5; t3.RightTree = t1; t5.LeftTree = t9; t5.RightTree = t2; t2.RightTree = t7; t4.RightTree = t0; t0.LeftTree = t8; System.out.println("Hello BinaryTree"); //t4.InorderPrint(t6); t6.VerticalPrint(t6, 0,0); for(Tuple<Integer,Integer,Integer> x : BinaryTree.printer) { System.out.println(x.x + " , " + x.y + " , " + x.z); } System.out.println(BinaryTree.printer.capacity()); int count = BinaryTree.printer.capacity(); for(int i =0; i < count; i++) System.out.println(BinaryTree.GetNextP() + " , "); } }
21.304348
107
0.622789
a368ab70728de914bec6b78ca4748871e7c767f9
2,382
package by.sir.max.library.factory; import by.sir.max.library.entity.book.bookcomponent.Author; import by.sir.max.library.entity.book.bookcomponent.BookLanguage; import by.sir.max.library.entity.book.bookcomponent.Genre; import by.sir.max.library.entity.book.bookcomponent.Publisher; import by.sir.max.library.service.BookComponentService; import by.sir.max.library.service.BookOrderService; import by.sir.max.library.service.BookService; import by.sir.max.library.service.impl.*; import by.sir.max.library.service.UserService; import by.sir.max.library.service.impl.UserServiceImpl; public class ServiceFactory { private final UserService userService; private final BookService bookService; private final BookComponentService<Author> bookAuthorService; private final BookComponentService<Genre> bookGenreService; private final BookComponentService<BookLanguage> bookLanguageService; private final BookComponentService<Publisher> bookPublisherService; private final BookOrderService bookOrderService; private ServiceFactory() { userService = new UserServiceImpl(); bookService = new BookServiceImpl(); bookAuthorService = new BookAuthorServiceImpl(); bookGenreService = new BookGenreServiceImpl(); bookLanguageService = new BookLanguageServiceImpl(); bookPublisherService = new BookPublisherServiceImpl(); bookOrderService = new BookOrderServiceImpl(); } private static class ServiceFactorySingletonHolder { static final ServiceFactory INSTANCE = new ServiceFactory(); } public static ServiceFactory getInstance() { return ServiceFactorySingletonHolder.INSTANCE; } public UserService getUserService() { return userService; } public BookService getBookService() { return bookService; } public BookComponentService<Author> getBookAuthorService() { return bookAuthorService; } public BookComponentService<Genre> getBookGenreService() { return bookGenreService; } public BookComponentService<BookLanguage> getBookLanguageService() { return bookLanguageService; } public BookComponentService<Publisher> getBookPublisherService() { return bookPublisherService; } public BookOrderService getBookOrderService() { return bookOrderService; } }
34.521739
73
0.754408
ed9e5b9221be2eab4b2904fc07d8ff122540e9d5
4,021
/******************************************************************************* * Copyright (c) 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.accessibility; import org.eclipse.swt.internal.cocoa.*; /** * This class is used to describe a table header for objects that have an accessible * role of ACC.ROLE_TABLE, but aren't implemented like NSTableViews. That means they * report back their children as a list of cells in row-major order instead of a list of * rows with cells as children of those rows. The assumption is that the first 'row' * of cells (cell 0 to cell 'column-count - 1') are the column headers of the table. * * This class works with the parent control to act as the header section of the table, * and reports the cells in the header so that screen readers (VoiceOver, mainly) can * identify the column of the cell that the VoiceOver cursor is reading. */ class AccessibleTableHeader extends Accessible { public AccessibleTableHeader(Accessible accessible, int childID) { super(accessible); index = childID; addAccessibleControlListener(new AccessibleControlAdapter() { public void getChildren(AccessibleControlEvent e) { int validColumnCount = Math.max (1, parent.getColumnCount()); Accessible[] children = new Accessible[validColumnCount]; AccessibleControlEvent event = new AccessibleControlEvent(this); for (int i = 0; i < validColumnCount; i++) { event.childID = i; event.detail = ACC.CHILDID_CHILD_AT_INDEX; for (int j = 0; j < parent.accessibleControlListeners.size(); j++) { AccessibleControlListener listener = (AccessibleControlListener) parent.accessibleControlListeners.elementAt(j); listener.getChild(event); } event.accessible.parent = AccessibleTableHeader.this; children[i] = event.accessible; } e.children = children; } public void getChildCount(AccessibleControlEvent e) { e.detail = Math.max (1, parent.getColumnCount()); } public void getLocation(AccessibleControlEvent e) { int validColumnCount = Math.max (1, parent.getColumnCount()); Accessible[] children = new Accessible[validColumnCount]; AccessibleControlEvent event = new AccessibleControlEvent(this); for (int i = 0; i < validColumnCount; i++) { event.childID = i; event.detail = ACC.CHILDID_CHILD_AT_INDEX; for (int j = 0; j < parent.accessibleControlListeners.size(); j++) { AccessibleControlListener listener = (AccessibleControlListener) parent.accessibleControlListeners.elementAt(j); listener.getChild(event); } event.accessible.parent = AccessibleTableHeader.this; children[i] = event.accessible; } // Ask first child for position. NSValue positionObj = (NSValue)children[0].getPositionAttribute(ACC.CHILDID_SELF); NSPoint position = positionObj.pointValue(); // Ask all children for size. int height = 0; int width = 0; for (int j = 0; j < children.length; j++) { NSValue sizeObj = (NSValue)children[j].getSizeAttribute(ACC.CHILDID_SELF); NSSize size = sizeObj.sizeValue(); if (size.height > height) height = (int) size.height; width += size.width; } e.x = (int) position.x; // Flip y coordinate for Cocoa. NSArray screens = NSScreen.screens(); NSScreen screen = new NSScreen(screens.objectAtIndex(0)); NSRect frame = screen.frame(); e.y = (int) (frame.height - position.y - height); e.width = width; e.height = height; } public void getRole(AccessibleControlEvent e) { e.detail = ACC.ROLE_TABLECOLUMNHEADER; } }); } }
39.038835
118
0.682915
b68e5f6a10e314ce3c6a61686eebd5d45323b7df
512
package frc.robot.subsystems.shooter; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.components.AngularVelocityComponent; public class Shooter extends SubsystemBase { private AngularVelocityComponent shooterMotor; public Shooter(AngularVelocityComponent s1) { shooterMotor = s1; } public void setSpeed(double speed) { shooterMotor.setAngularVelocity(speed); } public double getSpeed() { return shooterMotor.getAngularVelocity(); } }
25.6
53
0.740234
587f97fd65340e2f08c3afb741e547299c457ab4
86
package main.java.com.monochrome.microestore.entity; public class CategoryEntity { }
17.2
52
0.813953
31d0a5a79436740aa04ea51e1e80c8174d0f1239
3,796
/* * This file is part of GriefPrevention, licensed under the MIT License (MIT). * * Copyright (c) Ryan Hamshire * Copyright (c) bloodmc * Copyright (c) contributors * * 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.ryanhamshire.griefprevention.task; import me.ryanhamshire.griefprevention.GPPlayerData; import me.ryanhamshire.griefprevention.GriefPreventionPlugin; import me.ryanhamshire.griefprevention.visual.Visualization; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.entity.living.player.Player; import java.util.ArrayList; import java.util.concurrent.TimeUnit; //applies a visualization for a player by sending him block change packets public class VisualizationApplicationTask implements Runnable { private Visualization visualization; private Player player; private GPPlayerData playerData; private boolean resetActive; public VisualizationApplicationTask(Player player, GPPlayerData playerData, Visualization visualization) { this(player, playerData, visualization, true); } public VisualizationApplicationTask(Player player, GPPlayerData playerData, Visualization visualization, boolean resetActive) { this.visualization = visualization; this.playerData = playerData; this.player = player; this.resetActive = resetActive; } @Override public void run() { if (this.playerData.visualBlocks != null) { if (this.resetActive) { this.playerData.revertActiveVisual(this.player); } } for (int i = 0; i < this.visualization.elements.size(); i++) { BlockSnapshot snapshot = this.visualization.elements.get(i).getFinal(); this.player.sendBlockChange(snapshot.getPosition(), snapshot.getState()); } // remember the visualization applied to this player for later (so it can be inexpensively reverted) if (this.visualization.getClaim() != null) { this.playerData.visualClaimId = this.visualization.getClaim().id; this.visualization.getClaim().playersWatching.add(this.player.getUniqueId()); } this.playerData.visualBlocks = new ArrayList<>(this.visualization.elements); // schedule automatic visualization reversion in 60 seconds. // only create revert task if not resizing/starting a claim if (playerData.lastShovelLocation == null) { this.playerData.visualRevertTask = Sponge.getGame().getScheduler().createTaskBuilder().async().delay(1, TimeUnit.MINUTES) .execute(new VisualizationReversionTask(this.player, this.playerData)).submit(GriefPreventionPlugin.instance); } } }
44.658824
133
0.729979
72ff55085384b37158561362bf57a0bda071d669
1,719
package snod.com.cn.entity; import java.io.Serializable; import java.util.Date; /** * 文件信息实体 * @author lvjj */ public class FileInfo implements Serializable{ private static final long serialVersionUID = 1L; private int id; private String fileName; private String fileRoute; private long fileSize; private String fileType; private int fileStatus; private Date createTime; private int createUserId; private String createUserName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileRoute() { return fileRoute; } public void setFileRoute(String fileRoute) { this.fileRoute = fileRoute; } public long getFileSize() { return fileSize; } public void setFileSize(long fileSize) { this.fileSize = fileSize; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public int getFileStatus() { return fileStatus; } public void setFileStatus(int fileStatus) { this.fileStatus = fileStatus; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getCreateUserId() { return createUserId; } public void setCreateUserId(int createUserId) { this.createUserId = createUserId; } public String getCreateUserName() { return createUserName; } public void setCreateUserName(String createUserName) { this.createUserName = createUserName; } }
20.963415
56
0.699244
dd201c9177573b37e25680b960d4d2a7a21062db
2,130
package com.senzing.g2.search.elastic; import java.io.StringReader; import java.util.Set; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonValue; import javax.json.JsonValue.ValueType; // This class will search all of the attributes of a JSON document, and return a list of fields that // start with a particular substring. public class JsonFieldValueFinder { public static void findValues(String sourceJson, String searchValue, Set<String> searchResults) { StringReader sr = new StringReader(sourceJson); JsonReader jsonReader = Json.createReader(sr); JsonObject jsonObject = jsonReader.readObject(); findValues(jsonObject,searchValue,searchResults); } public static void findValues(JsonObject sourceJson, String searchValue, Set<String> searchResults) { String preparedSearchString = standardizeForMatching(searchValue); searchResults.clear(); sourceJson.entrySet().stream().forEach((entry) -> { //String key = entry.getKey(); JsonValue value = entry.getValue(); searchForValue(value,preparedSearchString,searchResults); }); } private static void searchForValue(JsonValue sourceValue, String searchValue, Set<String> searchResults) { ValueType valueType = sourceValue.getValueType(); switch (valueType) { case ARRAY: JsonArray sourceArray = sourceValue.asJsonArray(); sourceArray.stream().forEach((entry) -> { searchForValue(entry,searchValue,searchResults); }); break; case OBJECT: JsonObject sourceObject = sourceValue.asJsonObject(); sourceObject.entrySet().stream().forEach((entry) -> { JsonValue value = entry.getValue(); searchForValue(value,searchValue,searchResults); }); break; default: { String rawValue = Utils.getSimpleRawValue(sourceValue); if (standardizeForMatching(rawValue).startsWith(searchValue)) { searchResults.add(rawValue); } } } } private static String standardizeForMatching(String str) { return str.toLowerCase(); } }
29.583333
105
0.724413
aa8d175b219559752f5a0e541837f89bd1eb570d
2,258
package io.odpf.dagger.core.source.kafka.builder; import io.odpf.dagger.common.configuration.Configuration; import io.odpf.dagger.common.core.StencilClientOrchestrator; import io.odpf.dagger.common.serde.DataTypes; import io.odpf.dagger.common.serde.proto.deserialization.ProtoDeserializer; import io.odpf.dagger.core.source.StreamConfig; import org.apache.flink.streaming.connectors.kafka.KafkaDeserializationSchema; import java.util.HashMap; import java.util.List; import java.util.Map; import static io.odpf.dagger.core.metrics.telemetry.TelemetryTypes.INPUT_PROTO; import static io.odpf.dagger.core.utils.Constants.FLINK_ROWTIME_ATTRIBUTE_NAME_DEFAULT; import static io.odpf.dagger.core.utils.Constants.FLINK_ROWTIME_ATTRIBUTE_NAME_KEY; public class ProtoDataStreamBuilder extends StreamBuilder { private final String protoClassName; private final StreamConfig streamConfig; private StencilClientOrchestrator stencilClientOrchestrator; private Configuration configuration; private Map<String, List<String>> metrics = new HashMap<>(); public ProtoDataStreamBuilder(StreamConfig streamConfig, StencilClientOrchestrator stencilClientOrchestrator, Configuration configuration) { super(streamConfig, configuration); this.streamConfig = streamConfig; this.protoClassName = streamConfig.getProtoClass(); this.stencilClientOrchestrator = stencilClientOrchestrator; this.configuration = configuration; } @Override void addTelemetry() { addDefaultMetrics(metrics); addMetric(metrics, INPUT_PROTO.getValue(), protoClassName); } @Override Map<String, List<String>> getMetrics() { return metrics; } @Override public boolean canBuild() { return getInputDataType() == DataTypes.PROTO; } @Override KafkaDeserializationSchema getDeserializationSchema() { int timestampFieldIndex = Integer.parseInt(streamConfig.getEventTimestampFieldIndex()); String rowTimeAttributeName = configuration.getString(FLINK_ROWTIME_ATTRIBUTE_NAME_KEY, FLINK_ROWTIME_ATTRIBUTE_NAME_DEFAULT); return new ProtoDeserializer(protoClassName, timestampFieldIndex, rowTimeAttributeName, stencilClientOrchestrator); } }
40.321429
144
0.782994
6b5c1c536b23dd3df756d924194b0c7137b53c9f
12,205
package water.api; import org.junit.Assert; import org.junit.Test; import water.Key; import water.TestUtil; import water.fvec.Frame; import java.util.Arrays; public class ConfusionMatrixTest extends TestUtil { final boolean debug = false; @Test public void testIdenticalVectors() { simpleCMTest( "smalldata/test/cm/v1.csv", "smalldata/test/cm/v1.csv", ar("A", "B", "C"), ar("A", "B", "C"), ar("A", "B", "C"), ar( ar(2L, 0L, 0L, 0L), ar(0L, 2L, 0L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); } @Test public void testVectorAlignment() { simpleCMTest( "smalldata/test/cm/v1.csv", "smalldata/test/cm/v2.csv", ar("A", "B", "C"), ar("A", "B", "C"), ar("A", "B", "C"), ar( ar(1L, 1L, 0L, 0L), ar(0L, 1L, 1L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); } /** Negative test testing expected exception if two vectors * of different lengths are provided. */ @Test(expected = IllegalArgumentException.class) public void testDifferentLenghtVectors() { simpleCMTest( "smalldata/test/cm/v1.csv", "smalldata/test/cm/v3.csv", ar("A", "B", "C"), ar("A", "B", "C"), ar("A", "B", "C"), ar( ar(1L, 1L, 0L, 0L), ar(0L, 1L, 1L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); } @Test public void testDifferentDomains() { simpleCMTest( "smalldata/test/cm/v1.csv", "smalldata/test/cm/v4.csv", ar("A", "B", "C"), ar("B", "C"), ar("A", "B", "C"), ar( ar(0L, 2L, 0L, 0L), ar(0L, 0L, 2L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); simpleCMTest( "smalldata/test/cm/v4.csv", "smalldata/test/cm/v1.csv", ar("B", "C"), ar("A", "B", "C"), ar("A", "B", "C"), ar( ar(0L, 0L, 0L, 0L), ar(2L, 0L, 0L, 0L), ar(0L, 2L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); simpleCMTest( "smalldata/test/cm/v2.csv", "smalldata/test/cm/v4.csv", ar("A", "B", "C"), ar("B", "C"), ar("A", "B", "C"), ar( ar(0L, 1L, 0L, 0L), ar(0L, 1L, 1L, 0L), ar(0L, 0L, 2L, 0L), ar(0L, 0L, 0L, 0L) ), debug); } @Test public void testSimpleNumericVectors() { simpleCMTest( "smalldata/test/cm/v1n.csv", "smalldata/test/cm/v1n.csv", ar("0", "1", "2"), ar("0", "1", "2"), ar("0", "1", "2"), ar( ar(2L, 0L, 0L, 0L), ar(0L, 2L, 0L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); simpleCMTest( "smalldata/test/cm/v1n.csv", "smalldata/test/cm/v2n.csv", ar("0", "1", "2"), ar("0", "1", "2"), ar("0", "1", "2"), ar( ar(1L, 1L, 0L, 0L), ar(0L, 1L, 1L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); } @Test public void testDifferentDomainsNumericVectors() { simpleCMTest( "smalldata/test/cm/v1n.csv", "smalldata/test/cm/v4n.csv", ar("0", "1", "2"), ar("1", "2"), ar("0", "1", "2"), ar( ar(0L, 2L, 0L, 0L), ar(0L, 0L, 2L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); simpleCMTest( "smalldata/test/cm/v4n.csv", "smalldata/test/cm/v1n.csv", ar("1", "2"), ar("0", "1", "2"), ar("0", "1", "2"), ar( ar(0L, 0L, 0L, 0L), ar(2L, 0L, 0L, 0L), ar(0L, 2L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); simpleCMTest( "smalldata/test/cm/v2n.csv", "smalldata/test/cm/v4n.csv", ar("0", "1", "2"), ar("1", "2"), ar("0", "1", "2"), ar( ar(0L, 1L, 0L, 0L), ar(0L, 1L, 1L, 0L), ar(0L, 0L, 2L, 0L), ar(0L, 0L, 0L, 0L) ), debug); } /** Test for PUB-216: * The case when vector domain is set to a value (0~A, 1~B, 2~C), but actual values stored in * vector references only a subset of domain (1~B, 2~C). The TransfVec was using minimum from * vector (i.e., value 1) to compute transformation but minimum was wrong since it should be 0. */ @Test public void testBadModelPrect() { simpleCMTest( frame("v1", vec(ar("A","B","C"), ari(0,0,1,1,2) )), frame("v2", vec(ar("A","B","C"), ari(1,1,2,2,2) )), ar("A","B","C"), ar("A","B","C"), ar("A","B","C"), ar( ar(0L, 2L, 0L, 0L), ar(0L, 0L, 2L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); simpleCMTest( frame("v1", vec(ar("B","C"), ari(0,0,1,1) )), frame("v2", vec(ar("A","B"), ari(1,1,0,0) )), ar("B","C"), ar("A","B"), ar("A","B","C"), ar( ar(0L, 0L, 0L, 0L), // A ar(0L, 2L, 0L, 0L), // B ar(2L, 0L, 0L, 0L), // C ar(0L, 0L, 0L, 0L) // NA ), debug); } @Test public void testBadModelPrect2() { simpleCMTest( frame("v1", vec(ari(-1,-1,0,0,1) )), frame("v2", vec(ari( 0, 0,1,1,1) )), ar("-1","0","1"), ar("0","1"), ar("-1","0","1"), ar( ar(0L, 2L, 0L, 0L), ar(0L, 0L, 2L, 0L), ar(0L, 0L, 1L, 0L), ar(0L, 0L, 0L, 0L) ), debug); simpleCMTest( frame("v1", vec(ari(-1,-1,0,0) )), frame("v2", vec(ari( 1, 1,0,0) )), ar("-1","0"), ar("0","1"), ar("-1","0","1"), ar( ar(0L, 0L, 2L, 0L), ar(0L, 2L, 0L, 0L), ar(0L, 0L, 0L, 0L), ar(0L, 0L, 0L, 0L) ), debug); // The case found by Nidhi on modified covtype dataset simpleCMTest( frame("v1", vec(ari( 1, 2, 3, 4, 5, 6, 7) )), frame("v2", vec(ari( 1, 2, 3, 4, 5, 6, -1) )), ar( "1","2","3","4","5","6","7"), ar("-1", "1","2","3","4","5","6"), ar("-1", "1","2","3","4","5","6","7"), ar( ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "-1" ar( 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "1" ar( 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), // "2" ar( 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L), // "3" ar( 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L), // "4" ar( 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), // "5" ar( 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L), // "6" ar( 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "7" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L) // "NAs" ), debug); // Another case simpleCMTest( frame("v1", vec(ari( 7, 8, 9, 10, 11) )), frame("v2", vec(ari( 7, 8, 13, 10, 11) )), ar("7","8", "9","10","11"), ar("7","8","10","11","13"), ar("7","8","9","10","11","13"), ar( ar( 1L, 0L, 0L, 0L, 0L, 0L, 0L), // "7" ar( 0L, 1L, 0L, 0L, 0L, 0L, 0L), // "8" ar( 0L, 0L, 0L, 0L, 0L, 1L, 0L), // "9" ar( 0L, 0L, 0L, 1L, 0L, 0L, 0L), // "10" ar( 0L, 0L, 0L, 0L, 1L, 0L, 0L), // "11" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "13" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L) // "NAs" ), debug); // Mixed case simpleCMTest( frame("v1", vec(ar("-1", "1", "A"), ari( 0, 1, 2) )), frame("v2", vec(ar( "0", "1", "B"), ari( 0, 1, 2) )), ar("-1", "1", "A"), ar( "0", "1", "B"), ar( "-1", "0", "1", "A", "B"), ar( ar( 0L, 1L, 0L, 0L, 0L, 0L), // "-1" ar( 0L, 0L, 0L, 0L, 0L, 0L), // "0" ar( 0L, 0L, 1L, 0L, 0L, 0L), // "1" ar( 0L, 0L, 0L, 0L, 1L, 0L), // "A" ar( 0L, 0L, 0L, 0L, 0L, 0L), // "B" ar( 0L, 0L, 0L, 0L, 0L, 0L) // "NAs" ), false); // Mixed case with change of numeric ordering 1, 10, 9 -> 1,9,10 simpleCMTest( frame("v1", vec(ar("-1", "1", "10", "9", "A"), ari( 0, 1, 2, 3, 4) )), frame("v2", vec(ar( "0", "2", "8", "9", "B"), ari( 0, 1, 2, 3, 4) )), ar("-1", "1", "10", "9", "A"), ar( "0", "2", "8", "9", "B"), ar( "-1", "0", "1", "2", "8", "9", "10", "A", "B"), ar( ar( 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "-1" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "0" ar( 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L), // "1" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "2" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "8" ar( 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L), // "9" ar( 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L), // "10" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L), // "A" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), // "B" ar( 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L) // "NAs" ), debug); } private void simpleCMTest(String f1, String f2, String[] expectedActualDomain, String[] expectedPredictDomain, String[] expectedDomain, long[][] expectedCM, boolean debug) { simpleCMTest(parseFrame(Key.make("v1.hex"), find_test_file(f1)), parseFrame(Key.make("v2.hex"), find_test_file(f2)), expectedActualDomain, expectedPredictDomain, expectedDomain, expectedCM, debug); } /** Delete v1, v2 after processing. */ private void simpleCMTest(Frame v1, Frame v2, String[] expectedActualDomain, String[] expectedPredictDomain, String[] expectedDomain, long[][] expectedCM, boolean debug) { try { ConfusionMatrix cm = computeCM(v1, v2); // -- DEBUG -- if (debug) { System.err.println(Arrays.toString(cm.actual_domain)); System.err.println(Arrays.toString(cm.predicted_domain)); for (int i=0; i<cm.cm.length; i++) System.err.println(Arrays.toString(cm.cm[i])); StringBuilder sb = new StringBuilder(); cm.toASCII(sb); System.err.println(sb.toString()); } // -- -- -- assertCMEqual(expectedActualDomain, expectedPredictDomain, expectedDomain, expectedCM, cm); } finally { if (v1 != null) v1.delete(); if (v2 != null) v2.delete(); } } private void assertCMEqual(String[] expectedActualDomain, String[] expectedPredictDomain, String[] expectedDomain, long[][] expectedCM, ConfusionMatrix actualCM) { Assert.assertArrayEquals("Actual CM domain differs", expectedActualDomain, actualCM.actual_domain); Assert.assertArrayEquals("Predicted CM domain differs", expectedPredictDomain, actualCM.predicted_domain); Assert.assertArrayEquals("Expected domain differs", expectedDomain, actualCM.domain); long[][] acm = actualCM.cm; Assert.assertEquals("CM dimension differs", expectedCM.length, acm.length); for (int i=0; i < acm.length; i++) Assert.assertArrayEquals("CM row " +i+" differs!", expectedCM[i], acm[i]); } private ConfusionMatrix computeCM(Frame v1, Frame v2) { assert v1.vecs().length == 1 && v2.vecs().length == 1 : "Test expect single vector frames!"; ConfusionMatrix cm = new ConfusionMatrix(); cm.actual = v1; cm.vactual = v1.vecs()[0]; cm.predict = v2; cm.vpredict = v2.vecs()[0]; // Ohh nooo, this is block call :-) // Finally time for joke: // """ Two men walk into a bar. The first one says "I'll have some H2O." The next man says "I'll have some H2O too" :-D """ cm.invoke(); return cm; } }
32.72118
201
0.436215
0e862637dd19f872127e226d28299f2b70ec2048
1,318
package com.teaminabox.eclipse.wiki.text; /** * A TextRegionVisitor that returns a default value for each TextRegionVisitor method. */ public class GenericTextRegionVisitor<T> implements TextRegionVisitor<T> { private T defaultReturnValue; public GenericTextRegionVisitor(T defaultReturnValue) { this.defaultReturnValue = defaultReturnValue; } public T visit(UndefinedTextRegion undefinedTextRegion) { return defaultReturnValue; } public T visit(UrlTextRegion urlTextRegion) { return defaultReturnValue; } public T visit(WikiWordTextRegion wikiNameTextRegion) { return defaultReturnValue; } public T visit(WikiUrlTextRegion wikiUrlTextRegion) { return defaultReturnValue; } public T visit(BasicTextRegion basicTextRegion) { return defaultReturnValue; } public T visit(EclipseResourceTextRegion eclipseResourceTextRegion) { return defaultReturnValue; } public T visit(PluginResourceTextRegion eclipseResourceTextRegion) { return defaultReturnValue; } public T visit(JavaTypeTextRegion region) { return defaultReturnValue; } public T visit(ForcedLinkTextRegion region) { return defaultReturnValue; } public T visit(EmbeddedWikiWordTextRegion region) { return defaultReturnValue; } public T visit(PAThWayTextRegion region) { return defaultReturnValue; } }
22.724138
86
0.796662
5f0a8a59a6d84b89865f5129abe054f1151a9457
3,381
package de.jaggl.sqlbuilder.core.queries; import static de.jaggl.sqlbuilder.core.dialect.Dialects.MYSQL; import static de.jaggl.sqlbuilder.core.dialect.Dialects.SYBASE; import static de.jaggl.sqlbuilder.core.queries.Queries.createTable; import static de.jaggl.sqlbuilder.core.utils.Indentation.enabled; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import de.jaggl.sqlbuilder.core.columns.datetime.DateColumn; import de.jaggl.sqlbuilder.core.columns.datetime.DateTimeColumn; import de.jaggl.sqlbuilder.core.columns.number.doubletype.DoubleColumn; import de.jaggl.sqlbuilder.core.columns.number.integer.IntColumn; import de.jaggl.sqlbuilder.core.columns.string.VarCharColumn; import de.jaggl.sqlbuilder.core.schema.Schema; import de.jaggl.sqlbuilder.core.schema.Table; class CreateTableTest { public static final Schema DBA = Schema.create("dba"); public static final Table PERSONS = DBA.table("persons"); public static final VarCharColumn FORENAME = PERSONS.varCharColumn("forename").size(50).noDefault().build(); public static final VarCharColumn LASTNAME = PERSONS.varCharColumn("lastname").size(50).defaultNull().build(); public static final VarCharColumn NICKNAME = PERSONS.varCharColumn("nickname").size(30).defaultValue("Schubi").build(); public static final IntColumn AGE = PERSONS.intColumn("age").size(5).unsigned().notNull().noDefault().autoIncrement().build(); public static final DoubleColumn SIZE = PERSONS.doubleColumn("size").size(2.2).unsigned().notNull().defaultValue(55.8).build(); public static final DateColumn BIRTHDAY = PERSONS.dateColumn("birthday").notNull().build(); public static final DateTimeColumn HAPPENING = PERSONS.dateTimeColumn("happening").notNull().build(); @Test void testCreateTable() { var createTable = createTable(PERSONS); createTable.println(); createTable.println(SYBASE, enabled()); assertThat(createTable.build(MYSQL)) .isEqualTo("CREATE TABLE `dba`.`persons` (`forename` VARCHAR(50), `lastname` VARCHAR(50) DEFAULT NULL, `nickname` VARCHAR(30) DEFAULT 'Schubi', `age` INT(5) UNSIGNED NOT NULL AUTO_INCREMENT, `size` DOUBLE(2,2) UNSIGNED NOT NULL DEFAULT 55.8, `birthday` DATE NOT NULL, `happening` DATETIME NOT NULL, PRIMARY KEY (`age`))"); assertThat(createTable.build(MYSQL, enabled())) .isEqualTo("CREATE TABLE `dba`.`persons`\n" // + "(\n" // + " `forename` VARCHAR(50),\n" // + " `lastname` VARCHAR(50) DEFAULT NULL,\n" // + " `nickname` VARCHAR(30) DEFAULT 'Schubi',\n" // + " `age` INT(5) UNSIGNED NOT NULL AUTO_INCREMENT,\n" // + " `size` DOUBLE(2,2) UNSIGNED NOT NULL DEFAULT 55.8,\n" // + " `birthday` DATE NOT NULL,\n" // + " `happening` DATETIME NOT NULL,\n" // + " PRIMARY KEY (`age`)\n" // + ")"); assertThat(createTable.build(MYSQL)).isEqualTo(createTable.build(SYBASE)); assertThat(createTable.build(MYSQL, enabled())).isEqualTo(createTable.build(SYBASE, enabled())); assertThat(CreateTable.copy(createTable).build(MYSQL)).isEqualTo(createTable.build(MYSQL)); } }
54.532258
338
0.672582
13525f5d185f05946dc59cdefb56e7a076667aa6
1,477
package com.lac.petrinet.core; import java.util.ArrayList; import java.util.List; import com.lac.petrinet.netcommunicator.InformedTransition; public class TransitionCycleListener implements Runnable { private List<InformedTransition> transitions; private int numberOfCycles = -1; public TransitionCycleListener(List<InformedTransition> transitions) { this.transitions = transitions; } public TransitionCycleListener(List<InformedTransition> transitions, int numberOfCycles) { this.transitions = transitions; this.numberOfCycles = numberOfCycles; } @Override public void run() { int counter = 0; boolean needNewRound = false; List<InformedTransition> transitionsWithInformed = new ArrayList<InformedTransition>(); while(counter < numberOfCycles || numberOfCycles < 0){ try { transitionsWithInformed.removeAll(transitionsWithInformed); do{ needNewRound = false; for(InformedTransition transition : transitions ){ if(transition.communicate()){ transitionsWithInformed.add(transition); needNewRound = true; } } }while(needNewRound); int i = 0; for(InformedTransition t : transitions){ if(transitionsWithInformed.contains(t)){ transitionsWithInformed.remove(transitionsWithInformed.indexOf(t)); t.startDummies(); Thread.yield(); i++; } } counter++; } catch (InterruptedException e) { e.printStackTrace(); } } } }
24.616667
91
0.7109
827a7eb37d6e89571092f807d74340f80a487924
14,511
/* * 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.shenyu.admin.model.entity; import org.apache.shenyu.admin.model.dto.ResourceDTO; import org.apache.shenyu.common.utils.UUIDUtils; import reactor.util.StringUtils; import java.sql.Timestamp; import java.util.Objects; import java.util.Optional; /** * The Resource Entity. */ public final class ResourceDO extends BaseDO { private static final long serialVersionUID = 4663697054300237200L; /** * resource parent key. */ private String parentId; /** * resource title. */ private String title; /** * resource name. */ private String name; /** * resource url. */ private String url; /** * resource component. */ private String component; /** * resource type. */ private Integer resourceType; /** * resource sort. */ private Integer sort; /** * resource icon. */ private String icon; /** * resource is leaf. */ private Boolean isLeaf; /** * resource is route. */ private Integer isRoute; /** * resource perms. */ private String perms; /** * resource status. */ private Integer status; public ResourceDO() { } public ResourceDO(final String parentId, final String title, final String name, final String url, final String component, final Integer resourceType, final Integer sort, final String icon, final Boolean isLeaf, final Integer isRoute, final String perms, final Integer status) { this.parentId = parentId; this.title = title; this.name = name; this.url = url; this.component = component; this.resourceType = resourceType; this.sort = sort; this.icon = icon; this.isLeaf = isLeaf; this.isRoute = isRoute; this.perms = perms; this.status = status; } /** * Gets the value of parentId. * * @return the value of parentId */ public String getParentId() { return parentId; } /** * Sets the parentId. * * @param parentId parentId */ public void setParentId(final String parentId) { this.parentId = parentId; } /** * Gets the value of title. * * @return the value of title */ public String getTitle() { return title; } /** * Sets the title. * * @param title title */ public void setTitle(final String title) { this.title = title; } /** * Gets the value of name. * * @return the value of name */ public String getName() { return name; } /** * Sets the name. * * @param name name */ public void setName(final String name) { this.name = name; } /** * Gets the value of url. * * @return the value of url */ public String getUrl() { return url; } /** * Sets the url. * * @param url url */ public void setUrl(final String url) { this.url = url; } /** * Gets the value of component. * * @return the value of component */ public String getComponent() { return component; } /** * Sets the component. * * @param component component */ public void setComponent(final String component) { this.component = component; } /** * Gets the value of resourceType. * * @return the value of resourceType */ public Integer getResourceType() { return resourceType; } /** * Sets the resourceType. * * @param resourceType resourceType */ public void setResourceType(final Integer resourceType) { this.resourceType = resourceType; } /** * Gets the value of sort. * * @return the value of sort */ public Integer getSort() { return sort; } /** * Sets the sort. * * @param sort sort */ public void setSort(final Integer sort) { this.sort = sort; } /** * Gets the value of icon. * * @return the value of icon */ public String getIcon() { return icon; } /** * Sets the icon. * * @param icon icon */ public void setIcon(final String icon) { this.icon = icon; } /** * Gets the value of isLeaf. * * @return the value of isLeaf */ public Boolean getIsLeaf() { return isLeaf; } /** * Sets the isLeaf. * * @param isLeaf isLeaf */ public void setIsLeaf(final Boolean isLeaf) { this.isLeaf = isLeaf; } /** * Gets the value of isRoute. * * @return the value of isRoute */ public Integer getIsRoute() { return isRoute; } /** * Sets the isRoute. * * @param isRoute isRoute */ public void setIsRoute(final Integer isRoute) { this.isRoute = isRoute; } /** * Gets the value of perms. * * @return the value of perms */ public String getPerms() { return perms; } /** * Sets the perms. * * @param perms perms */ public void setPerms(final String perms) { this.perms = perms; } /** * Gets the value of status. * * @return the value of status */ public Integer getStatus() { return status; } /** * Sets the status. * * @param status status */ public void setStatus(final Integer status) { this.status = status; } /** * builder method. * * @return builder object. */ public static ResourceDO.ResourceDOBuilder builder() { return new ResourceDO.ResourceDOBuilder(); } /** * build ResourceDO. * * @param resourceDTO {@linkplain ResourceDTO} * @return {@linkplain ResourceDO} */ public static ResourceDO buildResourceDO(final ResourceDTO resourceDTO) { return Optional.ofNullable(resourceDTO).map(item -> { Timestamp currentTime = new Timestamp(System.currentTimeMillis()); ResourceDO resourceDO = ResourceDO.builder() .parentId(item.getParentId()) .title(item.getTitle()) .name(item.getName()) .url(item.getUrl()) .component(item.getComponent()) .resourceType(item.getResourceType()) .sort(item.getSort()) .icon(item.getIcon()) .isLeaf(item.getIsLeaf()) .isRoute(item.getIsRoute()) .perms(item.getPerms()) .status(item.getStatus()) .build(); if (StringUtils.isEmpty(item.getId())) { resourceDO.setId(UUIDUtils.getInstance().generateShortUuid()); resourceDO.setDateCreated(currentTime); } else { resourceDO.setId(item.getId()); } return resourceDO; }).orElse(null); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ResourceDO that = (ResourceDO) o; return Objects.equals(parentId, that.parentId) && Objects.equals(title, that.title) && Objects.equals(name, that.name) && Objects.equals(url, that.url) && Objects.equals(component, that.component) && Objects.equals(resourceType, that.resourceType) && Objects.equals(sort, that.sort) && Objects.equals(icon, that.icon) && Objects.equals(isLeaf, that.isLeaf) && Objects.equals(isRoute, that.isRoute) && Objects.equals(perms, that.perms) && Objects.equals(status, that.status); } @Override public int hashCode() { return Objects.hash(super.hashCode(), parentId, title, name, url, component, resourceType, sort, icon, isLeaf, isRoute, perms, status); } public static final class ResourceDOBuilder { private String id; private Timestamp dateCreated; private Timestamp dateUpdated; private String parentId; private String title; private String name; private String url; private String component; private Integer resourceType; private Integer sort; private String icon; private Boolean isLeaf; private Integer isRoute; private String perms; private Integer status; private ResourceDOBuilder() { } /** * id. * * @param id the id. * @return ResourceDOBuilder. */ public ResourceDOBuilder id(final String id) { this.id = id; return this; } /** * dateCreated. * * @param dateCreated the dateCreated. * @return ResourceDOBuilder. */ public ResourceDOBuilder dateCreated(final Timestamp dateCreated) { this.dateCreated = dateCreated; return this; } /** * dateUpdated. * * @param dateUpdated the dateUpdated. * @return ResourceDOBuilder. */ public ResourceDOBuilder dateUpdated(final Timestamp dateUpdated) { this.dateUpdated = dateUpdated; return this; } /** * parentId. * * @param parentId the parentId. * @return ResourceDOBuilder. */ public ResourceDOBuilder parentId(final String parentId) { this.parentId = parentId; return this; } /** * title. * * @param title the title. * @return ResourceDOBuilder. */ public ResourceDOBuilder title(final String title) { this.title = title; return this; } /** * name. * * @param name the name. * @return ResourceDOBuilder. */ public ResourceDOBuilder name(final String name) { this.name = name; return this; } /** * url. * * @param url the url. * @return ResourceDOBuilder. */ public ResourceDOBuilder url(final String url) { this.url = url; return this; } /** * component. * * @param component the component. * @return ResourceDOBuilder. */ public ResourceDOBuilder component(final String component) { this.component = component; return this; } /** * resourceType. * * @param resourceType the resourceType. * @return ResourceDOBuilder. */ public ResourceDOBuilder resourceType(final Integer resourceType) { this.resourceType = resourceType; return this; } /** * sort. * * @param sort the sort. * @return ResourceDOBuilder. */ public ResourceDOBuilder sort(final Integer sort) { this.sort = sort; return this; } /** * icon. * * @param icon the icon. * @return ResourceDOBuilder. */ public ResourceDOBuilder icon(final String icon) { this.icon = icon; return this; } /** * isLeaf. * * @param isLeaf the isLeaf. * @return ResourceDOBuilder. */ public ResourceDOBuilder isLeaf(final Boolean isLeaf) { this.isLeaf = isLeaf; return this; } /** * isRoute. * * @param isRoute the isRoute. * @return ResourceDOBuilder. */ public ResourceDOBuilder isRoute(final Integer isRoute) { this.isRoute = isRoute; return this; } /** * perms. * * @param perms the perms. * @return ResourceDOBuilder. */ public ResourceDOBuilder perms(final String perms) { this.perms = perms; return this; } /** * status. * * @param status the status. * @return ResourceDOBuilder. */ public ResourceDOBuilder status(final Integer status) { this.status = status; return this; } /** * build method. * * @return build object. */ public ResourceDO build() { ResourceDO resourceDO = new ResourceDO(parentId, title, name, url, component, resourceType, sort, icon, isLeaf, isRoute, perms, status); resourceDO.setId(id); resourceDO.setDateCreated(dateCreated); resourceDO.setDateUpdated(dateUpdated); return resourceDO; } } }
23.143541
148
0.523189
1492423a031ff2d5baab22183a0fb3001e951ea4
5,633
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.cli.compiler.grape; import java.io.File; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.settings.building.SettingsBuildingException; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.AuthenticationContext; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.Proxy; import org.eclipse.aether.repository.RemoteRepository; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.cli.testutil.SystemProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; /** * Tests for {@link SettingsXmlRepositorySystemSessionAutoConfiguration}. * * @author Andy Wilkinson */ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests { @Mock private RepositorySystem repositorySystem; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void basicSessionCustomization() throws SettingsBuildingException { assertSessionCustomization("src/test/resources/maven-settings/basic"); } @Test public void encryptedSettingsSessionCustomization() throws SettingsBuildingException { assertSessionCustomization("src/test/resources/maven-settings/encrypted"); } @Test public void propertyInterpolation() throws SettingsBuildingException { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils .newSession(); given(this.repositorySystem.newLocalRepositoryManager(eq(session), any(LocalRepository.class))).willAnswer((invocation) -> { LocalRepository localRepository = invocation.getArgument(1); return new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepository); }); SystemProperties.doWithSystemProperties( () -> new SettingsXmlRepositorySystemSessionAutoConfiguration().apply( session, SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem), "user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar"); assertThat(session.getLocalRepository().getBasedir().getAbsolutePath()) .endsWith(File.separatorChar + "bar" + File.separatorChar + "repository"); } private void assertSessionCustomization(String userHome) { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils .newSession(); SystemProperties.doWithSystemProperties( () -> new SettingsXmlRepositorySystemSessionAutoConfiguration().apply( session, SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem), "user.home:" + userHome); RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", "http://maven.example.com").build(); assertMirrorSelectorConfiguration(session, repository); assertProxySelectorConfiguration(session, repository); assertAuthenticationSelectorConfiguration(session, repository); } private void assertProxySelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) { Proxy proxy = session.getProxySelector().getProxy(repository); repository = new RemoteRepository.Builder(repository).setProxy(proxy).build(); AuthenticationContext authenticationContext = AuthenticationContext .forProxy(session, repository); assertThat(proxy.getHost()).isEqualTo("proxy.example.com"); assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) .isEqualTo("proxyuser"); assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) .isEqualTo("somepassword"); } private void assertMirrorSelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) { RemoteRepository mirror = session.getMirrorSelector().getMirror(repository); assertThat(mirror).as("Mirror configured for repository " + repository.getId()) .isNotNull(); assertThat(mirror.getHost()).isEqualTo("maven.example.com"); } private void assertAuthenticationSelectorConfiguration( DefaultRepositorySystemSession session, RemoteRepository repository) { Authentication authentication = session.getAuthenticationSelector() .getAuthentication(repository); repository = new RemoteRepository.Builder(repository) .setAuthentication(authentication).build(); AuthenticationContext authenticationContext = AuthenticationContext .forRepository(session, repository); assertThat(authenticationContext.get(AuthenticationContext.USERNAME)) .isEqualTo("tester"); assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)) .isEqualTo("secret"); } }
40.52518
87
0.802237
7925b807063a4d290a0bcda515339a87f49f913a
7,035
/* * Copyright 2010-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.k2js.translate.context; import gnu.trove.THashMap; import gnu.trove.TIntArrayList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.resolve.scopes.JetScope; import java.util.*; final class OverloadedMemberNameGenerator { private final Map<FunctionDescriptor, String> nameMap = new THashMap<FunctionDescriptor, String>(); @NotNull public String forExtensionProperty(PropertyAccessorDescriptor accessor) { String resolvedName = nameMap.get(accessor); if (resolvedName != null) { return resolvedName; } String name = Namer.getNameForAccessor(accessor.getCorrespondingProperty().getName().asString(), accessor instanceof PropertyGetterDescriptor); JetScope memberScope = getMemberScope(accessor.getCorrespondingProperty()); if (memberScope != null) { return resolveExtensionPropertyName(accessor, name, memberScope); } return name; } // see testOverloadedFun private static int sortFunctions(FunctionDescriptor[] sorted, Collection<FunctionDescriptor> unsorted) { int index = 0; for (FunctionDescriptor function : unsorted) { if (function.getKind().isReal()) { sorted[index++] = function; } } Arrays.sort(sorted, new Comparator<FunctionDescriptor>() { @Override public int compare(FunctionDescriptor a, FunctionDescriptor b) { if (a == null) { return b == null ? 0 : 1; } else if (b == null) { return -1; } Integer result = Visibilities.compare(b.getVisibility(), a.getVisibility()); if (result == null) { return 0; } else if (result == 0) { // open fun > not open fun int aWeight = a.getModality().isOverridable() ? 1 : 0; int bWeight = b.getModality().isOverridable() ? 1 : 0; return bWeight - aWeight; } return result; } }); return index; } @Nullable public String forClassOrNamespaceFunction(FunctionDescriptor function) { String resolvedName = nameMap.get(function); if (resolvedName != null) { return resolvedName; } JetScope memberScope = getMemberScope(function); if (memberScope == null) { return null; } Collection<FunctionDescriptor> functions = memberScope.getFunctions(function.getName()); String name = function.getName().asString(); final String originalName = name; if (functions.size() <= 1) { return name; } FunctionDescriptor[] sorted = new FunctionDescriptor[functions.size()]; int realSize = sortFunctions(sorted, functions); int counter = -1; TIntArrayList occupiedIndices = null; for (int i = 0; i < realSize; i++) { FunctionDescriptor currentFunction = sorted[i]; Set<? extends FunctionDescriptor> overriddenFunctions = currentFunction.getOverriddenDescriptors(); String currentName; if (overriddenFunctions.isEmpty()) { if (occupiedIndices != null) { while (occupiedIndices.contains(counter)) { counter++; } } currentName = counter == -1 ? originalName : originalName + '$' + counter; counter++; } else { FunctionDescriptor overriddenFunction = overriddenFunctions.iterator().next(); String overriddenFunctionName = forClassOrNamespaceFunction(overriddenFunction); assert overriddenFunctionName != null; if (occupiedIndices == null) { occupiedIndices = new TIntArrayList(); } int index = overriddenFunctionName.lastIndexOf('$'); if (index != -1) { index = Integer.parseInt(overriddenFunctionName.substring(index + 1)); } occupiedIndices.add(index); currentName = overriddenFunctionName; } if (currentFunction == function) { name = currentName; } nameMap.put(currentFunction, currentName); } return name; } private String resolveExtensionPropertyName(PropertyAccessorDescriptor accessor, String name, JetScope memberScope) { Collection<VariableDescriptor> properties = memberScope.getProperties(accessor.getCorrespondingProperty().getName()); if (properties.size() <= 1) { return name; } int counter = -1; boolean isGetter = accessor instanceof PropertyGetterDescriptor; for (VariableDescriptor variable : properties) { if (!(variable instanceof PropertyDescriptor) || variable.getReceiverParameter() == null) { continue; } PropertyDescriptor property = (PropertyDescriptor) variable; PropertyAccessorDescriptor currentAccessor = isGetter ? property.getGetter() : property.getSetter(); if (currentAccessor == null) { continue; } String currentName = counter == -1 ? name : name + '$' + counter; if (currentAccessor == accessor) { name = currentName; } nameMap.put(currentAccessor, currentName); counter++; } return name; } @Nullable private static JetScope getMemberScope(DeclarationDescriptor descriptor) { DeclarationDescriptor containing = descriptor.getContainingDeclaration(); if (containing instanceof ClassDescriptor) { return ((ClassDescriptor) containing).getDefaultType().getMemberScope(); } else if (containing instanceof NamespaceDescriptor) { return ((NamespaceDescriptor) containing).getMemberScope(); } else { return null; } } }
38.442623
125
0.591898
de051ee5c7c7adb9f917e068c09e8ed2e49e885d
757
package edwardwang.bouncingball.Interaction.EButton; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; /** * Created by edwardwang on 8/8/16. */ public class EButton extends Button{ public EButton(Context context) { super(context); } public EButton(Context context, AttributeSet attrs) { super(context, attrs); } public EButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public EButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } ///////////////////////////////////////////////////////////////// }
24.419355
92
0.640687
00183dc56c349c9c1499a07e8a9f7f06de2ce717
7,645
package com.hevelian.identity.core.api; import com.hevelian.identity.core.TenantService; import com.hevelian.identity.core.TenantService.TenantActiveAlreadyInStateException; import com.hevelian.identity.core.TenantService.TenantHasNoLogoException; import com.hevelian.identity.core.TenantService.TenantNotFoundByDomainException; import com.hevelian.identity.core.api.dto.TenantAdminRequestDTO.NewTenantGroup; import com.hevelian.identity.core.api.dto.TenantDomainDTO; import com.hevelian.identity.core.api.dto.TenantRequestDTO; import com.hevelian.identity.core.api.pagination.PageRequestParameters; import com.hevelian.identity.core.api.pagination.PageRequestParametersReader; import com.hevelian.identity.core.api.validation.constraints.Logo; import com.hevelian.identity.core.exc.ImageReadException; import com.hevelian.identity.core.model.Tenant; import com.hevelian.identity.core.pagination.PageRequestBuilder; import com.hevelian.identity.core.specification.EntitySpecificationsBuilder; import io.swagger.annotations.ApiParam; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.MediaType; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.groups.Default; import java.awt.image.BufferedImage; import java.io.IOException; import java.time.LocalDateTime; import static com.hevelian.identity.core.model.Tenant.FIELD_DATE_CREATED; import static com.hevelian.identity.core.specification.EntitySpecification.FROM; import static com.hevelian.identity.core.specification.EntitySpecification.TO; @RestController @RequestMapping(path = "/TenantService") @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Validated public class TenantController { private final String domain = "Tenant domain"; private final String tenantLogo = "Tenant logo. It is a 'image/png' or 'image/jpeg' file where width/height is not greater than 300 pixels"; private final TenantService tenantService; private final PasswordEncoder passwordEncoder; @RequestMapping(path = "/activateTenant", method = RequestMethod.POST) public void activateTenant(@Valid @RequestBody TenantDomainDTO tenantDomainDTO) throws TenantNotFoundByDomainException, TenantActiveAlreadyInStateException { tenantService.activateTenant(tenantDomainDTO.getTenantDomain()); } @RequestMapping(path = "/deactivateTenant", method = RequestMethod.POST) public void deactivateTenant(@Valid @RequestBody TenantDomainDTO tenantDomainDTO) throws TenantNotFoundByDomainException, TenantActiveAlreadyInStateException { tenantService.deactivateTenant(tenantDomainDTO.getTenantDomain()); } @RequestMapping(path = "/addTenant", method = RequestMethod.POST) public PrimitiveResult<String> addTenant(@Validated(value = {Default.class, NewTenantGroup.class}) @RequestBody TenantRequestDTO tenant) throws TenantService.TenantDomainAlreadyExistsException { tenant.getTenantAdmin() .setPassword(passwordEncoder.encode(tenant.getTenantAdmin().getPassword())); return new PrimitiveResult<>( tenantService.addTenant(tenant.toEntity(), tenant.getTenantAdmin().toEntity()).getDomain()); } @RequestMapping(path = "/setTenantLogo", method = RequestMethod.POST) public void setTenantLogo(@ApiParam(value = domain, required = true) @RequestParam String tenantDomain, @ApiParam(value = tenantLogo, required = true) @Logo @RequestParam MultipartFile logo) throws TenantNotFoundByDomainException, ImageReadException { try { tenantService.setTenantLogo(tenantDomain, logo.getBytes()); } catch (IOException e) { throw new ImageReadException("Failed in converting MultipartFile to byte array.",e); } } @RequestMapping(path = "/getTenantLogo", method = RequestMethod.GET, produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE}) public BufferedImage getTenantLogo(@ApiParam(value = domain, required = true) @RequestParam String tenantDomain) throws TenantNotFoundByDomainException, TenantHasNoLogoException { return tenantService.getTenantLogo(tenantDomain); } @RequestMapping(path = "/updateTenant", method = RequestMethod.POST) public void updateTenant(@Valid @RequestBody TenantRequestDTO tenant) throws TenantNotFoundByDomainException { if (tenant.getTenantAdmin().getPassword() != null) tenant.getTenantAdmin() .setPassword(passwordEncoder.encode(tenant.getTenantAdmin().getPassword())); tenantService.updateTenant(tenant.toEntity(), tenant.getTenantAdmin().toEntity()); } @RequestMapping(path = "/deleteTenant", method = RequestMethod.POST) public void deleteTenant(@Valid @RequestBody TenantDomainDTO tenantDomainDTO) throws TenantNotFoundByDomainException { tenantService.deleteTenant(tenantDomainDTO.getTenantDomain()); } @RequestMapping(path = "/getTenant", method = RequestMethod.POST) public Tenant getTenant(@Valid @RequestBody TenantDomainDTO tenantDomainDTO) throws TenantNotFoundByDomainException { return tenantService.getTenant(tenantDomainDTO.getTenantDomain()); } @RequestMapping(path = "/getAllTenants", method = RequestMethod.GET) public Page<Tenant> getAllTenants(@ApiParam(value = PageRequestParameters.PAGE_DESCRIPTION,defaultValue = PageRequestParameters.DEFAULT_PAGE) @RequestParam(name = PageRequestParameters.PAGE, required = false) @Min(PageRequestParameters.PAGE_MIN) Integer page, @ApiParam(value = PageRequestParameters.SIZE_DESCRIPTION,defaultValue = PageRequestParameters.DEFAULT_SIZE) @RequestParam(name = PageRequestParameters.SIZE, required = false) @Min(PageRequestParameters.SIZE_MIN) Integer size, @ApiParam(value = PageRequestParameters.SORT_DESCRIPTION) @RequestParam(name = PageRequestParameters.SORT, required = false) String sort, @ApiParam(value = "Domain") @RequestParam(required = false) String domain, @ApiParam(value = "Tenant is active") @RequestParam(required = false) Boolean active, @ApiParam(value = "Date created from (including entered time).API uses UTC time zone. Format: yyyy-MM-dd'T'HH:mm:ss.SSS") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateFrom, @ApiParam(value = "Date created to (excluding entered time).API uses UTC time zone. Format: yyyy-MM-dd'T'HH:mm:ss.SSS") @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime dateTo) { PageRequestBuilder pageRequestBuilder = new PageRequestParametersReader().readParameters(page, size, sort); EntitySpecificationsBuilder<Tenant> builder = new EntitySpecificationsBuilder<>(); builder.with(Tenant.FIELD_DOMAIN, domain) .with(Tenant.FIELD_ACTIVE, active) .with(FIELD_DATE_CREATED + FROM, dateFrom) .with(FIELD_DATE_CREATED + TO, dateTo); return tenantService.searchTenants(builder.build(), pageRequestBuilder.build()); } }
59.263566
261
0.764814
4f6e93500db17cd49ecb28a9048d05a4d9267cac
8,171
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import org.opencv.core.Point; import edu.wpi.first.wpilibj.util.Color; /** * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean * constants. This class should not be used for any other purpose. All constants should be declared * globally (i.e. public static). Do not put anything functional in this class. * * <p>It is advised to statically import this class (or one of its inner classes) wherever the * constants are needed, to reduce verbosity. */ public final class Constants { //Buttons public static final int gyroButton = 6; public static final int forceReverseIndexer = 5; public static final int runIntake = 2;//5; public static final int trackAndSpin = 2; public static final int shootBall = 1; public static final int setShoot = 11; public static final int turretManualOverride = 3; public static final int climbButton = 3; //Actually set //Joystick public static final int forwardAxis = 1; public static final int strafeAxis = 0; public static int manualTurretAxis = 2; //public static final int rotationAxis = 2; //Uncomment for cool joystick public static final int rotationAxis = 4; //Uncomment for other thing public static final Point[] cameraROI = new Point[]{new Point(0,0), new Point(50,50)}; public static final Color blueBall = new Color(0.16064453125, 0.42333984375, 0.416259765625); //Actually get real values public static final Color redBall = new Color(0.5029296875, 0.140380859375, 0.357177734375); public static final int ultrasonicPin = 0; //Climber public static final int climber1 = 0; //public static final int climber2 = 2; public static final double driveSpeedCap = 1; //Percent of max speed public static final double rotationSpeedCap = 0.6; /** * The left-to-right distance between the drivetrain wheels * * Should be measured from center to center. */ public static final double DRIVETRAIN_TRACKWIDTH_METERS = 0.5715; // FIXME Measure and set trackwidth /** * The front-to-back distance between the drivetrain wheels. * * Should be measured from center to center. */ public static final double DRIVETRAIN_WHEELBASE_METERS = 0.5715; // FIXME Measure and set wheelbase // public static final int DRIVETRAIN_PIGEON_ID = 0; // FIXME Set Pigeon ID public static final int FRONT_LEFT_MODULE_DRIVE_MOTOR = 2; // FIXME Set front left module drive motor ID public static final int FRONT_LEFT_MODULE_STEER_MOTOR = 4; // FIXME Set front left module steer motor ID public static final int FRONT_LEFT_MODULE_STEER_ENCODER = 3; // FIXME Set front left steer encoder ID // public static final double FRONT_LEFT_MODULE_STEER_OFFSET = -Math.toRadians(271.230469); // 360-88.769531 public static final double FRONT_LEFT_MODULE_STEER_OFFSET = -Math.toRadians(266.748047); // 360-88.769531 public static final int FRONT_RIGHT_MODULE_DRIVE_MOTOR = 5; // FIXME Set front right drive motor ID public static final int FRONT_RIGHT_MODULE_STEER_MOTOR = 7; // FIXME Set front right steer motor ID public static final int FRONT_RIGHT_MODULE_STEER_ENCODER = 6; // FIXME Set front right steer encoder ID // public static final double FRONT_RIGHT_MODULE_STEER_OFFSET = -Math.toRadians(94.482422); // 360-85.517578+180 public static final double FRONT_RIGHT_MODULE_STEER_OFFSET = -Math.toRadians(82.878113); public static final int BACK_LEFT_MODULE_DRIVE_MOTOR = 11; // FIXME Set back left drive motor ID public static final int BACK_LEFT_MODULE_STEER_MOTOR = 13; // FIXME Set back left steer motor ID public static final int BACK_LEFT_MODULE_STEER_ENCODER = 12; // FIXME Set back left steer encoder ID // public static final double BACK_LEFT_MODULE_STEER_OFFSET = -Math.toRadians(164.970703); // 360-15.0292971+180 public static final double BACK_LEFT_MODULE_STEER_OFFSET = -Math.toRadians(16.699219); public static final int BACK_RIGHT_MODULE_DRIVE_MOTOR = 8; // FIXME Set back right drive motor ID public static final int BACK_RIGHT_MODULE_STEER_MOTOR = 10; // FIXME Set back right steer motor ID public static final int BACK_RIGHT_MODULE_STEER_ENCODER = 9; // FIXME Set back right steer encoder ID public static final double BACK_RIGHT_MODULE_STEER_OFFSET = -Math.toRadians(139.828491);//139.471); // 360-155.654297+180 // Robot // units are in inches!! public static final double trackWidth = 22.5; public static final double wheelBase = 22.5; public static final int PH_ID = 31; public static final int HOOK_SOLENOID_1 = 1; public static final int HOOK_SOLENOID_2 = 2; public static final int LIFTER_SOLENOID = 7; //THESE UNITS ARE IN INCHES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! (!!) public static final double reflectiveStripWidth = 9.0; public static final double reflectiveStripHeight = 10.0; public static final double LIMELIGHTHEIGHT = 36; public static final double HUBHEIGHT = 105; // constant thing - no touchie public static final double TOINCHES = 0.81442; public static final double thing = 1.5; // In degrees public static final double LIMELIGHTANGLE = 25.5-0.2; public static final double TURRET_TOLERANCE = 1; public static final double SHOOTER_ENCODER_OFFSET = 0; //In rotations; shooter degree of movement clockwise and counterclockwise from the centerline public static final double SHOOTER_MAX_ROT_CLOCKWISE = 180.0;//45/8; public static final double SHOOTER_MAX_ROT_COUNTERCLOCK = 180;//-45/8; //can id public static final int TURN_MOTOR_ID = 22; public static final int SHOOTER_MOTOR_1_ID = 25; public static final int TURRET_ENCODER_ID = 9; public static final int SHOOTER_ENCODER_ID = 8; //public static final int SHOOTER_ENCODER_ID = 9; public static final int INTAKE_MOTOR_ID = 30; public static final int STORAGE_MOTOR_ID = 23; public static final int FEEDER_MOTOR_ID = 24; //public static final int INTAKE_MOTOR_ID = ; //public static final int DEPLOY_INTAKE_MOTOR_ID = ; //public static final int //PID constants: index 0 represents P, 1 represents I, 2, represents D //public static final double[] TURN_MOTOR_PID = new double[] {0.025, 0.000, 10, 0.0}; public static final double[] TURN_MOTOR_PID = new double[] {0.006, 0, 15, 0.0}; //public static final double[] TURN_MOTOR_PID = new double[] {0.02, 0.0002, 10, 0.0}; /* public static final double[] MASTER_SHOOTER_PID = new double[] {0.0004, 0.000001, 0.01};//.0004}; public static final double[] SLAVE_SHOOTER_PID = new double[] {0.0004, 0.000001, 0.01};//0004}; */ public static final double[] MASTER_SHOOTER_PID = new double[] {0.002, /*0.000000037*/0, 9};//.0004}; public static final double[] SLAVE_SHOOTER_PID = MASTER_SHOOTER_PID; // public static final double[] FEEDFORWARD = new double[] {0.00007,0};//{0.00002, 0.00002}; //le data public static final double[] DISTANCE = {77.476902, 95, 131.466488, 157, 185.365014, 204.941936, 242}; public static final double[] SPEED = {-2300, -2400, -2600, -2900, -3100, -3250, -3600}; //public static final double TRANSLATE = -1636.1; //public static final double SCALER = -7.9555; public static final double TRANSLATE = -1541.93- 105; public static final double SCALER = /*-8.17586;*/ -7.9; public static final double SHOOTER_SPROCKET_RATIO = 180/16.0; // les speed public static final double FLYWHEEL_TOLERANCE = 250;//50; //public static final double BACK_RIGHT_MODULE_STEER_OFFSET = -Math.toRadians(24.345703); // 360-155.654297+180 public static final double TURN = 5; public static final double TURRET_TURN_SPEED = 90; } //181.406250 //-1.757813 //170.332031 //-97.382813
47.783626
126
0.713866
ba4013d853ee5a13a7f56e72b8e87bf9db6c5f72
2,379
/* * Copyright (c) 2010, Stanislav Muhametsin. 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. * */ package org.sql.generation.implementation.grammar.builders.modification; import org.sql.generation.api.common.NullArgumentException; import org.sql.generation.api.grammar.builders.booleans.BooleanBuilder; import org.sql.generation.api.grammar.builders.modification.DeleteBySearchBuilder; import org.sql.generation.api.grammar.modification.DeleteBySearch; import org.sql.generation.api.grammar.modification.TargetTable; import org.sql.generation.implementation.grammar.common.SQLBuilderBase; import org.sql.generation.implementation.grammar.modification.DeleteBySearchImpl; import org.sql.generation.implementation.transformation.spi.SQLProcessorAggregator; /** * @author Stanislav Muhametsin */ public class DeleteBySearchBuilderImpl extends SQLBuilderBase implements DeleteBySearchBuilder { private final BooleanBuilder _whereBuilder; private TargetTable _targetTable; public DeleteBySearchBuilderImpl(final SQLProcessorAggregator processor, final BooleanBuilder whereBuilder) { super(processor); NullArgumentException.validateNotNull("where builder", whereBuilder); this._whereBuilder = whereBuilder; } @Override public DeleteBySearch createExpression() { return new DeleteBySearchImpl(this.getProcessor(), this._targetTable, this._whereBuilder.createExpression()); } @Override public DeleteBySearchBuilder setTargetTable(final TargetTable table) { NullArgumentException.validateNotNull("table", table); this._targetTable = table; return this; } @Override public TargetTable getTargetTable() { return this._targetTable; } @Override public BooleanBuilder getWhere() { return this._whereBuilder; } }
36.045455
117
0.76797
a8eeadfb0a558464779df728367141c56dd4e606
1,824
package com.openkappa.simd.base64; import java.util.concurrent.ThreadLocalRandom; import static java.nio.charset.StandardCharsets.UTF_8; public class StreamingBase64 { private static final byte[] ENCODING = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static final byte END = '='; public static void main(String... args) { byte[] in = new byte[1024]; ThreadLocalRandom.current().nextBytes(in); byte[] out = new byte[2000]; encodeChunkBuffered(in, out); System.out.println(new String(out, UTF_8)); System.out.println(new String(java.util.Base64.getEncoder().encode(in), UTF_8)); } public static void encodeChunkBuffered(byte[] in, byte[] out) { int i = 0; int j = 0; // 3 bytes in, 4 bytes out for (; j + 3 < out.length && i + 2 < in.length; i += 3, j += 4) { // map 3 bytes into the lower 24 bits of an integer int word = (in[i + 0] & 0xFF) << 16 | (in[i + 1] & 0xFF) << 8 | (in[i + 2] & 0xFF); // for each 6-bit subword, find the appropriate character in the lookup table out[j + 0] = (byte)lookup((word >>> 18) & 0x3F); out[j + 1] = (byte)lookup((word >>> 12) & 0x3F); out[j + 2] = (byte)lookup((word >>> 6) & 0x3F); out[j + 3] = (byte)lookup(word & 0x3F); } } private static int lookup(int i) { int shift = 'A'; shift += i >= 26 ? 6 : 0; shift -= i >= 52 ? 75 : 0; shift += i == 62 ? 241 : 0; shift -= i == 63 ? 12 : 0; return shift + i; } }
32.571429
89
0.495066
0f5dcabc1f1a0084d0d197c7b7866d13c4221aa6
321
package monty; import java.util.Random; public class SwitchingAgent implements Agent { private Random random = new Random(); @Override public int getInitialDoor(int numDoors) { return this.random.nextInt(numDoors); } @Override public boolean getSwitch() { return true; } }
17.833333
46
0.663551
2c85cf7c4270c01f8325397193961d3e9d8da05f
15,347
package lib.winmister332.wmlib.spigot.libraries.events; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerAdvancementDoneEvent; import org.bukkit.event.player.PlayerAnimationEvent; import org.bukkit.event.player.PlayerArmorStandManipulateEvent; import org.bukkit.event.player.PlayerBedEnterEvent; import org.bukkit.event.player.PlayerBedLeaveEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerBucketEvent; import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerChangedMainHandEvent; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerCommandSendEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerEditBookEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.event.player.PlayerInteractAtEntityEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemBreakEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerItemDamageEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.event.player.PlayerItemMendEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerLevelChangeEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPortalEvent; import org.bukkit.event.player.PlayerPickupArrowEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerToggleFlightEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.event.player.PlayerToggleSprintEvent; import org.bukkit.event.player.PlayerUnleashEntityEvent; import org.bukkit.event.player.PlayerVelocityEvent; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockCanBuildEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockExplodeEvent; import org.bukkit.event.block.BlockFormEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockRedstoneEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryCreativeEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.inventory.InventoryInteractEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryPickupItemEvent; import org.bukkit.event.server.BroadcastMessageEvent; import org.bukkit.event.server.MapInitializeEvent; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.server.ServerLoadEvent; import org.bukkit.event.server.TabCompleteEvent; import org.bukkit.event.server.ServerListPingEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkPopulateEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.PortalCreateEvent; import org.bukkit.event.world.SpawnChangeEvent; import org.bukkit.event.world.WorldInitEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldSaveEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityCreatePortalEvent; import org.bukkit.event.entity.EntityDamageByBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDropItemEvent; import org.bukkit.event.entity.EntityInteractEvent; import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.entity.EntityPortalEnterEvent; import org.bukkit.event.entity.EntityPortalExitEvent; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityPotionEffectEvent; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.EntityResurrectEvent; import org.bukkit.event.entity.EntitySpawnEvent; import org.bukkit.event.entity.EntityTargetLivingEntityEvent; import org.bukkit.event.entity.EntityTeleportEvent; import org.bukkit.event.entity.EntityUnleashEvent; import org.bukkit.event.entity.PlayerLeashEntityEvent; public abstract class EventHandler implements Listener { public static EventHandler INSTANCE = null; public EventHandler() { INSTANCE = this; } @org.bukkit.event.EventHandler public void onPlayerChatEvent(AsyncPlayerChatEvent event){} @org.bukkit.event.EventHandler public void onPlayerAdvancementEvent(PlayerAdvancementDoneEvent event){} @org.bukkit.event.EventHandler public void onPlayerAnimationEvent(PlayerAnimationEvent event){} @org.bukkit.event.EventHandler public void onPlayerArmorStandManipulateEvent(PlayerArmorStandManipulateEvent event){} @org.bukkit.event.EventHandler public void onPlayerBedEnterEvent(PlayerBedEnterEvent event){} @org.bukkit.event.EventHandler public void onPlayerBedLeaveEvent(PlayerBedLeaveEvent event){} @org.bukkit.event.EventHandler public void onPlayerBucketEmptyEvent(PlayerBucketEmptyEvent event){} @org.bukkit.event.EventHandler public void onPlayerBucketEvent(PlayerBucketEvent event){} @org.bukkit.event.EventHandler public void onPlayerBucketFillEvent(PlayerBucketFillEvent event){} @org.bukkit.event.EventHandler public void onPlayerChangedMainHandEvent(PlayerChangedMainHandEvent event){} @org.bukkit.event.EventHandler public void onPlayerChangedWorldEvent(PlayerChangedWorldEvent event){} @org.bukkit.event.EventHandler public void onPlayerCommandSendEvent(PlayerCommandSendEvent event){} @org.bukkit.event.EventHandler public void onPlayerDropItemEvent(PlayerDropItemEvent event){} @org.bukkit.event.EventHandler public void onPlayerEditBookEvent(PlayerEditBookEvent event){} @org.bukkit.event.EventHandler public void onPlayerGameModeChangeEvent(PlayerGameModeChangeEvent event){} @org.bukkit.event.EventHandler public void onPlayerExpChangeEvent(PlayerExpChangeEvent event){} @org.bukkit.event.EventHandler public void onPlayerInteractAtEntityEvent(PlayerInteractAtEntityEvent event){} @org.bukkit.event.EventHandler public void onPlayerInteractEntityEvent(PlayerInteractEntityEvent event){} @org.bukkit.event.EventHandler public void onPlayerInteractEvent(PlayerInteractEvent event){} @org.bukkit.event.EventHandler public void onPlayerItemBreakEvent(PlayerItemBreakEvent event){} @org.bukkit.event.EventHandler public void onPlayerItemConsumeEvent(PlayerItemConsumeEvent event){} @org.bukkit.event.EventHandler public void onPlayerItemDamageEvent(PlayerItemDamageEvent event){} @org.bukkit.event.EventHandler public void onPlayerItemHeldEvent(PlayerItemHeldEvent event){} @org.bukkit.event.EventHandler public void onPlayerItemMendEvent(PlayerItemMendEvent event){} @org.bukkit.event.EventHandler public void onPlayerJoinEvent(PlayerJoinEvent event){} @org.bukkit.event.EventHandler public void onPlayerLevelChangeEvent(PlayerLevelChangeEvent event){} @org.bukkit.event.EventHandler public void onPlayerKickEvent(PlayerKickEvent event){} @org.bukkit.event.EventHandler public void onPlayerMoveEvent(PlayerMoveEvent event){} @org.bukkit.event.EventHandler public void onPlayerPortalEvent(PlayerPortalEvent event){} @org.bukkit.event.EventHandler public void onPlayerPickupArrowEvent(PlayerPickupArrowEvent event){} @org.bukkit.event.EventHandler public void onPlayerQuitEvent(PlayerQuitEvent event){} @org.bukkit.event.EventHandler public void onPlayerRespawnEvent(PlayerRespawnEvent event){} @org.bukkit.event.EventHandler public void onPlayerTeleportEvent(PlayerTeleportEvent event){} @org.bukkit.event.EventHandler public void onPlayerToggleFlightEvent(PlayerToggleFlightEvent event){} @org.bukkit.event.EventHandler public void onPlayerToggleSneakEvent(PlayerToggleSneakEvent event){} @org.bukkit.event.EventHandler public void onPlayerToggleSprintEvent(PlayerToggleSprintEvent event){} @org.bukkit.event.EventHandler public void onPlayerUnleashEntityEvent(PlayerUnleashEntityEvent event){} @org.bukkit.event.EventHandler public void onPlayerVelocityEvent(PlayerVelocityEvent event){} @org.bukkit.event.EventHandler public void onBlockBreakEvent(BlockBreakEvent event) {} @org.bukkit.event.EventHandler public void onBlockBurnEvent(BlockBurnEvent event) {} @org.bukkit.event.EventHandler public void onBlockCanBuildEvent(BlockCanBuildEvent event) {} @org.bukkit.event.EventHandler public void onBlockDamageEvent(BlockDamageEvent event) {} @org.bukkit.event.EventHandler public void onBlockExplodeEvent(BlockExplodeEvent event) {} @org.bukkit.event.EventHandler public void onBlockFormEvent(BlockFormEvent event) {} @org.bukkit.event.EventHandler public void onBlockIgniteEvent(BlockIgniteEvent event) {} @org.bukkit.event.EventHandler public void onBlockPlaceEvent(BlockPlaceEvent event) {} @org.bukkit.event.EventHandler public void onBlockRedstoneEvent(BlockRedstoneEvent event) {} @org.bukkit.event.EventHandler public void onBlockSignChangeEvent(SignChangeEvent event) {} @org.bukkit.event.EventHandler public void onEnchantItemEvent(EnchantItemEvent event) {} @org.bukkit.event.EventHandler public void onInventoryClickEvent(InventoryClickEvent event) {} @org.bukkit.event.EventHandler public void onInventoryCloseEvent(InventoryCloseEvent event) {} @org.bukkit.event.EventHandler public void onInventoryCreativeEvent(InventoryCreativeEvent event) {} @org.bukkit.event.EventHandler public void onInventoryInteractEvent(InventoryInteractEvent event) {} @org.bukkit.event.EventHandler public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) {} @org.bukkit.event.EventHandler public void onInventoryOpenEvent(InventoryOpenEvent event) {} @org.bukkit.event.EventHandler public void onInventoryPickupItemEvent(InventoryPickupItemEvent event) {} @org.bukkit.event.EventHandler public void onInventoryDragEvent(InventoryDragEvent event) {} @org.bukkit.event.EventHandler public void onBroadcastMessageEvent(BroadcastMessageEvent event) {} @org.bukkit.event.EventHandler public void onMapInitializeEvent(MapInitializeEvent event) {} @org.bukkit.event.EventHandler public void onPluginDisableEvent(PluginDisableEvent event) {} @org.bukkit.event.EventHandler public void onPluginEnableEvent(PluginEnableEvent event) {} @org.bukkit.event.EventHandler public void onServerCommandEvent(ServerCommandEvent event) {} @org.bukkit.event.EventHandler public void onServerLoadEvent(ServerLoadEvent event) {} @org.bukkit.event.EventHandler public void onTabCompleteEvent(TabCompleteEvent event) {} @org.bukkit.event.EventHandler public void onServerListPingEvent(ServerListPingEvent event) {} @org.bukkit.event.EventHandler public void onChunkLoadEvent(ChunkLoadEvent event) {} @org.bukkit.event.EventHandler public void onChunkPopulate(ChunkPopulateEvent event) {} @org.bukkit.event.EventHandler public void onChunkUnloadEvent(ChunkUnloadEvent event) {} @org.bukkit.event.EventHandler public void onPortalCreateEvent(PortalCreateEvent event) {} @org.bukkit.event.EventHandler public void onSpawnChangeEvent(SpawnChangeEvent event) {} @org.bukkit.event.EventHandler public void onWorldInitEvent(WorldInitEvent event) {} @org.bukkit.event.EventHandler public void onWorldLoadEvent(WorldLoadEvent event) {} @org.bukkit.event.EventHandler public void onWorldSaveEvent(WorldSaveEvent event) {} @org.bukkit.event.EventHandler public void onWorldUnloadEvent(WorldUnloadEvent event) {} @org.bukkit.event.EventHandler public void onPlayerDeathEvent(PlayerDeathEvent event) {} @org.bukkit.event.EventHandler public void onCreatureSpawnEvent(CreatureSpawnEvent event) {} @org.bukkit.event.EventHandler public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) {} @org.bukkit.event.EventHandler public void onEntityCreatePortalEvent(EntityCreatePortalEvent event) {} @org.bukkit.event.EventHandler public void onEntityDamageEvent(EntityDamageEvent event) {} @org.bukkit.event.EventHandler public void onEntityDamageByBlockEvent(EntityDamageByBlockEvent event) {} @org.bukkit.event.EventHandler public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {} @org.bukkit.event.EventHandler public void onEntityDeathEvent(EntityDeathEvent event) {} @org.bukkit.event.EventHandler public void onEntityDropItemEvent(EntityDropItemEvent event) {} @org.bukkit.event.EventHandler public void onEntityInteractEvent(EntityInteractEvent event) {} @org.bukkit.event.EventHandler public void onEntityPickupEvent(EntityPickupItemEvent event) {} @org.bukkit.event.EventHandler public void onEntityPortalEnterEvent(EntityPortalEnterEvent event) {} @org.bukkit.event.EventHandler public void onEntityPortalExitEvent(EntityPortalExitEvent event) {} @org.bukkit.event.EventHandler public void onEntityPortalEvent(EntityPortalEvent event) {} @org.bukkit.event.EventHandler public void onEntityPotionEffectEvent(EntityPotionEffectEvent event) {} @org.bukkit.event.EventHandler public void onEntityRegainHealthEvent(EntityRegainHealthEvent event) {} @org.bukkit.event.EventHandler public void onEntityResurrectEvent(EntityResurrectEvent event) {} @org.bukkit.event.EventHandler public void onEntitySpawnEvent(EntitySpawnEvent event) {} @org.bukkit.event.EventHandler public void onEntityTargetLivingEntityEvent(EntityTargetLivingEntityEvent event) {} @org.bukkit.event.EventHandler public void onEntityTeleportEvent(EntityTeleportEvent event) {} @org.bukkit.event.EventHandler public void onEntityUnleashEvent(EntityUnleashEvent event) {} @org.bukkit.event.EventHandler public void onEntityLeashEntityEvent(PlayerLeashEntityEvent event) {} }
37.431707
90
0.807259
89120e944e5dbfa65d2a957ce54e70c0ba66fd80
639
package com.oracle.truffle.sl.rev; import com.oracle.truffle.sl.nodes.SLTypes; import java.util.HashMap; import java.util.Map; public class MySLTypesT implements SLTypesT { private final static Map<SLTypes, SLTypesT> cache = new HashMap<>(); private final ExecSLRevisitor alg; private final SLTypes it; private MySLTypesT(ExecSLRevisitor alg, SLTypes it) { this.alg = alg; this.it = it; } public static SLTypesT INSTANCE(ExecSLRevisitor alg, SLTypes it) { if (!cache.containsKey(it)) { cache.put(it, new MySLTypesT(alg, it)); } return cache.get(it); } }
25.56
72
0.663537
e3731e668ce18031315097f2be13ed4c8fd3fb48
4,118
package com.configcat; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.jupiter.api.Assertions.*; public class AutoPollingPolicyIntegrationTest { private AutoPollingPolicy policy; private MockWebServer server; @BeforeEach public void setUp() throws IOException { this.server = new MockWebServer(); this.server.start(); PollingMode pollingMode = PollingModes.AutoPoll(2); ConfigFetcher fetcher = new ConfigFetcher(new OkHttpClient.Builder().build(), "", this.server.url("/").toString(), PollingModes.AutoPoll(2)); ConfigCache cache = new InMemoryConfigCache(); this.policy = (AutoPollingPolicy)pollingMode.accept(new RefreshPolicyFactory(cache, fetcher)); } @AfterEach public void tearDown() throws IOException { this.policy.close(); this.server.shutdown(); } @Test public void ensuresPollingIntervalGreaterThanTwoSeconds() { assertThrows(IllegalArgumentException.class, ()-> PollingModes.AutoPoll(1)); } @Test public void get() throws InterruptedException, ExecutionException { this.server.enqueue(new MockResponse().setResponseCode(200).setBody("test")); this.server.enqueue(new MockResponse().setResponseCode(200).setBody("test2").setBodyDelay(3, TimeUnit.SECONDS)); //first call assertEquals("test", this.policy.getConfigurationJsonAsync().get()); //wait for cache refresh Thread.sleep(6000); //next call will get the new value assertEquals("test2", this.policy.getConfigurationJsonAsync().get()); } @Test public void getFail() throws InterruptedException, ExecutionException { this.server.enqueue(new MockResponse().setResponseCode(500).setBody("")); //first call assertEquals(null, this.policy.getConfigurationJsonAsync().get()); } @Test public void getMany() throws InterruptedException, ExecutionException { this.server.enqueue(new MockResponse().setResponseCode(200).setBody("test")); this.server.enqueue(new MockResponse().setResponseCode(200).setBody("test2")); this.server.enqueue(new MockResponse().setResponseCode(200).setBody("test3")); this.server.enqueue(new MockResponse().setResponseCode(200).setBody("test4")); //first calls assertEquals("test", this.policy.getConfigurationJsonAsync().get()); assertEquals("test", this.policy.getConfigurationJsonAsync().get()); assertEquals("test", this.policy.getConfigurationJsonAsync().get()); //wait for cache refresh Thread.sleep(2500); //next call will get the new value assertEquals("test2", this.policy.getConfigurationJsonAsync().get()); //wait for cache refresh Thread.sleep(2500); //next call will get the new value assertEquals("test3", this.policy.getConfigurationJsonAsync().get()); //wait for cache refresh Thread.sleep(2500); //next call will get the new value assertEquals("test4", this.policy.getConfigurationJsonAsync().get()); } @Test public void getWithFailedRefresh() throws InterruptedException, ExecutionException { this.server.enqueue(new MockResponse().setResponseCode(200).setBody("test")); this.server.enqueue(new MockResponse().setResponseCode(500)); //first call assertEquals("test", this.policy.getConfigurationJsonAsync().get()); //wait for cache invalidation Thread.sleep(3000); //previous value returned because of the refresh failure assertEquals("test", this.policy.getConfigurationJsonAsync().get()); } }
35.5
120
0.688441
de45a59aa0649b9a968ed8c173d306760a6edc1b
4,685
package core.parsers; import core.commands.Context; import core.commands.ContextSlashReceived; import core.exceptions.LastFmException; import core.parsers.explanation.util.Explanation; import core.parsers.explanation.util.ExplanationLine; import core.parsers.explanation.util.ExplanationLineType; import core.parsers.params.EnumParameters; import dao.exceptions.InstanceNotFoundException; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Optional; public class EnumParser<T extends Enum<T>> extends Parser<EnumParameters<T>> { protected final Class<T> clazz; private final boolean allowEmpty; private final boolean hasParams; private final boolean continueOnNomatch; public EnumParser(Class<T> tClass) { this(tClass, false, false, false); } public EnumParser(Class<T> tClass, boolean allowEmpty, boolean hasParams, boolean continueOnNomatch) { this.clazz = tClass; this.allowEmpty = allowEmpty; this.hasParams = hasParams; this.continueOnNomatch = continueOnNomatch; } @Override protected void setUpErrorMessages() { } @Override public EnumParameters<T> parseSlashLogic(ContextSlashReceived ctx) throws LastFmException, InstanceNotFoundException { EnumSet<T> ts = EnumSet.allOf(clazz); List<String> lines = ts.stream().map(x -> x.name().replaceAll("_", "-").toLowerCase()).toList(); SlashCommandEvent e = ctx.e(); Optional<String> option = Optional.ofNullable(e.getOption("option")).map(OptionMapping::getAsString); if (option.isEmpty()) { if (allowEmpty) { return new EnumParameters<>(ctx, null, null); } sendError("Pls introduce only one of the following: **" + String.join("**, **", lines) + "**", ctx); return null; } String param = Optional.ofNullable(e.getOption("parameter")).map(OptionMapping::getAsString).orElse(null); return new EnumParameters<>(ctx, option.map(z -> Enum.valueOf(clazz, z.toUpperCase().replaceAll("-", "_"))).orElse(null), param); } @Override protected EnumParameters<T> parseLogic(Context e, String[] words) { EnumSet<T> ts = EnumSet.allOf(clazz); List<String> lines = ts.stream().map(x -> x.name().replaceAll("_", "-").toLowerCase()).toList(); if (words.length == 0) { if (allowEmpty) { return new EnumParameters<>(e, null, null); } sendError("Pls introduce only one of the following: **" + String.join("**, **", lines) + "**", e); return null; } else if (words.length > 1) { if (!hasParams) { sendError("Pls introduce only one of the following: **" + String.join("**, **", lines) + "**", e); return null; } } Optional<String> first = lines.stream().filter(x -> words[0].equalsIgnoreCase(x)).findFirst(); if (first.isEmpty()) { if (continueOnNomatch) { return new EnumParameters<>(e, null, String.join(" ", words)); } sendError("Pls introduce one of the following: " + String.join(",", lines), e); return null; } String params; if (words.length > 1) { params = String.join(" ", Arrays.copyOfRange(words, 1, words.length)); } else { params = null; } return new EnumParameters<>(e, Enum.valueOf(clazz, first.get().toUpperCase().replaceAll("-", "_")), params); } @Override public List<Explanation> getUsages() { List<String> lines = EnumSet.allOf(clazz).stream().map(x -> x.name().replaceAll("_", "-").toLowerCase()).toList(); OptionData data = new OptionData(OptionType.STRING, "option", "One of the possible configuration values"); if (!allowEmpty) { data.setRequired(true); } for (String line : lines) { data.addChoice(line, line); } Explanation option = () -> new ExplanationLine("option", "Option being one of: **" + String.join("**, **", lines) + "**", data); if (hasParams) { Explanation params = () -> new ExplanationLineType("parameter", "Parameter for option", OptionType.STRING); return List.of(option, params); } return List.of(option); } }
39.369748
137
0.624973
8f03a019df3fcf50bdc1249b864e4cebe65bc2e3
1,839
package com.vidya.poc.camel; import org.apache.camel.EndpointInject; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.model.ModelCamelContext; import org.apache.camel.test.spring.MockEndpoints; import org.apache.camel.test.spring.UseAdviceWith; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @MockEndpoints @UseAdviceWith @ContextConfiguration({ "classpath:META-INF/spring/camel-context-test.xml" }) public class HTTPUrlInvocationTest { @Produce(uri = "direct:start") private ProducerTemplate template; @EndpointInject(uri = "mock:advised") private MockEndpoint mockResultEndPoint; @Autowired private ModelCamelContext modelCamelContext; // This method invokes the Mock end point URL when ever tests are run. @Test public void test_happy_path_mock_endpoint_url() throws Exception { modelCamelContext.getRouteDefinition("urlInvocation").adviceWith(modelCamelContext, new RouteBuilder() { @Override public void configure() throws Exception { // intercept sending to mock:foo and do something else interceptSendToEndpoint("https:*").skipSendToOriginalEndpoint().to("mock:advised"); } }); template.sendBody("Himalayas"); mockResultEndPoint.expectedMessageCount(1); mockResultEndPoint.assertIsSatisfied(); } }
34.055556
106
0.813486
92568e13bfa7ea3bc824c9ff0d0ff5aa9b3adf58
690
package com.careydevelopment.ecosystem.customer.service; import org.springframework.http.HttpStatus; public class ServiceException extends RuntimeException { private static final long serialVersionUID = -7661881974219233311L; private int statusCode; public ServiceException (String message, HttpStatus httpStatus) { super(message); if (httpStatus != null) this.statusCode = httpStatus.value(); else this.statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value(); } public ServiceException (String message, int statusCode) { super(message); this.statusCode = statusCode; } public int getStatusCode() { return statusCode; } }
25.555556
70
0.730435
4943db716351df247edaebe8350ad274d9711ae7
2,379
package com.judgelee.viewdrawdemo.customdraw.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ComposePathEffect; import android.graphics.CornerPathEffect; import android.graphics.DashPathEffect; import android.graphics.DiscretePathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathDashPathEffect; import android.graphics.PathEffect; import android.graphics.RectF; import android.graphics.SumPathEffect; import android.view.View; /** * Author: lijiajie * Date: 2019/3/8 * Desc: */ public class PathEffectView extends View { private Paint mPaint; private PathEffect[] mPathEffects; private Path mRandomPath; public PathEffectView(Context context) { super(context); init(); } private void init() { mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.BLACK); mPaint.setStrokeWidth(3); mRandomPath = new Path(); mRandomPath.moveTo(10, 50); for (int i = 3; i < 30; i++) { mRandomPath.lineTo(i * 35, (float) (Math.random() * 100)); //mRandomPath.rLineTo(i * 35, (float) (Math.random() * 100)); } mPathEffects = new PathEffect[7]; mPathEffects[0] = new PathEffect(); mPathEffects[1] = new CornerPathEffect(3000); mPathEffects[2] = new DiscretePathEffect(10, 10); mPathEffects[3] = new DashPathEffect(new float[] { 20, 5 }, 2000); Path trianglePath = new Path(); trianglePath.addCircle(0, 0, 5, Path.Direction.CCW); mPathEffects[4] = new PathDashPathEffect(trianglePath, 30, 0, PathDashPathEffect.Style.TRANSLATE); mPathEffects[5] = new ComposePathEffect(mPathEffects[3], mPathEffects[1]); mPathEffects[6] = new SumPathEffect(mPathEffects[3], mPathEffects[1]); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < 7; i++) { mPaint.setPathEffect(mPathEffects[i]); canvas.translate(0, 100); if (i == 6) { mRandomPath.offset(0, 300); mRandomPath.lineTo(30, 20); } canvas.drawPath(mRandomPath, mPaint); if (i == 6) { RectF rectF = new RectF(); mRandomPath.computeBounds(rectF, true); mPaint.setPathEffect(new PathEffect()); canvas.drawRect(rectF, mPaint); } } } }
26.730337
102
0.68348
c356ebc4af4bee7ced48c02fa068309eeb94fe5b
3,472
package org.anddev.andengine.engine; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.input.touch.TouchEvent; public class DoubleSceneSplitScreenEngine extends Engine { private Camera mSecondCamera; private Scene mSecondScene; public DoubleSceneSplitScreenEngine(EngineOptions paramEngineOptions, Camera paramCamera) { super(paramEngineOptions); this.mSecondCamera = paramCamera; } protected void convertSurfaceToSceneTouchEvent(Camera paramCamera, TouchEvent paramTouchEvent) { int i = this.mSurfaceWidth >> 1; if (paramCamera == getFirstCamera()) { paramCamera.convertSurfaceToSceneTouchEvent(paramTouchEvent, i, this.mSurfaceHeight); return; } paramTouchEvent.offset(-i, 0.0F); paramCamera.convertSurfaceToSceneTouchEvent(paramTouchEvent, i, this.mSurfaceHeight); } @Deprecated public Camera getCamera() { return this.mCamera; } protected Camera getCameraFromSurfaceTouchEvent(TouchEvent paramTouchEvent) { if (paramTouchEvent.getX() <= this.mSurfaceWidth >> 1) { return getFirstCamera(); } return getSecondCamera(); } public Camera getFirstCamera() { return this.mCamera; } public Scene getFirstScene() { return super.getScene(); } @Deprecated public Scene getScene() { return super.getScene(); } protected Scene getSceneFromSurfaceTouchEvent(TouchEvent paramTouchEvent) { if (paramTouchEvent.getX() <= this.mSurfaceWidth >> 1) { return getFirstScene(); } return getSecondScene(); } public Camera getSecondCamera() { return this.mSecondCamera; } public Scene getSecondScene() { return this.mSecondScene; } protected void onDrawScene(GL10 paramGL10) { Camera localCamera1 = getFirstCamera(); Camera localCamera2 = getSecondCamera(); int i = this.mSurfaceWidth >> 1; int j = this.mSurfaceHeight; paramGL10.glEnable(3089); paramGL10.glScissor(0, 0, i, j); paramGL10.glViewport(0, 0, i, j); this.mScene.onDraw(paramGL10, localCamera1); localCamera1.onDrawHUD(paramGL10); paramGL10.glScissor(i, 0, i, j); paramGL10.glViewport(i, 0, i, j); this.mSecondScene.onDraw(paramGL10, localCamera2); localCamera2.onDrawHUD(paramGL10); paramGL10.glDisable(3089); } protected void onUpdateScene(float paramFloat) { super.onUpdateScene(paramFloat); if (this.mSecondScene != null) { this.mSecondScene.onUpdate(paramFloat); } } public void setFirstScene(Scene paramScene) { super.setScene(paramScene); } @Deprecated public void setScene(Scene paramScene) { super.setScene(paramScene); } public void setSecondScene(Scene paramScene) { this.mSecondScene = paramScene; } protected void updateUpdateHandlers(float paramFloat) { super.updateUpdateHandlers(paramFloat); getSecondCamera().onUpdate(paramFloat); } } /* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar * Qualified Name: org.anddev.andengine.engine.DoubleSceneSplitScreenEngine * JD-Core Version: 0.7.0.1 */
25.910448
97
0.683468
10d040590988cdfb4ad843dd325bbc5bdb86255c
2,970
package projectzulu.common.mobs.entitydefaults; import java.util.HashSet; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Items; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.BiomeDictionary.Type; import net.minecraftforge.common.config.Configuration; import projectzulu.common.api.CustomMobData; import projectzulu.common.api.ItemList; import projectzulu.common.core.ConfigHelper; import projectzulu.common.core.DefaultProps; import projectzulu.common.core.ItemGenerics; import projectzulu.common.core.entitydeclaration.EntityProperties; import projectzulu.common.core.entitydeclaration.SpawnableDeclaration; import projectzulu.common.mobs.entity.EntityEagle; import projectzulu.common.mobs.models.ModelEagle; import projectzulu.common.mobs.renders.RenderGenericLiving; import projectzulu.common.mobs.renders.RenderWrapper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class EagleDeclaration extends SpawnableDeclaration { public EagleDeclaration() { super("Eagle", 35, EntityEagle.class, EnumCreatureType.ambient); setSpawnProperties(5, 5, 1, 1); setRegistrationProperties(128, 3, true); setDropAmount(0, 2); eggColor1 = (224 << 16) + (224 << 8) + 224; eggColor2 = (28 << 16) + (21 << 8) + 17; } @Override public void outputDataToList(Configuration config, CustomMobData customMobData) { ConfigHelper.configDropToMobData(config, "MOB CONTROLS." + mobName, customMobData, Items.chicken, 0, 10); ConfigHelper.configDropToMobData(config, "MOB CONTROLS." + mobName, customMobData, Items.feather, 0, 8); ConfigHelper.configDropToMobData(config, "MOB CONTROLS." + mobName, customMobData, ItemList.genericCraftingItems, ItemGenerics.Properties.Talon.meta(), 4); ConfigHelper.configDropToMobData(config, "MOB CONTROLS." + mobName, customMobData, ItemList.genericCraftingItems, ItemGenerics.Properties.SmallHeart.meta(), 4); customMobData.entityProperties = new EntityProperties(20f, 4.0f, 0.22f).createFromConfig(config, mobName); super.outputDataToList(config, customMobData); } @Override @SideOnly(Side.CLIENT) public RenderWrapper getEntityrender(Class<? extends EntityLivingBase> entityClass) { return new RenderGenericLiving(new ModelEagle(), 0.5f, new ResourceLocation(DefaultProps.mobKey, "eagle.png")); } @Override public HashSet<String> getDefaultBiomesToSpawn() { HashSet<String> defaultBiomesToSpawn = new HashSet<String>(); defaultBiomesToSpawn.add(BiomeGenBase.extremeHills.biomeName); defaultBiomesToSpawn.add(BiomeGenBase.extremeHillsEdge.biomeName); defaultBiomesToSpawn.addAll(typeToArray(Type.MOUNTAIN)); return defaultBiomesToSpawn; } }
45.692308
119
0.759259
16457b03c821459e6df29b401e22e1ed377a9504
356
package com.rishi.frendzapp.ui.base; import android.content.Context; //It class uses for delegate functionality from Activity public abstract class BaseActivityHelper { private Context context; public BaseActivityHelper(Context context) { this.context = context; } public Context getContext() { return context; } }
19.777778
56
0.713483
44cd686d572f254008f58e37061579a79a7cbea2
3,074
package ru.job4j.search; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.stream.IntStream; /** * @author Oxana Menushina (oxsm@mail.ru). * @version $Id$ * @since 0.1 */ public class Arguments { private Map<String, String> args; /** * Конструктор. * Инициализирует ассоциативный массив args, * в котором ключи - ключи из массива входных параметров, * значения - значения ключей из массива входных параметров, * @param input массив входных параметров. */ public Arguments(String[] input) { this.args = new HashMap<>(); this.args.put("-d", null); this.args.put("-n", null); this.args.put("-m", null); this.args.put("-f", null); this.args.put("-r", null); this.args.put("-o", null); IntStream.range(0, input.length).forEach(i -> args.replace(input[i], null, (i < input.length - 1) && !"-m".equals(input[i]) && !"-f".equals(input[i]) && !"-l".equals(input[i]) ? input[i + 1] : input[i])); } /** * Метод возвращает директорию, * в котораой начинать поис заданных файлов. * @return директория, * в котораой начинать поис заданных файлов. */ public String directory() { return this.args.get("-d"); } /** * Метод возвращает имя файла или маску для поиска файлов. * @return имя файла, маску для поиска файлов. */ public String fileName() { return this.args.get("-n"); } /** * Метод возвращает критерий поиска файлов: * -m - искать по маске, * -f - полное совпадение имени. * @return критерий поиска файлов. */ public String criterion() { return this.args.get("-m") != null ? "-m" : "-f"; } /** * Метод возвращает значение отличное от null, * если нужно искать файлы с уровнем доступа только для чтения, * null - если данный ключ не задан, * т.е искать файлы с любым уровнем доступа. * @return значение уровня доступа: * null - поиск файлов с любым уровнем доступа, * не null - поиск файлов с уровнем доступа только для чтения. */ public String accessLevel() { return this.args.get("-l"); } /** * Метод возвращает название файла, * в который нужно записать результаты поиска. * @return название файла, * для записи результатов поиска. */ public String output() { return this.args.get("-o"); } /** * Валидация ключей. */ public void validate() { if (this.args.get("-d") == null || this.args.get("-n") == null || this.args.get("-o") == null || (this.args.get("-m") == null ^ this.args.get("-f") == null)) { throw new IncorrectDataException("Введены не все данные."); } Path path = Paths.get(this.args.get("-d")); if (!Files.exists(path)) { throw new IncorrectDataException("Данная директория не существует."); } } }
30.137255
122
0.583604
2f6330283a40dbd4c8bf22d4f94dbf945f7251af
2,532
/* * The contents of this file are subject to the terms of the Common Development * and Distribution License (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at http://www.netbeans.org/cddl.html * or http://www.netbeans.org/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.netbeans.org/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. */ package org.netbeans.modules.erlang.project; import java.io.IOException; import org.netbeans.api.project.Project; import org.netbeans.modules.erlang.makeproject.spi.support.RakeBasedProjectType; import org.netbeans.modules.erlang.makeproject.spi.support.RakeProjectHelper; /** * Factory for simple Ruby projects. * @author Jesse Glick */ @org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.erlang.makeproject.spi.support.RakeBasedProjectType.class) public final class RubyProjectType implements RakeBasedProjectType { public static final String TYPE = "org.netbeans.modules.erlang.project"; // NOI18N private static final String PROJECT_CONFIGURATION_NAME = "data"; // NOI18N public static final String PROJECT_CONFIGURATION_NAMESPACE = "http://www.netbeans.org/ns/erlang-project/1"; // NOI18N private static final String PRIVATE_CONFIGURATION_NAME = "data"; // NOI18N private static final String PRIVATE_CONFIGURATION_NAMESPACE = "http://www.netbeans.org/ns/erlang-project-private/1"; // NOI18N /** Do nothing, just a service. */ public RubyProjectType() {} public String getType() { return TYPE; } public Project createProject(RakeProjectHelper helper) throws IOException { return new RubyProject(helper); } public String getPrimaryConfigurationDataElementName(boolean shared) { return shared ? PROJECT_CONFIGURATION_NAME : PRIVATE_CONFIGURATION_NAME; } public String getPrimaryConfigurationDataElementNamespace(boolean shared) { return shared ? PROJECT_CONFIGURATION_NAMESPACE : PRIVATE_CONFIGURATION_NAMESPACE; } }
42.2
130
0.756714
e437b1ff3b8b5c787f1f9e97058c2039b7745690
1,310
// // Decompiled by Procyon v0.5.36 // package org.apache.maven.scm.provider.cvslib.cvsexe.command.diff; import org.codehaus.plexus.util.cli.CommandLineException; import org.apache.maven.scm.ScmException; import org.codehaus.plexus.util.cli.StreamConsumer; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.apache.maven.scm.provider.cvslib.command.diff.CvsDiffConsumer; import org.apache.maven.scm.command.diff.DiffScmResult; import org.codehaus.plexus.util.cli.Commandline; import org.apache.maven.scm.provider.cvslib.command.diff.AbstractCvsDiffCommand; public class CvsExeDiffCommand extends AbstractCvsDiffCommand { @Override protected DiffScmResult executeCvsCommand(final Commandline cl) throws ScmException { final CvsDiffConsumer consumer = new CvsDiffConsumer(this.getLogger(), cl.getWorkingDirectory()); final CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer(); try { CommandLineUtils.executeCommandLine(cl, consumer, stderr); } catch (CommandLineException ex) { throw new ScmException("Error while executing command.", ex); } return new DiffScmResult(cl.toString(), consumer.getChangedFiles(), consumer.getDifferences(), consumer.getPatch()); } }
42.258065
124
0.764885
009bfb14a351916780a8fb269bf7e7a9c7cfefe2
1,379
import java.util.*; public class DriverS { public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.println("Enter 1 for Stack_ArrayList "); System.out.println("Enter 2 for Stack_LinearList "); System.out.println("Enter your choice "); Integer choice = in.nextInt(); switch(choice) { case 1: Stack_ArrayList ob = new Stack_ArrayList<Integer>(); ob.push(1); ob.push(2); ob.push(3); ob.push(4); ob.push(5); System.out.println("Size of Stack is : " + ob.Size()); System.out.println("Removing topmost element ... "+ob.pop()); System.out.println("Displaying topmost element ... " +ob.peek()); break; case 2: Stack_LinearList ob1 = new Stack_LinearList<Integer>(); ob1.push(1); ob1.push(2); ob1.push(3); ob1.push(4); ob1.push(5); System.out.println("Size of Stack is : " + ob1.Size()); System.out.println("Removing topmost element ... "+ob1.pop()); System.out.println("Displaying topmost element ... " +ob1.peek()); break; default: System.out.println("Wrong Choice!!"); } } }
33.634146
78
0.509065
f877f8cb1b64c75cb48877421730a4ea25ba0a95
2,326
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.access; import org.springframework.beans.factory.BeanFactory; /** * Used to track a reference to a {@link BeanFactory} obtained through * a {@link BeanFactoryLocator}. * * <p>It is safe to call {@link #release()} multiple times, but * {@link #getFactory()} must not be called after calling release. * * @author Colin Sampaleanu * @see BeanFactoryLocator * @see org.springframework.context.access.ContextBeanFactoryReference */ public interface BeanFactoryReference { /** * Return the {@link BeanFactory} instance held by this reference. * @throws IllegalStateException if invoked after {@code release()} has been called */ BeanFactory getFactory(); /** * Indicate that the {@link BeanFactory} instance referred to by this object is not * needed any longer by the client code which obtained the {@link BeanFactoryReference}. * <p>Depending on the actual implementation of {@link BeanFactoryLocator}, and * the actual type of {@code BeanFactory}, this may possibly not actually * do anything; alternately in the case of a 'closeable' {@code BeanFactory} * or derived class (such as {@link org.springframework.context.ApplicationContext}) * may 'close' it, or may 'close' it once no more references remain. * <p>In an EJB usage scenario this would normally be called from * {@code ejbRemove()} and {@code ejbPassivate()}. * <p>This is safe to call multiple times. * @see BeanFactoryLocator * @see org.springframework.context.access.ContextBeanFactoryReference * @see org.springframework.context.ConfigurableApplicationContext#close() */ void release(); }
40.103448
90
0.72399
80539161210ebb405afac600b5d007b08ad604a9
1,796
package mage.cards.d; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.keyword.CyclingAbility; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.AbilityPredicate; import mage.target.common.TargetCreaturePermanent; /** * * @author jonubuu */ public final class DeadshotMinotaur extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creature with flying"); static { filter.add(new AbilityPredicate(FlyingAbility.class)); } public DeadshotMinotaur(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{R}{G}"); this.subtype.add(SubType.MINOTAUR); this.power = new MageInt(3); this.toughness = new MageInt(4); // When Deadshot Minotaur enters the battlefield, it deals 3 damage to target creature with flying. Ability ability = new EntersBattlefieldTriggeredAbility(new DamageTargetEffect(3, "it"), false); ability.addTarget(new TargetCreaturePermanent(filter)); this.addAbility(ability); // Cycling {RG} this.addAbility(new CyclingAbility(new ManaCostsImpl("{R/G}"))); } public DeadshotMinotaur(final DeadshotMinotaur card) { super(card); } @Override public DeadshotMinotaur copy() { return new DeadshotMinotaur(this); } }
30.965517
110
0.740535
6e7bb8a677a227ae7eee65de536d70830396f7f8
787
package net.open_services.scheck.annotations; /** * The severity of an issue. * @author Nick Crossley. Released to public domain 2019. */ public enum IssueSeverity { /** Informational severity (the lowest). */ Info, /** Warning severity. */ Warning, /** Error severity (the highest real level). */ Error, /** A special value for the reporting threshold, to show the summary only. */ None; /** * Get an IssueSeverity enum value from its name. * @param name the name of an IssueSeverity * @return the named IssueSeverity * @throws IllegalArgumentException if {@code name} is not an IssueSeverity name */ public static IssueSeverity findSeverity(String name) { return IssueSeverity.valueOf(name); } }
24.59375
84
0.660737
92271edcd7308762177f8789dca22074e4240a92
706
package uk.gov.ida.matchingserviceadapter.domain; import org.joda.time.DateTime; import uk.gov.ida.saml.core.domain.IdaMatchingServiceResponse; import java.util.UUID; import static java.text.MessageFormat.format; public class HealthCheckResponseFromMatchingService extends IdaMatchingServiceResponse { public HealthCheckResponseFromMatchingService(String entityId, String healthCheckRequestId, String msaVersion, boolean eidasEnabled, boolean shouldSignWithSHA1) { super(format("healthcheck-response-id-{0}-version-{1}-eidasenabled-{2}-shouldsignwithsha1-{3}", UUID.randomUUID(), msaVersion, eidasEnabled, shouldSignWithSHA1), healthCheckRequestId, entityId, DateTime.now()); } }
41.529412
218
0.808782
c16db5f08bb771782227e378ace8c1d1223a0931
8,298
package uk.ac.ebi.biosamples.ena; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.time.Instant; import java.time.LocalDate; import java.util.Date; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; @Service public class EraProDao { @Autowired @Qualifier("eraJdbcTemplate") protected JdbcTemplate jdbcTemplate; private Logger log = LoggerFactory.getLogger(getClass()); private static final String STATUS_CLAUSE = "STATUS_ID IN (4, 5, 6, 7, 8)"; /** * Return a set of BioSamples accessions that have been updated or made public within * the specified date range * * @param minDate * @param maxDate * @return */ public SortedSet<String> getSamples(LocalDate minDate, LocalDate maxDate) { /* select * from cv_status; 1 draft The entry is draft. 2 private The entry is private. 3 cancelled The entry has been cancelled. 4 public The entry is public. 5 suppressed The entry has been suppressed. 6 killed The entry has been killed. 7 temporary_suppressed the entry has been temporarily suppressed. 8 temporary_killed the entry has been temporarily killed. */ //once it has been public, it can only be suppressed and killed and can't go back to public again String query = "SELECT BIOSAMPLE_ID FROM SAMPLE WHERE BIOSAMPLE_ID LIKE 'SAME%' AND EGA_ID IS NULL AND BIOSAMPLE_AUTHORITY= 'N' " + "AND " + STATUS_CLAUSE + " AND ((LAST_UPDATED BETWEEN ? AND ?) OR (FIRST_PUBLIC BETWEEN ? AND ?)) ORDER BY BIOSAMPLE_ID ASC"; SortedSet<String> samples = new TreeSet<>(); Date minDateOld = java.sql.Date.valueOf(minDate); Date maxDateOld = java.sql.Date.valueOf(maxDate); List<String> result = jdbcTemplate.queryForList(query, String.class, minDateOld, maxDateOld, minDateOld, maxDateOld); samples.addAll(result); return samples; } public void doSampleCallback(LocalDate minDate, LocalDate maxDate, RowCallbackHandler rch) { String query = "SELECT UNIQUE(BIOSAMPLE_ID), STATUS_ID FROM SAMPLE WHERE BIOSAMPLE_ID LIKE 'SAME%' AND SAMPLE_ID LIKE 'ERS%' AND EGA_ID IS NULL AND BIOSAMPLE_AUTHORITY= 'N' " + "AND " + STATUS_CLAUSE + " AND ((LAST_UPDATED BETWEEN ? AND ?) OR (FIRST_PUBLIC BETWEEN ? AND ?)) ORDER BY BIOSAMPLE_ID ASC"; Date minDateOld = java.sql.Date.valueOf(minDate); Date maxDateOld = java.sql.Date.valueOf(maxDate); jdbcTemplate.query(query, rch, minDateOld, maxDateOld, minDateOld, maxDateOld); } public void getSingleSample(String bioSampleId, RowCallbackHandler rch) { String query = "SELECT UNIQUE(BIOSAMPLE_ID), STATUS_ID FROM SAMPLE WHERE BIOSAMPLE_ID LIKE 'SAME%' AND SAMPLE_ID LIKE 'ERS%' AND EGA_ID IS NULL AND BIOSAMPLE_AUTHORITY= 'N' " + "AND " + STATUS_CLAUSE + " AND BIOSAMPLE_ID=? ORDER BY BIOSAMPLE_ID ASC"; jdbcTemplate.query(query, rch, bioSampleId); } public void getNcbiCallback(LocalDate minDate, LocalDate maxDate, RowCallbackHandler rch) { String query = "SELECT UNIQUE(BIOSAMPLE_ID), STATUS_ID FROM SAMPLE WHERE (BIOSAMPLE_ID LIKE 'SAMN%' OR BIOSAMPLE_ID LIKE 'SAMD%' ) " + "AND " + STATUS_CLAUSE + " AND ((LAST_UPDATED BETWEEN ? AND ?) OR (FIRST_PUBLIC BETWEEN ? AND ?)) ORDER BY BIOSAMPLE_ID ASC"; Date minDateOld = java.sql.Date.valueOf(minDate); Date maxDateOld = java.sql.Date.valueOf(maxDate); jdbcTemplate.query(query, rch, minDateOld, maxDateOld, minDateOld, maxDateOld); } public Instant getUpdateDateTime(String biosampleAccession) { String sql = "SELECT to_char(LAST_UPDATED, 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') FROM SAMPLE WHERE BIOSAMPLE_ID = ? AND BIOSAMPLE_AUTHORITY='N' AND SAMPLE_ID LIKE 'ERS%'"; String dateString = jdbcTemplate.queryForObject(sql, String.class, biosampleAccession); log.trace("Update date of \"+biosampleAccession+\"is " + dateString); return Instant.parse(dateString); } public String getChecklist(String biosampleAccession) { String sql = "SELECT CHECKLIST_ID FROM SAMPLE WHERE BIOSAMPLE_ID = ? AND BIOSAMPLE_AUTHORITY='N' AND SAMPLE_ID LIKE 'ERS%'"; String checklist = jdbcTemplate.queryForObject(sql, String.class, biosampleAccession); log.trace("Checklist of " + biosampleAccession + " is " + checklist); return checklist; } public String getStatus(String biosampleAccession) { String sql = "SELECT STATUS_ID FROM SAMPLE WHERE BIOSAMPLE_ID = ? AND BIOSAMPLE_AUTHORITY='N' AND SAMPLE_ID LIKE 'ERS%'"; Integer statusId = jdbcTemplate.queryForObject(sql, Integer.class, biosampleAccession); log.trace("Status of " + biosampleAccession + " is " + statusId); if (1 == statusId) { return "draft"; } else if (2 == statusId) { return "private"; } else if (3 == statusId) { return "cancelled"; } else if (4 == statusId) { return "public"; } else if (5 == statusId) { return "suppressed"; } else if (6 == statusId) { return "killed"; } else if (7 == statusId) { return "temporary_suppressed"; } else if (8 == statusId) { return "temporary_killed"; } throw new RuntimeException("Unrecognised statusid " + statusId); } public Instant getReleaseDateTime(String biosampleAccession) { String sql = "SELECT to_char(FIRST_PUBLIC, 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') FROM SAMPLE WHERE BIOSAMPLE_ID = ? AND BIOSAMPLE_AUTHORITY='N' AND SAMPLE_ID LIKE 'ERS%'"; String dateString = jdbcTemplate.queryForObject(sql, String.class, biosampleAccession); if (dateString == null) { return null; } log.trace("Release date of \"+biosampleAccession+\"is " + dateString); return Instant.parse(dateString); } public String getSampleXml(String biosampleAccession) throws SQLException { String sql = "SELECT SAMPLE_XML FROM SAMPLE WHERE BIOSAMPLE_ID = ? AND BIOSAMPLE_AUTHORITY='N' AND SAMPLE_ID LIKE 'ERS%'"; String result = jdbcTemplate.queryForObject(sql, String.class, biosampleAccession); return result; } public void getEnaDatabaseSample(String enaAccession, RowCallbackHandler rch) { String query = "select BIOSAMPLE_ID,\n" + " FIXED_TAX_ID, " + " FIXED_SCIENTIFIC_NAME, " + " FIXED_COMMON_NAME, " + " FIXED, " + " TAX_ID, " + " SCIENTIFIC_NAME, " + " to_char(first_public, 'yyyy-mm-dd') as first_public,\n" + " to_char(last_updated, 'yyyy-mm-dd') as last_updated,\n" + " (select nvl(cv_broker_name.description, T1.broker_name)\n" + " from XMLTable('/SAMPLE_SET[ 1 ]/SAMPLE/@broker_name' passing sample.sample_xml\n" + " columns broker_name varchar(1000) path '.') T1\n" + " left join cv_broker_name on (cv_broker_name.broker_name = T1.broker_name)) as broker_name,\n" + " (select nvl(cv_center_name.description, T2.center_name)\n" + " from XMLTable('/SAMPLE_SET[ 1 ]/SAMPLE/@center_name' passing sample.sample_xml\n" + " columns center_name varchar(1000) path '.') T2\n" + " left join cv_center_name on (cv_center_name.center_name = T2.center_name)) as center_name\n" + "from SAMPLE\n" + "where BIOSAMPLE_ID = ?"; jdbcTemplate.query(query, rch, enaAccession); } }
49.688623
182
0.639431
8e660b8df749f42ccfed04379f68eca7152bdd25
1,966
package vn.techmaster.demojpa.model.mapping; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Entity @Table(name = "countries") @Data public class Country { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; String name; int population; } /* Cách này quá dài phải không các bạn ! @Entity @Table(name = "countries") public class Country { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int population; public Country() { } public Country(Long id, String name, int population) { this.id = id; this.name = name; this.population = population; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Country country = (Country) o; return population == country.population && Objects.equals(id, country.id) && Objects.equals(name, country.name); } @Override public int hashCode() { return Objects.hash(id, name, population); } @Override public String toString() { final StringBuilder sb = new StringBuilder("Country{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append(", population=").append(population); sb.append('}'); return sb.toString(); } } */
22.089888
66
0.613428
6cfaa4ffa4212c592dd38aa2f801641e5f04ea2c
1,575
package stonehorse.grit.test; import stonehorse.grit.Associative; import stonehorse.grit.PersistentMap; import java.util.HashMap; import static org.junit.Assert.*; public class AssociativeBase { public void testAssciative(PersistentMap<Number, String> empty) { assertTrue("Not empty", empty.entrySet().isEmpty()); nullValue(empty.with(0, null)); } private void nullValue(PersistentMap<Number, String> empty) { PersistentMap<Number, String> object = empty.with(0, null); HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); hashmap.put(0, null); testEqHash(object, hashmap); assertEquals(object.entrySet().size(), 1); testEqHash(object.entrySet(), hashmap.entrySet()); assertNull(object.get(0)); assertNull(object.getOrDefault(0, "null")); assertEquals("not null", object.getOrDefault(1, "not null")); assertTrue(object.has(0)); assertFalse(object.has(1)); PersistentMap<Number, String> another = empty.with(0, null); testEqHash(object, another); testEqHash(object.entrySet(), another.entrySet()); another = object.with(0, null); testEqHash(object, another); another = another.with(1, null); assertTrue(another.has(1)); assertFalse(object.has(1)); assertFalse(another.equals(object)); } private void testEqHash(Object o1, Object o2) { assertEquals(o1, o2); assertEquals(o2, o1); assertEquals(o2.hashCode(), o1.hashCode()); } }
31.5
74
0.646349
ad73afde91b269829166ba0482eac1d6ede3ed91
7,740
package com.xbeats.permission; import android.content.Context; import android.content.pm.PackageManager; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.util.Log; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Created by XBeats on 2019/9/23 */ public class Permissions { private static final String TAG = Permissions.class.getSimpleName(); public static Permissions with(@NonNull Context context) { return new Permissions(context); } private Context mContext; private Permissions(@NonNull Context context) { mContext = context; } private Handler mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.obj instanceof PermissionRequest) { final PermissionRequest permissionRequest = (PermissionRequest) msg.obj; final FragmentActivity activity = PermissionUtils.getBaseActivity(permissionRequest.mContext); if (activity == null || activity.isFinishing()) { return; } // 1) 收集没有权限的申请 List<String> permissionList = new LinkedList<>(); List<String> noPermissionList = new LinkedList<>(); for (String item : permissionRequest.permissions) { if (ContextCompat.checkSelfPermission(activity, item) == PackageManager.PERMISSION_GRANTED) { permissionList.add(item); } else { noPermissionList.add(item); } } // 1.1) 权限全部通过,直接返回 if (noPermissionList.isEmpty()) { PermissionLogger.log("权限全部通过啦 -->"); permissionRequest.mCallback.onResult(permissionList.toArray(new String[0]), noPermissionList.toArray(new String[0])); return; } // 2. 收集需要解释权限意图的申请 // 第一次请求权限也需要解释 List<String> needRequest = new LinkedList<>(); Iterator<String> iterator = noPermissionList.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (ActivityCompat.shouldShowRequestPermissionRationale(activity, item)) { PermissionLogger.log("提醒用户开启权限:" + item + " -->"); needRequest.add(item); iterator.remove(); } else if (PermissionUtils.noPermissionRecord(activity, item)) { // 用户没有请求过权限,则再次提示用户 PermissionLogger.log("用户还没申请过权限:" + item + " -->"); needRequest.add(item); iterator.remove(); } } // 2.1) 用户选择了“不再提醒”,不能再进行解释 if (needRequest.isEmpty()) { PermissionLogger.log("用户选择了“不再提醒”,不能再进行解释 -->"); permissionRequest.mCallback.onResult(permissionList.toArray(new String[0]), noPermissionList.toArray(new String[0])); return; } // 3) 查看用户拦截器 (Activity自定义 > Application自定义 > 全局默认) // 3.1) 某界面自定义拦截器 final Chain chain = new Chain(activity, permissionList, noPermissionList, needRequest, permissionRequest.mCallback); if (permissionRequest.mPermissionInterceptor != null) { permissionRequest.mPermissionInterceptor.intercept(chain, permissionList.toArray(new String[0]), noPermissionList.toArray(new String[0]), needRequest); return; } // 3.2) 反射查找全局拦截器 Class<? extends PermissionInterceptor> interceptorClass = PermissionConfig.instance(activity).getInterceptorClass(); if (interceptorClass != null) { try { PermissionInterceptor interceptor = interceptorClass.newInstance(); interceptor.intercept(chain, permissionList.toArray(new String[0]), noPermissionList.toArray(new String[0]), needRequest); } catch (Exception e) { e.printStackTrace(); PermissionLogger.log("反射全局拦截器失败 -->"); } return; } // 3.3) 全局默认拦截器 if (PermissionConfig.instance(activity).isEnabledDefaultInterceptor()) { new DefaultApplicationInterceptor().intercept(chain, permissionList.toArray(new String[0]), noPermissionList.toArray(new String[0]), needRequest); return; } // 3.4) 无拦截器,直接发起权限请求 chain.request(); } } }; public PermissionRequest load(final String... permissions) { PermissionRequest request = new PermissionRequest(mContext, permissions); Message message = mHandler.obtainMessage(); message.obj = request; message.sendToTarget(); return request; } public static class PermissionRequest { private Context mContext; private String[] permissions; private Callback mCallback; private PermissionInterceptor mPermissionInterceptor; PermissionRequest(Context context, String[] permissions) { mContext = context; this.permissions = permissions; } public PermissionRequest callback(Callback callback) { mCallback = callback; return this; } public PermissionRequest setInterceptor(PermissionInterceptor permissionInterceptor) { mPermissionInterceptor = permissionInterceptor; return this; } } public static class Chain { private FragmentActivity mActivity; private List<String> granted; private List<String> denied; private List<String> request; private Callback callback; private Chain(@NonNull FragmentActivity mActivity, List<String> granted, List<String> denied, List<String> request, Callback callback) { this.mActivity = mActivity; this.granted = granted; this.denied = denied; this.request = request; this.callback = callback; } @NonNull public FragmentActivity getActivity() { return mActivity; } public final void request() { FragmentManager fragmentManager = mActivity.getSupportFragmentManager(); InnerFragment permissionsFragment = (InnerFragment) fragmentManager.findFragmentByTag(TAG); if (permissionsFragment == null) { permissionsFragment = new InnerFragment(); fragmentManager .beginTransaction() .add(permissionsFragment, TAG) .commitNowAllowingStateLoss(); } permissionsFragment.request(granted, denied, request, callback); } public final void ignored() { LinkedList<String> denied = new LinkedList<>(this.denied); denied.addAll(request); callback.onResult(granted.toArray(new String[0]), denied.toArray(new String[0])); } } }
39.896907
171
0.583592
45e006c5732686fd4b27cce91797e319e8e32a2b
2,370
package com.networknt.eventuate.reference.common.model; import java.util.ArrayList; import java.util.List; public class ReferenceTable { private String tableId; private String tableName; private String tableDesc; private String host; private boolean active = true; private boolean editable = true; private boolean common = true; private List<ReferenceValue> values = new ArrayList<ReferenceValue>(); public ReferenceTable() { } public ReferenceTable(String tableName) { this.tableName = tableName; } public String getTableName() { if (tableName!=null) { return tableName.toUpperCase(); } return tableName; } public String getTableId() { return tableId; } public void setTableId(String tableId) { this.tableId = tableId; } public void setTableName(String tableName) { this.tableName = tableName; } public String getTableDesc() { return tableDesc; } public void setTableDesc(String tableDesc) { this.tableDesc = tableDesc; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public boolean isEditable() { return editable; } public void setEditable(boolean editable) { this.editable = editable; } public boolean isCommon() { return common; } public void setCommon(boolean common) { this.common = common; } public List<ReferenceValue> getValues() { return values; } public void setValues(List<ReferenceValue> values) { this.values = values; } public void addValue(ReferenceValue value) { this.values.add(value); } public void updateObject(ReferenceTable newRef) { setTableName(newRef.getTableName()); setTableDesc(newRef.getTableDesc()); setHost(newRef.getHost()); setActive(newRef.isActive()); setEditable(newRef.isEditable()); setCommon(newRef.isCommon()); } }
21.160714
75
0.591983
669e4eb8ca8c3d5241cbcc02e44d6c67a1d86134
2,378
/* * Copyright (C) 2013 Jordan Fish <fishjord at msu.edu> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package edu.msu.cme.rdp.readseq; import edu.msu.cme.rdp.readseq.readers.IndexedSeqReader; import edu.msu.cme.rdp.readseq.readers.QSeqReader; import edu.msu.cme.rdp.readseq.readers.SeqReader; import edu.msu.cme.rdp.readseq.readers.Sequence; import edu.msu.cme.rdp.readseq.readers.SequenceReader; import edu.msu.cme.rdp.readseq.readers.core.FastqCore; import edu.msu.cme.rdp.readseq.writers.FastqWriter; import java.io.File; import java.io.IOException; /** * * @author Jordan Fish <fishjord at msu.edu> */ public class ToFastq { public static void main(String[] args) throws Exception { if (args.length != 1 && args.length != 2) { System.err.println("USAGE: ToFastq <seqfile> [qualfile]"); System.exit(1); } final SeqReader reader; if (args.length == 2) { reader = new QSeqReader(new File(args[0]), new File(args[1])); } else { reader = new SequenceReader(new File(args[0])); } Sequence seq = reader.readNextSequence(); if (!(seq instanceof QSequence)) { throw new IOException("Input doesn't contain quality information"); } FastqWriter out = new FastqWriter(System.out, FastqCore.Phred33QualFunction); long startTime = System.currentTimeMillis(); int thisFileTotalSeqs = 0; do { out.writeSeq(seq); thisFileTotalSeqs++; } while ((seq = reader.readNextSequence()) != null); System.err.println("Converted " + thisFileTotalSeqs + " sequences (" + reader.getFormat() + ") to fastq in " + (System.currentTimeMillis() - startTime) / 1000 + " s"); } }
36.584615
175
0.671573
7c38ac5b050d1e010a25c02a6cdf17ff9bd62b44
12,804
/* 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.wiki.auth.authorize; import org.apache.commons.lang3.ArrayUtils; import org.apache.wiki.WikiContext; import org.apache.wiki.WikiSession; import org.apache.wiki.auth.Authorizer; import org.apache.wiki.auth.NoSuchPrincipalException; import org.apache.wiki.auth.WikiSecurityException; import org.apache.wiki.event.WikiEventListener; import org.apache.wiki.event.WikiEventManager; import org.apache.wiki.event.WikiSecurityEvent; import org.apache.wiki.ui.InputValidator; import javax.servlet.http.HttpServletRequest; import java.security.Principal; /** * <p> * Facade class for storing, retrieving and managing wiki groups on behalf of AuthorizationManager, JSPs and other presentation-layer * classes. GroupManager works in collaboration with a back-end {@link GroupDatabase}, which persists groups to permanent storage. * </p> * <p> * <em>Note: prior to JSPWiki 2.4.19, GroupManager was an interface; it is now a concrete, final class. The aspects of GroupManager * which previously extracted group information from storage (e.g., wiki pages) have been refactored into the GroupDatabase interface.</em> * </p> * @since 2.4.19 */ public interface GroupManager extends Authorizer, WikiEventListener { /** Key used for adding UI messages to a user's WikiSession. */ String MESSAGES_KEY = "group"; String PROP_GROUPDATABASE = "jspwiki.groupdatabase"; /** * Returns the Group matching a given name. If the group cannot be found, this method throws a <code>NoSuchPrincipalException</code>. * * @param name the name of the group to find * @return the group * @throws NoSuchPrincipalException if the group cannot be found */ Group getGroup( final String name ) throws NoSuchPrincipalException; /** * Returns the current external {@link GroupDatabase} in use. This method is guaranteed to return a properly-initialized GroupDatabase, * unless it could not be initialized. In that case, this method throws a {@link org.apache.wiki.api.exceptions.WikiException}. The * GroupDatabase is lazily initialized. * * @throws org.apache.wiki.auth.WikiSecurityException if the GroupDatabase could not be initialized * @return the current GroupDatabase * @since 2.3 */ GroupDatabase getGroupDatabase() throws WikiSecurityException; /** * <p> * Extracts group name and members from passed parameters and populates an existing Group with them. The Group will either be a copy of * an existing Group (if one can be found), or a new, unregistered Group (if not). Optionally, this method can throw a * WikiSecurityException if the Group does not yet exist in the GroupManager cache. * </p> * <p> * The <code>group</code> parameter in the HTTP request contains the Group name to look up and populate. The <code>members</code> * parameter contains the member list. If these differ from those in the existing group, the passed values override the old values. * </p> * <p> * This method does not commit the new Group to the GroupManager cache. To do that, use {@link #setGroup(WikiSession, Group)}. * </p> * @param name the name of the group to construct * @param memberLine the line of text containing the group membership list * @param create whether this method should create a new, empty Group if one with the requested name is not found. If <code>false</code>, * groups that do not exist will cause a <code>NoSuchPrincipalException</code> to be thrown * @return a new, populated group * @see org.apache.wiki.auth.authorize.Group#RESTRICTED_GROUPNAMES * @throws WikiSecurityException if the group name isn't allowed, or if <code>create</code> is <code>false</code> * and the Group named <code>name</code> does not exist */ Group parseGroup( String name, String memberLine, boolean create ) throws WikiSecurityException; /** * <p> * Extracts group name and members from the HTTP request and populates an existing Group with them. The Group will either be a copy of * an existing Group (if one can be found), or a new, unregistered Group (if not). Optionally, this method can throw a * WikiSecurityException if the Group does not yet exist in the GroupManager cache. * </p> * <p> * The <code>group</code> parameter in the HTTP request contains the Group name to look up and populate. The <code>members</code> * parameter contains the member list. If these differ from those in the existing group, the passed values override the old values. * </p> * <p> * This method does not commit the new Group to the GroupManager cache. To do that, use {@link #setGroup(WikiSession, Group)}. * </p> * @param context the current wiki context * @param create whether this method should create a new, empty Group if one with the requested name is not found. If <code>false</code>, * groups that do not exist will cause a <code>NoSuchPrincipalException</code> to be thrown * @return a new, populated group * @throws WikiSecurityException if the group name isn't allowed, or if <code>create</code> is <code>false</code> * and the Group does not exist */ default Group parseGroup( final WikiContext context, final boolean create ) throws WikiSecurityException { // Extract parameters final HttpServletRequest request = context.getHttpRequest(); final String name = request.getParameter( "group" ); final String memberLine = request.getParameter( "members" ); // Create the named group; we pass on any NoSuchPrincipalExceptions // that may be thrown if create == false, or WikiSecurityExceptions final Group group = parseGroup( name, memberLine, create ); // If no members, add the current user by default if( group.members().length == 0 ) { group.add( context.getWikiSession().getUserPrincipal() ); } return group; } /** * Removes a named Group from the group database. If not found, throws a <code>NoSuchPrincipalException</code>. After removal, this * method will commit the delete to the back-end group database. It will also fire a * {@link org.apache.wiki.event.WikiSecurityEvent#GROUP_REMOVE} event with the GroupManager instance as the source and the Group as target. * If <code>index</code> is <code>null</code>, this method throws an {@link IllegalArgumentException}. * * @param index the group to remove * @throws WikiSecurityException if the Group cannot be removed by the back-end * @see org.apache.wiki.auth.authorize.GroupDatabase#delete(Group) */ void removeGroup( final String index ) throws WikiSecurityException; /** * <p> * Saves the {@link Group} created by a user in a wiki session. This method registers the Group with the GroupManager and saves it to * the back-end database. If an existing Group with the same name already exists, the new group will overwrite it. After saving the * Group, the group database changes are committed. * </p> * <p> * This method fires the following events: * </p> * <ul> * <li><strong>When creating a new Group</strong>, this method fires a {@link org.apache.wiki.event.WikiSecurityEvent#GROUP_ADD} with * the GroupManager instance as its source and the new Group as the target.</li> * <li><strong>When overwriting an existing Group</strong>, this method fires a new * {@link org.apache.wiki.event.WikiSecurityEvent#GROUP_REMOVE} with this GroupManager instance as the source, and the new Group as the * target. It then fires a {@link org.apache.wiki.event.WikiSecurityEvent#GROUP_ADD} event with the same source and target.</li> * </ul> * <p> * In addition, if the save or commit actions fail, this method will attempt to restore the older version of the wiki group if it * exists. This will result in a <code>GROUP_REMOVE</code> event (for the new version of the Group) followed by a <code>GROUP_ADD</code> * event (to indicate restoration of the old version). * </p> * <p> * This method will register the new Group with the GroupManager. For example, {@link org.apache.wiki.auth.AuthenticationManager} * attaches each WikiSession as a GroupManager listener. Thus, the act of registering a Group with <code>setGroup</code> means that * all WikiSessions will automatically receive group add/change/delete events immediately. * </p> * * @param session the wiki session, which may not be <code>null</code> * @param group the Group, which may not be <code>null</code> * @throws WikiSecurityException if the Group cannot be saved by the back-end */ void setGroup( final WikiSession session, final Group group ) throws WikiSecurityException; /** * Validates a Group, and appends any errors to the session errors list. Any validation errors are added to the wiki session's messages * collection (see {@link WikiSession#getMessages()}. * * @param context the current wiki context * @param group the supplied Group */ default void validateGroup( final WikiContext context, final Group group ) { final InputValidator validator = new InputValidator( MESSAGES_KEY, context ); // Name cannot be null or one of the restricted names try { checkGroupName( context, group.getName() ); } catch( final WikiSecurityException e ) { } // Member names must be "safe" strings final Principal[] members = group.members(); for( final Principal member : members ) { validator.validateNotNull( member.getName(), "Full name", InputValidator.ID ); } } /** * Checks if a String is blank or a restricted Group name, and if it is, appends an error to the WikiSession's message list. * * @param context the wiki context * @param name the Group name to test * @throws WikiSecurityException if <code>session</code> is <code>null</code> or the Group name is illegal * @see Group#RESTRICTED_GROUPNAMES */ default void checkGroupName( final WikiContext context, final String name ) throws WikiSecurityException { // TODO: groups cannot have the same name as a user // Name cannot be null final InputValidator validator = new InputValidator( MESSAGES_KEY, context ); validator.validateNotNull( name, "Group name" ); // Name cannot be one of the restricted names either if( ArrayUtils.contains( Group.RESTRICTED_GROUPNAMES, name ) ) { throw new WikiSecurityException( "The group name '" + name + "' is illegal. Choose another." ); } } // events processing ....................................................... /** * Registers a WikiEventListener with this instance. This is a convenience method. * * @param listener the event listener */ void addWikiEventListener( WikiEventListener listener ); /** * Un-registers a WikiEventListener with this instance. This is a convenience method. * * @param listener the event listener */ void removeWikiEventListener( WikiEventListener listener ); /** * Fires a WikiSecurityEvent of the provided type, Principal and target Object to all registered listeners. * * @see org.apache.wiki.event.WikiSecurityEvent * @param type the event type to be fired * @param target the changed Object, which may be <code>null</code> */ default void fireEvent( final int type, final Object target ) { if( WikiEventManager.isListening( this ) ) { WikiEventManager.fireEvent( this, new WikiSecurityEvent( this, type, target ) ); } } }
50.015625
143
0.693611
15f0d4594830d7f43e83b04d929d956ad8b3942d
651
package com.ctrip.xpipe.redis.console.healthcheck.actions.sentinel; import com.ctrip.xpipe.redis.console.healthcheck.AbstractActionContext; import com.ctrip.xpipe.redis.console.healthcheck.RedisHealthCheckInstance; import java.util.Set; /** * @author chen.zhu * <p> * Oct 09, 2018 */ public class SentinelActionContext extends AbstractActionContext<Set<SentinelHello>> { public SentinelActionContext(RedisHealthCheckInstance instance, Throwable t) { super(instance, t); } public SentinelActionContext(RedisHealthCheckInstance instance, Set<SentinelHello> sentinelHellos) { super(instance, sentinelHellos); } }
28.304348
104
0.771121
a571c979f0c71c69111cd80436a6c23130c5b750
4,081
package edu.mit.scansite.server.dispatch.handler.motif; import java.io.File; import javax.servlet.ServletContext; import net.customware.gwt.dispatch.server.ActionHandler; import net.customware.gwt.dispatch.server.ExecutionContext; import net.customware.gwt.dispatch.shared.ActionException; import net.customware.gwt.dispatch.shared.DispatchException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Provider; import edu.mit.scansite.server.dataaccess.file.ImageInOut; import edu.mit.scansite.server.images.histograms.ServerHistogram; import edu.mit.scansite.shared.DataAccessException; import edu.mit.scansite.shared.FilePaths; import edu.mit.scansite.shared.dispatch.motif.HistogramRetrieverResult; import edu.mit.scansite.shared.dispatch.motif.HistogramUpdateAction; import edu.mit.scansite.shared.transferobjects.Histogram; /** * @author Tobieh * @author Konstantin Krismer */ public class HistogramUpdateHandler implements ActionHandler<HistogramUpdateAction, HistogramRetrieverResult> { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final Provider<ServletContext> contextProvider; @Inject public HistogramUpdateHandler(final Provider<ServletContext> contextProvider) { this.contextProvider = contextProvider; } @Override public Class<HistogramUpdateAction> getActionType() { return HistogramUpdateAction.class; } @Override public HistogramRetrieverResult execute(HistogramUpdateAction action, ExecutionContext context) throws DispatchException { ImageInOut imageIO = new ImageInOut(); String imagePathClient = ""; HistogramRetrieverResult result = new HistogramRetrieverResult(); Histogram histogram = action.getHistogram(); // use the client-histogram's filename to find the plain version of the // histogram long systimeMs = FilePaths.getFilePathNumber(histogram .getImageFilePath()); // set imagefilepath to that of the plain histogram (that way, this // image is // loaded into the serverhistogram) histogram.setImageFilePath(FilePaths.getHistogramFilePath( contextProvider.get().getRealPath("/"), null, systimeMs)); ServerHistogram serverHistogram = new ServerHistogram(histogram); serverHistogram.setPlot(imageIO.getImage(histogram.getImageFilePath())); deleteFile(histogram.getImageFilePath()); deleteFile(FilePaths.getHistogramFilePath(contextProvider.get() .getRealPath("/"), null, systimeMs)); // save plain histogram (without thresholds) - new fileName, since the // browser caches the other image systimeMs = System.currentTimeMillis(); try { imageIO.saveImage(serverHistogram.getPlot(), FilePaths .getHistogramFilePath(contextProvider.get() .getRealPath("/"), null, systimeMs)); } catch (DataAccessException e) { logger.error("Error saving histogram image: " + e.toString()); throw new ActionException("Error saving histogram image.", e); } imagePathClient = FilePaths.getHistogramFilePath(contextProvider.get() .getRealPath("/"), histogram.toString(), systimeMs); // save client-histogram, set filepath and create datastructure try { imageIO.saveImage(serverHistogram.getDbEditHistogramPlot(), imagePathClient); } catch (DataAccessException e) { logger.error("Error saving histogram image: " + e.getMessage()); throw new ActionException("Error saving histogram image.", e); } serverHistogram.setImageFilePath(imagePathClient.replace( contextProvider.get().getRealPath("/"), "")); result.setHistogramNr(action.getHistogramNr()); result.setHistogram(serverHistogram.toClientHistogram()); return result; } @Override public void rollback(HistogramUpdateAction action, HistogramRetrieverResult result, ExecutionContext context) throws DispatchException { } /** * deletes the given file. * * @param filePath * A path that leads to the file. */ private void deleteFile(String filePath) { File f = new File(filePath); if (f.exists() && f.isFile()) { f.delete(); } } }
33.727273
80
0.769909
7f3fb0bef7e217967d9e5cf0cf42bd0886550b99
21,933
package Interfaces.Administrador.AdmAluno; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import objetos.Aluno; import objetos_dao.AlunoDAO; /** * * @author GabrielFelipe */ public class EditAlunAlerta extends javax.swing.JFrame { AlunoDAO alunoBanco = new AlunoDAO(); Aluno aluno_antigo; Aluno aluno_novo; OpAlunos opa; public EditAlunAlerta(Aluno antigo, Aluno novo, OpAlunos opa) { aluno_antigo = antigo; aluno_novo = novo; this.opa = opa; initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { Titulo1 = new javax.swing.JLabel(); NomeEditAlun1 = new javax.swing.JLabel(); nomeEditAlun1 = new javax.swing.JLabel(); CPFEditAlun1 = new javax.swing.JLabel(); cpfEditAlun1 = new javax.swing.JLabel(); SexoEditAlun1 = new javax.swing.JLabel(); sexoEditAlun1 = new javax.swing.JLabel(); NutrEditAlun1 = new javax.swing.JLabel(); nutrEditAlun1 = new javax.swing.JLabel(); TelefoneEditAlun1 = new javax.swing.JLabel(); telefoneEditAlun1 = new javax.swing.JLabel(); EmailEditAlun1 = new javax.swing.JLabel(); emailEditAlun1 = new javax.swing.JLabel(); SetaEditAlun = new javax.swing.JLabel(); NomeEditAlun2 = new javax.swing.JLabel(); nomeEditAlun2 = new javax.swing.JLabel(); CPFEditAlun2 = new javax.swing.JLabel(); cpfEditAlun2 = new javax.swing.JLabel(); SexoEditAlun2 = new javax.swing.JLabel(); sexoEditAlun2 = new javax.swing.JLabel(); NutrEditAlun2 = new javax.swing.JLabel(); nutrEditAlun2 = new javax.swing.JLabel(); TelefoneEditAlun2 = new javax.swing.JLabel(); telefoneEditAlun2 = new javax.swing.JLabel(); EmaiEditAlun2 = new javax.swing.JLabel(); emailEditAlun2 = new javax.swing.JLabel(); ConfirmaEditAlun = new javax.swing.JButton(); CancelaEditAlun = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); Titulo1.setFont(new java.awt.Font("Impact", 0, 24)); // NOI18N Titulo1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); Titulo1.setText("Editar o Funcionário: "); Titulo1.setToolTipText(""); NomeEditAlun1.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N NomeEditAlun1.setText("Nome:"); NomeEditAlun1.setToolTipText(""); nomeEditAlun1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N nomeEditAlun1.setText("???"); CPFEditAlun1.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N CPFEditAlun1.setText("CPF:"); CPFEditAlun1.setToolTipText(""); cpfEditAlun1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N cpfEditAlun1.setText("???"); SexoEditAlun1.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N SexoEditAlun1.setText("Sexo:"); SexoEditAlun1.setToolTipText(""); sexoEditAlun1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N sexoEditAlun1.setText("???"); NutrEditAlun1.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N NutrEditAlun1.setText("Nutricionista:"); NutrEditAlun1.setToolTipText(""); nutrEditAlun1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N nutrEditAlun1.setText("???"); TelefoneEditAlun1.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N TelefoneEditAlun1.setText("Telefone:"); TelefoneEditAlun1.setToolTipText(""); telefoneEditAlun1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N telefoneEditAlun1.setText("???"); EmailEditAlun1.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N EmailEditAlun1.setText("Email:"); EmailEditAlun1.setToolTipText(""); emailEditAlun1.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N emailEditAlun1.setText("???"); SetaEditAlun.setFont(new java.awt.Font("Dialog", 1, 55)); // NOI18N SetaEditAlun.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); SetaEditAlun.setText("→"); NomeEditAlun2.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N NomeEditAlun2.setText("Nome:"); NomeEditAlun2.setToolTipText(""); nomeEditAlun2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N nomeEditAlun2.setText("???"); CPFEditAlun2.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N CPFEditAlun2.setText("CPF:"); CPFEditAlun2.setToolTipText(""); cpfEditAlun2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N cpfEditAlun2.setText("???"); SexoEditAlun2.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N SexoEditAlun2.setText("Sexo:"); SexoEditAlun2.setToolTipText(""); sexoEditAlun2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N sexoEditAlun2.setText("???"); NutrEditAlun2.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N NutrEditAlun2.setText("Nutricionista:"); NutrEditAlun2.setToolTipText(""); nutrEditAlun2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N nutrEditAlun2.setText("???"); TelefoneEditAlun2.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N TelefoneEditAlun2.setText("Telefone:"); TelefoneEditAlun2.setToolTipText(""); telefoneEditAlun2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N telefoneEditAlun2.setText("???"); EmaiEditAlun2.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N EmaiEditAlun2.setText("Email:"); EmaiEditAlun2.setToolTipText(""); emailEditAlun2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N emailEditAlun2.setText("???"); ConfirmaEditAlun.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N ConfirmaEditAlun.setText("Sim"); ConfirmaEditAlun.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ConfirmaEditAlunActionPerformed(evt); } }); CancelaEditAlun.setFont(new java.awt.Font("Impact", 0, 18)); // NOI18N CancelaEditAlun.setText("Cancelar"); CancelaEditAlun.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CancelaEditAlunActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Titulo1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(NomeEditAlun1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(nomeEditAlun1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(60, 60, 60)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(60, 60, 60) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(SexoEditAlun1) .addComponent(CPFEditAlun1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cpfEditAlun1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(sexoEditAlun1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(EmailEditAlun1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(emailEditAlun1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(TelefoneEditAlun1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(telefoneEditAlun1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(NutrEditAlun1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(nutrEditAlun1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(SetaEditAlun))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(TelefoneEditAlun2) .addGap(12, 12, 12) .addComponent(telefoneEditAlun2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(EmaiEditAlun2) .addGap(12, 12, 12) .addComponent(emailEditAlun2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(SexoEditAlun2) .addComponent(CPFEditAlun2) .addComponent(NutrEditAlun2) .addComponent(NomeEditAlun2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cpfEditAlun2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(sexoEditAlun2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nutrEditAlun2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nomeEditAlun2, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(18, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ConfirmaEditAlun, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(CancelaEditAlun, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(184, 184, 184)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(Titulo1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(NomeEditAlun1) .addComponent(nomeEditAlun1)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(CPFEditAlun1) .addComponent(cpfEditAlun1)) .addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(SexoEditAlun1) .addComponent(sexoEditAlun1)) .addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(nutrEditAlun1) .addComponent(NutrEditAlun1))) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(SetaEditAlun))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(TelefoneEditAlun1) .addComponent(telefoneEditAlun1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(EmailEditAlun1) .addComponent(emailEditAlun1))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(NomeEditAlun2) .addComponent(nomeEditAlun2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(CPFEditAlun2) .addComponent(cpfEditAlun2)) .addGap(5, 5, 5) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(SexoEditAlun2) .addComponent(sexoEditAlun2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(NutrEditAlun2) .addComponent(nutrEditAlun2)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TelefoneEditAlun2) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(telefoneEditAlun2))) .addGap(5, 5, 5) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EmaiEditAlun2) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(emailEditAlun2))))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ConfirmaEditAlun, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(CancelaEditAlun, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(33, Short.MAX_VALUE)) ); setSize(new java.awt.Dimension(696, 369)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // Quando Abre a Janela //Antes nomeEditAlun1.setText(aluno_antigo.getNome()); cpfEditAlun1.setText(aluno_antigo.getCPF()); sexoEditAlun1.setText(String.valueOf(aluno_antigo.getSexo())); if(aluno_antigo.getNutricionista() == null) nutrEditAlun1.setText(""); else nutrEditAlun1.setText(aluno_antigo.getNutricionista().getNome()); telefoneEditAlun1.setText(aluno_antigo.getTelefone()); emailEditAlun1.setText(aluno_antigo.getEmail()); //Depois nomeEditAlun2.setText(aluno_novo.getNome()); cpfEditAlun2.setText(aluno_novo.getCPF()); sexoEditAlun2.setText(String.valueOf(aluno_novo.getSexo())); if(aluno_novo.getNutricionista() == null) nutrEditAlun2.setText(""); else nutrEditAlun2.setText(aluno_novo.getNutricionista().getNome()); telefoneEditAlun2.setText(aluno_novo.getTelefone()); emailEditAlun2.setText(aluno_novo.getEmail()); }//GEN-LAST:event_formWindowOpened private void ConfirmaEditAlunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConfirmaEditAlunActionPerformed try { // Click no Botão Sim: alunoBanco.altera(aluno_novo); dispose(); JOptionPane.showMessageDialog(null, "Aluno editado com sucesso"); opa.Limpar(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Não foi possível editar o aluno"); } }//GEN-LAST:event_ConfirmaEditAlunActionPerformed private void CancelaEditAlunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelaEditAlunActionPerformed // Click no Botão Cancelar: dispose(); }//GEN-LAST:event_CancelaEditAlunActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel CPFEditAlun1; private javax.swing.JLabel CPFEditAlun2; private javax.swing.JButton CancelaEditAlun; private javax.swing.JButton ConfirmaEditAlun; private javax.swing.JLabel EmaiEditAlun2; private javax.swing.JLabel EmailEditAlun1; private javax.swing.JLabel NomeEditAlun1; private javax.swing.JLabel NomeEditAlun2; private javax.swing.JLabel NutrEditAlun1; private javax.swing.JLabel NutrEditAlun2; private javax.swing.JLabel SetaEditAlun; private javax.swing.JLabel SexoEditAlun1; private javax.swing.JLabel SexoEditAlun2; private javax.swing.JLabel TelefoneEditAlun1; private javax.swing.JLabel TelefoneEditAlun2; private javax.swing.JLabel Titulo1; private javax.swing.JLabel cpfEditAlun1; private javax.swing.JLabel cpfEditAlun2; private javax.swing.JLabel emailEditAlun1; private javax.swing.JLabel emailEditAlun2; private javax.swing.JLabel nomeEditAlun1; private javax.swing.JLabel nomeEditAlun2; private javax.swing.JLabel nutrEditAlun1; private javax.swing.JLabel nutrEditAlun2; private javax.swing.JLabel sexoEditAlun1; private javax.swing.JLabel sexoEditAlun2; private javax.swing.JLabel telefoneEditAlun1; private javax.swing.JLabel telefoneEditAlun2; // End of variables declaration//GEN-END:variables }
54.289604
159
0.614781
0de0d063c1c01baffa8c8113eaef9220ccf05247
305
package testPackage; import org.springframework.stereotype.Component; /** * @author HeYi * @version V2.0 * @Description: * @date 2019/6/25 16:32 */ @Component public class TestBean implements TestInterface { @Override public void outPrint(String s) { System.out.println(s); } }
16.944444
48
0.681967
21307c08247224ec50530d3f140c9e631f7604d0
635
package io.techcode.logbulk.net; import io.vertx.core.eventbus.impl.codecs.JsonObjectMessageCodec; import io.vertx.core.json.JsonObject; /** * Fast json object message codec that avoid copy. */ public class FastJsonObjectCodec extends JsonObjectMessageCodec { public static final String CODEC_NAME = FastJsonObjectCodec.class.getSimpleName(); @Override public JsonObject transform(JsonObject evt) { // Avoid copy when we use it as event schema return evt; } @Override public String name() { return CODEC_NAME; } @Override public byte systemCodecID() { return -1; } }
24.423077
86
0.707087
1c0bcee7913a580503113154116cb34b9d8bbea2
10,255
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.flat; import android.graphics.Typeface; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.ReactShadowNodeImpl; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.uimanager.annotations.ReactProp; import javax.annotation.Nullable; /** * RCTVirtualText is a {@link FlatTextShadowNode} that can contain font styling information. */ /* package */ class RCTVirtualText extends FlatTextShadowNode { private static final String BOLD = "bold"; private static final String ITALIC = "italic"; private static final String NORMAL = "normal"; private static final String PROP_SHADOW_OFFSET = "textShadowOffset"; private static final String PROP_SHADOW_RADIUS = "textShadowRadius"; private static final String PROP_SHADOW_COLOR = "textShadowColor"; private static final int DEFAULT_TEXT_SHADOW_COLOR = 0x55000000; private FontStylingSpan mFontStylingSpan = FontStylingSpan.INSTANCE; private ShadowStyleSpan mShadowStyleSpan = ShadowStyleSpan.INSTANCE; @Override public void addChildAt(ReactShadowNodeImpl child, int i) { super.addChildAt(child, i); notifyChanged(true); } @Override protected void performCollectText(SpannableStringBuilder builder) { for (int i = 0, childCount = getChildCount(); i < childCount; ++i) { FlatTextShadowNode child = (FlatTextShadowNode) getChildAt(i); child.collectText(builder); } } @Override protected void performApplySpans(SpannableStringBuilder builder, int begin, int end, boolean isEditable) { mFontStylingSpan.freeze(); // All spans will automatically extend to the right of the text, but not the left - except // for spans that start at the beginning of the text. final int flag; if (isEditable) { flag = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE; } else { flag = begin == 0 ? Spannable.SPAN_INCLUSIVE_INCLUSIVE : Spannable.SPAN_EXCLUSIVE_INCLUSIVE; } builder.setSpan( mFontStylingSpan, begin, end, flag); if (mShadowStyleSpan.getColor() != 0 && mShadowStyleSpan.getRadius() != 0) { mShadowStyleSpan.freeze(); builder.setSpan( mShadowStyleSpan, begin, end, flag); } for (int i = 0, childCount = getChildCount(); i < childCount; ++i) { FlatTextShadowNode child = (FlatTextShadowNode) getChildAt(i); child.applySpans(builder, isEditable); } } @Override protected void performCollectAttachDetachListeners(StateBuilder stateBuilder) { for (int i = 0, childCount = getChildCount(); i < childCount; ++i) { FlatTextShadowNode child = (FlatTextShadowNode) getChildAt(i); child.performCollectAttachDetachListeners(stateBuilder); } } @ReactProp(name = ViewProps.FONT_SIZE, defaultFloat = Float.NaN) public void setFontSize(float fontSizeSp) { final int fontSize; if (Float.isNaN(fontSizeSp)) { fontSize = getDefaultFontSize(); } else { fontSize = fontSizeFromSp(fontSizeSp); } if (mFontStylingSpan.getFontSize() != fontSize) { getSpan().setFontSize(fontSize); notifyChanged(true); } } @ReactProp(name = ViewProps.COLOR, defaultDouble = Double.NaN) public void setColor(double textColor) { if (mFontStylingSpan.getTextColor() != textColor) { getSpan().setTextColor(textColor); notifyChanged(false); } } @Override public void setBackgroundColor(int backgroundColor) { if (isVirtual()) { // for nested Text elements, we want to apply background color to the text only // e.g. Hello <style backgroundColor=red>World</style>, "World" will have red background color if (mFontStylingSpan.getBackgroundColor() != backgroundColor) { getSpan().setBackgroundColor(backgroundColor); notifyChanged(false); } } else { // for top-level Text element, background needs to be applied for the entire shadow node // // For example: <Text style={flex:1}>Hello World</Text> // "Hello World" may only occupy e.g. 200 pixels, but the node may be measured at e.g. 500px. // In this case, we want background to be 500px wide as well, and this is exactly what // FlatShadowNode does. super.setBackgroundColor(backgroundColor); } } @ReactProp(name = ViewProps.FONT_FAMILY) public void setFontFamily(@Nullable String fontFamily) { if (!TextUtils.equals(mFontStylingSpan.getFontFamily(), fontFamily)) { getSpan().setFontFamily(fontFamily); notifyChanged(true); } } @ReactProp(name = ViewProps.FONT_WEIGHT) public void setFontWeight(@Nullable String fontWeightString) { final int fontWeight; if (fontWeightString == null) { fontWeight = -1; } else if (BOLD.equals(fontWeightString)) { fontWeight = Typeface.BOLD; } else if (NORMAL.equals(fontWeightString)) { fontWeight = Typeface.NORMAL; } else { int fontWeightNumeric = parseNumericFontWeight(fontWeightString); if (fontWeightNumeric == -1) { throw new RuntimeException("invalid font weight " + fontWeightString); } fontWeight = fontWeightNumeric >= 500 ? Typeface.BOLD : Typeface.NORMAL; } if (mFontStylingSpan.getFontWeight() != fontWeight) { getSpan().setFontWeight(fontWeight); notifyChanged(true); } } @ReactProp(name = ViewProps.TEXT_DECORATION_LINE) public void setTextDecorationLine(@Nullable String textDecorationLineString) { boolean isUnderlineTextDecorationSet = false; boolean isLineThroughTextDecorationSet = false; if (textDecorationLineString != null) { for (String textDecorationLineSubString : textDecorationLineString.split(" ")) { if ("underline".equals(textDecorationLineSubString)) { isUnderlineTextDecorationSet = true; } else if ("line-through".equals(textDecorationLineSubString)) { isLineThroughTextDecorationSet = true; } } } if (isUnderlineTextDecorationSet != mFontStylingSpan.hasUnderline() || isLineThroughTextDecorationSet != mFontStylingSpan.hasStrikeThrough()) { FontStylingSpan span = getSpan(); span.setHasUnderline(isUnderlineTextDecorationSet); span.setHasStrikeThrough(isLineThroughTextDecorationSet); notifyChanged(true); } } @ReactProp(name = ViewProps.FONT_STYLE) public void setFontStyle(@Nullable String fontStyleString) { final int fontStyle; if (fontStyleString == null) { fontStyle = -1; } else if (ITALIC.equals(fontStyleString)) { fontStyle = Typeface.ITALIC; } else if (NORMAL.equals(fontStyleString)) { fontStyle = Typeface.NORMAL; } else { throw new RuntimeException("invalid font style " + fontStyleString); } if (mFontStylingSpan.getFontStyle() != fontStyle) { getSpan().setFontStyle(fontStyle); notifyChanged(true); } } @ReactProp(name = PROP_SHADOW_OFFSET) public void setTextShadowOffset(@Nullable ReadableMap offsetMap) { float dx = 0; float dy = 0; if (offsetMap != null) { if (offsetMap.hasKey("width")) { dx = PixelUtil.toPixelFromDIP(offsetMap.getDouble("width")); } if (offsetMap.hasKey("height")) { dy = PixelUtil.toPixelFromDIP(offsetMap.getDouble("height")); } } if (!mShadowStyleSpan.offsetMatches(dx, dy)) { getShadowSpan().setOffset(dx, dy); notifyChanged(false); } } @ReactProp(name = PROP_SHADOW_RADIUS) public void setTextShadowRadius(float textShadowRadius) { textShadowRadius = PixelUtil.toPixelFromDIP(textShadowRadius); if (mShadowStyleSpan.getRadius() != textShadowRadius) { getShadowSpan().setRadius(textShadowRadius); notifyChanged(false); } } @ReactProp(name = PROP_SHADOW_COLOR, defaultInt = DEFAULT_TEXT_SHADOW_COLOR, customType = "Color") public void setTextShadowColor(int textShadowColor) { if (mShadowStyleSpan.getColor() != textShadowColor) { getShadowSpan().setColor(textShadowColor); notifyChanged(false); } } /** * Returns font size for this node. * When called on RCTText, this value is never -1 (unset). */ protected final int getFontSize() { return mFontStylingSpan.getFontSize(); } /** * Returns font style for this node. */ protected final int getFontStyle() { int style = mFontStylingSpan.getFontStyle(); return style >= 0 ? style : Typeface.NORMAL; } protected int getDefaultFontSize() { return -1; } /* package */ static int fontSizeFromSp(float sp) { return (int) Math.ceil(PixelUtil.toPixelFromSP(sp)); } protected final FontStylingSpan getSpan() { if (mFontStylingSpan.isFrozen()) { mFontStylingSpan = mFontStylingSpan.mutableCopy(); } return mFontStylingSpan; } /** * Returns a new SpannableStringBuilder that includes all the text and styling information to * create the Layout. */ /* package */ final SpannableStringBuilder getText() { SpannableStringBuilder sb = new SpannableStringBuilder(); collectText(sb); applySpans(sb, isEditable()); return sb; } private final ShadowStyleSpan getShadowSpan() { if (mShadowStyleSpan.isFrozen()) { mShadowStyleSpan = mShadowStyleSpan.mutableCopy(); } return mShadowStyleSpan; } /** * Return -1 if the input string is not a valid numeric fontWeight (100, 200, ..., 900), otherwise * return the weight. */ private static int parseNumericFontWeight(String fontWeightString) { // This should be much faster than using regex to verify input and Integer.parseInt return fontWeightString.length() == 3 && fontWeightString.endsWith("00") && fontWeightString.charAt(0) <= '9' && fontWeightString.charAt(0) >= '1' ? 100 * (fontWeightString.charAt(0) - '0') : -1; } }
33.295455
108
0.693125
eecbb19f3b3dfd57384adefc51c8604b73cd88a7
7,389
/* * 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.asterix.external.parser; import java.io.DataOutput; import java.io.IOException; import java.util.BitSet; import org.apache.asterix.common.exceptions.ErrorCode; import org.apache.asterix.common.exceptions.RuntimeDataException; import org.apache.asterix.om.base.AUnorderedList; import org.apache.asterix.om.types.AOrderedListType; import org.apache.asterix.om.types.ARecordType; import org.apache.asterix.om.types.ATypeTag; import org.apache.asterix.om.types.AUnionType; import org.apache.asterix.om.types.AUnorderedListType; import org.apache.asterix.om.types.BuiltinType; import org.apache.asterix.om.types.IAType; import org.apache.asterix.om.types.hierachy.ATypeHierarchy; import org.apache.asterix.om.utils.RecordUtil; import org.apache.hyracks.api.exceptions.HyracksDataException; /** * Abstract class for nested formats (ADM, JSON, XML ... etc) * TODO(wyk): remove extends AbstractDataParser and only take what's needed from it. * TODO(wyk): find a way to support ADM constructors for ADMDataParser */ public abstract class AbstractNestedDataParser<T> extends AbstractDataParser { private T currentParsedToken; /** * Parse object using the defined recordType. * * @param recordType * {@value RecordUtil.FULLY_OPEN_RECORD_TYPE} if parsing open object * @param out * @throws HyracksDataException */ protected abstract void parseObject(ARecordType recordType, DataOutput out) throws IOException; /** * Parse array using the defined listType. * * NOTE: currently AsterixDB only supports null values for open collection types. * * @param recordType * {@value AOrderedListType.FULL_OPEN_ORDEREDLIST_TYPE} if parsing open array * @param out * @throws HyracksDataException */ protected abstract void parseArray(AOrderedListType listType, DataOutput out) throws IOException; /** * Parse multiset using the defined listType. * * NOTE: currently AsterixDB only supports null values for open collection types. * * @param recordType * {@value AUnorderedListType.FULLY_OPEN_UNORDEREDLIST_TYPE} if parsing open multiset * @param out * @throws HyracksDataException */ protected abstract void parseMultiset(AUnorderedList listType, DataOutput out) throws IOException; /** * Map the third-party parser's token to {@link T} * This method is called by nextToken to set {@link AbstractNestedDataParser#currentParsedToken} * * @return the corresponding token * @throws IOException */ protected abstract T advanceToNextToken() throws IOException; public final T nextToken() throws IOException { currentParsedToken = advanceToNextToken(); return currentParsedToken; } public final T currentToken() { return currentParsedToken; } protected boolean isNullableType(IAType definedType) { if (definedType.getTypeTag() != ATypeTag.UNION) { return false; } return ((AUnionType) definedType).isNullableType(); } protected boolean isMissableType(IAType definedType) { if (definedType.getTypeTag() != ATypeTag.UNION) { return false; } return ((AUnionType) definedType).isMissableType(); } protected void checkOptionalConstraints(ARecordType recordType, BitSet nullBitmap) throws RuntimeDataException { for (int i = 0; i < recordType.getFieldTypes().length; i++) { if (!nullBitmap.get(i) && !isMissableType(recordType.getFieldTypes()[i])) { throw new RuntimeDataException(ErrorCode.PARSER_EXT_DATA_PARSER_CLOSED_FIELD_NULL, recordType.getFieldNames()[i]); } } } /** * Parser is not expecting definedType to be null. * * @param definedType * type defined by the user. * @param parsedTypeTag * parsed type. * @return * definedType is nullable && parsedTypeTag == ATypeTag.NULL => return ANULL * definedType == ANY && isComplexType => fully_open_complex_type * definedType == ANY && isAtomicType => ANY * defiendType == parsedTypeTag | canBeConverted => return definedType * @throws RuntimeDataException * type mismatch */ protected IAType checkAndGetType(IAType definedType, ATypeTag parsedTypeTag) throws RuntimeDataException { //Cannot be missing if (parsedTypeTag == ATypeTag.NULL && isNullableType(definedType)) { return BuiltinType.ANULL; } final IAType actualDefinedType = getActualType(definedType); if (actualDefinedType.getTypeTag() == ATypeTag.ANY) { switch (parsedTypeTag) { case OBJECT: return RecordUtil.FULLY_OPEN_RECORD_TYPE; case ARRAY: return AOrderedListType.FULL_OPEN_ORDEREDLIST_TYPE; case MULTISET: return AUnorderedListType.FULLY_OPEN_UNORDEREDLIST_TYPE; default: return BuiltinType.ANY; } } else if (actualDefinedType.getTypeTag() == parsedTypeTag || isConvertable(parsedTypeTag, actualDefinedType.getTypeTag())) { return actualDefinedType; } throw new RuntimeDataException(ErrorCode.PARSER_ADM_DATA_PARSER_TYPE_MISMATCH, definedType.getTypeName()); } private IAType getActualType(IAType definedType) { if (definedType.getTypeTag() == ATypeTag.UNION) { return ((AUnionType) definedType).getActualType(); } return definedType; } /** * Check promote/demote rules for mismatched types. * String type is a special case as it can be parsed as date/time/datetime/UUID * * @param parsedTypeTag * @param definedTypeTag * @return * true if it can be converted * false otherwise */ protected boolean isConvertable(ATypeTag parsedTypeTag, ATypeTag definedTypeTag) { boolean convertable = parsedTypeTag == ATypeTag.STRING; convertable &= definedTypeTag == ATypeTag.UUID || definedTypeTag == ATypeTag.DATE || definedTypeTag == ATypeTag.TIME || definedTypeTag == ATypeTag.DATETIME; return convertable || ATypeHierarchy.canPromote(parsedTypeTag, definedTypeTag) || ATypeHierarchy.canDemote(parsedTypeTag, definedTypeTag); } }
38.087629
116
0.678441
6c215fa2305747c70cac8551e3cdcb5da87176b0
2,940
/* * Copyright 2016 nekocode * * 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 cn.nekocode.emojix; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * @author nekocode (nekocode.cn@gmail.com) */ public class Emojix { private static class ContextWrapper extends android.content.ContextWrapper { private EmojixLayoutInflater inflater; public ContextWrapper(Context base) { super(base); } @Override public Object getSystemService(String name) { if (LAYOUT_INFLATER_SERVICE.equals(name)) { if (inflater == null) { inflater = new EmojixLayoutInflater(LayoutInflater.from(getBaseContext()), this); } return inflater; } return super.getSystemService(name); } } public static android.content.ContextWrapper wrap(Context base) { return new ContextWrapper(base); } public static void wrapView(View view) { if (view == null) return; if (view instanceof TextView) { TextView textView = (TextView) view; if (textView.getTag(R.id.tag_emojix_watcher) == null) { EmojixTextWatcher watcher = new EmojixTextWatcher(textView); textView.addTextChangedListener(watcher); textView.setTag(R.id.tag_emojix_watcher, watcher); } } else if (view instanceof ViewGroup) { if (view.getTag(R.id.tag_layout_listener) == null) { View.OnLayoutChangeListener listener = new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { ViewGroup parentView = (ViewGroup) v; int len = parentView.getChildCount(); for (int i = 0; i < len; i ++) { wrapView(parentView.getChildAt(i)); } } }; view.addOnLayoutChangeListener(listener); view.setTag(R.id.tag_layout_listener, listener); } } } }
35
102
0.598639
2cf1e727e87dc8a64a062dbcd542ed1b3157124c
1,010
package CouchBase; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; public class CouchBase { public static void main(String[] args) { Cluster cluster = CouchbaseCluster.create(); cluster.authenticate("ahmed", "123456"); Bucket bucket = cluster.openBucket("images"); bucket.counter("id", 0, Long.MAX_VALUE); long id = bucket.counter("id", 1).content(); System.out.println("ID "+ id); JsonObject user = JsonObject.empty() .put("firstname", "Walter") .put("lastname", "White") .put("job", "chemistry teacher") .put("age", 50); JsonDocument doc = JsonDocument.create(id +"" , user); JsonDocument response = bucket.upsert(doc); cluster.disconnect(); } }
29.705882
62
0.633663
ec97d134ff8f7f8532c8acb9dbd64dd2310a761b
1,001
/** * 项目名称:quickstart-design-pattern * 文件名:ConcreteHandler.java * 版本信息: * 日期:2018年1月27日 * Copyright yangzl Corporation 2018 * 版权所有 * */ package org.quickstart.design.pattern.responsibility.chain; /** * ConcreteHandler * * @author:youngzil@163.com * @2018年1月27日 上午9:51:27 * @since 1.0 */ public class ConcreteHandler extends Handler { /** * 处理方法,调用此方法处理请求 */ @Override public void handleRequest() { /** * 判断是否有后继的责任对象 如果有,就转发请求给后继的责任对象 如果没有,则处理请求 */ if (getSuccessor() != null) { System.out.println("放过请求"); getSuccessor().handleRequest(); } else { System.out.println("处理请求"); } } /* (non-Javadoc) * @see org.quickstart.design.pattern.responsibility.chain.Handler#handleFeeRequest(java.lang.String, double) */ @Override public String handleFeeRequest(String user, double fee) { // TODO Auto-generated method stub return null; } }
22.244444
113
0.61039
6fca953021f62875cf239aef79a6d90aaccd878f
998
package io.hyperfoil.internal; import java.nio.file.Path; import java.nio.file.Paths; /** * This interface should decouple controller implementation (in clustering module) and its uses (e.g. CLI). * The controller should listen on {@link #host()}:{@link #port()} as usual. */ public interface Controller { Path DEFAULT_ROOT_DIR = Paths.get(System.getProperty("java.io.tmpdir"), "hyperfoil"); String DEPLOYER = Properties.get(Properties.DEPLOYER, "ssh"); long DEPLOY_TIMEOUT = Properties.getLong(Properties.DEPLOY_TIMEOUT, 60000); Path ROOT_DIR = Properties.get(Properties.ROOT_DIR, Paths::get, DEFAULT_ROOT_DIR); Path BENCHMARK_DIR = Properties.get(Properties.BENCHMARK_DIR, Paths::get, ROOT_DIR.resolve("benchmark")); Path HOOKS_DIR = ROOT_DIR.resolve("hooks"); Path RUN_DIR = Properties.get(Properties.RUN_DIR, Paths::get, ROOT_DIR.resolve("run")); String host(); int port(); void stop(); interface Factory { Controller start(Path rootDir); } }
34.413793
108
0.726453
2107acf2afb2e064ac51a7de9c60fac81d945cf8
13,234
package fr.ralala.hexviewer.ui.fragments; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.view.LayoutInflater; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import androidx.appcompat.app.AlertDialog; import androidx.preference.CheckBoxPreference; import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceScreen; import fr.ralala.hexviewer.ApplicationCtx; import fr.ralala.hexviewer.R; import fr.ralala.hexviewer.ui.activities.SettingsActivity; import fr.ralala.hexviewer.ui.utils.UIHelper; /** * ****************************************************************************** * <p><b>Project HexViewer</b><br/> * Settings fragments * </p> * * @author Keidan * <p> * ****************************************************************************** */ public class SettingsFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener { private static final int MIN_ABBREVIATE_PORTRAIT = 1; private static final int MAX_ABBREVIATE_PORTRAIT = 25; private static final int MIN_ABBREVIATE_LANDSCAPE = 4; private static final int MAX_ABBREVIATE_LANDSCAPE = 80; private static final int MIN_HEX_ROW_HEIGHT = 10; private static final int MAX_HEX_ROW_HEIGHT = 1000; private static final int MIN_HEX_FONT_SIZE = 1; private static final int MAX_HEX_FONT_SIZE = 50; private static final int MIN_PLAIN_ROW_HEIGHT = 50; private static final int MAX_PLAIN_ROW_HEIGHT = 1000; private static final int MIN_PLAIN_FONT_SIZE = 1; private static final int MAX_PLAIN_FONT_SIZE = 10; private final SettingsActivity mActivity; private final ApplicationCtx mApp; protected Preference mAbbreviatePortrait; protected Preference mAbbreviateLandscape; protected CheckBoxPreference mHexRowHeightAuto; protected Preference mHexRowHeight; protected Preference mHexFontSize; protected CheckBoxPreference mPlainRowHeightAuto; protected Preference mPlainRowHeight; protected Preference mPlainFontSize; private ListPreference mLanguage; public SettingsFragment(SettingsActivity owner) { mActivity = owner; mApp = ApplicationCtx.getInstance(); } /** * Called during {@link #onCreate(Bundle)} to supply the preferences for this fragment. * Subclasses are expected to call {@link #setPreferenceScreen(PreferenceScreen)} either * directly or via helper methods such as {@link #addPreferencesFromResource(int)}. * * @param savedInstanceState If the fragment is being re-created from a previous saved state, * this is the state. * @param rootKey If non-null, this preference fragment should be rooted at the * {@link PreferenceScreen} with this key. */ @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.preferences, rootKey); mAbbreviatePortrait = findPreference(ApplicationCtx.CFG_ABBREVIATE_PORTRAIT); mAbbreviateLandscape = findPreference(ApplicationCtx.CFG_ABBREVIATE_LANDSCAPE); mHexRowHeightAuto = findPreference(ApplicationCtx.CFG_HEX_ROW_HEIGHT_AUTO); mHexRowHeight = findPreference(ApplicationCtx.CFG_HEX_ROW_HEIGHT); mHexFontSize = findPreference(ApplicationCtx.CFG_HEX_FONT_SIZE); mPlainRowHeightAuto = findPreference(ApplicationCtx.CFG_PLAIN_ROW_HEIGHT_AUTO); mPlainRowHeight = findPreference(ApplicationCtx.CFG_PLAIN_ROW_HEIGHT); mPlainFontSize = findPreference(ApplicationCtx.CFG_PLAIN_FONT_SIZE); mLanguage = findPreference(ApplicationCtx.CFG_LANGUAGE); mAbbreviatePortrait.setOnPreferenceClickListener(this); mAbbreviateLandscape.setOnPreferenceClickListener(this); mHexRowHeightAuto.setOnPreferenceClickListener(this); mHexRowHeight.setOnPreferenceClickListener(this); mHexFontSize.setOnPreferenceClickListener(this); mPlainRowHeightAuto.setOnPreferenceClickListener(this); mPlainRowHeight.setOnPreferenceClickListener(this); mPlainFontSize.setOnPreferenceClickListener(this); mLanguage.setOnPreferenceChangeListener(this); mHexRowHeightAuto.setChecked(mApp.isHexRowHeightAuto()); mPlainRowHeightAuto.setChecked(mApp.isPlainRowHeightAuto()); mHexRowHeight.setEnabled(!mApp.isHexRowHeightAuto()); mPlainRowHeight.setEnabled(!mApp.isPlainRowHeightAuto()); mLanguage.setDefaultValue(mApp.getApplicationLanguage(getContext())); } /** * Called when a preference has been clicked. * * @param preference The preference that was clicked * @return {@code true} if the click was handled */ @Override public boolean onPreferenceClick(Preference preference) { if (preference.equals(mAbbreviatePortrait)) { displayDialog(mAbbreviatePortrait.getTitle(), mApp.getAbbreviatePortrait(), MIN_ABBREVIATE_PORTRAIT, MAX_ABBREVIATE_PORTRAIT, mApp::setAbbreviatePortrait); } else if (preference.equals(mAbbreviateLandscape)) { displayDialog(mAbbreviateLandscape.getTitle(), mApp.getAbbreviateLandscape(), MIN_ABBREVIATE_LANDSCAPE, MAX_ABBREVIATE_LANDSCAPE, mApp::setAbbreviateLandscape); } else if (preference.equals(mHexRowHeightAuto)) { mHexRowHeight.setEnabled(!mHexRowHeightAuto.isChecked()); } else if (preference.equals(mHexRowHeight)) { displayDialog(mHexRowHeight.getTitle(), mApp.getHexRowHeight(), MIN_HEX_ROW_HEIGHT, MAX_HEX_ROW_HEIGHT, mApp::setHexRowHeight); } else if (preference.equals(mHexFontSize)) { displayDialog(mHexFontSize.getTitle(), mApp.getHexFontSize(), MIN_HEX_FONT_SIZE, MAX_HEX_FONT_SIZE, mApp::setHexFontSize, true); } else if (preference.equals(mPlainRowHeightAuto)) { mPlainRowHeight.setEnabled(!mPlainRowHeightAuto.isChecked()); } else if (preference.equals(mPlainRowHeight)) { displayDialog(mPlainRowHeight.getTitle(), mApp.getPlainRowHeight(), MIN_PLAIN_ROW_HEIGHT, MAX_PLAIN_ROW_HEIGHT, mApp::setPlainRowHeight); } else if (preference.equals(mPlainFontSize)) { displayDialog(mPlainFontSize.getTitle(), mApp.getPlainFontSize(), MIN_PLAIN_FONT_SIZE, MAX_PLAIN_FONT_SIZE, mApp::setPlainFontSize, true); } return false; } /** * Called when a preference has been changed. * * @param preference The preference that was clicked * @param newValue The new value. * @return {@code true} if the click was handled */ @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.equals(mLanguage)) { if (!mActivity.isChanged()) { mApp.setApplicationLanguage("" + newValue); getActivity().finish(); return true; } else { new AlertDialog.Builder(getContext()) .setCancelable(false) //.setIcon(R.mipmap.ic_launcher) .setTitle(preference.getTitle()) .setMessage(R.string.control_language_change) .setPositiveButton(android.R.string.yes, (dialog, whichButton) -> dialog.dismiss()).show(); } } return false; } /** * Displays the input dialog box. * * @param title Dialog title. * @param defaultValue Default value. * @param minValue Min value. * @param maxValue Max value. * @param iv Callback which will be called if the entry is valid. */ @SuppressLint("InflateParams") private void displayDialog(CharSequence title, int defaultValue, int minValue, int maxValue, InputValidated<Integer> iv) { displayDialog(title, defaultValue, minValue, maxValue, (v) -> iv.onValidated(v.intValue()), false); } /** * Displays the input dialog box. * * @param title Dialog title. * @param defaultValue Default value. * @param minValue Min value. * @param maxValue Max value. * @param iv Callback which will be called if the entry is valid. */ @SuppressLint("InflateParams") private void displayDialog(CharSequence title, float defaultValue, float minValue, float maxValue, InputValidated<Float> iv, boolean decimal) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setCancelable(false) .setTitle(title) .setPositiveButton(android.R.string.yes, null) .setNegativeButton(android.R.string.no, (dialog, whichButton) -> { }); LayoutInflater factory = LayoutInflater.from(mActivity); builder.setView(factory.inflate(R.layout.content_dialog_pref_input, null)); final AlertDialog dialog = builder.create(); dialog.show(); EditText et = dialog.findViewById(R.id.editText); if (et != null) { int inputType = InputType.TYPE_CLASS_NUMBER; String def; int maxLen; if (decimal) { maxLen = 5; inputType |= InputType.TYPE_NUMBER_FLAG_DECIMAL; def = String.valueOf(defaultValue); } else { maxLen = 3; def = String.valueOf((int) defaultValue); } et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLen)}); et.setInputType(inputType); et.setText(def); et.requestFocus(); Editable text = et.getText(); if (text.length() > 0) { text.replace(0, 1, text.subSequence(0, 1), 0, 1); et.selectAll(); } } final InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener((v) -> { if (et != null && validInput(et, defaultValue, minValue, maxValue, iv, decimal)) { imm.hideSoftInputFromWindow(et.getWindowToken(), 0); dialog.dismiss(); } }); dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener((v) -> { if (et != null) imm.hideSoftInputFromWindow(et.getWindowToken(), 0); dialog.dismiss(); }); } /** * Validation of the input. * * @param et EditText * @param defaultValue Default value. * @param minValue Min value. * @param maxValue Max value. * @param iv Callback * @return False on error. */ private boolean validInput(EditText et, float defaultValue, float minValue, float maxValue, InputValidated<Float> iv, boolean decimal) { try { Editable s = et.getText(); float nb = Float.parseFloat(s.toString()); if (s.length() == 0) { et.setText(String.valueOf(!decimal ? (int) minValue : minValue)); et.selectAll(); return false; } else { if (nb < minValue) { UIHelper.shakeError(et, mActivity.getString(R.string.error_less_than) + ": " + minValue); et.setText(String.valueOf(!decimal ? (int) minValue : minValue)); et.selectAll(); return false; } else if (nb > maxValue) { UIHelper.shakeError(et, mActivity.getString(R.string.error_greater_than) + ": " + maxValue); et.setText(String.valueOf(!decimal ? (int) maxValue : maxValue)); et.selectAll(); return false; } else et.setError(null); iv.onValidated(nb); return true; } } catch (Exception ex) { UIHelper.shakeError(et, ex.getMessage()); et.setText(String.valueOf(!decimal ? (int) defaultValue : defaultValue)); et.selectAll(); return false; } } /* ----------------------------- */ private interface InputValidated<T> { void onValidated(T n); } }
43.248366
151
0.624981
fa84e9569726830159c71b70b89ff6bab2f21770
4,722
/* * 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.tools.ant.taskdefs.optional; import org.apache.tools.ant.BuildFileTest; import org.apache.tools.ant.util.FileUtils; import java.util.Properties; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * JUnit Testcase for the optional replaceregexp task. * */ public class ReplaceRegExpTest extends BuildFileTest { private static final String PROJECT_PATH = "src/etc/testcases/taskdefs/optional"; private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); public ReplaceRegExpTest(String name) { super(name); } public void setUp() { configureProject(PROJECT_PATH + "/replaceregexp.xml"); } public void tearDown() { executeTarget("cleanup"); } public void testReplace() throws IOException { Properties original = new Properties(); FileInputStream propsFile = null; try { propsFile = new FileInputStream(new File(System.getProperty("root"), PROJECT_PATH + "/replaceregexp.properties")); original.load(propsFile); } finally { if (propsFile != null) { propsFile.close(); propsFile = null; } } assertEquals("Def", original.get("OldAbc")); executeTarget("testReplace"); Properties after = new Properties(); try { propsFile = new FileInputStream(new File(System.getProperty("root"), PROJECT_PATH + "/test.properties")); after.load(propsFile); } finally { if (propsFile != null) { propsFile.close(); propsFile = null; } } assertNull(after.get("OldAbc")); assertEquals("AbcDef", after.get("NewProp")); } // inspired by bug 22541 public void testDirectoryDateDoesNotChange() { executeTarget("touchDirectory"); File myFile = new File(System.getProperty("root"), PROJECT_PATH + "/" + getProject().getProperty("tmpregexp")); long timeStampBefore = myFile.lastModified(); executeTarget("testDirectoryDateDoesNotChange"); long timeStampAfter = myFile.lastModified(); assertEquals("directory date should not change", timeStampBefore, timeStampAfter); } public void testDontAddNewline1() throws IOException { executeTarget("testDontAddNewline1"); assertTrue("Files match", FILE_UTILS .contentEquals(new File(System.getProperty("root"), PROJECT_PATH + "/test.properties"), new File(System.getProperty("root"), PROJECT_PATH + "/replaceregexp2.result.properties"))); } public void testDontAddNewline2() throws IOException { executeTarget("testDontAddNewline2"); assertTrue("Files match", FILE_UTILS .contentEquals(new File(System.getProperty("root"), PROJECT_PATH + "/test.properties"), new File(System.getProperty("root"), PROJECT_PATH + "/replaceregexp2.result.properties"))); } public void testNoPreserveLastModified() throws Exception { executeTarget("lastModifiedSetup"); String tmpdir = project.getProperty("tmpregexp"); long ts1 = new File(tmpdir, "test.txt").lastModified(); Thread.sleep(3000); executeTarget("testNoPreserve"); assertTrue(ts1 < new File(tmpdir, "test.txt").lastModified()); } public void testPreserveLastModified() throws Exception { executeTarget("lastModifiedSetup"); String tmpdir = project.getProperty("tmpregexp"); long ts1 = new File(tmpdir, "test.txt").lastModified(); Thread.sleep(3000); executeTarget("testPreserve"); assertTrue(ts1 == new File(tmpdir, "test.txt").lastModified()); } }// ReplaceRegExpTest
38.080645
126
0.648454
810a4b28e8d0bebec23b878a993b9505f99714a0
773
package com.leetcode.sort; /** * Created by caozhen on 2019/1/25 */ /** * 冒泡排序: * * 时间复杂度为:O(n2) * * 双重循环语句,外层控制循环多少趟,内层控制每一趟的循环次数。 * * 每进行一趟排序,就会少比较一次,因为每进行一趟排序都会找出一个较大值。 * * 外层循环 n次,内层循环n-i次 */ public class BubbleSort { public static void main(String[] args) { int[] a = {10, 50, 30, 69, 79, 40, 20, 80}; int n = a.length; int tmp = 0; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (a[j] > a[j + 1]) { tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } for (int i = 0; i < a.length; i++) { System.out.printf("%d ", a[i]); } } }
17.177778
51
0.393273
a1c0a809b2476cb38f85737ba3dc210802135aec
4,112
package org.n0nb0at.hbase; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; public class HBaseOperation { public static Configuration configuration; public static Connection connection; public static Admin admin; public static void main(String[] args) { try { // 初始化连接 init(); // 创建表 createTable("guopeng:student", "info", "score"); // 更新字段信息 /*insertData("guopeng:student", "guopeng", "info", "student_id", "20190343020028"); insertData("guopeng:student", "guopeng", "info", "class", "3"); insertData("guopeng:student", "guopeng", "score", "underStanding", "60"); insertData("guopeng:student", "guopeng", "score", "programing", "80");*/ // 查询行信息:可指定列族、列名 getData("guopeng:student", "guopeng", StringUtils.EMPTY, StringUtils.EMPTY); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭连接 close(); } } public static void init() { configuration = HBaseConfiguration.create(); // configuration.set("hbase.rootdir", "hdfs://master01:9000/hbase"); // configuration.set("hbase.zookeeper.quorum", "master01,slave01,slave02"); configuration.set("hbase.rootdir", "hdfs://jikehadoop01:9000/hbase"); configuration.set("hbase.zookeeper.quorum", "47.101.216.12"); configuration.set("hbase.zookeeper.property.clientPort", "2181"); try { connection = ConnectionFactory.createConnection(configuration); admin = connection.getAdmin(); } catch (IOException e) { e.printStackTrace(); } } public static void close() { try { if (admin != null) { admin.close(); } if (null != connection) { connection.close(); } } catch (IOException e) { e.printStackTrace(); } } public static void createTable(String myTableName, String... colFamily) throws IOException { TableName tableName = TableName.valueOf(myTableName); if (admin.tableExists(tableName)) { System.out.println("table is exists!"); } else { TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(tableName); for (String str : colFamily) { ColumnFamilyDescriptor family = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(str)).build(); tableDescriptor.setColumnFamily(family); } admin.createTable(tableDescriptor.build()); } } public static void insertData(String tableName, String rowKey, String colFamily, String col, String val) throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); Put put = new Put(rowKey.getBytes()); put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes()); table.put(put); table.close(); System.out.printf("insert success! rowKey:%s, colFamily:%s, col:%s val:%s %n", rowKey, colFamily, col, val); } public static void getData(String tableName, String rowKey, String colFamily, String col) throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); Get get = new Get(rowKey.getBytes()); if (!StringUtils.isEmpty(colFamily)) { if (!StringUtils.isEmpty(col)) { get.addColumn(colFamily.getBytes(), col.getBytes()); } else { get.addFamily(colFamily.getBytes()); } } Result result = table.get(get); System.out.printf("getData: %s%n", result.toString()); table.close(); } }
37.045045
98
0.58536
6be5e004376833f0ba11baa515829879a6326d71
152
package com.velmurugan.certifier.dao; import com.velmurugan.certifier.entity.Settings; public interface SettingsDao extends GenericDao<Settings> { }
19
59
0.822368
09f4407d42a7f2229ec3b6b9e33aef0663ec0ea6
2,284
package com.robotman2412.litemod.mixin; import com.robotman2412.litemod.block.railables.HyperAbstractRailBlock; import net.minecraft.block.AbstractRailBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.enums.RailShape; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.vehicle.AbstractMinecartEntity; import net.minecraft.state.property.Property; import net.minecraft.tag.BlockTags; import net.minecraft.tag.Tag; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(AbstractMinecartEntity.class) public abstract class AbstractMinecartEntityMixin extends Entity { private AbstractMinecartEntityMixin(EntityType<?> type, World world) { super(type, world); } @Redirect(at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockState;matches(Lnet/minecraft/tag/Tag;)Z"), method = "tick") public boolean redirectIsRailBlock(BlockState blockState, Tag<Block> tag) { boolean value = blockState.matches(tag); if (tag == BlockTags.RAILS) { return blockState.getBlock() instanceof AbstractRailBlock; } return value; } @Redirect(at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockState;get(Lnet/minecraft/state/property/Property;)Ljava/lang/Comparable;"), method = "moveOnRail") public <T extends Comparable<T>> T redirectGetRailShape(BlockState state, Property<T> property) { T value = state.get(property); int x = MathHelper.floor(this.getX()); int y = MathHelper.floor(this.getY()); int z = MathHelper.floor(this.getZ()); if (this.world.getBlockState(new BlockPos(x, y - 1, z)).getBlock() instanceof AbstractRailBlock) { y --; } BlockPos pos = new BlockPos(x, y, z); if (state.getBlock() instanceof HyperAbstractRailBlock) { Object obj = this; RailShape shape = ((HyperAbstractRailBlock) state.getBlock()).getRailShapeFor(this.world, (AbstractMinecartEntity) obj, pos, state); try { return (T) shape; } catch (ClassCastException e) { return value; } } return value; } }
38.066667
172
0.760508
6e058acf9172b3eadd151a9a9d94fb190f5bfca9
295
package liulx.iservice; import liulx.domain.Post; import liulx.domain.User; import java.util.List; /** * Created by Liu Lixiang on 2017/5/3. */ public interface IPostService { Post create(Post post, User user); List<Post> getPosts(User user); Post getPost(int id, User user); }
18.4375
38
0.705085
7ff2cc2e7c4c9ef3a830c6c189487984fe0d5da4
446
package echowand.info; import echowand.common.ClassEOJ; import echowand.common.EPC; /** * 水位センサクラスの基本設定を行う。 * @author Yoshiki Makino */ public class WaterLevelSensorInfo extends DeviceObjectInfo { /** * WaterLevelSensorInfoを生成する */ public WaterLevelSensorInfo() { setClassEOJ(new ClassEOJ((byte)0x00, (byte)(0x14))); add(EPC.xE0, true, false, false, 1, new PropertyConstraintWaterLevel()); } }
22.3
80
0.679372
10736c24e3dc82eb27270cd23cf0a75d52012235
1,941
package lemon.elastic.query4j.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author Robert HG (254963746@qq.com) on 6/23/14. */ public class CollectionUtil { private CollectionUtil() { } @SuppressWarnings("rawtypes") public static boolean isNotEmpty(Map map) { return map != null && map.size() > 0; } @SuppressWarnings("rawtypes") public static boolean isEmpty(Map map) { return !isNotEmpty(map); } public static boolean isNotEmpty(Collection<?> collection) { return collection != null && collection.size() > 0; } public static boolean isEmpty(Collection<?> collection) { return !isNotEmpty(collection); } @SuppressWarnings("rawtypes") public static int sizeOf(Collection collection) { if (isEmpty(collection)) { return 0; } return collection.size(); } public static boolean noNullElements(Object[] array) { if (array != null) { for (int i = 0; i < array.length; i++) { if (array[i] == null) { return false; } } return true; } return false; } public static String[] toArray(List<String> values) { String[] valuesAsArray = new String[values.size()]; return values.toArray(valuesAsArray); } /** * 返回第一个列表中比第二个多出来的元素 * * @param list1 * @param list2 * @return */ public static <T> List<T> getLeftDiff(List<T> list1, List<T> list2) { if (isEmpty(list2)) { return list1; } List<T> list = new ArrayList<T>(); if (isNotEmpty(list1)) { for (T o : list1) { if (!list2.contains(o)) { list.add(o); } } } return list; } }
23.670732
73
0.539413
dca8891c42ad99abe951eccc9bb063c441318576
1,695
package io.yggdrash.core.store; import io.yggdrash.common.store.StateStore; public class BlockChainStore { private final TransactionStore transactionStore; private final ReceiptStore receiptStore; private final StateStore stateStore; private final ConsensusBlockStore consensusBlockStore; private final BranchStore branchStore; private final ContractStore contractStore; private final LogStore logStore; public BlockChainStore(TransactionStore transactionStore, ReceiptStore receiptStore, StateStore stateStore, ConsensusBlockStore consensusBlockStore, BranchStore branchStore, LogStore logStore) { this.transactionStore = transactionStore; this.receiptStore = receiptStore; this.stateStore = stateStore; this.consensusBlockStore = consensusBlockStore; this.branchStore = branchStore; this.logStore = logStore; contractStore = new ContractStore(branchStore, stateStore, receiptStore); } public TransactionStore getTransactionStore() { return transactionStore; } public ReceiptStore getReceiptStore() { return receiptStore; } public StateStore getStateStore() { return stateStore; } public ConsensusBlockStore getConsensusBlockStore() { return consensusBlockStore; } public BranchStore getBranchStore() { return branchStore; } public ContractStore getContractStore() { return contractStore; } public LogStore getLogStore() { return logStore; } }
29.224138
81
0.669027
d773cbd3a99daf1b180fb20d3c8526958fc28b35
4,156
/** * Black Duck JIRA Plugin * * Copyright (C) 2020 Synopsys, Inc. * https://www.synopsys.com/ * * 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 com.blackducksoftware.integration.jira.mocks.field; import java.util.ArrayList; import java.util.List; import org.ofbiz.core.entity.GenericValue; import com.atlassian.jira.issue.fields.Field; import com.atlassian.jira.issue.fields.OrderableField; import com.atlassian.jira.issue.fields.layout.field.EditableDefaultFieldLayout; import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem; import com.atlassian.jira.project.Project; import com.atlassian.jira.user.ApplicationUser; public class EditableDefaultFieldLayoutMock implements EditableDefaultFieldLayout { private final List<FieldLayoutItem> fieldLayoutItems = new ArrayList<>(); @Override public String getType() { return null; } @Override public void hide(final FieldLayoutItem arg0) { } @Override public void makeOptional(final FieldLayoutItem arg0) { } @Override public void makeRequired(final FieldLayoutItem arg0) { } @Override public void setDescription(final String arg0) { } @Override public void setDescription(final FieldLayoutItem arg0, final String arg1) { } @Override public void setName(final String arg0) { } @Override public void setRendererType(final FieldLayoutItem arg0, final String arg1) { } @Override public void show(final FieldLayoutItem arg0) { } @Override public String getDescription() { return null; } @Override public FieldLayoutItem getFieldLayoutItem(final OrderableField arg0) { return null; } @Override public FieldLayoutItem getFieldLayoutItem(final String arg0) { return null; } @Override public List<FieldLayoutItem> getFieldLayoutItems() { return fieldLayoutItems; } public void addFieldLayoutItem(final FieldLayoutItem fieldLayoutItem) { fieldLayoutItems.add(fieldLayoutItem); } @Override public GenericValue getGenericValue() { return null; } @Override public List<Field> getHiddenFields(final Project arg0, final List<String> arg1) { return null; } @Override public Long getId() { return null; } @Override public String getName() { return null; } @Override public String getRendererTypeForField(final String arg0) { return null; } @Override public List<FieldLayoutItem> getRequiredFieldLayoutItems(final Project arg0, final List<String> arg1) { return null; } @Override public List<FieldLayoutItem> getVisibleCustomFieldLayoutItems(final Project arg0, final List<String> arg1) { return null; } @Override public List<FieldLayoutItem> getVisibleLayoutItems(final Project arg0, final List<String> arg1) { return null; } @Override public boolean isDefault() { return false; } @Override public boolean isFieldHidden(final String arg0) { return false; } @Override public List<FieldLayoutItem> getVisibleLayoutItems(final ApplicationUser arg0, final Project arg1, final List<String> arg2) { // Auto-generated method stub return null; } }
22.586957
112
0.696102
64e63d6867b1834711a7cdeac92691f32a57e444
696
package com.rscnn.model; import android.renderscript.RenderScript; import com.rscnn.network.ConvNet; import com.rscnn.postprocess.ClassifierPostProcess; import com.rscnn.postprocess.PostProcess; import com.rscnn.preprocess.PreProcess; import java.io.IOException; public class MobileNet extends ObjectDetector { public MobileNet(RenderScript renderScript, String modelDir) throws IOException { float[] meanValue = new float[]{103.94f,116.78f,123.68f}; PreProcess preProcess = new PreProcess(meanValue, 0.017f); PostProcess postProcess = new ClassifierPostProcess(); this.convNet = new ConvNet(renderScript, null, modelDir, preProcess, postProcess); } }
34.8
90
0.767241
61c83fe17973457552cc4855926e32d5bc3b0129
5,088
package haxe; import haxe.root.*; @SuppressWarnings(value={"rawtypes", "unchecked"}) public class Timer extends haxe.lang.HxObject { public Timer(haxe.lang.EmptyObject empty) { { } } public Timer(int time_ms) { haxe.Timer.__hx_ctor_haxe_Timer(this, time_ms); } public static void __hx_ctor_haxe_Timer(haxe.Timer __temp_me10, int time_ms) { __temp_me10.run = ( (( haxe.Timer___hx_ctor_haxe_Timer_113__Fun.__hx_current != null )) ? (haxe.Timer___hx_ctor_haxe_Timer_113__Fun.__hx_current) : (haxe.Timer___hx_ctor_haxe_Timer_113__Fun.__hx_current = ((haxe.Timer___hx_ctor_haxe_Timer_113__Fun) (new haxe.Timer___hx_ctor_haxe_Timer_113__Fun()) )) ); __temp_me10.timer = new java.util.Timer(); __temp_me10.timer.scheduleAtFixedRate(((java.util.TimerTask) (__temp_me10.task = new haxe._Timer.TimerTask(((haxe.Timer) (__temp_me10) ))) ), ((long) (time_ms) ), ((long) (time_ms) )); } public static haxe.Timer delay(haxe.lang.Function f, int time_ms) { haxe.root.Array<haxe.lang.Function> f1 = new haxe.root.Array<haxe.lang.Function>(new haxe.lang.Function[]{f}); haxe.root.Array<haxe.Timer> t = new haxe.root.Array<haxe.Timer>(new haxe.Timer[]{new haxe.Timer(((int) (time_ms) ))}); t.__get(0).run = new haxe.Timer_delay_128__Fun(((haxe.root.Array<haxe.Timer>) (t) ), ((haxe.root.Array<haxe.lang.Function>) (f1) )); return t.__get(0); } public static <T> T measure(haxe.lang.Function f, java.lang.Object pos) { double t0 = haxe.Timer.stamp(); T r = ((T) (f.__hx_invoke0_o()) ); haxe.Log.trace.__hx_invoke2_o(0.0, ( haxe.lang.Runtime.toString(( haxe.Timer.stamp() - t0 )) + "s" ), 0.0, pos); return r; } public static double stamp() { return haxe.root.Sys.time(); } public static java.lang.Object __hx_createEmpty() { return new haxe.Timer(((haxe.lang.EmptyObject) (haxe.lang.EmptyObject.EMPTY) )); } public static java.lang.Object __hx_create(haxe.root.Array arr) { return new haxe.Timer(((int) (haxe.lang.Runtime.toInt(arr.__get(0))) )); } public java.util.Timer timer; public java.util.TimerTask task; public void stop() { this.timer.cancel(); this.timer = null; this.task = null; } public haxe.lang.Function run; @Override public java.lang.Object __hx_setField(java.lang.String field, java.lang.Object value, boolean handleProperties) { { boolean __temp_executeDef77 = true; switch (field.hashCode()) { case 113291: { if (field.equals("run")) { __temp_executeDef77 = false; this.run = ((haxe.lang.Function) (value) ); return value; } break; } case 110364485: { if (field.equals("timer")) { __temp_executeDef77 = false; this.timer = ((java.util.Timer) (value) ); return value; } break; } case 3552645: { if (field.equals("task")) { __temp_executeDef77 = false; this.task = ((java.util.TimerTask) (value) ); return value; } break; } } if (__temp_executeDef77) { return super.__hx_setField(field, value, handleProperties); } else { throw null; } } } @Override public java.lang.Object __hx_getField(java.lang.String field, boolean throwErrors, boolean isCheck, boolean handleProperties) { { boolean __temp_executeDef78 = true; switch (field.hashCode()) { case 113291: { if (field.equals("run")) { __temp_executeDef78 = false; return this.run; } break; } case 110364485: { if (field.equals("timer")) { __temp_executeDef78 = false; return this.timer; } break; } case 3540994: { if (field.equals("stop")) { __temp_executeDef78 = false; return ((haxe.lang.Function) (new haxe.lang.Closure(((java.lang.Object) (this) ), haxe.lang.Runtime.toString("stop"))) ); } break; } case 3552645: { if (field.equals("task")) { __temp_executeDef78 = false; return this.task; } break; } } if (__temp_executeDef78) { return super.__hx_getField(field, throwErrors, isCheck, handleProperties); } else { throw null; } } } @Override public java.lang.Object __hx_invokeField(java.lang.String field, haxe.root.Array dynargs) { { boolean __temp_executeDef79 = true; switch (field.hashCode()) { case 3540994: { if (field.equals("stop")) { __temp_executeDef79 = false; this.stop(); } break; } } if (__temp_executeDef79) { return super.__hx_invokeField(field, dynargs); } } return null; } @Override public void __hx_getFields(haxe.root.Array<java.lang.String> baseArr) { baseArr.push("run"); baseArr.push("task"); baseArr.push("timer"); { super.__hx_getFields(baseArr); } } }
19.875
305
0.60967
7665f9d911afb5769c77f4cef91897ed247f6e4f
1,176
package com.gabe.bedwars.events; import com.gabe.bedwars.arenas.Game; import com.gabe.bedwars.team.GameTeam; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class BWBreakBedEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final Player player; private final Game game; private final GameTeam team; private boolean cancelled = false; public BWBreakBedEvent(Game game, Player player, GameTeam team) { this.player = player; this.game = game; this.team = team; } public Player getPlayer() { return player; } public Game getGame() { return game; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(boolean cancel) { cancelled = cancel; } public GameTeam getTeam() { return team; } }
22.615385
69
0.672619
c2f0bb85f90af7e5959b8583d903e55dc9a3237a
6,226
/* * 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 com.google.cloud.dataflow.sdk.options; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import com.google.api.services.bigquery.Bigquery.Datasets.Delete; import com.google.api.services.storage.Storage; import com.google.cloud.dataflow.sdk.options.GoogleApiDebugOptions.GoogleApiTracer; import com.google.cloud.dataflow.sdk.util.TestCredential; import com.google.cloud.dataflow.sdk.util.Transport; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link GoogleApiDebugOptions}. */ @RunWith(JUnit4.class) public class GoogleApiDebugOptionsTest { private static final String STORAGE_GET_TRACE = "--googleApiTrace={\"Objects.Get\":\"GetTraceDestination\"}"; private static final String STORAGE_GET_AND_LIST_TRACE = "--googleApiTrace={\"Objects.Get\":\"GetTraceDestination\"," + "\"Objects.List\":\"ListTraceDestination\"}"; private static final String STORAGE_TRACE = "--googleApiTrace={\"Storage\":\"TraceDestination\"}"; @Test public void testWhenTracingMatches() throws Exception { String[] args = new String[] {STORAGE_GET_TRACE}; GcsOptions options = PipelineOptionsFactory.fromArgs(args).as(GcsOptions.class); options.setGcpCredential(new TestCredential()); assertNotNull(options.getGoogleApiTrace()); Storage.Objects.Get request = Transport.newStorageClient(options).build().objects().get("testBucketId", "testObjectId"); assertEquals("GetTraceDestination", request.get("$trace")); } @Test public void testWhenTracingDoesNotMatch() throws Exception { String[] args = new String[] {STORAGE_GET_TRACE}; GcsOptions options = PipelineOptionsFactory.fromArgs(args).as(GcsOptions.class); options.setGcpCredential(new TestCredential()); assertNotNull(options.getGoogleApiTrace()); Storage.Objects.List request = Transport.newStorageClient(options).build().objects().list("testProjectId"); assertNull(request.get("$trace")); } @Test public void testWithMultipleTraces() throws Exception { String[] args = new String[] {STORAGE_GET_AND_LIST_TRACE}; GcsOptions options = PipelineOptionsFactory.fromArgs(args).as(GcsOptions.class); options.setGcpCredential(new TestCredential()); assertNotNull(options.getGoogleApiTrace()); Storage.Objects.Get getRequest = Transport.newStorageClient(options).build().objects().get("testBucketId", "testObjectId"); assertEquals("GetTraceDestination", getRequest.get("$trace")); Storage.Objects.List listRequest = Transport.newStorageClient(options).build().objects().list("testProjectId"); assertEquals("ListTraceDestination", listRequest.get("$trace")); } @Test public void testMatchingAllCalls() throws Exception { String[] args = new String[] {STORAGE_TRACE}; GcsOptions options = PipelineOptionsFactory.fromArgs(args).as(GcsOptions.class); options.setGcpCredential(new TestCredential()); assertNotNull(options.getGoogleApiTrace()); Storage.Objects.Get getRequest = Transport.newStorageClient(options).build().objects().get("testBucketId", "testObjectId"); assertEquals("TraceDestination", getRequest.get("$trace")); Storage.Objects.List listRequest = Transport.newStorageClient(options).build().objects().list("testProjectId"); assertEquals("TraceDestination", listRequest.get("$trace")); } @Test public void testMatchingAgainstClient() throws Exception { GcsOptions options = PipelineOptionsFactory.as(GcsOptions.class); options.setGcpCredential(new TestCredential()); options.setGoogleApiTrace(new GoogleApiTracer().addTraceFor( Transport.newStorageClient(options).build(), "TraceDestination")); Storage.Objects.Get getRequest = Transport.newStorageClient(options).build().objects().get("testBucketId", "testObjectId"); assertEquals("TraceDestination", getRequest.get("$trace")); Delete deleteRequest = Transport.newBigQueryClient(options.as(BigQueryOptions.class)) .build().datasets().delete("testProjectId", "testDatasetId"); assertNull(deleteRequest.get("$trace")); } @Test public void testMatchingAgainstRequestType() throws Exception { GcsOptions options = PipelineOptionsFactory.as(GcsOptions.class); options.setGcpCredential(new TestCredential()); options.setGoogleApiTrace(new GoogleApiTracer().addTraceFor( Transport.newStorageClient(options).build().objects() .get("aProjectId", "aObjectId"), "TraceDestination")); Storage.Objects.Get getRequest = Transport.newStorageClient(options).build().objects().get("testBucketId", "testObjectId"); assertEquals("TraceDestination", getRequest.get("$trace")); Storage.Objects.List listRequest = Transport.newStorageClient(options).build().objects().list("testProjectId"); assertNull(listRequest.get("$trace")); } @Test public void testDeserializationAndSerializationOfGoogleApiTracer() throws Exception { String serializedValue = "{\"Api\":\"Token\"}"; ObjectMapper objectMapper = new ObjectMapper(); assertEquals(serializedValue, objectMapper.writeValueAsString( objectMapper.readValue(serializedValue, GoogleApiTracer.class))); } }
42.067568
100
0.743656