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
eeb215b2fc62673141dab8a2594f4121f6f4e6c1
6,319
/* * 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.netbeans.modules.url; import java.awt.Component; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.BeanInfo; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JMenuItem; import org.openide.awt.Mnemonics; import org.openide.cookies.OpenCookie; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileStateInvalidException; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUIUtils; import org.openide.loaders.DataObject; import org.openide.nodes.Node; import org.openide.util.HelpCtx; import org.openide.util.ImageUtilities; import org.openide.util.Utilities; import org.openide.util.WeakListeners; import org.openide.util.actions.Presenter; /** * Presenter which creates actual components on demand. * * @author Ian Formanek * @author Marian Petras */ final class URLPresenter implements Presenter.Menu, Presenter.Toolbar, Presenter.Popup, ActionListener { /** <code>URLDataObject</code> this presenter presents */ private final URLDataObject dataObject; /** * Creates a new presenter for a specified <code>URLDataObject</code>. * * @param dataObject <code>URLDataObject</code> to represent */ URLPresenter(URLDataObject dataObject) { this.dataObject = dataObject; } /* implements interface Presenter.Menu */ public JMenuItem getMenuPresenter() { JMenuItem menuItem = new JMenuItem(); initialize(menuItem, false); return menuItem; } /* implements interface Presenter.Popup */ public JMenuItem getPopupPresenter() { JMenuItem menuItem = new JMenuItem(); initialize(menuItem, false); return menuItem; } /* implements interface Presenter.Toolbar */ public Component getToolbarPresenter() { JButton toolbarButton = new JButton(); initialize(toolbarButton, true); return toolbarButton; } /** * Initializes a specified presenter. * * @param presenter presenter to initialize */ private void initialize(AbstractButton presenter, boolean useIcons) { if (useIcons) { // set the presenter's icon: Image icon = ImageUtilities.loadImage( "org/netbeans/modules/url/urlObject.png"); //NOI18N try { FileObject file = dataObject.getPrimaryFile(); icon = FileUIUtils.getImageDecorator(file.getFileSystem()). annotateIcon(icon, BeanInfo.ICON_COLOR_16x16, dataObject.files()); } catch (FileStateInvalidException fsie) { // OK, so we use the default icon } presenter.setIcon(new ImageIcon(icon)); } /* set the presenter's text and ensure it is maintained up-to-date: */ NameChangeListener listener = new NameChangeListener(presenter); presenter.addPropertyChangeListener( WeakListeners.propertyChange(listener, dataObject)); updateName(presenter); /* * The above code works with the assumption that it is called * from the AWT event dispatching thread (it manipulates * the presenter's display name). The same applies to * NameChangeListener's method propertyChange(...). * * At least, both mentioned parts of code should be called from * the same thread since method updateText(...) is not thread-safe. */ presenter.addActionListener(this); HelpCtx.setHelpIDString(presenter, dataObject.getHelpCtx().getHelpID()); } /** * Updates display text and tooltip of a specified presenter. * * @param presenter presenter whose name is to be updated */ private void updateName(AbstractButton presenter) { String name = dataObject.getName(); try { FileObject file = dataObject.getPrimaryFile(); name = file.getFileSystem().getDecorator().annotateName(name, dataObject.files()); } catch (FileStateInvalidException fsie) { /* OK, so we use the default name */ } Mnemonics.setLocalizedText(presenter, name); } /* implements interface ActionListener */ /** * Performs operation <em>open</em> of the <code>DataObject</code>. */ public void actionPerformed(ActionEvent evt) { Node.Cookie open = dataObject.getCookie(OpenCookie.class); if (open != null) { ((OpenCookie) open).open(); } } /** */ private class NameChangeListener implements PropertyChangeListener { /** */ private final AbstractButton presenter; /** */ NameChangeListener(AbstractButton presenter) { this.presenter = presenter; } /* Implements interface PropertyChangeListener. */ public void propertyChange(PropertyChangeEvent evt) { if (DataObject.PROP_NAME.equals(evt.getPropertyName())) { URLPresenter.this.updateName(presenter); } } } }
33.973118
94
0.64852
81ce5158ecedb3a258a1595194a304a0f92e1a70
980
package ghost.framework.web.context.servlet.filter; import javax.servlet.Filter; import javax.servlet.ServletContext; import javax.servlet.ServletException; /** * package: ghost.framework.web.context.servlet.filter * * @Author: 郭树灿{gsc-e590} * @link: 手机:13715848993, QQ 27048384 * @Description:调度过滤器接口 * @Date: 2020/4/27:23:39 */ public interface IDispatcherFilter extends Filter { /** * 获取过滤器执行链 * @return */ IFilterExecutionChain getFilterExecutionChain(); ServletContext getContext(); /** * 添加过滤器 * * @param filter * @throws ServletException */ void add(Filter filter) throws ServletException; /** * 删除过滤器 * * @param filter */ void remove(Filter filter); // void add(HttpSessionListener sessionListener); // void remove(HttpSessionListener sessionListener); // void add(ServletContextListener contextListener); // void remove(ServletContextListener contextListener); }
25.128205
58
0.687755
d360d9b8085d5f0d76c0712dd5634ff16bcc35cf
3,877
package com.github.queued.slr4v.model; import java.io.*; import java.text.DecimalFormat; import java.util.LinkedList; public class Dataset extends Matrix { public Dataset(int row, int col) { super(row, col); } public static LinkedList<Dataset> fromFile(String fileName) { File file = new File(fileName); BufferedReader br; LinkedList<Dataset> datasets = new LinkedList<Dataset>(); try { br = new BufferedReader(new FileReader(file)); String header = br.readLine(); String line; // System.out.println("Header: " + header); int header_sz = header.split(",").length; while ((line = br.readLine()) != null) { // System.out.println(line); String[] str = line.split(","); if( str.length != header_sz ) { br.close(); throw new RuntimeException(String.format("Invalid input: size of header is not match header(%s)\\{%d\\} input(%s)\\{%d\\}", header, header_sz, line, str.length)); } Dataset m = new Dataset(1, str.length); for( int i = 0 ; i < str.length ; i++) { m.setData(0, i, Double.parseDouble(str[i].trim())); } datasets.addLast(m); } // System.out.println("Number of inputs: " + datasets.size()); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return datasets; } public static Matrix getMatrix(LinkedList<Dataset> datasets) { int row = datasets.size(); int col = datasets.get(0).col; Matrix m = new Matrix(row, col); for (int i = 0 ;i < row ; i++) { Matrix mAtRow = (Matrix) datasets.get(i); for( int j = 0; j < col; j++) { m.data[i][j] = mAtRow.getData(0, j); } } return m; } @Override public void random(double min, double max) { for (int i = 0; i < this.row; i++) { for (int j = 0; j < this.col; j++) this.data[i][j] = min + Math.random() * (max - min); } } @Override public void Print() { System.out.println(this.toString()); } public static LinkedList<Double> expectedValueFromFile(String fileName) { File file = new File(fileName); BufferedReader br; LinkedList<Double> ev = new LinkedList<Double>(); try { br = new BufferedReader(new FileReader(file)); String line = br.readLine(); // System.out.println("Header: " + line); while ((line = br.readLine()) != null) { // System.out.println(line); ev.addLast(Double.parseDouble(line.trim())); } // System.out.println("Number of outputs: " + ev.size()); br.close(); } catch (IOException e) { e.printStackTrace(); } return ev; } @Override public String toString() { DecimalFormat df = new DecimalFormat("#.##"); StringBuilder strBuilder = new StringBuilder(); strBuilder.append("Matrix : ["); for (int i = 0; i < this.row; i++) { strBuilder.append("["); for (int j = 0; j < this.col; j++) { strBuilder.append(df.format(this.data[i][j])); if ((j + 1) < this.col) { strBuilder.append(","); } } if ((i + 1) < this.row) System.out.print("],"); else strBuilder.append("]"); } strBuilder.append("]\n"); return strBuilder.toString(); } }
30.527559
182
0.491101
6a369133259edd7d2b18962bf3d67a5579396ac2
4,957
package lib.trajectory; import com.gemsrobotics.lib.controls.DriveMotionPlanner; import com.gemsrobotics.lib.controls.MotionPlanner; import com.gemsrobotics.lib.math.se2.RigidTransform; import com.gemsrobotics.lib.math.se2.RigidTransformWithCurvature; import com.gemsrobotics.lib.math.se2.Rotation; import com.gemsrobotics.lib.physics.MotorModel; import com.gemsrobotics.lib.subsystems.drivetrain.ChassisState; import com.gemsrobotics.lib.subsystems.drivetrain.DifferentialDriveModel; import com.gemsrobotics.lib.subsystems.drivetrain.WheelState; import com.gemsrobotics.lib.trajectory.*; import com.gemsrobotics.lib.trajectory.parameterization.DifferentialDriveDynamicsConstraint; import com.gemsrobotics.lib.trajectory.parameterization.Parameterizer; import com.gemsrobotics.lib.trajectory.parameterization.TimedState; import com.gemsrobotics.lib.trajectory.parameterization.TrajectoryUtils; import com.gemsrobotics.lib.utils.Units; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.util.Arrays; import java.util.Collections; import java.util.List; public class TestIntegration { @Test public void testSplineTrajectoryGenerator() { // Specify desired waypoints. final List<RigidTransform> waypoints = Arrays.asList( new RigidTransform(0, 0, Rotation.identity()), new RigidTransform(4, 0, Rotation.identity())); final double peakVoltage = 12.0; final double wheelRadius = 0.08016875; final double freeSpeed = 4.8 / wheelRadius; // r/s final double kS = 0.36167; // V final double kV = 0.1329; // V / (rad / s) final double kA = 0.012; // V / (rad / s^2) final double mass = 62.73; // kg final var cfg = new MotionPlanner.MotionConfig() {{ maxDx = 0.00127; maxDy = 0.00127; maxDtheta = Rotation.degrees(5.0).getRadians(); maxVoltage = 10.0; maxVelocity = 4.8; maxAcceleration = 3.2; maxCentripetalAcceleration = 2.0; }}; // Create a trajectory from splines. Trajectory<RigidTransformWithCurvature> trajectory = TrajectoryUtils.trajectoryFromSplineWaypoints(waypoints, cfg); final var modelProps = new DifferentialDriveModel.Properties() {{ massKg = mass; // kg angularMomentInertiaKgMetersSquared = Math.pow(Units.inches2Meters(6.0), 2) * massKg; angularDragTorquePerRadiansPerSecond = 12.0; wheelRadiusMeters = wheelRadius; wheelbaseRadiusMeters = 0.351; }}; final var transmission = new MotorModel(new MotorModel.Properties() {{ speedRadiansPerSecondPerVolt = (1 / kV); torquePerVolt = wheelRadius * wheelRadius * mass / (2.0 * kA); stictionVoltage = kS; }}); final var model = new DifferentialDriveModel(modelProps, transmission, transmission); // Generate the timed trajectory. Trajectory<TimedState<RigidTransformWithCurvature>> timedTrajectory = Parameterizer.timeParameterizeTrajectory( false, new DistanceView<>(trajectory), 1.0, Collections.emptyList(), cfg, 0.0, 0.0); for (int i = 1; i < timedTrajectory.length(); ++i) { TrajectoryPoint<TimedState<RigidTransformWithCurvature>> prev = timedTrajectory.getPoint(i - 1); TrajectoryPoint<TimedState<RigidTransformWithCurvature>> next = timedTrajectory.getPoint(i); assertThat(prev.state().getAcceleration(), closeTo((next.state().getVelocity() - prev.state().getVelocity()) / (next.state().t() - prev.state().t()), 1e-6)); final double dt = next.state().t() - prev.state().t(); assertThat(next.state().getVelocity(), closeTo(prev.state().getVelocity() + prev.state().getAcceleration() * dt, 1E-6)); assertThat(next.state().distance(prev.state()), closeTo(prev.state().getVelocity() * dt + 0.5 * prev.state().getAcceleration() * dt * dt, 1E-6)); } // "Follow" the trajectory. final double dt = 0.01; TrajectoryIterator<TimedState<RigidTransformWithCurvature>> iterator = new TrajectoryIterator<>(new TimedView<>(timedTrajectory)); var sample = iterator.getSample(); do { final TimedState<RigidTransformWithCurvature> state = sample.getState(); final DifferentialDriveModel.Dynamics dynamics = model.solveInverseDynamics( new ChassisState(state.getVelocity(), state.getVelocity() * state.getState().getCurvature()), new ChassisState(state.getAcceleration(), state.getAcceleration() * state.getState().getCurvature()), false); sample = iterator.advance(dt); } while (!iterator.isDone()); } }
45.063636
169
0.666129
299680e64cc09aed5fb470bb1c02d7c53b411f92
4,898
package au.com.mountainpass.hyperstate; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Date; import javax.security.auth.x500.X500Principal; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.x509.X509V1CertificateGenerator; public class SelfSignedCertificate { static { // adds the Bouncy castle provider to java security Security.addProvider(new BouncyCastleProvider()); } private KeyPair keyPair; private X509Certificate cert; public SelfSignedCertificate(String domainName) throws Exception { this.keyPair = createKeyPair(); this.cert = createSelfSignedCertificate(keyPair, domainName); } private X509Certificate createSelfSignedCertificate(final KeyPair keyPair, final String domainName) throws Exception { // generate a key pair // see // http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation final Date startDate = new Date(); final Date expiryDate = new Date( System.currentTimeMillis() + (1000L * 60 * 60 * 24)); final BigInteger serialNumber = BigInteger .valueOf(Math.abs((long) (new SecureRandom().nextInt()))); // serial // number for // certificate final X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); final X500Principal dnName = new X500Principal("CN=" + domainName); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName); certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); final X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC"); return cert; } private KeyPair createKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException { final KeyPairGenerator keyPairGenerator = KeyPairGenerator .getInstance("RSA", "BC"); keyPairGenerator.initialize(2048, new SecureRandom()); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); return keyPair; } public X509Certificate getCertificate() { return this.cert; } public PrivateKey getPrivateKey() { return this.keyPair.getPrivate(); } static public void addCertToTrustStore(final String trustStoreFile, final String trustStorePassword, final String trustStoreType, final String keyAlias, final SelfSignedCertificate selfSignedCertificate) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { if (trustStoreFile != null) { final KeyStore ks = KeyStore.getInstance(trustStoreType); final File trustFile = new File(trustStoreFile); ks.load(null, null); ks.setCertificateEntry(keyAlias, selfSignedCertificate.getCertificate()); final FileOutputStream fos = new FileOutputStream(trustFile); ks.store(fos, trustStorePassword.toCharArray()); fos.close(); } } public static void addPrivateKeyToKeyStore(String keyStore, String keyStorePassword, String keyPassword, String keyAlias, SelfSignedCertificate selfSignedCertificate) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // load an empty key store ks.load(null, keyStorePassword.toCharArray()); // add the key ks.setKeyEntry(keyAlias, selfSignedCertificate.getPrivateKey(), keyPassword.toCharArray(), new java.security.cert.Certificate[] { selfSignedCertificate.getCertificate() }); // Write the key store to disk. File ksFile = new File(keyStore); ksFile.getParentFile().mkdirs(); final FileOutputStream fos = new FileOutputStream(ksFile); ks.store(fos, keyStorePassword.toCharArray()); fos.close(); } }
38.265625
121
0.682932
f52d5f4f16a00ce7ecd09c71f1048e08189e32b0
1,669
package com.example.reservationandlivraisonapi.entity.acteurs; import com.example.reservationandlivraisonapi.entity.buyable.Buyable; import com.example.reservationandlivraisonapi.entity.buyable.Category; import com.example.reservationandlivraisonapi.entity.commande.Reservation; import com.example.reservationandlivraisonapi.entity.reclamation.Reclamation; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import java.util.ArrayList; import java.util.Collection; @Entity @Data @NoArgsConstructor @DiscriminatorValue("REST") public class Restaurant extends EntrepriseInfo { @OneToMany(mappedBy = "restaurant") @JsonIgnore private Collection<Buyable> buyables = new ArrayList<>(); @OneToMany(mappedBy = "restaurant") @JsonIgnore private Collection<Category> categories = new ArrayList<>(); @OneToMany(mappedBy = "restaurant") @JsonIgnore private Collection<Reservation> reservations = new ArrayList<>(); public Restaurant(Integer user_id, String username, String password, String ville, String adresse, String name, String phone) { super(user_id, username, password, ville, adresse, name, phone); } public Restaurant(Integer user_id, String username, String password, String ville, String adresse, float latitude, float longitude, String name, String phone) { super(user_id, username, password, null, ville, adresse, latitude, longitude, name, phone); } }
37.931818
164
0.786099
783f46a84c76d7ba5bbf5a9875be974aa3a97bfc
246
package demo_abstractFactory; public abstract class AbstractYellowHuman implements Human { public void getColor(){ System.out.println("黄色皮肤"); } public void talk(){ System.out.println(this.getClass()+"在说话"); } }
20.5
60
0.662602
35bfcb0d6b7d048f7913a1e469d7ef37335094b3
572
package com.example.repl.tools; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; public class CompileFailureException extends RuntimeException { private static final long serialVersionUID = 1L; private Diagnostic<? extends JavaFileObject> lastErrorInfo; public CompileFailureException(String message, Diagnostic<? extends JavaFileObject> lastErrorInfo) { super(message); this.lastErrorInfo = lastErrorInfo; } public Diagnostic<? extends JavaFileObject> getLastErrorInfo() { return lastErrorInfo; } }
26
104
0.751748
be813c71d168fb7c0533ab84d762b518c92459ee
1,081
package com.goblimey.addressbook; import org.junit.Test; import java.util.Date; import static org.junit.Assert.*; /** * Basic tests for in-memory address book implementation. * Created by simon on 22/02/18. */ public class ContactInMemoryImplTest { private static final String EXPECTED_NAME = "Simon Ritchie"; private static final Gender EXPECTED_GENDER = Gender.MALE; @Test public void constructor_test() throws Exception { Contact book = new ContactInMemoryImpl(EXPECTED_NAME, EXPECTED_GENDER, new Date()); assertEquals(EXPECTED_NAME, book.getName()); assertEquals(EXPECTED_GENDER, book.getGender()); assertNotNull(book.getDOB()); } @Test public void getter_setter_test() throws Exception { Contact book = new ContactInMemoryImpl(); book.setName(EXPECTED_NAME); book.setGender(EXPECTED_GENDER); book.setDOB(new Date()); assertEquals(EXPECTED_NAME, book.getName()); assertEquals(EXPECTED_GENDER, book.getGender()); assertNotNull(book.getDOB()); } }
28.447368
91
0.694727
13988f437c691a57bf00af712936de0637cae0d0
742
package io.neow3j.protocol.jsonrpc; public class JsonRpcErrorConstants { public static final int PARSE_ERROR_CODE = -32700; public static final String PARSE_ERROR_MESSAGE = "Parse error"; public static final int INVALID_REQUEST_CODE = -32600; public static final String INVALID_REQUEST_MESSAGE = "Invalid request"; public static final int METHOD_NOT_FOUND_CODE = -32601; public static final String METHOD_NOT_FOUND_MESSAGE = "Method not found"; public static final int INVALID_PARAMS_CODE = -32602; public static final String INVALID_PARAMS_MESSAGE = "Invalid params"; public static final int INTERNAL_ERROR_CODE = -32603; public static final String INTERNAL_ERROR_MESSAGE = "Internal Error"; }
35.333333
77
0.769542
4c3d9e22a287f8d75864448be6d65e96fc8f85de
1,820
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2021 the original authors 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 io.sarl.eclipse.launching.dialog; import org.eclipse.debug.ui.ILaunchConfigurationDialog; import org.eclipse.debug.ui.ILaunchConfigurationTab; import org.eclipse.jdt.debug.ui.launchConfigurations.JavaArgumentsTab; /** * Tab group object for configuring the run of a Java application embedding SARL. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 0.7 */ public class SARLApplicationLaunchConfigurationTabGroup extends AbstractSARLLaunchConfigurationTabGroup { @Override public void createTabs(ILaunchConfigurationDialog dialog, String mode) { final ILaunchConfigurationTab[] tabs = buildTabList(dialog, mode, list -> { // Add before the dynamically provided panels final SARLApplicationMainLaunchConfigurationTab mainTab = new SARLApplicationMainLaunchConfigurationTab(); list.add(0, mainTab); list.add(1, new JavaArgumentsTab()); list.add(2, new SARLRuntimeEnvironmentTab(false)); addSreChangeListeners(list, mainTab); return true; }); setTabs(tabs); } }
32.5
109
0.757143
62e25366f0609be83d1788c82932afec4a607661
10,072
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.commonservices.generichandlers; import org.odpi.openmetadata.frameworks.connectors.ffdc.InvalidParameterException; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.InstanceProperties; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper; import java.util.Date; import java.util.Map; /** * PersonRoleBuilder creates the parts for an entity that represents a person role plus manages the properties for the * relationships. */ public class PersonRoleBuilder extends ReferenceableBuilder { private String name = null; private String description = null; private String scope = null; private int headCount = 1; private boolean headCountLimitSet = false; /** * Create constructor * * @param qualifiedName unique name for the role * @param name short display name for the role * @param description description of the role * @param scope the scope of the role * @param headCount number of individuals that can be appointed to this role * @param additionalProperties additional properties for a role * @param typeGUID unique identifier of this element's type * @param typeName unique name of this element's type * @param extendedProperties properties for a role subtype * @param repositoryHelper helper methods * @param serviceName name of this OMAS * @param serverName name of local server */ PersonRoleBuilder(String qualifiedName, String name, String description, String scope, int headCount, boolean headCountLimitSet, Map<String, String> additionalProperties, String typeGUID, String typeName, Map<String, Object> extendedProperties, OMRSRepositoryHelper repositoryHelper, String serviceName, String serverName) { super(qualifiedName, additionalProperties, typeGUID, typeName, extendedProperties, repositoryHelper, serviceName, serverName); this.name = name; this.description = description; this.scope = scope; this.headCount = headCount; this.headCountLimitSet = headCountLimitSet; } /** * Create constructor * * @param qualifiedName unique name for the role * @param name short display name for the role * @param description description of the role * @param headCount number of individuals that can be appointed to this role * @param headCountLimitSet should the head count property be set? * @param repositoryHelper helper methods * @param serviceName name of this OMAS * @param serverName name of local server */ PersonRoleBuilder(String qualifiedName, String name, String description, int headCount, boolean headCountLimitSet, OMRSRepositoryHelper repositoryHelper, String serviceName, String serverName) { super(qualifiedName, repositoryHelper, serviceName, serverName); this.name = name; this.description = description; this.headCount = headCount; this.headCountLimitSet = headCountLimitSet; } /** * Relationship constructor * * @param repositoryHelper helper methods * @param serviceName name of this OMAS * @param serverName name of local server */ PersonRoleBuilder(OMRSRepositoryHelper repositoryHelper, String serviceName, String serverName) { super(OpenMetadataAPIMapper.PERSON_ROLE_TYPE_GUID, OpenMetadataAPIMapper.PERSON_ROLE_TYPE_NAME, repositoryHelper, serviceName, serverName); } /** * Return the supplied bean properties in an InstanceProperties object. * * @param methodName name of the calling method * @return InstanceProperties object * @throws InvalidParameterException there is a problem with the properties */ @Override public InstanceProperties getInstanceProperties(String methodName) throws InvalidParameterException { InstanceProperties properties = super.getInstanceProperties(methodName); properties = repositoryHelper.addStringPropertyToInstance(serviceName, properties, OpenMetadataAPIMapper.NAME_PROPERTY_NAME, name, methodName); properties = repositoryHelper.addStringPropertyToInstance(serviceName, properties, OpenMetadataAPIMapper.DESCRIPTION_PROPERTY_NAME, description, methodName); properties = repositoryHelper.addStringPropertyToInstance(serviceName, properties, OpenMetadataAPIMapper.SCOPE_PROPERTY_NAME, scope, methodName); if (headCountLimitSet) { properties = repositoryHelper.addIntPropertyToInstance(serviceName, properties, OpenMetadataAPIMapper.HEAD_COUNT_PROPERTY_NAME, headCount, methodName); } return properties; } /** * Return the bean properties for the TeamLeadership relationship in an InstanceProperties object. * * @param position description of a special leadership position in the team eg team leader * @param methodName name of the calling method * @return InstanceProperties object */ InstanceProperties getTeamLeadershipProperties(String position, String methodName) { return repositoryHelper.addStringPropertyToInstance(serviceName, null, OpenMetadataAPIMapper.POSITION_PROPERTY_NAME, position, methodName); } /** * Return the bean properties for the TeamMembership relationship in an InstanceProperties object. * * @param position description of a special position in the team eg Milk Monitor * @param methodName name of the calling method * @return InstanceProperties object */ InstanceProperties getTeamMembershipProperties(String position, String methodName) { return repositoryHelper.addStringPropertyToInstance(serviceName, null, OpenMetadataAPIMapper.POSITION_PROPERTY_NAME, position, methodName); } /** * Return the bean properties for the PersonRoleAppointment relationship in an InstanceProperties object. * * @param isPublic is this appointment visible to others * @param effectiveFrom the official start date of the appointment - null means effective immediately * @param effectiveFrom the official end date of the appointment - null means unknown * @param methodName name of the calling method * @return InstanceProperties object */ InstanceProperties getAppointmentProperties(boolean isPublic, Date effectiveFrom, Date effectiveTo, String methodName) { InstanceProperties properties = repositoryHelper.addBooleanPropertyToInstance(serviceName, null, OpenMetadataAPIMapper.IS_PUBLIC_PROPERTY_NAME, isPublic, methodName); properties.setEffectiveFromTime(effectiveFrom); properties.setEffectiveFromTime(effectiveTo); return properties; } }
43.982533
132
0.517871
d6b8dac2ea98d3fec4cbc4bf0daad9c86e49b109
1,442
/******************************************************************************* * Copyright (c) 2000, 2012 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.internal.cocoa; public class NSURLAuthenticationChallenge extends NSObject { public NSURLAuthenticationChallenge() { super(); } public NSURLAuthenticationChallenge(long /*int*/ id) { super(id); } public NSURLAuthenticationChallenge(id id) { super(id); } public long /*int*/ previousFailureCount() { return OS.objc_msgSend(this.id, OS.sel_previousFailureCount); } public NSURLCredential proposedCredential() { long /*int*/ result = OS.objc_msgSend(this.id, OS.sel_proposedCredential); return result != 0 ? new NSURLCredential(result) : null; } public NSURLProtectionSpace protectionSpace() { long /*int*/ result = OS.objc_msgSend(this.id, OS.sel_protectionSpace); return result != 0 ? new NSURLProtectionSpace(result) : null; } public id sender() { long /*int*/ result = OS.objc_msgSend(this.id, OS.sel_sender); return result != 0 ? new id(result) : null; } }
30.680851
81
0.663662
fb411698afa49f769ef2fed3ca96d3d6540b4fac
13,615
/* * 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.commons.math4.linear; import org.apache.commons.math4.TestUtils; import org.apache.commons.math4.exception.DimensionMismatchException; import org.apache.commons.math4.exception.NullArgumentException; import org.apache.commons.math4.exception.NumberIsTooLargeException; import org.apache.commons.math4.exception.OutOfRangeException; import org.apache.commons.math4.linear.Array2DRowRealMatrix; import org.apache.commons.math4.linear.DiagonalMatrix; import org.apache.commons.math4.linear.MatrixUtils; import org.apache.commons.math4.linear.RealMatrix; import org.apache.commons.math4.linear.RealVector; import org.apache.commons.math4.linear.SingularMatrixException; import org.apache.commons.math4.util.Precision; import org.junit.Assert; import org.junit.Test; /** * Test cases for the {@link DiagonalMatrix} class. */ public class DiagonalMatrixTest { @Test public void testConstructor1() { final int dim = 3; final DiagonalMatrix m = new DiagonalMatrix(dim); Assert.assertEquals(dim, m.getRowDimension()); Assert.assertEquals(dim, m.getColumnDimension()); } @Test public void testConstructor2() { final double[] d = { -1.2, 3.4, 5 }; final DiagonalMatrix m = new DiagonalMatrix(d); for (int i = 0; i < m.getRowDimension(); i++) { for (int j = 0; j < m.getRowDimension(); j++) { if (i == j) { Assert.assertEquals(d[i], m.getEntry(i, j), 0d); } else { Assert.assertEquals(0d, m.getEntry(i, j), 0d); } } } // Check that the underlying was copied. d[0] = 0; Assert.assertFalse(d[0] == m.getEntry(0, 0)); } @Test public void testConstructor3() { final double[] d = { -1.2, 3.4, 5 }; final DiagonalMatrix m = new DiagonalMatrix(d, false); for (int i = 0; i < m.getRowDimension(); i++) { for (int j = 0; j < m.getRowDimension(); j++) { if (i == j) { Assert.assertEquals(d[i], m.getEntry(i, j), 0d); } else { Assert.assertEquals(0d, m.getEntry(i, j), 0d); } } } // Check that the underlying is referenced. d[0] = 0; Assert.assertTrue(d[0] == m.getEntry(0, 0)); } @Test(expected=DimensionMismatchException.class) public void testCreateError() { final double[] d = { -1.2, 3.4, 5 }; final DiagonalMatrix m = new DiagonalMatrix(d, false); m.createMatrix(5, 3); } @Test public void testCreate() { final double[] d = { -1.2, 3.4, 5 }; final DiagonalMatrix m = new DiagonalMatrix(d, false); final RealMatrix p = m.createMatrix(5, 5); Assert.assertTrue(p instanceof DiagonalMatrix); Assert.assertEquals(5, p.getRowDimension()); Assert.assertEquals(5, p.getColumnDimension()); } @Test public void testCopy() { final double[] d = { -1.2, 3.4, 5 }; final DiagonalMatrix m = new DiagonalMatrix(d, false); final DiagonalMatrix p = (DiagonalMatrix) m.copy(); for (int i = 0; i < m.getRowDimension(); ++i) { Assert.assertEquals(m.getEntry(i, i), p.getEntry(i, i), 1.0e-20); } } @Test public void testGetData() { final double[] data = { -1.2, 3.4, 5 }; final int dim = 3; final DiagonalMatrix m = new DiagonalMatrix(dim); for (int i = 0; i < dim; i++) { m.setEntry(i, i, data[i]); } final double[][] out = m.getData(); Assert.assertEquals(dim, out.length); for (int i = 0; i < m.getRowDimension(); i++) { Assert.assertEquals(dim, out[i].length); for (int j = 0; j < m.getRowDimension(); j++) { if (i == j) { Assert.assertEquals(data[i], out[i][j], 0d); } else { Assert.assertEquals(0d, out[i][j], 0d); } } } } @Test public void testAdd() { final double[] data1 = { -1.2, 3.4, 5 }; final DiagonalMatrix m1 = new DiagonalMatrix(data1); final double[] data2 = { 10.1, 2.3, 45 }; final DiagonalMatrix m2 = new DiagonalMatrix(data2); final DiagonalMatrix result = m1.add(m2); Assert.assertEquals(m1.getRowDimension(), result.getRowDimension()); for (int i = 0; i < result.getRowDimension(); i++) { for (int j = 0; j < result.getRowDimension(); j++) { if (i == j) { Assert.assertEquals(data1[i] + data2[i], result.getEntry(i, j), 0d); } else { Assert.assertEquals(0d, result.getEntry(i, j), 0d); } } } } @Test public void testSubtract() { final double[] data1 = { -1.2, 3.4, 5 }; final DiagonalMatrix m1 = new DiagonalMatrix(data1); final double[] data2 = { 10.1, 2.3, 45 }; final DiagonalMatrix m2 = new DiagonalMatrix(data2); final DiagonalMatrix result = m1.subtract(m2); Assert.assertEquals(m1.getRowDimension(), result.getRowDimension()); for (int i = 0; i < result.getRowDimension(); i++) { for (int j = 0; j < result.getRowDimension(); j++) { if (i == j) { Assert.assertEquals(data1[i] - data2[i], result.getEntry(i, j), 0d); } else { Assert.assertEquals(0d, result.getEntry(i, j), 0d); } } } } @Test public void testAddToEntry() { final double[] data = { -1.2, 3.4, 5 }; final DiagonalMatrix m = new DiagonalMatrix(data); for (int i = 0; i < m.getRowDimension(); i++) { m.addToEntry(i, i, i); Assert.assertEquals(data[i] + i, m.getEntry(i, i), 0d); } } @Test public void testMultiplyEntry() { final double[] data = { -1.2, 3.4, 5 }; final DiagonalMatrix m = new DiagonalMatrix(data); for (int i = 0; i < m.getRowDimension(); i++) { m.multiplyEntry(i, i, i); Assert.assertEquals(data[i] * i, m.getEntry(i, i), 0d); } } @Test public void testMultiply1() { final double[] data1 = { -1.2, 3.4, 5 }; final DiagonalMatrix m1 = new DiagonalMatrix(data1); final double[] data2 = { 10.1, 2.3, 45 }; final DiagonalMatrix m2 = new DiagonalMatrix(data2); final DiagonalMatrix result = (DiagonalMatrix) m1.multiply((RealMatrix) m2); Assert.assertEquals(m1.getRowDimension(), result.getRowDimension()); for (int i = 0; i < result.getRowDimension(); i++) { for (int j = 0; j < result.getRowDimension(); j++) { if (i == j) { Assert.assertEquals(data1[i] * data2[i], result.getEntry(i, j), 0d); } else { Assert.assertEquals(0d, result.getEntry(i, j), 0d); } } } } @Test public void testMultiply2() { final double[] data1 = { -1.2, 3.4, 5 }; final DiagonalMatrix diag1 = new DiagonalMatrix(data1); final double[][] data2 = { { -1.2, 3.4 }, { -5.6, 7.8 }, { 9.1, 2.3 } }; final RealMatrix dense2 = new Array2DRowRealMatrix(data2); final RealMatrix dense1 = new Array2DRowRealMatrix(diag1.getData()); final RealMatrix diagResult = diag1.multiply(dense2); final RealMatrix denseResult = dense1.multiply(dense2); for (int i = 0; i < dense1.getRowDimension(); i++) { for (int j = 0; j < dense2.getColumnDimension(); j++) { Assert.assertEquals(denseResult.getEntry(i, j), diagResult.getEntry(i, j), 0d); } } } @Test public void testOperate() { final double[] data = { -1.2, 3.4, 5 }; final DiagonalMatrix diag = new DiagonalMatrix(data); final RealMatrix dense = new Array2DRowRealMatrix(diag.getData()); final double[] v = { 6.7, 890.1, 23.4 }; final double[] diagResult = diag.operate(v); final double[] denseResult = dense.operate(v); TestUtils.assertEquals(diagResult, denseResult, 0d); } @Test public void testPreMultiply() { final double[] data = { -1.2, 3.4, 5 }; final DiagonalMatrix diag = new DiagonalMatrix(data); final RealMatrix dense = new Array2DRowRealMatrix(diag.getData()); final double[] v = { 6.7, 890.1, 23.4 }; final double[] diagResult = diag.preMultiply(v); final double[] denseResult = dense.preMultiply(v); TestUtils.assertEquals(diagResult, denseResult, 0d); } @Test public void testPreMultiplyVector() { final double[] data = { -1.2, 3.4, 5 }; final DiagonalMatrix diag = new DiagonalMatrix(data); final RealMatrix dense = new Array2DRowRealMatrix(diag.getData()); final double[] v = { 6.7, 890.1, 23.4 }; final RealVector vector = MatrixUtils.createRealVector(v); final RealVector diagResult = diag.preMultiply(vector); final RealVector denseResult = dense.preMultiply(vector); TestUtils.assertEquals("preMultiply(Vector) returns wrong result", diagResult, denseResult, 0d); } @Test(expected=NumberIsTooLargeException.class) public void testSetNonDiagonalEntry() { final DiagonalMatrix diag = new DiagonalMatrix(3); diag.setEntry(1, 2, 3.4); } @Test public void testSetNonDiagonalZero() { final DiagonalMatrix diag = new DiagonalMatrix(3); diag.setEntry(1, 2, 0.0); Assert.assertEquals(0.0, diag.getEntry(1, 2), Precision.SAFE_MIN); } @Test(expected=NumberIsTooLargeException.class) public void testAddNonDiagonalEntry() { final DiagonalMatrix diag = new DiagonalMatrix(3); diag.addToEntry(1, 2, 3.4); } @Test public void testAddNonDiagonalZero() { final DiagonalMatrix diag = new DiagonalMatrix(3); diag.addToEntry(1, 2, 0.0); Assert.assertEquals(0.0, diag.getEntry(1, 2), Precision.SAFE_MIN); } @Test public void testMultiplyNonDiagonalEntry() { final DiagonalMatrix diag = new DiagonalMatrix(3); diag.multiplyEntry(1, 2, 3.4); Assert.assertEquals(0.0, diag.getEntry(1, 2), Precision.SAFE_MIN); } @Test public void testMultiplyNonDiagonalZero() { final DiagonalMatrix diag = new DiagonalMatrix(3); diag.multiplyEntry(1, 2, 0.0); Assert.assertEquals(0.0, diag.getEntry(1, 2), Precision.SAFE_MIN); } @Test(expected=OutOfRangeException.class) public void testSetEntryOutOfRange() { final DiagonalMatrix diag = new DiagonalMatrix(3); diag.setEntry(3, 3, 3.4); } @Test(expected=NullArgumentException.class) public void testNull() { new DiagonalMatrix(null, false); } @Test(expected=NumberIsTooLargeException.class) public void testSetSubMatrixError() { final double[] data = { -1.2, 3.4, 5 }; final DiagonalMatrix diag = new DiagonalMatrix(data); diag.setSubMatrix(new double[][] { {1.0, 1.0}, {1.0, 1.0}}, 1, 1); } @Test public void testSetSubMatrix() { final double[] data = { -1.2, 3.4, 5 }; final DiagonalMatrix diag = new DiagonalMatrix(data); diag.setSubMatrix(new double[][] { {0.0, 5.0, 0.0}, {0.0, 0.0, 6.0}}, 1, 0); Assert.assertEquals(-1.2, diag.getEntry(0, 0), 1.0e-20); Assert.assertEquals( 5.0, diag.getEntry(1, 1), 1.0e-20); Assert.assertEquals( 6.0, diag.getEntry(2, 2), 1.0e-20); } @Test(expected=SingularMatrixException.class) public void testInverseError() { final double[] data = { 1, 2, 0 }; final DiagonalMatrix diag = new DiagonalMatrix(data); diag.inverse(); } @Test(expected=SingularMatrixException.class) public void testInverseError2() { final double[] data = { 1, 2, 1e-6 }; final DiagonalMatrix diag = new DiagonalMatrix(data); diag.inverse(1e-5); } @Test public void testInverse() { final double[] data = { 1, 2, 3 }; final DiagonalMatrix m = new DiagonalMatrix(data); final DiagonalMatrix inverse = m.inverse(); final DiagonalMatrix result = m.multiply(inverse); TestUtils.assertEquals("DiagonalMatrix.inverse() returns wrong result", MatrixUtils.createRealIdentityMatrix(data.length), result, Math.ulp(1d)); } }
36.306667
104
0.585898
85836941e85a0f300207d54eadebb502c0e786aa
65
package mrs.domain.model; public enum RoleName { ADMIN, USER }
10.833333
25
0.738462
3509c1db2145ff6cbb08614dda9a0cfdbc817234
11,167
/******************************************************************************* * Copyright (c) 2004, 2010 IBM Corporation. * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.a11y.utils.accprobe.accservice.core.win32.ia2; import org.a11y.utils.accprobe.accservice.core.win32.msaa.Msaa; import org.a11y.utils.accprobe.accservice.core.win32.msaa.MsaaAccessibilityEventService; import org.a11y.utils.accprobe.accservice.core.win32.msaa.MsaaAccessible; import org.a11y.utils.accprobe.accservice.core.win32.msaa.MsaaWindowService; import org.a11y.utils.accprobe.accservice.AccessibilityServiceException; import org.a11y.utils.accprobe.accservice.AccessibilityServiceManager; import org.a11y.utils.accprobe.accservice.IWindowService; import org.a11y.utils.accprobe.accservice.core.IAccessibleElement; import org.a11y.utils.accprobe.accservice.event.AccessibilityModelEvent; import org.a11y.utils.accprobe.core.model.InvalidComponentException; import org.a11y.utils.accprobe.core.model.events.ModelEventType; public class IA2AccessibilityEventService extends MsaaAccessibilityEventService { private static final long serialVersionUID = 4370682108473838982L; public static final int IA2_EVENT_ACTION_CHANGED = 0x101; public static final int IA2_EVENT_ACTIVE_DECENDENT_CHANGED = IA2_EVENT_ACTION_CHANGED + 1; public static final int IA2_EVENT_ACTIVE_DESCENDENT_CHANGED = IA2_EVENT_ACTIVE_DECENDENT_CHANGED; public static final int IA2_EVENT_DOCUMENT_ATTRIBUTE_CHANGED = IA2_EVENT_ACTIVE_DECENDENT_CHANGED + 1; public static final int IA2_EVENT_DOCUMENT_CONTENT_CHANGED = IA2_EVENT_DOCUMENT_ATTRIBUTE_CHANGED + 1; public static final int IA2_EVENT_DOCUMENT_LOAD_COMPLETE = IA2_EVENT_DOCUMENT_CONTENT_CHANGED + 1; public static final int IA2_EVENT_DOCUMENT_LOAD_STOPPED = IA2_EVENT_DOCUMENT_LOAD_COMPLETE + 1; public static final int IA2_EVENT_DOCUMENT_RELOAD = IA2_EVENT_DOCUMENT_LOAD_STOPPED + 1; public static final int IA2_EVENT_HYPERLINK_END_INDEX_CHANGED = IA2_EVENT_DOCUMENT_RELOAD + 1; public static final int IA2_EVENT_HYPERLINK_NUMBER_OF_ANCHORS_CHANGED = IA2_EVENT_HYPERLINK_END_INDEX_CHANGED + 1; public static final int IA2_EVENT_HYPERLINK_SELECTED_LINK_CHANGED = IA2_EVENT_HYPERLINK_NUMBER_OF_ANCHORS_CHANGED + 1; public static final int IA2_EVENT_HYPERTEXT_LINK_ACTIVATED = IA2_EVENT_HYPERLINK_SELECTED_LINK_CHANGED + 1; public static final int IA2_EVENT_HYPERTEXT_LINK_SELECTED = IA2_EVENT_HYPERTEXT_LINK_ACTIVATED + 1; public static final int IA2_EVENT_HYPERLINK_START_INDEX_CHANGED = IA2_EVENT_HYPERTEXT_LINK_SELECTED + 1; public static final int IA2_EVENT_HYPERTEXT_CHANGED = IA2_EVENT_HYPERLINK_START_INDEX_CHANGED + 1; public static final int IA2_EVENT_HYPERTEXT_NLINKS_CHANGED = IA2_EVENT_HYPERTEXT_CHANGED + 1; public static final int IA2_EVENT_OBJECT_ATTRIBUTE_CHANGED = IA2_EVENT_HYPERTEXT_NLINKS_CHANGED + 1; public static final int IA2_EVENT_PAGE_CHANGED = IA2_EVENT_OBJECT_ATTRIBUTE_CHANGED + 1; public static final int IA2_EVENT_ROLE_CHANGED = IA2_EVENT_PAGE_CHANGED + 1; public static final int IA2_EVENT_TABLE_CAPTION_CHANGED = IA2_EVENT_ROLE_CHANGED + 1; public static final int IA2_EVENT_TABLE_COLUMN_DESCRIPTION_CHANGED = IA2_EVENT_TABLE_CAPTION_CHANGED + 1; public static final int IA2_EVENT_TABLE_COLUMN_HEADER_CHANGED = IA2_EVENT_TABLE_COLUMN_DESCRIPTION_CHANGED + 1; public static final int IA2_EVENT_TABLE_MODEL_CHANGED = IA2_EVENT_TABLE_COLUMN_HEADER_CHANGED + 1; public static final int IA2_EVENT_TABLE_ROW_DESCRIPTION_CHANGED = IA2_EVENT_TABLE_MODEL_CHANGED + 1; public static final int IA2_EVENT_TABLE_ROW_HEADER_CHANGED = IA2_EVENT_TABLE_ROW_DESCRIPTION_CHANGED + 1; public static final int IA2_EVENT_TABLE_SUMMARY_CHANGED = IA2_EVENT_TABLE_ROW_HEADER_CHANGED + 1; public static final int IA2_EVENT_TEXT_ATTRIBUTE_CHANGED = IA2_EVENT_TABLE_SUMMARY_CHANGED + 1; public static final int IA2_EVENT_TEXT_CARET_MOVED = IA2_EVENT_TEXT_ATTRIBUTE_CHANGED + 1; public static final int IA2_EVENT_TEXT_CHANGED = IA2_EVENT_TEXT_CARET_MOVED + 1; public static final int IA2_EVENT_TEXT_COLUMN_CHANGED = IA2_EVENT_TEXT_CHANGED + 1; public static final int IA2_EVENT_TEXT_INSERTED = IA2_EVENT_TEXT_COLUMN_CHANGED + 1; public static final int IA2_EVENT_TEXT_REMOVED = IA2_EVENT_TEXT_INSERTED + 1; public static final int IA2_EVENT_TEXT_UPDATED = IA2_EVENT_TEXT_REMOVED + 1; public static final int IA2_EVENT_TEXT_SELECTION_CHANGED = IA2_EVENT_TEXT_UPDATED + 1; public static final int IA2_EVENT_VISIBLE_DATA_CHANGED = IA2_EVENT_TEXT_SELECTION_CHANGED + 1; private static final int INCONTEXT_PROPS_LENGTH = 6; public IA2AccessibilityEventService (IWindowService windowService) { super(windowService); } /** * callback from the native Windows system for out-of-process IA2 events. The parameters are: * * <p><ul> * <li>event information (hwnd, child Id, Object ID, event ID)to form a new <code>IA2Accessible</code>. * In this case, the source of the resulting event will be this <code>IA2Accessible</code> object. * </ul></p> * * <p>The appropriate listeners for the given event id are notified and the <code>AccesibilityModelEvent</code> is * created from the formed <code>IA2Accessible</code> </p> * * @param eventId * @param hwnd * @param idObject * @param idChild * @param time */ protected static void winEventCallback(int eventId, int hwnd, int idObject, int idChild, long threadId, long time, int isGlobal) { if(initClockTicks > time){ setTimeDiff(); } long dms =System.currentTimeMillis(); long ctime = time+ timeDiff; AccessibilityModelEvent accEvent = null; IAccessibleElement acc = null; int ref = createAccessibleObjectFromEvent(hwnd,idObject,idChild); if (ref!=0) { acc = new IA2Accessible(ref); } else { ref = MsaaAccessibilityEventService.createAccessibleObjectFromEvent(hwnd,idObject,idChild); if (ref!=0) { acc = new MsaaAccessible(ref); } } if (acc != null) { String evName = eventName(eventId); if(eventId == EVENT_OBJECT_FOCUS){ ((MsaaAccessible)acc).setHowFound("Focus Event; hwnd="+Integer.toHexString(hwnd).toUpperCase()); } accEvent = new AccessibilityModelEvent(acc); accEvent.setEventType(evName); accEvent.setTimeMillis(ctime); String windowClass = MsaaWindowService.getWindowClass(hwnd); String miscData= "hwnd="+ Integer.toHexString(hwnd).toUpperCase()+ " ;objectId="+idObject+ "; childId="+ idChild+ "; threadId="+ threadId + "; windowClass=" + windowClass+ "; "; accEvent.setMiscData(miscData); if(evName.startsWith("IA2_EVENT_TEXT")){ if (acc instanceof IA2Accessible) { IA2Accessible ia2Acc = (IA2Accessible) acc; try { IA2AccessibleText accText = (IA2AccessibleText) ia2Acc.getAccessibleText(); if(accText!=null){ StringBuffer sb = new StringBuffer(); long offset = accText.getCaretOffset(); if(offset>=0){ sb.append("Caret Offset="+offset+ "; "); } IA2TextSegment oldText = accText.getOldText(); if(oldText!=null && evName.equals("IA2_EVENT_TEXT_REMOVED")){ sb.append("oldText="+ oldText.getText()+ "; "); } IA2TextSegment newText = accText.getNewText(); if(newText!=null && evName.equals("IA2_EVENT_TEXT_INSERTED")){ sb.append("newText="+ newText.getText()+ "; "); } if(evName.equals("IA2_EVENT_TEXT_SELECTION_CHANGED")){ String sel = accText.getSelection(0); String text = accText.getText(); long start =text.indexOf(sel, 0); sb.append("SelStart=" + start); sb.append(" ;SelEnd=" + (start+sel.length())); } miscData = miscData + sb.toString(); } } catch (InvalidComponentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } accEvent.setMiscData(miscData); try { IWindowService winService = AccessibilityServiceManager.getInstance() .getAccessibilityService(IA2AccessibilityService.IA2_ACCSERVICE_NAME).getWindowService(); int pid; if(isGlobal==0){ pid = hwnd!=0 ? winService.getProcessId(hwnd): winService.getProcessId(winService.getActiveWindow()); }else{ pid =0; } fireAccessibilityModelEvent(accEvent, eventId, pid , false); } catch (AccessibilityServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected static native int createAccessibleObjectFromEvent(int hwnd, int idObject, int idChild); public static String eventName(int event){ String evName = null; IA2GuiModel iarch = new IA2GuiModel(); ModelEventType itype= iarch.getModelEventType(Integer.valueOf(event)); if(itype!=null){ evName = itype.getEventName(); } return evName; } /** * callback from the native Windows system for in-process IA2 events. * The event information is read from a memory map file as a string array. * * <p>The appropriate listeners for the given event id are notified and the <code>AccesibilityModelEvent</code> is * created. Here, the source of the AccesibilityModelEvent is a string array containing information about the * accessible that fired the event</p> */ protected void winEventIPCallback () { int mPtr = openFileMapping(FILE_MAP_READ|FILE_MAP_WRITE, false, fileMappingObjName); int state =0; int eventId =0; long timeMillis =0; String[] source=null; if(mPtr != 0) { int vPtr = mapViewOfFile(mPtr, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0); if(vPtr != 0) { String props[] = readFromMem(vPtr); if(props!=null && props.length==INCONTEXT_PROPS_LENGTH){ String roleName =null; try { long role = Long.parseLong(props[1]); roleName= Msaa.getMsaaA11yRoleName(role); if(roleName==null){ roleName= IA2.getIA2A11yRoleName(role); } } catch (NumberFormatException e) { // role returned as a string roleName= props[1]; } state= Integer.parseInt(props[2]); eventId = Integer.parseInt(props[3]); timeMillis = Long.parseLong(props[4]); if(initClockTicks > timeMillis){ setTimeDiff(); } timeMillis = timeMillis+timeDiff; source = new String[INCONTEXT_PROPS_LENGTH]; source[0]=props[0]; source[1]= roleName; source[2]= Msaa.getState(state).toString(); source[3]= eventName(eventId); source[4]= Long.valueOf(timeMillis).toString(); source[5]= props[5]; } unmapViewOfFile(vPtr); } closeHandle(mPtr); } //handle data AccessibilityModelEvent accEvent = null; if (source!=null){ try { accEvent = new AccessibilityModelEvent(source); fireAccessibilityModelEvent(accEvent, eventId, windowService.getProcessId(windowService.getActiveWindow()), true); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //protected native int internalSetWinEventHook (int eventMin, int eventMax, int idThread, int idProcess, int dwFlags); //public native boolean initThread(); }
44.313492
120
0.739053
e500f9054761a1ffe6d2975f1c3ec5eb28747362
365
package com.microsoft.bingads.v11.api.test.entities.criterions.campaign.daytime; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ BulkCampaignDayTimeCriterionReadTests.class, BulkCampaignDayTimeCriterionWriteTests.class, }) public class BulkCampaignDayTimeCriterionTests { }
28.076923
81
0.780822
cb68ba2649db46ea762e23cd0a3270ef2eb58be7
1,225
package de.uhd.ifi.se.quizapp.tests.labelimageexercise.labelimagedatamanager; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.junit.Ignore; import org.junit.Test; import de.uhd.ifi.se.quizapp.model.Student; import de.uhd.ifi.se.quizapp.model.labelimageexercise.LabelImageResult; public class TestGetResultByStudent extends LabelImageDataTestingSuper { @Test public void testGetResultByStudentNull() throws ClassNotFoundException, SQLException { assertEquals(new ArrayList<>(), this.dataManager.getResultByStudent(null)); } @Test public void testGetResultByStudentNotInDatabase() throws ClassNotFoundException, SQLException { Student student = new Student(); List<LabelImageResult> results = this.dataManager.getResultByStudent(student); assertEquals(0, results.size(), 0); } @Test @Ignore public void testGetResultByStudentInDatabase() throws ClassNotFoundException, SQLException { Student student = this.dataManager.getStudent("t"); List<LabelImageResult> results = this.dataManager.getResultByStudent(student); assertNotEquals(0, results.size(), 0); } }
32.236842
96
0.805714
ab0f6407e6e5f1e1ab061ad51f04c7a4f47bf11c
3,281
package io.deki.dsdn; import io.deki.dsdn.util.ProcessUtil; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; /** * @author Deki on 18.06.2021 * @project dsdn **/ public class Compiler { /** * Compiles the source code of an entire directory using the javac command line tool. * * @param dir Directory of source code to compile * @param output Directory where compiled .class files will be saved * @param libraries List of libraries to add to classpath when compiling * @return Returns whether or not the operation was successful */ public static boolean compile(File dir, File output, File... libraries) { cleanDirectory(output); output.mkdirs(); StringBuilder classpath = new StringBuilder(); for (File library : libraries) { classpath.append(library).append(";"); } File indexFile = new File(dir + "-index"); indexSourceFiles(dir, indexFile); String command = String.format("javac @%s -d %s", indexFile, output); if (classpath.length() > 0) { command += " -cp " + classpath; } int exitCode = ProcessUtil.execute(command); indexFile.delete(); return exitCode == 0; } /** * Packages class files in a directory to a jar file. * * @param dir Directory of class files to package * @param output File to package classes to * @return Returns whether or not the operation was successful */ public static boolean createJar(File dir, File output) { if (output.exists()) { output.delete(); } //use the -C argument to make sure the directory structure inside the jar file is //the same as source package structure int exitCode = ProcessUtil.execute(String.format("jar cf %s -C %s .", output, dir, dir)); return exitCode == 0; } /** * Traverses a directory and saves the full path of every .java file it finds. The paths are saved * to a file that we can pass to javac later to compile the source code of the whole directory. * * @param dir Directory to traverse * @param output File to which the paths will be saved. If the file already exists it will be * overwritten. */ private static void indexSourceFiles(File dir, File output) { try { if (output.exists()) { output.delete(); } output.createNewFile(); StringBuilder builder = new StringBuilder(); List<String> files = Files.walk(dir.toPath()).map(Path::toString) .filter(file -> file.endsWith(".java")).collect(Collectors.toList()); files.forEach(file -> builder.append(file).append(" ")); Files.write(output.toPath(), builder.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } /** * Fully deletes a directory, if it exists. * * @param dir Directory to delete */ private static void cleanDirectory(File dir) { if (dir.exists()) { if (!dir.isDirectory()) { dir.delete(); } else { try { FileUtils.deleteDirectory(dir); } catch (IOException e) { e.printStackTrace(); } } } } }
31.247619
100
0.64584
59cca8d8ac8da83730e433736915aea295c8bdbd
1,559
package util.study.collection.generictest; /** * @version: java version 1.7+ * @Author : mzp * @Time : 2019/7/9 11:40 * @File : GenericClassTest * @Software: IntelliJ IDEA 2019.3.15 */ import java.util.List; /** * 定义一个泛型类 * @Author maozp3 * @Description: * @Date: 2019/7/9 11:40 */ public class GenericClassTest<T> { /** 一。 * 这个不是泛型方法,只是使用了泛型类中已声明的T */ public void test1(T t, List list){ System.out.println(t.toString()); } /** 二、 * 声明泛型方法:是在方法的返回值前面加上<T> (字母可以任意写,可是A、B、C....等)。 在返回值前面声明类型,在入参传参时确定具体类型。 * 泛型方法,使用泛型E,这种泛型E可以为任意类型。可以类型与T相同,也可以不同。 * 由于下面的泛型方法在声明的时候声明了泛型<E>,因此即使在泛型类中并未声明泛型, * 编译器也能够正确识别泛型方法中识别的泛型。 */ public <E> void test2(E e){ System.out.println(e.toString()); } /** 三、 * 在返回值前面加了个 <M> ,表示可以声明一个 M类型的泛型。 和类名上面的<T>的作用是一样的(允许声明一个T类型的泛型)。在返回值前面声明类型,在入参传参时确定具体类型。 * 在泛型类中声明了一个泛型方法,使用泛型M,注意这个M是一种全新的类型; * 可以与泛型类中声明的T不是同一种类型。 * 意义:传入M类型的参数,这里的返回值也是M类型 */ public <M> M test3(M t){ System.out.println(t.toString()); return t; } /** 四 * 声明带返回类型的泛型。这里T的具体类型就是这个类声明的时候,用的类型了。 * 比如: GenericClassTest<String> gc = new GenericClassTest<>(); (注:这里如果不指定类型,那么T默认是Object类型) * 那么这个T就是 String类型了。 gc.getValue(参数), 这个参数也是String类型,当然返回值也是String * @param value * @return */ public T getValue(T value){ return value; } }
25.983333
100
0.561257
05e8b941c2a3fe8d9dcf91117e21f28ccc611c39
2,169
/* * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com. * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jaspersoft.jasperserver.war.dto; import java.util.Set; import java.util.List; import com.jaspersoft.jasperserver.api.metadata.user.domain.Role; /** * @author Ionut Nedelcu (ionutned@users.sourceforge.net) * @version $Id */ public class RoleWrapper extends BaseDTO { private Role role; private List usersNotInRole; private List usersInRole; private Object selectedUsersNotInRole; private Object selectedUsersInRole; public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public List getUsersNotInRole() { return usersNotInRole; } public void setUsersNotInRole(List usersNotInRole) { this.usersNotInRole = usersNotInRole; } public List getUsersInRole() { return usersInRole; } public void setUsersInRole(List usersInRole) { this.usersInRole = usersInRole; } public Object getSelectedUsersInRole() { return selectedUsersInRole; } public void setSelectedUsersInRole(Object selectedUsersInRole) { this.selectedUsersInRole = selectedUsersInRole; } public Object getSelectedUsersNotInRole() { return selectedUsersNotInRole; } public void setSelectedUsersNotInRole(Object selectedUsersNotInRole) { this.selectedUsersNotInRole = selectedUsersNotInRole; } }
23.835165
77
0.757492
13db17a1841b18944ad2bbb95025a2a27a2a9d98
1,164
// pr 44587 import org.aspectj.testing.Tester; import org.aspectj.lang.NoAspectBoundException; public class ErroneousExceptionConversion { public static void main(String[] args) { try { new ErroneousExceptionConversion(); Tester.checkFailed("Wanted an exception in initializer error"); } catch (NoAspectBoundException nabEx) { // good // check nabEx.getCause instanceof RuntimeException and has explanation "boom..." Throwable cause = nabEx.getCause(); if (!(cause instanceof RuntimeException)) { Tester.checkFailed("Should have a RuntimeException as cause"); } } catch(Throwable t) { Tester.checkFailed("Wanted an ExceptionInInitializerError but got " + t); } } } aspect A { int ErroneousExceptionConversion.someField = throwIt(); public static int throwIt() { throw new RuntimeException("Exception during aspect initialization"); } public A() { System.err.println("boom in 5..."); throw new RuntimeException("boom"); } // if I change this to execution the test passes... after() throwing : initialization(ErroneousExceptionConversion.new(..)) { System.out.println("After throwing"); } }
25.866667
84
0.718213
635234c63cedbf3570a9e03786e68a9d06ec12c4
104
package generics.studyGenInterface; public interface GenInterfaceOne<T> { void display(T value); }
17.333333
37
0.769231
29085b4dd9f9b00afb7bd2c108590bb95aebea65
18,970
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.viz.aviation.climatology; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; /** * TrendWindSpdCanvasComp class draws the slider information on the wind speed * canvas and handles the user inputs. * * <pre> * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 28 FEB 2008 938 lvenable Initial creation. * 12 Aug 2013 #2256 lvenable Moved calcArrow() to parent abstract class * * </pre> * * @author lvenable * @version 1.0 * */ public class TrendWindSpdCanvasComp extends TrendSliderComp implements MouseMoveListener, MouseListener { /** * Parent composite. */ private Composite parent; /** * Mouse is down flag. */ private boolean mouseDown = false; /** * Move arrow flag. */ private boolean moveArrow = false; /** * Move the left side of the range flag. */ private boolean moveBarLeftSide = false; /** * Move the right side of the range flag. */ private boolean moveBarRightSide = false; /** * Move the arrow and range flag. */ private boolean moveAll = false; /** * X coordinate of the 0 value. */ private int xCoord0 = hLineStartXCoord; /** * X coordinate of the 4 value. */ private int xCoord4 = xCoord0 + 50; /** * X coordinate of the 10 value. */ private int xCoord10 = xCoord4 + 70; /** * X coordinate of the 30 value. */ private int xCoord30 = xCoord10 + 130; /** * X coordinate of the 31+ value. */ private int xCoord31Plus = hLineEndXCoord; /** * X coordinate difference between 31+ and 30. */ private int xCoord30_31Diff = ((xCoord31Plus - xCoord30) / 2) + xCoord30; /** * Value to pixel factor from 0 to 4. */ private double factor0to4 = 4.0 / (xCoord4 - xCoord0); /** * Value to pixel factor from 4 to 10. */ private double factor4to10 = 6.0 / (xCoord10 - xCoord4); /** * Value to pixel factor from 10 to 30. */ private double factor10to30 = 20.0 / (xCoord30 - xCoord10); /** * Constructor. * * @param parent * Parent composite. */ public TrendWindSpdCanvasComp(Composite parent) { super(parent, "Wind Speed"); this.parent = parent; init(); } /** * Initialize method. */ private void init() { arrowCenterXCoord = 150; barWidth = 100; barRect = new Rectangle(xCoord4, hLineYcoord + 3, barWidth, 15); barRightXCoord = barWidth + barRect.x; moveAll(150); drawingCanvas.addMouseListener(this); drawingCanvas.addMouseMoveListener(this); validateValueListeners(); validateRangeListeners(); } /** * Draw the dial information on the wind speed canvas. * * @param gc * Graphical context. */ @Override public void drawCanvas(GC gc) { int fontHeight = gc.getFontMetrics().getHeight(); int fontWidth = gc.getFontMetrics().getAverageCharWidth(); // --------------------------------------- // Draw the background color. // --------------------------------------- gc.setBackground(parent.getDisplay().getSystemColor( SWT.COLOR_WIDGET_BACKGROUND)); gc.fillRectangle(0, 0, canvasWidth + 5, canvasHeight + 5); // ------------------------------------------- // Draw the horizontal line and hash marks // ------------------------------------------- gc.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_BLACK)); // Draw horizontal line. gc.drawLine(hLineStartXCoord, hLineYcoord, hLineEndXCoord, hLineYcoord); // Draw hash marks. gc.drawLine(xCoord0, hLineYcoord, xCoord0, hLineYcoord - dashLine); gc.drawLine(xCoord4, hLineYcoord, xCoord4, hLineYcoord - dashLine); gc.drawLine(xCoord10, hLineYcoord, xCoord10, hLineYcoord - dashLine); gc.drawLine(xCoord30, hLineYcoord, xCoord30, hLineYcoord - dashLine); gc.drawLine(xCoord31Plus, hLineYcoord, xCoord31Plus, hLineYcoord - dashLine); // --------------------------------------------- // Draw the labels // --------------------------------------------- gc.drawString("0", xCoord0 - fontWidth / 2, hLineYcoord - dashLine - 3 - fontHeight, true); gc.drawString("4", xCoord4 - fontWidth / 2, hLineYcoord - dashLine - 3 - fontHeight, true); gc.drawString("10", xCoord10 - fontWidth, hLineYcoord - dashLine - 3 - fontHeight, true); gc.drawString("30", xCoord30 - fontWidth, hLineYcoord - dashLine - 3 - fontHeight, true); gc.drawString("31+", xCoord31Plus - (fontWidth * 3) / 2 - 2, hLineYcoord - dashLine - 3 - fontHeight, true); // ------------------------------------------------- // Draw the range rectangle and blue arrow marker // ------------------------------------------------- // Draw blue arrow. gc.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_BLUE)); calcArrow(); gc.fillPolygon(arrowPoints); // Draw red rectangle range. gc.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_RED)); gc.setAlpha(80); gc.fillRectangle(barRect); gc.setAlpha(255); gc.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_RED)); gc.setLineWidth(2); gc.drawRectangle(barRect); } /** * Not Implemented... */ @Override public void mouseDoubleClick(MouseEvent e) { } /** * Called when a mouse button is pressed. * * @param e * Mouse event. */ @Override public void mouseDown(MouseEvent e) { if (region.contains(e.x, e.y)) { if (e.button == 2) { moveAll = true; mouseDown = true; } else if (e.button == 1) { mouseDown = true; moveArrow = true; } return; } if (barRect.contains(e.x, e.y)) { if (e.x <= barRect.x + 2) { moveBarLeftSide = true; mouseDown = true; } else if (e.x >= barRightXCoord - 2) { moveBarRightSide = true; mouseDown = true; } } } /** * Called when a mouse button is released. * * @param e * Mouse event. */ @Override public void mouseUp(MouseEvent e) { mouseDown = false; moveArrow = false; moveBarLeftSide = false; moveBarRightSide = false; moveAll = false; } /** * Called when the mouse is moved over the control. * * @param e * Mouse event. */ @Override public void mouseMove(MouseEvent e) { if (mouseDown == false) { return; } if (moveArrow == true) { moveArrow(e.x); } else if (moveBarLeftSide == true) { moveLeftSideOfRange(e.x); } else if (moveBarRightSide == true) { moveRightSideOfRange(e.x); } else if (moveAll == true) { if (e.x <= hLineStartXCoord || e.x >= hLineEndXCoord) { return; } moveAll(e.x); } drawingCanvas.redraw(); } /** * Move the arrow. * * @param xCoord * X coordinate to move to. */ private void moveArrow(int xCoord) { arrowCenterXCoord = calcNewXCoord(xCoord); Double val = calcXCoordToValue(arrowCenterXCoord); setValueText(val); } /** * Move the starting range (left side of bar). * * @param xCoord * X coordinate to move to. */ private void moveLeftSideOfRange(int xCoord) { int newXCoord = calcNewXCoord(xCoord); if (newXCoord >= barRightXCoord) { return; } barRect.width = barRightXCoord - newXCoord; barRect.x = newXCoord; Double startVal = calcXCoordToValue(barRect.x); Double endVal = calcXCoordToValue(barRightXCoord); setRangeText(startVal, endVal); } /** * Move the ending range (right side of bar). * * @param xCoord * X coordinate to move to. */ private void moveRightSideOfRange(int xCoord) { int newXCoord = calcNewXCoord(xCoord); if (newXCoord <= barRect.x) { return; } barRightXCoord = newXCoord; barRect.width = barRightXCoord - barRect.x; Double startVal = calcXCoordToValue(barRect.x); Double endVal = calcXCoordToValue(barRightXCoord); setRangeText(startVal, endVal); } /** * Move the arrow and the range. * * @param xCoord */ private void moveAll(int xCoord) { if (xCoord > xCoord30) { return; } int currArrowX = arrowCenterXCoord; int currBarLeftX = barRect.x; int currBarRightX = barRightXCoord; int offset = xCoord - arrowCenterXCoord; if (currArrowX + offset < hLineStartXCoord || currBarLeftX + offset < hLineStartXCoord) { return; } if (currArrowX + offset >= hLineEndXCoord) { return; } if (currBarRightX != xCoord31Plus) { if (currBarRightX + offset > xCoord30) { return; } } moveArrow(xCoord); moveLeftSideOfRange(currBarLeftX + offset); if (barRightXCoord != xCoord31Plus) { moveRightSideOfRange(currBarRightX + offset); } } /** * Calculate the new X coordinate based on the X coordinate passed in. * * @param xCoord * New X coordinate. * @return Adjusted X coordinate. */ private int calcNewXCoord(int xCoord) { int newXCoord = xCoord; if (xCoord < xCoord0) { newXCoord = xCoord0; } else if (xCoord > xCoord31Plus) { newXCoord = xCoord31Plus; } else if (xCoord >= xCoord30 && xCoord < xCoord30_31Diff) { newXCoord = xCoord30; } else if (xCoord >= xCoord30_31Diff && xCoord <= xCoord31Plus) { newXCoord = xCoord31Plus; } else { newXCoord = xCoord; } return newXCoord; } /** * Calculate the X coordinate to a display value. * * @param xCoord * X coordinate. * @return Wind speed value. */ private Double calcXCoordToValue(int xCoord) { double rv = 0.0; if (xCoord < xCoord0) { return rv; } if (xCoord <= xCoord4) { rv = (xCoord - xCoord0) * factor0to4; } else if (xCoord <= xCoord10) { rv = (xCoord - xCoord4) * factor4to10 + 4.0; } else if (xCoord <= xCoord30) { rv = (xCoord - xCoord10) * factor10to30 + 10.0; } else if (xCoord >= xCoord31Plus) { return Double.NaN; } return rv; } /** * Calculate value to X coordinate. * * @param val * Wind speed value. * @return X coordinate. */ private int calcValueToXCoord(Double val) { int rv = 0; if (val > 30.0 || val < 0.0) { return INVALID_INT; } if (val <= 4.0) { rv = (int) Math.round(val / factor0to4 + xCoord0); } else if (val <= 10.0) { rv = (int) Math.round((val - 4.0) / factor4to10 + xCoord4); } else if (val <= 30.0) { rv = (int) Math.round((val - 10.0) / factor10to30 + xCoord10); } return rv; } /** * Validate the user inputs in the value text control. */ @Override public void validateValueInputs() { if (checkInput(valueTF.getText()) == false) { userInformation("Must enter a wind speed in the form D.D, DD.D, or 31+"); valueTF.setFocus(); valueTF.selectAll(); return; } if (valueTF.getText().compareTo("31+") == 0) { arrowCenterXCoord = xCoord31Plus; drawingCanvas.redraw(); return; } try { Double val = Double.valueOf(valueTF.getText()); arrowCenterXCoord = calcValueToXCoord(val); setValueText(val); drawingCanvas.redraw(); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } /** * Validate the user inputs in the range text control. */ @Override public void validateRangeInputs() { if (rangeTF.getText().indexOf("-") < 0) { userInformation("Must enter wind speed range in the form D{D}.D-D{D}.D|31+"); rangeTF.setFocus(); rangeTF.selectAll(); return; } String[] ranges = rangeTF.getText().split("-"); if (checkInput(ranges[0]) == false || checkInput(ranges[1]) == false) { userInformation("Must enter wind speed range in the form D{D}.D-D{D}.D|31+"); rangeTF.setFocus(); rangeTF.selectAll(); return; } String startStr = ranges[0]; String endStr = ranges[1]; if (startStr.compareTo("31+") == 0) { userInformation("Start Range cannot have a 31+ value"); rangeTF.setFocus(); rangeTF.selectAll(); return; } try { Double startVal = Double.valueOf(startStr); if (startVal < 0.0 || startVal > 30.0) { userInformation("Start Range must be from 0.0 to 30.0"); rangeTF.setFocus(); rangeTF.selectAll(); return; } int newXCoord = calcValueToXCoord(startVal); barRect.x = newXCoord; barRect.width = barRightXCoord - newXCoord; Double endVal = 0.0; if (endStr.compareTo("31+") == 0) { barRightXCoord = xCoord31Plus; barRect.width = barRightXCoord - barRect.x; endVal = Double.NaN; } else { endVal = Double.valueOf(endStr); if (endVal < startVal) { userInformation("Start Range value must be less than the End Range value."); rangeTF.setFocus(); rangeTF.selectAll(); return; } barRightXCoord = calcValueToXCoord(endVal); barRect.width = barRightXCoord - barRect.x; } setRangeText(startVal, endVal); // TODO drawingCanvas.redraw(); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } /** * Set the text in the value text control. * * @param val * Value to be converted in to wind speed. */ public void setValueText(Double val) { if (val.isNaN() == true || val > 30) { valueTF.setText("31+"); } else { valueTF.setText(String.format("%3.1f", val)); } if (valueTF.getText().compareTo("31+") == 0) { arrowCenterXCoord = xCoord31Plus; } else { arrowCenterXCoord = calcValueToXCoord(val); } drawingCanvas.redraw(); } /** * Set the text in the range text control. * * @param startVal * Start value to be converted in to wind speed. * @param endVal * End value to be converted in to wind speed. */ public void setRangeText(Double startVal, Double endVal) { if (startVal.isNaN() == true || startVal > 30) { rangeTF.setText("31+-31+"); return; } else if (endVal.isNaN() == true || endVal > 30) { rangeTF.setText(String.format("%2.1f-31+", startVal)); } else { rangeTF.setText(String.format("%2.1f-%2.1f", startVal, endVal)); } String[] ranges = rangeTF.getText().split("-"); String endStr = ranges[1]; int newXCoord = calcValueToXCoord(startVal); barRect.x = newXCoord; barRect.width = barRightXCoord - newXCoord; if (endStr.compareTo("31+") == 0) { barRightXCoord = xCoord31Plus; barRect.width = barRightXCoord - barRect.x; endVal = Double.NaN; } else { barRightXCoord = calcValueToXCoord(endVal); barRect.width = barRightXCoord - barRect.x; } drawingCanvas.redraw(); } public String getRange() { return rangeTF.getText(); } /** * Validate the user input. * * @param input * Input string. * @return True if the input is good, false otherwise. */ private boolean checkInput(String input) { return input .matches("(\\d\\u002E[0-9])|(\\u002E[0-9])|(\\d{2})|(\\d{1})|" + "(\\u002E[0-9][0-9])|(\\d{2}\\u002E[0-9])|([3][1]\\u002B)"); } public String[] getWindSpdRange() { String[] windSpdRange = new String[2]; String[] str = rangeTF.getText().split("-"); windSpdRange[0] = str[0]; windSpdRange[1] = str[1]; if (windSpdRange[1].endsWith("+")) { windSpdRange[1] = windSpdRange[1].substring(0, (windSpdRange[1].length() - 1)); } return windSpdRange; } }
28.229167
96
0.528677
a898b39361fca9e51f37f0f2b473ade962cdc16c
3,365
package com.lauriethefish.betterportals.bukkit.portal.blockarray; import com.lauriethefish.betterportals.bukkit.BetterPortals; import com.lauriethefish.betterportals.bukkit.network.BlockDataUpdateResult; import com.lauriethefish.betterportals.bukkit.network.BlockDataArrayRequest; import lombok.Getter; public class BlockRequestWorker implements Runnable { private BetterPortals pl; @Getter private CachedViewableBlocksArray cachedArray; private BlockDataArrayRequest request; private volatile BlockDataUpdateResult result = null; private volatile boolean failed = false; public BlockRequestWorker(BetterPortals pl, BlockDataArrayRequest request, CachedViewableBlocksArray cachedArray, boolean runAsync) { this.pl = pl; this.cachedArray = cachedArray; this.request = request; // Choose whether on not to run asynchronously if(runAsync) { new Thread(this).start(); } else { run(); } } public boolean hasFinished() { return result != null; } public boolean hasFailed() { return failed; } // Called to process the BlockDataUpdateResult on the main thread once it has been fetched (only called for get/update block array requests) public void finishUpdate() { if(request.getMode() != BlockDataArrayRequest.Mode.GET_OR_UPDATE) {throw new IllegalStateException("Non-get/update requests do not need finishing");} cachedArray.checkForChanges(request, true, false); cachedArray.processExternalUpdate(request, result); } @Override public void run() { String destinationServer = request.getDestPos().getServerName(); // Make sure we're actually connected if(pl.getNetworkClient() == null) { pl.getLogger().warning("Update for external portal failed - bungeecord is not enabled!"); failed = true; return; } // Update with the right code switch(request.getMode()) { case GET_OR_UPDATE: fetchUpdateResult(); return; case CLEAR: fetchClearResult(); } } // Fetches a BlockDataUpdateResult in order to get the blocks at the destination private void fetchUpdateResult() { String destinationServer = request.getDestPos().getServerName(); try { // Send the request to the destination server Object rawResult = pl.getNetworkClient().sendRequestToServer(request, destinationServer); result = (BlockDataUpdateResult) rawResult; } catch (Throwable ex) { pl.getLogger().warning("An error occurred while fetching the blocks for an external portal. This portal will not activate."); failed = true; ex.printStackTrace(); } } // Sends a request to just clear the block array private void fetchClearResult() { String destinationServer = request.getDestPos().getServerName(); try { pl.getNetworkClient().sendRequestToServer(request, destinationServer); } catch(Throwable ex) { pl.getLogger().warning("Failed to clear block array for an external portal when deactivated"); failed = true; ex.printStackTrace(); } } }
36.576087
157
0.659138
b6332fc93a807a4b10768f954695b746e2e032f0
3,853
/** * Copyright (C) 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.dashboard.ui.taglib; import org.jboss.dashboard.ui.UIServices; import org.jboss.dashboard.workspace.EnvelopesManager; import org.jboss.dashboard.ui.components.URLMarkupGenerator; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagData; import javax.servlet.jsp.tagext.TagExtraInfo; import javax.servlet.jsp.tagext.TagSupport; import javax.servlet.jsp.tagext.VariableInfo; import java.io.IOException; import java.util.List; public class EnvelopeHeadTag extends BaseTag { public static final String ENVELOPE_TOKEN = "envelopeHeadToken"; private boolean allowScripts = true; private boolean allowPages = true; private boolean allowEnvelopes = true; public static class TEI extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData tagData) { VariableInfo[] info = new VariableInfo[]{}; return info; } } public int doStartTag() throws JspException { pageContext.getRequest().setAttribute(ENVELOPE_TOKEN, Boolean.TRUE); /* // Removed due to incompatibilities with some charting libraries try { printBaseHref(); } catch (IOException e) { log.error("Error: ", e); } */ EnvelopesManager envelopesManager = null; if (allowEnvelopes) { envelopesManager = UIServices.lookup().getEnvelopesManager(); if (envelopesManager.getBeforeHeaderIncludePages() != null) for (int i = 0; i < envelopesManager.getBeforeHeaderIncludePages().length; i++) { String page = envelopesManager.getBeforeHeaderIncludePages()[i]; jspInclude(page); } } if (allowScripts) { jspInclude(envelopesManager.getScriptsIncludePage()); } List headers; if (allowPages) { headers = envelopesManager.getHeaderPagesToInclude(); if (headers != null) for (int i = 0; i < headers.size(); i++) { String page = (String) headers.get(i); jspInclude(page); } } return SKIP_BODY; } protected void printBaseHref() throws IOException { URLMarkupGenerator urlMarkupGenerator = UIServices.lookup().getUrlMarkupGenerator(); ServletRequest request = pageContext.getRequest(); String baseHref = urlMarkupGenerator.getBaseHref(request); StringBuffer sb = new StringBuffer(); sb.append("<base href=\"").append(baseHref).append("\">"); pageContext.getOut().println(sb); } public boolean isAllowScripts() { return allowScripts; } public void setAllowScripts(boolean allowScripts) { this.allowScripts = allowScripts; } public boolean isAllowPages() { return allowPages; } public void setAllowPages(boolean allowPages) { this.allowPages = allowPages; } public boolean isAllowEnvelopes() { return allowEnvelopes; } public void setAllowEnvelopes(boolean allowEnvelopes) { this.allowEnvelopes = allowEnvelopes; } }
32.108333
97
0.662081
dd9fcd58ea54dce2e84d936dc396b6bd5aa3896b
846
package com.smileduster.vsboard.api.model.common; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor public enum ResponseCode { success("0", "Done."), loginFail("f1000", "Login failed."), dupEmail("f1100", "Provided email is registered."), unknownTarget("f2000", "Unknown target."), illegalGroup("f2101", "Illegal group provided."), illegalBattle("f2102", "Illegal battle provided."), illegalMember("f2103", "Illegal member provided."), dependentBattle("f2200", "Some battles are relying on the target that will be deleted."), unknownError("e0000", "Unknown error occurred."), comingSoon("f0000", "Coming soon."); private String code; private String msg; ResponseCode(String code, String msg){ this.code = code; this.msg = msg; } }
24.171429
93
0.676123
9cd0d55131e14c1f814873a4ec134ff65daa80ca
1,053
package space; public class Nucleus<T> { public synchronized Nucleus<T> developNew() { String pinioned = "whDmK9AOXupJ3fuRSD"; return this.the; } public synchronized void prepareSecond(Nucleus<T> third) { double upstairsMax = 0.21616814924534855; this.the = third; } public synchronized T goInformation() { double keepsake = 0.834399456364029; return this.computer; } public Nucleus(T results, Nucleus<T> future, Nucleus<T> old) { this.computer = results; this.the = future; this.first = old; } public synchronized void rigidPreliminary(Nucleus<T> original) { double integral = 0.3182052345793611; this.first = original; } private Nucleus<T> the; private Nucleus<T> first; private T computer; static final String slot = "oZm21QzB"; public synchronized Nucleus<T> developOriginal() { int amount = 1875889127; return this.first; } public synchronized void determineTabulations(T information) { String nominal = "iK"; this.computer = information; } }
22.891304
66
0.692308
269ac8db3758b7e110e7e86b136a542e25d9895c
19,711
package org.embulk.output.bigquery_java; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.nio.channels.Channels; import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; import com.google.cloud.bigquery.LegacySQLTypeName; import com.google.cloud.bigquery.QueryJobConfiguration; import com.google.common.base.Throwables; import org.embulk.output.bigquery_java.config.BigqueryColumnOption; import org.embulk.output.bigquery_java.config.PluginTask; import org.embulk.output.bigquery_java.exception.BigqueryBackendException; import org.embulk.output.bigquery_java.exception.BigqueryException; import org.embulk.output.bigquery_java.exception.BigqueryInternalException; import org.embulk.output.bigquery_java.exception.BigqueryRateLimitExceededException; import org.embulk.spi.Column; import org.embulk.spi.Schema; import org.embulk.spi.type.BooleanType; import org.embulk.spi.type.DoubleType; import org.embulk.spi.type.JsonType; import org.embulk.spi.type.LongType; import org.embulk.spi.type.StringType; import org.embulk.spi.type.TimestampType; import org.embulk.spi.type.Type; import org.embulk.spi.util.RetryExecutor; import static org.embulk.spi.util.RetryExecutor.retryExecutor; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryOptions; import com.google.cloud.bigquery.CopyJobConfiguration; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.FormatOptions; import com.google.cloud.bigquery.Job; import com.google.cloud.bigquery.JobId; import com.google.cloud.bigquery.JobInfo; import com.google.cloud.bigquery.JobStatistics; import com.google.cloud.bigquery.StandardSQLTypeName; import com.google.cloud.bigquery.StandardTableDefinition; import com.google.cloud.bigquery.Table; import com.google.cloud.bigquery.TableDataWriteChannel; import com.google.cloud.bigquery.TableDefinition; import com.google.cloud.bigquery.TableId; import com.google.cloud.bigquery.TableInfo; import com.google.cloud.bigquery.WriteChannelConfiguration; import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BigqueryClient { private final Logger logger = LoggerFactory.getLogger(BigqueryClient.class); private BigQuery bigquery; private String dataset; private PluginTask task; private Schema schema; private List<BigqueryColumnOption> columnOptions; public BigqueryClient(PluginTask task, Schema schema) { this.task = task; this.schema = schema; this.dataset = task.getDataset(); this.columnOptions = this.task.getColumnOptions().orElse(Collections.emptyList()); try { this.bigquery = getClientWithJsonKey(this.task.getJsonKeyfile()); } catch (IOException e) { throw new RuntimeException(e); } } private static BigQuery getClientWithJsonKey(String key) throws IOException { return BigQueryOptions.newBuilder() .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(key))) .build() .getService(); } public Job getJob(JobId jobId) { return this.bigquery.getJob(jobId); } public Table getTable(String name) { return getTable(TableId.of(this.dataset, name)); } public Table getTable(TableId tableId) { return this.bigquery.getTable(tableId); } public Table createTableIfNotExist(String table, String dataset) { com.google.cloud.bigquery.Schema schema = buildSchema(this.schema, this.columnOptions); TableDefinition tableDefinition = StandardTableDefinition.of(schema); return bigquery.create(TableInfo.newBuilder(TableId.of(dataset, table), tableDefinition).build()); } public JobStatistics.LoadStatistics load(Path loadFile, String table, JobInfo.WriteDisposition writeDestination) throws BigqueryException { String dataset = this.dataset; int retries = this.task.getRetries(); PluginTask task = this.task; Schema schema = this.schema; List<BigqueryColumnOption> columnOptions = this.columnOptions; try { // https://cloud.google.com/bigquery/quotas#standard_tables // Maximum rate of table metadata update operations — 5 operations every 10 seconds per table return retryExecutor() .withRetryLimit(retries) .withInitialRetryWait(2 * 1000) .withMaxRetryWait(10 * 1000) .runInterruptible(new RetryExecutor.Retryable<JobStatistics.LoadStatistics>() { @Override public JobStatistics.LoadStatistics call() { UUID uuid = UUID.randomUUID(); String jobId = String.format("embulk_load_job_%s", uuid.toString()); if (Files.exists(loadFile)) { // TODO: "embulk-output-bigquery: Load job starting... job_id:[#{job_id}] #{path} => #{@project}:#{@dataset}.#{table} in #{@location_for_log}" logger.info("embulk-output-bigquery: Load job starting... job_id:[{}] {} => {}.{}", jobId, loadFile.toString(), dataset, table); } else { logger.info("embulk-output-bigquery: Load job starting... {} does not exist, skipped", loadFile.toString()); // TODO: should throw error? return null; } TableId tableId = TableId.of(dataset, table); WriteChannelConfiguration writeChannelConfiguration = WriteChannelConfiguration.newBuilder(tableId) .setFormatOptions(FormatOptions.json()) .setWriteDisposition(writeDestination) .setMaxBadRecords(task.getMaxBadRecords()) .setIgnoreUnknownValues(task.getIgnoreUnknownValues()) .setSchema(buildSchema(schema, columnOptions)) .build(); TableDataWriteChannel writer = bigquery.writer(JobId.of(jobId), writeChannelConfiguration); try (OutputStream stream = Channels.newOutputStream(writer)) { Files.copy(loadFile, stream); } catch (IOException e) { logger.info(e.getMessage()); } Job job = writer.getJob(); return (JobStatistics.LoadStatistics) waitForLoad(job); } @Override public boolean isRetryableException(Exception exception) { return exception instanceof BigqueryBackendException || exception instanceof BigqueryRateLimitExceededException || exception instanceof BigqueryInternalException; } @Override public void onRetry(Exception exception, int retryCount, int retryLimit, int retryWait) throws RetryExecutor.RetryGiveupException { String message = String.format("embulk-output-bigquery: Load job failed. Retrying %d/%d after %d seconds. Message: %s", retryCount, retryLimit, retryWait / 1000, exception.getMessage()); if (retryCount % retries == 0) { logger.warn(message, exception); } else { logger.warn(message); } } @Override public void onGiveup(Exception firstException, Exception lastException) throws RetryExecutor.RetryGiveupException { logger.error("embulk-output-bigquery: Give up retrying for Load job"); } }); } catch (RetryExecutor.RetryGiveupException ex) { Throwables.throwIfInstanceOf(ex.getCause(), BigqueryException.class); // TODO: throw new RuntimeException(ex); } catch (InterruptedException ex) { throw new BigqueryException("interrupted"); } } public JobStatistics.CopyStatistics copy(String sourceTable, String destinationTable, String destinationDataset, JobInfo.WriteDisposition writeDestination) throws BigqueryException { String dataset = this.dataset; int retries = this.task.getRetries(); try { return retryExecutor() .withRetryLimit(retries) .withInitialRetryWait(2 * 1000) .withMaxRetryWait(10 * 1000) .runInterruptible(new RetryExecutor.Retryable<JobStatistics.CopyStatistics>() { @Override public JobStatistics.CopyStatistics call() { UUID uuid = UUID.randomUUID(); String jobId = String.format("embulk_load_job_%s", uuid.toString()); TableId destTableId = TableId.of(destinationDataset, destinationTable); TableId srcTableId = TableId.of(dataset, sourceTable); CopyJobConfiguration copyJobConfiguration = CopyJobConfiguration.newBuilder(destTableId, srcTableId) .setWriteDisposition(writeDestination) .build(); Job job = bigquery.create(JobInfo.newBuilder(copyJobConfiguration).setJobId(JobId.of(jobId)).build()); return (JobStatistics.CopyStatistics) waitForCopy(job); } @Override public boolean isRetryableException(Exception exception) { return exception instanceof BigqueryBackendException || exception instanceof BigqueryRateLimitExceededException || exception instanceof BigqueryInternalException; } @Override public void onRetry(Exception exception, int retryCount, int retryLimit, int retryWait) throws RetryExecutor.RetryGiveupException { String message = String.format("embulk-output-bigquery: Copy job failed. Retrying %d/%d after %d seconds. Message: %s", retryCount, retryLimit, retryWait / 1000, exception.getMessage()); if (retryCount % retries == 0) { logger.warn(message, exception); } else { logger.warn(message); } } @Override public void onGiveup(Exception firstException, Exception lastException) throws RetryExecutor.RetryGiveupException { logger.error("embulk-output-bigquery: Give up retrying for Copy job"); } }); } catch (RetryExecutor.RetryGiveupException ex) { Throwables.throwIfInstanceOf(ex.getCause(), BigqueryException.class); // TODO: throw new RuntimeException(ex); } catch (InterruptedException ex) { throw new BigqueryException("interrupted"); } } public JobStatistics.QueryStatistics executeQuery(String query) { int retries = this.task.getRetries(); try { return retryExecutor() .withRetryLimit(retries) .withInitialRetryWait(2 * 1000) .withMaxRetryWait(10 * 1000) .runInterruptible(new RetryExecutor.Retryable<JobStatistics.QueryStatistics>() { @Override public JobStatistics.QueryStatistics call() { UUID uuid = UUID.randomUUID(); String jobId = String.format("embulk_query_job_%s", uuid.toString()); QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query) .setUseLegacySql(false) .build(); Job job = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(JobId.of(jobId)).build()); return (JobStatistics.QueryStatistics) waitForQuery(job); } @Override public boolean isRetryableException(Exception exception) { return exception instanceof BigqueryBackendException || exception instanceof BigqueryRateLimitExceededException || exception instanceof BigqueryInternalException; } @Override public void onRetry(Exception exception, int retryCount, int retryLimit, int retryWait) throws RetryExecutor.RetryGiveupException { String message = String.format("embulk-output-bigquery: Query job failed. Retrying %d/%d after %d seconds. Message: %s", retryCount, retryLimit, retryWait / 1000, exception.getMessage()); if (retryCount % retries == 0) { logger.warn(message, exception); } else { logger.warn(message); } } @Override public void onGiveup(Exception firstException, Exception lastException) throws RetryExecutor.RetryGiveupException { logger.error("embulk-output-bigquery: Give up retrying for Query job"); } }); } catch (RetryExecutor.RetryGiveupException ex) { Throwables.throwIfInstanceOf(ex.getCause(), BigqueryException.class); // TODO: throw new RuntimeException(ex); } catch (InterruptedException ex) { throw new BigqueryException("interrupted"); } } public boolean deleteTable(String table) { return this.bigquery.delete(TableId.of(this.dataset, table)); } public boolean deleteTable(String table, String dataset) { return this.bigquery.delete(TableId.of(dataset, table)); } private JobStatistics waitForLoad(Job job) throws BigqueryException { return new BigqueryJobWaiter(this.task, this, job).waitFor("Load"); } private JobStatistics waitForCopy(Job job) throws BigqueryException { return new BigqueryJobWaiter(this.task, this, job).waitFor("Copy"); } private JobStatistics waitForQuery(Job job) throws BigqueryException { return new BigqueryJobWaiter(this.task, this, job).waitFor("Query"); } @VisibleForTesting protected com.google.cloud.bigquery.Schema buildSchema(Schema schema, List<BigqueryColumnOption> columnOptions) { // TODO: support schema file if (this.task.getTemplateTable().isPresent()) { TableId tableId = TableId.of(this.dataset, this.task.getTemplateTable().get()); Table table = this.bigquery.getTable(tableId); return table.getDefinition().getSchema(); } List<Field> fields = new ArrayList<>(); for (Column col : schema.getColumns()) { Field field; StandardSQLTypeName sqlTypeName = getStandardSQLTypeNameByEmbulkType(col.getType()); LegacySQLTypeName legacySQLTypeName = getLegacySQLTypeNameByEmbulkType(col.getType()); Field.Mode fieldMode = Field.Mode.NULLABLE; Optional<BigqueryColumnOption> columnOption = BigqueryUtil.findColumnOption(col.getName(), columnOptions); if (columnOption.isPresent()) { BigqueryColumnOption colOpt = columnOption.get(); if (!colOpt.getMode().isEmpty()) { fieldMode = Field.Mode.valueOf(colOpt.getMode()); } if (colOpt.getType().isPresent()) { if (this.task.getEnableStandardSQL()) { sqlTypeName = StandardSQLTypeName.valueOf(colOpt.getType().get()); } else { legacySQLTypeName = LegacySQLTypeName.valueOf(colOpt.getType().get()); } } } if (task.getEnableStandardSQL()) { field = Field.of(col.getName(), sqlTypeName); } else { field = Field.of(col.getName(), legacySQLTypeName); } // TODO:: support field for JSON type field = field.toBuilder() .setMode(fieldMode) .build(); fields.add(field); } return com.google.cloud.bigquery.Schema.of(fields); } @VisibleForTesting protected StandardSQLTypeName getStandardSQLTypeNameByEmbulkType(Type type) { if (type instanceof BooleanType) { return StandardSQLTypeName.BOOL; } else if (type instanceof LongType) { return StandardSQLTypeName.INT64; } else if (type instanceof DoubleType) { return StandardSQLTypeName.FLOAT64; } else if (type instanceof StringType) { return StandardSQLTypeName.STRING; } else if (type instanceof TimestampType) { return StandardSQLTypeName.TIMESTAMP; } else if (type instanceof JsonType) { return StandardSQLTypeName.STRING; } else { throw new RuntimeException("never reach here"); } } @VisibleForTesting protected LegacySQLTypeName getLegacySQLTypeNameByEmbulkType(Type type) { if (type instanceof BooleanType) { return LegacySQLTypeName.BOOLEAN; } else if (type instanceof LongType) { return LegacySQLTypeName.INTEGER; } else if (type instanceof DoubleType) { return LegacySQLTypeName.FLOAT; } else if (type instanceof StringType) { return LegacySQLTypeName.STRING; } else if (type instanceof TimestampType) { return LegacySQLTypeName.TIMESTAMP; } else if (type instanceof JsonType) { return LegacySQLTypeName.STRING; } else { throw new RuntimeException("never reach here"); } } }
47.268585
175
0.579473
4ec88d1b697c06847f270b1a8c97eecc369d5227
5,777
package com.study.yang.lifehelper.db; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import de.greenrobot.dao.AbstractDao; import de.greenrobot.dao.Property; import de.greenrobot.dao.internal.DaoConfig; import com.study.yang.lifehelper.db.Note; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "NOTE". */ public class NoteDao extends AbstractDao<Note, Long> { public static final String TABLENAME = "NOTE"; /** * Properties of entity Note.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property Title = new Property(1, String.class, "title", false, "TITLE"); public final static Property SaveTime = new Property(2, String.class, "saveTime", false, "SAVE_TIME"); public final static Property Content = new Property(3, String.class, "content", false, "CONTENT"); public final static Property OrderTime = new Property(4, Long.class, "orderTime", false, "ORDER_TIME"); public final static Property ColorType = new Property(5, String.class, "colorType", false, "COLOR_TYPE"); public final static Property DeleteType = new Property(6, Integer.class, "deleteType", false, "DELETE_TYPE"); }; public NoteDao(DaoConfig config) { super(config); } public NoteDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(SQLiteDatabase db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"NOTE\" (" + // "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id "\"TITLE\" TEXT," + // 1: title "\"SAVE_TIME\" TEXT," + // 2: saveTime "\"CONTENT\" TEXT," + // 3: content "\"ORDER_TIME\" INTEGER," + // 4: orderTime "\"COLOR_TYPE\" TEXT," + // 5: colorType "\"DELETE_TYPE\" INTEGER);"); // 6: deleteType } /** Drops the underlying database table. */ public static void dropTable(SQLiteDatabase db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"NOTE\""; db.execSQL(sql); } /** @inheritdoc */ @Override protected void bindValues(SQLiteStatement stmt, Note entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String title = entity.getTitle(); if (title != null) { stmt.bindString(2, title); } String saveTime = entity.getSaveTime(); if (saveTime != null) { stmt.bindString(3, saveTime); } String content = entity.getContent(); if (content != null) { stmt.bindString(4, content); } Long orderTime = entity.getOrderTime(); if (orderTime != null) { stmt.bindLong(5, orderTime); } String colorType = entity.getColorType(); if (colorType != null) { stmt.bindString(6, colorType); } Integer deleteType = entity.getDeleteType(); if (deleteType != null) { stmt.bindLong(7, deleteType); } } /** @inheritdoc */ @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } /** @inheritdoc */ @Override public Note readEntity(Cursor cursor, int offset) { Note entity = new Note( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // title cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // saveTime cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // content cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4), // orderTime cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // colorType cursor.isNull(offset + 6) ? null : cursor.getInt(offset + 6) // deleteType ); return entity; } /** @inheritdoc */ @Override public void readEntity(Cursor cursor, Note entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setTitle(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setSaveTime(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setContent(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3)); entity.setOrderTime(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4)); entity.setColorType(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5)); entity.setDeleteType(cursor.isNull(offset + 6) ? null : cursor.getInt(offset + 6)); } /** @inheritdoc */ @Override protected Long updateKeyAfterInsert(Note entity, long rowId) { entity.setId(rowId); return rowId; } /** @inheritdoc */ @Override public Long getKey(Note entity) { if(entity != null) { return entity.getId(); } else { return null; } } /** @inheritdoc */ @Override protected boolean isEntityUpdateable() { return true; } }
35.881988
117
0.59408
c2738b3770fb5baf889f447361e4ae7aa327a0b5
2,296
package net.teamfruit.projectrtm.rtm.world.station; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import net.teamfruit.projectrtm.ngtlib.math.AABBInt; public class Station { protected World worldObj; protected String name; protected List<AABBInt> partsList = new ArrayList<AABBInt>(); public Station() { this.name = ""; } public Station(World world, String par2) { this.worldObj = world; this.name = par2; } public void readFromNBT(NBTTagCompound nbt) { this.name = nbt.getString("Name"); NBTTagList nbttaglist = nbt.getTagList("Parts", 10); for (int i = 0; i<nbttaglist.tagCount(); ++i) { NBTTagCompound nbt1 = nbttaglist.getCompoundTagAt(i); int x0 = nbt1.getInteger("MinX"); int y0 = nbt1.getInteger("MinY"); int z0 = nbt1.getInteger("MinZ"); int x1 = nbt1.getInteger("MaxX"); int y1 = nbt1.getInteger("MaxY"); int z1 = nbt1.getInteger("MaxZ"); this.partsList.add(new AABBInt(x0, y0, z0, x1, y1, z1)); } } public void writeToNBT(NBTTagCompound nbt) { nbt.setString("Name", this.name); NBTTagList nbttaglist = new NBTTagList(); Iterator iterator = this.partsList.iterator(); while (iterator.hasNext()) { AABBInt chunk = (AABBInt) iterator.next(); NBTTagCompound nbt1 = new NBTTagCompound(); nbt1.setInteger("MinX", chunk.minX); nbt1.setInteger("MinY", chunk.minY); nbt1.setInteger("MinZ", chunk.minZ); nbt1.setInteger("MaxX", chunk.maxX); nbt1.setInteger("MaxY", chunk.maxY); nbt1.setInteger("MaxZ", chunk.maxZ); nbttaglist.appendTag(nbt1); } nbt.setTag("Parts", nbttaglist); } public void add(AABBInt aabb) { this.partsList.add(aabb); } /*public class StationChunk { public final int blockX; public final int blockY; public final int blockZ; public StationChunk(int x, int y, int z) { this.blockX = x; this.blockY = y; this.blockZ = z; } public int getChunkX() { return this.blockX >> 4; } public int getChunkY() { return this.blockY >> 4; } public int getChunkZ() { return this.blockZ >> 4; } }*/ }
25.230769
63
0.656794
6b6aafec0e44a2b75c0e53f4d0011614c6ee33c4
1,051
package cn.mcmod.tofucraft.client.render; import cn.mcmod.tofucraft.TofuMain; import cn.mcmod.tofucraft.client.model.ModelTofuChinger; import cn.mcmod.tofucraft.entity.EntityTofuChinger; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderTofuChinger extends RenderLiving<EntityTofuChinger> { private static final ResourceLocation CHINGER_TEXTURES = new ResourceLocation(TofuMain.MODID, "textures/mob/tofuchinger.png"); public RenderTofuChinger(RenderManager p_i47210_1_) { super(p_i47210_1_, new ModelTofuChinger(), 0.4F); } /** * Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityTofuChinger entity) { return CHINGER_TEXTURES; } }
40.423077
130
0.79353
ac8d3154f1dfe9862af565d1a2d2fe16be32ce1e
2,294
//package org.firstinspires.ftc.teamcode.SkyStone.V1liftGrab; // // //import com.qualcomm.robotcore.eventloop.opmode.OpMode; //import com.qualcomm.robotcore.hardware.DcMotor; //import com.qualcomm.robotcore.hardware.Servo; // //import org.firstinspires.ftc.teamcode.RobotLibs.lib.PSConfigOpMode; //import org.firstinspires.ftc.teamcode.RobotLibs.lib.PSEnum; //import org.firstinspires.ftc.teamcode.RobotLibs.lib.PSRobot; //import org.firstinspires.ftc.teamcode.RobotLibs.lib.hardware.MotorEx; // //public abstract class Config_r1 extends PSConfigOpMode { // // Drive drive; // Lift lift; // @Override // public void config(OpMode opMode) { // robot = new PSRobot(opMode); // drive = new Drive(); // lift = new Lift(); // } // // class Drive { // MotorEx leftFront; // MotorEx rightFront; // MotorEx leftBack; // MotorEx rightBack; // // // public Drive() { // leftFront = robot.motorHandler.newDriveMotor("LF", PSEnum.MotorLoc.LEFTFRONT, 13); // rightFront = robot.motorHandler.newDriveMotor("RF", PSEnum.MotorLoc.RIGHTFRONT, 13); // leftBack = robot.motorHandler.newDriveMotor("LB", PSEnum.MotorLoc.LEFTBACK, 13); // rightBack = robot.motorHandler.newDriveMotor("RB",PSEnum.MotorLoc.RIGHTBACK, 13); // } // // } // class Lift { // MotorEx liftMotorRight; // Servo grabberLeft; // Servo grabberRight; // double motorPowerAdding = 0; // public Lift(){ // liftMotorRight = robot.motorHandler.newMotor("lift",20); // liftMotorRight.motorObject.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); // grabberLeft = hardwareMap.servo.get("grabL"); // grabberRight = hardwareMap.servo.get("grabR"); // } // public void liftPower(double power){ // liftMotorRight.setPower(power+motorPowerAdding); // } // public void openGrab(){ // motorPowerAdding = 0.2; // grabberLeft.setPosition(0.5); // grabberRight.setPosition(0.5); // // } // public void closeGrab(){ // motorPowerAdding = 0.1; // grabberLeft.setPosition(1); // grabberRight.setPosition(0); } // } //}
35.292308
98
0.621622
b17da2d2afabcb2679fbab7e89be38dc69a2a1cc
1,831
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.silong.foundation.constants; import com.silong.foundation.model.ErrorDetail; import lombok.Getter; /** * 通用错误信息 * * @author louis sin * @version 1.0.0 * @since 2022-01-14 09:16 */ public enum CommonErrorCode { /** 服务内部错误 */ SERVICE_INTERNAL_ERROR("%s.error.0001", "An internal error occurred in the %s."), /** 权限不足 */ INSUFFICIENT_PERMISSIONS("%s.error.0002", "Not authorized to operate."), /** 鉴权失败 */ AUTHENTICATION_FAILED("%s.error.0003", "Authentication failed."); /** 错误码 */ @Getter private final String code; /** 错误提示 */ @Getter private final String message; CommonErrorCode(String code, String message) { this.code = code; this.message = message; } /** * 根据服务名生成错误详情信息,供返回 * * @param serviceName 服务名 * @return 错误详情 */ public ErrorDetail format(String serviceName) { return ErrorDetail.builder() .errorCode(String.format(code, serviceName)) .errorMessage(String.format(message, serviceName)) .build(); } }
27.742424
83
0.699618
1f46f65f4cc3e51aa4b72751a0588d764f5d746d
1,091
/* * Copyright (C) 2014-2015 LinkedIn Corp. 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. */ package gobblin.yarn.event; /** * A type of events for new container requests to be used with a {@link com.google.common.eventbus.EventBus}. * * @author ynli */ public class NewContainerRequest { private final int newContainersRequested; public NewContainerRequest(int newContainersRequested) { this.newContainersRequested = newContainersRequested; } /** * Get the number of new containers requested. * * @return the number of new containers requested */ public int getNewContainersRequested() { return this.newContainersRequested; } }
29.486486
109
0.735105
4b6fbb63c85d5583902167ccefa36d6d8beb2397
1,192
package com.simibubi.create.lib.mixin.client; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import com.mojang.blaze3d.pipeline.RenderTarget; import com.simibubi.create.lib.extensions.RenderTargetExtensions; import net.minecraft.client.renderer.PostChain; @Mixin(PostChain.class) public abstract class PostChainMixin { @Shadow @Final private RenderTarget screenTarget; @Inject( method = "addTempTarget", at = @At( value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;setClearColor(FFFF)V", shift = At.Shift.AFTER ), locals = LocalCapture.CAPTURE_FAILHARD ) public void create$isStencil(String name, int width, int height, CallbackInfo ci, RenderTarget rendertarget) { if (((RenderTargetExtensions) screenTarget).create$isStencilEnabled()) { ((RenderTargetExtensions) rendertarget).create$enableStencil(); } } }
32.216216
111
0.785235
a0a29cf31a39626ffe7010194207fcadf7cddc75
964
/* * Copyright 2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.frontend.find.hod.databases; import com.hp.autonomy.hod.client.api.authentication.TokenType; import com.hp.autonomy.hod.client.api.resource.Resources; import com.hp.autonomy.hod.client.error.HodErrorException; import com.hp.autonomy.hod.client.token.TokenProxy; import com.hp.autonomy.searchcomponents.core.databases.DatabasesService; import com.hp.autonomy.searchcomponents.hod.databases.Database; import com.hp.autonomy.searchcomponents.hod.databases.HodDatabasesRequest; import org.springframework.stereotype.Service; @Service public interface FindHodDatabasesService extends DatabasesService<Database, HodDatabasesRequest, HodErrorException> { Resources getAllIndexes(final TokenProxy<?, TokenType.Simple> tokenProxy) throws HodErrorException; }
45.904762
117
0.826763
e052b89a5b51b0aeb2abe14ee95e01b679f1bc3f
527
package com.fleetlize.rating.usecase.mapper; import com.fleetlize.rating.entities.Booking; import com.fleetlize.rating.gateway.data.entities.BookingEntity; import org.mapstruct.InheritInverseConfiguration; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @Mapper(componentModel = "spring") public interface BookingEntityMapper { @Mapping(source = "carPlate", target = "car.plate") BookingEntity from(final Booking booking); @InheritInverseConfiguration Booking from(final BookingEntity bookingEntity); }
27.736842
64
0.810247
331b957421c0b1bc910875a43705c008b26e2790
4,103
package net.minecraft.client.gui; import com.google.common.collect.Lists; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import java.util.Map.Entry; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiSnooper$List; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.client.settings.GameSettings$Options; public class GuiSnooper extends GuiScreen { private final GuiScreen field_146608_a; private final GameSettings game_settings_2; private final List field_146604_g = Lists.newArrayList(); private final List field_146609_h = Lists.newArrayList(); private String field_146610_i; private String[] field_146607_r; private GuiSnooper$List field_146606_s; private GuiButton field_146605_t; public GuiSnooper(GuiScreen var1, GameSettings var2) { this.field_146608_a = var1; this.game_settings_2 = var2; } public void initGui() { this.field_146610_i = I18n.format("options.snooper.title", new Object[0]); String var1 = I18n.format("options.snooper.desc", new Object[0]); ArrayList var2 = Lists.newArrayList(); for(Object var4 : this.fontRendererObj.listFormattedStringToWidth(var1, this.width - 30)) { var2.add((String)var4); } this.field_146607_r = (String[])var2.toArray(new String[var2.size()]); this.field_146604_g.clear(); this.field_146609_h.clear(); this.buttonList.add(this.field_146605_t = new GuiButton(1, this.width / 2 - 152, this.height - 30, 150, 20, this.game_settings_2.b(GameSettings$Options.SNOOPER_ENABLED))); this.buttonList.add(new GuiButton(2, this.width / 2 + 2, this.height - 30, 150, 20, I18n.format("gui.done", new Object[0]))); boolean var6 = this.mc.getIntegratedServer() != null && this.mc.getIntegratedServer().getPlayerUsageSnooper() != null; for(Entry var5 : (new TreeMap(this.mc.getPlayerUsageSnooper().getCurrentStats())).entrySet()) { this.field_146604_g.add("C " + (String)var5.getKey()); this.field_146609_h.add(this.fontRendererObj.trimStringToWidth((String)var5.getValue(), this.width - 220)); } for(Entry var9 : (new TreeMap(this.mc.getIntegratedServer().getPlayerUsageSnooper().getCurrentStats())).entrySet()) { this.field_146604_g.add("S " + (String)var9.getKey()); this.field_146609_h.add(this.fontRendererObj.trimStringToWidth((String)var9.getValue(), this.width - 220)); } this.field_146606_s = new GuiSnooper$List(this); } public void handleMouseInput() throws IOException { super.handleMouseInput(); this.field_146606_s.handleMouseInput(); } protected void actionPerformed(GuiButton var1) throws IOException { if(var1.enabled) { if(var1.id == 2) { this.game_settings_2.saveOptions(); this.game_settings_2.saveOptions(); this.mc.displayGuiScreen(this.field_146608_a); } if(var1.id == 1) { this.game_settings_2.setOptionValue(GameSettings$Options.SNOOPER_ENABLED, 1); this.field_146605_t.displayString = this.game_settings_2.b(GameSettings$Options.SNOOPER_ENABLED); } } } public void drawScreen(int var1, int var2, float var3) { this.drawDefaultBackground(); this.field_146606_s.drawScreen(var1, var2, var3); this.drawCenteredString(this.fontRendererObj, this.field_146610_i, this.width / 2, 8, 16777215); int var4 = 22; for(String var8 : this.field_146607_r) { this.drawCenteredString(this.fontRendererObj, var8, this.width / 2, var4, 8421504); var4 += this.fontRendererObj.f(); } super.drawScreen(var1, var2, var3); } static List access$000(GuiSnooper var0) { return var0.field_146604_g; } static List access$100(GuiSnooper var0) { return var0.field_146609_h; } private static IOException a(IOException var0) { return var0; } }
38.345794
177
0.700219
5ecce3fba17a4f289cdf23ba9bcc9f2ed6949f34
773
package com.devil.netty; import com.alibaba.fastjson.JSON; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; /** * 编码 * * @author Devil * @date Created in 2021/7/26 17:04 */ public class RpcEncoder extends MessageToByteEncoder { private Class<?> target; public RpcEncoder(Class target) { this.target = target; } @Override protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { if (target.isInstance(msg)) { byte[] data = JSON.toJSONBytes(msg); // 先将消息长度写入,也就是消息头 out.writeInt(data.length); // 消息体中包含我们要发送的数据 out.writeBytes(data); } } }
23.424242
96
0.652005
55637a12c91c04c55ffb7b61dc8d7894bbc1cf4b
1,589
package com.dopoiv.clinic.project.messageboard.entity; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableLogic; import com.dopoiv.clinic.common.tools.BaseEntity; import java.time.LocalDateTime; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.springframework.format.annotation.DateTimeFormat; /** * MessageBoard 实体类 * * @author wangduofu * @since 2021-05-14 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @ApiModel(value = "MessageBoard对象", description = "") public class MessageBoard extends BaseEntity { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "用户id") private String userId; @ApiModelProperty(value = "留言内容") private String message; @ApiModelProperty(value = "逻辑删除") @TableLogic @TableField(fill = FieldFill.INSERT) private Integer deleted; @ApiModelProperty(value = "留言时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; @ApiModelProperty(value = "用户昵称") @TableField(exist = false) private String nickname; @ApiModelProperty(value = "用户姓名") @TableField(exist = false) private String realName; }
27.877193
68
0.750787
2567adef2760c4ce8f80bbe7bf2009b061ac138d
1,884
package com.aaa.project.system.messionStatus.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.aaa.project.system.messionStatus.mapper.MessionStatusMapper; import com.aaa.project.system.messionStatus.domain.MessionStatus; import com.aaa.project.system.messionStatus.service.IMessionStatusService; import com.aaa.common.support.Convert; /** * 任务状态 服务层实现 * * @author aaa * @date 2019-04-20 */ @Service public class MessionStatusServiceImpl implements IMessionStatusService { @Autowired private MessionStatusMapper messionStatusMapper; /** * 查询任务状态信息 * * @param messionStatusId 任务状态ID * @return 任务状态信息 */ @Override public MessionStatus selectMessionStatusById(Integer messionStatusId) { return messionStatusMapper.selectMessionStatusById(messionStatusId); } /** * 查询任务状态列表 * * @param messionStatus 任务状态信息 * @return 任务状态集合 */ @Override public List<MessionStatus> selectMessionStatusList(MessionStatus messionStatus) { return messionStatusMapper.selectMessionStatusList(messionStatus); } /** * 新增任务状态 * * @param messionStatus 任务状态信息 * @return 结果 */ @Override public int insertMessionStatus(MessionStatus messionStatus) { return messionStatusMapper.insertMessionStatus(messionStatus); } /** * 修改任务状态 * * @param messionStatus 任务状态信息 * @return 结果 */ @Override public int updateMessionStatus(MessionStatus messionStatus) { return messionStatusMapper.updateMessionStatus(messionStatus); } /** * 删除任务状态对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deleteMessionStatusByIds(String ids) { return messionStatusMapper.deleteMessionStatusByIds(Convert.toStrArray(ids)); } }
22.428571
80
0.725584
65d979fbfdcd63aa01b1eaca11fb6b158a7c3eb7
463
package io.hackages.learning.domain.manager.aircraft.spi; import io.hackages.learning.domain.model.Aircraft; import java.io.IOException; import java.util.List; public interface AircraftServiceProvider { List<Aircraft> getAircrafts(); Aircraft addAircraft(String code, String description); void deleteAircraft(String code) throws IOException; Aircraft changeDescription(String description); Aircraft fetchAircraftByCode(String code); }
23.15
58
0.788337
cd2a35d3c42c20834fc2814434dc21a4b4f0824c
1,817
package org.roaringbitmap.circuits.topk; import org.roaringbitmap.RoaringBitmap; import org.roaringbitmap.circuits.comparator.BasicComparator; import org.roaringbitmap.circuits.comparator.OwenComparator; import org.roaringbitmap.circuits.comparator.OwenHorizontalComparator; public class Benchmark { public static TopK[] Top = { new RinfretONeilTopK(),new TreeTopK(),new SSUMTopK(), new NaiveScanCountTopK() }; public static void main(String[] args) { System.out.println("Generating the data"); final int N = 2000; final int universe = 1000000; RoaringBitmap[] b = new RoaringBitmap[N]; for (int k = 0; k < b.length; ++k) { b[k] = new RoaringBitmap(); b[k].flip(0,k+1); } for (TopK t : Top) { System.out.println("benchmarking " + t.name()); System.out.println("dry run... "); for (int time = 0; time < 3; ++time) // JIT for (int threshVal = 1; threshVal <= 10; ++threshVal) { if(t.top(threshVal, universe,b).getCardinality()!=threshVal) throw new RuntimeException("bug"); } System.out.println("actual benchmark... "); for (int k = 0; k < 3; ++k) { long bef = System.currentTimeMillis(); for (int time = 0; time < 3; ++time) for (int threshVal = 1; threshVal <= 10; ++threshVal) { if(t.top(threshVal, universe,b).getCardinality()!=threshVal) throw new RuntimeException("bug"); } long aft = System.currentTimeMillis(); System.out.println(t.name() + " time : " + (aft - bef)); } } } }
37.854167
86
0.539351
52e214b4b81c728c2904542e6fe736ee63555ef8
704
package cn.zhenly.lftp.cmd; class Util { static int getPortFromData(byte[] data) { String str = new String(data); if (str.substring(0, 4).equals("BUYS")) { System.out.println("[ERROR] Server is buys now"); return -1; } if (!str.substring(0, 4).equals("PORT")) { System.out.println("[ERROR] System error!"); return -1; } int port = -1; try { port = Integer.parseInt(str.substring(4)); } catch (NumberFormatException e) { e.printStackTrace(); } if (port == -1) { System.out.println("[INFO] Can't get port from " + str); } else { System.out.println("[INFO] Get send port: " + port); } return port; } }
25.142857
62
0.566761
fabdf706c0dd50f2285ba4e2f49690553fc76539
4,770
package com.qxcmp.shoppingmall; import com.google.common.collect.Sets; import com.qxcmp.core.entity.AbstractEntityService; import com.qxcmp.core.support.IDGenerator; import com.qxcmp.user.UserService; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.context.ApplicationContext; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Date; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Supplier; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; /** * 平台券服务 * <p> * 支持以下服务 <ol> <li>查询用户领取券的信息</li> <li>为用户领取券</li> <li>批量发布券</li> </ol> * * @author aaric */ @Service @RequiredArgsConstructor public class OfferService extends AbstractEntityService<Offer, String, OfferRepository> { private final UserService userService; private final ApplicationContext applicationContext; public Page<Offer> findByUserId(String userId, Pageable pageable) { return repository.findByUserIdOrderByDateReceivedDesc(userId, pageable); } /** * 平台发布券统一接口,商户通用一个券原型来发布 * <p> * 要获取或者领取券,需要根据券的类型和名称获取 * * @param prototype 券原型 * @param quantity 要发布的券的数量 * * @return 发布券以后的ID */ public Set<String> publish(Consumer<Offer> prototype, int quantity) { checkArgument(quantity > 0, "Offer quantity must great than 0"); Offer offer = next(); prototype.accept(offer); checkState(StringUtils.isNotBlank(offer.getName()), "Offer name can't be empty"); checkState(StringUtils.isNotBlank(offer.getType()), "Offer type can't be empty"); checkState(StringUtils.isNotBlank(offer.getVendorID()), "Offer vendor can't be empty"); checkState(Objects.nonNull(offer.getDateStart()), "Offer start date can't be empty"); checkState(Objects.nonNull(offer.getDateEnd()), "Offer end date can't be empty"); checkState(offer.getDateEnd().getTime() - offer.getDateStart().getTime() > 0, "Offer end date must great than start date"); Set<String> offerIds = Sets.newHashSet(); for (int i = 0; i < quantity; i++) { Offer o = create(() -> { offer.setId(null); return offer; }); offerIds.add(o.getId()); } return offerIds; } /** * 平台领券统一接口 * <p> * 当用户存在,且券还没有被领取的时候才进行领取操作 * * @param userId 用户ID * @param offerId 券ID * * @return 领取后的券,如果领取失败返回空 */ public Optional<Offer> pick(String userId, String offerId) { return userService.findOne(userId).map(user -> { Optional<Offer> offerOptional = findOne(offerId); if (!offerOptional.isPresent() || StringUtils.isNotBlank(offerOptional.get().getUserId())) { return null; } return update(offerId, offer -> { offer.setUserId(userId); offer.setStatus(OfferStatus.PICKED); offer.setDateReceived(new Date()); }); }); } /** * 使用一个券 * <p> * 若成功使用一个券,会发出券使用事件 * * @param userId 使用券的用户ID * @param offerId 使用的券ID * * @return 券是否使用成功 */ public void comsume(String userId, String offerId) throws Exception { Optional<Offer> offerOptional = findOne(offerId); if (!offerOptional.isPresent()) { throw new Exception("券不存在"); } Offer offer = offerOptional.get(); if (!offer.getStatus().equals(OfferStatus.PICKED)) { throw new Exception("无效的券状态:" + offer.getStatus().getValue()); } if (!StringUtils.equals(userId, offer.getUserId())) { throw new Exception("券的领取用户不一致"); } if (System.currentTimeMillis() - offer.getDateEnd().getTime() > 0) { update(offer.getId(), o -> o.setStatus(OfferStatus.EXPIRED)); throw new Exception("券已过期"); } applicationContext.publishEvent(new OfferEvent(update(offer.getId(), o -> { o.setDateUsed(new Date()); o.setStatus(OfferStatus.USED); }))); } @Override public Offer create(Supplier<Offer> supplier) { Offer entity = supplier.get(); if (StringUtils.isNotEmpty(entity.getId())) { return null; } entity.setId(IDGenerator.next()); entity.setDateCreated(new Date()); entity.setStatus(OfferStatus.NEW); return super.create(() -> entity); } }
30.189873
131
0.630398
3e275db01c77ee4a1a0151a3642f13201ed7ae21
3,844
/******************************************************************************* * Copyright (c) 2004, 2009 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.data.ui.dataset; import java.math.BigDecimal; import java.util.Date; import java.util.List; import org.eclipse.birt.report.engine.api.IEngineTask; import org.eclipse.birt.report.model.api.DynamicFilterParameterHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; /** * */ public class ReportParameterUtil { public static void completeParamDefalutValues( IEngineTask engineTask, ModuleHandle moduleHandle ) { List paramsList = moduleHandle.getAllParameters( ); for ( int i = 0; i < paramsList.size( ); i++ ) { Object parameterObject = paramsList.get( i ); if ( parameterObject instanceof ScalarParameterHandle ) { ScalarParameterHandle parameterHandle = (ScalarParameterHandle) parameterObject; if ( ( parameterHandle.getDefaultValueList( ) == null || parameterHandle.getDefaultValueList( ).size( ) == 0) && ( parameterHandle.getDefaultValueListMethod( ) == null || parameterHandle.getDefaultValueListMethod( ).trim( ).length( ) == 0 )) { String paramType = parameterHandle.getParamType( ); if ( DesignChoiceConstants.SCALAR_PARAM_TYPE_MULTI_VALUE.equals( paramType ) ) { engineTask.setParameter( parameterHandle.getName( ), new Object[]{ getDummyDefaultValue( parameterHandle ) }, parameterHandle.getDisplayName( ) ); } else // no default value in handle engineTask.setParameter( parameterHandle.getName( ), getDummyDefaultValue( parameterHandle ), parameterHandle.getDisplayName( ) ); } } else if ( parameterObject instanceof DynamicFilterParameterHandle ) { List defaultValue = ( (DynamicFilterParameterHandle) parameterObject ).getDefaultValueList( ); if ( defaultValue == null || defaultValue.size( ) == 0 ) { //no default value in handle engineTask.setParameter( ( (DynamicFilterParameterHandle) parameterObject ).getName( ), "true", ( (DynamicFilterParameterHandle) parameterObject ).getDisplayName( ) ); } } } } public static Object getDummyDefaultValue( ScalarParameterHandle parameterHandle ) { String type = parameterHandle.getDataType( ); // No default value; if param allows null value, null is used if ( !parameterHandle.isRequired( ) ) return null; // Return a fixed default value appropriate for the data type if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) ) return ""; if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) ) return new Double( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type ) ) return new BigDecimal( (double) 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) ) return new Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_DATE.equals( type ) ) return new java.sql.Date( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_TIME.equals( type ) ) return new java.sql.Time( 0 ); if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) ) return Boolean.FALSE; if ( DesignChoiceConstants.PARAM_TYPE_INTEGER.equals( type ) ) return Integer.valueOf( 0 ); return null; } }
36.961538
99
0.691727
b5c851f490f7eaa37ab1e346d7e2c85725f34ef9
1,148
package cn.oauth.open.cache; import cn.oauth.open.cache.vo.CodeCacheVo; public class Cache { private String key;// 缓存ID private CodeCacheVo value;// 缓存数据 private long createTime;// 缓存开始时间 private long cacheTime;// 缓存时间 public Cache() { super(); } public Cache(String key, CodeCacheVo value, long createTime) { this.key = key; this.value = value; this.createTime = createTime; } public String getKey() { return key; } public long getCreateTime() { return createTime; } public Object getValue() { return value; } public void setKey(String string) { key = string; } public void setCreateTime(long l) { createTime = l; } public void setValue(CodeCacheVo vo) { value = vo; } public void setCacheTime(long cacheTime) { this.cacheTime = cacheTime; } public long getCacheTime() { return cacheTime; } @Override public String toString() { StringBuffer sb = new StringBuffer("Cache ["); sb.append("key=").append(key) .append(",value=").append(value) .append(",createTime=").append(createTime) .append(",cacheTime=").append(cacheTime) .append("]"); return sb.toString(); } }
18.516129
63
0.678571
8e17fe6d4878147d945cb2de106c7b1b7c8fe16d
7,986
/* * 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.netbeans.modules.java.platform; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.security.CodeSource; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import org.netbeans.api.annotations.common.CheckForNull; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.annotations.common.NullAllowed; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.platform.JavaPlatform; import org.netbeans.api.java.platform.Specification; import org.netbeans.spi.java.classpath.support.ClassPathSupport; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.modules.Dependency; import org.openide.modules.SpecificationVersion; import org.openide.util.NbCollections; import org.openide.util.Utilities; /** * Basic impl in case no other providers can be found. * @author Jesse Glick * @author Tomas Zezula */ public final class FallbackDefaultJavaPlatform extends JavaPlatform { private static final Logger LOG = Logger.getLogger(FallbackDefaultJavaPlatform.class.getName()); private static final Map<String,String> JAVADOC_URLS; static { final Map<String,String> m = new HashMap<>(); m.put("1.5", "https://docs.oracle.com/javase/1.5.0/docs/api/"); // NOI18N m.put("1.6", "https://docs.oracle.com/javase/6/docs/api/"); // NOI18N m.put("1.7", "https://docs.oracle.com/javase/7/docs/api/"); // NOI18N m.put("1.8", "https://docs.oracle.com/javase/8/docs/api/"); // NOI18N JAVADOC_URLS = Collections.unmodifiableMap(m); } private static FallbackDefaultJavaPlatform instance; private volatile List<URL> javadoc; private volatile ClassPath src; private FallbackDefaultJavaPlatform() { setSystemProperties(NbCollections.checkedMapByFilter(System.getProperties(), String.class, String.class, false)); } @Override public String getDisplayName() { return System.getProperty("java.vm.vendor") + " " + System.getProperty("java.vm.version"); // NOI18N } @Override public Map<String,String> getProperties() { return Collections.singletonMap("platform.ant.name", "default_platform"); } private static ClassPath sysProp2CP(String propname) { String sbcp = System.getProperty(propname); if (sbcp == null) { return null; } List<URL> roots = new ArrayList<>(); StringTokenizer tok = new StringTokenizer(sbcp, File.pathSeparator); while (tok.hasMoreTokens()) { File f = new File(tok.nextToken()); if (!f.exists()) { continue; } URL u; try { File normf = FileUtil.normalizeFile(f); u = Utilities.toURI(normf).toURL(); } catch (MalformedURLException x) { throw new AssertionError(x); } if (FileUtil.isArchiveFile(u)) { u = FileUtil.getArchiveRoot(u); } roots.add(u); } return ClassPathSupport.createClassPath(roots.toArray(new URL[roots.size()])); } private static ClassPath sampleClass2CP(Class prototype) { CodeSource cs = prototype.getProtectionDomain().getCodeSource(); return ClassPathSupport.createClassPath(cs != null ? new URL[] {cs.getLocation()} : new URL[0]); } @Override public ClassPath getBootstrapLibraries() { // XXX ignore standard extensions etc. ClassPath cp = sysProp2CP("sun.boot.class.path"); // NOI18N return cp != null ? cp : sampleClass2CP(Object.class); } @Override public ClassPath getStandardLibraries() { ClassPath cp = sysProp2CP("java.class.path"); // NOI18N return cp != null ? cp : sampleClass2CP(/* likely in startup CP */ Dependency.class); } @Override public String getVendor() { return System.getProperty("java.vm.vendor"); } @Override public Specification getSpecification() { return new Specification(/*J2SEPlatformImpl.PLATFORM_J2SE*/"j2se", Dependency.JAVA_SPEC); // NOI18N } @Override public Collection<FileObject> getInstallFolders() { return Collections.singleton(FileUtil.toFileObject(FileUtil.normalizeFile(new File(System.getProperty("java.home"))))); // NOI18N } @Override public FileObject findTool(String toolName) { return null; // XXX too complicated, probably unnecessary for this purpose } @Override public ClassPath getSourceFolders() { ClassPath res = src; if (res == null) { res = src = ClassPathSupport.createClassPath( getSources(getInstallFolders())); } return res; } @Override public List<URL> getJavadocFolders() { List<URL> res = javadoc; if (res == null) { final SpecificationVersion version = getSpecification().getVersion(); final URL root = toURL(JAVADOC_URLS.get(version.toString())); res = javadoc = root == null ? Collections.<URL>emptyList() : Collections.<URL>singletonList(root); } return res; } @NonNull private static FileObject[] getSources(@NonNull final Collection<? extends FileObject> installFolders) { if (installFolders.isEmpty()) { return new FileObject[0]; } final FileObject installFolder = installFolders.iterator().next(); if (installFolder == null || !installFolder.isValid()) { return new FileObject[0]; } FileObject src = installFolder.getFileObject("src.zip"); //NOI18N if (src == null) { src = installFolder.getFileObject("src.jar"); //NOI18N } if (src == null || !src.canRead()) { return new FileObject[0]; } FileObject root = FileUtil.getArchiveRoot(src); if (root == null) { return new FileObject[0]; } if (Utilities.getOperatingSystem() == Utilities.OS_MAC) { FileObject reloc = root.getFileObject("src"); //NOI18N if (reloc != null) { root = reloc; } } return new FileObject[]{root}; } @CheckForNull private static URL toURL(@NullAllowed final String root) { if (root == null) { return null; } try { return new URL (root); } catch (MalformedURLException e) { LOG.log( Level.WARNING, "Invalid Javadoc root: {0}", //NOI18N root); return null; } } public static synchronized FallbackDefaultJavaPlatform getInstance() { if (instance == null) { instance = new FallbackDefaultJavaPlatform(); } return instance; } }
35.180617
137
0.641498
fead08213e03ddf6f5dd3e831dd97c87121d8506
4,919
/* * Copyright 2018-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.parser.implicit; import com.facebook.buck.io.file.MorePaths; import com.google.common.collect.ImmutableMap; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import javax.annotation.Nullable; /** * Given a configuration, find packages that should be implicitly included for a given build file */ public class PackageImplicitIncludesFinder { private final IncludeNode node; /** * Simple class that contains mappings to implicit includes that should be used for a given * package (and all subpackages), and mappings to other includes that should be used for further * nested subpackages. */ private static class IncludeNode { final ImmutableMap<Path, IncludeNode> childPackages; final Optional<ImplicitInclude> include; IncludeNode(ImmutableMap<Path, IncludeNode> childPackages, Optional<ImplicitInclude> include) { this.childPackages = childPackages; this.include = include; } /** * Gets the include for the deepest matching path of the tree. * * <p>If there are settings for foo, and foo/bar, then foo/bar/baz should return the settings * for foo/bar. If not_foo is specified, then the root settings should be returned. */ Optional<ImplicitInclude> findIncludeForPath(Path packagePath) { IncludeNode currentNode = this; Optional<ImplicitInclude> lastPresentInclude = currentNode.include; for (Path component : packagePath) { IncludeNode childNode = currentNode.childPackages.get(component); if (childNode == null) { return lastPresentInclude; } else { if (childNode.include.isPresent()) { lastPresentInclude = childNode.include; } currentNode = childNode; } } return lastPresentInclude; } } /** Builder class to create {@link IncludeNode} instances */ private static class IncludeNodeBuilder { private Map<Path, IncludeNodeBuilder> nodes = new HashMap<>(); private Optional<ImplicitInclude> include = Optional.empty(); /** Creates a node at a subpath, or returns the existing builder */ IncludeNodeBuilder getOrCreateIncludeNodeForPath(Path path) { return nodes.computeIfAbsent(path, p -> new IncludeNodeBuilder()); } void setInclude(ImplicitInclude include) { this.include = Optional.of(include); } IncludeNode build() { return new IncludeNode( nodes.entrySet().stream() .collect(ImmutableMap.toImmutableMap(Entry::getKey, e -> e.getValue().build())), include); } } private PackageImplicitIncludesFinder(ImmutableMap<String, ImplicitInclude> packageToInclude) { IncludeNodeBuilder rootBuilder = new IncludeNodeBuilder(); for (Map.Entry<String, ImplicitInclude> entry : packageToInclude.entrySet()) { Path path = Paths.get(entry.getKey()); IncludeNodeBuilder currentBuilder = rootBuilder; for (Path component : path) { if (component.toString().isEmpty()) { continue; } currentBuilder = currentBuilder.getOrCreateIncludeNodeForPath(component); } currentBuilder.setInclude(entry.getValue()); } node = rootBuilder.build(); } /** * Create a {@link PackageImplicitIncludesFinder} from configuration in .buckconfig * * @param packageToInclude A mapping of package paths to file that should be included * @return A {@link PackageImplicitIncludesFinder} instance */ public static PackageImplicitIncludesFinder fromConfiguration( ImmutableMap<String, ImplicitInclude> packageToInclude) { return new PackageImplicitIncludesFinder(packageToInclude); } /** * Find the file (if any) that should be included implicitly for a given build file path * * @param packagePath The path to a package relative to the cell root. * @return The path to a file and symbols that should be implicitly included for the given * package. */ public Optional<ImplicitInclude> findIncludeForBuildFile(@Nullable Path packagePath) { if (packagePath == null) { packagePath = MorePaths.EMPTY_PATH; } return node.findIncludeForPath(packagePath); } }
36.169118
99
0.708884
1c3851c2970f172c351e2b787bd91f512c9aa70b
1,473
package com.project.backend.controller; import com.project.backend.dto.ApplicationDto; import com.project.backend.service.ApplicationService; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @CrossOrigin @Slf4j @RestController @RequestMapping("/api/v1/applications") public class ApplicationController { private final ApplicationService applicationService; @Autowired public ApplicationController(ApplicationService applicationService) { this.applicationService = applicationService; } @ApiOperation(value = "List all applications.") @GetMapping public ResponseEntity<List<ApplicationDto>> getAll(){ log.info("Controller: Request to list all applications"); return new ResponseEntity<>(applicationService.getAll(), HttpStatus.OK); } @ApiOperation(value = "Get application by identity number.") @GetMapping("/get-status/{identiyNumber}") public ResponseEntity<ApplicationDto> getStatus(@PathVariable("identiyNumber") String identiyNumber){ log.info("Controller: Request to fetch application with identity number information"); return new ResponseEntity<>(applicationService.getStatus(identiyNumber), HttpStatus.OK); } }
34.255814
105
0.77461
fe2ecb5397f3d096321f4546088aa7754ee4bcef
1,181
package io.art.transport.allocator; import io.art.transport.configuration.*; import io.netty.buffer.*; import lombok.experimental.*; import static io.art.core.checker.ModuleChecker.*; import static io.netty.buffer.ByteBufAllocator.*; @UtilityClass public class WriteBufferAllocator { public static ByteBuf allocateWriteBuffer(TransportModuleConfiguration configuration) { if (!withTransport()) return DEFAULT.ioBuffer(); int writeBufferInitialCapacity = configuration.getWriteBufferInitialCapacity(); int writeBufferMaxCapacity = configuration.getWriteBufferMaxCapacity(); switch (configuration.getWriteBufferType()) { case DEFAULT: return DEFAULT.buffer(writeBufferInitialCapacity, writeBufferMaxCapacity); case HEAP: return DEFAULT.heapBuffer(writeBufferInitialCapacity, writeBufferMaxCapacity); case IO: return DEFAULT.ioBuffer(writeBufferInitialCapacity, writeBufferMaxCapacity); case DIRECT: return DEFAULT.directBuffer(writeBufferInitialCapacity, writeBufferMaxCapacity); } return DEFAULT.ioBuffer(); } }
42.178571
96
0.722269
054b3483586ba726589f5ca79dd8ada6063cd98c
1,961
/* * File created on Mar 23, 2016 * * Copyright (c) 2016 Carl Harris, Jr * and others as noted * * 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.soulwing.prospecto.api.listener; /** * An interceptor that is notified as property values are visited during * view generation or view application. * * @author Carl Harris */ public interface ViewNodePropertyInterceptor extends ViewListener { /** * Notifies the recipient that a value has been extracted from a model * for use as the value of a view node in a view. * <p> * The recipient can pass the value unchanged or replace the value. * @param event the subject event * @return the value to use to replace of the subject value; if the handler * does not wish to change the value it <em>must</em> return the * {@linkplain ViewNodePropertyEvent#getValue() subject value}. */ Object didExtractValue(ViewNodePropertyEvent event); /** * Notifies the recipient that a value will be injected into a model from * a view node associated with a view. * <p> * The recipient can pass the value unchanged or replace the value. * @param event the subject event * @return the value to use to replace of the subject value; if the handler * does not wish to change the value it <em>must</em> return the * {@linkplain ViewNodePropertyEvent#getValue() subject value}. */ Object willInjectValue(ViewNodePropertyEvent event); }
36.314815
77
0.72361
8557f715e218a8ba276fc4cacb11fbc2e2d6e331
1,894
package com.kdl.rf.modules.sys.controller; import com.kdl.rf.common.controller.BaseController; import com.kdl.rf.common.dto.R; import com.kdl.rf.modules.sys.entity.UserRole; import com.kdl.rf.modules.sys.service.IUserRoleService; import com.kdl.rf.modules.sys.vo.UserRoleVO; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.List; /** * <p> * 用户与角色对应关系 前端控制器 * </p> * * @author Kalvin * @since 2019-04-29 */ @RestController @RequestMapping("sys/userRole") public class UserRoleController extends BaseController { @Autowired private IUserRoleService userRoleService; @GetMapping(value = "index") public ModelAndView index() { return new ModelAndView("sys/user_role"); } /** * 角色成员列表数据接口 * @param userRole 参数 * @return r */ @GetMapping(value = "list/data") public R listData(UserRole userRole) { return R.ok(userRoleService.listUserRolePage(userRole)); } @RequiresPermissions("sys:userRole:add") @PostMapping(value = "save") public R save(UserRoleVO userRoleVO) { userRoleService.saveOrUpdateBatchUserRole(userRoleVO); return R.ok(); } @RequiresPermissions("sys:userRole:del") @PostMapping(value = "removeBatch") public R removeBatch(@RequestParam("ids") List<Long> ids) { userRoleService.removeByIds(ids); return R.ok(); } @GetMapping(value = "count") public R count(Long roleId) { return R.ok(userRoleService.countUserRoleByRoleId(roleId)); } @GetMapping(value = "get/roleNames/{userId}") public R getRoleNames(@PathVariable Long userId) { return R.ok(userRoleService.getRoleNamesByUserId(userId)); } }
26.305556
67
0.700634
e6aeca43f5c85b7e01f60dddd26810879aa108c4
795
package com.devworks.askmeanything.controllers; import com.devworks.askmeanything.models.data.Profile; import com.devworks.askmeanything.repositories.ProfileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Optional; @RestController @RequestMapping("/api/profile") public class ProfileController { @Autowired ProfileRepository profileRepository; @GetMapping("/{userId}") public Optional<Profile> GetUserProfile(@PathVariable String userId) { return profileRepository.findById(userId); } @PutMapping("/{userId}") public Profile UpdateUserProfile(@PathVariable String userId, @RequestBody Profile profile) { return profileRepository.save(profile); } }
29.444444
97
0.774843
54829fe9c50f4d411a44ba782e0434f5b17ff74d
106
package com.couchbase.dbdownloadexample; public interface DownloaderListener { void onCompleted(); }
17.666667
40
0.792453
d85e64f004946bec025a58266e12fb3d24c08c2e
2,073
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ /** * <copyright> * Copyright 1997-2002 BBNT Solutions, LLC * under sponsorship of the Defense Advanced Research Projects Agency (DARPA). * * This program is free software; you can redistribute it and/or modify * it under the terms of the Cougaar Open Source License as published by * DARPA on the Cougaar Open Source Website (www.cougaar.org). * * THE COUGAAR SOFTWARE AND ANY DERIVATIVE SUPPLIED BY LICENSOR IS * PROVIDED 'AS IS' WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR * IMPLIED, INCLUDING (BUT NOT LIMITED TO) ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND WITHOUT * ANY WARRANTIES AS TO NON-INFRINGEMENT. IN NO EVENT SHALL COPYRIGHT * HOLDER BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE OF DATA OR PROFITS, * TORTIOUS CONDUCT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE COUGAAR SOFTWARE. * </copyright> * * Created on Aug 26, 2002 */ package net.sourceforge.pmd.stat; import java.util.List; import net.sourceforge.pmd.FooRule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.rule.stat.StatisticalRule; import net.sourceforge.pmd.lang.rule.stat.StatisticalRuleHelper; public class MockStatisticalRule extends FooRule implements StatisticalRule { private StatisticalRuleHelper helper; public MockStatisticalRule() { helper = new StatisticalRuleHelper(this); } @Override public String getName() { return this.getClass().getName(); } @Override public void apply(List<? extends Node> nodes, RuleContext ctx) { super.apply(nodes, ctx); helper.apply(ctx); } @Override public void addDataPoint(DataPoint point) { helper.addDataPoint(point); } @Override public Object[] getViolationParameters(DataPoint point) { return null; } }
31.409091
79
0.726001
0d8a425c0d7d8053704f67b998759e20068586ed
4,033
package myessentials.deploader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; public class Downloader { private final ByteBuffer downloadBuffer = ByteBuffer.allocateDirect(1 << 23); private File destinationFolder; public Downloader(File destinationFolder) { this.destinationFolder = destinationFolder; if (!this.destinationFolder.exists()) { this.destinationFolder.mkdirs(); } } public void load(Dependency dep) { if (!checkExisting(dep)) { download(dep); } } // Returns true if dep exists, false if it doesn't private boolean checkExisting(Dependency dep) { VersionedFile vFile; File[] files = destinationFolder.listFiles(); if (files == null) return false; for (File f : files) { vFile = new VersionedFile(f.getName(), dep.getFile().getPattern()); if (!vFile.matches() || !vFile.getName().equals(dep.getName())) continue; int cmp = vFile.getVersion().compareTo(dep.getVersion()); if (cmp < 0) { System.out.println("[MyEssentials-Core] Deleted old version " + f.getName()); deleteDep(f); return false; } if (cmp > 0) { System.out.println("[MyEssentials-Core] Warning: version of " + dep.getName() + ", " + vFile.getVersion() + " is newer than request " + dep.getVersion()); } return true; } return false; } private void deleteDep(File depFile) { if (!depFile.delete()) { depFile.deleteOnExit(); System.out.println("[MyEssentials-Core] Was not able to delete file " + depFile.getPath() + ". Will try to delete on exit."); System.exit(1); } } private void download(Dependency dep) { File depFile = new File(destinationFolder, dep.getFile().getFilename()); try { String baseURL = dep.getUrl(); if (!baseURL.endsWith("/")) { baseURL += "/"; } URL depURL = new URL(baseURL + dep.getFile().getFilename()); System.out.println("Downloading file " + depURL.toString()); URLConnection connection = depURL.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestProperty("User-Agent", "MyEssentials-Core Downloader"); int sizeGuess = connection.getContentLength(); download(connection.getInputStream(), sizeGuess, depFile); System.out.println("Download Complete"); } catch (Exception e) { e.printStackTrace(); } } private void download(InputStream is, int sizeGuess, File target) throws Exception { if (sizeGuess > downloadBuffer.capacity()) throw new Exception(String.format("The file %s is too large to be downloaded - the download is invalid", target.getName())); downloadBuffer.clear(); int bytesRead, fullLength = 0; try { byte[] smallBuffer = new byte[1024]; while((bytesRead = is.read(smallBuffer)) >= 0) { downloadBuffer.put(smallBuffer, 0, bytesRead); fullLength += bytesRead; } is.close(); downloadBuffer.limit(fullLength); downloadBuffer.position(0); } catch (IOException e) { e.printStackTrace(); } try { if (!target.exists()) target.createNewFile(); downloadBuffer.position(0); FileOutputStream fos = new FileOutputStream(target); fos.getChannel().write(downloadBuffer); fos.close(); } catch (Exception e) { throw e; } } }
33.608333
170
0.575254
7ab926d848067692e399887ee7eedac6fa0b224d
4,123
/* * Copyright 2017, Harsha R. * * 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 gov.sanjoseca.programs.walknroll.internal.config; import com.google.appengine.api.datastore.Query.Filter; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; import gov.sanjoseca.programs.walknroll.objectify.PersistentDataManager; import gov.sanjoseca.programs.walknroll.rest.MissingParameterException; import gov.sanjoseca.programs.walknroll.rest.PaginatedResponse; import io.swagger.annotations.Api; import org.apache.commons.lang3.StringUtils; import javax.faces.bean.ApplicationScoped; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import java.util.List; /** * Application configuration. */ // TODO: Protect this API endpoint. @Api @Path("/v1/admin/config") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @ApplicationScoped public class ApplicationConfiguration { private static final ApplicationConfiguration INSTANCE = new ApplicationConfiguration(); /** * Convenience method to get hold of an instance of this class. * * @return an instance of <code>ApplicationConfiguration</code>. */ public static ApplicationConfiguration getInstance() { return INSTANCE; } @GET public PaginatedResponse<ConfigData> getConfigurations(@QueryParam("page") @DefaultValue("1") int page, @QueryParam("pageSize") @DefaultValue("100") int pageSize, @Context UriInfo uriInfo) { int offset = (page - 1) * pageSize; List<ConfigData> results = PersistentDataManager.getInstance(ConfigData.class).getItems(offset, pageSize, null); return new PaginatedResponse<>(results, page, pageSize, results.size(), uriInfo); } @GET @Path("/{name}") public ConfigData getConfiguration(@PathParam("name") String name) { Filter filter = new FilterPredicate("key", FilterOperator.EQUAL, name); return PersistentDataManager.getInstance(ConfigData.class).getItemByFilter(filter); } @POST public void setConfiguration(ConfigData data) { if (data == null) { throw new MissingParameterException("No content provided.", null); } ConfigData entry = getConfiguration(data.getKey()); if (entry != null) { entry.setValue(data.getValue()); } else { entry = data; } PersistentDataManager.getInstance(ConfigData.class).persist(entry); } /** * Convenience method to get hold of application properties. * * @param key the property key. * @param raiseExceptionIfNull set it to true if an exception should be raised if the value is null. * @return the value. * @throws IllegalStateException if the value was null and raiseExceptionIfNull parameter was set to true. */ public String getApplicationConfiguration(String key, boolean raiseExceptionIfNull) { ConfigData configData = ApplicationConfiguration.getInstance().getConfiguration(key); String value = configData != null ? configData.getValue() : null; if (StringUtils.isEmpty(value) && raiseExceptionIfNull) { throw new IllegalStateException("Unable to process task. Value for " + key + " was null. Please specify a valid value."); } return value; } }
38.53271
120
0.691002
52220cef2e08ba2a8d2238b9205421be2849d98c
818
package org.firstinspires.ftc.teamcode.robots.reach.utils; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DistanceSensor; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; @TeleOp(name="Distance Sensor Test") public class DistanceSensorTest extends LinearOpMode { DistanceSensor chassisLengthSensor = null; @Override public void runOpMode() throws InterruptedException { chassisLengthSensor = hardwareMap.get(DistanceSensor.class, "distLength"); waitForStart(); while(opModeIsActive()) { telemetry.addData("chassis length (m)", chassisLengthSensor.getDistance(DistanceUnit.METER)); telemetry.update(); } } }
31.461538
105
0.749389
17dca630a8d302342a1a5ffe7fe362276bf7da03
3,963
/******************************************************************************* * Copyright (c) 2008, 2013 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.pde.api.tools.ui.internal; import org.eclipse.jface.resource.CompositeImageDescriptor; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; /** * A main icon and several adornments. The adornments are computed according to * flags set on creation of the descriptor. */ public class ApiImageDescriptor extends CompositeImageDescriptor { /** Flag to render the error (red x) adornment */ public static final int ERROR = 0x0001; /** Flag to render the success (green check mark) adornment */ public static final int SUCCESS = 0x0002; private ImageDescriptor fBaseImage; private int fFlags; private Point fSize; /** * Create a new composite image. * * @param baseImage an image descriptor used as the base image * @param flags flags indicating which adornments are to be rendered * */ public ApiImageDescriptor(ImageDescriptor baseImage, int flags) { setBaseImage(baseImage); setFlags(flags); } /** * @see CompositeImageDescriptor#getSize() */ @Override protected Point getSize() { if (fSize == null) { ImageData data = getBaseImage().getImageData(); setSize(new Point(data.width, data.height)); } return fSize; } /** * @see Object#equals(java.lang.Object) */ @Override public boolean equals(Object object) { if (!(object instanceof ApiImageDescriptor)) { return false; } ApiImageDescriptor other = (ApiImageDescriptor) object; return (getBaseImage().equals(other.getBaseImage()) && getFlags() == other.getFlags()); } /** * @see Object#hashCode() */ @Override public int hashCode() { return getBaseImage().hashCode() | getFlags(); } /** * @see CompositeImageDescriptor#drawCompositeImage(int, int) */ @Override protected void drawCompositeImage(int width, int height) { ImageData bg = getBaseImage().getImageData(); if (bg == null) { bg = DEFAULT_IMAGE_DATA; } drawImage(bg, 0, 0); drawOverlays(); } private ImageData getImageData(String imageDescriptorKey) { return ApiUIPlugin.getImageDescriptor(imageDescriptorKey).getImageData(); } /** * Add any overlays to the image as specified in the flags. */ protected void drawOverlays() { int flags = getFlags(); int x = 0; int y = 0; ImageData data = null; if ((flags & ERROR) != 0) { x = 0; y = getSize().y; data = getImageData(IApiToolsConstants.IMG_OVR_ERROR); y -= data.height; drawImage(data, x, y); } else if ((flags & SUCCESS) != 0) { x = 0; y = getSize().y; data = getImageData(IApiToolsConstants.IMG_OVR_SUCCESS); y -= data.height; drawImage(data, x, y); } } protected ImageDescriptor getBaseImage() { return fBaseImage; } protected void setBaseImage(ImageDescriptor baseImage) { fBaseImage = baseImage; } protected int getFlags() { return fFlags; } protected void setFlags(int flags) { fFlags = flags; } protected void setSize(Point size) { fSize = size; } }
28.307143
95
0.601564
fc9f33b10758b799bcbec736265fcdae6d26360c
3,537
package com.tm.kafka.connect.rest.http.payload.templated; import org.apache.kafka.common.config.AbstractConfig; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigDef.Importance; import org.apache.kafka.common.config.ConfigDef.Type; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class RegexResponseValueProviderConfig extends AbstractConfig { public static final String RESPONSE_VAR_NAMES_CONFIG = "rest.source.response.var.names"; private static final String RESPONSE_VAR_NAMES_DOC = "A list of variable names to be used for substitution into the " + "HTTP request template. A regex must be defined for each variable and will be run against the HTTP response to " + "extract values for the next HTTP request."; private static final String RESPONSE_VAR_NAMES_DISPLAY = "Template variables for REST source connector."; @SuppressWarnings("unchecked") private static final List<String> RESPONSE_VAR_NAMES_DEFAULT = Collections.EMPTY_LIST; public static final String RESPONSE_VAR_REGEX_CONFIG = "rest.source.response.var.%s.regex"; private static final String RESPONSE_VAR_REGEX_DOC = "The regex used to extract the %s variable from the HTTP response. " + "This parameter can then be used in the next templated HTTP request."; private static final String RESPONSE_VAR_REGEX_DISPLAY = "Regex for %s variable for REST source connector."; private static final Object RESPONSE_VAR_REGEX_DEFAULT = ConfigDef.NO_DEFAULT_VALUE; private final Map<String, String> responseVariableRegexs; protected RegexResponseValueProviderConfig(ConfigDef config, Map<String, ?> unparsedConfig) { super(config, unparsedConfig); List<String> variableNames = getResponseVariableNames(); responseVariableRegexs = new HashMap<>(variableNames.size()); variableNames.forEach(key -> responseVariableRegexs.put(key, getString(String.format(RESPONSE_VAR_REGEX_CONFIG, key)))); } public RegexResponseValueProviderConfig(Map<String, ?> unparsedConfig) { this(conf(unparsedConfig), unparsedConfig); } public static ConfigDef conf(Map<String, ?> unparsedConfig) { String group = "REST_HTTP"; int orderInGroup = 0; ConfigDef config = new ConfigDef() .define(RESPONSE_VAR_NAMES_CONFIG, Type.LIST, RESPONSE_VAR_NAMES_DEFAULT, Importance.LOW, RESPONSE_VAR_NAMES_DOC, group, ++orderInGroup, ConfigDef.Width.SHORT, RESPONSE_VAR_NAMES_DISPLAY) ; // This is a bit hacky and there may be a better way of doing it, but I don't know it. // We need to create config items dynamically, based on the parameter names, // so we need a 2 pass parse of the config. @SuppressWarnings("unchecked") List<String> varNames = (List) config.parse(unparsedConfig).get(RESPONSE_VAR_NAMES_CONFIG); for(String varName : varNames) { config.define(String.format(RESPONSE_VAR_REGEX_CONFIG, varName), Type.STRING, RESPONSE_VAR_REGEX_DEFAULT, Importance.HIGH, String.format(RESPONSE_VAR_REGEX_DOC, varName), group, ++orderInGroup, ConfigDef.Width.SHORT, String.format(RESPONSE_VAR_REGEX_DISPLAY, varName)); } return(config); } public List<String> getResponseVariableNames() { return this.getList(RESPONSE_VAR_NAMES_CONFIG); } public Map<String, String> getResponseVariableRegexs() { return responseVariableRegexs; } }
38.868132
125
0.746395
f79d07e45d29ff0149c9e5311ceb91768a8d1a7e
10,442
package com.ctrip.xpipe.redis.console.migration.model.impl; import com.ctrip.xpipe.api.observer.Observable; import com.ctrip.xpipe.api.observer.Observer; import com.ctrip.xpipe.observer.AbstractObservable; import com.ctrip.xpipe.redis.console.migration.exception.MigrationUnderProcessingException; import com.ctrip.xpipe.redis.console.migration.model.MigrationCluster; import com.ctrip.xpipe.redis.console.migration.model.MigrationEvent; import com.ctrip.xpipe.redis.console.migration.model.MigrationLock; import com.ctrip.xpipe.redis.console.migration.status.MigrationStatus; import com.ctrip.xpipe.redis.console.model.MigrationEventTbl; import com.ctrip.xpipe.redis.console.service.migration.exception.ClusterNotFoundException; import com.ctrip.xpipe.utils.VisibleForTesting; import com.google.common.collect.Lists; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** * @author shyin * <p> * Dec 8, 2016 */ public class DefaultMigrationEvent extends AbstractObservable implements MigrationEvent, Observer { private MigrationEventTbl event; private MigrationLock migrationLock; private Map<Long, MigrationCluster> migrationClusters = new HashMap<>(); private AtomicBoolean running = new AtomicBoolean(false); public DefaultMigrationEvent(MigrationEventTbl event, MigrationLock migrationLock) { this.event = event; this.migrationLock = migrationLock; } @Override public MigrationEventTbl getEvent() { return event; } @Override public void process() throws Exception { List<MigrationCluster> localMigrationClusters = getMigrationClusters(); if (localMigrationClusters.isEmpty()) { logger.info("[process][{}][no cluster]{}", event.getId(), localMigrationClusters); return; } processCluster(localMigrationClusters.get(0)); } private boolean lockBeforeProcess() { if (!running.compareAndSet(false, true)) { logger.info("[lockBeforeProcess][{}] is running, skip", event.getId()); return false; } try { migrationLock.updateLock(); } catch (Throwable th) { logger.info("[lockBeforeProcess][{}] lock fail, skip", event.getId(), th); running.set(false); return false; } return true; } private void unlockAfterProcess() { migrationLock.releaseLock(); running.set(false); } @Override public long getMigrationEventId() { return event.getId(); } @Override public MigrationCluster getMigrationCluster(long clusterId) { return migrationClusters.get(clusterId); } @Override public MigrationCluster getMigrationCluster(String clusterName) { for(MigrationCluster migrationCluster : getMigrationClusters()){ if(migrationCluster.clusterName().equals(clusterName)){ return migrationCluster; } } return null; } private MigrationCluster tryGetMigrationCluster(long clusterId) throws ClusterNotFoundException { MigrationCluster migrationCluster = getMigrationCluster(clusterId); if(migrationCluster == null){ throw new ClusterNotFoundException(clusterId); } return migrationCluster; } private MigrationCluster tryGetMigrationCluster(String clusterName) throws ClusterNotFoundException { MigrationCluster migrationCluster = getMigrationCluster(clusterName); if(migrationCluster == null){ throw new ClusterNotFoundException(clusterName); } return migrationCluster; } private void allowAllClustersStart() { migrationClusters.values().forEach(cluster -> cluster.allowStart(true)); } private void allowOneClusterStart(long clusterId) { migrationClusters.forEach((id, cluster) -> cluster.allowStart(id.equals(clusterId))); } private void processCluster(MigrationCluster migrationCluster) throws Exception { if (!lockBeforeProcess()) throw new MigrationUnderProcessingException(getMigrationEventId()); allowAllClustersStart(); try { migrationCluster.start(); } catch (Exception e) { logger.info("[processCluster][{}] {} start fail", getMigrationEventId(), migrationCluster.clusterName(), e); unlockAfterProcess(); throw e; } } @Override public void processCluster(long clusterId) throws Exception { MigrationCluster migrationCluster = tryGetMigrationCluster(clusterId); processCluster(migrationCluster); } @Override public void cancelCluster(long clusterId) throws ClusterNotFoundException { MigrationCluster migrationCluster = tryGetMigrationCluster(clusterId); if (!lockBeforeProcess()) return; try { allowOneClusterStart(clusterId); migrationCluster.cancel(); } catch (Throwable th) { logger.info("[cancelCluster][{}][{}] fail", event.getId(), clusterId, th); unlockAfterProcess(); } } @Override public void forceClusterProcess(long clusterId) throws ClusterNotFoundException { MigrationCluster migrationCluster = tryGetMigrationCluster(clusterId); if (!lockBeforeProcess()) return; try { allowOneClusterStart(clusterId); migrationCluster.forceProcess(); } catch (Throwable th) { logger.info("[forceClusterProcess][{}][{}] fail", event.getId(), clusterId, th); unlockAfterProcess(); } } @Override public void forceClusterEnd(long clusterId) throws ClusterNotFoundException { MigrationCluster migrationCluster = tryGetMigrationCluster(clusterId); if (!lockBeforeProcess()) return; try { allowOneClusterStart(clusterId); migrationCluster.forceEnd(); } catch (Throwable th) { logger.info("[forceClusterEnd][{}][{}] fail", event.getId(), clusterId, th); unlockAfterProcess(); } } @Override public MigrationCluster rollbackCluster(long clusterId) throws ClusterNotFoundException { MigrationCluster migrationCluster = tryGetMigrationCluster(clusterId); if (!lockBeforeProcess()) return migrationCluster; allowOneClusterStart(clusterId); return rollbackCluster(migrationCluster); } @Override public MigrationCluster rollbackCluster(String clusterName) throws ClusterNotFoundException { MigrationCluster migrationCluster = tryGetMigrationCluster(clusterName); if (!lockBeforeProcess()) return migrationCluster; allowOneClusterStart(migrationCluster.getMigrationCluster().getClusterId()); return rollbackCluster(migrationCluster); } private MigrationCluster rollbackCluster(MigrationCluster migrationCluster) { try { migrationCluster.rollback(); } catch (Throwable th) { logger.info("[rollbackCluster][{}][{}] fail", event.getId(), migrationCluster.clusterName(), th); unlockAfterProcess(); } return migrationCluster; } @Override public List<MigrationCluster> getMigrationClusters() { return Lists.newLinkedList(migrationClusters.values()); } @Override public void addMigrationCluster(MigrationCluster migrationClsuter) { migrationClsuter.addObserver(this); migrationClusters.put(migrationClsuter.getMigrationCluster().getClusterId(), migrationClsuter); } @Override public void update(Object args, Observable observable) { if (args instanceof MigrationCluster) { if (((MigrationCluster) args).getStatus().isTerminated() || !((MigrationCluster) args).isStarted()) { // Submit next task according to policy processNext(); } } int finishedCnt = 0; int stopped = 0; int totalClusters = migrationClusters.size(); for (MigrationCluster cluster : migrationClusters.values()) { if (cluster.getStatus().isTerminated()) { ++finishedCnt; continue; } if (!cluster.isStarted()) { ++stopped; } } if (finishedCnt == totalClusters) { // migration done notifyObservers(this); } if (finishedCnt + stopped >= totalClusters) { unlockAfterProcess(); } } private void processNext() { for (MigrationCluster migrationCluster : migrationClusters.values()) { if (!migrationCluster.getStatus().isTerminated() && !MigrationStatus.RollBack.equals(migrationCluster.getStatus()) && !migrationCluster.isStarted()) { try { migrationCluster.start(); } catch (Exception e) { logger.info("[processNext][{}] {} start fail", getMigrationEventId(), migrationCluster.clusterName(), e); } } } } @Override public boolean isDone() { int successCnt = 0; List<MigrationCluster> migrationClusters = getMigrationClusters(); for (MigrationCluster cluster : migrationClusters) { if (cluster.getStatus().isTerminated()) { ++successCnt; } } if (successCnt == migrationClusters.size()) { // logger.info("[isDone][true]{}, success:{}", getMigrationEventId(), successCnt); return true; } return false; } @Override public boolean isRunning() { return running.get(); } @VisibleForTesting public void setMigrationLock(MigrationLock lock) { this.migrationLock = lock; } @VisibleForTesting public Map<Long, MigrationCluster> getMigrationClustersMap() { return migrationClusters; } @VisibleForTesting public void setMigrationClustersMap(Map<Long, MigrationCluster> migrationClusters) { this.migrationClusters = migrationClusters; } @Override public String toString() { return String.format("[eventId:%d]", getMigrationEventId()); } }
33.683871
125
0.650929
009dcab70eea29314c1cc74c13612439463bc845
6,344
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.runtime; import org.apache.lucene.document.StoredField; import org.apache.lucene.geo.GeoTestUtil; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreMode; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.script.AbstractLongFieldScript; import org.elasticsearch.script.GeoPointFieldScript; import org.elasticsearch.script.Script; import org.elasticsearch.search.lookup.SearchLookup; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.function.Function; import static org.hamcrest.Matchers.equalTo; public class GeoPointScriptFieldDistanceFeatureQueryTests extends AbstractScriptFieldQueryTestCase< GeoPointScriptFieldDistanceFeatureQuery> { private final Function<LeafReaderContext, AbstractLongFieldScript> leafFactory = ctx -> null; @Override protected GeoPointScriptFieldDistanceFeatureQuery createTestInstance() { double lat = GeoTestUtil.nextLatitude(); double lon = GeoTestUtil.nextLongitude(); double pivot = randomDouble() * GeoUtils.EARTH_EQUATOR; return new GeoPointScriptFieldDistanceFeatureQuery(randomScript(), leafFactory, randomAlphaOfLength(5), lat, lon, pivot); } @Override protected GeoPointScriptFieldDistanceFeatureQuery copy(GeoPointScriptFieldDistanceFeatureQuery orig) { return new GeoPointScriptFieldDistanceFeatureQuery( orig.script(), leafFactory, orig.fieldName(), orig.lat(), orig.lon(), orig.pivot() ); } @Override protected GeoPointScriptFieldDistanceFeatureQuery mutate(GeoPointScriptFieldDistanceFeatureQuery orig) { Script script = orig.script(); String fieldName = orig.fieldName(); double lat = orig.lat(); double lon = orig.lon(); double pivot = orig.pivot(); switch (randomInt(4)) { case 0: script = randomValueOtherThan(script, this::randomScript); break; case 1: fieldName += "modified"; break; case 2: lat = randomValueOtherThan(lat, GeoTestUtil::nextLatitude); break; case 3: lon = randomValueOtherThan(lon, GeoTestUtil::nextLongitude); break; case 4: pivot = randomValueOtherThan(pivot, () -> randomDouble() * GeoUtils.EARTH_EQUATOR); break; default: fail(); } return new GeoPointScriptFieldDistanceFeatureQuery(script, leafFactory, fieldName, lat, lon, pivot); } @Override public void testMatches() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"location\": [34, 6]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"location\": [-3.56, -45.98]}")))); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); SearchLookup searchLookup = new SearchLookup(null, null); Function<LeafReaderContext, AbstractLongFieldScript> leafFactory = ctx -> new GeoPointFieldScript( "test", Map.of(), searchLookup, ctx ) { final GeoPoint point = new GeoPoint(); @Override public void execute() { GeoUtils.parseGeoPoint(searchLookup.source().get("location"), point, true); emit(point.lat(), point.lon()); } }; GeoPointScriptFieldDistanceFeatureQuery query = new GeoPointScriptFieldDistanceFeatureQuery( randomScript(), leafFactory, "test", 0, 0, 30000 ); TopDocs td = searcher.search(query, 2); assertThat(td.scoreDocs[0].score, equalTo(0.0077678584F)); assertThat(td.scoreDocs[0].doc, equalTo(0)); assertThat(td.scoreDocs[1].score, equalTo(0.005820022F)); assertThat(td.scoreDocs[1].doc, equalTo(1)); } } } public void testMaxScore() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of()); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); GeoPointScriptFieldDistanceFeatureQuery query = createTestInstance(); float boost = randomFloat(); assertThat( query.createWeight(searcher, ScoreMode.COMPLETE, boost).scorer(reader.leaves().get(0)).getMaxScore(randomInt()), equalTo(boost) ); } } } @Override protected void assertToString(GeoPointScriptFieldDistanceFeatureQuery query) { assertThat( query.toString(query.fieldName()), equalTo("GeoPointScriptFieldDistanceFeatureQuery(lat=" + query.lat() + ",lon=" + query.lon() + ",pivot=" + query.pivot() + ")") ); } @Override public final void testVisit() { assertEmptyVisit(); } }
40.929032
139
0.622478
46421e084fda87c7d9fb4a9a907af5fbb2d1f03e
724
package com.fuerve.whiteboard.milestone2.structures; import java.util.NoSuchElementException; /** * Double-ended queue interface (I need both stacks and queues). * I'm not as kind as Java's implementation, which has the offer and poll semantics. */ public interface Deque<T> extends Queue<T> { /** * Pushes an element onto the head of the structure as if it were a stack. * @param element The element to push. */ void push(final T element) throws ClassCastException, NullPointerException, IllegalArgumentException; /** * Pops an element from the head of the structure as if it were a stack. * @return The head of the stack. */ T pop() throws NoSuchElementException; }
32.909091
105
0.705801
039eadbff2287d998de28fbcd664580a25495f6c
458
package com.geekutil.designpattern.iterator; /** * @author Asens * create 2019-10-13 12:07 **/ public class Client { public static void main(String[] args) { NormalList list = new NormalList(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); Iterator iterator = list.createIterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } }
20.818182
50
0.558952
754611b832392745368f12fef857a80ed6e0221b
3,788
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.internal.processors.cache.persistence.wal.filehandle; import java.io.IOException; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.pagemem.wal.WALPointer; import org.apache.ignite.internal.processors.cache.persistence.StorageException; import org.apache.ignite.internal.processors.cache.persistence.wal.io.SegmentIO; import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordSerializer; /** * Manager of {@link FileWriteHandle}. */ public interface FileHandleManager { /** * Initialize {@link FileWriteHandle} for first time. * * @param fileIO FileIO. * @param position Init position. * @param serializer Serializer for file handle. * @return Created file handle. * @throws IOException if creation was not success. */ FileWriteHandle initHandle(SegmentIO fileIO, long position, RecordSerializer serializer) throws IOException; /** * Create next file handle. * * @param fileIO FileIO. * @param serializer Serializer for file handle. * @return Created file handle. * @throws IOException if creation was not success. */ FileWriteHandle nextHandle(SegmentIO fileIO, RecordSerializer serializer) throws IOException; /** * Start manager. */ void start(); /** * On activate. */ void onActivate(); /** * On deactivate. * * @throws IgniteCheckedException if fail. */ void onDeactivate() throws IgniteCheckedException; /** * Resume logging. */ void resumeLogging(); /** * @param ptr Pointer until need to flush. * @param explicitFsync {@code true} if fsync required. * @throws IgniteCheckedException if fail. * @throws StorageException if storage was fail. */ void flush(WALPointer ptr, boolean explicitFsync) throws IgniteCheckedException, StorageException; }
38.262626
112
0.724393
fe6b943516e82f4b76d949138a0157fe5aa2e83b
2,742
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998-1999 IBM Corp. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package javax.rmi.CORBA; import java.rmi.RemoteException; import java.rmi.NoSuchObjectException; import java.rmi.Remote; /** * Supports delegation for method implementations in {@link javax.rmi.PortableRemoteObject}. * The delegate is a singleton instance of a class that implements this * interface and provides a replacement implementation for all the * methods of <code>javax.rmi.PortableRemoteObject</code>. * * Delegates are enabled by providing the delegate's class name as the * value of the * <code>javax.rmi.CORBA.PortableRemoteObjectClass</code> * system property. * * @see javax.rmi.PortableRemoteObject */ public interface PortableRemoteObjectDelegate { /** * Delegation call for {@link javax.rmi.PortableRemoteObject#exportObject}. * @param obj object to export * @throws RemoteException if the object cannot be exported */ void exportObject(Remote obj) throws RemoteException; /** * Delegation call for {@link javax.rmi.PortableRemoteObject#toStub}. * @param obj remote to convert to stub * @return stub of the remote * @throws NoSuchObjectException if the object does not exist */ Remote toStub (Remote obj) throws NoSuchObjectException; /** * Delegation call for {@link javax.rmi.PortableRemoteObject#unexportObject}. * @param obj object to unremove * @throws NoSuchObjectException if the object does not exist */ void unexportObject(Remote obj) throws NoSuchObjectException; /** * Delegation call for {@link javax.rmi.PortableRemoteObject#narrow}. * @param narrowFrom object to narrow from * @param narrowTo target to narrow to * @return object of the desired type * @throws ClassCastException if the object cannot be narrowed */ java.lang.Object narrow (java.lang.Object narrowFrom, java.lang.Class narrowTo) throws ClassCastException; /** * Delegation call for {@link javax.rmi.PortableRemoteObject#connect}. * @param target remote object to connect * @param source starting object * @throws RemoteException if an error occurred connecting */ void connect (Remote target, Remote source) throws RemoteException; }
34.708861
92
0.691466
4e8042c68a18f662369a244d12635fb961066599
795
package com.globalload; import java.io.IOException; import java.util.logging.Logger; public class LibraryLoaderJNI { private static final Logger LOGGER = Logger.getLogger(LibraryLoaderJNI.class.getName()); static { try { NativeUtils.loadLibraryFromJar("/libnativeload.so"); LOGGER.info("Loaded nativeload"); } catch (UnsatisfiedLinkError | IOException e) { LOGGER.warning("Couldn't load nativeload"); LOGGER.warning(e.getMessage()); e.printStackTrace(); } } public LibraryLoaderJNI() { } public static void main(String[] var0) { test(); } public static native void test(); public static native boolean loadLibrary(String var1) throws UnsatisfiedLinkError; }
24.090909
92
0.646541
1de3409b3b57218bef77297250f18bacdca651ee
1,455
package com.airwallex.airskiff.flink; import org.apache.flink.api.common.eventtime.Watermark; import org.apache.flink.api.common.eventtime.WatermarkGenerator; import org.apache.flink.api.common.eventtime.WatermarkOutput; import java.time.Clock; public class HybridWatermarkGenerator<T> implements WatermarkGenerator<T> { private final long maxDelay; private final EventTimeManager eventTimeManager; private final Clock clock; private long maxTs; private long lastProcessTime; public HybridWatermarkGenerator(long maxDelay, EventTimeManager eventTimeManager, Clock clock) { this.maxDelay = maxDelay; this.eventTimeManager = eventTimeManager; this.clock = clock; this.lastProcessTime = clock.millis(); } @Override public void onEvent(T t, long ts, WatermarkOutput watermarkOutput) { maxTs = Math.max(maxTs, ts); long currentTime = clock.millis(); lastProcessTime = currentTime; eventTimeManager.checkCaughtUp(currentTime - ts); } @Override public void onPeriodicEmit(WatermarkOutput watermarkOutput) { if (eventTimeManager.isCaughtUp()) { watermarkOutput.emitWatermark(new Watermark(maxTs)); } else { long elapsed = clock.millis() - lastProcessTime; if (elapsed >= Constants.TEN_SECONDS.toMillis()) { watermarkOutput.emitWatermark(new Watermark(maxTs)); } else { watermarkOutput.emitWatermark(new Watermark(maxTs - maxDelay)); } } } }
32.333333
98
0.741581
14a3bad01e5d05726fe7fe977ba8501f75fa8307
1,826
/* * Copyright 2012 GitHub Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mobile.ui; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; /** * Pager that stores current fragment */ public abstract class FragmentStatePagerAdapter extends android.support.v4.app.FragmentStatePagerAdapter implements FragmentProvider { private final AppCompatActivity activity; private Fragment selected; /** * @param activity */ public FragmentStatePagerAdapter(final AppCompatActivity activity) { super(activity.getSupportFragmentManager()); this.activity = activity; } @Override public Fragment getSelected() { return selected; } @Override public void setPrimaryItem(final ViewGroup container, final int position, final Object object) { super.setPrimaryItem(container, position, object); boolean changed = false; if (object instanceof Fragment) { changed = object != selected; selected = (Fragment) object; } else { changed = object != null; selected = null; } if (changed) activity.invalidateOptionsMenu(); } }
28.092308
77
0.680175
f6c46dc52f7f75b30116822a6f30bd0d533cbdd9
6,743
package com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalAnalysis.byReference; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiWhiteSpace; import com.jetbrains.php.config.PhpLanguageLevel; import com.jetbrains.php.config.PhpProjectConfigurationFacade; import com.jetbrains.php.lang.lexer.PhpTokenTypes; import com.jetbrains.php.lang.psi.elements.*; import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor; import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection; import com.kalessil.phpStorm.phpInspectionsEA.utils.NamedElementUtil; import com.kalessil.phpStorm.phpInspectionsEA.utils.OpenapiResolveUtil; import com.kalessil.phpStorm.phpInspectionsEA.utils.OpenapiTypesUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /* * This file is part of the Php Inspections (EA Extended) package. * * (c) Vladimir Reznichenko <kalessil@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ public class PassingByReferenceCorrectnessInspector extends BasePhpInspection { private static final String message = "Emits a notice (only variable references should be returned/passed by reference)."; private static final Map<String, String> skippedFunctionsCache = new ConcurrentHashMap<>(); private static final Set<String> skippedFunctions = new HashSet<>(); static { /* workaround for https://youtrack.jetbrains.com/issue/WI-37984 */ skippedFunctions.add("current"); skippedFunctions.add("key"); } @NotNull public String getShortName() { return "PassingByReferenceCorrectnessInspection"; } @Override @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new BasePhpElementVisitor() { @Override public void visitPhpFunctionCall(@NotNull FunctionReference reference) { final String functionName = reference.getName(); if (functionName != null && !functionName.isEmpty() && !skippedFunctionsCache.containsKey(functionName)) { final boolean skip = skippedFunctions.contains(functionName) && this.isFromRootNamespace(reference); if (!skip && this.hasIncompatibleArguments(reference)) { this.analyze(reference); } } } @Override public void visitPhpMethodReference(@NotNull MethodReference reference) { final String methodName = reference.getName(); if (methodName != null && !methodName.isEmpty() && this.hasIncompatibleArguments(reference)) { this.analyze(reference); } } private boolean hasIncompatibleArguments(@NotNull FunctionReference reference) { final PsiElement[] arguments = reference.getParameters(); if (arguments.length > 0) { final PhpLanguageLevel php = PhpProjectConfigurationFacade.getInstance(reference.getProject()).getLanguageLevel(); final boolean supportsNew = php.compareTo(PhpLanguageLevel.PHP560) <= 0; return !Arrays.stream(arguments).allMatch(a -> a instanceof Variable || (supportsNew && a instanceof NewExpression)); } return false; } private void analyze(@NotNull FunctionReference reference) { final PsiElement resolved = OpenapiResolveUtil.resolveReference(reference); if (resolved instanceof Function) { final Function function = (Function) resolved; final Parameter[] parameters = function.getParameters(); final PsiElement[] arguments = reference.getParameters(); /* search for anomalies */ for (int index = 0, max = Math.min(parameters.length, arguments.length); index < max; ++index) { if (parameters[index].isPassByRef()) { final PsiElement argument = arguments[index]; if (argument instanceof FunctionReference && !this.isByReference(argument)) { final PsiElement inner = OpenapiResolveUtil.resolveReference((FunctionReference) argument); if (inner instanceof Function) { final PsiElement name = NamedElementUtil.getNameIdentifier((Function) inner); if (!this.isByReference(name)) { holder.registerProblem(argument, message); } } } else if (argument instanceof NewExpression) { holder.registerProblem(argument, message); } } } /* remember global functions without references */ if (parameters.length > 0 && OpenapiTypesUtil.isFunctionReference(reference)) { final boolean hasReferences = Arrays.stream(parameters).anyMatch(Parameter::isPassByRef); if (!hasReferences) { final String functionName = function.getName(); final boolean isFromRootNamespace = function.getFQN().equals('\\' + functionName); if (isFromRootNamespace) { skippedFunctionsCache.putIfAbsent(functionName, functionName); } } } } } private boolean isByReference(@Nullable PsiElement element) { boolean result = false; if (element != null) { PsiElement ampersandCandidate = element.getPrevSibling(); if (ampersandCandidate instanceof PsiWhiteSpace) { ampersandCandidate = ampersandCandidate.getPrevSibling(); } result = OpenapiTypesUtil.is(ampersandCandidate, PhpTokenTypes.opBIT_AND); } return result; } }; } }
50.320896
137
0.607296
d66803f9bdc1ff0e3059c8d9cee03c6d5cd242e2
3,479
/** * Copyright (C) 2010 - 2014 VREM Software Development <VREMSoftwareDevelopment@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.travelagency.identity; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.PasswordTextField; import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator; import org.apache.wicket.markup.html.panel.ComponentFeedbackPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.ResourceModel; import ca.travelagency.components.decorators.FieldDecorator; import ca.travelagency.components.fields.StringFieldHelper; import ca.travelagency.components.formheader.SavePanel; import ca.travelagency.components.javascript.JSUtils; public class ResetPasswordPanel extends Panel { private static final long serialVersionUID = 1L; static final String FEEDBACK = "feedback"; static final String FORM = "form"; static final String NEW_PASSWORD = "newPassword"; static final String CONFIRM_PASSWORD = "confirmPassword"; static final String SAVE_BUTTON = "saveButton"; public ResetPasswordPanel(String id, IModel<SystemUser> model) { super(id); Form<SystemUser> form = new Form<SystemUser>(FORM, model); form.setOutputMarkupId(true); add(form); form.add(new ComponentFeedbackPanel(FEEDBACK, form)); final PasswordTextField newPasswordField = new PasswordTextField(NEW_PASSWORD, new Model<String>()); newPasswordField.setLabel(new ResourceModel("password")) .add(StringFieldHelper.maxLenFieldValidator()) .add(new FieldDecorator()); form.add(newPasswordField); PasswordTextField confirmPasswordField = new PasswordTextField(CONFIRM_PASSWORD, new Model<String>()); confirmPasswordField.setLabel(new ResourceModel("confirmPassword")) .add(StringFieldHelper.maxLenFieldValidator()) .add(new FieldDecorator()); form.add(confirmPasswordField); form.add(new EqualPasswordInputValidator(newPasswordField, confirmPasswordField)); form.add(new SavePanel<SystemUser>(SAVE_BUTTON, form) { private static final long serialVersionUID = 1L; @Override public void preSubmit(AjaxRequestTarget target, SystemUser daoEntity, boolean newDaoEntity) { daoEntity.setPassword(newPasswordField.getConvertedInput()); } @Override public void setMessage(SystemUser daoEntity) { String message = getLocalizer().getString("passwordReset.message", ResetPasswordPanel.this); getSession().success(message + " " + daoEntity.getName()); } }); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); response.render(OnDomReadyHeaderItem.forScript(JSUtils.INITIALIZE)); } }
39.988506
104
0.779247
ddb5c2d9fc54d4b5c6c8f2625bb4a894df396f2b
685
package com.github.leeyazhou.scf.server.util; import java.util.HashMap; import java.util.Map; import com.github.leeyazhou.scf.core.IInit; import com.github.leeyazhou.scf.server.contract.context.SCFChannel; public class MethodMapping implements IInit { private static final Map<SCFChannel, HashMap<String, String>> channelMap = new HashMap<SCFChannel, HashMap<String, String>>(); @Override public void init() { // TODO 从授权文件中加载方法名到methodMap } public static boolean check(SCFChannel channel, String methodName) { HashMap<String, String> map = channelMap.get(channel); if (map != null) { return map.containsKey(methodName); } return false; } }
26.346154
128
0.735766
fd1c28f134d5321540004700ee9f5995dd44bcd5
3,158
package org.aieonf.concept.rest; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.aieonf.commons.http.AbstractHttpRequest; import org.aieonf.commons.http.ResponseEvent; import org.aieonf.concept.domain.IDomainAieon; import org.aieonf.concept.request.AbstractKeyEventService; import org.aieonf.concept.request.KeyEvent; /** * Send a Request <R> and returns data <D> * @author Kees * * @param <R> * @param <D> */ public abstract class AbstractRESTKeyEventService<R,D> extends AbstractKeyEventService<R> { private String url; protected AbstractRESTKeyEventService( IDomainAieon domain, String url ){ super( domain ); this.url = url; } @Override public void setEvent( R request, long id, long token ) throws Exception{ setEvent( request, id, token, new HashMap<String, String>()); } public void setEvent( R request, long id, long token, Map<String, String> parameters ) throws Exception{ WebClient client = new WebClient( url); parameters.put( Attributes.ID.toString(), String.valueOf(id)); parameters.put( Attributes.TOKEN.toString(), String.valueOf(token)); parameters.put( Attributes.DOMAIN.toString(), super.getDomain().getDomain()); client.sendGet(request, parameters); } public void add( R request, long id, long token, Map<String, String> parameters, String post, D data ) throws Exception{ WebClient client = new WebClient( url ); parameters.put( Attributes.ID.toString(), String.valueOf(id)); parameters.put( Attributes.TOKEN.toString(), String.valueOf(token)); parameters.put( Attributes.DOMAIN.toString(), super.getDomain().getDomain()); client.sendPost(request, parameters, post, data); } public void delete( R request, long id, long token, Map<String, String> parameters, String post, D data ) throws Exception{ WebClient client = new WebClient( url); parameters.put( Attributes.ID.toString(), String.valueOf(id)); parameters.put( Attributes.TOKEN.toString(), String.valueOf(token)); parameters.put( Attributes.DOMAIN.toString(), super.getDomain().getDomain()); client.sendDelete(request, parameters, post, data); } protected abstract D onProcessResponse( ResponseEvent<R,D> response ); private class WebClient extends AbstractHttpRequest<R,D>{ public WebClient(String path) { super(path); } @Override public void sendGet( R request, Map<String, String> parameters) throws Exception { super.sendGet(request, parameters); } @Override public void sendPost( R request, Map<String, String> parameters, String post, D data) throws Exception { super.sendPost(request, parameters, post, data ); } @Override public void sendDelete( R request, Map<String, String> parameters, String post, D data) throws Exception { super.sendDelete(request, parameters, post, data); } @Override protected String onHandleResponse(ResponseEvent<R,D> response, D data ) throws IOException { notifyKeyEventChanged( new KeyEvent<R>( this, response.getRequest(), response.getParameters() )); return response.getResponse(); } } }
35.483146
125
0.720709
33420019ef3428b8b250718edaa9f3244dce5a6d
944
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions; import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCommandArgumentList; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.arguments.GrArgumentListImpl; /** * @author ilyas */ public class GrCommandArgumentListImpl extends GrArgumentListImpl implements GrCommandArgumentList { public GrCommandArgumentListImpl(@NotNull ASTNode node) { super(node); } public String toString() { return "Command arguments"; } @Override public void accept(@NotNull GroovyElementVisitor visitor) { visitor.visitCommandArguments(this); } }
32.551724
140
0.793432
130799f3f2beaa860af5e4930dea38a9ad391969
910
package com.ngdesk.modules; import java.util.List; import javax.validation.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonProperty; public class MergeData { @JsonProperty("ENTRY") @NotEmpty(message = "ENTRY_REQUIRED") private String entry; @JsonProperty("MERGE_ENTRIES") @NotEmpty(message = "MERGE_ENTRIES_REQUIRED") private List<String> mergeEntries; public MergeData() {} public MergeData(@NotEmpty(message = "ENTRY_REQUIRED") String entry, @NotEmpty(message = "MERGE_ENTRIES_REQUIRED") List<String> mergeEntries) { super(); this.entry = entry; this.mergeEntries = mergeEntries; } public String getEntry() { return entry; } public void setEntry(String entry) { this.entry = entry; } public List<String> getMergeEntries() { return mergeEntries; } public void setMergeEntries(List<String> mergeEntries) { this.mergeEntries = mergeEntries; } }
20.222222
77
0.743956
47cdcecfe72f706eec5e80ea539005496d88cc0b
3,361
/* * Copyright (C) 2015 Hamburg Sud and the contributors. * * 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.aludratest.service.database.tablecolumn; /** Object factory for different table column types. Use the returned objects to retrieve values from a * {@link org.aludratest.service.database.DataRow}. * * @author falbrech */ public interface TableColumnFactory { /** Creates a new IntColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new IntColumn object identifying the given column. */ public IntColumn createIntColumn(String columnName); /** Creates a new LongColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new LongColumn object identifying the given column. */ public LongColumn createLongColumn(String columnName); /** Creates a new FloatColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new FloatColumn object identifying the given column. */ public FloatColumn createFloatColumn(String columnName); /** Creates a new DoubleColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new DoubleColumn object identifying the given column. */ public DoubleColumn createDoubleColumn(String columnName); /** Creates a new StringColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new StringColumn object identifying the given column. */ public StringColumn createStringColumn(String columnName); /** Creates a new DateColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new DateColumn object identifying the given column. */ public DateColumn createDateColumn(String columnName); /** Creates a new TimeColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new TimeColumn object identifying the given column. */ public TimeColumn createTimeColumn(String columnName); /** Creates a new TimestampColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new TimestampColumn object identifying the given column. */ public TimestampColumn createTimestampColumn(String columnName); /** Creates a new ClobColumn object for the column with the given name. * * @param columnName Name of the column. * * @return A new ClobColumn object identifying the given column. */ public ClobColumn createClobColumn(String columnName); }
37.764045
103
0.70366
5d0dc7ce225156d29eb9f0e56942c50cbce88824
1,762
package com.example.demo; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.regex.Pattern; /** * Created by dequan.yu on 2021/11/24. */ @Slf4j public class TestCase { @Test public void sumBigDecimalList() { List<BigDecimal> list = Arrays.asList(new BigDecimal(31), new BigDecimal(40), new BigDecimal(30)); BigDecimal sum = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add); log.info(sum.toString()); } @Test public void regex() { String content = "-5.011111111%"; String pattern = "\\b(?<!\\.)(?!0+(?:\\.0+)?%)(?:\\d|[1-9]\\d|100)(?:(?<!100)\\.\\d+)?%"; boolean isMatch = Pattern.matches(pattern, content); System.out.println("字符串中是否包含了字符串? " + isMatch); } @Test public void sort() { List<String> list = Arrays.asList("5.1-6.4%", "5.1%", "3.1%", "12.8%", "14.5%"); list.sort(Comparator.reverseOrder()); list.forEach(System.out::println); List<Movie> movies = Arrays.asList( new Movie("Lord of the rings", 8.8), new Movie("Back to the future", 8.5), new Movie("Carlito's way", 7.9), new Movie("Pulp fiction", 8.9)); movies.sort(Comparator.comparingDouble(Movie::getRating) .reversed()); movies.forEach(System.out::println); } @Data private static class Movie { private String name; private double rating; public Movie(String name, double rating) { this.name = name; this.rating = rating; } } }
27.53125
106
0.581725
ec9511be9c35233f877dbde56993fdd04e7a7dd5
913
package com.mithion.griefguardian.network; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import com.mithion.griefguardian.GriefGuardian; import com.mithion.griefguardian.claims.ClaimsList; /** * Handles the sync claims message. * * Author: Mithion * Sept 6, 2014 * */ public class PacketSyncMessageHandler implements IMessageHandler<PacketSyncClaims, PacketSyncClaims>{ @Override public PacketSyncClaims onMessage(PacketSyncClaims message, MessageContext ctx) { if (ctx.side == Side.CLIENT){ if (message.isStopRenderPacket()){ GriefGuardian.proxy.setRenderClaims(false); }else{ GriefGuardian.proxy.setRenderClaims(true); ClaimsList.For(GriefGuardian.proxy.getClientWorld()).loadFromSyncPacket(message); } } return null; } }
27.666667
101
0.784228
ead08654da5ebed8acc062c2d7736a91bca6d8e3
1,289
package org.minijax.rs; import static org.junit.jupiter.api.Assertions.*; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.minijax.rs.test.MinijaxTest; import org.minijax.rs.util.CacheControlUtils; class CacheControlTest extends MinijaxTest { @GET @Path("/public") public static Response getPublic() { return Response.ok().cacheControl(CacheControlUtils.fromString("public")).build(); } @GET @Path("/private") public static String getPrivate() { return "ok"; } @BeforeAll public static void setUpCacheControlTest() { resetServer(); getServer().defaultCacheControl(CacheControlUtils.fromString("private")); register(CacheControlTest.class); } @Test void testPublicCacheControl() { final Response r = target("/public").request().get(); assertEquals("public", r.getHeaderString(HttpHeaders.CACHE_CONTROL)); } @Test void testPrivateCacheControl() { final Response r = target("/private").request().get(); assertEquals("private", r.getHeaderString(HttpHeaders.CACHE_CONTROL)); } }
26.854167
90
0.690458
ed917c4e2fefde76f9b9f9db03d07542569ba6ab
215
package algebra.curves.barreto_lynn_scott.abstract_bls_parameters; import algebra.fields.abstractfieldparameters.AbstractFpParameters; public abstract class AbstractBLSFqParameters extends AbstractFpParameters {}
35.833333
77
0.893023
88b2ccdc2533de86490ed2d82860dbc52f8a7d16
224
package com.yz.yx.dao; import com.yz.yx.bean.Post; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface PostDao { List<Post> getAllPost(); Post getPostById(Integer pid); }
16
44
0.736607
a3608c3d511e43c98c95ae47ac070ebfea77794e
555
package com.avereon.xenon.testutil; import com.avereon.event.EventHandler; import com.avereon.xenon.product.ProductEvent; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @SuppressWarnings( "unused" ) public class ProgramEventCollector implements EventHandler<ProductEvent> { private final List<ProductEvent> events = new CopyOnWriteArrayList<>(); @Override public void handle( ProductEvent event ) { events.add( event ); } @SuppressWarnings( "unused" ) public List<ProductEvent> getEvents() { return events; } }
22.2
74
0.774775
71cae2b04e3f33fe251f1a25cb0d8223dc0484fa
4,604
/** * Copyright (C) 2012 Xeiam LLC http://xeiam.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.xeiam.xchange.service; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xeiam.xchange.ExchangeException; import com.xeiam.xchange.ExchangeSpecification; import com.xeiam.xchange.streaming.socketio.SocketIO; import com.xeiam.xchange.utils.Assert; /** * <p> * Socket IO exchange service to provide the following to streaming market data API: * </p> * <ul> * <li>Connection to an upstream exchange data source with a configured provider</li> * </ul> */ public abstract class BaseSocketIOExchangeService extends BaseExchangeService implements StreamingExchangeService { private final Logger log = LoggerFactory.getLogger(BaseSocketIOExchangeService.class); private final ExecutorService executorService; private final BlockingQueue<ExchangeEvent> exchangeEvents = new ArrayBlockingQueue<ExchangeEvent>(1024); private SocketIO socketIO; private RunnableExchangeEventProducer runnableMarketDataEventProducer = null; /** * Constructor * * @param exchangeSpecification The exchange specification providing the required connection data */ public BaseSocketIOExchangeService(ExchangeSpecification exchangeSpecification) throws IOException { super(exchangeSpecification); // Assert.notNull(exchangeSpecification.getHost(), "host cannot be null"); executorService = Executors.newSingleThreadExecutor(); } @Override public synchronized void connect(String url, RunnableExchangeEventListener runnableExchangeEventListener) { // Validate inputs Assert.notNull(runnableExchangeEventListener, "runnableMarketDataListener cannot be null"); // Validate state if (executorService.isShutdown()) { throw new IllegalStateException("Service has been stopped. Create a new one rather than reuse a reference."); } try { log.debug("Attempting to open a socketIO against {}:{}", url, exchangeSpecification.getPort()); this.runnableMarketDataEventProducer = new RunnableSocketIOEventProducer(socketIO, exchangeEvents); this.socketIO = new SocketIO(url, (RunnableSocketIOEventProducer) runnableMarketDataEventProducer); } catch (IOException e) { throw new ExchangeException("Failed to open socket: " + e.getMessage(), e); } runnableExchangeEventListener.setExchangeEventQueue(exchangeEvents); executorService.submit(runnableMarketDataEventProducer); log.debug("Started OK"); } @Override public void send(String message) { this.socketIO.send(message); } @Override public synchronized void disconnect() { if (!executorService.isShutdown()) { // We close on the socket to get an immediate result // otherwise the producer would block until the exchange // sent a message which could be forever if (socketIO != null) { socketIO.disconnect(); } } executorService.shutdownNow(); log.debug("Stopped"); } @Override public RunnableExchangeEventProducer getRunnableMarketDataEventProducer() { return runnableMarketDataEventProducer; } @Override public void setRunnableMarketDataEventProducer(RunnableExchangeEventProducer runnableMarketDataEventProducer) { this.runnableMarketDataEventProducer = runnableMarketDataEventProducer; } }
35.415385
115
0.764553
75a8449541e96f18272e85bd23c898fb6fd04016
17,417
// ================================================================================================= // Copyright 2013 Twitter, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ================================================================================================= package com.twitter.common.stats; import java.util.Arrays; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.twitter.common.quantity.Amount; import com.twitter.common.quantity.Data; /** * <p> * Implements Histogram structure for computing approximate quantiles. * The implementation is based on the following paper: * * <pre> * [MP80] Munro & Paterson, "Selection and Sorting with Limited Storage", * Theoretical Computer Science, Vol 12, p 315-323, 1980. * </pre> * </p> * <p> * You could read a detailed description of the same algorithm here: * * <pre> * [MRL98] Manku, Rajagopalan & Lindsay, "Approximate Medians and other * Quantiles in One Pass and with Limited Memory", Proc. 1998 ACM * SIGMOD, Vol 27, No 2, p 426-435, June 1998. * </pre> * </p> * <p> * There's a good explanation of the algorithm in the Sawzall source code * See: http://szl.googlecode.com/svn-history/r36/trunk/src/emitters/szlquantile.cc * </p> * Here's a schema of the tree: * <pre> * [4] level 3, weight=rootWeight=8 * | * [3] level 2, weight=4 * | * [2] level 1, weight=2 * / \ * [0] [1] level 0, weight=1 * </pre> * <p> * {@code [i]} represents {@code buffer[i]} * The depth of the tree is limited to a maximum value * Every buffer has the same size * </p> * <p> * We add element in {@code [0]} or {@code [1]}. * When {@code [0]} and {@code [1]} are full, we collapse them, it generates a temporary buffer * of weight 2, if {@code [2]} is empty, we put the collapsed buffer into {@code [2]} otherwise * we collapse {@code [2]} with the temporary buffer and put it in {@code [3]} if it's empty and * so on... * </p> */ public final class ApproximateHistogram implements Histogram { @VisibleForTesting public static final Precision DEFAULT_PRECISION = new Precision(0.02, 100 * 1000); @VisibleForTesting public static final Amount<Long, Data> DEFAULT_MAX_MEMORY = Amount.of(12L, Data.KB); @VisibleForTesting static final long ELEM_SIZE = 8; // sizeof long // See above @VisibleForTesting long[][] buffer; @VisibleForTesting long count = 0L; @VisibleForTesting int leafCount = 0; // number of elements in the bottom two leaves @VisibleForTesting int currentTop = 1; @VisibleForTesting int[] indices; // member for optimization reason private boolean leavesSorted = true; private int rootWeight = 1; private long[][] bufferPool; // pool of 2 buffers (used for merging) private int bufferSize; private int maxDepth; /** * Private init method that is called only by constructors. * All allocations are done in this method. * * @param bufSize size of each buffer * @param depth maximum depth of the tree of buffers */ @VisibleForTesting void init(int bufSize, int depth) { bufferSize = bufSize; maxDepth = depth; bufferPool = new long[2][bufferSize]; indices = new int[depth + 1]; buffer = new long[depth + 1][bufferSize]; // only allocate the first 2 buffers, lazily allocate the others. allocate(0); allocate(1); Arrays.fill(buffer, 2, buffer.length, null); clear(); } @VisibleForTesting ApproximateHistogram(int bufSize, int depth) { init(bufSize, depth); } /** * Constructor with precision constraint, it will allocated as much memory as require to match * this precision constraint. * @param precision the requested precision */ public ApproximateHistogram(Precision precision) { Preconditions.checkNotNull(precision); int depth = computeDepth(precision.getEpsilon(), precision.getN()); int bufSize = computeBufferSize(depth, precision.getN()); init(bufSize, depth); } /** * Constructor with memory constraint, it will find the best possible precision that satisfied * the memory constraint. * @param maxMemory the maximum amount of memory that the instance will take */ public ApproximateHistogram(Amount<Long, Data> maxMemory, int expectedSize) { Preconditions.checkNotNull(maxMemory); Preconditions.checkArgument(1024 <= maxMemory.as(Data.BYTES), "at least 1KB is required for an Histogram"); double epsilon = DEFAULT_PRECISION.getEpsilon(); int n = expectedSize; int depth = computeDepth(epsilon, n); int bufSize = computeBufferSize(depth, n); long maxBytes = maxMemory.as(Data.BYTES); // Increase precision if the maxMemory allow it, otherwise reduce precision. (by 5% steps) boolean tooMuchMem = memoryUsage(bufSize, depth) > maxBytes; double multiplier = tooMuchMem ? 1.05 : 0.95; while((maxBytes < memoryUsage(bufSize, depth)) == tooMuchMem) { epsilon *= multiplier; if (epsilon < 0.00001) { // for very high memory constraint increase N as well n *= 10; epsilon = DEFAULT_PRECISION.getEpsilon(); } depth = computeDepth(epsilon, n); bufSize = computeBufferSize(depth, n); } if (!tooMuchMem) { // It's ok to consume less memory than the constraint // but we never have to consume more! depth = computeDepth(epsilon / multiplier, n); bufSize = computeBufferSize(depth, n); } init(bufSize, depth); } /** * Constructor with memory constraint. * @see #ApproximateHistogram(Amount, int) */ public ApproximateHistogram(Amount<Long, Data> maxMemory) { this(maxMemory, DEFAULT_PRECISION.getN()); } /** * Default Constructor. * @see #ApproximateHistogram(Amount) */ public ApproximateHistogram() { this(DEFAULT_MAX_MEMORY); } @Override public synchronized void add(long x) { // if the leaves of the tree are full, "collapse" recursively the tree if (leafCount == 2 * bufferSize) { Arrays.sort(buffer[0]); Arrays.sort(buffer[1]); recCollapse(buffer[0], 1); leafCount = 0; } // Now we're sure there is space for adding x if (leafCount < bufferSize) { buffer[0][leafCount] = x; } else { buffer[1][leafCount - bufferSize] = x; } leafCount++; count++; leavesSorted = (leafCount == 1); } @Override public synchronized long getQuantile(double q) { Preconditions.checkArgument(0.0 <= q && q <= 1.0, "quantile must be in the range 0.0 to 1.0 inclusive"); if (count == 0) { return 0L; } // the two leaves are the only buffer that can be partially filled int buf0Size = Math.min(bufferSize, leafCount); int buf1Size = Math.max(0, leafCount - buf0Size); long sum = 0; long target = (long) Math.ceil(count * (1.0 - q)); int i; if (! leavesSorted) { Arrays.sort(buffer[0], 0, buf0Size); Arrays.sort(buffer[1], 0, buf1Size); leavesSorted = true; } Arrays.fill(indices, bufferSize - 1); indices[0] = buf0Size - 1; indices[1] = buf1Size - 1; do { i = biggest(indices); indices[i]--; sum += weight(i); } while (sum < target); return buffer[i][indices[i] + 1]; } @Override public synchronized long[] getQuantiles(double[] quantiles) { return Histograms.extractQuantiles(this, quantiles); } @Override public synchronized void clear() { count = 0L; leafCount = 0; currentTop = 1; rootWeight = 1; leavesSorted = true; } /** * MergedHistogram is a Wrapper on top of multiple histograms, it gives a view of all the * underlying histograms as it was just one. * Note: Should only be used for querying the underlying histograms. */ private static class MergedHistogram implements Histogram { private final ApproximateHistogram[] histograms; private MergedHistogram(ApproximateHistogram[] histograms) { this.histograms = histograms; } @Override public void add(long x) { /* Ignore, Shouldn't be used */ assert(false); } @Override public void clear() { /* Ignore, Shouldn't be used */ assert(false); } @Override public long getQuantile(double quantile) { Preconditions.checkArgument(0.0 <= quantile && quantile <= 1.0, "quantile must be in the range 0.0 to 1.0 inclusive"); long count = initIndices(); if (count == 0) { return 0L; } long sum = 0; long target = (long) Math.ceil(count * (1.0 - quantile)); int iHist = -1; int iBiggest = -1; do { long biggest = Long.MIN_VALUE; for (int i = 0; i < histograms.length; i++) { ApproximateHistogram hist = histograms[i]; int indexBiggest = hist.biggest(hist.indices); if (indexBiggest >= 0) { long value = hist.buffer[indexBiggest][hist.indices[indexBiggest]]; if (iBiggest == -1 || biggest <= value) { iBiggest = indexBiggest; biggest = value; iHist = i; } } } histograms[iHist].indices[iBiggest]--; sum += histograms[iHist].weight(iBiggest); } while (sum < target); ApproximateHistogram hist = histograms[iHist]; int i = hist.indices[iBiggest]; return hist.buffer[iBiggest][i + 1]; } @Override public synchronized long[] getQuantiles(double[] quantiles) { return Histograms.extractQuantiles(this, quantiles); } /** * Initialize the indices array for each Histogram and return the global count. */ private long initIndices() { long count = 0L; for (int i = 0; i < histograms.length; i++) { ApproximateHistogram h = histograms[i]; int[] indices = h.indices; count += h.count; int buf0Size = Math.min(h.bufferSize, h.leafCount); int buf1Size = Math.max(0, h.leafCount - buf0Size); if (! h.leavesSorted) { Arrays.sort(h.buffer[0], 0, buf0Size); Arrays.sort(h.buffer[1], 0, buf1Size); h.leavesSorted = true; } Arrays.fill(indices, h.bufferSize - 1); indices[0] = buf0Size - 1; indices[1] = buf1Size - 1; } return count; } } /** * Return a MergedHistogram * @param histograms array of histograms to merged together * @return a new Histogram */ public static Histogram merge(ApproximateHistogram[] histograms) { return new MergedHistogram(histograms); } /** * We compute the "smallest possible b" satisfying two inequalities: * 1) (b - 2) * (2 ^ (b - 2)) + 0.5 <= epsilon * N * 2) k * (2 ^ (b - 1)) >= N * * For an explanation of these inequalities, please read the Munro-Paterson or * the Manku-Rajagopalan-Linday papers. */ @VisibleForTesting static int computeDepth(double epsilon, long n) { int b = 2; while ((b - 2) * (1L << (b - 2)) + 0.5 <= epsilon * n) { b += 1; } return b; } @VisibleForTesting static int computeBufferSize(int depth, long n) { return (int) (n / (1L << (depth - 1))); } /** * Return an estimation of the memory used by an instance. * The size is due to: * - a fix cost (76 bytes) for the class + fields * - bufferPool: 16 + 2 * (16 + bufferSize * ELEM_SIZE) * - indices: 16 + sizeof(Integer) * (depth + 1) * - buffer: 16 + (depth + 1) * (16 + bufferSize * ELEM_SIZE) * * Note: This method is tested with unit test, it will break if you had new fields. * @param bufferSize the size of a buffer * @param depth the depth of the tree of buffer (depth + 1 buffers) */ @VisibleForTesting static long memoryUsage(int bufferSize, int depth) { return 176 + (24 * depth) + (bufferSize * ELEM_SIZE * (depth + 3)); } /** * Return the level of the biggest element (using the indices array 'ids' * to track which elements have been already returned). Every buffer has * already been sorted at this point. * @return the level of the biggest element or -1 if no element has been found */ @VisibleForTesting int biggest(final int[] ids) { long biggest = Long.MIN_VALUE; final int id0 = ids[0], id1 = ids[1]; int iBiggest = -1; if (0 < leafCount && 0 <= id0) { biggest = buffer[0][id0]; iBiggest = 0; } if (bufferSize < leafCount && 0 <= id1) { long x = buffer[1][id1]; if (x > biggest) { biggest = x; iBiggest = 1; } } for (int i = 2; i < currentTop + 1; i++) { if (!isBufferEmpty(i) && 0 <= ids[i]) { long x = buffer[i][ids[i]]; if (x > biggest) { biggest = x; iBiggest = i; } } } return iBiggest; } /** * Based on the number of elements inserted we can easily know if a buffer * is empty or not */ @VisibleForTesting boolean isBufferEmpty(int level) { if (level == currentTop) { return false; // root buffer (if present) is always full } else { long levelWeight = 1 << (level - 1); return (((count - leafCount) / bufferSize) & levelWeight) == 0; } } /** * Return the weight of the level ie. 2^(i-1) except for the two tree * leaves (weight=1) and for the root */ private int weight(int level) { if (level == 0) { return 1; } else if (level == maxDepth) { return rootWeight; } else { return 1 << (level - 1); } } private void allocate(int i) { if (buffer[i] == null) { buffer[i] = new long[bufferSize]; } } /** * Recursively collapse the buffers of the tree. * Upper buffers will be allocated on first access in this method. */ private void recCollapse(long[] buf, int level) { // if we reach the root, we can't add more buffer if (level == maxDepth) { // weight() return the weight of the root, in that case we need the // weight of merge result int mergeWeight = 1 << (level - 1); int idx = level % 2; long[] merged = bufferPool[idx]; long[] tmp = buffer[level]; collapse(buf, mergeWeight, buffer[level], rootWeight, merged); buffer[level] = merged; bufferPool[idx] = tmp; rootWeight += mergeWeight; } else { allocate(level + 1); // lazy allocation (if needed) if (level == currentTop) { // if we reach the top, add a new buffer collapse1(buf, buffer[level], buffer[level + 1]); currentTop += 1; rootWeight *= 2; } else if (isBufferEmpty(level + 1)) { // if the upper buffer is empty, use it collapse1(buf, buffer[level], buffer[level + 1]); } else { // it the upper buffer isn't empty, collapse with it long[] merged = bufferPool[level % 2]; collapse1(buf, buffer[level], merged); recCollapse(merged, level + 1); } } } /** * collapse two sorted Arrays of different weight * ex: [2,5,7] weight 2 and [3,8,9] weight 3 * weight x array + concat = [2,2,5,5,7,7,3,3,3,8,8,8,9,9,9] * sort = [2,2,3,3,3,5,5,7,7,8,8,8,9,9,9] * select every nth elems = [3,7,9] (n = sum weight / 2) */ @VisibleForTesting static void collapse( long[] left, int leftWeight, long[] right, int rightWeight, long[] output) { int totalWeight = leftWeight + rightWeight; int halfTotalWeight = (totalWeight / 2) - 1; int i = 0, j = 0, k = 0, cnt = 0; int weight; long smallest; while (i < left.length || j < right.length) { if (i < left.length && (j == right.length || left[i] < right[j])) { smallest = left[i]; weight = leftWeight; i++; } else { smallest = right[j]; weight = rightWeight; j++; } int cur = (cnt + halfTotalWeight) / totalWeight; cnt += weight; int next = (cnt + halfTotalWeight) / totalWeight; for(; cur < next; cur++) { output[k] = smallest; k++; } } } /** * Optimized version of collapse for collapsing two array of the same weight * (which is what we want most of the time) */ private static void collapse1( long[] left, long[] right, long[] output) { int i = 0, j = 0, k = 0, cnt = 0; long smallest; while (i < left.length || j < right.length) { if (i < left.length && (j == right.length || left[i] < right[j])) { smallest = left[i]; i++; } else { smallest = right[j]; j++; } if (cnt % 2 == 1) { output[k] = smallest; k++; } cnt++; } } }
30.717813
100
0.601194
92aa2f9a8fb2af68a79e6a27b70792de2a1ea4d1
3,195
package com.derongan.minecraft.guiy.gui.inputs; import com.derongan.minecraft.guiy.gui.ClickEvent; import com.derongan.minecraft.guiy.gui.Element; import com.derongan.minecraft.guiy.gui.GuiRenderer; import com.derongan.minecraft.guiy.gui.Size; import de.erethon.headlib.HeadLib; import java.util.ArrayList; import java.util.function.Consumer; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; /** * Input that produces a numeric result. This input is always a 9x5 element. * The result is always a Double. */ public class NumberInput implements Element, Input<Double> { private final ArrayList<String> inputs; private Consumer<Double> consumer; public NumberInput() { inputs = new ArrayList<>(9); } @Override public Size getSize() { return Size.create(9, 5); } @Override public void draw(GuiRenderer guiRenderer) { for (int y = 1; y < 6; y++) { guiRenderer.renderAt(0, y, new ItemStack(Material.IRON_BARS)); guiRenderer.renderAt(1, y, new ItemStack(Material.IRON_BARS)); guiRenderer.renderAt(2, y, new ItemStack(Material.IRON_BARS)); guiRenderer.renderAt(6, y, new ItemStack(Material.IRON_BARS)); guiRenderer.renderAt(7, y, new ItemStack(Material.IRON_BARS)); guiRenderer.renderAt(8, y, new ItemStack(Material.IRON_BARS)); } ItemStack decimal = HeadLib.WOODEN_DOT.toItemStack("."); for (int i = 0; i < 9; i++) { guiRenderer.renderAt(3 + (i % 3), 1 + (i / 3), HeadLib.valueOf(String.format("WOODEN_%d", i + 1)) .toItemStack(String.valueOf(i + 1))); } guiRenderer.renderAt(3, 4, decimal); guiRenderer.renderAt(4, 4, HeadLib.WOODEN_0.toItemStack("0")); guiRenderer.renderAt(5, 4, HeadLib.WOODEN_ARROW_LEFT.toItemStack("Delete")); for (int i = 0; i < inputs.size(); i++) { guiRenderer.renderAt((9 - inputs.size()) + i, 0, HeadLib.valueOf(String.format("WOODEN_%s", inputs.get(i))) .toItemStack(inputs.get(i))); } } @Override public void onClick(ClickEvent clickEvent) { if (clickEvent.getX() > 2 && clickEvent.getX() < 6) { if (clickEvent.getY() < 4 && clickEvent.getY() > 0) { int x = clickEvent.getX() - 3; int y = clickEvent.getY() - 1; int num = y * 3 + x + 1; inputs.add(String.valueOf(num)); } } if (clickEvent.getX() == 5 && clickEvent.getY() == 4) { inputs.remove(inputs.size() - 1); } if (clickEvent.getX() == 3 && clickEvent.getY() == 4) { inputs.add("DOT"); } if (clickEvent.getX() == 4 && clickEvent.getY() == 4) { inputs.add("0"); } } @Override public Double getResult() { return Double.valueOf(String.join("", inputs).replaceAll("DOT", ".")); } @Override public void setSubmitAction(Consumer<Double> consumer) { this.consumer = consumer; } @Override public Consumer<Double> getSubmitAction() { return consumer; } }
32.272727
119
0.594679
74a7767d32247a3dfd060c5c1d67395e53fad497
766
package Medium; /** * */ public class MyHashMap { Object[] store; /** Initialize your data structure here. */ public MyHashMap() { store=new Object[1000001]; } /** value will always be non-negative. */ public void put(int key, int value) { store[key]=value; } /** Returns the value to which the specified key is mapped, or -1 if this mp contains no mapping for the key */ public int get(int key) { if(store[key]!=null){ return (Integer)store[key];} else return -1; } /** Removes the mapping of the specified value key if this mp contains a mapping for the key */ public void remove(int key) { if(store[key]!=null){ store[key]=-1; } } }
23.9375
115
0.577023
f92c30f48b851f77e29eef1dd96010a6609d437f
1,894
package tests.pages.data; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class MainData { Path resourcesImagesFolder = Paths.get("src", "main", "resources", "images"); boolean getRandomBoolean(){ Random r = new Random(); return r.nextBoolean(); } public int getRandomNumber(int from, int to){ return ThreadLocalRandom.current().nextInt(from, to); } int generateRandomNumericValue(int length){ StringBuilder s = new StringBuilder(); for (int b = 0; b < length; b++) s.append(getRandomNumber(0, 9)); return Integer.parseInt(String.valueOf(s)); } String generateRandomWord(int length, boolean isAlphaNumeric){ String alphaUpper = "ABCDEFGHIJKLMNOPRSTQUXWVZ"; String alphaLower = alphaUpper.toLowerCase(); String numeric = "0123456789"; char [] charContainer; if (isAlphaNumeric){ charContainer = (alphaUpper + alphaLower + numeric).toCharArray(); } else {charContainer = (alphaUpper + alphaLower).toCharArray();} StringBuilder s = new StringBuilder(); for (int i = 0; i < length; i++){ s.append(charContainer[getRandomNumber(1, charContainer.length - 1)]); } return String.valueOf(s); } String generateRandomWord(int length){ return generateRandomWord(length, false); } double generateRandomDouble(int from, int to){ Random r = new Random(); return from + r.nextDouble() * (to - from); } String generateRandomText(int wordsLength){ StringBuilder s = new StringBuilder(); for (int i =0; i < wordsLength; i++){ s.append(generateRandomWord(getRandomNumber(3, 12))).append(" "); } return String.valueOf(s); } }
31.566667
82
0.630412
9f9b4be774396c74fea7822ccb1f5fd3e074fbe5
2,496
/** * * Copyright 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.jivesoftware.smackx.omemo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.Set; import org.jivesoftware.smackx.omemo.internal.OmemoCachedDeviceList; import org.junit.Test; /** * Test behavior of device lists. * * @author Paul Schaub */ public class DeviceListTest { /** * Test, whether deviceList updates are correctly merged into the cached device list. * IDs in the update become active devices, active IDs that were not in the update become inactive. * Inactive IDs that were not in the update stay inactive. */ @Test public void mergeDeviceListsTest() { OmemoCachedDeviceList cached = new OmemoCachedDeviceList(); assertNotNull(cached.getActiveDevices()); assertNotNull(cached.getInactiveDevices()); cached.getInactiveDevices().add(1); cached.getInactiveDevices().add(2); cached.getActiveDevices().add(3); Set<Integer> update = new HashSet<>(); update.add(4); update.add(1); cached.merge(update); assertTrue(cached.getActiveDevices().contains(1) && !cached.getActiveDevices().contains(2) && !cached.getActiveDevices().contains(3) && cached.getActiveDevices().contains(4)); assertTrue(!cached.getInactiveDevices().contains(1) && cached.getInactiveDevices().contains(2) && cached.getInactiveDevices().contains(3) && !cached.getInactiveDevices().contains(4)); assertTrue(cached.getAllDevices().size() == 4); assertFalse(cached.contains(17)); cached.addDevice(17); assertTrue(cached.getActiveDevices().contains(17)); assertNotNull(cached.toString()); } }
31.594937
103
0.679487
e75e0886c434e91f455d2209fa568175a3b7da35
2,068
package com.yy.other.constant; public enum TrainType { C("城际列车", true, true), D("动车组", true, true), G("高速列车", true, true), Z("直达列车", true, true), T("特快列车", true, true), K("快速列车", true, true), L("临时旅客列车", true, true), A("局管内临时旅客列车", true, true), Y("旅游列车", true, true), O("普快列车", true, false); private String desc; private boolean hasAirConditioning; private boolean isNewAirConditioning; TrainType(String desc, boolean hasAirConditioning, boolean isNewAirConditioning) { this.desc = desc; this.hasAirConditioning = hasAirConditioning; this.isNewAirConditioning = isNewAirConditioning; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public boolean isHasAirConditioning() { return hasAirConditioning; } public void setHasAirConditioning(boolean hasAirConditioning) { this.hasAirConditioning = hasAirConditioning; } public boolean isNewAirConditioning() { return isNewAirConditioning; } public void setNewAirConditioning(boolean newAirConditioning) { isNewAirConditioning = newAirConditioning; } public static TrainType getTrainType(String trainCode){ if (trainCode.startsWith("C")){ return TrainType.C; } if (trainCode.startsWith("D")){ return TrainType.D; } if (trainCode.startsWith("G")){ return TrainType.G; } if (trainCode.startsWith("Z")){ return TrainType.Z; } if (trainCode.startsWith("T")){ return TrainType.T; } if (trainCode.startsWith("K")){ return TrainType.K; } if (trainCode.startsWith("L")){ return TrainType.L; } if (trainCode.startsWith("A")){ return TrainType.A; } if (trainCode.startsWith("Y")){ return TrainType.Y; } return TrainType.O; } }
25.530864
86
0.58559
9f342b95c54df729f78aa6842d2e4642738690cf
2,906
package info.smart_tools.smartactors.task_plugins.non_blocking_queue.non_blocking_queue_plugin; import info.smart_tools.smartactors.feature_loading_system.bootstrap_item.BootstrapItem; import info.smart_tools.smartactors.base.interfaces.iaction.exception.ActionExecuteException; import info.smart_tools.smartactors.feature_loading_system.interfaces.ibootstrap.IBootstrap; import info.smart_tools.smartactors.feature_loading_system.interfaces.ibootstrap_item.IBootstrapItem; import info.smart_tools.smartactors.ioc.iioccontainer.exception.RegistrationException; import info.smart_tools.smartactors.ioc.iioccontainer.exception.ResolutionException; import info.smart_tools.smartactors.base.exception.invalid_argument_exception.InvalidArgumentException; import info.smart_tools.smartactors.ioc.ioc.IOC; import info.smart_tools.smartactors.feature_loading_system.interfaces.iplugin.IPlugin; import info.smart_tools.smartactors.feature_loading_system.interfaces.iplugin.exception.PluginException; import info.smart_tools.smartactors.task.interfaces.iqueue.IQueue; import info.smart_tools.smartactors.ioc.named_keys_storage.Keys; import info.smart_tools.smartactors.task.non_blocking_queue.NonBlockingQueue; import info.smart_tools.smartactors.base.strategy.apply_function_to_arguments.ApplyFunctionToArgumentsStrategy; import java.util.concurrent.ConcurrentLinkedQueue; /** * Plugin that registers non-blocking queue in IOC. */ public class PluginNonlockingQueue implements IPlugin { private final IBootstrap<IBootstrapItem<String>> bootstrap; /** * The constructor. * * @param bootstrap the bootstrap */ public PluginNonlockingQueue(final IBootstrap<IBootstrapItem<String>> bootstrap) { this.bootstrap = bootstrap; } @Override public void load() throws PluginException { try { IBootstrapItem<String> item = new BootstrapItem("queue"); item .after("IOC") .after("IFieldNamePlugin") .process(() -> { try { IOC.register(Keys.getOrAdd(IQueue.class.getCanonicalName()), new ApplyFunctionToArgumentsStrategy(args -> { try { return new NonBlockingQueue<>(new ConcurrentLinkedQueue<>()); } catch (Exception e) { throw new RuntimeException(e); } })); } catch (ResolutionException | RegistrationException | InvalidArgumentException e) { throw new ActionExecuteException(e); } }); bootstrap.add(item); } catch (InvalidArgumentException e) { throw new PluginException(e); } } }
45.40625
135
0.68307
0111bca2f0cdb215ea8cf75f04f950f186684dde
281
package net.renfei.api.datacenter.entity; import lombok.Data; import java.util.Date; /** * @author RenFei */ @Data public class TokenDTO { private String uuid; private String userId; private String token; private Date expiration; private Date issueTime; }
15.611111
41
0.708185
32559885de9f0139d3858e7ff683089b1101ed37
2,572
/******************************************************************************* * Copyright 2017 Cognizant Technology Solutions * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ /*package com.cognizant.devops.engines.platformengine.modules.correlation.model; *//** * @author Vishal Ganjare (vganjare) *//* public class Correlation { private CorrelationNode source; private CorrelationNode destination; private String relationName; public CorrelationNode getSource() { return source; } public void setSource(CorrelationNode source) { this.source = source; } public CorrelationNode getDestination() { return destination; } public void setDestination(CorrelationNode destination) { this.destination = destination; } public String getRelationName() { return relationName; } public void setRelationName(String relationName) { this.relationName = relationName; } }*/ package com.cognizant.devops.engines.platformengine.modules.correlation.model; public class Correlation { private CorrelationNode source; private CorrelationNode destination; private String relationName; public CorrelationNode getSource() { return source; } public void setSource(CorrelationNode source) { this.source = source; } public CorrelationNode getDestination() { return destination; } public void setDestination(CorrelationNode destination) { this.destination = destination; } public String getRelationName() { return relationName; } public void setRelationName(String relationName) { this.relationName = relationName; } @Override public String toString() { return "CorrelationJson [source=" + source + ", destination=" + destination + ", relationName=" + relationName + ", getSource()=" + getSource() + ", getDestination()=" + getDestination() + ", getRelationName()=" + getRelationName() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
30.619048
112
0.683515
9fd66dcbcf572833f5da08a76e82d8f3881df072
1,718
/* =================================================== * Copyright 2015 Alex Muthmann * * 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 de.dev.eth0.rssreader.app.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import de.dev.eth0.rssreader.R; import de.dev.eth0.rssreader.app.ui.AbstractBaseActivity; import de.dev.eth0.rssreader.core.data.model.Author; import java.util.List; /** * * @author deveth0 */ public class AuthorListAdapter extends AbstractRecyclerViewAdapter<AuthorListHolder, Author> { /** * * @param content * @param activity * @param listener */ public AuthorListAdapter(List<Author> content, AbstractBaseActivity activity, View.OnClickListener listener) { super(content, activity, listener); } @Override public AuthorListHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View itemView = LayoutInflater. from(viewGroup.getContext()). inflate(R.layout.author_list_entry, viewGroup, false); itemView.setOnClickListener(getListener()); return new AuthorListHolder(itemView, getActivity()); } }
33.038462
112
0.69383
d5e0da195cec50c27d66616336fa5af7a66ae094
1,616
package modfest.crystalmodifiers.common.block; import modfest.crystalmodifiers.common.block.blockentity.CrystalSealerBlockEntity; import net.fabricmc.fabric.api.container.ContainerProviderRegistry; import net.minecraft.block.Block; import net.minecraft.block.BlockEntityProvider; import net.minecraft.block.BlockState; import net.minecraft.block.entity.BlockEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.Identifier; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.BlockView; import net.minecraft.world.World; public class CrystalSealer extends Block implements BlockEntityProvider { public static final Identifier ID = new Identifier("crystal_sealer"); public CrystalSealer(Settings settings) { super(settings.nonOpaque()); } @Override public BlockEntity createBlockEntity(BlockView view) { return new CrystalSealerBlockEntity(); } @Override public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { if (world.isClient) return ActionResult.PASS; BlockEntity entity = world.getBlockEntity(pos); if (entity != null && entity instanceof CrystalSealerBlockEntity) { ContainerProviderRegistry.INSTANCE.openContainer(CrystalSealer.ID, player, (packetByteBuf -> packetByteBuf.writeBlockPos(pos))); } return ActionResult.SUCCESS; } }
40.4
141
0.757426
d93eec0429890290b18df9bb5031d08ee3b6e4d7
31,648
package bulgakov.arthur.avitoanalyticsm.utils; /** * Created by A on 24.04.2015. */ import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.DatabaseUtils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.support.design.widget.Snackbar; import android.util.DisplayMetrics; import android.util.Log; import android.util.Pair; import android.view.Display; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import com.jjoe64.graphview.series.DataPoint; import java.io.BufferedWriter; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Random; import bulgakov.arthur.avitoanalyticsm.R; import bulgakov.arthur.avitoanalyticsm.ui.MainActivity; public class Utils { static final String TAG = Constants.APP_TAG; public static final String MIME_TYPE_AUDIO = "audio/*"; public static final String MIME_TYPE_TEXT = "text/*"; public static final String MIME_TYPE_IMAGE = "image/*"; public static final String MIME_TYPE_VIDEO = "video/*"; public static final String MIME_TYPE_APP = "application/*"; public static final String HIDDEN_PREFIX = "."; public static final String DATE_FORMAT = "yyyy/MMMM/dd HH:mm"; /** * File (not directories) filter. * * @author paulburke */ public static FileFilter sFileFilter = new FileFilter() { @Override public boolean accept(File file) { final String fileName = file.getName(); // Return files only (not directories) and skip hidden files return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX); } }; /** * Folder (directories) filter. * * @autho r paulburke */ public static FileFilter sDirFilter = new FileFilter() { @Override public boolean accept(File file) { final String fileName = file.getName(); // Return directories only and skip hidden directories return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX); } }; private static final boolean DEBUG = false; // Set to true to enable logging /** * File and folder comparator. TODO Expose sorting option method * * @author paulburke */ public static Comparator<File> sComparator = new Comparator<File>() { @Override public int compare(File f1, File f2) { // Sort alphabetically by lower case, which is much cleaner return f1.getName().toLowerCase().compareTo( f2.getName().toLowerCase()); } }; // public static Context appContext = null; // public static RoomActivity roomActivity = null; // public static SharedPreferences preferences; private Utils() { } //private constructor to enforce Singleton pattern /** * Gets the extension of a file name, like ".png" or ".jpg". * * @param uri * @return Extension including the dot("."); "" if there is no extension; * null if uri was null. */ public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { return uri.substring(dot); } else { // No extension. return ""; } } /** * @return Whether the URI is a local one. */ public static boolean isLocal(String url) { if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) { return true; } return false; } /** * @return True if Uri is a MediaStore Uri. * @author paulburke */ public static boolean isMediaUri(Uri uri) { return "media".equalsIgnoreCase(uri.getAuthority()); } /** * Convert File into Uri. * * @param file * @return uri */ public static Uri getUri(File file) { if (file != null) { return Uri.fromFile(file); } return null; } /** * Returns the path only (without file name). * * @param file * @return */ public static File getPathWithoutFilename(File file) { if (file != null) { if (file.isDirectory()) { // no file to be split off. Return everything return file; } else { String filename = file.getName(); String filepath = file.getAbsolutePath(); // Construct path without file name. String pathwithoutname = filepath.substring(0, filepath.length() - filename.length()); if (pathwithoutname.endsWith("/")) { pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1); } return new File(pathwithoutname); } } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is {@link UtilsLocalStorageProvider}. * @author paulburke */ public static boolean isLocalStorageDocument(Uri uri) { return UtilsLocalStorageProvider.AUTHORITY.equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. * @author paulburke */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. * @author paulburke */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. * @author paulburke */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. * @author paulburke */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { if (DEBUG) DatabaseUtils.dumpCursor(cursor); final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * Get the file size in a human-readable string. * * @param size * @return * @author paulburke */ public static String getReadableFileSize(int size) { final int BYTES_IN_KILOBYTES = 1024; final DecimalFormat dec = new DecimalFormat("###.#"); final String KILOBYTES = " KB"; final String MEGABYTES = " MB"; final String GIGABYTES = " GB"; float fileSize = 0; String suffix = KILOBYTES; if (size > BYTES_IN_KILOBYTES) { fileSize = size / BYTES_IN_KILOBYTES; if (fileSize > BYTES_IN_KILOBYTES) { fileSize = fileSize / BYTES_IN_KILOBYTES; if (fileSize > BYTES_IN_KILOBYTES) { fileSize = fileSize / BYTES_IN_KILOBYTES; suffix = GIGABYTES; } else { suffix = MEGABYTES; } } } return String.valueOf(dec.format(fileSize) + suffix); } /** * Attempt to retrieve the thumbnail of given Uri from the MediaStore. This * should not be called on the UI thread. * * @param uri * @param mimeType * @return * @author paulburke */ public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) { if (DEBUG) Log.d(Constants.APP_TAG, "Attempting to get thumbnail"); if (!isMediaUri(uri)) { Log.e(Constants.APP_TAG, "You can only retrieve thumbnails for images and videos."); return null; } Bitmap bm = null; if (uri != null) { final ContentResolver resolver = context.getContentResolver(); Cursor cursor = null; try { cursor = resolver.query(uri, null, null, null, null); if (cursor.moveToFirst()) { final int id = cursor.getInt(0); if (DEBUG) Log.d(TAG, "Got thumb ID: " + id); if (mimeType.contains("video")) { bm = MediaStore.Video.Thumbnails.getThumbnail( resolver, id, MediaStore.Video.Thumbnails.MINI_KIND, null); } else if (mimeType.contains(Utils.MIME_TYPE_IMAGE)) { bm = MediaStore.Images.Thumbnails.getThumbnail( resolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null); } } } catch (Exception e) { if (DEBUG) Log.e(TAG, "getThumbnail", e); } finally { if (cursor != null) cursor.close(); } } return bm; } /** * Get the Intent for selecting content to be used in an Intent Chooser. * * @return The intent for opening a file with Intent.createChooser() * @author paulburke */ public static Intent createGetContentIntent() { // Implicitly allow the user to select a particular kind of data final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // The MIME data type filter intent.setType("*/*"); // Only return URIs that can be opened with ContentResolver intent.addCategory(Intent.CATEGORY_OPENABLE); return intent; } public static File saveBitmap(Bitmap bitmap, String dirPath, String fileName) { try { File dir = new File(dirPath); dir.mkdirs(); File file = new File(dir, fileName + ".png"); if (file.exists()) file.delete(); FileOutputStream fOut = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut); fOut.flush(); fOut.close(); return file; } catch (Exception e) { Log.d(Constants.APP_TAG, e.toString()); return null; } } public static Bitmap getBitmapByPath(String path) throws Exception { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeFile(path, options); } public static String getSaveDir(Activity activity) { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + activity.getString(R.string.app_dir) + "/saved"; } public static String getAppDir(Activity activity) { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + activity.getString(R.string.app_dir); } public static String getTempDir(Activity activity) { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + activity.getString(R.string.app_dir) + "/temp"; } public static String getCacheDir(Activity activity) { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + activity.getString(R.string.app_dir) + "/cached"; } public static boolean isNoInternet(Context context) { try { ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); return activeNetwork == null || !activeNetwork.isAvailable() || !activeNetwork.isConnected(); } catch (Exception e) { return true; } } public static int dpToPx(int dp, Context context) { return Math.round(dp * (context.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT)); } //picture of w*h -> picture of W*h1 or w1*H (proportional scaling) public static LinearLayout.LayoutParams scaleToLl(int w, int h, int W, int H) { float k; if ((float) h * W / w > H) k = (float) H / h; else k = (float) W / w; h *= k; w *= k; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(w, h); return layoutParams; } public static int displayWidth; public static int displayHeight; public static void getDisplaySize(Activity roomActivity) { Display display = roomActivity.getWindowManager().getDefaultDisplay(); if (Build.VERSION.SDK_INT >= 17) { //new pleasant way to get real metrics DisplayMetrics realMetrics = new DisplayMetrics(); display.getRealMetrics(realMetrics); displayWidth = realMetrics.widthPixels; displayHeight = realMetrics.heightPixels; } else if (Build.VERSION.SDK_INT >= 14) { //reflection for this weird in-between time try { Method mGetRawH = Display.class.getMethod("getRawHeight"); Method mGetRawW = Display.class.getMethod("getRawWidth"); displayWidth = (Integer) mGetRawW.invoke(display); displayHeight = (Integer) mGetRawH.invoke(display); } catch (Exception e) { //this may not be 100% accurate, but it's all we've got displayWidth = display.getWidth(); displayHeight = display.getHeight(); // Log.d("!", "Couldn't use reflection to get the real display metrics."); } } else { //This should be close, as lower API devices should not have window navigation bars displayWidth = display.getWidth(); displayHeight = display.getHeight(); } } public static Bitmap getResizedBitmap(Bitmap bitmap) { if (bitmap == null) return null; int maxSize = 1000; int width = bitmap.getWidth(); int height = bitmap.getHeight(); float bitmapRatio = (float) width / (float) height; if (bitmapRatio > 0) { width = maxSize; height = (int) (width / bitmapRatio); } else { height = maxSize; width = (int) (height * bitmapRatio); } return Bitmap.createScaledBitmap(bitmap, width, height, true); } public static String stringFromRes(Context context, int id) { return context.getString(id); } public static Bitmap rotateBitmap(Bitmap bitmap, int degree) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix mtx = new Matrix(); mtx.postRotate(degree); try { Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true); bitmap.recycle(); return newBitmap; } catch (OutOfMemoryError error) { return null; } } public static boolean isInt(String s) { try { Integer.parseInt(s); } catch (Exception e) { return false; } return true; } public static int toInt(String s) { try { return Integer.parseInt(s); } catch (Exception e) { return -1; } } public static boolean dateCompare(String unbanDateStr) { if (unbanDateStr == null) return true; SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); try { Date unbanDate = sdf.parse(unbanDateStr); return new Date().after(unbanDate); } catch (ParseException e) { Log.d("!", "wrong date format"); return true; } } public static int getIdByLink(String link) { int i = link.lastIndexOf("_"); if (i == -1) return -1; link = link.substring(i + 1); if (link.length() < 9 || !Utils.isInt(link)) return -1; return Utils.toInt(link); } public static void removeArrayPrefByPos(SharedPreferences prefs, String itemKey, int pos) { String sizeKey = getSizeKey(itemKey); int size = prefs.getInt(sizeKey, 0); for (int i = pos; i < size; i++) { prefs.edit().putString(itemKey + i, prefs.getString(itemKey + (i + 1), null)).commit(); } prefs.edit().remove(itemKey + (size - 1)).putInt(sizeKey, size - 1).commit(); } public static void addArrayPref(SharedPreferences prefs, String itemKey, String item) { Log.d(Constants.APP_TAG, "added!"); String sizeKey = getSizeKey(itemKey); int size = prefs.getInt(sizeKey, 0); prefs.edit().putString(itemKey + size, item).putInt(sizeKey, size + 1).commit(); } private static String getSizeKey(String itemKey) { switch (itemKey) { case Constants.SAVED_SEARCH_KEY: return Constants.SAVED_SEARCH_SIZE_KEY; case Constants.FAVOURITE_AD_KEY: return Constants.FAVOURITE_AD_SIZE_KEY; default: return Constants.SAVED_SEARCH_ADS_SIZE_KEY; } } public static void log(String text, Context ctx) { File file = new File(ctx.getExternalFilesDir(null), "service_log.txt"); if (!file.exists()) { Log.d(Constants.APP_TAG, "creating app folder..."); try { if (!file.createNewFile()) Log.d(Constants.APP_TAG, "log file not created!"); else Log.d(Constants.APP_TAG, "log file created!"); } catch (IOException e) { Log.d(Constants.APP_TAG, "Error writing "); } } else Log.d(Constants.APP_TAG, "folder exists = " + file.getAbsolutePath()); SimpleDateFormat sdfTime = new SimpleDateFormat(DATE_FORMAT); text = "At " + sdfTime.format(new Date()) + " -> " + text; try { BufferedWriter buf = new BufferedWriter(new FileWriter(file, true)); buf.append(text); buf.newLine(); buf.close(); } catch (IOException e) { Log.d(Constants.APP_TAG, e.toString()); } } public static String translit(String s) { if (s.equals("Резюме")) return "rezume"; HashMap<Character, String> f = new HashMap<>(); f.put('а', "a"); f.put('б', "b"); f.put('в', "v"); f.put('г', "g"); f.put('д', "d"); f.put('е', "e"); f.put('ё', "e"); f.put('ж', "zh"); f.put('з', "z"); f.put('и', "i"); f.put('й', "y"); f.put('к', "k"); f.put('л', "l"); f.put('м', "m"); f.put('н', "n"); f.put('о', "o"); f.put('п', "p"); f.put('р', "r"); f.put('с', "s"); f.put('т', "t"); f.put('у', "u"); f.put('ф', "f"); f.put('х', "h"); f.put('ц', "ts"); f.put('ч', "ch"); f.put('ш', "sh"); f.put('щ', "sch"); f.put('ъ', ""); f.put('ы', "y"); f.put('ь', ""); f.put('э', "e"); f.put('ю', "yu"); f.put('я', "ya"); f.put(' ', "_"); s = s.toLowerCase().replace(",", ""); String res = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (f.containsKey(c)) res += f.get(c); else res += c; } return res; } public static String getStringElement(String s, String keyword, char l, char r) { int i = s.indexOf(keyword); if (i == -1) return null; while (s.charAt(i) != l) i++; i++; int j = i; while (s.charAt(j) != r) j++; return s.substring(i, j).replace("&nbsp;", " "); } public static String getStringElement(String s, char l, char r) { return s.substring(s.lastIndexOf(l) + 1, s.indexOf(r)); } /*public static void setAirplaneMode(Context context, boolean enable) { if (Build.VERSION.SDK_INT < 17) { AirplaneModeSDK8.setAirplaneMode(context, enable); } else { AirplaneModeSDK17.setAirplaneMode(context, enable); } } public static void systemAppMoverDialog(final Context context) { if (!AirplaneModeSDK17.isSystemApp(context)) { Log.d(TAG, "not system app"); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Pair<Integer, String> ret = moveDataSystemApp("base.apk", "/data/app/bulgakov.arthur.avitoanalytics-*", "/system/priv-app", "root", false); if (0 != ret.first) { errorDialog(context, ret.second); } } }); builder.setMessage("Move app to system?"); builder.setTitle("Question:"); // Create the AlertDialog AlertDialog dialog = builder.create(); dialog.show(); } else { final boolean updatedSystemApp = AirplaneModeSDK17.isUpdatedSystemApp(context); AlertDialog.Builder builder = new AlertDialog.Builder(context); // Add the buttons builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Pair<Integer, String> ret = moveDataSystemApp("base.apk", "/system/priv-app", "/data/app/bulgakov.arthur.avitoanalytics-*", "system", updatedSystemApp); if (0 != ret.first) { errorDialog(context, ret.second); } } }); builder.setMessage("Move app to system?"); builder.setTitle("Question:"); // Create the AlertDialog AlertDialog dialog = builder.create(); dialog.show(); } } private static void errorDialog(Context context, final String errorMessage) { AlertDialog.Builder builder = new AlertDialog.Builder(context); // Add the buttons builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); builder.setMessage("Error:\n" + errorMessage); builder.setTitle("Error moving app"); // Create the AlertDialog AlertDialog dialog = builder.create(); dialog.show(); } static boolean isSuperUser() { boolean isSuperUser = false; Pair<Integer, String> ret; // check for /system/xbin/su ret = ProcessHelper.runCmd(false, "sh", "-c", "[ -f /system/xbin/su ]"); isSuperUser = (0 == ret.first); if (!isSuperUser) { // check for /system/bin/su ret = ProcessHelper.runCmd(false, "sh", "-c", "[ -f /system/bin/su ]"); isSuperUser = (0 == ret.first); } Log.d(TAG, "isSuperUser = " + isSuperUser); return isSuperUser; } static private Pair<Integer, String> moveDataSystemApp(String app, String from, String to, String owner, boolean updatedSystemApp) { int exitCode = -1; StringBuilder sb = new StringBuilder(); // make /system/app writable Pair<Integer, String> ret = ProcessHelper.runCmd(true, "su", "-c", "mount -o remount,rw /system"); sb.append(ret.second); if (0 != (exitCode = ret.first)) return new Pair<Integer, String>(exitCode, sb.toString()); if (!updatedSystemApp) { // move MiniStatus to /to/app ret = ProcessHelper.runCmd(true, "su", "-c", "cp " + from + "/" + app + " " + to); sb.append(ret.second); if (0 != (exitCode = ret.first)) return new Pair<Integer, String>(exitCode, sb.toString()); // set permissions ret = ProcessHelper.runCmd(true, "su", "-c", "chmod 644 " + to + "/" + app); sb.append(ret.second); if (0 != (exitCode = ret.first)) return new Pair<Integer, String>(exitCode, sb.toString()); // set owner ret = ProcessHelper.runCmd(true, "su", "-c", "chown " + owner + ":" + owner + " " + to + "/" + app); sb.append(ret.second); if (0 != (exitCode = ret.first)) return new Pair<Integer, String>(exitCode, sb.toString()); } // remove MiniStatus from /from/app ret = ProcessHelper.runCmd(true, "su", "-c", "rm " + from + "/" + app); sb.append(ret.second); if (0 != (exitCode = ret.first)) return new Pair<Integer, String>(exitCode, sb.toString()); // reboot ret = ProcessHelper.runCmd(true, "su", "-c", "reboot"); sb.append(ret.second); if (0 != (exitCode = ret.first)) return new Pair<Integer, String>(exitCode, sb.toString()); return new Pair<Integer, String>(exitCode, sb.toString()); }*/ public static void toast(final Activity activity, final String s) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, s, Toast.LENGTH_SHORT).show(); } }); } public static void snack(View view, String s) { Snackbar.make(view, s, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } public static String getCurrentDate() { Date curDate = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); return format.format(curDate); } public static AlertDialog.Builder getAlertDialogBuilder(Activity activity, String title, String message, View view) { return new AlertDialog.Builder(activity).setTitle(title).setMessage(message).setView(view); } public static void showProgress(Activity activity) { activity.runOnUiThread(new Runnable() { @Override public void run() { MainActivity.pd.show(); } }); } public static void hideProgress(Activity activity) { activity.runOnUiThread(new Runnable() { @Override public void run() { MainActivity.pd.hide(); } }); } public static DataPoint[] getAvitoDelPoints(DataPoint[] shopPoints, double k, Random random) { DataPoint[] avitoDelPoints = new DataPoint[shopPoints.length]; for (int i = 0; i < shopPoints.length; i++) { double delPrice = shopPoints[i].getY() * (randNear(random, 0.9, 0.04) - k * randNear(random, 0.1, 0.02)); avitoDelPoints[i] = new DataPoint(shopPoints[i].getX(), delPrice); } return avitoDelPoints; } public static ArrayList<Pair<Integer, Integer>> dtw(ArrayList<Integer> a1, ArrayList<Integer> a2) { int n = a1.size(); int m = a2.size(); int d[][] = new int[n][m]; // the euclidian distances matrix for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) d[i][j] = (int) Math.pow(a1.get(i) - a2.get(j), 2); // determinate of minimal distance int dw[][] = new int[n][n]; dw[0][0] = d[0][0]; for (int i = 1; i < n; i++) dw[i][0] = d[i][0] + dw[i - 1][0]; for (int j = 1; j < m; j++) dw[0][j] = d[0][j] + dw[0][j - 1]; for (int i = 1; i < n; i++) for (int j = 1; j < m; j++) if (dw[i - 1][j - 1] <= dw[i - 1][j]) if (dw[i - 1][j - 1] <= dw[i][j - 1]) dw[i][j] = d[i][j] + dw[i - 1][j - 1]; else dw[i][j] = d[i][j] + dw[i][j - 1]; else if (dw[i - 1][j] <= dw[i][j - 1]) dw[i][j] = d[i][j] + dw[i - 1][j]; else dw[i][j] = d[i][j] + dw[i][j - 1]; int i = n - 1, j = m - 1; // determinate of warping path ArrayList<Pair<Integer, Integer>> path = new ArrayList<>(); do { if (i > 0 && j > 0) { if (dw[i - 1][j - 1] <= dw[i - 1][j]) if (dw[i - 1][j - 1] <= dw[i][j - 1]) { i--; j--; } else j--; else if (dw[i - 1][j] <= dw[i][j - 1]) i--; else j--; } else if (i == 0) { j--; } else { i--; } path.add(new Pair<>(j, i)); } while (i != 0 || j != 0); return path; } public static double randNear(Random random, double v, double rK) { return v - random.nextDouble() * 2 * rK + rK; } public static DataPoint[] toDataPoint(ArrayList<Integer> a) { DataPoint[] d = new DataPoint[a.size()]; for (int i = 0; i < a.size(); i++) { d[i] = new DataPoint(i, a.get(i)); } return d; } public static double dist(int x1, int y1, int x2, int y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } public static boolean isCategoryLeaf(String category) { for (int i = 1; i < Constants.treeParentNum.length; i++) { if (Constants.categories[Constants.treeParentNum[i]].equals(category)) return false; } return true; } public static boolean containsIgnoreCase(String src, String what) { final int length = what.length(); if (length == 0) return true; // Empty string is contained final char firstLo = Character.toLowerCase(what.charAt(0)); final char firstUp = Character.toUpperCase(what.charAt(0)); for (int i = src.length() - length; i >= 0; i--) { // Quick check before calling the more expensive regionMatches() method: final char ch = src.charAt(i); if (ch != firstLo && ch != firstUp) continue; if (src.regionMatches(true, i, what, 0, length)) { return true; } } return false; } }
33.848128
135
0.58405
644eb1ecb4cf68e76d7196d4538db658453208df
511
package com.changgou.goods.feign; import com.changgou.goods.pojo.Spu; import entity.Result; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(value="goods") @RequestMapping("/spu") public interface SpuFeign { @GetMapping("/{id}") public Result<Spu> findById(@PathVariable(name = "id") Long id); }
28.388889
68
0.78865
d3e9c73dee0dba9650efe80d6d3d2ab8f05f0e6b
1,010
package training.movie; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class MovieService { @Autowired RedisTemplate<String,String> redis; @Autowired MovieRepository movieRepo; public Set<String> getAllMovies(String key) { return redis.opsForSet().members(key); } public Movie createMovie(Movie movie) { movie.setId(getNextId()); return movieRepo.save(movie); } public Optional<Movie> getMovie(String id) { return movieRepo.findById(id); } public Iterable<Movie> getAll() { return movieRepo.findAll(); } public void watch(String id) { redis.opsForHash().increment("movies:" + id, "watchCount", 1L); } private String getNextId() { return redis.opsForValue().increment("movieId").toString(); } }
23.488372
71
0.683168
efa3c6cc436fbb9c08615bb9a382cf5e9da2d1da
349
package org.nypl.simplified.app.reader; import java.io.File; /** * The type of asynchronous EPUB loaders. */ public interface ReaderReadiumEPUBLoaderType { /** * Attempt to load an EPUB. * * @param f The EPUB file * @param l The EPUB result listener */ void loadEPUB( File f, ReaderReadiumEPUBLoadListenerType l); }
15.863636
44
0.679083