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
4f1832611f50985dbb6eb0ea301c25921048b74b
7,583
/* * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.uictrls.fineupload5.ui; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.string.StringHelper; import com.helger.html.jscode.IJSExpression; import com.helger.html.jscode.JSAssocArray; import com.helger.html.jscode.html.JSHtml; import com.helger.photon.uictrls.fineupload5.FineUploader5Core; public class FineUploader5UI extends FineUploader5Core { public static final String DEFAULT_TEMPLATE = "qq-template"; private String m_sElementID; private String m_sListElementID; private IJSExpression m_aShowMessage; private IJSExpression m_aShowConfirm; private IJSExpression m_aShowPrompt; private String m_sTemplateID = DEFAULT_TEMPLATE; public FineUploader5UI (@Nonnull final Locale aDisplayLocale) { super (aDisplayLocale); } @Nullable public String getElementID () { return m_sElementID; } /** * Container element for the default drop zone * * @param sElementID * New value. May be <code>null</code>. * @return this for chaining */ @Nonnull public FineUploader5UI setElementID (@Nullable final String sElementID) { m_sElementID = sElementID; return this; } @Nullable public String getListElementID () { return m_sListElementID; } /** * Container element for the item list. * * @param sListElementID * New value. May be <code>null</code>. * @return this for chaining */ @Nonnull public FineUploader5UI setListElementID (@Nullable final String sListElementID) { m_sListElementID = sListElementID; return this; } @Nullable public IJSExpression getShowMessage () { return m_aShowMessage; } /** * Provide a function here to display a message to the user when the uploader * receives an error or the user attempts to leave the page. The provided * function may return a promise if one wishes to do asynchronous work whilst * waiting for user input.<br> * Default: <code>function(message) { window.alert(message); }</code> * * @param aShowMessage * New value. May be <code>null</code>. * @return this for chaining */ @Nonnull public FineUploader5UI setShowMessage (@Nullable final IJSExpression aShowMessage) { m_aShowMessage = aShowMessage; return this; } @Nullable public IJSExpression getShowConfirm () { return m_aShowConfirm; } /** * Provide a function here to prompt the user to confirm deletion of a file. * The provided function may return a promise if one wishes to do asynchronous * work whilst waiting for user input.<br> * Default: <code>function(message) { window.confirm(message); }</code> * * @param aShowConfirm * New value. May be <code>null</code>. * @return this for chaining */ @Nonnull public FineUploader5UI setShowConfirm (@Nullable final IJSExpression aShowConfirm) { m_aShowConfirm = aShowConfirm; return this; } @Nullable public IJSExpression getShowPrompt () { return m_aShowPrompt; } /** * Provide a function here to prompt the user for a filename when pasting * file(s). The provided function may return a promise if one wishes to do * asynchronous work whilst waiting for user input.<br> * Default: * <code>function(message, defaultValue) { window.prompt(message, defaultValue); }</code> * * @param aShowPrompt * New value. May be <code>null</code>. * @return this for chaining */ @Nonnull public FineUploader5UI setShowPrompt (@Nullable final IJSExpression aShowPrompt) { m_aShowPrompt = aShowPrompt; return this; } @Nonnull @Nonempty public String getTemplateID () { return m_sTemplateID; } /** * This points to the container element that contains the template to use for * one or more Fine Uploader UI instances. You can either specify a string, * which is the element ID (the ID of the container element on the page) or an * Element that points to the container element. * * @param sTemplateID * New value. May neither be <code>null</code> nor empty. * @return this for chaining */ @Nonnull public FineUploader5UI setTemplateID (@Nonnull @Nonempty final String sTemplateID) { ValueEnforcer.notEmpty (sTemplateID, "TemplateID"); m_sTemplateID = sTemplateID; return this; } @Override protected void extendJSONPart (@Nonnull @Nonempty final String sKey, @Nonnull final JSAssocArray aAssocArray, @Nullable final Locale aDisplayLocale) { if (sKey.equals (KEY_DELETE_FILE)) { if (aDisplayLocale != null) { aAssocArray.add ("confirmMessage", EFineUploader5UIText.DELETE_FILE_CONFIRM_MESSAGE.getDisplayText (aDisplayLocale)); aAssocArray.add ("deletingFailedText", EFineUploader5UIText.DELETE_FILE_DELETING_FAILED_TEXT.getDisplayText (aDisplayLocale)); aAssocArray.add ("deletingStatusText", EFineUploader5UIText.DELETE_FILE_DELETING_STATUS_TEXT.getDisplayText (aDisplayLocale)); } } } @Override protected void extendJSON (@Nonnull final JSAssocArray aRoot, @Nullable final Locale aDisplayLocale) { if (StringHelper.hasNoText (m_sElementID)) aRoot.add ("element", JSHtml.documentGetElementById (m_sElementID)); if (StringHelper.hasNoText (m_sListElementID)) aRoot.add ("listElement", JSHtml.documentGetElementById (m_sListElementID)); if (m_aShowMessage != null) aRoot.add ("showMessage", m_aShowMessage); if (m_aShowConfirm != null) aRoot.add ("showConfirm", m_aShowConfirm); if (m_aShowPrompt != null) aRoot.add ("showPrompt", m_aShowPrompt); if (!m_sTemplateID.equals (DEFAULT_TEMPLATE)) aRoot.add ("template", JSHtml.documentGetElementById (m_sTemplateID)); if (aDisplayLocale != null) { final JSAssocArray aSub = new JSAssocArray (); aSub.add ("uploadButton", EFineUploader5UIText.UPLOAD_BUTTON.getDisplayText (aDisplayLocale)); aSub.add ("cancelButton", EFineUploader5UIText.CANCEL_BUTTON.getDisplayText (aDisplayLocale)); aSub.add ("retryButton", EFineUploader5UIText.RETRY_BUTTON.getDisplayText (aDisplayLocale)); aSub.add ("failUpload", EFineUploader5UIText.FAIL_UPLOAD.getDisplayText (aDisplayLocale)); aSub.add ("dragZone", EFineUploader5UIText.DRAG_ZONE.getDisplayText (aDisplayLocale)); aSub.add ("dropProcessing", EFineUploader5UIText.DROP_PROCESSING.getDisplayText (aDisplayLocale)); aSub.add ("formatProgress", EFineUploader5UIText.FORMAT_PROGRESS.getDisplayText (aDisplayLocale)); aSub.add ("waitingForResponse", EFineUploader5UIText.WAITING_FOR_RESPONSE.getDisplayText (aDisplayLocale)); aRoot.add ("text", aSub); } } }
32.82684
134
0.71568
327c8d3599ef9594f22a55fc4111830cfd9d7540
5,171
/* Copyright 2004 - 2007 Kasper Nielsen <kasper@codehaus.org> Licensed under * the Apache 2.0 License, see http://coconut.codehaus.org/license. */ package org.coconut.attribute.spi; import java.io.Serializable; import org.coconut.attribute.Attribute; import org.coconut.attribute.AttributeMap; import org.coconut.attribute.Attributes; import org.coconut.operations.Predicates; import org.coconut.operations.Ops.Mapper; import org.coconut.operations.Ops.Predicate; /** * An abstract implementation of {@link Attribute}. * * @author <a href="mailto:kasper@codehaus.org">Kasper Nielsen</a> * @version $Id: Cache.java,v 1.2 2005/04/27 15:49:16 kasper Exp $ * @param <T> * the type of this attribute */ public abstract class AbstractAttribute<T> implements Attribute<T>, Serializable { /** The type of this attribute, as returned {@link #getAttributeType()}. */ private final transient Class<T> clazz; /** The default value of this attribute. */ private final transient T defaultValue; /** A Mapper that takes an AttributeMap and returns the value of this attribute. */ private final transient Mapper<AttributeMap, T> mapper = new AttributeMapToT(); /** The name of this attribute. */ private final transient String name; /** * Creates a new AbstractAttribute. * * @param name * the name of the attribute * @param clazz * the type of this attribute * @param defaultValue * the default value of this attribute */ public AbstractAttribute(String name, Class<T> clazz, T defaultValue) { if (name == null) { throw new NullPointerException("name is null"); } else if (clazz == null) { throw new NullPointerException("clazz is null"); } this.name = name; this.clazz = clazz; checkValid(defaultValue); this.defaultValue = defaultValue; } /** {@inheritDoc} */ public void checkValid(T value) { if (!isValid(value)) { throw new IllegalArgumentException("Illegal value for attribute " + getName() + ", value = " + value); } } /** {@inheritDoc} */ public T fromString(String str) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public final Class<T> getAttributeType() { return clazz; } /** {@inheritDoc} */ public T getDefaultValue() { return defaultValue; } /** {@inheritDoc} */ public final String getName() { return name; } /** {@inheritDoc} */ public final T getValue(AttributeMap attributes) { return getValue(attributes, defaultValue); } /** {@inheritDoc} */ public T getValue(AttributeMap attributes, T defaultValue) { return (T) attributes.get(this, defaultValue); } /** {@inheritDoc} */ public boolean isSet(AttributeMap attributes) { return attributes.containsKey(this); } /** {@inheritDoc} */ public boolean isValid(T value) { return true; // all values are accepted by default. } /** * Returns a mapper that extracts the value of this attribute from an * {@link AttributeMap}, or returns {@link #getDefaultValue()} if this attribute is * not present. * * @return a mapper from an AttributeMap to the value of this attribute */ public Mapper<AttributeMap, T> map() { return mapper; } /** {@inheritDoc} */ public void remove(AttributeMap attributes) { attributes.remove(this); } /** {@inheritDoc} */ public AttributeMap setValue(AttributeMap attributes, T value) { if (attributes == null) { throw new NullPointerException("attributes is null"); } checkValid(value); attributes.put(this, value); return attributes; } /** * Returns an AttributeMap containing only this attribute mapping to the specified * value. * * @param value * the value to create the singleton from * @return an AttributeMap containing only this attribute mapping to the specified * value */ public AttributeMap singleton(T value) { checkValid(value); return Attributes.singleton(this, value); } /** {@inheritDoc} */ @Override public String toString() { return name; } protected Predicate<AttributeMap> filter(Predicate<? super T> p) { return Predicates.mapAndEvaluate(map(), p); } /** * A MapperToLong that maps from an attribute map to the value of this attribute. */ class AttributeMapToT implements Mapper<AttributeMap, T>, Serializable { /** serialVersionUID. */ private static final long serialVersionUID = -953844729549732090L; /** {@inheritDoc} */ public T map(AttributeMap t) { return getValue(t); } } }
30.239766
90
0.601044
2fd69f2e6f7354616798ca1e35712599ab400134
9,122
/* * 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.jackrabbit.oak.security.authorization; import java.security.Principal; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import javax.jcr.security.AccessControlManager; import com.google.common.collect.ImmutableList; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.PropertyOption; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.namepath.NamePathMapper; import org.apache.jackrabbit.oak.plugins.name.NamespaceConstants; import org.apache.jackrabbit.oak.plugins.nodetype.NodeTypeConstants; import org.apache.jackrabbit.oak.plugins.version.VersionablePathHook; import org.apache.jackrabbit.oak.security.authorization.accesscontrol.AccessControlImporter; import org.apache.jackrabbit.oak.security.authorization.accesscontrol.AccessControlManagerImpl; import org.apache.jackrabbit.oak.security.authorization.accesscontrol.AccessControlValidatorProvider; import org.apache.jackrabbit.oak.security.authorization.permission.PermissionHook; import org.apache.jackrabbit.oak.security.authorization.permission.PermissionProviderImpl; import org.apache.jackrabbit.oak.security.authorization.permission.PermissionStoreValidatorProvider; import org.apache.jackrabbit.oak.security.authorization.permission.PermissionValidatorProvider; import org.apache.jackrabbit.oak.security.authorization.restriction.RestrictionProviderImpl; import org.apache.jackrabbit.oak.spi.commit.CommitHook; import org.apache.jackrabbit.oak.spi.commit.MoveTracker; import org.apache.jackrabbit.oak.spi.commit.ValidatorProvider; import org.apache.jackrabbit.oak.spi.lifecycle.WorkspaceInitializer; import org.apache.jackrabbit.oak.spi.security.CompositeConfiguration; import org.apache.jackrabbit.oak.spi.security.ConfigurationBase; import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters; import org.apache.jackrabbit.oak.spi.security.Context; import org.apache.jackrabbit.oak.spi.security.SecurityConfiguration; import org.apache.jackrabbit.oak.spi.security.SecurityProvider; import org.apache.jackrabbit.oak.spi.security.authorization.AuthorizationConfiguration; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants; import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionConstants; import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionProvider; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider; import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants; import org.apache.jackrabbit.oak.spi.xml.ImportBehavior; import org.apache.jackrabbit.oak.spi.xml.ProtectedItemImporter; /** * Default implementation of the {@code AccessControlConfiguration}. */ @Component(metatype = true, label = "Apache Jackrabbit Oak AuthorizationConfiguration") @Service({AuthorizationConfiguration.class, SecurityConfiguration.class}) @Properties({ @Property(name = PermissionConstants.PARAM_PERMISSIONS_JR2, label = "Jackrabbit 2.x Permissions", description = "Enforce backwards compatible permission validation with respect to the configurable options.", cardinality = 2, options = { @PropertyOption(name = "USER_MANAGEMENT", value = "USER_MANAGEMENT"), @PropertyOption(name = "REMOVE_NODE", value = "REMOVE_NODE") }), @Property(name = ProtectedItemImporter.PARAM_IMPORT_BEHAVIOR, label = "Import Behavior", description = "Behavior for access control related items upon XML import.", options = { @PropertyOption(name = ImportBehavior.NAME_ABORT, value = ImportBehavior.NAME_ABORT), @PropertyOption(name = ImportBehavior.NAME_BESTEFFORT, value = ImportBehavior.NAME_BESTEFFORT), @PropertyOption(name = ImportBehavior.NAME_IGNORE, value = ImportBehavior.NAME_IGNORE) }, value = ImportBehavior.NAME_ABORT), @Property(name = PermissionConstants.PARAM_READ_PATHS, label = "Readable Paths", description = "Enable full read access to regular nodes and properties at the specified paths irrespective of other policies that may take effective.", value = { NamespaceConstants.NAMESPACES_PATH, NodeTypeConstants.NODE_TYPES_PATH, PrivilegeConstants.PRIVILEGES_PATH }), @Property(name = PermissionConstants.PARAM_ADMINISTRATIVE_PRINCIPALS, label = "Administrative Principals", description = "Allows to specify principals that should be granted full permissions on the complete repository content.", cardinality = 10), @Property(name = CompositeConfiguration.PARAM_RANKING, label = "Ranking", description = "Ranking of this configuration in a setup with multiple authorization configurations.", intValue = 100) }) public class AuthorizationConfigurationImpl extends ConfigurationBase implements AuthorizationConfiguration { public AuthorizationConfigurationImpl() { super(); } @SuppressWarnings("UnusedDeclaration") @Activate private void activate(Map<String, Object> properties) { setParameters(ConfigurationParameters.of(properties)); } public AuthorizationConfigurationImpl(SecurityProvider securityProvider) { super(securityProvider, securityProvider.getParameters(NAME)); } //----------------------------------------------< SecurityConfiguration >--- @Nonnull @Override public String getName() { return NAME; } @Nonnull @Override public Context getContext() { return AuthorizationContext.getInstance(); } @Nonnull @Override public WorkspaceInitializer getWorkspaceInitializer() { return new AuthorizationInitializer(); } @Nonnull @Override public List<? extends CommitHook> getCommitHooks(@Nonnull String workspaceName) { return ImmutableList.of( new VersionablePathHook(workspaceName), new PermissionHook(workspaceName, getRestrictionProvider())); } @Nonnull @Override public List<ValidatorProvider> getValidators(@Nonnull String workspaceName, @Nonnull Set<Principal> principals, @Nonnull MoveTracker moveTracker) { return ImmutableList.of( new PermissionStoreValidatorProvider(), new PermissionValidatorProvider(getSecurityProvider(), workspaceName, principals, moveTracker), new AccessControlValidatorProvider(getSecurityProvider())); } @Nonnull @Override public List<ProtectedItemImporter> getProtectedItemImporters() { return Collections.<ProtectedItemImporter>singletonList(new AccessControlImporter()); } //-----------------------------------------< AccessControlConfiguration >--- @Nonnull @Override public AccessControlManager getAccessControlManager(@Nonnull Root root, @Nonnull NamePathMapper namePathMapper) { return new AccessControlManagerImpl(root, namePathMapper, getSecurityProvider()); } @Nonnull @Override public RestrictionProvider getRestrictionProvider() { RestrictionProvider restrictionProvider = getParameters().getConfigValue(AccessControlConstants.PARAM_RESTRICTION_PROVIDER, null, RestrictionProvider.class); if (restrictionProvider == null) { // default restrictionProvider = new RestrictionProviderImpl(); } return restrictionProvider; } @Nonnull @Override public PermissionProvider getPermissionProvider(@Nonnull Root root, @Nonnull String workspaceName, @Nonnull Set<Principal> principals) { return new PermissionProviderImpl(root, workspaceName, principals, this); } }
48.521277
167
0.738544
8231097d083d56721e33e29e5e0179dca3365feb
1,975
package com.github.cataclysmuprising.jpa.repository.impl; import com.github.cataclysmuprising.jpa.criteria.ContactInfoCriteria; import com.github.cataclysmuprising.jpa.entity.ContactInfoEntity; import com.github.cataclysmuprising.jpa.entity.QContactInfoEntity; import com.github.cataclysmuprising.jpa.repository.ContactInfoRepository; import com.github.cataclysmuprising.jpa.repository.base.AbstractRepositoryImpl; import com.querydsl.jpa.impl.JPADeleteClause; import com.querydsl.jpa.impl.JPAQueryFactory; import com.querydsl.jpa.impl.JPAUpdateClause; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import static com.github.cataclysmuprising.jpa.config.PrimaryPersistenceContext.ENTITY_MANAGER_FACTORY; @Repository public class ContactInfoRepositoryImpl extends AbstractRepositoryImpl<ContactInfoEntity, ContactInfoCriteria, Long> implements ContactInfoRepository { private final QContactInfoEntity qEntity = QContactInfoEntity.contactInfoEntity; public ContactInfoRepositoryImpl(@Qualifier(ENTITY_MANAGER_FACTORY) EntityManager entityManager) { super(new JpaMetamodelEntityInformation<>(ContactInfoEntity.class, entityManager.getMetamodel()), entityManager); } @Override public long update(ContactInfoEntity entity, ContactInfoCriteria criteria) { JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager); JPAUpdateClause jpaUpdateClause = queryFactory.update(qEntity); entity.mapForUpdate(jpaUpdateClause, qEntity); return jpaUpdateClause.where(criteria.getFilter()).execute(); } @Override public long delete(ContactInfoCriteria criteria) { JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager); JPADeleteClause jpaDeleteClause = queryFactory.delete(qEntity); return jpaDeleteClause.where(criteria.getFilter()).execute(); } }
45.930233
150
0.851646
ebed1c85f61e15de02593f3b1db6274bd7ca7a23
641
package com.rayworks.tracker.utils; /** * Created by Sean on 3/7/17. * <p> * A simple logger for debug usage. */ public final class DroidLogger { private static boolean debugMode = true; private static final String PREFIX = ">>> "; public static void setDebugMode(boolean value) { debugMode = value; } public static boolean isDebugMode() { return debugMode; } public static void d(String msg) { if (debugMode) System.out.println(PREFIX + msg); } public static void e(String msg) { if (debugMode) System.err.println(PREFIX + msg); } }
20.03125
52
0.606864
5ed90a4895a5fa75f89d1c0566a54041eed5a8a5
1,910
/* * Copyright 2020 ThoughtWorks, 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.thoughtworks.gocd.analytics; import com.thoughtworks.gocd.analytics.models.PipelineInstance; import java.time.ZonedDateTime; public class PipelineInstanceMother { public static PipelineInstance pipelineInstanceFrom(long id, String pipelineName, int pipelineCounter, ZonedDateTime pipelineScheduleTime) { PipelineInstance pipelineInstance = new PipelineInstance(); pipelineInstance.setId(id); pipelineInstance.setName(pipelineName); pipelineInstance.setCounter(Integer.valueOf(pipelineCounter)); pipelineInstance.setCreatedAt(pipelineScheduleTime); return pipelineInstance; } public static PipelineInstance pipelineInstanceFrom(long id, String pipelineName, int pipelineCounter, long workflowId) { PipelineInstance pipelineInstance = new PipelineInstance(); pipelineInstance.setId(id); pipelineInstance.setName(pipelineName); pipelineInstance.setCounter(Integer.valueOf(pipelineCounter)); pipelineInstance.setWorkflowId(workflowId); return pipelineInstance; } public static PipelineInstance pipelineInstanceWithId(long id) { PipelineInstance pipelineInstance = new PipelineInstance(); pipelineInstance.setId(id); return pipelineInstance; } }
36.037736
144
0.750262
2f5f209dca9a3e88035635ed1c1f758bfd58f52d
2,195
package pl.otros.logview.gui.config; import org.apache.commons.configuration.Configuration; import pl.otros.logview.api.ConfKeys; import pl.otros.logview.api.OtrosApplication; import pl.otros.logview.api.services.JumpToCodeService; import pl.otros.logview.ide.IdeIntegrationConfigurationPanel; import pl.otros.swing.config.AbstractConfigView; import pl.otros.swing.config.InMainConfig; import pl.otros.swing.config.ValidationResult; import javax.swing.*; public class IdeIntegrationConfigView extends AbstractConfigView implements InMainConfig { private final IdeIntegrationConfigurationPanel ideIntegrationConfigurationPanel; public IdeIntegrationConfigView(OtrosApplication otrosApplication) { super("ideIntegration", "IDE integration", "Integration with IDE (IntellijJ or Eclipse)"); ideIntegrationConfigurationPanel = new IdeIntegrationConfigurationPanel(otrosApplication); } @Override public JComponent getView() { return ideIntegrationConfigurationPanel; } @Override public ValidationResult validate() { return new ValidationResult(); } @Override public void loadConfiguration(Configuration configuration) { ideIntegrationConfigurationPanel.setSelectedHostname(configuration.getString(ConfKeys.JUMP_TO_CODE_HOST, JumpToCodeService.DEFAULT_HOST)); ideIntegrationConfigurationPanel.setSelectedPort(configuration.getInt(ConfKeys.JUMP_TO_CODE_PORT, JumpToCodeService.DEFAULT_PORT)); ideIntegrationConfigurationPanel.setAutoJumpEnabled(configuration.getBoolean(ConfKeys.JUMP_TO_CODE_AUTO_JUMP_ENABLED, true)); ideIntegrationConfigurationPanel.setEnabledIdeIntegration(configuration.getBoolean(ConfKeys.JUMP_TO_CODE_ENABLED, true)); } @Override public void saveConfiguration(Configuration c) { c.setProperty(ConfKeys.JUMP_TO_CODE_PORT, ideIntegrationConfigurationPanel.getSelectedPort()); c.setProperty(ConfKeys.JUMP_TO_CODE_HOST, ideIntegrationConfigurationPanel.getSelectedHostname()); c.setProperty(ConfKeys.JUMP_TO_CODE_AUTO_JUMP_ENABLED, ideIntegrationConfigurationPanel.isAutoJumpEnabled()); c.setProperty(ConfKeys.JUMP_TO_CODE_ENABLED, ideIntegrationConfigurationPanel.isEnabledIdeIntegration()); } }
44.795918
142
0.837358
c2cf53ae2a5e7d1835fa83737fe791c050a0b06d
15,448
/** * 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.activemq.bugs; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.QueueConnection; import javax.jms.QueueReceiver; import javax.jms.QueueSession; import javax.jms.Session; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.RegionBroker; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.BrokerInfo; import org.apache.activemq.network.DiscoveryNetworkConnector; import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.util.TimeUtils; import org.apache.activemq.util.Wait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest extends JmsMultipleBrokersTestSupport { static final String payload = new String(new byte[10 * 1024]); private static final Logger LOG = LoggerFactory.getLogger(AMQ4485NetworkOfXBrokersWithNDestsFanoutTransactionTest.class); final int portBase = 61600; final int numBrokers = 4; final int numProducers = 10; final int numMessages = 800; final int consumerSleepTime = 20; StringBuilder brokersUrl = new StringBuilder(); HashMap<ActiveMQQueue, AtomicInteger> accumulators = new HashMap<ActiveMQQueue, AtomicInteger>(); private ArrayList<Throwable> exceptions = new ArrayList<Throwable>(); protected void buildUrlList() throws Exception { for (int i = 0; i < numBrokers; i++) { brokersUrl.append("tcp://localhost:" + (portBase + i)); if (i != numBrokers - 1) { brokersUrl.append(','); } } } protected BrokerService createBroker(int brokerid) throws Exception { BrokerService broker = new BrokerService(); broker.setPersistent(true); broker.setDeleteAllMessagesOnStartup(true); broker.getManagementContext().setCreateConnector(false); broker.setUseJmx(true); broker.setBrokerName("B" + brokerid); broker.addConnector(new URI("tcp://localhost:" + (portBase + brokerid))); addNetworkConnector(broker); broker.setSchedulePeriodForDestinationPurge(0); broker.getSystemUsage().setSendFailIfNoSpace(true); broker.getSystemUsage().getMemoryUsage().setLimit(512 * 1024 * 1024); PolicyMap policyMap = new PolicyMap(); PolicyEntry policyEntry = new PolicyEntry(); policyEntry.setExpireMessagesPeriod(0); policyEntry.setQueuePrefetch(1000); policyEntry.setMemoryLimit(1024 * 1024l); policyEntry.setOptimizedDispatch(false); policyEntry.setProducerFlowControl(false); policyEntry.setEnableAudit(true); policyEntry.setUseCache(true); policyMap.put(new ActiveMQQueue("GW.>"), policyEntry); broker.setDestinationPolicy(policyMap); KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); kahaDBPersistenceAdapter.setConcurrentStoreAndDispatchQueues(false); brokers.put(broker.getBrokerName(), new BrokerItem(broker)); return broker; } private void addNetworkConnector(BrokerService broker) throws Exception { StringBuilder networkConnectorUrl = new StringBuilder("static:(").append(brokersUrl.toString()); networkConnectorUrl.append(')'); for (int i = 0; i < 2; i++) { NetworkConnector nc = new DiscoveryNetworkConnector(new URI(networkConnectorUrl.toString())); nc.setName("Bridge-" + i); nc.setNetworkTTL(1); nc.setDecreaseNetworkConsumerPriority(true); nc.setDynamicOnly(true); nc.setPrefetchSize(100); nc.setDynamicallyIncludedDestinations( Arrays.asList(new ActiveMQDestination[]{new ActiveMQQueue("GW.*")})); broker.addNetworkConnector(nc); } } public void testBrokers() throws Exception { buildUrlList(); for (int i = 0; i < numBrokers; i++) { createBroker(i); } startAllBrokers(); waitForBridgeFormation(numBrokers - 1); verifyPeerBrokerInfos(numBrokers - 1); final List<ConsumerState> consumerStates = startAllGWConsumers(numBrokers); startAllGWFanoutConsumers(numBrokers); LOG.info("Waiting for percolation of consumers.."); TimeUnit.SECONDS.sleep(5); LOG.info("Produce mesages.."); long startTime = System.currentTimeMillis(); // produce produce(numMessages); assertTrue("Got all sent", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { for (ConsumerState tally : consumerStates) { final int expected = numMessages * (tally.destination.isComposite() ? tally.destination.getCompositeDestinations().length : 1); LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get()); if (tally.accumulator.get() != expected) { LOG.info("Tally for: " + tally.brokerName + ", dest: " + tally.destination + " - " + tally.accumulator.get() + " != " + expected + ", " + tally.expected); return false; } LOG.info("got tally on " + tally.brokerName); } return true; } }, 1000 * 60 * 1000l)); assertTrue("No exceptions:" + exceptions, exceptions.isEmpty()); LOG.info("done"); long duration = System.currentTimeMillis() - startTime; LOG.info("Duration:" + TimeUtils.printDuration(duration)); } private void startAllGWFanoutConsumers(int nBrokers) throws Exception { StringBuffer compositeDest = new StringBuffer(); for (int k = 0; k < nBrokers; k++) { compositeDest.append("GW." + k); if (k + 1 != nBrokers) { compositeDest.append(','); } } ActiveMQQueue compositeQ = new ActiveMQQueue(compositeDest.toString()); for (int id = 0; id < nBrokers; id++) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); connectionFactory.setWatchTopicAdvisories(false); QueueConnection queueConnection = connectionFactory.createQueueConnection(); queueConnection.start(); final QueueSession queueSession = queueConnection.createQueueSession(true, Session.SESSION_TRANSACTED); final MessageProducer producer = queueSession.createProducer(compositeQ); queueSession.createReceiver(new ActiveMQQueue("IN")).setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { producer.send(message); queueSession.commit(); } catch (Exception e) { LOG.error("Failed to fanout to GW: " + message, e); } } }); } } private List<ConsumerState> startAllGWConsumers(int nBrokers) throws Exception { List<ConsumerState> consumerStates = new LinkedList<ConsumerState>(); for (int id = 0; id < nBrokers; id++) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); connectionFactory.setWatchTopicAdvisories(false); QueueConnection queueConnection = connectionFactory.createQueueConnection(); queueConnection.start(); final QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQQueue destination = new ActiveMQQueue("GW." + id); QueueReceiver queueReceiver = queueSession.createReceiver(destination); final ConsumerState consumerState = new ConsumerState(); consumerState.brokerName = ((ActiveMQConnection) queueConnection).getBrokerName(); consumerState.receiver = queueReceiver; consumerState.destination = destination; for (int j = 0; j < numMessages * (consumerState.destination.isComposite() ? consumerState.destination.getCompositeDestinations().length : 1); j++) { consumerState.expected.add(j); } if (!accumulators.containsKey(destination)) { accumulators.put(destination, new AtomicInteger(0)); } consumerState.accumulator = accumulators.get(destination); queueReceiver.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { try { if (consumerSleepTime > 0) { TimeUnit.MILLISECONDS.sleep(consumerSleepTime); } } catch (InterruptedException e) { e.printStackTrace(); } try { consumerState.accumulator.incrementAndGet(); try { consumerState.expected.remove(((ActiveMQMessage) message).getProperty("NUM")); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { LOG.error("Failed to commit slow receipt of " + message, e); } } }); consumerStates.add(consumerState); } return consumerStates; } private void produce(int numMessages) throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(numProducers); final AtomicInteger toSend = new AtomicInteger(numMessages); for (int i = 1; i <= numProducers; i++) { final int id = i % numBrokers; executorService.execute(new Runnable() { @Override public void run() { try { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:" + (portBase + id) + ")"); connectionFactory.setWatchTopicAdvisories(false); QueueConnection queueConnection = connectionFactory.createQueueConnection(); queueConnection.start(); QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = queueSession.createProducer(null); int val = 0; while ((val = toSend.decrementAndGet()) >= 0) { ActiveMQQueue compositeQ = new ActiveMQQueue("IN"); LOG.info("Send to: " + ((ActiveMQConnection) queueConnection).getBrokerName() + ", " + val + ", dest:" + compositeQ); Message textMessage = queueSession.createTextMessage(((ActiveMQConnection) queueConnection).getBrokerName() + "->" + val + " payload:" + payload); textMessage.setIntProperty("NUM", val); producer.send(compositeQ, textMessage); } queueConnection.close(); } catch (Throwable throwable) { throwable.printStackTrace(); exceptions.add(throwable); } } }); } } private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { final BrokerService broker = brokerItem.broker; final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); return max == regionBroker.getPeerBrokerInfos().length; } }); LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); List<String> missing = new ArrayList<String>(); for (int i = 0; i < max; i++) { missing.add("B" + i); } if (max != regionBroker.getPeerBrokerInfos().length) { for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { LOG.info(info.getBrokerName()); missing.remove(info.getBrokerName()); } LOG.info("Broker infos off.." + missing); } assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); } private void verifyPeerBrokerInfos(final int max) throws Exception { Collection<BrokerItem> brokerList = brokers.values(); for (Iterator<BrokerItem> i = brokerList.iterator(); i.hasNext(); ) { verifyPeerBrokerInfo(i.next(), max); } } protected void tearDown() throws Exception { super.tearDown(); } class ConsumerState { AtomicInteger accumulator; String brokerName; QueueReceiver receiver; ActiveMQDestination destination; Vector<Integer> expected = new Vector<Integer>(); } }
43.638418
178
0.628819
f6dc766f6c01e772e59662d41a37298d1f97c275
347
package com.orlandolorenzo.auth; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JwtBasedAuthenticationApplication { public static void main(String[] args) { SpringApplication.run(JwtBasedAuthenticationApplication.class, args); } }
26.692308
71
0.841499
4db5e8dfde1a587221e46dcd1cbe0f912fc6bb8d
752
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.domain.FengdieSitesListRespModel; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.marketing.tool.fengdie.sites.batchquery response. * * @author auto create * @since 1.0, 2021-01-06 16:27:10 */ public class AlipayMarketingToolFengdieSitesBatchqueryResponse extends AlipayResponse { private static final long serialVersionUID = 4686816995779219653L; /** * 获取云凤蝶站点列表返回值模型 */ @ApiField("data") private FengdieSitesListRespModel data; public void setData(FengdieSitesListRespModel data) { this.data = data; } public FengdieSitesListRespModel getData( ) { return this.data; } }
23.5
88
0.738032
db98507f0c6d1289488fcf7a49d233b0d8f56951
1,855
/* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 Elias Ku * * 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.intellij.plugins.haxe.lang.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.plugins.haxe.lang.psi.*; import com.intellij.psi.PsiIdentifier; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * @author: Fedor.Korotkov */ public abstract class AnonymousHaxeTypeImpl extends AbstractHaxePsiClass implements HaxeAnonymousType { public AnonymousHaxeTypeImpl(@NotNull ASTNode node) { super(node); } @NotNull @Override public List<HaxeType> getHaxeExtendsList() { final HaxeTypeExtendsList typeExtendsList = getAnonymousTypeBody().getTypeExtendsList(); if (typeExtendsList != null) { final List<HaxeType> typeList = typeExtendsList.getTypeList(); if (!typeList.isEmpty()) { return typeList; } } return super.getHaxeExtendsList(); } @Override public HaxeComponentName getComponentName() { return null; } @Override public HaxeGenericParam getGenericParam() { return null; } @Nullable @Override public PsiIdentifier getNameIdentifier() { return new HaxeIdentifierImpl(new HaxeDummyASTNode("AnonymousType")); } }
28.538462
103
0.739084
b6428994b7c9fdb6dc2968a7e5faf2574952b8ec
710
package devopsdistilled.operp.client.items.panes.controllers.impl; import javax.inject.Inject; import devopsdistilled.operp.client.items.models.BrandModel; import devopsdistilled.operp.client.items.panes.ListBrandPane; import devopsdistilled.operp.client.items.panes.controllers.ListBrandPaneController; import devopsdistilled.operp.client.items.panes.models.ListBrandPaneModel; public class ListBrandPaneControllerImpl implements ListBrandPaneController { @Inject private ListBrandPane view; @Inject private ListBrandPaneModel model; @Inject private BrandModel brandModel; @Override public void init() { view.init(); brandModel.registerObserver(view); model.registerObserver(view); } }
24.482759
84
0.825352
30c5fbb01b4a303e2883347d3401d1948356a64a
669
package chat; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration; import org.springframework.kafka.annotation.EnableKafka; @EnableKafka @SpringBootApplication public class ChatApplication { public static void main(String[] args) { try { // Нет времени сделать нормальный health check для kafkа, возвращающий успех, только после создания output-topic Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } SpringApplication.run(ChatApplication.class, args); } }
30.409091
118
0.778774
14389ee890e29595eb6415431dde82a366c21cbd
1,070
package mrthomas20121.tinkers_reforged.trait.electrical_copper; import net.minecraft.entity.LivingEntity; import net.minecraft.util.DamageSource; import slimeknights.tconstruct.library.modifiers.Modifier; import slimeknights.tconstruct.library.tools.context.ToolAttackContext; import slimeknights.tconstruct.library.tools.nbt.IModifierToolStack; import javax.annotation.Nonnull; import java.util.Objects; import java.util.Random; public class TraitElectrostatic extends Modifier { public TraitElectrostatic() { super(0xE0B475); } @Override public int afterEntityHit(@Nonnull IModifierToolStack tool, int level, @Nonnull ToolAttackContext context, float damageDealt) { Random rand = context.getAttacker().getRandom(); if(rand.nextInt(100) >= 50) { LivingEntity livingEntity = Objects.requireNonNull(context.getLivingTarget()); DamageSource source = DamageSource.CACTUS; livingEntity.hurt(source.setScalesWithDifficulty(), livingEntity.getHealth()*0.3f); } return 0; } }
35.666667
131
0.751402
07dd155b72a45ee2b0fc40d4295bfa568edd9b32
4,661
package com.ruoyi.catering.domain; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.util.Date; /** * 回收记录对象 cy_recovery_record * * @author lsy * @date 2020-07-08 */ public class RecoveryRecord extends BaseEntity { private static final long serialVersionUID = 1L; /** * 回收记录id */ private Long id; /** * 餐馆id */ // @Excel(name = "餐馆id") private Long restaurantId; /** * 定位地点 */ @Excel(name = "定位地点") private String location; /** * 经度 */ private String longitude; /** * 纬度 */ private String latitude; /** * 回收人员id */ // @Excel(name = "回收人员id") private Long userId; /** * 回收车号 */ @Excel(name = "回收车号") private String carNo; /** * 垃圾分类id */ // @Excel(name = "垃圾分类id") private Long garbageId; /** * 回收重量 */ @Excel(name = "回收重量") private double weight; /** * 取证照片 */ // @Excel(name = "取证照片") private String img; private String recycleImg; /** * 回收日期 */ @Excel(name = "回收日期", width = 30, dateFormat = "yyyy-MM-dd") private Date recoveryDate; /** * 状态 */ // @Excel(name = "状态", readConverterExp = "1=上报") private Integer status; private Integer size; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setRestaurantId(Long restaurantId) { this.restaurantId = restaurantId; } public Long getRestaurantId() { return restaurantId; } public void setLocation(String location) { this.location = location; } public String getLocation() { return location; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLongitude() { return longitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLatitude() { return latitude; } public void setUserId(Long userId) { this.userId = userId; } public Long getUserId() { return userId; } public void setCarNo(String carNo) { this.carNo = carNo; } public String getCarNo() { return carNo; } public void setGarbageId(Long garbageId) { this.garbageId = garbageId; } public Long getGarbageId() { return garbageId; } public void setWeight(double weight) { this.weight = weight; } public double getWeight() { return weight; } public void setImg(String img) { this.img = img; } public String getImg() { return img; } public String getRecycleImg() { return recycleImg; } public void setRecycleImg(String recycleImg) { this.recycleImg = recycleImg; } public void setRecoveryDate(Date recoveryDate) { this.recoveryDate = recoveryDate; } public Date getRecoveryDate() { return recoveryDate; } public void setStatus(Integer status) { this.status = status; } public Integer getStatus() { return status; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("restaurantId", getRestaurantId()) .append("location", getLocation()) .append("longitude", getLongitude()) .append("latitude", getLatitude()) .append("userId", getUserId()) .append("carNo", getCarNo()) .append("garbageId", getGarbageId()) .append("weight", getWeight()) .append("img", getImg()) .append("recycleImg", getRecycleImg()) .append("recoveryDate", getRecoveryDate()) .append("status", getStatus()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .append("size", getSize()) .toString(); } }
20.353712
72
0.5531
0d6f41d6ac0534b0aec249241433f9670b967b9a
2,153
package org.firstinspires.ftc.teamcode.opmodes; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.base_classes.SimpleAutoBot; import org.firstinspires.ftc.teamcode.enums.Alliance; /** * A time based auto **/ public abstract class TimeAutoSecondary extends LinearOpMode { public abstract Alliance getAlliance(); public SimpleAutoBot robot = new SimpleAutoBot(this); public ElapsedTime runtime = new ElapsedTime(); @Override public void runOpMode() { //TODO: Set times //Power is backwards //Turning is backwards long AWAY_TIME = 500; long TURN_TIME = 400; long FORWARD_TIME = 900; double SPEED = -.4; double TURN_SPEED = -.5; robot.initAuto(); // Wait for the game to start (driver presses PLAY) waitForStart(); runtime.reset(); // Run until the end of auto (driver presses STOP) // changed while to if if (opModeIsActive()) { //Drive backwards away from wall robot.driveForwards(SPEED); sleep(AWAY_TIME); robot.stopDriving(); robot.raisePulley(0.5); sleep(500); robot.stopPulley(); robot.leftHand.setPosition(.49); robot.rightHand.setPosition(.65); robot.lowerPulley(0.5); sleep(350); robot.stopPulley(); //Rotate if (getAlliance() == Alliance.BLUE) { //Rotate counterclockwise to point in correct direction robot.rotateCounter(TURN_SPEED); sleep(TURN_TIME); robot.stopDriving(); } else if (getAlliance() == Alliance.RED) { //Rotate clockwise to point in correct direction robot.rotateClockwise(TURN_SPEED); sleep(TURN_TIME); robot.stopDriving(); } robot.driveForwards(SPEED); sleep(FORWARD_TIME); robot.stopDriving(); } } }
26.580247
71
0.582443
f4bf208641969a468981509debf522f8d826d754
426
package org.globsframework.model.utils; import org.globsframework.model.GlobList; import org.globsframework.model.GlobRepository; import javax.swing.*; public class GlobListActionAdapter implements GlobListFunctor { private Action action; public GlobListActionAdapter(Action action) { this.action = action; } public void run(GlobList list, GlobRepository repository) { action.actionPerformed(null); } }
22.421053
63
0.78169
02d455abb7a5c0dc7657dd666c1e08a6d8c6adc9
1,585
package com.eshop.authservice.resource; import java.security.Principal; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.eshop.authservice.domain.User; import com.eshop.authservice.service.UserService; @RestController @RequestMapping("/api/v1/users") public class UserResource { @Autowired private UserService userService; @RequestMapping(value = "/current", method = RequestMethod.GET) public Principal getUser(Principal principal) { return principal; } @PreAuthorize("#oauth2.hasScope('server')") @RequestMapping(method = RequestMethod.POST) public void createUser(@Valid @RequestBody User user) { userService.create(user); } @RequestMapping(value = "/me", method = RequestMethod.GET) public ResponseEntity<User> profile() { //User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String user = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String email = user + "@gmail.com"; User profile = User.builder().username(user).email(email).build(); return ResponseEntity.ok(profile); } }
31.7
95
0.793691
27d4d0afa2f6f809361bc4430a3697061515fab9
484
public class Split { private void split() { try { BufferedReader rd = rFile("codes.csv"); while(true) { String line = rd.readLine(); if(line == null) break; Scanner src = new Scanner(line); src.useDelimiter(","); while(true) { String field = src.next(); if(field == null) break; BufferedWriter wr = new BufferedWriter(new FileWriter(field)); } } } catch(IOException ex) { throw new RuntimeExcpetion(ex.toString()); } } }
21.043478
68
0.605372
411694f9d82426b851ee854c75e6121b5d48afe8
3,111
package com.trsvax.bootstrap.services.bootstrapprovider; import java.util.HashSet; import java.util.Set; import org.apache.tapestry5.Asset; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.annotations.Path; import org.apache.tapestry5.corelib.components.Alerts; import org.apache.tapestry5.dom.Element; import org.apache.tapestry5.dom.Visitor; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONArray; import org.apache.tapestry5.services.Environment; import org.apache.tapestry5.services.javascript.InitializationPriority; import org.apache.tapestry5.services.javascript.JavaScriptSupport; import org.slf4j.Logger; import com.trsvax.bootstrap.AbstractFrameworkProvider; import com.trsvax.bootstrap.BootstrapProvider; import com.trsvax.bootstrap.FrameworkMixin; import com.trsvax.bootstrap.environment.AlertsEnvironment; public class AlertsProvider extends AbstractFrameworkProvider implements BootstrapProvider { public class AlertsVisitor implements Visitor { Element controls; final String type; final Set<Element> pop; final FrameworkMixin mixin; public AlertsVisitor(final FrameworkMixin mixin, final String type, final Set<Element> pop) { this.type = type; this.pop = pop; this.mixin = mixin; } public void visit(Element element) { if (!hasName("div", element)) { return; } javaScriptSupport.importStylesheet(alertsCss); javaScriptSupport.importJavaScriptLibrary(alertsJs); javaScriptSupport.addInitializerCall(InitializationPriority.EARLY, "bootstrapAlerts", new JSONArray()); } } private final Class<?>[] handles = {Alerts.class}; private final Class<AlertsEnvironment> environmentClass = AlertsEnvironment.class; private final Environment environment; @SuppressWarnings("unused") private final Logger logger; @Inject @Path("classpath:com/trsvax/bootstrap/t5-bootstrap-alerts.js") private Asset alertsJs; @Inject @Path("classpath:com/trsvax/bootstrap/t5-bootstrap-alerts.css") private Asset alertsCss; private JavaScriptSupport javaScriptSupport; public AlertsProvider(Environment environment, Logger logger, JavaScriptSupport javaScriptSupport) { this.environment = environment; this.logger = logger; this.javaScriptSupport = javaScriptSupport; } public boolean instrument(FrameworkMixin mixin) { return instrument(mixin, environment.peekRequired(environmentClass), handles); } boolean handle(FrameworkMixin mixin) { if ( Alerts.class.getCanonicalName().equals(mixin.getComponentClassName())) { return true; } return false; } public boolean cleanupRender(FrameworkMixin mixin, MarkupWriter writer) { if ( ! handle(mixin)) { return false; } final AlertsEnvironment alertsEnvironment = environment.peekRequired(environmentClass); final String type = alertsEnvironment.getType(mixin); if ( type == null ) { return false; } final Set<Element> pop = new HashSet<Element>(); mixin.getRoot().visit( new AlertsVisitor(mixin,type,pop)); for ( Element element : pop ) { element.pop(); } return true; } }
30.5
106
0.777563
6a6d441a09c127eb48d8fb03503db4c09d768757
619
package fr.nargit.rating.algorihtm.elo.performance; /** * Created by NargiT on 13/01/2016 */ public class DefaultEloPerformance implements EloPerformance { @Override public double getWinningProbability(double playerRating, double opponentRating) { // return 1/(Math.pow(10,-(playerRating-opponentRating)/400)+1); // return transformedRating(playerRating) / (transformedRating(playerRating) + transformedRating(opponentRating)); return 1 / (1 + transformedRating(opponentRating - playerRating)); } private double transformedRating(double value) { return Math.pow(10, value / 400.0); } }
32.578947
119
0.74475
0f02100c0b5d220b7f259dff8d2d16afafc354ab
9,992
package com.game30.javagl.programs; import java.nio.Buffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL21; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL40; /** * An enumeration of the different uniform types available in the OpenGL Scripting Language. * * <p>This is sort of a hack class that gets around the restrictive nature of the LWJGL methods requires a different * method for each uniform type. Each of the uniform types defined in this enumeration knows which method it needs to * call write a generic {@link Buffer} to the uniform. * * @author Brian Norman * @since 1.0.0 */ public enum GLUniformType { /** * An integer array uniform type of length 1. */ Integer(1) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform1iv(position, (IntBuffer) data); } }, /** * An integer array uniform type of length 2. */ Integer2(2) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform2iv(position, (IntBuffer) data); } }, /** * An integer array uniform type of length 3. */ Integer3(3) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform3iv(position, (IntBuffer) data); } }, /** * An integer array uniform type of length 4. */ Integer4(4) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform4iv(position, (IntBuffer) data); } }, /** * An unsigned integer array uniform type of length 1. */ UnsignedInteger(1) { @Override void writeUniform(int position, Buffer data) { GL30.glUniform1uiv(position, (IntBuffer) data); } }, /** * An unsigned integer array uniform type of length 2. */ UnsignedInteger2(2) { @Override void writeUniform(int position, Buffer data) { GL30.glUniform2uiv(position, (IntBuffer) data); } }, /** * An unsigned integer array uniform type of length 3. */ UnsignedInteger3(3) { @Override void writeUniform(int position, Buffer data) { GL30.glUniform3uiv(position, (IntBuffer) data); } }, /** * An unsigned integer array uniform type of length 4. */ UnsignedInteger4(4) { @Override void writeUniform(int position, Buffer data) { GL30.glUniform4uiv(position, (IntBuffer) data); } }, /** * A float array uniform type of length 1. */ Float(1) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform1fv(position, (FloatBuffer) data); } }, /** * A float array uniform type of length 2. */ Float2(2) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform2fv(position, (FloatBuffer) data); } }, /** * A float array uniform type of length 3. */ Float3(3) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform3fv(position, (FloatBuffer) data); } }, /** * A float array uniform type of length 4. */ Float4(4) { @Override void writeUniform(int position, Buffer data) { GL20.glUniform4fv(position, (FloatBuffer) data); } }, /** * A float square matrix uniform type of size 2 by 2. */ FloatMatrix2(4) { @Override void writeUniform(int position, Buffer data) { GL20.glUniformMatrix2fv(position, false, (FloatBuffer) data); } }, /** * A float square matrix uniform type of size 3 by 3. */ FloatMatrix3(9) { @Override void writeUniform(int position, Buffer data) { GL20.glUniformMatrix3fv(position, false, (FloatBuffer) data); } }, /** * A float square matrix uniform type of size 4 by 4. */ FloatMatrix4(16) { @Override void writeUniform(int position, Buffer data) { GL20.glUniformMatrix4fv(position, false, (FloatBuffer) data); } }, /** * A float matrix uniform type of size 2 by 3. */ FloatMatrix2x3(6) { @Override void writeUniform(int position, Buffer data) { GL21.glUniformMatrix2x3fv(position, false, (FloatBuffer) data); } }, /** * A float matrix uniform type of size 3 by 2. */ FloatMatrix3x2(6) { @Override void writeUniform(int position, Buffer data) { GL21.glUniformMatrix3x2fv(position, false, (FloatBuffer) data); } }, /** * A float matrix uniform type of size 2 by 4. */ FloatMatrix2x4(8) { @Override void writeUniform(int position, Buffer data) { GL21.glUniformMatrix2x4fv(position, false, (FloatBuffer) data); } }, /** * A float matrix uniform type of size 4 by 2. */ FloatMatrix4x2(8) { @Override void writeUniform(int position, Buffer data) { GL21.glUniformMatrix4x2fv(position, false, (FloatBuffer) data); } }, /** * A float matrix uniform type of size 3 by 4. */ FloatMatrix3x4(12) { @Override void writeUniform(int position, Buffer data) { GL21.glUniformMatrix3x4fv(position, false, (FloatBuffer) data); } }, /** * A float matrix uniform type of size 4 by 3. */ FloatMatrix4x3(12) { @Override void writeUniform(int position, Buffer data) { GL21.glUniformMatrix4x3fv(position, false, (FloatBuffer) data); } }, /** * A double array uniform type of length 1. */ Double(1) { @Override void writeUniform(int position, Buffer data) { GL40.glUniform1dv(position, (DoubleBuffer) data); } }, /** * A double array uniform type of length 2. */ Double2(2) { @Override void writeUniform(int position, Buffer data) { GL40.glUniform2dv(position, (DoubleBuffer) data); } }, /** * A double array uniform type of length 3. */ Double3(3) { @Override void writeUniform(int position, Buffer data) { GL40.glUniform3dv(position, (DoubleBuffer) data); } }, /** * A double array uniform type of length 4. */ Double4(4) { @Override void writeUniform(int position, Buffer data) { GL40.glUniform4dv(position, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 2 by 2. */ DoubleMatrix2(4) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix2dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 3 by 3. */ DoubleMatrix3(16) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix3dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 4 by 4. */ DoubleMatrix4(16) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix4dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 2 by 3. */ DoubleMatrix2x3(6) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix2x3dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 3 by 2. */ DoubleMatrix3x2(6) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix3x2dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 2 by 4. */ DoubleMatrix2x4(8) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix2x4dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 4 by 2. */ DoubleMatrix4x2(8) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix4x2dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 3 by 4. */ DoubleMatrix3x4(12) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix3x4dv(position, false, (DoubleBuffer) data); } }, /** * A double square matrix uniform type of size 4 by 3. */ DoubleMatrix4x3(12) { @Override void writeUniform(int position, Buffer data) { GL40.glUniformMatrix4x3dv(position, false, (DoubleBuffer) data); } }, // End of enumeration ; /** The size of the. */ private final int size; /** * Creates a new with the specified size. * * @param size the uniform size. */ GLUniformType(int size) { this.size = size; } /** * The number of primitive values associated with the uniform type. * * @return the size of the uniform. */ public int getSize() { return size; } /** * Writes the specified buffer data to the uniform at the specified position. * * @param position the position of the uniform. * @param data the uniform data to be written. */ abstract void writeUniform(int position, Buffer data); }
25.168766
118
0.572858
887cafbccc3c028bdc0585c3e352a22ce14af1ee
2,859
package uk.sky.cqlmigrate; import com.datastax.driver.core.Cluster; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({Cluster.class}) public class CassandraClusterFactoryTest { @Mock private Cluster.Builder clusterBuilderMock; @Mock private Cluster clusterMock; @Before public void setUp() throws Exception { mockStatic(Cluster.class); when(Cluster.builder()).thenReturn(clusterBuilderMock); when(clusterBuilderMock.addContactPoints(any(String[].class))).thenReturn(clusterBuilderMock); when(clusterBuilderMock.withPort(anyInt())).thenReturn(clusterBuilderMock); when(clusterBuilderMock.withCredentials(any(String.class), any(String.class))).thenReturn(clusterBuilderMock); } @Test public void createClusterWithCredentials() throws Exception { String expectedUser = "cassandra-user"; String expectedPassword = "cassandra-password"; //when CassandraClusterFactory.createCluster(new String[]{"host1"}, 0, expectedUser, expectedPassword); //then verify(clusterBuilderMock).withCredentials(expectedUser, expectedPassword); } @Test public void createClusterWithNullCredentials() throws Exception { String expectedUser = null; String expectedPassword = null; //when CassandraClusterFactory.createCluster(new String[]{"host1"}, 0, expectedUser, expectedPassword); //then verify(clusterBuilderMock, never()).withCredentials(expectedUser, expectedPassword); } @Test public void createClusterWithNullPassword() throws Exception { String expectedUser = "cassandra"; String expectedPassword = null; //when CassandraClusterFactory.createCluster(new String[]{"host1"}, 0, expectedUser, expectedPassword); //then verify(clusterBuilderMock, never()).withCredentials(expectedUser, expectedPassword); } @Test public void createClusterWithNullUser() throws Exception { String expectedUser = null; String expectedPassword = "cassandra"; //when CassandraClusterFactory.createCluster(new String[]{"host1"}, 0, expectedUser, expectedPassword); //then verify(clusterBuilderMock, never()).withCredentials(expectedUser, expectedPassword); } }
32.862069
118
0.726828
9bd258a37491ef9e65597d72c318d9c2f2c1cf98
1,979
package ru.job4j.chess.firuges.black; import ru.job4j.chess.firuges.Cell; import ru.job4j.chess.firuges.Figure; import ru.job4j.chess.firuges.ImpossibleMoveException; /** * Class BishopBlack решение задачи части 002 - Контрольные вопросы. Решение задачи - Каркас шахматной доски. * @author vmyaskovskiy * @version $Id$ * @since 0.1 */ public class RookBlack implements Figure { private final Cell position; public RookBlack(final Cell position) { this.position = position; } @Override public Cell position() { return this.position; } /** * Метод way просчитывает правильный путь фигуры, выдает исключение если фигура движется неправильн. * @param source координаты ячейки откуда ходят * @param dest координаты ячейки куда ходят */ @Override public Cell[] way(Cell source, Cell dest) { int range; if (dest.x - source.x == 0) { range = Math.abs(dest.y - source.y); } else { range = Math.abs(dest.x - source.x); } Cell[] steps = new Cell[range]; int deltaX = (int) Math.signum(dest.x - source.x); int deltaY = (int) Math.signum(dest.y - source.y); int x = source.x; int y = source.y; for (int i = 0; i < range; i++) { if ((deltaX == 1 && deltaY == 0) || (deltaX == -1 && deltaY == 0) || (deltaX == 0 && deltaY == 1) || (deltaX == 0 && deltaY == -1)) { x += deltaX; y += deltaY; steps[i] = Cell.values()[8 * x + y]; } else { throw new ImpossibleMoveException("Так нельзя ходить"); } } return steps; } @Override public Figure copy(Cell dest) { return new RookBlack(dest); } }
32.442623
110
0.514907
0a7fe33202f92070eadd3aa802675cd664cf23a6
4,851
package men.brakh.kasiski.kasiskiTests.impl; import javafx.scene.control.ProgressBar; import men.brakh.kasiski.KasiskiMath; import men.brakh.kasiski.kasiskiTests.KasiskiTest; import men.brakh.kasiski.ProgressivePair; import java.util.ArrayList; import java.util.List; public class ProgressiveKasiskiTest extends KasiskiTest { private String alphabet; private ProgressBar additinalBar = null; /** * Повторения прогрессивных пар * @see ProgressivePair */ private List<ProgressivePair> progressivePairs = new ArrayList<>(); public ProgressiveKasiskiTest(String text, int lgrammsLength, String alphabet) { super(text, lgrammsLength); this.alphabet = alphabet; } public void setProgressBar(ProgressBar jProgressBar) { this.additinalBar = jProgressBar; } /** * Сдвиг строки на одну позицию (Цезарь с ключем = 1) * @param str строка * @return "сдвинутая" строка */ public String shiftStrings(String str) { StringBuilder newStr = new StringBuilder(str); for(int i = 0; i < newStr.length(); i++) { int currCharIndex = alphabet.indexOf(newStr.charAt(i)); newStr.setCharAt(i, alphabet.charAt((currCharIndex + 1) % alphabet.length()) ); } return newStr.toString(); } /** * Получение расстояния, повторяющегося больше всего в текущей итерации прогрессивных пар * @return расстояние, повторяющееся больше всего в текущей итерации прогрессивных пар */ private int getMaxProgressivePairsRepeated() { int maxCount = -1; int maxNumber = 0; for(int i = 0; i < progressivePairs.size(); i++) { int count = 0; for(int j = 0; j < progressivePairs.size(); j++) { if(progressivePairs.get(i).getLength() == progressivePairs.get(j).getLength()) { count++; } } if((count > maxCount) && (progressivePairs.get(i).getLength() > 1) ) { maxCount = count; maxNumber = progressivePairs.get(i).getLength(); } } return maxNumber; } /** * Получение списка, каждый элемент которого - наиболее повторяющееся расстояние на i-ой итерации * @return Список наиболее вероятных расстояний */ private ArrayList<Integer> getFillLineRepeats() { ArrayList<Integer> lineRepeat = new ArrayList(); for (int i = 0; i < text.length() - lgrammsLength + 1; i++) { // Ищем одинаковые n-звучия (n символов, которые повторяюстя на протяжении текста) String subStr1 = text.substring(i, i + lgrammsLength); int predI = i; for (int j = i + 1; j < text.length() - lgrammsLength + 1; j++) { String subStr2 = text.substring(j, j + lgrammsLength); String comparedSubStr = shiftStrings(subStr1); for(int k = 1; k < alphabet.length(); k++) { if(comparedSubStr.equals(subStr2)) { progressivePairs.add(new ProgressivePair(predI, j, k)); // Добавляем прогрессивные пары } comparedSubStr = shiftStrings(comparedSubStr); } } if(getMaxProgressivePairsRepeated() > 0) System.out.println(getMaxProgressivePairsRepeated()); // Из найденных прогрессивных пар определяем максимально повторяющуюся длину lineRepeat.add(getMaxProgressivePairsRepeated()); // Эту длину добавляем в отдельный список progressivePairs.clear(); // и отчищаем список прогрессивных пар if(additinalBar != null) { // Если отрисовка из гуишки и там есть прогрессбар - обновляем его additinalBar.progressProperty().setValue(((float)i / (float)(text.length() - lgrammsLength + 1))); } } return lineRepeat; } /** * Заполнение таблицы НОДов на основе наиболее вероятных расстояний * @param lineRepeats Наиболее вероятные расстояния */ private void searchRepeatsGcd(List<Integer> lineRepeats) { for (int j = 0; j < lineRepeats.size(); j++) { for(int k = j+1; k < lineRepeats.size(); k++){ int currGcd = KasiskiMath.gcd(lineRepeats.get(j), lineRepeats.get(k)); if ((currGcd > 1)) gcdsTable.addGcd(currGcd); } } progressivePairs.clear(); } /** * Тест Касиски для прогрессивного ключа * @return наиболее вероятный ключ */ @Override public int test() { List<Integer> lineRepeats = getFillLineRepeats(); searchRepeatsGcd(lineRepeats); if(gcdsTable.size() == 0) { return 0; } return gcdsTable.getFirstKey(); } }
37.604651
152
0.602144
4705f198b1f8d781e986e9b15426ab52ef757c84
454
package org.adligo.tests4j.shared.output; /** * A output delegateor that can be used by multiple threads * when running on a platform with threading (i.e. not GWT). * @author scott * */ public interface I_ConcurrentOutputDelegator extends I_OutputBuffer { /** * poll the main output * @return */ public abstract String poll(); /** * a thread local delegate * @param buffer */ public void setDelegate(I_ToggleOutputBuffer buffer); }
21.619048
69
0.713656
259378f09d512f199425f9f0efdf45c2b378f990
113
/** * Filter related implementation classes. */ package io.toolisticon.annotationprocessortoolkit.tools.filter;
28.25
63
0.80531
7ff9129cb88aefb50f2446ff04fe4106d8d2cb35
1,520
package edu.hm.hafner; /** * Useless class - only for test-cases. * * @author Christian M&ouml;stl */ public class MissingSwitchDefault { private String monat; /** * Creates a new instance of {@link MissingSwitchDefault}. * * @param month * monat */ public MissingSwitchDefault(final int month) { switch (month) { case 1: monat = "Januar"; break; case 2: monat = "Februar"; break; case 3: monat = "März"; break; case 4: monat = "April"; break; case 5: monat = "Mai"; break; case 6: monat = "Juni"; break; case 7: monat = "Juli"; break; case 8: monat = "August"; break; case 9: monat = "September"; break; case 10: monat = "Oktober"; break; case 11: monat = "November"; break; case 12: monat = "Dezember"; break; } } /** * Returns the monat. * * @return the monat */ public String getMonat() { return monat; } }
22.686567
63
0.356579
1636dda39932e49a290eb77925ceeded83d3193f
1,716
package co.miranext.nosql; import co.miranext.nosql.criteria.ColumnCriterion; import co.miranext.nosql.criteria.Criteria; import co.miranext.nosql.criteria.FieldCriterion; import co.miranext.nosql.postgresql.PgsqlJsonRepository; import co.miranext.nosql.query.SQLObjectQuery; import org.boon.core.reflection.BeanUtils; import org.boon.core.reflection.fields.FieldAccess; import org.junit.Test; import java.util.Map; import static org.junit.Assert.*; /** * */ public class CriteriaTest { @Test public void testCriteriaSQLStrings() { ColumnCriterion cr = new ColumnCriterion("column","test"); assertEquals("column",cr.getColumn()); assertEquals("test",cr.getValue()); assertEquals("column=?",cr.toSQLString(null)); FieldCriterion fieldCriterion = new FieldCriterion("id","abc"); //new PsqlJsonFieldCriterion("column","id","abc"); Criteria criteria = new Criteria(); criteria.add(cr); criteria.add(fieldCriterion); Samp document = new Samp(); Map<String,FieldAccess> fields = BeanUtils.getFieldsFromObject(document); assertEquals("column=?" + SQLObjectQuery.SQL_AND_DELIMITER + "data->>'id'=?", SQLObjectQuery.toSQLCriteriaFilter(null,DocumentMeta.fromAnnotation(document.getClass()),criteria, PgsqlJsonRepository.CRITERION_TRANSFORMER)); ColumnExtra extra = new ColumnExtra("col"); ColumnExtra extraAuto = new ColumnExtra("auto:record_id"); assertEquals("col",extra.getColumn()); assertFalse(extra.isAuto()); assertEquals("record_id", extraAuto.getColumn()); assertTrue(extraAuto.isAuto()); } } @Document(table="samp") class Samp { }
29.084746
184
0.702797
754e8f7b960d877658016d65fff499b3d66dd364
834
package testNG.Example; import org.junit.Test; import org.testng.annotations.BeforeTest; import java.io.IOException; import java.text.MessageFormat; public class DockerTest { String browserName = "chrome"; String nodePrefix = "standalone-"; String nodeSuffix = "-debug"; String imageNameJoin = "-"; String buildName = ":3.10.0-argon"; //"3.8.1-bohrium"; String dockerCom = "docker run -d -p 4444:4444 -p 5900:5900 -v /dev/shm:/dev/shm selenium/{0}{1}{2}{3}"; final String dockerlaunch = MessageFormat.format(dockerCom, nodePrefix, browserName, nodeSuffix, buildName); @BeforeTest public void docker() throws IOException { Process myProcess = Runtime.getRuntime().exec( dockerlaunch ); } public DockerTest() throws IOException { } @Test public void test() { } }
25.272727
112
0.683453
08c31c499746487a8b81f8b736c26b2171816d68
1,065
package cz.znj.kvr.sw.exp.java.netty; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import org.apache.commons.io.Charsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.concurrent.Executor; /** * Created by rat on 2015-09-20. */ @ChannelHandler.Sharable public class ExecutorDistributionHandler extends ChannelHandlerAdapter { public ExecutorDistributionHandler(Executor executor) { this.executor = executor; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { executor.execute(() -> { logger.error("Got message "+msg); ctx.fireChannelRead(msg); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); } protected Executor executor; protected Logger logger = LogManager.getLogger(); }
23.152174
74
0.769014
93a0f085ad3797f64645db88dc52b81d9e42397a
10,777
/* * Copyright (c) 2017 litas * * 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.litas.ltlwallet; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.litas.ltlwallet.widget.Toolbar; import com.litas.ltlwallet.model.Wallet; import com.litas.ltlwallet.model.WalletManager; import com.litas.ltlwallet.util.Helper; import com.litas.ltlwallet.util.BitlitasThreadPoolExecutor; import timber.log.Timber; public class GenerateReviewFragment extends Fragment { static final public String VIEW_TYPE_DETAILS = "details"; static final public String VIEW_TYPE_ACCEPT = "accept"; static final public String VIEW_TYPE_WALLET = "wallet"; ScrollView scrollview; ProgressBar pbProgress; TextView tvWalletName; TextView tvWalletPassword; TextView tvWalletAddress; TextView tvWalletMnemonic; TextView tvWalletViewKey; TextView tvWalletSpendKey; ImageButton bCopyAddress; LinearLayout llAdvancedInfo; Button bAdvancedInfo; Button bAccept; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_review, container, false); scrollview = (ScrollView) view.findViewById(R.id.scrollview); pbProgress = (ProgressBar) view.findViewById(R.id.pbProgress); tvWalletName = (TextView) view.findViewById(R.id.tvWalletName); tvWalletPassword = (TextView) view.findViewById(R.id.tvWalletPassword); tvWalletAddress = (TextView) view.findViewById(R.id.tvWalletAddress); tvWalletViewKey = (TextView) view.findViewById(R.id.tvWalletViewKey); tvWalletSpendKey = (TextView) view.findViewById(R.id.tvWalletSpendKey); tvWalletMnemonic = (TextView) view.findViewById(R.id.tvWalletMnemonic); bCopyAddress = (ImageButton) view.findViewById(R.id.bCopyAddress); bAdvancedInfo = (Button) view.findViewById(R.id.bAdvancedInfo); llAdvancedInfo = (LinearLayout) view.findViewById(R.id.llAdvancedInfo); bAccept = (Button) view.findViewById(R.id.bAccept); boolean testnet = WalletManager.getInstance().isTestNet(); tvWalletMnemonic.setTextIsSelectable(testnet); tvWalletSpendKey.setTextIsSelectable(testnet); bAccept.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { acceptWallet(); } }); view.findViewById(R.id.bCopyViewKey).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { copyViewKey(); } }); bCopyAddress.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { copyAddress(); } }); bCopyAddress.setClickable(false); view.findViewById(R.id.bAdvancedInfo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAdvancedInfo(); } }); showProgress(); Bundle args = getArguments(); String path = args.getString("path"); String password = args.getString("password"); this.type = args.getString("type"); new AsyncShow().executeOnExecutor(BitlitasThreadPoolExecutor.BITLITAS_THREAD_POOL_EXECUTOR, path, password); return view; } void copyViewKey() { Helper.clipBoardCopy(getActivity(), getString(R.string.label_copy_viewkey), tvWalletViewKey.getText().toString()); Toast.makeText(getActivity(), getString(R.string.message_copy_viewkey), Toast.LENGTH_SHORT).show(); } void copyAddress() { Helper.clipBoardCopy(getActivity(), getString(R.string.label_copy_address), tvWalletAddress.getText().toString()); Toast.makeText(getActivity(), getString(R.string.message_copy_address), Toast.LENGTH_SHORT).show(); } void nocopy() { Toast.makeText(getActivity(), getString(R.string.message_nocopy), Toast.LENGTH_SHORT).show(); } void showAdvancedInfo() { llAdvancedInfo.setVisibility(View.VISIBLE); bAdvancedInfo.setVisibility(View.GONE); scrollview.post(new Runnable() { @Override public void run() { scrollview.fullScroll(ScrollView.FOCUS_DOWN); } }); } String type; private void acceptWallet() { String name = tvWalletName.getText().toString(); String password = tvWalletPassword.getText().toString(); bAccept.setEnabled(false); acceptCallback.onAccept(name, password); } private class AsyncShow extends AsyncTask<String, Void, Boolean> { String password; String name; String address; String seed; String viewKey; String spendKey; boolean isWatchOnly; Wallet.Status status; @Override protected Boolean doInBackground(String... params) { if (params.length != 2) return false; String walletPath = params[0]; password = params[1]; Wallet wallet; boolean closeWallet; if (type.equals(GenerateReviewFragment.VIEW_TYPE_WALLET)) { wallet = GenerateReviewFragment.this.walletCallback.getWallet(); closeWallet = false; } else { wallet = WalletManager.getInstance().openWallet(walletPath, password); closeWallet = true; } name = wallet.getName(); status = wallet.getStatus(); if (status != Wallet.Status.Status_Ok) { if (closeWallet) wallet.close(); return false; } address = wallet.getAddress(); seed = wallet.getSeed(); viewKey = wallet.getSecretViewKey(); spendKey = isWatchOnly ? getActivity().getString(R.string.label_watchonly) : wallet.getSecretSpendKey(); isWatchOnly = wallet.isWatchOnly(); if (closeWallet) wallet.close(); return true; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (!isAdded()) return; // never mind tvWalletName.setText(name); if (result) { if (type.equals(GenerateReviewFragment.VIEW_TYPE_ACCEPT)) { tvWalletPassword.setText(password); bAccept.setVisibility(View.VISIBLE); bAccept.setEnabled(true); } tvWalletAddress.setText(address); tvWalletMnemonic.setText(seed); tvWalletViewKey.setText(viewKey); tvWalletSpendKey.setText(spendKey); bAdvancedInfo.setVisibility(View.VISIBLE); bCopyAddress.setClickable(true); bCopyAddress.setImageResource(R.drawable.ic_content_copy_black_24dp); activityCallback.setTitle(name, getString(R.string.details_title)); activityCallback.setToolbarButton( GenerateReviewFragment.VIEW_TYPE_ACCEPT.equals(type) ? Toolbar.BUTTON_NONE : Toolbar.BUTTON_BACK); } else { // TODO show proper error message and/or end the fragment? tvWalletAddress.setText(status.toString()); tvWalletMnemonic.setText(status.toString()); tvWalletViewKey.setText(status.toString()); tvWalletSpendKey.setText(status.toString()); } hideProgress(); } } Listener activityCallback = null; AcceptListener acceptCallback = null; ListenerWithWallet walletCallback = null; public interface Listener { void setTitle(String title, String subtitle); void setToolbarButton(int type); } public interface AcceptListener { void onAccept(String name, String password); } public interface ListenerWithWallet { Wallet getWallet(); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof Listener) { this.activityCallback = (Listener) context; } if (context instanceof AcceptListener) { this.acceptCallback = (AcceptListener) context; } if (context instanceof ListenerWithWallet) { this.walletCallback = (ListenerWithWallet) context; } } @Override public void onResume() { super.onResume(); Timber.d("onResume()"); String name = tvWalletName.getText().toString(); if (name.isEmpty()) name = null; activityCallback.setTitle(name, getString(R.string.details_title)); activityCallback.setToolbarButton( GenerateReviewFragment.VIEW_TYPE_ACCEPT.equals(type) ? Toolbar.BUTTON_NONE : Toolbar.BUTTON_BACK); } public void showProgress() { pbProgress.setVisibility(View.VISIBLE); } public void hideProgress() { pbProgress.setVisibility(View.GONE); } boolean backOk() { return !type.equals(GenerateReviewFragment.VIEW_TYPE_ACCEPT); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.wallet_details_menu, menu); super.onCreateOptionsMenu(menu, inflater); } }
35.923333
122
0.648604
704f42dbe4801f72f2efb566b1a0d9c27733ffaf
547
package commands; import image.Figure; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.io.File; public class LoadImageCommand implements Command<Figure> { private final ImageView view; private final File file; public LoadImageCommand(final ImageView view, final File file) { this.view = view; this.file = file; } @Override public Figure execute() { view.setImage(new Image(file.toURI().toString())); return new Figure(file.getAbsoluteFile()); } }
21.88
68
0.687386
b3d44632bcda11a07cadbc00eed4ab942ac43e4d
366
package org.semanticweb.owlapi.docstore; import org.semanticweb.owlapi.model.OWLAnnotation; /** * @author Matthew Horridge, Stanford University, Bio-Medical Informatics Research Group, Date: 26/10/2014 */ public interface AnnotationIndex { ChangeResult addAnnotation(OWLAnnotation annotation); ChangeResult removeAnnotation(OWLAnnotation annotation); }
28.153846
106
0.800546
bf7cf91729274322a5cba9b222b159e012bba33e
22,175
package com.sudwood.advancedutilities.client; import com.sudwood.advancedutilities.AdvancedUtilities; import com.sudwood.advancedutilities.blocks.AdvancedUtilitiesBlocks; import com.sudwood.advancedutilities.client.models.ModelBellows; import com.sudwood.advancedutilities.client.models.ModelBoiler; import com.sudwood.advancedutilities.client.models.ModelGun; import com.sudwood.advancedutilities.client.models.ModelJackHammer; import com.sudwood.advancedutilities.client.models.ModelJetpack; import com.sudwood.advancedutilities.client.models.ModelJetpackArmor; import com.sudwood.advancedutilities.client.models.ModelKilnHeld; import com.sudwood.advancedutilities.client.models.ModelPowerLegs; import com.sudwood.advancedutilities.client.models.ModelPowerLegsArmor; import com.sudwood.advancedutilities.client.models.ModelQuarryFrame; import com.sudwood.advancedutilities.client.models.ModelRebreather; import com.sudwood.advancedutilities.client.models.ModelRebreatherArmor; import com.sudwood.advancedutilities.client.models.ModelRunningShoes; import com.sudwood.advancedutilities.client.models.ModelRunningShoesArmor; import com.sudwood.advancedutilities.client.models.ModelSmeltryHeld; import com.sudwood.advancedutilities.client.models.ModelSplitterTube; import com.sudwood.advancedutilities.client.models.ModelSteamCharger; import com.sudwood.advancedutilities.client.models.ModelSteamCompressor; import com.sudwood.advancedutilities.client.models.ModelSteamCrusher; import com.sudwood.advancedutilities.client.models.ModelSteamFurnace; import com.sudwood.advancedutilities.client.models.ModelSteamQuarry; import com.sudwood.advancedutilities.client.models.ModelSteamSmeltry; import com.sudwood.advancedutilities.client.models.ModelTank; import com.sudwood.advancedutilities.client.models.ModelTomato; import com.sudwood.advancedutilities.client.models.ModelToolForge; import com.sudwood.advancedutilities.client.models.ModelTube; import com.sudwood.advancedutilities.client.renders.RenderArmorForge; import com.sudwood.advancedutilities.client.renders.RenderBellows; import com.sudwood.advancedutilities.client.renders.RenderBoiler; import com.sudwood.advancedutilities.client.renders.RenderBullet; import com.sudwood.advancedutilities.client.renders.RenderElevator; import com.sudwood.advancedutilities.client.renders.RenderFluidTube; import com.sudwood.advancedutilities.client.renders.RenderItem; import com.sudwood.advancedutilities.client.renders.RenderItemTube; import com.sudwood.advancedutilities.client.renders.RenderJackHammer; import com.sudwood.advancedutilities.client.renders.RenderJetpackItem; import com.sudwood.advancedutilities.client.renders.RenderKiln; import com.sudwood.advancedutilities.client.renders.RenderMagnetTube; import com.sudwood.advancedutilities.client.renders.RenderPortaChest; import com.sudwood.advancedutilities.client.renders.RenderPortaChestItem; import com.sudwood.advancedutilities.client.renders.RenderQuarryFrame; import com.sudwood.advancedutilities.client.renders.RenderRationedItemTube; import com.sudwood.advancedutilities.client.renders.RenderRebreather; import com.sudwood.advancedutilities.client.renders.RenderRestrictedItemTube; import com.sudwood.advancedutilities.client.renders.RenderRunningShoesItem; import com.sudwood.advancedutilities.client.renders.RenderSmeltry; import com.sudwood.advancedutilities.client.renders.RenderSpeedyMinecart; import com.sudwood.advancedutilities.client.renders.RenderSplitterTube; import com.sudwood.advancedutilities.client.renders.RenderSteamCharger; import com.sudwood.advancedutilities.client.renders.RenderSteamCompressor; import com.sudwood.advancedutilities.client.renders.RenderSteamCrusher; import com.sudwood.advancedutilities.client.renders.RenderSteamFurnace; import com.sudwood.advancedutilities.client.renders.RenderSteamQuarry; import com.sudwood.advancedutilities.client.renders.RenderSteamSmeltry; import com.sudwood.advancedutilities.client.renders.RenderTank; import com.sudwood.advancedutilities.client.renders.RenderTankItem; import com.sudwood.advancedutilities.client.renders.RenderTileEntityBase; import com.sudwood.advancedutilities.client.renders.RenderTomato; import com.sudwood.advancedutilities.client.renders.RenderTomatoPlant; import com.sudwood.advancedutilities.client.renders.RenderToolForge; import com.sudwood.advancedutilities.client.renders.RenderWire; import com.sudwood.advancedutilities.entity.EntityBullet; import com.sudwood.advancedutilities.entity.minecart.EntityChunkChestCart; import com.sudwood.advancedutilities.entity.minecart.EntityChunkLoadingCart; import com.sudwood.advancedutilities.entity.minecart.EntityChunkTankCart; import com.sudwood.advancedutilities.entity.minecart.EntitySpeedyChestcart; import com.sudwood.advancedutilities.entity.minecart.EntitySpeedyChunkChestCart; import com.sudwood.advancedutilities.entity.minecart.EntitySpeedyChunkLoadCart; import com.sudwood.advancedutilities.entity.minecart.EntitySpeedyChunkTankCart; import com.sudwood.advancedutilities.entity.minecart.EntitySpeedyMinecart; import com.sudwood.advancedutilities.entity.minecart.EntitySpeedyTankCart; import com.sudwood.advancedutilities.entity.minecart.EntityTankCart; import com.sudwood.advancedutilities.items.AdvancedUtilitiesItems; import com.sudwood.advancedutilities.tileentity.TileEntityArmorForge; import com.sudwood.advancedutilities.tileentity.TileEntityBellows; import com.sudwood.advancedutilities.tileentity.TileEntityBoiler; import com.sudwood.advancedutilities.tileentity.TileEntityElevator; import com.sudwood.advancedutilities.tileentity.TileEntityFluidTube; import com.sudwood.advancedutilities.tileentity.TileEntityHPBoiler; import com.sudwood.advancedutilities.tileentity.TileEntityItemTube; import com.sudwood.advancedutilities.tileentity.TileEntityKiln; import com.sudwood.advancedutilities.tileentity.TileEntityMagnetTube; import com.sudwood.advancedutilities.tileentity.TileEntityPortaChest; import com.sudwood.advancedutilities.tileentity.TileEntityQuarryFrame; import com.sudwood.advancedutilities.tileentity.TileEntityRationedItemTube; import com.sudwood.advancedutilities.tileentity.TileEntityRestrictedItemTube; import com.sudwood.advancedutilities.tileentity.TileEntitySmeltry; import com.sudwood.advancedutilities.tileentity.TileEntitySplitterFluidTube; import com.sudwood.advancedutilities.tileentity.TileEntitySplitterItemTube; import com.sudwood.advancedutilities.tileentity.TileEntitySteamCharger; import com.sudwood.advancedutilities.tileentity.TileEntitySteamCompressor; import com.sudwood.advancedutilities.tileentity.TileEntitySteamCrusher; import com.sudwood.advancedutilities.tileentity.TileEntitySteamFurnace; import com.sudwood.advancedutilities.tileentity.TileEntitySteamQuarry; import com.sudwood.advancedutilities.tileentity.TileEntitySteamSmeltry; import com.sudwood.advancedutilities.tileentity.TileEntityTank; import com.sudwood.advancedutilities.tileentity.TileEntityTomatoPlant; import com.sudwood.advancedutilities.tileentity.TileEntityToolForge; import com.sudwood.advancedutilities.tileentity.TileEntityWire; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.client.registry.RenderingRegistry; import net.minecraft.client.renderer.entity.RenderMinecart; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.MinecraftForgeClient; public class ClientRegistering { public static int kilnId; public static int smeltryId; public static int toolForgeId; public static int boilerId; public static int steamCrusherId; public static int steamFurnaceId; public static int steamSmeltryId; public static int bellowsId; public static int steamCompressorId; public static int tubeId; public static int steamChargerId; public static KeyHandler keyhandle; public static int tankId; public static int tomatoPlantId; public static int splitterTubeId; public static int steamQuarryId; public static int quarryFrameId; public static int wireId; public static int portaChestId; public static int elevatorId; public static final ModelJetpackArmor jetpackArmor = new ModelJetpackArmor(1.0F); public static final ModelRebreatherArmor rebreatherArmor = new ModelRebreatherArmor(1.0F); public static final ModelRunningShoesArmor shoesArmor = new ModelRunningShoesArmor(1.3F); public static final ModelPowerLegsArmor legsArmor = new ModelPowerLegsArmor(1.0F); public static void registerRendering() { kilnId = RenderingRegistry.getNextAvailableRenderId(); smeltryId = RenderingRegistry.getNextAvailableRenderId(); toolForgeId = RenderingRegistry.getNextAvailableRenderId(); boilerId = RenderingRegistry.getNextAvailableRenderId(); steamCrusherId = RenderingRegistry.getNextAvailableRenderId(); steamFurnaceId = RenderingRegistry.getNextAvailableRenderId(); steamSmeltryId = RenderingRegistry.getNextAvailableRenderId(); bellowsId = RenderingRegistry.getNextAvailableRenderId(); steamCompressorId = RenderingRegistry.getNextAvailableRenderId(); tubeId = RenderingRegistry.getNextAvailableRenderId(); steamChargerId = RenderingRegistry.getNextAvailableRenderId(); tankId = RenderingRegistry.getNextAvailableRenderId(); tomatoPlantId = RenderingRegistry.getNextAvailableRenderId(); splitterTubeId = RenderingRegistry.getNextAvailableRenderId(); steamQuarryId = RenderingRegistry.getNextAvailableRenderId(); quarryFrameId = RenderingRegistry.getNextAvailableRenderId(); wireId = RenderingRegistry.getNextAvailableRenderId(); portaChestId = RenderingRegistry.getNextAvailableRenderId(); elevatorId = RenderingRegistry.getNextAvailableRenderId(); keyhandle = new KeyHandler(); RenderingRegistry.registerEntityRenderingHandler(EntityBullet.class, new RenderBullet()); RenderingRegistry.registerEntityRenderingHandler(EntitySpeedyMinecart.class, new RenderSpeedyMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntitySpeedyChestcart.class, new RenderSpeedyMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntityChunkLoadingCart.class, new RenderMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntitySpeedyChunkLoadCart.class, new RenderSpeedyMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntitySpeedyChunkChestCart.class, new RenderSpeedyMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntityChunkChestCart.class, new RenderMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntityTankCart.class, new RenderMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntitySpeedyTankCart.class, new RenderSpeedyMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntityChunkTankCart.class, new RenderMinecart()); RenderingRegistry.registerEntityRenderingHandler(EntitySpeedyChunkTankCart.class, new RenderSpeedyMinecart()); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityKiln.class, new RenderKiln()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.blockKiln), new RenderTileEntityBase(new ModelKilnHeld(), new ResourceLocation("advancedutilities","textures/blocks/kiln.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySmeltry.class, new RenderSmeltry()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.blockSmeltry), new RenderTileEntityBase(new ModelSmeltryHeld(), new ResourceLocation("advancedutilities","textures/blocks/smeltry.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityToolForge.class, new RenderToolForge()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.blockToolForge), new RenderTileEntityBase(new ModelToolForge(), new ResourceLocation("advancedutilities","textures/blocks/toolforge.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityArmorForge.class, new RenderArmorForge()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.blockArmorForge), new RenderTileEntityBase(new ModelToolForge(), new ResourceLocation("advancedutilities","textures/blocks/armorforge.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityBoiler.class, new RenderBoiler(0)); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.steamBoiler), new RenderTileEntityBase(new ModelBoiler(), new ResourceLocation("advancedutilities","textures/blocks/boiler.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityHPBoiler.class, new RenderBoiler(1)); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.hpBoiler), new RenderTileEntityBase(new ModelBoiler(), new ResourceLocation("advancedutilities","textures/blocks/hpboiler.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySteamCrusher.class, new RenderSteamCrusher()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.steamCrusher), new RenderTileEntityBase(new ModelSteamCrusher(), new ResourceLocation("advancedutilities","textures/blocks/steamcrusher.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySteamFurnace.class, new RenderSteamFurnace()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.steamFurnace), new RenderTileEntityBase(new ModelSteamFurnace(), new ResourceLocation("advancedutilities","textures/blocks/steamfurnace.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySteamSmeltry.class, new RenderSteamSmeltry()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.steamSmeltry), new RenderTileEntityBase(new ModelSteamSmeltry(), new ResourceLocation("advancedutilities","textures/blocks/steamsmeltry.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityBellows.class, new RenderBellows()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.bellows), new RenderTileEntityBase(new ModelBellows(), new ResourceLocation("advancedutilities","textures/blocks/bellows.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySteamCompressor.class, new RenderSteamCompressor()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.steamCompressor), new RenderTileEntityBase(new ModelSteamCompressor(), new ResourceLocation("advancedutilities","textures/blocks/steamcompressor.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityItemTube.class, new RenderItemTube()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.itemTube), new RenderTileEntityBase(new ModelTube(), new ResourceLocation("advancedutilities","textures/blocks/itemtube.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityRestrictedItemTube.class, new RenderRestrictedItemTube()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.restrictedItemTube), new RenderTileEntityBase(new ModelTube(), new ResourceLocation("advancedutilities","textures/blocks/restricteditemtube.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityMagnetTube.class, new RenderMagnetTube()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.magnetItemTube), new RenderTileEntityBase(new ModelTube(), new ResourceLocation("advancedutilities","textures/blocks/magnetitemtube.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityRationedItemTube.class, new RenderRationedItemTube()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.rationedItemTube), new RenderTileEntityBase(new ModelTube(), new ResourceLocation("advancedutilities","textures/blocks/rationeditemtube.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySplitterItemTube.class, new RenderSplitterTube()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.splitterItemTube), new RenderTileEntityBase(new ModelSplitterTube(), new ResourceLocation("advancedutilities","textures/blocks/itemtube.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityFluidTube.class, new RenderFluidTube()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.fluidTube), new RenderTileEntityBase(new ModelTube(), new ResourceLocation("advancedutilities","textures/blocks/fluidtube.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySplitterFluidTube.class, new RenderSplitterTube()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.splitterFluidTube), new RenderTileEntityBase(new ModelSplitterTube(), new ResourceLocation("advancedutilities","textures/blocks/fluidtube.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySteamCharger.class, new RenderSteamCharger()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.steamCharger), new RenderTileEntityBase(new ModelSteamCharger(), new ResourceLocation("advancedutilities","textures/blocks/steamcharger.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityTank.class, new RenderTank()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.blockTank), new RenderTileEntityBase(new ModelTank(), new ResourceLocation("advancedutilities","textures/blocks/tank.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityTomatoPlant.class, new RenderTomatoPlant()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.tomatoPlant), new RenderTileEntityBase(new ModelTank(), new ResourceLocation("advancedutilities","textures/blocks/tomatoplant.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySteamQuarry.class, new RenderSteamQuarry()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.steamQuarry), new RenderTileEntityBase(new ModelSteamQuarry(), new ResourceLocation("advancedutilities","textures/blocks/steamquarry.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityQuarryFrame.class, new RenderQuarryFrame()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.quarryFrame), new RenderTileEntityBase(new ModelQuarryFrame(), new ResourceLocation("advancedutilities","textures/blocks/quarryframe.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityPortaChest.class, new RenderPortaChest()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.portaChestWood), new RenderPortaChestItem()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.portaChestBronze), new RenderPortaChestItem()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.portaChestGold), new RenderPortaChestItem()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.portaChestDiamond), new RenderPortaChestItem()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.portaChestPlatinum), new RenderPortaChestItem()); TileEntitySpecialRenderer eRender = new RenderElevator(); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityElevator.class, eRender); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.elevator), new RenderTileEntityBase(new ResourceLocation(AdvancedUtilities.MODID, "models/elevator/elevator.obj"), new ResourceLocation("advancedutilities","models/elevator/elevator.png"))); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityWire.class, new RenderWire()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.ironWire), new RenderTileEntityBase(new ModelQuarryFrame(), new ResourceLocation("advancedutilities","textures/blocks/ironwire.png"))); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.copperWire), new RenderTileEntityBase(new ModelQuarryFrame(), new ResourceLocation("advancedutilities","textures/blocks/copperwire.png"))); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.goldWire), new RenderTileEntityBase(new ModelQuarryFrame(), new ResourceLocation("advancedutilities","textures/blocks/goldwire.png"))); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AdvancedUtilitiesBlocks.blockTank), new RenderTankItem(new ModelTank(), new ResourceLocation("advancedutilities","textures/blocks/tank.png"))); MinecraftForgeClient.registerItemRenderer(AdvancedUtilitiesItems.pnumaticGun, new RenderItem(new ModelGun(), new ResourceLocation("advancedutilities","textures/items/gun.png"))); MinecraftForgeClient.registerItemRenderer(AdvancedUtilitiesItems.jackHammer, new RenderJackHammer(new ModelJackHammer(), new ResourceLocation("advancedutilities","textures/items/jackhammer.png"))); MinecraftForgeClient.registerItemRenderer(AdvancedUtilitiesItems.steamJetpack, new RenderJetpackItem(new ModelJetpack(), new ResourceLocation("advancedutilities","textures/items/jetpack.png"))); MinecraftForgeClient.registerItemRenderer(AdvancedUtilitiesItems.rebreather, new RenderRebreather(new ModelRebreather(), new ResourceLocation("advancedutilities","textures/items/rebreather.png"))); MinecraftForgeClient.registerItemRenderer(AdvancedUtilitiesItems.runningShoes, new RenderRunningShoesItem(new ModelRunningShoes(), new ResourceLocation("advancedutilities","textures/items/runningshoes.png"))); MinecraftForgeClient.registerItemRenderer(AdvancedUtilitiesItems.steamLegs, new RenderRunningShoesItem(new ModelPowerLegs(), new ResourceLocation("advancedutilities","textures/items/powerlegs.png"))); MinecraftForgeClient.registerItemRenderer(AdvancedUtilitiesItems.tomato, new RenderTomato(new ModelTomato(), new ResourceLocation("advancedutilities","textures/items/tomato.png"))); } }
83.052434
280
0.865479
26f6281e0e3caf521c9db15bc2930495e314aabc
6,388
/* * Copyright 2013 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.optaplanner.core.api.score.buildin.hardsoftdouble; import org.optaplanner.core.api.score.AbstractScore; import org.optaplanner.core.api.score.FeasibilityScore; import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore; /** * This {@link Score} is based on 2 levels of double constraints: hard and soft. * Hard constraints have priority over soft constraints. * <p/> * WARNING: NOT RECOMMENDED TO USE DUE TO ROUNDING ERRORS THAT CAUSE SCORE CORRUPTION. * For example, this prints false: <code>System.out.println((0.01 + 0.05) == (0.01 + 0.02 + 0.03));</code> * Use {@link HardSoftBigDecimalScore} instead. * <p/> * This class is immutable. * @see Score */ public final class HardSoftDoubleScore extends AbstractScore<HardSoftDoubleScore> implements FeasibilityScore<HardSoftDoubleScore> { private static final String HARD_LABEL = "hard"; private static final String SOFT_LABEL = "soft"; public static HardSoftDoubleScore parseScore(String scoreString) { String[] levelStrings = parseLevelStrings(HardSoftDoubleScore.class, scoreString, HARD_LABEL, SOFT_LABEL); double hardScore = parseLevelAsDouble(HardSoftDoubleScore.class, scoreString, levelStrings[0]); double softScore = parseLevelAsDouble(HardSoftDoubleScore.class, scoreString, levelStrings[1]); return valueOf(hardScore, softScore); } public static HardSoftDoubleScore valueOf(double hardScore, double softScore) { return new HardSoftDoubleScore(hardScore, softScore); } // ************************************************************************ // Fields // ************************************************************************ private final double hardScore; private final double softScore; private HardSoftDoubleScore(double hardScore, double softScore) { this.hardScore = hardScore; this.softScore = softScore; } /** * The total of the broken negative hard constraints and fulfilled positive hard constraints. * Their weight is included in the total. * The hard score is usually a negative number because most use cases only have negative constraints. * @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled */ public double getHardScore() { return hardScore; } /** * The total of the broken negative soft constraints and fulfilled positive soft constraints. * Their weight is included in the total. * The soft score is usually a negative number because most use cases only have negative constraints. * <p/> * In a normal score comparison, the soft score is irrelevant if the 2 scores don't have the same hard score. * @return higher is better, usually negative, 0 if no soft constraints are broken/fulfilled */ public double getSoftScore() { return softScore; } // ************************************************************************ // Worker methods // ************************************************************************ public boolean isFeasible() { return getHardScore() >= 0.0; } public HardSoftDoubleScore add(HardSoftDoubleScore augment) { return new HardSoftDoubleScore(hardScore + augment.getHardScore(), softScore + augment.getSoftScore()); } public HardSoftDoubleScore subtract(HardSoftDoubleScore subtrahend) { return new HardSoftDoubleScore(hardScore - subtrahend.getHardScore(), softScore - subtrahend.getSoftScore()); } public HardSoftDoubleScore multiply(double multiplicand) { return new HardSoftDoubleScore(hardScore * multiplicand, softScore * multiplicand); } public HardSoftDoubleScore divide(double divisor) { return new HardSoftDoubleScore(hardScore / divisor, softScore / divisor); } public HardSoftDoubleScore power(double exponent) { return new HardSoftDoubleScore(Math.pow(hardScore, exponent), Math.pow(softScore, exponent)); } public HardSoftDoubleScore negate() { return new HardSoftDoubleScore(-hardScore, -softScore); } public Number[] toLevelNumbers() { return new Number[]{hardScore, softScore}; } public boolean equals(Object o) { // A direct implementation (instead of EqualsBuilder) to avoid dependencies if (this == o) { return true; } else if (o instanceof HardSoftDoubleScore) { HardSoftDoubleScore other = (HardSoftDoubleScore) o; return hardScore == other.getHardScore() && softScore == other.getSoftScore(); } else { return false; } } public int hashCode() { // A direct implementation (instead of HashCodeBuilder) to avoid dependencies return (((17 * 37) + Double.valueOf(hardScore).hashCode())) * 37 + Double.valueOf(softScore).hashCode(); } public int compareTo(HardSoftDoubleScore other) { // A direct implementation (instead of CompareToBuilder) to avoid dependencies if (hardScore != other.getHardScore()) { if (hardScore < other.getHardScore()) { return -1; } else { return 1; } } else { if (softScore < other.getSoftScore()) { return -1; } else if (softScore > other.getSoftScore()) { return 1; } else { return 0; } } } public String toString() { return hardScore + HARD_LABEL + "/" + softScore + SOFT_LABEL; } }
37.798817
114
0.638228
e8664ede072675e6e2bb6841e0a12b4d6805c610
3,770
// Copyright 2016 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.loadtest; import static google.registry.request.RequestParameters.extractOptionalIntParameter; import static google.registry.request.RequestParameters.extractRequiredParameter; import dagger.Module; import dagger.Provides; import google.registry.request.Parameter; import javax.servlet.http.HttpServletRequest; import org.joda.time.Minutes; /** * Dagger module for loadtest package. * * @see "google.registry.module.backend.ToolsComponent" */ @Module public final class LoadTestModule { // There's already an @Parameter("clientId") for CreateGroupsAction that's only optional, and we // want this one to be required, so give it a different name. @Provides @Parameter("loadtestClientId") static String provideClientId(HttpServletRequest req) { return extractRequiredParameter(req, "clientId"); } @Provides @Parameter("delaySeconds") static int provideDelaySeconds(HttpServletRequest req) { return extractOptionalIntParameter(req, "delaySeconds") .or(Minutes.ONE.toStandardSeconds().getSeconds()); } @Provides @Parameter("runSeconds") static int provideRunSeconds(HttpServletRequest req) { return extractOptionalIntParameter(req, "runSeconds") .or(Minutes.ONE.toStandardSeconds().getSeconds()); } @Provides @Parameter("successfulDomainCreates") static int provideSuccessfulDomainCreates(HttpServletRequest req) { return extractOptionalIntParameter(req, "successfulDomainCreates").or(0); } @Provides @Parameter("failedDomainCreates") static int provideFailedDomainCreates(HttpServletRequest req) { return extractOptionalIntParameter(req, "failedDomainCreates").or(0); } @Provides @Parameter("domainInfos") static int provideDomainInfos(HttpServletRequest req) { return extractOptionalIntParameter(req, "domainInfos").or(0); } @Provides @Parameter("domainChecks") static int provideDomainChecks(HttpServletRequest req) { return extractOptionalIntParameter(req, "domainChecks").or(0); } @Provides @Parameter("successfulContactCreates") static int provideSuccessfulContactCreates(HttpServletRequest req) { return extractOptionalIntParameter(req, "successfulContactCreates").or(0); } @Provides @Parameter("failedContactCreates") static int provideFailedContactCreates(HttpServletRequest req) { return extractOptionalIntParameter(req, "failedContactCreates").or(0); } @Provides @Parameter("contactInfos") static int provideContactInfos(HttpServletRequest req) { return extractOptionalIntParameter(req, "contactInfos").or(0); } @Provides @Parameter("successfulHostCreates") static int provideSuccessfulHostCreates(HttpServletRequest req) { return extractOptionalIntParameter(req, "successfulHostCreates").or(0); } @Provides @Parameter("failedHostCreates") static int provideFailedHostCreates(HttpServletRequest req) { return extractOptionalIntParameter(req, "failedHostCreates").or(0); } @Provides @Parameter("hostInfos") static int provideHostInfos(HttpServletRequest req) { return extractOptionalIntParameter(req, "hostInfos").or(0); } }
32.5
98
0.766844
732f500de464a1965c850e3ee1fdde8318bc4722
2,396
package toolkit.jetty; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.webapp.WebAppContext; import toolkit.derby.DerbyUtils; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; /** * @author simetrias */ public class WebContainer { private static final Logger logger = Logger.getLogger(WebContainer.class.getName()); private static final Properties properties; private static final String WEBCONTAINER_PORT = "webcontainer_port"; private static final String WEBCONTAINER_WEBAPP = "webcontainer_webapp"; private static final String DEFAULT_WEBAPP = "webapp"; private static final String DEFAULT_PORT = "8080"; static { properties = new Properties(); try { File propFile = new File("webservices.properties"); if (propFile.exists()) { properties.load(new FileReader(propFile)); } } catch (IOException e) { logger.log(Level.SEVERE, null, e); } } public static void main(String[] args) { Logger logger = Logger.getLogger(WebContainer.class.getName()); try { String startDerby = System.getProperty("startDerby"); if (startDerby != null && Boolean.parseBoolean(startDerby)) { DerbyUtils.startDerbyServer(); } WebContainer server = new WebContainer(); server.start(); } catch (Throwable t) { logger.log(Level.SEVERE, null, t); System.exit(1); } } private void startWebServer() throws Exception { Server server = new Server(); Connector connector = new SelectChannelConnector(); int port = new Integer(properties.getProperty(WEBCONTAINER_PORT, DEFAULT_PORT)); connector.setPort(port); server.addConnector(connector); String webapp = properties.getProperty(WEBCONTAINER_WEBAPP, DEFAULT_WEBAPP); WebAppContext wac = new WebAppContext(webapp, "/"); server.setHandler(wac); server.setStopAtShutdown(true); server.start(); } public void start() throws Exception { startWebServer(); } }
31.946667
88
0.657763
3ef99aaa1a222916821f63470209873078a37b90
1,357
package org.robolectric.shadows; import android.location.Criteria; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.TestRunners; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(TestRunners.WithDefaults.class) public class CriteriaTest { private Criteria criteria; @Before public void setUp() { criteria = new Criteria(); } @Test public void shouldReturnAccuracy() { criteria.setAccuracy(Criteria.ACCURACY_COARSE); assertThat(criteria.getAccuracy()).isEqualTo(Criteria.ACCURACY_COARSE); } @Test public void shouldReturnPowerRequirement() { criteria.setPowerRequirement(Criteria.POWER_HIGH); assertThat(criteria.getPowerRequirement()).isEqualTo(Criteria.POWER_HIGH); } @Test public void shouldBeEqual() { criteria.setPowerRequirement(Criteria.POWER_HIGH); criteria.setAccuracy(Criteria.ACCURACY_COARSE); Criteria criteria1 = new Criteria(criteria); Assert.assertTrue(criteria1.equals(criteria)); Criteria criteria2 = new Criteria(); criteria2.setPowerRequirement(Criteria.POWER_HIGH); criteria2.setAccuracy(Criteria.ACCURACY_COARSE); Assert.assertTrue(criteria2.equals(criteria)); } }
28.270833
82
0.725866
28e902b238429d097ece016d22b2899c6095e883
1,384
package cn.xeblog.api.interceptor; import cn.xeblog.api.constant.CommonConstant; import cn.xeblog.api.enums.Code; import cn.xeblog.api.exception.ErrorCodeException; import cn.xeblog.api.service.AdminUserService; import cn.xeblog.api.util.CheckUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 登录拦截器 * * @author yanpanyi */ @Component public class LoginInterceptor implements HandlerInterceptor { @Resource private AdminUserService adminUserService; private final static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.debug("登陆拦截"); String token = request.getHeader(CommonConstant.TOKEN); String uid = request.getHeader(CommonConstant.UID); logger.debug("token {}", token); logger.debug("uid {}", uid); if (CheckUtils.validateToken(uid, token, adminUserService.getToken())) { return true; } // token无效 throw new ErrorCodeException(Code.INVALID_TOKEN); } }
29.446809
121
0.745665
356ec2e6f76bb6510bdc1e649292065445a0edab
1,620
package problems.java.concurrency; import org.apache.commons.lang3.tuple.Pair; import java.util.concurrent.atomic.AtomicReference; public class CAS { static class Simulated { private int value; synchronized int get() { return value; } synchronized int compareAndSwap(int expected, int newValue) { int oldValue = value; if(oldValue == expected) { value = newValue; } return oldValue; } } static class Counter { Simulated casValue; int getValue() { return casValue.get(); } int increment() { int v; do { v = casValue.get(); } while(v != casValue.compareAndSwap(v, v + 1)); return v + 1; } } static class NumberRange { AtomicReference<Pair<Integer,Integer>> atomicReference = new AtomicReference<>(); int getLeft() { return atomicReference.get().getLeft(); } int getRight() { return atomicReference.get().getRight(); } void setLeft(int left) { while(true) { Pair<Integer,Integer> oldVal = atomicReference.get(); Pair<Integer,Integer> newVal = Pair.of(left, oldVal.getRight()); if(atomicReference.compareAndSet(oldVal, newVal)) { return; } } } } }
21.038961
89
0.475309
39758388a28715ac4209e007c2ca4289e5bd91a6
9,052
package ink.envoy.logindemo; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import org.javatuples.Pair; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import de.codecrafters.tableview.TableView; import de.codecrafters.tableview.model.TableColumnWeightModel; import de.codecrafters.tableview.toolkit.SimpleTableDataAdapter; import de.codecrafters.tableview.toolkit.SimpleTableHeaderAdapter; import ink.envoy.logindemo.util.UsersDatabaseHelper; public class UserDetailActivity extends AppCompatActivity { private enum CurrentUserRole { UNKNOWN, ADMIN, NORMAL } private enum LoadDataStatus { IS_ADMIN, IS_NORMALUSER } private static final Map<Integer, String> dbFieldMap = new HashMap<Integer, String>() {{ put(R.string.field_user_detail_activity_id, "_id"); put(R.string.field_user_detail_activity_username, "username"); put(R.string.field_user_detail_activity_password, "password"); put(R.string.field_user_detail_activity_role, "isAdmin"); put(R.string.field_user_detail_activity_sign_up_time, "createdAt"); put(R.string.field_user_detail_activity_last_update_time, "updatedAt"); }}; private static final int[] detailFieldsInAdminView = { R.string.field_user_detail_activity_id, R.string.field_user_detail_activity_username, R.string.field_user_detail_activity_password, R.string.field_user_detail_activity_role, R.string.field_user_detail_activity_sign_up_time, R.string.field_user_detail_activity_last_update_time }; private static final int[] detailFieldsInNormalView = { R.string.field_user_detail_activity_id, R.string.field_user_detail_activity_username, R.string.field_user_detail_activity_role, R.string.field_user_detail_activity_sign_up_time, }; private static final Map<CurrentUserRole, int[]> userRoleFieldMap = new HashMap<CurrentUserRole, int[]>() {{ put(CurrentUserRole.ADMIN, detailFieldsInAdminView); put(CurrentUserRole.NORMAL, detailFieldsInNormalView); }}; private UsersDatabaseHelper usersDatabaseHelper; private TableView userDetailTableView; private Button removeUserButton; private CurrentUserRole currentLoginUserRole; private String currentUserId; private String currentUsername; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_detail); initialize(); } private void initialize() { usersDatabaseHelper = new UsersDatabaseHelper(getApplicationContext()); Intent intent = getIntent(); currentLoginUserRole = intent.getStringExtra("currentLoginUserRole").equals("ADMIN") ? CurrentUserRole.ADMIN : CurrentUserRole.NORMAL; currentUserId = intent.getStringExtra("id"); retrieveUserInfoById(currentUserId); bindViews(); LoadDataStatus status = loadData(); if (status == LoadDataStatus.IS_ADMIN|| currentLoginUserRole != CurrentUserRole.ADMIN) { removeUserButton.setVisibility(View.INVISIBLE); } removeUserButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(UserDetailActivity.this) .setMessage(getString(R.string.hint_are_you_sure_to_remove_user)) .setPositiveButton(getString(R.string.action_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { removeUserById(currentUserId); Intent intent = new Intent(); intent.putExtra("removedUser", currentUserId); setResult(1, intent); UserDetailActivity.this.finish(); } }).setNegativeButton(getString(R.string.action_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do nothing } }).show(); } }); } private void removeUserById(String id) { SQLiteDatabase db = usersDatabaseHelper.getWritableDatabase(); db.delete("users", "_id=?", new String[] { id }); db.close(); } private void retrieveUserInfoById(String id) { SQLiteDatabase db = usersDatabaseHelper.getReadableDatabase(); Cursor cursor = db.query( "users", new String[] { dbFieldMap.get(R.string.field_user_detail_activity_username) }, "_id=?", new String[] { id }, null, null, null); if (cursor.moveToNext()) { currentUsername = cursor.getString(0); } else { throw new RuntimeException("User id does not exist"); } cursor.close(); db.close(); } private void bindViews() { userDetailTableView = (TableView) findViewById(R.id.userDetailTableView); removeUserButton = (Button) findViewById(R.id.removeUserButton); } private LoadDataStatus loadData() { boolean isAdmin = false; SQLiteDatabase db = usersDatabaseHelper.getReadableDatabase(); List<String> requiredDBFieldsList = new LinkedList<>(); int [] arr = userRoleFieldMap.get(CurrentUserRole.ADMIN); for (int key : userRoleFieldMap.get(currentLoginUserRole)) { requiredDBFieldsList.add(dbFieldMap.get(key)); } Cursor cursor = db.query( "users", requiredDBFieldsList.toArray(new String[requiredDBFieldsList.size()]), "username=?", new String[] { currentUsername }, null, null, null); List<String[]> results = new LinkedList<>(); while (cursor.moveToNext()) { List<Pair<String, String>> singleUserDetail = new LinkedList<>(); int[] fields = userRoleFieldMap.get(currentLoginUserRole); for (int i = 0; i < fields.length; ++i) { int field = fields[i]; switch (field) { case R.string.field_user_detail_activity_id: singleUserDetail.add(new Pair<>(getString(field), cursor.getInt(i) + "")); break; case R.string.field_user_detail_activity_username: case R.string.field_user_detail_activity_password: singleUserDetail.add(new Pair<>(getString(field), cursor.getString(i))); break; case R.string.field_user_detail_activity_role: isAdmin = cursor.getInt(i) == 1; singleUserDetail.add(new Pair<>(getString(field), getString( isAdmin ? R.string.hint_user_detail_activity_isAdmin_true : R.string.hint_user_detail_activity_isAdmin_false))); break; case R.string.field_user_detail_activity_sign_up_time: case R.string.field_user_detail_activity_last_update_time: singleUserDetail.add(new Pair<>(getString(field), SimpleDateFormat .getDateTimeInstance().format(new Date(cursor.getLong(i))))); break; } } for (Pair<String, String> userDetailItem : singleUserDetail) { results.add(new String[] { userDetailItem.getValue0(), userDetailItem.getValue1() }); } } cursor.close(); db.close(); userDetailTableView.setHeaderVisible(false); userDetailTableView.setDataAdapter(new SimpleTableDataAdapter(getApplicationContext(), results)); TableColumnWeightModel columnModel = new TableColumnWeightModel(2); columnModel.setColumnWeight(0, 2); columnModel.setColumnWeight(1, 3); userDetailTableView.setColumnModel(columnModel); return isAdmin ? LoadDataStatus.IS_ADMIN : LoadDataStatus.IS_NORMALUSER; } }
42.299065
119
0.619421
a960567dfcc2d5b611f44827548c346cb4ef5df2
6,411
package com.zmh.projectoa.controller; import com.zmh.projectoa.dto.ReturnDto; import com.zmh.projectoa.model.Messages; import com.zmh.projectoa.service.MessageService; import com.zmh.projectoa.service.RedisService; import com.zmh.projectoa.service.UsersService; import com.zmh.projectoa.util.JSONUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; /** * @author zmh * @date 2018/2/1521:41 * 站内信 */ @Controller @RequestMapping(value = "/message") public class MessageController { @Autowired UsersService usersService; @Autowired MessageService messageService; @Autowired RedisService redisService; /** * 站内信箱 */ @RequestMapping(value = "/message") public String message() { return "message"; } /** * 站内信详情 */ @RequestMapping(value = "/message_dtl/{id}") public String message_dtl() { return "message_dtl"; } /** * 发送站内信 */ @RequestMapping(value = "/send_message") @ResponseBody public ReturnDto sendMessage(@RequestParam("userIDs") String userIDs, @RequestParam("title") String title, @RequestParam("message") String message, HttpServletRequest request) { String userID[] = userIDs.split(","); Integer sendId = (Integer) request.getSession().getAttribute("userID"); for (String receiveId : userID) { Messages messages = new Messages(); messages.setSendId(sendId); messages.setReceiveId(Integer.parseInt(receiveId)); messages.setTitle(title); messages.setMessage(message); int messageID = messageService.insertMessage(messages); String unReadMessageIDs = redisService.getValue("message_" + receiveId); if (Objects.isNull(unReadMessageIDs) || "null".equals(unReadMessageIDs)) unReadMessageIDs = String.valueOf(messageID); else unReadMessageIDs += "," + messageID; redisService.setValue("message_" + receiveId, unReadMessageIDs); } return ReturnDto.buildSuccessReturnDto("success"); } /** * 返回特别定制的所有用户信息给用户选择站内信发给谁 */ @RequestMapping(value = "/getAllUser") @ResponseBody public ReturnDto getAllUser(HttpServletRequest request) { Integer id = (Integer) request.getSession().getAttribute("userID"); return usersService.getAllUser(id); } /** * 获取本人未读信息 */ @RequestMapping(value = "/getUnReadMessages") @ResponseBody public ReturnDto getUnReadMessages(HttpServletRequest request) { Integer id = (Integer) request.getSession().getAttribute("userID"); //这里的思路是去redis取message_+'本人id'为key的value 里面包含所有未读messageID String unReadMessageIDs = redisService.getValue("message_" + id); //取出来是空直接跳过 标准格式是10,22,44 代表未读messageID if (!Objects.isNull(unReadMessageIDs) && !"null".equals(unReadMessageIDs) && unReadMessageIDs.length() > 0) { List<Integer> list = JSONUtil.String2List(unReadMessageIDs); //返回一个list<map> map包括发件人姓名 和 message的 id titile List<Map<String, String>> selectByIDs = messageService.selectByIDs(list); return ReturnDto.buildSuccessReturnDto(selectByIDs); } return ReturnDto.buildFailedReturnDto("数据异常"); } /** * 设为已读 * 从redis中剔除这条 */ @RequestMapping(value = "/setIsRead") @ResponseBody public ReturnDto setIsRead(@RequestParam("id") Integer messageID, HttpServletRequest request) { Integer userID = (Integer) request.getSession().getAttribute("userID"); List<Integer> list = new ArrayList<>(); String unReadMessageIDs = redisService.getValue("message_" + userID); //取出来是空直接跳过 标准格式是10,22,44 代表未读messageID if (!Objects.isNull(unReadMessageIDs) && !"null".equals(unReadMessageIDs)) { list = JSONUtil.String2List(unReadMessageIDs); } if(!list.contains(messageID)) return ReturnDto.buildFailedReturnDto("这条信息不存在"); list.remove(messageID); unReadMessageIDs = JSONUtil.List2String(list); redisService.setValue("message_" + userID, unReadMessageIDs); return ReturnDto.buildSuccessReturnDto("success"); } /** * 本人所有接收到的信 */ @RequestMapping(value = "/getMessages") @ResponseBody public ReturnDto getMessages(HttpServletRequest request) { Integer id = (Integer) request.getSession().getAttribute("userID"); Integer pageNum; try { pageNum = Integer.parseInt(request.getParameter("pageNum")); }catch (Exception e){ pageNum = 1; } return ReturnDto.buildSuccessReturnDto(messageService.selectByreceiveID(id, pageNum)); } /** * 返回某一条详细信息 * 新增判断这条信息是否属于这个人 */ @RequestMapping(value = "/getMessageDtl") @ResponseBody public ReturnDto checkMessage(@RequestParam("id") Integer id, HttpServletRequest request) { Integer userID = (Integer) request.getSession().getAttribute("userID"); Messages message = messageService.selectByID(id); if(userID != null && message != null && !"".equals(userID) && userID.intValue() == message.getReceiveId().intValue()) return ReturnDto.buildSuccessReturnDto(message); return ReturnDto.buildFailedReturnDto("没有权限"); } /** * 传入ID 返回发件人 */ @RequestMapping(value = "/getSendUserName") @ResponseBody public ReturnDto getSendUserName(@RequestParam("id") Integer id) { return ReturnDto.buildSuccessReturnDto(usersService.detailUser(id).getRealname()); } /** * 最后一条信息 */ @RequestMapping(value = "/getLastMessage") @ResponseBody public ReturnDto getLastMessage(HttpServletRequest request) { Integer id = (Integer) request.getSession().getAttribute("userID"); return ReturnDto.buildSuccessReturnDto(messageService.getLastMessage(id)); } }
35.41989
117
0.665731
99b58877d295bd1363ac6cec1840e395aefdf1a5
2,550
package ru.job4j.io; import org.junit.Test; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; /** * Test. * * @author Elena Kartashova (kartashova.ee@yandex.ru) * @version $Id$ * @since 0.1 */ public class ConsoleChatTest { public final static String LN = System.lineSeparator(); public ConsoleChat chatting(String dialogs) { ConsoleChat chat = null; try (BufferedReader user = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(dialogs.getBytes())))) { chat = new ConsoleChat(user); chat.start(); } catch (IOException e) { e.printStackTrace(); } return chat; } /** * Тестирование завершение чата. */ @Test public void whenSayFinishThenEndChatting() throws IOException { String words = "закончить"; ConsoleChat chat = this.chatting(words); try (BufferedReader read = new BufferedReader(new FileReader(chat.getAddress() + "/chat.log"))) { assertThat(read.readLine(), is("Ты: закончить")); } } /** * Тестирование функций стоп и продолжить. */ @Test public void whenSayStopAndProceedThenPausedAndContinue() throws IOException { String words = String.format("Hello%sстоп%sтест%sпродолжить%sтест%sзакончить", LN, LN, LN, LN, LN); ConsoleChat chat = this.chatting(words); List<String> buffer = chat.getBuffer(); String line; try (BufferedReader read = new BufferedReader(new FileReader(chat.getAddress() + "/chat.log"))) { assertThat(read.readLine(), is("Ты: Hello")); line = read.readLine(); assertThat(line.substring(0, 5), is("Бот: ")); assertThat(buffer.contains(line.substring(5)), is(true)); assertThat(read.readLine(), is("Ты: стоп")); assertThat(read.readLine(), is("Ты: тест")); assertThat(read.readLine(), is("Ты: продолжить")); line = read.readLine(); assertThat(line.substring(0, 5), is("Бот: ")); assertThat(buffer.contains(line.substring(5)), is(true)); assertThat(read.readLine(), is("Ты: тест")); line = read.readLine(); assertThat(line.substring(0, 5), is("Бот: ")); assertThat(buffer.contains(line.substring(5)), is(true)); assertThat(read.readLine(), is("Ты: закончить")); } } }
34
125
0.608627
3e1b954bf826a157fc94fda51f38afb98b7f355b
483
package panda.dao.sql.expert; import panda.dao.DB; import panda.dao.entity.Entity; import panda.lang.Strings; public class MariadbSqlExpert extends MysqlSqlExpert { @Override public DB getDatabaseType() { return DB.MARIADB; } protected String getTableOption(Entity<?> entity, String name, String defv) { String v = getEntityOptionString(entity, "mariadb-" + name, defv); if (Strings.isEmpty(v)) { return super.getTableOption(entity, name, defv); } return v; } }
23
78
0.73499
116fd4e4e43552ff7c7c0ce95cef45f8df4640cf
3,252
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.stunner.bpmn.client.forms.fields.scriptEditor; import java.util.List; import javax.inject.Inject; import org.jboss.errai.common.client.dom.Event; import org.jboss.errai.common.client.dom.Option; import org.jboss.errai.common.client.dom.Select; import org.jboss.errai.common.client.dom.TextArea; import org.jboss.errai.common.client.dom.Window; import org.jboss.errai.ui.client.local.api.IsElement; import org.jboss.errai.ui.shared.api.annotations.DataField; import org.jboss.errai.ui.shared.api.annotations.EventHandler; import org.jboss.errai.ui.shared.api.annotations.ForEvent; import org.jboss.errai.ui.shared.api.annotations.Templated; import org.uberfire.commons.data.Pair; @Templated public class ScriptTypeFieldEditorView implements IsElement, ScriptTypeFieldEditorPresenter.View { @Inject @DataField("language") private Select language; @Inject @DataField("script") private TextArea script; private ScriptTypeFieldEditorPresenter presenter; @Override public void init(ScriptTypeFieldEditorPresenter presenter) { this.presenter = presenter; } @Override public void setScript(String script) { this.script.setValue(script); } @Override public String getScript() { return script.getValue(); } @Override public void setLanguage(String language) { this.language.setValue(language); } @Override public String getLanguage() { return language.getValue(); } @Override public void setLanguageOptions(List<Pair<String, String>> options) { clearSelect(language); options.forEach(option -> language.add(newOption(option.getK1(), option.getK2()))); } private Option newOption(final String text, final String value) { final Option option = (Option) Window.getDocument().createElement("option"); option.setTextContent(text); option.setValue(value); return option; } private void clearSelect(Select select) { int options = select.getOptions().getLength(); for (int i = 0; i < options; i++) { select.remove(0); } } @EventHandler("language") private void onLanguageChange(@ForEvent("change") final Event event) { presenter.onLanguageChange(); } @EventHandler("script") private void onScriptChange(@ForEvent("change") final Event event) { presenter.onScriptChange(); } }
30.111111
84
0.676199
571c63078b862e179ee268432d5b7f6d4bb1afa6
4,210
package com.beanie.stepsensors; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBAdapter { private static final String TAG = "DBAdapter"; //used for logging database version changes // Field Names: public static final String KEY_ROWID = "_id"; public static final String KEY_TASK = "task"; public static final String KEY_CALORIE = "calorie"; public static final String KEY_DATE = "date"; public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_TASK,KEY_CALORIE, KEY_DATE}; // Column Numbers for each Field Name: public static final int COL_ROWID = 0; public static final int COL_TASK = 1; public static final int COL_CALORIE = 1; public static final int COL_DATE = 3; // DataBase info: public static final String DATABASE_NAME = "dbToDo"; public static final String DATABASE_TABLE = "mainToDo"; public static final int DATABASE_VERSION = 3; // The version number must be incremented each time a change to DB structure occurs. //SQL statement to create database private static final String DATABASE_CREATE_SQL = "CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK + " TEXT NOT NULL, " + KEY_CALORIE + " TEXT NOT NULL, " + KEY_DATE + " TEXT" + ");"; private final Context context; private DatabaseHelper myDBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; myDBHelper = new DatabaseHelper(context); } // Open the database connection. public DBAdapter open() { db = myDBHelper.getWritableDatabase(); return this; } // Close the database connection. public void close() { myDBHelper.close(); } // Add a new set of values to be inserted into the database. public long insertRow(String task,String calorie, String date) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_TASK, task); initialValues.put(KEY_CALORIE, calorie); initialValues.put(KEY_DATE, date); // Insert the data into the database. return db.insert(DATABASE_TABLE, null, initialValues); } // Delete a row from the database, by rowId (primary key) public boolean deleteRow(long rowId) { String where = KEY_ROWID + "=" + rowId; return db.delete(DATABASE_TABLE, where, null) != 0; } public void deleteAll() { Cursor c = getAllRows(); long rowId = c.getColumnIndexOrThrow(KEY_ROWID); if (c.moveToFirst()) { do { deleteRow(c.getLong((int) rowId)); } while (c.moveToNext()); } c.close(); } // Return all data in the database. public Cursor getAllRows() { String where = null; Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null); if (c != null) { c.moveToFirst(); } return c; } // Get a specific row (by rowId) public Cursor getRow(long rowId) { String where = KEY_ROWID + "=" + rowId; Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null); if (c != null) { c.moveToFirst(); } return c; } // Change an existing row to be equal to new data. public boolean updateRow(long rowId, String task, String calorie, String date) { String where = KEY_ROWID + "=" + rowId; ContentValues newValues = new ContentValues(); newValues.put(KEY_TASK, task); newValues.put(KEY_CALORIE, calorie); newValues.put(KEY_DATE, date); // Insert it into the database. return db.update(DATABASE_TABLE, newValues, where, null) != 0; } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase _db) { _db.execSQL(DATABASE_CREATE_SQL); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } } }
28.639456
132
0.684086
4041529d850746e2bad144981c1ce14b76a8473e
806
package com.hihsoft.db1.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hihsoft.db1.persistence.TsysAppMapper; import com.hihsoft.framework.core.baseclass.service.BaseService; import com.hihsoft.framework.exception.ServiceException; /** * <p> Title: </p> * <p> Description:</p> * <p> Copyright: Copyright (c) 2014 </p> * <p> Company:hihsoft.co.,ltd </p> * * @author zhujw * @version 1.0 */ @Service(value ="tsysAppService") public class TsysAppService<T> extends BaseService<T> { @Autowired private TsysAppMapper<T> mapper; public TsysAppMapper<T> getMapper() { return mapper; } public List selectTsysApp() throws ServiceException { return getMapper().selectTsysApp(); } }
22.388889
64
0.740695
3eed49bde95ba8608c58e3ea1914c5f11ed613a9
10,315
package com.hbm.lib; import com.hbm.entity.projectile.EntityBullet; import com.hbm.entity.projectile.EntityBulletBase; import com.hbm.entity.projectile.EntityCombineBall; import com.hbm.entity.projectile.EntityDischarge; import com.hbm.entity.projectile.EntityFire; import com.hbm.entity.projectile.EntityLN2; import com.hbm.entity.projectile.EntityLaserBeam; import com.hbm.entity.projectile.EntityMinerBeam; import com.hbm.entity.projectile.EntityPlasmaBeam; import com.hbm.entity.projectile.EntityRainbow; import net.minecraft.entity.Entity; import net.minecraft.util.DamageSource; import net.minecraft.util.EntityDamageSourceIndirect; public class ModDamageSource extends DamageSource { public static DamageSource nuclearBlast = (new DamageSource("nuclearBlast")).setExplosion(); public static DamageSource mudPoisoning = (new DamageSource("mudPoisoning")).setDamageBypassesArmor(); public static DamageSource acid = (new DamageSource("acid")).setDamageBypassesArmor(); public static DamageSource euthanizedSelf = (new DamageSource("euthanizedSelf")).setDamageBypassesArmor(); public static DamageSource euthanizedSelf2 = (new DamageSource("euthanizedSelf2")).setDamageBypassesArmor(); public static DamageSource tauBlast = (new DamageSource("tauBlast")).setDamageBypassesArmor(); public static DamageSource radiation = (new DamageSource("radiation")).setDamageBypassesArmor(); public static DamageSource suicide = (new DamageSource("suicide")).setProjectile(); public static DamageSource teleporter = (new DamageSource("teleporter")).setDamageIsAbsolute(); public static DamageSource cheater = (new DamageSource("cheater")).setDamageIsAbsolute().setDamageBypassesArmor().setDamageAllowedInCreativeMode(); public static DamageSource rubble = (new DamageSource("rubble")).setProjectile(); public static DamageSource shrapnel = (new DamageSource("shrapnel")).setProjectile(); public static DamageSource blackhole = (new DamageSource("blackhole")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource turbofan = (new DamageSource("blender")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource meteorite = (new DamageSource("meteorite")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource boxcar = (new DamageSource("boxcar")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource boat = (new DamageSource("boat")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource taint = (new DamageSource("taint")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource ams = (new DamageSource("ams")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource amsCore = (new DamageSource("amsCore")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource broadcast = (new DamageSource("broadcast")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource bang = (new DamageSource("bang")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource pc = (new DamageSource("pc")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource cloud = (new DamageSource("cloud")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource lead = (new DamageSource("lead")).setDamageIsAbsolute().setDamageBypassesArmor(); public static DamageSource enervation = (new DamageSource("enervation")).setDamageIsAbsolute().setDamageBypassesArmor(); public ModDamageSource(String p_i1566_1_) { super(p_i1566_1_); } public static DamageSource causeBulletDamage(EntityBullet p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("revolverBullet", p_76353_0_, p_76353_1_)).setProjectile(); } public static DamageSource causeBulletDamage(EntityBulletBase base, Entity ent) { return (new EntityDamageSourceIndirect("revolverBullet", base, ent)).setProjectile(); } public static DamageSource causeDisplacementDamage(EntityBullet p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("chopperBullet", p_76353_0_, p_76353_1_)).setProjectile(); } public static DamageSource causeTauDamage(EntityBullet p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("tau", p_76353_0_, p_76353_1_)).setProjectile().setDamageBypassesArmor(); } public static DamageSource causeCombineDamage(EntityCombineBall p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("cmb", p_76353_0_, p_76353_1_)).setProjectile().setDamageBypassesArmor(); } public static DamageSource causeSubatomicDamage(EntityRainbow p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("subAtomic", p_76353_0_, p_76353_1_)).setProjectile().setDamageBypassesArmor(); } public static DamageSource causeSubatomicDamage2(EntityRainbow p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("subAtomic2", p_76353_0_, p_76353_1_)).setProjectile().setDamageBypassesArmor(); } public static DamageSource causeSubatomicDamage3(EntityRainbow p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("subAtomic3", p_76353_0_, p_76353_1_)).setProjectile().setDamageBypassesArmor(); } public static DamageSource causeSubatomicDamage4(EntityRainbow p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("subAtomic4", p_76353_0_, p_76353_1_)).setProjectile().setDamageBypassesArmor(); } public static DamageSource causeSubatomicDamage5(EntityRainbow p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("subAtomic5", p_76353_0_, p_76353_1_)).setProjectile().setDamageBypassesArmor(); } public static DamageSource euthanized(Entity p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("euthanized", p_76353_0_, p_76353_1_)).setDamageBypassesArmor(); } public static DamageSource causeDischargeDamage(EntityDischarge p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("electrified", p_76353_0_, p_76353_1_)).setDamageBypassesArmor(); } public static DamageSource causeFireDamage(EntityFire p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("flamethrower", p_76353_0_, p_76353_1_)).setFireDamage().setDamageBypassesArmor(); } public static DamageSource causePlasmaDamage(EntityPlasmaBeam p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("plasma", p_76353_0_, p_76353_1_)).setDamageBypassesArmor(); } public static DamageSource causeIceDamage(EntityLN2 p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("ice", p_76353_0_, p_76353_1_)).setDamageBypassesArmor(); } public static DamageSource causeLaserDamage(EntityLaserBeam p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("laser", p_76353_0_, p_76353_1_)).setDamageBypassesArmor(); } public static DamageSource causeLaserDamage(EntityMinerBeam p_76353_0_, Entity p_76353_1_) { return (new EntityDamageSourceIndirect("laser", p_76353_0_, p_76353_1_)).setDamageBypassesArmor(); } public static boolean getIsBullet(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("revolverBullet"); } return false; } public static boolean getIsEmplacer(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("chopperBullet"); } return false; } public static boolean getIsTau(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("tau"); } return false; } public static boolean getIsPoison(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("euthanized"); } return false; } public static boolean getIsCmb(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("cmb"); } return false; } public static boolean getIsSubatomic(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { String s = ((EntityDamageSourceIndirect)source).damageType; return s.equals("subAtomic") || s.equals("subAtomic2") || s.equals("subAtomic3") || s.equals("subAtomic4") || s.equals("subAtomic5"); } return false; } public static boolean getIsDischarge(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("electrified"); } return false; } public static boolean getIsFire(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("flamethrower"); } return false; } public static boolean getIsPlasma(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("plasma"); } return false; } public static boolean getIsLiquidNitrogen(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("ice"); } return false; } public static boolean getIsLaser(DamageSource source) { if(source instanceof EntityDamageSourceIndirect) { return ((EntityDamageSourceIndirect)source).damageType.equals("laser"); } return false; } }
49.354067
149
0.744062
be54483c2550341de076c735a69997b136244a5b
2,340
/** * COPYRIGHT (C) 2015 Alessandro Aiezza II. All Rights Reserved. */ package com.shaba.hexaturn.state; import static com.shaba.hexaturn.HexaturnSatelliteData.BORDER_HEX; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.function.Supplier; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import com.shaba.hexaturn.Enemy; import com.shaba.hexaturn.HexaturnBoard; import com.shaba.hexaturn.HexaturnSatelliteData; import com.shaba.hexaturn.HexaturnSatelliteData.HexaturnSatelliteDataBuilder; import one.util.streamex.StreamEx; /** * @author Alessandro Aiezza II * */ @RunWith ( MockitoJUnitRunner.StrictStubs.class ) public class PlayerMoveCalculatorTest { private HexaturnBoard board; private PlayerMoveCalculator moveCalculator; @Before public void setup() { buildBoard(); moveCalculator = new PlayerMoveCalculator(); } @Test public void shouldHaveTwoNextMoves() { assertThat( moveCalculator.calculateNextMoves( board ).toList() ).hasSize( 2 ) .allSatisfy( nextMove -> { System.out.println( nextMove ); assertThat( moveCalculator.applyMove( board, nextMove ) .peek( System.out::println ) .toJavaOptional() .map( HexaturnBoard::isTerminal ) ) .hasValue( true ); } ); } private void buildBoard() { board = StreamEx.<Supplier<HexaturnSatelliteDataBuilder>> of( BORDER_HEX::toBuilder, () -> sdb().occupant( Enemy::new ), this::sdb, this::sdb, () -> sdb().hasGoal( true ) ) .map( s -> s.get().build() ) .chain( hexStream -> { final List<HexaturnSatelliteData> data = hexStream.toList(); return HexaturnBoard.builder() .width( 1 ) .height( data.size() ) .data( data ) .build(); } ); } /** * Shortcut for a {@link HexaturnSatelliteDataBuilder}. */ private HexaturnSatelliteDataBuilder sdb() { return HexaturnSatelliteData.builder(); } }
28.192771
86
0.607692
dc0ea70930a7fbc81936f9dffd50aa643fe7776a
7,383
// Copyright 2000-2020 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 com.intellij.openapi.vcs.update; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.scope.packageSet.NamedScopesHolder; import com.intellij.psi.search.scope.packageSet.PackageSetBase; import com.intellij.ui.SimpleTextAttributes; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.TreeNode; import java.io.File; import java.util.*; /** * author: lesya */ public class GroupTreeNode extends AbstractTreeNode implements Disposable { private final @Nls String myName; private final boolean mySupportsDeletion; private final List<String> myFilePaths = new ArrayList<>(); private final Map<@NonNls String, @Nls String> myErrorsMap; private final SimpleTextAttributes myInvalidAttributes; private final Project myProject; private final String myFileGroupId; public GroupTreeNode(@Nls @NotNull String name, boolean supportsDeletion, @NotNull SimpleTextAttributes invalidAttributes, @NotNull Project project, @NotNull Map<@NonNls String, @Nls String> errorsMap, @NonNls String id) { myName = name; mySupportsDeletion = supportsDeletion; myInvalidAttributes = invalidAttributes; myProject = project; myErrorsMap = errorsMap; myFileGroupId = id; } public String getFileGroupId() { return myFileGroupId; } @NotNull @Override public String getName() { return myName; } @Override public Icon getIcon(boolean expanded) { return AllIcons.Nodes.Folder; } @NotNull @Override public Collection<VirtualFile> getVirtualFiles() { ArrayList<VirtualFile> result = new ArrayList<>(); for (int i = 0; i < getChildCount(); i++) { result.addAll(((AbstractTreeNode)getChildAt(i)).getVirtualFiles()); } return result; } @NotNull @Override public Collection<File> getFiles() { ArrayList<File> result = new ArrayList<>(); for (int i = 0; i < getChildCount(); i++) { result.addAll(((AbstractTreeNode)getChildAt(i)).getFiles()); } return result; } @Override protected int getItemsCount() { int result = 0; Enumeration children = children(); while (children.hasMoreElements()) { AbstractTreeNode treeNode = (AbstractTreeNode)children.nextElement(); result += treeNode.getItemsCount(); } return result; } @Override protected boolean showStatistics() { return true; } @NotNull @Override public SimpleTextAttributes getAttributes() { return myFilterAttributes == null ? SimpleTextAttributes.SIMPLE_CELL_ATTRIBUTES : myFilterAttributes; } @Override public boolean getSupportsDeletion() { return mySupportsDeletion; } public void addFilePath(@NotNull String filePath) { myFilePaths.add(filePath); } public void rebuild(boolean groupByPackages, @Nullable Pair<PackageSetBase, NamedScopesHolder> filter, boolean showOnlyFilteredItems) { myFilterAttributes = null; if (containsGroups()) { rebuildGroups(groupByPackages, filter, showOnlyFilteredItems); } else { rebuildFiles(groupByPackages, filter, showOnlyFilteredItems); } } private void rebuildGroups(boolean groupByPackages, @Nullable Pair<PackageSetBase, NamedScopesHolder> filter, boolean showOnlyFilteredItems) { boolean apply = false; for (int i = 0; i < getChildCount(); i++) { GroupTreeNode childGroup = (GroupTreeNode)getChildAt(i); childGroup.rebuild(groupByPackages, filter, showOnlyFilteredItems); apply |= childGroup.myFilterAttributes != null; } applyFilter(apply); } private void rebuildFiles(boolean groupByPackages, @Nullable Pair<PackageSetBase, NamedScopesHolder> filter, boolean showOnlyFilteredItems) { for (int i = getChildCount() - 1; i >= 0; i--) { final TreeNode node = getChildAt(i); if (node instanceof Disposable) { Disposer.dispose((Disposable)node); } } removeAllChildren(); if (groupByPackages) { buildPackages(); acceptFilter(filter, showOnlyFilteredItems); } else { buildFiles(filter, showOnlyFilteredItems); } setTreeModel(myTreeModel); if (myTreeModel != null) { myTreeModel.nodeStructureChanged(this); } } private void buildPackages() { Collection<File> files = new LinkedHashSet<>(); for (final String myFilePath : myFilePaths) { files.add(new File(myFilePath)); } GroupByPackages groupByPackages = new GroupByPackages(files); List<File> roots = groupByPackages.getRoots(); addFiles(this, roots, files, groupByPackages, null); } private void addFiles(@NotNull AbstractTreeNode parentNode, @NotNull List<? extends File> roots, @NotNull final Collection<? extends File> files, @NotNull GroupByPackages groupByPackages, String parentPath) { roots.sort((file1, file2) -> { boolean containsFile1 = files.contains(file1); boolean containsFile2 = files.contains(file2); if (containsFile1 == containsFile2) { return file1.getAbsolutePath().compareToIgnoreCase(file2.getAbsolutePath()); } return containsFile1 ? 1 : -1; }); for (final File root : roots) { FileOrDirectoryTreeNode child = files.contains(root) ? new FileTreeNode(root.getAbsolutePath(), myInvalidAttributes, myProject, parentPath) : new DirectoryTreeNode(root.getAbsolutePath(), myProject, parentPath); Disposer.register((Disposable)parentNode, child); parentNode.add(child); addFiles(child, groupByPackages.getChildren(root), files, groupByPackages, child.getFilePath()); } } private void buildFiles(@Nullable Pair<PackageSetBase, NamedScopesHolder> filter, boolean showOnlyFilteredItems) { myFilePaths.sort((path1, path2) -> path1.compareToIgnoreCase(path2)); boolean apply = false; for (final String filePath : myFilePaths) { final FileTreeNode child = new FileTreeNode(filePath, myInvalidAttributes, myProject, null); if (filter != null) { if (child.acceptFilter(filter, showOnlyFilteredItems)) { apply = true; } else if (showOnlyFilteredItems) { Disposer.dispose(child); continue; } } final String error = myErrorsMap.get(filePath); if (error != null) { child.setErrorText(error); } add(child); Disposer.register(this, child); } applyFilter(apply); } private boolean containsGroups() { return myFilePaths.isEmpty(); } @Override public void dispose() { } }
31.551282
140
0.672085
cc110a65efd3a2f900ed7b37057f976c4369c474
2,597
package com.jeffrpowell.adventofcode; import java.awt.geom.Point2D; import java.util.function.Function; public enum Direction { LEFT(pt->new Point2D.Double(pt.getX() - 1, pt.getY()), true), RIGHT(pt->new Point2D.Double(pt.getX() + 1, pt.getY()), true), UP(pt->new Point2D.Double(pt.getX(), pt.getY() - 1), true), DOWN(pt->new Point2D.Double(pt.getX(), pt.getY() + 1), true), UP_LEFT(pt->new Point2D.Double(pt.getX() - 1, pt.getY() - 1), false), UP_RIGHT(pt->new Point2D.Double(pt.getX() + 1, pt.getY() - 1), false), DOWN_LEFT(pt->new Point2D.Double(pt.getX() - 1, pt.getY() + 1), false), DOWN_RIGHT(pt->new Point2D.Double(pt.getX() + 1, pt.getY() + 1), false); private final Function<Point2D, Point2D> travelFn; private final boolean cardinal; private Direction(Function<Point2D, Point2D> travelFn, boolean cardinal) { this.travelFn = travelFn; this.cardinal = cardinal; } public boolean isCardinal() { return cardinal; } public Point2D travelFrom(Point2D location) { return travelFn.apply(location); } public Point2D travelFromNTimes(Point2D location, int n) { for (int i = 0; i < n; i++) { location = travelFn.apply(location); } return location; } public Direction rotateLeft90() { switch (this) { case LEFT: return DOWN; case RIGHT: return UP; case UP: return LEFT; case DOWN: return RIGHT; case UP_LEFT: return DOWN_LEFT; case UP_RIGHT: return UP_LEFT; case DOWN_LEFT: return DOWN_RIGHT; case DOWN_RIGHT: return UP_RIGHT; } return null; } public Direction rotateRight90() { switch (this) { case LEFT: return UP; case RIGHT: return DOWN; case UP: return RIGHT; case DOWN: return LEFT; case UP_LEFT: return UP_RIGHT; case UP_RIGHT: return DOWN_RIGHT; case DOWN_LEFT: return UP_LEFT; case DOWN_RIGHT: return DOWN_LEFT; } return null; } public Direction opposite() { switch (this) { case LEFT: return RIGHT; case RIGHT: return LEFT; case UP: return DOWN; case DOWN: return UP; case UP_LEFT: return DOWN_RIGHT; case UP_RIGHT: return DOWN_LEFT; case DOWN_LEFT: return UP_RIGHT; case DOWN_RIGHT: return UP_LEFT; } return null; } public int rotation90Distance(Direction d) { int distance = 0; Direction current = d; while (current != this) { distance++; current = current.rotateRight90(); } return distance; } }
20.776
76
0.623797
10344a45c87005962746c82047d8f6c3f90aa1f0
656
// � A+ Computer Science - www.apluscompsci.com // Name - Sebastian Nunez // Date - 11/02/18 // Class - 10th // Lab - Factorial import static java.lang.System.*; public class FactorialRunner { public static void main(String[] args) { //add test cases Factorial test = new Factorial(5); out.println(test); test.setNum(4); out.println(test); test.setNum(8); out.println(test); test.setNum(15); out.println(test); test.setNum(6); out.println(test); test.setNum(9); out.println(test); test.setNum(3); out.println(test); } }
18.742857
47
0.560976
e681e7c46d28c44565a051ec1f2c42ae56ab7fa6
565
package com.imooc.entity; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import javax.persistence.*; /** * @author gusuchen * Created in 2018-01-13 22:31 * Description: 地铁站信息表 * Modified by: */ @Accessors(chain = true) @Data @Entity @Table(name = "subway_station") @NoArgsConstructor public class SubwayStation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // 所属地铁线id @Column(name = "subway_id") private Long subwayId; // 站点名称 private String name; }
17.65625
55
0.707965
6ea4439cce80d4f51a380eb0c6a119e3b810396d
840
package com.twu.biblioteca.Controller; import com.twu.biblioteca.Repository.BookRepository; public class BookListController extends BaseController{ private String message; private String[] options; private BookRepository bookRepository; public BookListController() { message = "BookList:"; options = new String[12]; bookRepository = new BookRepository(); generateBookListOptions(); } public String getMessage() { return message; } public String[] getOptions() { return options; } private void generateBookListOptions() { String[] bookNames = bookRepository.getAllBookName(); this.options[0] = "exit"; this.options[1] = "go back"; System.arraycopy(bookNames, 0, this.options, 2, bookNames.length + 2 - 2); } }
25.454545
82
0.654762
7768029c65f66854fdc8868a5009da5b715efbb6
3,682
package com.zookpeer.curator_demo.demo; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; /** * @Description: curator基本用法 * @author: pengfei_yao * @create: 2019/11/8 14:11 */ public class CuratorBase { // 会话超时时间 private static final int SESSION_TIMEOUT = 30 * 1000; // 连接超时时间 private static final int CONNECTION_TIMEOUT = 3 * 1000; // Zookeeper服务地址 private static final String CONNECT_ADDR = "127.0.0.1:2181"; // 创建连接实例 // private CuratorFramework client = null; public static void main(String[] args) throws Exception{ // 1. 重试策略: 初试时间为1s,重试10次 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10); // 2. 通过工厂创建连接 CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(CONNECT_ADDR) .connectionTimeoutMs(CONNECTION_TIMEOUT) .sessionTimeoutMs(SESSION_TIMEOUT) .retryPolicy(retryPolicy) // .namespace("root") .build(); // 3. 开启连接 client.start(); System.out.println("ZooKeeper states : " + ZooKeeper.States.CONNECTED); System.out.println("客户端连接状态 : " + client.getState()); System.out.println("客户端 : " + client.getZookeeperClient().toString()); // 创建永久节点 // client.create().forPath("/curator", "/curator data".getBytes()); // 创建永久有序节点 client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/curator_sequential", "/curator_sequential data".getBytes()); // 创建临时节点 client.create().withMode(CreateMode.EPHEMERAL).forPath("/curator/ephemeral", "/curator/ephemeral data".getBytes()); // 创建临时有序节点 client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/curator/ephemeral_path1", "/curator/ephemeral_path1 data".getBytes()); // client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/curator/ephemeral_path2", "curator/ephemeral_path2 data".getBytes()); // 测试检查某个节点是否存在 Stat stat1 = client.checkExists().forPath("/curator"); Stat stat2 = client.checkExists().forPath("/curator2"); System.out.println("'/curator'是否存在: " + (stat1 != null ? true : false)); System.out.println("'/curator2'是否存在 :" + (stat2 != null ? true :false)); // 获取某个节点的所有节点 System.out.println("所有的节点 : " + client.getChildren().forPath("/")); // 获取某个节点的数据 System.out.println("获取某个节点的数据 : " + new String(client.getData().forPath("/curator"))); // 设置某个节点数据 client.setData().forPath("/curator", "/curator modified data".getBytes()); System.out.println("获取新设置节点的数据 : " + new String(client.getData().forPath("/curator"))); // 创建测试节点数据 client.create().orSetData().creatingParentContainersIfNeeded().forPath("/curator/del_key1", "/curator/del_key1 data".getBytes()); client.create().orSetData().creatingParentContainersIfNeeded().forPath("/curator/del_key2", "/curator/del_key2 data".getBytes()); client.create().orSetData().creatingParentContainersIfNeeded().forPath("/curator/del_key2/test_key", "/curator/del_key2 data".getBytes()); // 删除节点 client.delete().forPath("/curator/del_key1"); // 级联删除子节点 client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/curator/del_key2"); } }
37.191919
162
0.66214
3105fa40bd4653882024e7599f58b6183d53e9e9
1,343
package net.sf.jasperreports.chartthemes.handlers; import org.exolab.castor.mapping.GeneralizedFieldHandler; import org.jfree.ui.GradientPaintTransformType; import org.jfree.ui.StandardGradientPaintTransformer; public class StandartGradientPaintTransformerHandler extends GeneralizedFieldHandler { /** * */ public Object convertUponGet(Object value) { if (value == null) { return null; } return ((StandardGradientPaintTransformer) value).getType().toString(); } /** * */ public Object convertUponSet(Object value) { if (value == null) { return null; } GradientPaintTransformType type = GradientPaintTransformType.CENTER_HORIZONTAL.toString().equals(value) ? GradientPaintTransformType.CENTER_HORIZONTAL : GradientPaintTransformType.CENTER_VERTICAL.toString().equals(value) ? GradientPaintTransformType.CENTER_VERTICAL : GradientPaintTransformType.HORIZONTAL.toString().equals(value) ? GradientPaintTransformType.HORIZONTAL : GradientPaintTransformType.VERTICAL.toString().equals(value) ? GradientPaintTransformType.VERTICAL : null; if (type != null) { return new StandardGradientPaintTransformer(type); } return null; } @Override public Class<StandardGradientPaintTransformer> getFieldType() { return StandardGradientPaintTransformer.class; } }
29.195652
105
0.76545
f84425c66c83fbce3315d48f4c2242499d943f78
18,528
package org.robolectric.shadows; import android.os.Parcel; import android.text.TextUtils; import android.util.Pair; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.annotation.RealObject; import org.robolectric.annotation.HiddenApi; import org.robolectric.util.ReflectionHelpers; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Objects; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static android.os.Build.VERSION_CODES.KITKAT_WATCH; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static org.robolectric.RuntimeEnvironment.castNativePtr; /** * Shadow for {@link android.os.Parcel}. */ @Implements(Parcel.class) @SuppressWarnings("unchecked") public class ShadowParcel { @RealObject private Parcel realObject; private static final Map<Long, ByteBuffer> NATIVE_PTR_TO_PARCEL = new LinkedHashMap<>(); private static long nextNativePtr = 1; // this needs to start above 0, which is a magic number to Parcel @Implementation public void writeByteArray(byte[] b, int offset, int len) { if (b == null) { realObject.writeInt(-1); return; } Number nativePtr = ReflectionHelpers.getField(realObject, "mNativePtr"); nativeWriteByteArray(nativePtr.longValue(), b, offset, len); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static int nativeDataSize(int nativePtr) { return nativeDataSize((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static int nativeDataSize(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).dataSize(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static int nativeDataAvail(int nativePtr) { return nativeDataAvail((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static int nativeDataAvail(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).dataAvailable(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static int nativeDataPosition(int nativePtr) { return nativeDataPosition((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static int nativeDataPosition(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).dataPosition(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static int nativeDataCapacity(int nativePtr) { return nativeDataCapacity((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static int nativeDataCapacity(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).dataCapacity(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeSetDataSize(int nativePtr, int size) { nativeSetDataSize((long) nativePtr, size); } @Implementation(minSdk = LOLLIPOP) public static void nativeSetDataSize(long nativePtr, int size) { NATIVE_PTR_TO_PARCEL.get(nativePtr).setDataSize(size); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeSetDataPosition(int nativePtr, int pos) { nativeSetDataPosition((long) nativePtr, pos); } @Implementation(minSdk = LOLLIPOP) public static void nativeSetDataPosition(long nativePtr, int pos) { NATIVE_PTR_TO_PARCEL.get(nativePtr).setDataPosition(pos); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeSetDataCapacity(int nativePtr, int size) { nativeSetDataCapacity((long) nativePtr, size); } @Implementation(minSdk = LOLLIPOP) public static void nativeSetDataCapacity(long nativePtr, int size) { NATIVE_PTR_TO_PARCEL.get(nativePtr).setDataCapacity(size); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeWriteByteArray(int nativePtr, byte[] b, int offset, int len) { nativeWriteByteArray((long) nativePtr, b, offset, len); } @Implementation(minSdk = LOLLIPOP) public static void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len) { NATIVE_PTR_TO_PARCEL.get(nativePtr).writeByteArray(b, offset, len); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeWriteInt(int nativePtr, int val) { nativeWriteInt((long) nativePtr, val); } @Implementation(minSdk = LOLLIPOP) public static void nativeWriteInt(long nativePtr, int val) { NATIVE_PTR_TO_PARCEL.get(nativePtr).writeInt(val); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeWriteLong(int nativePtr, long val) { nativeWriteLong((long) nativePtr, val); } @Implementation(minSdk = LOLLIPOP) public static void nativeWriteLong(long nativePtr, long val) { NATIVE_PTR_TO_PARCEL.get(nativePtr).writeLong(val); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeWriteFloat(int nativePtr, float val) { nativeWriteFloat((long) nativePtr, val); } @Implementation(minSdk = LOLLIPOP) public static void nativeWriteFloat(long nativePtr, float val) { NATIVE_PTR_TO_PARCEL.get(nativePtr).writeFloat(val); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeWriteDouble(int nativePtr, double val) { nativeWriteDouble((long) nativePtr, val); } @Implementation(minSdk = LOLLIPOP) public static void nativeWriteDouble(long nativePtr, double val) { NATIVE_PTR_TO_PARCEL.get(nativePtr).writeDouble(val); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeWriteString(int nativePtr, String val) { nativeWriteString((long) nativePtr, val); } @Implementation(minSdk = LOLLIPOP) public static void nativeWriteString(long nativePtr, String val) { NATIVE_PTR_TO_PARCEL.get(nativePtr).writeString(val); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static byte[] nativeCreateByteArray(int nativePtr) { return nativeCreateByteArray((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static byte[] nativeCreateByteArray(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).readByteArray(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static int nativeReadInt(int nativePtr) { return nativeReadInt((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static int nativeReadInt(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).readInt(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static long nativeReadLong(int nativePtr) { return nativeReadLong((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static long nativeReadLong(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).readLong(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static float nativeReadFloat(int nativePtr) { return nativeReadFloat((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static float nativeReadFloat(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).readFloat(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static double nativeReadDouble(int nativePtr) { return nativeReadDouble((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static double nativeReadDouble(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).readDouble(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static String nativeReadString(int nativePtr) { return nativeReadString((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static String nativeReadString(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).readString(); } @Implementation @HiddenApi synchronized public static Number nativeCreate() { long nativePtr = nextNativePtr++; NATIVE_PTR_TO_PARCEL.put(nativePtr, new ByteBuffer()); return castNativePtr(nativePtr); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeFreeBuffer(int nativePtr) { nativeFreeBuffer((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static void nativeFreeBuffer(long nativePtr) { NATIVE_PTR_TO_PARCEL.get(nativePtr).clear(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeDestroy(int nativePtr) { nativeDestroy((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static void nativeDestroy(long nativePtr) { NATIVE_PTR_TO_PARCEL.remove(nativePtr); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static byte[] nativeMarshall(int nativePtr) { return nativeMarshall((long) nativePtr); } @Implementation(minSdk = LOLLIPOP) public static byte[] nativeMarshall(long nativePtr) { return NATIVE_PTR_TO_PARCEL.get(nativePtr).toByteArray(); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeUnmarshall(int nativePtr, byte[] data, int offset, int length) { nativeUnmarshall((long) nativePtr, data, offset, length); } @Implementation(minSdk = LOLLIPOP) public static void nativeUnmarshall(long nativePtr, byte[] data, int offset, int length) { NATIVE_PTR_TO_PARCEL.put(nativePtr, ByteBuffer.fromByteArray(data, offset, length)); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeAppendFrom(int thisNativePtr, int otherNativePtr, int offset, int length) { nativeAppendFrom((long) thisNativePtr, otherNativePtr, offset, length); } @Implementation(minSdk = LOLLIPOP) public static void nativeAppendFrom(long thisNativePtr, long otherNativePtr, int offset, int length) { ByteBuffer thisByteBuffer = NATIVE_PTR_TO_PARCEL.get(thisNativePtr); ByteBuffer otherByteBuffer = NATIVE_PTR_TO_PARCEL.get(otherNativePtr); thisByteBuffer.appendFrom(otherByteBuffer, offset, length); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeWriteInterfaceToken(int nativePtr, String interfaceName) { nativeWriteInterfaceToken((long) nativePtr, interfaceName); } @Implementation(minSdk = LOLLIPOP) public static void nativeWriteInterfaceToken(long nativePtr, String interfaceName) { // Write StrictMode.ThreadPolicy bits (assume 0 for test). nativeWriteInt(nativePtr, 0); nativeWriteString(nativePtr, interfaceName); } @HiddenApi @Implementation(maxSdk = KITKAT_WATCH) public static void nativeEnforceInterface(int nativePtr, String interfaceName) { nativeEnforceInterface((long) nativePtr, interfaceName); } @Implementation(minSdk = LOLLIPOP) public static void nativeEnforceInterface(long nativePtr, String interfaceName) { // Consume StrictMode.ThreadPolicy bits (don't bother setting in test). nativeReadInt(nativePtr); String actualInterfaceName = nativeReadString(nativePtr); if (!Objects.equals(interfaceName, actualInterfaceName)) { throw new SecurityException("Binder invocation to an incorrect interface"); } } private static class ByteBuffer { // List of elements where a pair is a piece of data and the sizeof that data private List<Pair<Integer, ?>> buffer = new ArrayList<>(); private int index; /** * Removes all elements from the byte buffer */ public void clear() { index = 0; buffer.clear(); } /** * Reads a byte array from the byte buffer based on the current data position */ public byte[] readByteArray() { int length = readInt(); if (length == -1) { return null; } byte[] array = new byte[length]; for (int i = 0; i < length; i++) { array[i] = readByte(); } return array; } /** * Writes a byte to the byte buffer at the current data position */ public void writeByte(byte b) { writeValue(Byte.SIZE / 8, b); } /** * Writes a byte array starting at offset for length bytes to the byte buffer at the current * data position */ public void writeByteArray(byte[] b, int offset, int length) { writeInt(b.length); for (int i = offset; i < offset + length && i < b.length; i++) { writeByte(b[i]); } } /** * Reads a byte from the byte buffer based on the current data position */ public byte readByte() { return readValue((byte) 0); } /** * Writes an int to the byte buffer at the current data position */ public void writeInt(int i) { writeValue(Integer.SIZE / 8, i); } /** * Reads a int from the byte buffer based on the current data position */ public int readInt() { return readValue(0); } /** * Writes a long to the byte buffer at the current data position */ public void writeLong(long l) { writeValue(Long.SIZE / 8, l); } /** * Reads a long from the byte buffer based on the current data position */ public long readLong() { return readValue(0l); } /** * Writes a float to the byte buffer at the current data position */ public void writeFloat(float f) { writeValue(Float.SIZE / 8, f); } /** * Reads a float from the byte buffer based on the current data position */ public float readFloat() { return readValue(0f); } /** * Writes a double to the byte buffer at the current data position */ public void writeDouble(double d) { writeValue(Double.SIZE / 8, d); } /** * Reads a double from the byte buffer based on the current data position */ public double readDouble() { return readValue(0d); } /** * Writes a String to the byte buffer at the current data position */ public void writeString(String s) { int length = TextUtils.isEmpty(s) ? Integer.SIZE / 8 : s.length(); writeValue(length, s); } /** * Reads a String from the byte buffer based on the current data position */ public String readString() { return readValue(null); } /** * Appends the contents of the other byte buffer to this byte buffer * starting at offset and ending at length. * * @param other ByteBuffer to append to this one * @param offset number of bytes from beginning of byte buffer to start copy from * @param length number of bytes to copy */ public void appendFrom(ByteBuffer other, int offset, int length) { int otherIndex = other.toIndex(offset); int otherEndIndex = other.toIndex(offset + length); for (int i = otherIndex; i < otherEndIndex && i < other.buffer.size(); i++) { int elementSize = other.buffer.get(i).first; Object elementValue = other.buffer.get(i).second; writeValue(elementSize, elementValue); } } /** * Creates a Byte buffer from a raw byte array. * * @param array byte array to read from * @param offset starting position in bytes to start reading array at * @param length number of bytes to read from array */ public static ByteBuffer fromByteArray(byte[] array, int offset, int length) { ByteBuffer byteBuffer = new ByteBuffer(); try { ByteArrayInputStream bis = new ByteArrayInputStream(array, offset, length); ObjectInputStream ois = new ObjectInputStream(bis); int numElements = ois.readInt(); for (int i = 0; i < numElements; i++) { int sizeOf = ois.readInt(); Object value = ois.readObject(); byteBuffer.buffer.add(Pair.create(sizeOf, value)); } return byteBuffer; } catch (Exception e) { throw new RuntimeException(e); } } /** * Converts a ByteBuffer to a raw byte array. This method should be * symmetrical with fromByteArray. */ public byte[] toByteArray() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); int length = buffer.size(); oos.writeInt(length); for (Pair<Integer, ?> element : buffer) { oos.writeInt(element.first); oos.writeObject(element.second); } return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Number of unused bytes in this byte buffer. */ public int dataAvailable() { return dataSize() - dataPosition(); } /** * Total buffer size in bytes of byte buffer included unused space. */ public int dataCapacity() { return dataSize(); } /** * Current data position of byte buffer in bytes. Reads / writes are from this position. */ public int dataPosition() { return toDataPosition(index); } /** * Current amount of bytes currently written for ByteBuffer. */ public int dataSize() { int totalSize = totalSize(); int dataPosition = dataPosition(); return totalSize > dataPosition ? totalSize : dataPosition; } /** * Sets the current data position. * * @param pos * Desired position in bytes */ public void setDataPosition(int pos) { index = toIndex(pos); } public void setDataSize(int size) { // TODO } public void setDataCapacity(int size) { // TODO } private int totalSize() { int size = 0; for (Pair<Integer, ?> element : buffer) { size += element.first; } return size; } private <T> T readValue(T defaultValue) { return (index < buffer.size()) ? (T) buffer.get(index++).second : defaultValue; } private void writeValue(int i, Object o) { Pair<Integer, ?> value = Pair.create(i, o); if (index < buffer.size()) { buffer.set(index, value); } else { buffer.add(value); } index++; } private int toDataPosition(int index) { int pos = 0; for (int i = 0; i < index; i++) { pos += buffer.get(i).first; } return pos; } private int toIndex(int dataPosition) { int calculatedPos = 0; int i = 0; for (; i < buffer.size() && calculatedPos < dataPosition; i++) { calculatedPos += buffer.get(i).first; } return i; } } }
29.597444
106
0.687608
108f6f1f02474903141514cfbcfbfabba1ab6bce
1,573
package behavioralDesignPatterns.commandDesignPattern.projectDocumentOperations.Invoker; import behavioralDesignPatterns.commandDesignPattern.projectDocumentOperations.Command.Command; import behavioralDesignPatterns.commandDesignPattern.projectDocumentOperations.ConcreteCommand.CommandManager; import behavioralDesignPatterns.commandDesignPattern.projectDocumentOperations.ConcreteCommand.CopyCommand; import behavioralDesignPatterns.commandDesignPattern.projectDocumentOperations.ConcreteCommand.CutCommand; import behavioralDesignPatterns.commandDesignPattern.projectDocumentOperations.ConcreteCommand.PasteCommand; import behavioralDesignPatterns.commandDesignPattern.projectDocumentOperations.Receiver.Document; public class DocumentInvoker { private Document document; private CommandManager commandManager; public DocumentInvoker(Document document) { this.document = document; commandManager = CommandManager.getInstance(); } public CommandManager getCommandManager() { return commandManager; } public void cut(int position, int length) { Command cutCommand = new CutCommand(document, position, length); commandManager.invoke(cutCommand); } public void copy(int position, int length) { Command copyCommand = new CopyCommand(document, position, length); commandManager.invoke(copyCommand); } public void paste(String text, int position) { Command pasteCommand = new PasteCommand(document, text, position); commandManager.invoke(pasteCommand); } }
42.513514
110
0.802924
fcee2e43fb7cbaeda65737bec8503d6a9b51961e
981
package org.winwin.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import lombok.Data; @Entity @Table(name = "APPLICATION_USER") @Data public class ApplicationUser extends AuditModel { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false, unique = true) private String username; @NotBlank @Column(nullable = false) private String firstname; @NotBlank @Column(nullable = false) private String lastname; @NotBlank @Column(nullable = false) private String password; @NotBlank @Column(nullable = false) private String email; @NotBlank @Column(nullable = false) private String role; @NotBlank @Column(nullable = false) private String location; }
20.4375
50
0.734964
2927860f4fa150e94f503bc5a1434cbfd08ace7d
562
package com.android.samsung.codelab.guestbookdapp.contract; public interface IntroContract { interface View { void setLoading(boolean isLoading); void toastMessage(String message); void showDialog(String title, String btnText, String message, DialogOnClickListener callback); void launchDeepLink(String deeplink); void showTimelineActivity(boolean animated); } interface Presenter { boolean initializeKeystore(); } interface DialogOnClickListener { void dialogOnClick(); } }
23.416667
102
0.699288
cccf0361187da808d74036f03eb93df992e2f605
1,323
/* * Copyright 2019, Perfect Sense, 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 gyro.core.scope; import java.util.Set; import gyro.core.GyroUI; import gyro.core.Namespace; import gyro.core.Type; import gyro.core.resource.DiffableInternals; import gyro.core.resource.Resource; @Namespace("test") @Type("resource") public class TestResource extends Resource { public TestResource(String name) { DiffableInternals.setName(this, name); } @Override public boolean refresh() { return false; } @Override public void create(GyroUI ui, State state) { } @Override public void update(GyroUI ui, State state, Resource current, Set<String> changedFieldNames) { } @Override public void delete(GyroUI ui, State state) { } }
24.962264
97
0.710506
84e81e12016df47446b5766376599ef523006abb
1,809
package com.redhat.examples.reactive.coffeeshop; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.client.WebClient; import io.vertx.junit5.Checkpoint; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(VertxExtension.class) public class MessagingEndpointTest { @Test @DisplayName("Test Messaging Endpoint") public void testMessagingEndpoint(Vertx vertx, VertxTestContext tc) { JsonObject expectedMessage = new JsonObject() .put("name", "Buffy") .put("product", "Venti Dark Roast") .put("action", "order-received"); vertx.deployVerticle(new MockKafkaVerticle(expectedMessage), tc.completing()); Checkpoint deploymentCheckpoint = tc.checkpoint(); Checkpoint requestCheckpoint = tc.checkpoint(); WebClient webClient = WebClient.create(vertx); System.out.println("WebClient created"); JsonObject testPayload = new JsonObject() .put("name", "Buffy") .put("product", "Venti Dark Roast"); vertx.deployVerticle(new HttpVerticle(), tc.succeeding(id -> { System.out.println("SpikeHttpBarista deployed"); deploymentCheckpoint.flag(); webClient.post(8080, "localhost", "/messaging") .sendJsonObject(testPayload, tc.succeeding(resp -> { System.out.println("resp:" + resp.bodyAsString()); tc.verify(() -> { System.out.println("result: " + resp.bodyAsString()); assertThat(resp.statusCode()).isEqualTo(200); assertThat(resp.bodyAsString()).contains("Buffy"); requestCheckpoint.flag(); }); })); })); } }
32.303571
82
0.689331
2f936a4c4181876acdf9699ab5d8116ef7063f2d
2,602
package eoram.cloudexp.service; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import eoram.cloudexp.data.DataItem; import eoram.cloudexp.data.SimpleDataItem; import eoram.cloudexp.pollables.Completable; import eoram.cloudexp.pollables.Pollable; import eoram.cloudexp.utils.Errors; /** * Represents a scheduled operation. * <p><p> * A scheduled operation represents an operation that has been scheduled but may be pending (i.e., not completed yet). */ public class ScheduledOperation extends Pollable implements Completable { protected boolean completed = false; protected Operation operation = null; protected boolean success = false; protected DataItem dataItem = null; public ScheduledOperation(Operation op) { operation = op; completed = false; dataItem = null; success = false; } public synchronized boolean isReady() { return completed; } public synchronized void onSuccess(DataItem d) { completed = true; success = true; dataItem = d; } public synchronized void onFailure() { completed = true; success = false; dataItem = null; Errors.error("CODING FAIL!"); } public synchronized DataItem getDataItem() { waitUntilReady(); return dataItem; } public Operation getOperation() { return operation; } public synchronized boolean wasSuccessful() // will block until ready { if(completed == false) { waitUntilReady(); } return success; } public void save(ObjectOutputStream os) throws Exception { os.writeBoolean(completed); // save op (workaround for ObliviStore) // TODO: do things correctly later //os.writeObject(operation); boolean operationNotNull = operation != null; os.writeBoolean(operationNotNull); if(operationNotNull == true) { os.writeLong(operation.reqId); os.writeLong(operation.opId); os.writeObject(operation.key); } os.writeBoolean(success); Errors.verify(dataItem != null); os.writeObject(dataItem.toString()); } public ScheduledOperation(ObjectInputStream is) throws Exception { completed = is.readBoolean(); // load op (workaround for ObliviStore) // TODO: do things correctly later //operation = (Operation) is.readObject(); operation = null; boolean operationNotNull = is.readBoolean(); if(operationNotNull == true) { long reqId = is.readLong(); long opId = is.readLong(); String key = (String) is.readObject(); operation = new DownloadOperation(reqId, opId, key); } success = is.readBoolean(); String fromString = (String)is.readObject(); dataItem = new SimpleDataItem(fromString); } }
24.54717
118
0.72329
47ea356938398145769ae5ab4555b55a0a74ba86
2,337
package com.redhat.cloud.notifications.routers; import com.redhat.cloud.notifications.StuffHolder; import com.redhat.cloud.notifications.auth.rbac.RbacRaw; import com.redhat.cloud.notifications.auth.rbac.RbacServer; import io.smallrye.mutiny.Uni; import org.eclipse.microprofile.rest.client.inject.RestClient; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Optional; /** * Stuff around admin of the service and debugging */ @Path("/internal/admin") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class AdminService { @Inject @RestClient RbacServer rbacServer; @GET public Uni<Response> debugRbac(@QueryParam("rhid") String rhid) { Uni<RbacRaw> rbacRawUni = rbacServer.getRbacInfo("notifications,integrations", rhid); return rbacRawUni .onItem() .transform(r -> Response.ok(r.data).build()) .onFailure() .call(t -> Uni.createFrom().item(Response.serverError().entity("Rbac call failed -- see logs").build())); } @Path("/status") @POST public Response setAdminDown(@QueryParam("status") Optional<String> status) { Response.ResponseBuilder builder; StuffHolder th = StuffHolder.getInstance(); switch (status.orElse("ok")) { case "ok": th.setDegraded(false); th.setAdminDown(false); builder = Response.ok() .entity("Reset state to ok"); break; case "degraded": th.setDegraded(true); builder = Response.ok() .entity("Set degraded state"); break; case "admin-down": th.setAdminDown(true); builder = Response.ok() .entity("Set admin down state"); break; default: builder = Response.status(Response.Status.BAD_REQUEST) .entity("Unknown status passed"); } return builder.build(); } }
29.582278
121
0.607617
6ebc03678793834a67c6d19895e12ebb77bcdf47
5,455
/* * Copyright © 2017 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.plugin.sink; import io.cdap.cdap.api.data.format.StructuredRecord; import io.cdap.cdap.api.data.format.UnexpectedFormatException; import io.cdap.cdap.api.data.schema.Schema; import com.google.common.collect.ImmutableMap; import org.junit.Assert; import org.junit.Test; import java.io.IOException; /** * Test Structured Record to Text converter */ public class StructuredToTextTransformerTest { private static final Schema FULL_SCHEMA = Schema.recordOf("full", Schema.Field.of("bool_field", Schema.nullableOf(Schema.of(Schema.Type.BOOLEAN))), Schema.Field.of("int_field", Schema.nullableOf(Schema.of(Schema.Type.INT))), Schema.Field.of("long_field", Schema.nullableOf(Schema.of(Schema.Type.LONG))), Schema.Field.of("float_field", Schema.nullableOf(Schema.of(Schema.Type.FLOAT))), Schema.Field.of("double_field", Schema.nullableOf(Schema.of(Schema.Type.DOUBLE))), Schema.Field.of("bytes_field", Schema.nullableOf(Schema.of(Schema.Type.BYTES))), Schema.Field.of("string_field", Schema.of(Schema.Type.STRING)), Schema.Field.of("enum_field", Schema.nullableOf(Schema.enumWith("A", "B", "C"))), Schema.Field.of("array", Schema.arrayOf(Schema.of(Schema.Type.INT))), Schema.Field.of("map", Schema.mapOf(Schema.of(Schema.Type.STRING), Schema.of(Schema.Type.INT))), Schema.Field.of("union", Schema.unionOf(Schema.of(Schema.Type.NULL), Schema.of(Schema.Type.STRING))) ); private static final Schema VALID_SCHEMA = Schema.recordOf("valid", Schema.Field.of("bool_field", Schema.nullableOf(Schema.of(Schema.Type.BOOLEAN))), Schema.Field.of("int_field", Schema.nullableOf(Schema.of(Schema.Type.INT))), Schema.Field.of("long_field", Schema.nullableOf(Schema.of(Schema.Type.LONG))), Schema.Field.of("float_field", Schema.nullableOf(Schema.of(Schema.Type.FLOAT))), Schema.Field.of("double_field", Schema.nullableOf(Schema.of(Schema.Type.DOUBLE))), Schema.Field.of("bytes_field", Schema.nullableOf(Schema.of(Schema.Type.BYTES))), Schema.Field.of("string_field", Schema.of(Schema.Type.STRING)), Schema.Field.of("enum_field", Schema.nullableOf(Schema.enumWith("A", "B", "C"))) ); private static final StructuredRecord NONNULL_RECORD = StructuredRecord.builder(FULL_SCHEMA) .set("bool_field", false) .set("int_field", 1) .set("long_field", 1L) .set("float_field", 1.0) .set("double_field", 1.0) .set("bytes_field", new byte[]{}) .set("string_field", "String") .set("enum_field", "A") .set("array", new int[]{1, 2, 3}) .set("map", ImmutableMap.of("1", 1, "2", 2, "3", 3)) .set("union", null).build(); private static final String NONNULL_RECORD_STRING = "false\t1\t1\t1.0\t1.0\t\tString\tA"; private static final StructuredRecord NULL_RECORD = StructuredRecord.builder(FULL_SCHEMA) .set("bool_field", null) .set("int_field", null) .set("long_field", 1L) .set("float_field", 1.0) .set("double_field", 1.0) .set("bytes_field", null) .set("string_field", "String") .set("enum_field", "A") .set("array", new int[]{1, 2, 3}) .set("map", ImmutableMap.of("1", 1, "2", 2, "3", 3)) .set("union", null).build(); private static final String NULL_RECORD_STRING = "\t\t1\t1.0\t1.0\t\tString\tA"; private static final Schema INVALID_SCHEMA = Schema.recordOf("invalid", Schema.Field.of("array", Schema.arrayOf(Schema.of(Schema.Type.INT)))); @Test public void testInvalidOutputSchema() throws Exception { // Without specifying the output schema, NONNULL_RECORD's schema FULL_SCHEMA will be used as output schema, // which contains invalid types assertInvalidOutputSchema(new StructuredToTextTransformer("\t", null), NONNULL_RECORD); // Use INVALID_SCHEMA as output schema, which contains invalid type ARRAY assertInvalidOutputSchema(new StructuredToTextTransformer("\t", INVALID_SCHEMA), NONNULL_RECORD); } @Test public void testTextTransform() throws Exception { StructuredToTextTransformer transformer = new StructuredToTextTransformer("\t", VALID_SCHEMA); Assert.assertEquals(NONNULL_RECORD_STRING, transformer.transform(NONNULL_RECORD).toString()); Assert.assertEquals(NULL_RECORD_STRING, transformer.transform(NULL_RECORD).toString()); } private static void assertInvalidOutputSchema(StructuredToTextTransformer transformer, StructuredRecord record) throws IOException { try { transformer.transform(record); Assert.fail(); } catch (UnexpectedFormatException e) { // expected } } }
47.434783
120
0.678093
67498ca44e0b1736bb85ba417bd75e47442fd725
2,447
package datawave.query.jexl.visitors; import datawave.query.jexl.nodes.QueryPropertyMarker; import org.apache.commons.jexl2.parser.ASTNENode; import org.apache.commons.jexl2.parser.ASTNRNode; import org.apache.commons.jexl2.parser.ASTNotNode; import org.apache.commons.jexl2.parser.JexlNode; /** * Determine if all query terms are negated */ public class RootNegationCheckVisitor { /** * Since negations may be pushed down instead of simply looking for a top level negation, look for a leaf node without a negation. * * @param script * @return true if there is no path to a leaf node without passing through a negation, false otherwise */ public static Boolean hasTopLevelNegation(JexlNode script) { RootNegationCheckVisitor visitor = new RootNegationCheckVisitor(); // ensure all negations are pushed down JexlNode pushedDownTree = PushdownNegationVisitor.pushdownNegations(script); return !visitor.hasLeafWithoutNegation(pushedDownTree); } /** * For each child skip over any property markers and look for negations and leafs. If neither is found examine that child until either a negation or leaf is * found * * @param node * @return true if a leaf node was found, false otherwise */ private boolean hasLeafWithoutNegation(JexlNode node) { boolean foundLeaf = false; for (int i = 0; i < node.jjtGetNumChildren() && !foundLeaf; i++) { JexlNode child = node.jjtGetChild(i); Class<?> childClass = child.getClass(); // skip over any query property markers/assignments JexlNode sourceNode = QueryPropertyMarker.getQueryPropertySource(child, null); if (sourceNode != null) { child = sourceNode; } if (ASTNENode.class.equals(childClass) || ASTNotNode.class.equals(childClass) || ASTNRNode.class.equals(childClass)) { // no need to inspect this path anymore continue; } else if (child.jjtGetNumChildren() == 0) { // reached a leaf node without ever encountering a negation foundLeaf = true; } else { // neither a leaf nor negation, continue looking foundLeaf = hasLeafWithoutNegation(child); } } return foundLeaf; } }
39.467742
160
0.642011
afbd08567a4881dbbf45d6e0f7773fd393a65714
1,667
package com.sirma.javacourse.javagui.utils; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Holds utility methods for opening a sockets for a client and a server. */ public final class SocketUtils { private static final Logger logger = LoggerFactory.getLogger(SocketUtils.class); public static final int PORTS_START_RANGE = 7000; public static final int PORTS_END_RANGE = 7020; public static final String HOST = "localhost"; /** * Protects from instantiation. */ private SocketUtils() { } /** * Opens a client socket between 7000-7020. * * @return the socket at the first available port * @throws IOException thrown */ public static Socket openSocket() throws IOException { for (int port = PORTS_START_RANGE; port <= PORTS_END_RANGE; port++) { try { return new Socket(HOST, port); } catch (IOException e) { logger.info(e.getMessage(), e); } } throw new IOException(String.format("No running server sockets in ports range [%s...%s]", PORTS_START_RANGE, PORTS_END_RANGE)); } /** * Opens a server socket between 7000-7020. * * @return the server socket at the first available port * @throws IOException thrown */ public static ServerSocket openServerSocket() throws IOException { for (int port = PORTS_START_RANGE; port <= PORTS_END_RANGE; port++) { try { return new ServerSocket(port); } catch (IOException e) { logger.info(e.getMessage(), e); } } throw new IOException(String.format("No available ports in the range [%s...%s]", PORTS_START_RANGE, PORTS_END_RANGE)); } }
26.460317
91
0.707858
dcd9483c2e872573532727d221c5611ec56ec662
6,990
/** * Copyright 2015 Russoft di Enrico Russo * * 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 it.russoft.api.cache; import it.russoft.api.util.FactoryException; import it.russoft.api.util.NoSuchAttributeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; /** * Created by Enrico Russo on 02/10/14. * */ public class DefaultTemporaryCacheManager<K, V> extends TemporaryCacheManager<K, V> { private static final long DEFAULT_CHECK_INTERVAL = 5_000L; private static final long DEFAULT_LONGEVITY = 300_000L; private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTemporaryCacheManager.class); private static int tid = 0; private boolean running = true; private final Cache<K, TemporaryResource<K, V>> cache; private final Queue<TemporaryResource<K, V>> queue; private final Object lock; private final int size; // private long lastTimestamp; // private long lastLongevity; public DefaultTemporaryCacheManager(ResourceEnvironment<K, V> envi){ this(envi, 11); } public DefaultTemporaryCacheManager(ResourceEnvironment<K, V> envi, final int size){ super(envi); Comparator<TemporaryResource> comparator = new Comparator<TemporaryResource>() { @Override public int compare(TemporaryResource r1, TemporaryResource r2) { final long t1 = r1.getCreationTime()+r1.getLongevity(), t2 = r2.getCreationTime()+r2.getLongevity(); return t1 < t2 ? -1 : t1 > t2 ? 1 : 0; } }; this.lock = new Object(); this.cache = new DefaultTemporaryCache<>(); this.queue = new PriorityQueue<>(size, comparator); this.size = size; final Thread thread = new Thread(new Runnable(){ @Override public void run() { while (DefaultTemporaryCacheManager.this.running) { try { LOGGER.debug("Checking for expired cached resources... (cache: " + cache.size() + ", queue: " + queue.size() + ")"); boolean isValid; TemporaryResource<K, V> r; while ((r = queue.peek()) != null) { final long t = System.currentTimeMillis(); final long c = r.getCreationTime(); final long l = r.getLongevity(); final long x = c + l; // Uncaching of the resource if it's expired // or if the cache is full if (!(isValid = isValid(r, t)) || isFull()) { synchronized (lock) { queue.remove(r); cache.remove(r.getKey()); } LOGGER.debug("Uncached expired resource (at " + x + ") for key '" + r.getKey() + "'"); } // Break-Time-Condition // If the current resource is still valid then // all the followings in the queue are valid. if(isValid){ break; } } Thread.sleep(DEFAULT_CHECK_INTERVAL); } catch (Throwable t) { LOGGER.error("run", t); } } } }); thread.setName("DefaultTemporaryCacheManager#"+(++tid)); thread.start(); } @Override public V get(K key){ return get(key, DEFAULT_LONGEVITY); } @Override public V get(K key, long longevity){ return get(key, longevity, this.envi); } @Override public V get(K key, long longevity, ResourceEnvironment<K, V>envi){ if(envi == null){ throw new NullPointerException("'envi' argument cannot be null"); } final long timestamp = System.currentTimeMillis(); TemporaryResource<K, V> resource = this.cache.get(key); boolean isInvalid = false; if(resource == null || (isInvalid = !isValid(resource, timestamp))){ try{ if(isInvalid){ LOGGER.debug("Re-caching resource for key '"+key+"'"); } else { LOGGER.debug("Caching resource for key '"+key+"'"); } // Requesting to the ResourceEnvironment... V o = envi.get(key); DefaultResourceFactory<K, V> factory = new DefaultResourceFactory<>(key, o); resource = factory.newTemporaryResource(longevity); // setTime(timestamp, longevity); synchronized (this.lock) { if(isFull()) { LOGGER.warn("Unable to cache resource for key '" + key + "' because the cache is full"); } else{ this.cache.put(key, resource); this.queue.add(resource); } } return o; } catch (ClassCastException | FactoryException e) { throw new NoSuchAttributeException("Unable to retrieve the requested resource"); } catch (Exception e){ throw new NoSuchAttributeException("Unable to retrieve the requested resource from the ResourceEnvironment", e); } } return resource.getValue(); } private boolean isValid(TemporaryResource r, long t){ return t < r.getCreationTime()+r.getLongevity(); } private boolean isFull(){ return this.cache.size() >= this.size; } @Override public boolean isEmpty(){ return this.cache.isEmpty(); } // private synchronized void setTime(long timestamp, long longevity){ // long c = timestamp+longevity; // long l = this.lastTimestamp+this.lastLongevity; // if(c > l){ // this.lastTimestamp = timestamp; // this.lastLongevity = longevity; // } // } //} }
35.125628
140
0.535908
c570ffd360e7e024a15d846fe7f795d9cecd65ba
1,922
/* * Copyright 2019 Haulmont. * * 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.jmix.ui.component; public interface Slider<V extends Number> extends Field<V>, HasDatatype<V>, HasOrientation { String NAME = "slider"; /** * Sets the minimum value of the slider. * * @param min the minimum value of the slider */ void setMin(V min); /** * @return the minimum value of the slider */ V getMin(); /** * Sets the maximum value of the slider. * * @param max the maximum value of the slider */ void setMax(V max); /** * @return the maximum value of the slider */ V getMax(); /** * Sets the number of digits after the decimal point. * * @param resolution the number of digits after the decimal point */ void setResolution(int resolution); /** * @return resolution the number of digits after the decimal point */ int getResolution(); /** * Sets the slider to update its value when the user clicks on it. * <p> * By default this behavior is disabled. * * @param updateValueOnClick {@code true} to update the value of the slider on click */ void setUpdateValueOnClick(boolean updateValueOnClick); /** * @return {@code true} if the slider updates its value on click */ boolean isUpdateValueOnCLick(); }
26.328767
92
0.649324
20767b0472f5da41640d47ae147197445f3c2ee4
3,732
/* * Copyright (c) 2020 Vikash Madhow */ package ma.vi.esql.type; import ma.vi.base.lang.NotFoundException; import ma.vi.esql.parser.query.Column; import java.util.ArrayList; import java.util.List; /** * * @author Vikash Madhow (vikash.madhow@gmail.com) */ public abstract class Relation extends AbstractType { /** * Relation type. */ public enum RelationType { TABLE ('T'), VIEW ('V'), INDEX ('I'), SEQUENCE ('S'), COMPOSITE_TYPE('C'), PROJECTION ('P'), JOIN ('J'); public final char marker; RelationType(char marker) { this.marker = marker; } public static RelationType fromMarker(char marker) { return switch (marker) { case 'T' -> TABLE; case 'V' -> VIEW; case 'I' -> INDEX; case 'S' -> SEQUENCE; case 'C' -> COMPOSITE_TYPE; default -> throw new IllegalArgumentException("Unknown relation type: " + marker); }; } } public Relation(String name) { super(name); } public Relation(Relation other) { super(other); } public Relation forAlias(String alias) { return alias == null ? this : null; } @Override public abstract Relation copy(); @Override public Kind kind() { return Kind.COMPOSITE; } @Override public boolean isAbstract() { return false; } public abstract List<Column> columns(); public List<Column> columns(String name) { return columns(null, name); } public List<Column> columns(String relationAlias, String prefix) { Relation rel = this; if (relationAlias != null) { rel = forAlias(relationAlias); if (rel == null) { throw new NotFoundException("Relation with alias " + relationAlias + " could not be found"); } } List<Column> cols = new ArrayList<>(); for (Column c: rel.columns()) { String alias = c.alias(); if (alias != null && (alias.equals(prefix) || (alias.startsWith(prefix) && alias.length() > prefix.length() && alias.charAt(prefix.length()) == '/'))) { cols.add(c); } } return cols; } public boolean hasColumn(String name) { return hasColumn(null, name); } public boolean hasColumn(String relationAlias, String name) { return findColumn(relationAlias, name) != null; } public Column column(String name) throws NotFoundException, AmbiguousColumnException { return column(null, name); } public Column column(String relationAlias, String name) throws NotFoundException { Column col = findColumn(relationAlias, name); if (col == null) { throw new NotFoundException("Column " + (relationAlias == null ? "" : relationAlias + '.') + name + " could not be found in relation " + forAlias(relationAlias).name()); } return col; } public Column findColumn(String relationAlias, String name) { Relation rel = this; if (relationAlias != null) { rel = forAlias(relationAlias); if (rel == null) { throw new NotFoundException("Relation with alias " + relationAlias + " could not be found"); } } Column col = null; for (Column c: rel.columns()) { if (c.alias() != null && c.alias().equals(name)) { if (col != null) { throw new AmbiguousColumnException("Ambiguous column " + name); } col = c; } } return col; } @Override public String toString() { StringBuilder st = new StringBuilder(name()).append(" {\n"); for (Column c: columns()) { c._toString(st, 2, 2); st.append('\n'); } st.append('}'); return st.toString(); } }
24.392157
103
0.589764
e95e13c47db4ec3e9803df523b4081c11d718a0f
3,073
package com.ppdai.infrastructure.rest.controller.client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.codahale.metrics.Counter; import com.ppdai.infrastructure.radar.biz.common.exception.SoaException; import com.ppdai.infrastructure.radar.biz.dto.RadarConstanst; import com.ppdai.infrastructure.radar.biz.dto.client.GetAppMetaRequest; import com.ppdai.infrastructure.radar.biz.dto.client.GetAppMetaResponse; import com.ppdai.infrastructure.radar.biz.dto.client.GetAppRequest; import com.ppdai.infrastructure.radar.biz.dto.client.GetAppResponse; import com.ppdai.infrastructure.radar.biz.dto.pub.UpdateVersionRequest; import com.ppdai.infrastructure.radar.biz.dto.pub.UpdateVersionResponse; import com.ppdai.infrastructure.radar.biz.service.AppService; @RestController @RequestMapping(RadarConstanst.APPPRE) public class ClientAppController { private static final Logger log = LoggerFactory.getLogger(ClientAppNotifyController.class); @Autowired private AppService appService; private Counter counter = null; //直接获取app信息,不等待 @PostMapping("/getApp") public GetAppResponse getApp(@RequestBody GetAppRequest request) { try { return appService.getApp(request); } catch (Exception e) { GetAppResponse response = new GetAppResponse(); log.error("getAppFail失败", e); response.setSuc(false); response.setMsg("获取应用失败"); throw new SoaException(response, e); } } @PostMapping("/getAppMeta") public GetAppMetaResponse getAppMeta(@RequestBody GetAppMetaRequest request) { try { return appService.getAppMeta(request); } catch (Exception e) { GetAppMetaResponse response = new GetAppMetaResponse(); log.error("getAppMeta失败", e); response.setSuc(false); response.setMsg("获取应用失败"); throw new SoaException(response, e); } } @PostMapping("/updateVersion") public UpdateVersionResponse updateVersion(@RequestBody UpdateVersionRequest request) { try { UpdateVersionResponse response = new UpdateVersionResponse(); if (request == null || CollectionUtils.isEmpty(request.getAppIds())) { response.setSuc(false); response.setMsg("参数不能为空!"); return response; } response.setSuc(true); appService.updateVersionByIds(request.getAppIds()); for (long appid : request.getAppIds()) { log.info("app_{}_update_version in updateVersion method更新版本,结束", appid); } return response; } catch (Exception e) { UpdateVersionResponse response = new UpdateVersionResponse(); log.error("updateVersion失败", e); response.setSuc(false); response.setMsg("updateVersion失败"); throw new SoaException(response, e); } } public long getCount() { if (counter != null) { return counter.getCount(); } return 0; } }
34.920455
92
0.775464
afa46e5f973c6b1ee57a41003df8f0cd785bf3be
1,319
package com.kubrick.sbt.web.common.interceptor; import com.kubrick.sbt.web.common.annotation.LoginRequired; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 资源访问拦截器 * * @author k */ public class SourceAccessInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 反射获取方法上的LoginRequired注解 HandlerMethod handlerMethod = (HandlerMethod) handler; LoginRequired loginRequired = handlerMethod.getMethod().getAnnotation(LoginRequired.class); if (loginRequired == null) { return true; } // 有LoginRequired注解说明需要登录,提示用户登录 response.setContentType("application/json; charset=utf-8"); response.getWriter().print("你访问的资源需要登录"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
28.673913
116
0.79909
78574fdee2dde85bb47e3162cb21fa22b94b1fc8
1,484
package com.example.qkx.myshare; /** * Created by qkx on 16/5/30. */ public class Constants { public static final String KEY_OBJECT_ID = "objectId"; //user public static final String KEY_USERNAME = "username"; public static final String KEY_PASSWORD = "password"; public static final String KEY_USER_ID = "userId"; public static final String KEY_NICKNAME = "nickname"; public static final String KEY_HEAD_PHOTO = "headPhoto"; public static final String KEY_SELECTED_PATHS = "selectedPaths"; // share public static final String KEY_DESCRIPTION = "description"; public static final String KEY_IMAGES = "images"; public static final String KEY_OWNER_ID = "ownerId"; public static final String KEY_OWNER_NICKNAME = "ownerNickname"; // friend public static final String KEY_FRIEND_ID = "friendId"; // _file public static final String KEY_NAME = "name"; public static final String KEY_URL = "url"; // table public static final String TABLE_NAME_SHARE = "MyShare"; public static final String TABLE_NAME_USER = "MyUser"; public static final String TABLE_NAME_FRIEND = "MyFriend"; public static final String TABLE_NAME_FILE= "_File"; public static final int REQUEST_HOME_TO_CREATE_NEW = 10; public static final int REQUEST_CREATE_NEW_TO_CHOOSE = 20; public static final int REQUEST_FRIEND_TO_CHOOSE = 30; // upload head pic public static final int REQUEST_CAMERA = 40; }
32.26087
77
0.72372
c6c6ea7ed6169fa3740799e84849ea3cc69bba5c
10,099
import java.applet.Applet; import java.applet.AudioClip; import java.awt.Color; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; public class Ship implements KeyListener, ActionListener{ private JFrame frame; private JPanel panel; private static Icon actor,bar,bombr; private static JLabel label11,label12,label13,scoreLabel; private static int xActor=200; private static int yActor=450; private int x=0; static boolean gameover,bomb=true; private static int count,count2,count3,number; private static int count4,count5; private static int ok=0,ok2=0,ok3=0; private static Rectangle label; private static int Score,high_score,diff; User user; private Timer time1,time2; Ship(){} Ship(final JFrame frame,JPanel panel,User user,int high_score,int diff){ this.high_score=high_score;this.diff=diff; this.user=user; this.frame=frame; this.panel=panel; this.gameover=false; this.number=1; bar=new ImageIcon(getClass().getResource("can"+getNumber()+".jpg"));label12=new JLabel(bar); label12.setBounds(60,605,189,31);panel.add(label12); bombr=new ImageIcon(getClass().getResource("bombready.png"));label13=new JLabel(bombr); label13.setBounds(600,500,150,31);panel.add(label13); this.Score=0; scoreLabel = new JLabel(); scoreLabel.setBounds(620, 20, 100, 100); scoreLabel.setForeground(Color.BLACK); scoreLabel.setFont(new Font("0", Font.BOLD, 50)); scoreLabel.setText(""+Score); panel.add(scoreLabel); frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public void play(){ panel.setLayout(null); actor=new ImageIcon(getClass().getResource("arac11.png")); label11 = new JLabel(actor); label11.setBounds(xActor, yActor, 115, 85); panel.add(label11); frame.addKeyListener(this); panel.setOpaque( false ); frame.setLocationRelativeTo(null); frame.add(panel); frame.setResizable(false); frame.setVisible(true); time1=new Timer(20000,this);time1.start(); time2=new Timer(50000,this);time2.start(); } public static int getxActor() { return xActor; } public static int getyActor() { return yActor; } public void moveBox(int newX,int newY) { label11.setBounds(newX, newY, 115, 85); label=label11.getBounds(); } @Override public void keyPressed(KeyEvent event) { String whichKey=KeyEvent.getKeyText(event.getKeyCode()); if(whichKey.compareTo("Left")==0) { if(x==0){ x++; Thread aa=new Thread(new Jet(frame,panel,getDiff())); aa.start(); Clip clips; try { clips = AudioSystem.getClip(); clips.open(AudioSystem.getAudioInputStream(new File("fuze.wav"))); clips.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } changeLayoutLeft(); checkOver(); scoreLabel.setText(""+Score); panel.add(scoreLabel); frame.add(panel); }else if(whichKey.compareTo("Right")==0){ if(x==0){ x++; Thread aa=new Thread(new Jet(frame,panel,getDiff())); aa.start(); Clip clips; try { clips = AudioSystem.getClip(); clips.open(AudioSystem.getAudioInputStream(new File("fuze.wav"))); clips.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } changeLayoutRight(); checkOver(); scoreLabel.setText(""+getScore()); panel.add(scoreLabel); frame.add(panel); }else if(whichKey.compareTo("Up")==0){ if(x==0){ x++; Thread aa=new Thread(new Jet(frame,panel,getDiff())); aa.start(); Clip clips; try { clips = AudioSystem.getClip(); clips.open(AudioSystem.getAudioInputStream(new File("fuze.wav"))); clips.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } changeLayoutUp(); checkOver(); scoreLabel.setText(""+Score); panel.add(scoreLabel); frame.add(panel); }else if(whichKey.compareTo("Down")==0){ if(x==0){ x++; Thread aa=new Thread(new Jet(frame,panel,getDiff())); aa.start(); Clip clips; try { clips = AudioSystem.getClip(); clips.open(AudioSystem.getAudioInputStream(new File("fuze.wav"))); clips.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } changeLayoutDown(); checkOver(); scoreLabel.setText(""+Score); panel.add(scoreLabel); frame.add(panel); }else if(whichKey.compareTo("Space")==0){ changeSpace(); scoreLabel.setText(""+Score); panel.add(scoreLabel); frame.add(panel); }else if(whichKey.compareTo("Shift")==0){ changeShift(); scoreLabel.setText(""+Score); panel.add(scoreLabel); frame.add(panel); } } public void changeLayoutLeft() { if(xActor>0) xActor=xActor-30; moveBox(xActor,yActor); } public void changeLayoutRight() { if(xActor<700) xActor=xActor+30; moveBox(xActor,yActor); } public void changeLayoutUp() { yActor=yActor-30; moveBox(xActor,yActor); } public void changeLayoutDown() { if(yActor<580) yActor=yActor+50; moveBox(xActor,yActor); } public void changeSpace() { Thread thx=new Thread(new Rocket(frame,panel,xActor,yActor)); thx.start(); Clip clip; try { clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(new File("fuzee.wav"))); clip.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } private void changeShift() { if(bomb==true){ Thread thy=new Thread(new Rocket(frame,panel,xActor,yActor,7)); thy.start(); Clip clip; try { clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(new File("bomb.wav"))); clip.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } bomb=false; panel.remove(label13); } } public void checkOver(){ if(gameover==true){ if(number==11){ time1.stop();time2.stop(); label11.setIcon(null);panel.remove(label11); frame.add(panel); Thread t1 = new Thread(new Explosion(panel,frame,xActor,yActor,3)); t1.start(); frame.dispose(); JFrame finish = new JFrame("GAME OVER"); Icon over=new ImageIcon(getClass().getResource("gameover.jpg")); JLabel labl=new JLabel(over); JLabel your=new JLabel(); your.setBounds(100, 150, 610, 610); your.setForeground(Color.WHITE); your.setFont(new Font("0", Font.BOLD, 50)); your.setText("YOUR SCORE: "+Score); user.setScore(Score); finish.add(your); if(Score>this.getHigh_score()){ Icon newhighh=new ImageIcon(getClass().getResource("High_scoree.png")); JLabel newhigh=new JLabel(newhighh); newhigh.setBounds(500, 250, 290, 250); finish.add(newhigh); } finish.add(labl); finish.setSize(800,700); finish.setVisible(true); finish.setLocationRelativeTo(null); finish.setResizable(false); frame.setVisible(false); } else{ label12.setIcon(null);panel.remove(label12); number=number+1; bar=new ImageIcon(getClass().getResource("can"+getNumber()+".jpg"));label12=new JLabel(bar); label12.setBounds(60,605,189,31);panel.add(label12); gameover=false; } } } public static int getHigh_score() { return high_score; } public static void setHigh_score(int high_score) { Ship.high_score = high_score; } public static int getScore() { return Score; } public static void setScore(int score) { Score = score; } public void setX(int x) { this.x = x; } public static int getNumber() { return number; } public static Rectangle getLabel() { return label; } public static int getOk() { return ok; } public static void setOk(int ok) { Ship.ok = ok; } public static int getOk2() { return ok2; } public static void setOk2(int ok2) { Ship.ok2 = ok2; } public static int getOk3() { return ok3; } public static void setOk3(int ok3) { Ship.ok3 = ok3; } public static int getDiff() { return diff; } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent arg0) { if(arg0.getSource()==time2){ bomb=true; panel.add(label13); } else{ if(ok!=1 && ok2!=1 && ok3!=1){ count++; Thread aa=new Thread(new Jet(frame,panel,getDiff())); aa.start(); } if (count==3){ count--; count2++; Thread enemy=new Thread(new Enemy(frame,panel,getDiff())); enemy.start(); } if(count2==4){ count2=count2-2; count3++; count4++; count5++; Thread tank=new Thread(new Tank(frame,panel)); tank.start(); } if(count3==3){ count3++; ok=1; Thread th=new Thread(new Boss(frame,panel)); th.start(); } if(count4==6){ count4++; ok2=1; Thread thh=new Thread(new Boss(frame,panel)); thh.start(); } if(count5==9){ count5++; ok3=1; Thread thhh=new Thread(new Boss(frame,panel)); thhh.start(); } } } }
24.160287
96
0.663234
3005568912069b493d86575072e31eb1ac1e1329
1,380
/* * Copyright 2020 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.cucumber.platform.distributionautomation.glue.kafka.in; import com.alliander.data.scadameasurementpublishedevent.Message; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component; @Component public class LowVoltageMessageConsumer extends AbstractMessageConsumer { private static final Logger LOGGER = LoggerFactory.getLogger(LowVoltageMessageConsumer.class); protected LowVoltageMessageConsumer( @Value("${low.voltage.kafka.consumer.wait.fail.duration:90000}") final long waitFailMillis) { super(waitFailMillis); } @KafkaListener( containerFactory = "lowVoltageMessageKafkaListenerContainerFactory", topics = "${low.voltage.kafka.topic}") public void listen(final ConsumerRecord<String, Message> consumerRecord) { LOGGER.info("received consumerRecord"); this.consumerRecord = consumerRecord; } }
37.297297
99
0.78913
1447471e7fe436669d02f22bdeb06ae34afef04b
3,159
/* * Copyright (C) 2018 Andrea Binello ("andbin") * * This file is part of the "Swing JTable Demos" project and is licensed * under the MIT License. See one of the license files included in the root * of the project for the full text of the license. */ package net.andbin.jtabledemos; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import net.andbin.jtabledemos.common.resource.Resources; public class JTableDemosMainFrame extends JFrame { private static final long serialVersionUID = 1L; private JMenuBar menuBar; private JMenu databaseMenu; private JRadioButtonMenuItem selectMemoryDatabaseMenuItem; private JMenu helpMenu; private JMenuItem aboutMenuItem; private JList<JTableDemoListItem> demosList; private JScrollPane demosListScrollPane; private JButton runButton; public JTableDemosMainFrame(JTableDemoListItem[] demoListItems) { createMenuBar(); createGui(demoListItems); setTitle(JTableDemos.APP_NAME); setIconImages(Resources.loadWindowIcons()); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); } private void createMenuBar() { menuBar = new JMenuBar(); databaseMenu = new JMenu("Database"); selectMemoryDatabaseMenuItem = new JRadioButtonMenuItem("Select \"Memory\" databasee", true); helpMenu = new JMenu("Help"); aboutMenuItem = new JMenuItem("About " + JTableDemos.APP_NAME); aboutMenuItem.addActionListener(this::showAbout); menuBar.add(databaseMenu); menuBar.add(helpMenu); databaseMenu.add(selectMemoryDatabaseMenuItem); helpMenu.add(aboutMenuItem); setJMenuBar(menuBar); } private void createGui(JTableDemoListItem[] demoListItems) { demosList = new JList<>(demoListItems); demosList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); demosList.setSelectedIndex(0); demosListScrollPane = new JScrollPane(demosList); runButton = new JButton("RUN DEMO"); runButton.addActionListener(this::runDemo); JPanel mainPanel = new JPanel(new BorderLayout(10, 10)); mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); mainPanel.add(demosListScrollPane, BorderLayout.CENTER); mainPanel.add(runButton, BorderLayout.PAGE_END); add(mainPanel, BorderLayout.CENTER); } private void runDemo(ActionEvent e) { JTableDemoListItem demoListItem = demosList.getSelectedValue(); if (demoListItem != null) { demoListItem.getRunnable().run(new String[0]); } } private void showAbout(ActionEvent e) { JTableDemosAbout about = new JTableDemosAbout(); about.showDialog(this); } }
32.90625
101
0.71415
da24088d6dd7dbc9876e9d99de1669005c931fd3
383
package tv.floe.metronome.deeplearning.datasets.fetchers; import java.io.Serializable; import tv.floe.metronome.deeplearning.datasets.DataSet; public interface DataSetFetcher extends Serializable { boolean hasMore(); DataSet next(); void fetch(int numExamples); int totalOutcomes(); int inputColumns(); int totalExamples(); void reset(); int cursor(); }
14.185185
57
0.738903
38d07616c6dd190722e049ae4516a364d1943795
691
package com.zhuangfei.generalpageapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.zhuangfei.generalpage.BaseActivity; public class ExampleActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); inits(); } private void inits() { //隐藏提示页面 // getViewHelper().showSuccessView(); //无数据页面 // getViewHelper().showEmptyView(); //异常页面 // getViewHelper().showErrorView("网络连接出错了!"); //加载页面 getViewHelper().showLoadingView(); } }
22.290323
56
0.662808
6bd001063a45332f5fa479610b52e1854ec2ad6e
3,007
package com.aurelhubert.ahbottomnavigation.notification; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; import android.text.TextUtils; import java.util.ArrayList; import java.util.List; /** * @author repitch */ public class AHNotification implements Parcelable { @Nullable private String text; // can be null, so notification will not be shown @ColorInt private int textColor; // if 0 then use default value @ColorInt private int backgroundColor; // if 0 then use default value public AHNotification() { // empty } private AHNotification(Parcel in) { text = in.readString(); textColor = in.readInt(); backgroundColor = in.readInt(); } public boolean isEmpty() { return TextUtils.isEmpty(text); } public String getText() { return text; } public int getTextColor() { return textColor; } public int getBackgroundColor() { return backgroundColor; } public static AHNotification justText(String text) { return new Builder().setText(text).build(); } public static List<AHNotification> generateEmptyList(int size) { List<AHNotification> notificationList = new ArrayList<>(); for (int i = 0; i < size; i++) { notificationList.add(new AHNotification()); } return notificationList; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(text); dest.writeInt(textColor); dest.writeInt(backgroundColor); } public static class Builder { @Nullable private String text; @ColorInt private int textColor; @ColorInt private int backgroundColor; public Builder setText(String text) { this.text = text; return this; } public Builder setTextColor(@ColorInt int textColor) { this.textColor = textColor; return this; } public Builder setBackgroundColor(@ColorInt int backgroundColor) { this.backgroundColor = backgroundColor; return this; } public AHNotification build() { AHNotification notification = new AHNotification(); notification.text = text; notification.textColor = textColor; notification.backgroundColor = backgroundColor; return notification; } } public static final Creator<AHNotification> CREATOR = new Creator<AHNotification>() { @Override public AHNotification createFromParcel(Parcel in) { return new AHNotification(in); } @Override public AHNotification[] newArray(int size) { return new AHNotification[size]; } }; }
25.058333
89
0.622547
a3d262fe6fe007e55ba4722d12e98c3855a910f4
9,064
/* This software was created by United States Government employees at The Center for Cybersecurity and Cyber Operations (C3O) at the Naval Postgraduate School NPS. Please note that within the United States, copyright protection is not available for any works created by United States Government employees, pursuant to Title 17 United States Code Section 105. This software is in the public domain and is not subject to copyright. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package labtainers.mainui; import java.awt.Dimension; import java.util.ArrayList; import javax.swing.JPanel; /** * * @author Daniel Liao */ public class ContainerConfigAddHosts extends javax.swing.JPanel { /** * Creates new form ContainerConfigAddHosts */ private final ContainerObjPanel parent; public ContainerConfigAddHosts(ContainerObjPanel parent, LabData data, String type, String host, String ip, String network) { initComponents(); this.parent = parent; // IP MODE if(type.equals("ip")){ this.AddHostHostTF.setText(host); this.AddHostIpTF.setText(ip); this.AddHostNetworkCombobox.setVisible(false); } // NETWORK MODE else { //Fill the combobox with the current list of Networks for(int i = 0;i<data.getNetworks().size();i++) this.AddHostNetworkCombobox.addItem(data.getNetworks().get(i).name); this.AddHostNetworkCombobox.setSelectedItem(network); this.AddHostHostTF.setVisible(false); this.AddHostIpTF.setVisible(false); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { AddHostIpTF = new javax.swing.JTextField(); AddHostNetworkCombobox = new javax.swing.JComboBox<>(); AddHostHostTF = new javax.swing.JTextField(); AddHostDeleteButton = new javax.swing.JButton(); setBorder(javax.swing.BorderFactory.createEtchedBorder()); setMaximumSize(new java.awt.Dimension(545, 58)); setMinimumSize(new java.awt.Dimension(545, 58)); setName(""); // NOI18N setPreferredSize(new java.awt.Dimension(545, 58)); AddHostIpTF.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N AddHostHostTF.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N AddHostDeleteButton.setText("Delete"); AddHostDeleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddHostDeleteButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(AddHostNetworkCombobox, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AddHostHostTF, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AddHostIpTF, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AddHostDeleteButton) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(AddHostNetworkCombobox, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE) .addComponent(AddHostHostTF, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(AddHostDeleteButton) .addComponent(AddHostIpTF, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void AddHostDeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddHostDeleteButtonActionPerformed remove(); }//GEN-LAST:event_AddHostDeleteButtonActionPerformed // MANIPULATION // // Deletes this object protected void remove(){ JPanel containerAddhostPanel = (JPanel)this.getParent(); // delete the container from the list containerAddhostPanel.remove(this); // Shorten the panel height holding all the containers and resize it. parent.containerAddHostPanelLength-=63; containerAddhostPanel.setPreferredSize(new Dimension(0,parent.containerAddHostPanelLength)); // Redraw the panel containing the list of containers containerAddhostPanel.revalidate(); containerAddhostPanel.repaint(); } // Adds network to combobox protected void addNetworkToComboBox(String newNetworkName){ AddHostNetworkCombobox.addItem(newNetworkName); } // Deletes network from combobox protected void deleteNetworkInComboBox(String deletedNetwork){ AddHostNetworkCombobox.removeItem(deletedNetwork); } // Updates the combobox list with the renamed network protected void renameNetworkToComboBox(String oldNetwork, String newNetwork){ boolean updateSelectedItem = AddHostNetworkCombobox.getSelectedItem().equals(oldNetwork); ArrayList<String> tmp = new ArrayList<String>(); //Create new list to set as the combobox items for(int i=0;i<AddHostNetworkCombobox.getItemCount();i++){ if(AddHostNetworkCombobox.getItemAt(i).equals(oldNetwork)) tmp.add(newNetwork); else tmp.add(AddHostNetworkCombobox.getItemAt(i)); } // Empty the combobox items AddHostNetworkCombobox.removeAllItems(); // Fill the combobox with updated list of items for(int i=0;i<tmp.size();i++) AddHostNetworkCombobox.addItem(tmp.get(i)); // Set the selected item if the selected network was renamed if(updateSelectedItem) AddHostNetworkCombobox.setSelectedItem(newNetwork); } // GETTERS // public String getNetwork(){ return (String)(AddHostNetworkCombobox.getSelectedItem()); } public String getHost(){ return AddHostHostTF.getText(); } public String getIp(){ return AddHostIpTF.getText(); } public javax.swing.JComboBox<String> getNetworkCombobox(){ return AddHostNetworkCombobox; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton AddHostDeleteButton; private javax.swing.JTextField AddHostHostTF; private javax.swing.JTextField AddHostIpTF; private javax.swing.JComboBox<String> AddHostNetworkCombobox; // End of variables declaration//GEN-END:variables }
43.161905
139
0.694395
53f31914c01fc9e9f4aae62b6598e46e18170324
1,103
package com.example.edison.shudu; import android.content.Context; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SettingActivity extends PreferenceActivity { private static final String OPT_MUSIC = "music"; private static final String OPT_MUSIC_DEF = "true"; private static final String OPT_HINTS = "hints"; private static final String OPT_HINTS_DEF = "true"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); } public static boolean getMusic(Context context){ return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(OPT_MUSIC, Boolean.parseBoolean(OPT_MUSIC_DEF)); } public static boolean getHints(Context context){ return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(OPT_HINTS, Boolean.parseBoolean(OPT_HINTS_DEF)); } }
32.441176
76
0.75068
fea2b2a7de161666bff2637b9662c9f8492786d0
3,672
package org.jenkinsci.plugins.github_branch_source; import java.util.Collections; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMHeadCategory; import jenkins.scm.api.SCMHeadObserver; import jenkins.scm.api.SCMHeadOrigin; import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy; import jenkins.scm.api.trait.SCMHeadAuthority; import jenkins.scm.impl.ChangeRequestSCMHeadCategory; import jenkins.scm.impl.TagSCMHeadCategory; import jenkins.scm.impl.UncategorizedSCMHeadCategory; import org.junit.ClassRule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; public class TagDiscoveryTraitTest { @ClassRule public static JenkinsRule j = new JenkinsRule(); @Test public void decorateContext() throws Exception { GitHubSCMSourceContext probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()); assertThat(probe.wantBranches(), is(false)); assertThat(probe.wantPRs(), is(false)); assertThat(probe.wantTags(), is(false)); assertThat(probe.authorities(), is(Collections.<SCMHeadAuthority<?, ?, ?>>emptyList())); new TagDiscoveryTrait().applyToContext(probe); assertThat(probe.wantBranches(), is(false)); assertThat(probe.wantPRs(), is(false)); assertThat(probe.wantTags(), is(true)); assertThat(probe.authorities(), contains(instanceOf(TagDiscoveryTrait.TagSCMHeadAuthority.class))); } @Test public void includeCategory() throws Exception { assertThat(new TagDiscoveryTrait().includeCategory(ChangeRequestSCMHeadCategory.DEFAULT), is(false)); assertThat(new TagDiscoveryTrait().includeCategory(UncategorizedSCMHeadCategory.DEFAULT), is(false)); assertThat(new TagDiscoveryTrait().includeCategory(TagSCMHeadCategory.DEFAULT), is(true)); } @Test public void authority() throws Exception { try (GitHubSCMSourceRequest probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()).newRequest(new GitHubSCMSource("does-not-exist","http://does-not-exist.test"), null)) { TagDiscoveryTrait.TagSCMHeadAuthority instance = new TagDiscoveryTrait.TagSCMHeadAuthority(); assertThat(instance.isTrusted(probe, new SCMHead("v1.0.0")), is(false)); assertThat(instance.isTrusted(probe, new PullRequestSCMHead("PR-1", "does-not-exists", "http://does-not-exist.test", "feature/1", 1, new BranchSCMHead("master"), SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.MERGE)), is(false)); assertThat(instance.isTrusted(probe, new GitHubTagSCMHead("v1.0.0", 0L)), is(true)); } } @Test public void authority_with_repositoryUrl() throws Exception { try (GitHubSCMSourceRequest probe = new GitHubSCMSourceContext(null, SCMHeadObserver.collect()).newRequest( new GitHubSCMSource("", "", "https://github.com/example/does-not-exist", true), null)) { TagDiscoveryTrait.TagSCMHeadAuthority instance = new TagDiscoveryTrait.TagSCMHeadAuthority(); assertThat(instance.isTrusted(probe, new SCMHead("v1.0.0")), is(false)); assertThat(instance.isTrusted(probe, new PullRequestSCMHead("PR-1", "does-not-exists", "http://does-not-exist.test", "feature/1", 1, new BranchSCMHead("master"), SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.MERGE)), is(false)); assertThat(instance.isTrusted(probe, new GitHubTagSCMHead("v1.0.0", 0L)), is(true)); } } }
52.457143
191
0.723584
1f37514745dd34cd5588e291705c259787221f46
654
package org.computelab.config; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.stream.Collectors; final class StringUtils { /** * Trims a a list of strings. For each string value in the list, * whitespace are trimmed. Then empty strings are removed. The list * returned is a new list. */ static List<String> trim(List<String> vals) { checkNotNull(vals); return vals.stream() .map(val -> val.trim()) .filter(val -> val.length() > 0) .collect(Collectors.toList()); } private StringUtils() {} }
26.16
71
0.623853
aa273546f8fd9d223e2bb55bdc941dac9a63c41e
1,019
package net.atlassian.cmathtutor.domain.persistence.translate.changelog; import java.util.stream.Stream; import javax.xml.bind.annotation.adapters.XmlAdapter; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum FkCascadeActionType { CASCADE("CASCADE"), RESTRICT("RESTRICT"), SET_NULL("SET NULL"); private String sqlName; public static class Adapter extends XmlAdapter<String, FkCascadeActionType> { @Override public String marshal(FkCascadeActionType data) throws Exception { return data.sqlName; } @Override public FkCascadeActionType unmarshal(String value) throws Exception { return Stream.of(FkCascadeActionType.values()).filter(data -> data.sqlName.contentEquals(value)).findFirst() .orElseThrow(() -> new IllegalArgumentException( "enum FkCascadeActionType doesn't have a proper constant for name " + value)); } } }
29.114286
120
0.689892
5b78de5057484797144ed7cd39b39ae2ea5c3c68
577
package codewars.test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import codewars.exercises.CountTheDigit; class CountTheDigitTest { @Test public void test() { assertEquals(CountTheDigit.nbDig(10, 1), 4); assertEquals(CountTheDigit.nbDig(25, 1), 11); assertEquals(CountTheDigit.nbDig(5750, 0), 4700); assertEquals(CountTheDigit.nbDig(11011, 2), 9481); assertEquals(CountTheDigit.nbDig(12224, 8), 7733); assertEquals(CountTheDigit.nbDig(11549, 1), 11905); } }
27.47619
60
0.700173
c0c113312f565ab809c7b3da450f82307f208d6a
393
package com.hapramp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class LookupAccount { @Expose @SerializedName("result") private List<String> mResult; public List<String> getmResult() { return mResult; } public void setmResult(List<String> mResult) { this.mResult = mResult; } }
18.714286
50
0.735369
119dc8cbe9a884ed2b29b6dc97274a4dc7e37b08
237
package com.mohsinkd786.java.spring.repo; import org.springframework.data.mongodb.repository.MongoRepository; import com.mohsinkd786.java.spring.entity.Product; public interface MongoRepo extends MongoRepository<Product, String> { }
23.7
69
0.831224
56d16fe4215baa6737105371ab675bc527dab430
1,624
/* * Copyright 2018 Kostyantyn Krakovych * * 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 net.kosto.configuration.model; /** * Provides list of all supported database script types. * <p> * Each database script type has default value for relative {@link AbstractDatabaseItem#getSourceDirectory()} path. */ public enum DatabaseScriptType { /** * Database script should be executed one time only. */ ONE_TIME("script_one_time"), /** * Database script should be executed on every deploy. */ REUSABLE("script_reusable"); /** * Default relative path name for {@link AbstractDatabaseItem#getSourceDirectory()}. */ private final String sourceDirectory; /** * Constructs instance and sets default values. * * @param sourceDirectory Default relative path. */ DatabaseScriptType(final String sourceDirectory) { this.sourceDirectory = sourceDirectory; } /** * Returns relative path name for source directory. * * @return Relative path name for source directory. */ public String getSourceDirectory() { return sourceDirectory; } }
28
115
0.718596
287af99abb6ba3e9e640f0d57cb54b144cca30c8
584
package io.sphere.sdk.search.model; /** * Exception for {@link Range} in case the lower and upper bounds are exclusive and of the same value. * * {@include.example io.sphere.sdk.search.model.RangeTest#isInvalidWhenBoundsAreEqualAndExclusive()} */ public final class SameExclusiveBoundsException extends InvalidRangeException { private static final long serialVersionUID = -2217525602650171975L; public SameExclusiveBoundsException() { } public <T extends Comparable<? super T>> SameExclusiveBoundsException(final Range<T> range) { super(range); } }
32.444444
102
0.751712
5c0021e8b6a3c5455707d9157e52159291e26f25
3,698
package com.ysl.data.util; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.reflection.DefaultReflectorFactory; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import java.sql.SQLException; /** @author yousili @since 2021/8/18 */ public class InvocationOperationUtil { /** * 包装sql后,重置到invocation中 * @param invocation * @param sql * @throws SQLException */ private void resetSql2Invocation(Invocation invocation, String sql) throws SQLException { final Object[] args = invocation.getArgs(); MappedStatement statement = (MappedStatement) args[0]; Object parameterObject = args[1]; BoundSql boundSql = statement.getBoundSql(parameterObject); MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(boundSql)); MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(),new DefaultReflectorFactory()); msObject.setValue("sqlSource.boundSql.sql", sql); args[0] = newStatement; } private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) { MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) { StringBuilder keyProperties = new StringBuilder(); for (String keyProperty : ms.getKeyProperties()) { keyProperties.append(keyProperty).append(","); } keyProperties.delete(keyProperties.length() - 1, keyProperties.length()); builder.keyProperty(keyProperties.toString()); } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); return builder.build(); } private String getOperateType(Invocation invocation) { final Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; SqlCommandType commondType = ms.getSqlCommandType(); if (commondType.compareTo(SqlCommandType.SELECT) == 0) { return "select"; } if (commondType.compareTo(SqlCommandType.INSERT) == 0) { return "insert"; } if (commondType.compareTo(SqlCommandType.UPDATE) == 0) { return "update"; } if (commondType.compareTo(SqlCommandType.DELETE) == 0) { return "delete"; } return null; } // 定义一个内部辅助类,作用是包装sq class BoundSqlSqlSource implements SqlSource { private BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) { this.boundSql = boundSql; } @Override public BoundSql getBoundSql(Object parameterObject) { return boundSql; } } }
39.763441
159
0.676041
c2f3afc6d1707f045a24fa2ecce87bccfee65b37
1,228
package com.qa.springust.persistence.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @NoArgsConstructor @AllArgsConstructor @Data public class Musician { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Size(min = 0, max = 55) private String name; @Min(0) @Max(12) private Integer strings; @NotNull private String type; @ManyToOne private Band band; public Musician(Long id, String name, Integer strings, String type) { super(); this.id = id; this.name = name; this.strings = strings; this.type = type; } public Musician(String name, Integer strings, String type) { super(); this.name = name; this.strings = strings; this.type = type; } }
21.54386
73
0.696254
a3e76c243aed9f6aab6058f22c530a5d378b3e39
2,632
/* * Data Hub Service (DHuS) - For Space data distribution. * Copyright (C) 2017 GAEL Systems * * This file is part of DHuS software sources. * * 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 fr.gael.dhus.service.eviction; import fr.gael.dhus.database.object.config.eviction.Eviction; import org.quartz.CronScheduleBuilder; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; public class EvictionScheduler { /** Scheduler used to handle eviction CRONS */ private final Scheduler scheduler; public EvictionScheduler() throws SchedulerException { scheduler = StdSchedulerFactory.getDefaultScheduler(); } public void scheduleEviction(Eviction eviction) throws SchedulerException { JobDetail jobDetail = JobBuilder.newJob(EvictionJob.class) .withIdentity(eviction.getName(), "Eviction") .build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity(eviction.getName() + "Trigger", "EvictionTrigger") .withSchedule(CronScheduleBuilder.cronSchedule(eviction.getCron().getSchedule())) .build(); // remove existing job if exists if (scheduler.checkExists(jobDetail.getKey())) { scheduler.deleteJob(jobDetail.getKey()); } // schedule job scheduler.scheduleJob(jobDetail, trigger); } public void unscheduleEviction(Eviction eviction) throws SchedulerException { JobDetail jobDetail = JobBuilder.newJob(EvictionJob.class) .withIdentity(eviction.getName(), "Eviction") .build(); // remove existing job if exists if (scheduler.checkExists(jobDetail.getKey())) { scheduler.deleteJob(jobDetail.getKey()); } } public void start() throws SchedulerException { scheduler.start(); } }
32.097561
93
0.710486
d5e81b88f2b328360adf76c989398c5debb394c2
1,348
package tw.com.fcb.lion.core.commons.http; import java.time.LocalDate; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; @Component public class DateConverter implements Converter<String, LocalDate>{ @Override public LocalDate convert(String source) { // TODO Auto-generated method stub if(source == null) { return LocalDate.now(); } if(source.length() == 10) { return LocalDate.of(Integer.valueOf(source.substring(0,4)), Integer.valueOf(source.substring(5,7)), Integer.valueOf(source.substring(8,10))); }else if(source.length() == 8) { return LocalDate.of(Integer.valueOf(source.substring(0,4)), Integer.valueOf(source.substring(4,6)), Integer.valueOf(source.substring(6,8))); } else if (source.length() == 7) { String rocYear = source.substring(0,3); return LocalDate.of(Integer.parseInt(rocYear)+1911, Integer.valueOf(source.substring(3,5)), Integer.valueOf(source.substring(5,7))); } else if (source.length() == 6) { String rocYear = source.substring(0,2); return LocalDate.of(Integer.parseInt(rocYear)+1911, Integer.valueOf(source.substring(2,4)), Integer.valueOf(source.substring(4,6))); } return null; } }
27.510204
68
0.662463
b77b8d0fcf2c31e18edf3bf6445bb56dd368e726
4,674
package fr.insalyon.waso.web; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import fr.insalyon.waso.util.JsonHttpClient; import fr.insalyon.waso.util.exception.ServiceException; import java.io.IOException; import org.apache.http.message.BasicNameValuePair; /** * * @author WASO Team */ public class AjaxAction { protected String smaUrl; protected JsonObject container; protected JsonHttpClient jsonHttpClient; public AjaxAction(String smaUrl, JsonObject container) { this.smaUrl = smaUrl; this.container = container; this.jsonHttpClient = new JsonHttpClient(); } public void release() { try { this.jsonHttpClient.close(); } catch (IOException ex) { // Ignorer } } protected static JsonObject transformClient(JsonObject client) { // Transformation de l'entité Client pour l'affichage (id,denomination,adresse,ville) JsonObject jsonItem = new JsonObject(); jsonItem.addProperty("id", client.get("id").getAsString()); jsonItem.addProperty("denomination", client.get("denomination").getAsString()); // Pour afficher le code postal avant le nom de la ville String ville = client.get("ville").getAsString(); int indexCodePostal = ville.lastIndexOf(" "); if (indexCodePostal > 0) { ville = ville.substring(indexCodePostal + 1) + " " + ville.substring(0, indexCodePostal); } jsonItem.addProperty("adresse", client.get("adresse").getAsString()); jsonItem.addProperty("ville", ville); // Simplification des entités Personnes (id,nom,prenom) JsonArray persons = new JsonArray(); for (JsonElement p : client.get("personnes").getAsJsonArray()) { JsonObject person = p.getAsJsonObject(); JsonObject jsonSubItem = new JsonObject(); jsonSubItem.add("id", person.get("id")); jsonSubItem.add("nom", person.get("nom")); jsonSubItem.add("prenom", person.get("prenom")); persons.add(jsonSubItem); } jsonItem.add("personnes", persons); return jsonItem; } protected static JsonArray transformListeClient(JsonArray liste) { JsonArray jsonListe = new JsonArray(); for (JsonElement i : liste) { jsonListe.add(transformClient(i.getAsJsonObject())); } return jsonListe; } public void getListeClient() throws ServiceException { try { JsonObject smaResultContainer = this.jsonHttpClient.post( this.smaUrl, new BasicNameValuePair("SMA", "getListeClient") ); if (smaResultContainer == null) { throw new ServiceException("Appel impossible au SMA getListeClient [" + this.smaUrl + "]"); } JsonArray jsonListe = transformListeClient(smaResultContainer.getAsJsonArray("clients")); this.container.add("clients", jsonListe); } catch (IOException ex) { throw new ServiceException("Exception in Ajax getListeClient", ex); } } public void rechercherClientParNumero(Integer numero) throws ServiceException { try { JsonObject smaResultContainer = this.jsonHttpClient.post( this.smaUrl, new BasicNameValuePair("SMA", "rechercherClientParNumero"), new BasicNameValuePair("numero", Integer.toString(numero)) ); if (smaResultContainer == null) { throw new ServiceException("Appel impossible au SMA rechercherClientParNumero [" + this.smaUrl + "]"); } if (smaResultContainer.getAsJsonArray("clients") == null) { //throw new ServiceException("Erreur: SMA rechercherClientParNumero non-implémenté ??? [" + this.smaUrl + "]"); } else { JsonArray jsonListe = transformListeClient(smaResultContainer.getAsJsonArray("clients")); this.container.add("clients", jsonListe); } } catch (IOException ex) { throw new ServiceException("Exception in Ajax rechercherClientParNumero", ex); } } void rechercherClientParDenomination(String denomination, String ville) throws ServiceException { // ... } void rechercherClientParNomPersonne(String nomPersonne, String ville) throws ServiceException { // ... } }
31.16
127
0.612965
3416c95c42d2348a44e7710d158641ebcdac4ab5
145
package org.recap.model; /** * Created by akulak on 3/3/17. */ public class ItemAvailabilityResponse extends DocTypeAvailabilityResponse { }
16.111111
75
0.758621
41244227ee69ee0dbc1a9ca2dda16f4bb430c01a
2,119
/** * Copyright 2017-2020 O2 Czech Republic, a.s. * * 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 cz.o2.proxima.direct.core; import cz.o2.proxima.annotations.Stable; import cz.o2.proxima.repository.EntityDescriptor; import cz.o2.proxima.storage.StreamElement; import java.net.URI; import java.util.Map; import java.util.Optional; /** Dummy storage printing data to stdout. */ @Stable public class StdoutStorage implements DataAccessorFactory { private static final long serialVersionUID = 1L; @Override public Accept accepts(URI uri) { return uri.getScheme().equals("stdout") ? Accept.ACCEPT : Accept.REJECT; } @Override public DataAccessor createAccessor( DirectDataOperator op, EntityDescriptor entity, URI uri, Map<String, Object> cfg) { return new DataAccessor() { private static final long serialVersionUID = 1L; @Override public Optional<AttributeWriterBase> getWriter(Context context) { return Optional.of( new AbstractOnlineAttributeWriter(entity, uri) { @Override public void write(StreamElement data, CommitCallback callback) { System.out.println( String.format( "Writing entity %s to attribute %s with key %s and value of size %d", data.getEntityDescriptor(), data.getAttributeDescriptor(), data.getKey(), data.getValue().length)); callback.commit(true, null); } }); } }; } }
33.109375
93
0.656442
538de3f2787ddae1f108927be6936d3fdb1903bb
1,315
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Creation Date: Jan 22, 2015 * *******************************************************************************/ package org.oscm.apiversioning.upgrade.info; /** * @author qiu * */ public class VariableInfo { private String variableClassName; private String variableName; public VariableInfo(String variableClassName, String variableName) { this.variableClassName = variableClassName; this.variableName = variableName; } public String getVariableClassName() { return variableClassName; } public void setVariableClassName(String variableClassName) { this.variableClassName = variableClassName; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } }
31.309524
131
0.425856
bb22c7e0969a43c854986d8d1bbe4d463293b6dc
772
package subway; import subway.domain.*; import subway.view.*; import java.util.Scanner; public class Application { public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); Init.initialize(); startProgram(scanner); } public static void startProgram(Scanner kbd) { View.showMainMenu(); String mainInput = InputView.inputFunction(kbd, Constants.MAIN_FUNCTIONS); goSubMenu(mainInput, kbd); } public static void goSubMenu(String input, Scanner kbd) { System.out.println(); if (input.equals(Constants.FIND_PATH)) PathManage.managePath(kbd); if (input.equalsIgnoreCase(Constants.FINISH_PROGRAM)) View.finishProgram(); } }
26.62069
82
0.656736
48057f9fdb2b747aa6ba4235151e070a8114f874
491
package cl.global.logic.exercise.utilities.exceptions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) public class FieldsErrorsTest { @Test public void fieldErrorsTest() { final FieldsErrors fieldsErrors = new FieldsErrors("exampleField", "errorFieldExample"); assertEquals(fieldsErrors, fieldsErrors); } }
27.277778
92
0.802444