hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e1497f72ffbd17ae93ec0f7237c3281a6913f74
5,007
java
Java
byte-buddy-dep/src/test/java/net/bytebuddy/agent/builder/AgentBuilderInitializationStrategyTest.java
scordio/byte-buddy
90afb6039d420a43682dbc3055765355b87eb094
[ "Apache-2.0" ]
4,962
2015-01-05T12:39:16.000Z
2022-03-31T22:33:40.000Z
byte-buddy-dep/src/test/java/net/bytebuddy/agent/builder/AgentBuilderInitializationStrategyTest.java
chefdd/byte-buddy
7a41b53d7023ae047be63c8cef2871fd5860b032
[ "Apache-2.0" ]
1,138
2015-01-15T03:55:52.000Z
2022-03-30T22:17:06.000Z
byte-buddy-dep/src/test/java/net/bytebuddy/agent/builder/AgentBuilderInitializationStrategyTest.java
chefdd/byte-buddy
7a41b53d7023ae047be63c8cef2871fd5860b032
[ "Apache-2.0" ]
704
2015-01-15T13:35:58.000Z
2022-03-29T07:28:20.000Z
43.53913
138
0.760735
8,737
package net.bytebuddy.agent.builder; import net.bytebuddy.description.annotation.AnnotationList; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.loading.ClassInjector; import net.bytebuddy.implementation.LoadedTypeInitializer; import net.bytebuddy.implementation.auxiliary.AuxiliaryType; import net.bytebuddy.test.utility.MockitoRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.mockito.Mock; import java.lang.annotation.Annotation; import java.security.ProtectionDomain; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.*; public class AgentBuilderInitializationStrategyTest { private static final byte[] QUX = new byte[]{1, 2, 3}, BAZ = new byte[]{4, 5, 6}; @Rule public TestRule mockitoRule = new MockitoRule(this); @Mock private DynamicType.Builder<?> builder; @Mock private DynamicType dynamicType; @Mock private ClassLoader classLoader; @Mock private ProtectionDomain protectionDomain; @Mock private AgentBuilder.InjectionStrategy injectionStrategy; @Test public void testNoOp() throws Exception { assertThat(AgentBuilder.Default.InitializationStrategy.NoOp.INSTANCE.dispatcher(), is((AgentBuilder.InitializationStrategy.Dispatcher) AgentBuilder.Default.InitializationStrategy.NoOp.INSTANCE)); } @Test public void testNoOpApplication() throws Exception { assertThat(AgentBuilder.Default.InitializationStrategy.NoOp.INSTANCE.apply(builder), is((DynamicType.Builder) builder)); } @Test public void testNoOpRegistration() throws Exception { AgentBuilder.Default.InitializationStrategy.NoOp.INSTANCE.register(dynamicType, classLoader, protectionDomain, injectionStrategy); verifyZeroInteractions(dynamicType); verifyZeroInteractions(classLoader); verifyZeroInteractions(injectionStrategy); } @Test public void testPremature() throws Exception { assertThat(AgentBuilder.InitializationStrategy.Minimal.INSTANCE.dispatcher(), is((AgentBuilder.InitializationStrategy.Dispatcher) AgentBuilder.InitializationStrategy.Minimal.INSTANCE)); } @Test public void testPrematureApplication() throws Exception { assertThat(AgentBuilder.InitializationStrategy.Minimal.INSTANCE.apply(builder), is((DynamicType.Builder) builder)); } @Test @SuppressWarnings("unchecked") public void testMinimalRegistrationIndependentType() throws Exception { Annotation eagerAnnotation = mock(AuxiliaryType.SignatureRelevant.class); when(eagerAnnotation.annotationType()).thenReturn((Class) AuxiliaryType.SignatureRelevant.class); TypeDescription independent = mock(TypeDescription.class), dependent = mock(TypeDescription.class); when(independent.getDeclaredAnnotations()).thenReturn(new AnnotationList.ForLoadedAnnotations(eagerAnnotation)); when(dependent.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty()); Map<TypeDescription, byte[]> map = new HashMap<TypeDescription, byte[]>(); map.put(independent, QUX); map.put(dependent, BAZ); when(dynamicType.getAuxiliaryTypes()).thenReturn(map); ClassInjector classInjector = mock(ClassInjector.class); when(injectionStrategy.resolve(classLoader, protectionDomain)).thenReturn(classInjector); when(classInjector.inject(Collections.singletonMap(independent, QUX))) .thenReturn(Collections.<TypeDescription, Class<?>>singletonMap(independent, Foo.class)); LoadedTypeInitializer loadedTypeInitializer = mock(LoadedTypeInitializer.class); when(dynamicType.getLoadedTypeInitializers()).thenReturn(Collections.singletonMap(independent, loadedTypeInitializer)); AgentBuilder.InitializationStrategy.Minimal.INSTANCE.register(dynamicType, classLoader, protectionDomain, injectionStrategy); verify(classInjector).inject(Collections.singletonMap(independent, QUX)); verifyNoMoreInteractions(classInjector); verify(loadedTypeInitializer).onLoad(Foo.class); verifyNoMoreInteractions(loadedTypeInitializer); } @Test public void testMinimalRegistrationDependentType() throws Exception { TypeDescription dependent = mock(TypeDescription.class); when(dependent.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty()); when(dynamicType.getAuxiliaryTypes()).thenReturn(Collections.singletonMap(dependent, BAZ)); AgentBuilder.InitializationStrategy.Minimal.INSTANCE.register(dynamicType, classLoader, protectionDomain, injectionStrategy); verifyZeroInteractions(injectionStrategy); } private static class Foo { /* empty */ } }
3e149823f2a270d3ceb8bebd28d8f0bf39dd4e3f
3,406
java
Java
file-toolkit-service-starter/src/main/java/io/github/nichetoolkit/file/service/impl/FileChunkServiceImpl.java
NicheToolkit/file-toolkit
2a276955f3eddcd18aacb2780ee409678392e643
[ "Apache-2.0" ]
null
null
null
file-toolkit-service-starter/src/main/java/io/github/nichetoolkit/file/service/impl/FileChunkServiceImpl.java
NicheToolkit/file-toolkit
2a276955f3eddcd18aacb2780ee409678392e643
[ "Apache-2.0" ]
null
null
null
file-toolkit-service-starter/src/main/java/io/github/nichetoolkit/file/service/impl/FileChunkServiceImpl.java
NicheToolkit/file-toolkit
2a276955f3eddcd18aacb2780ee409678392e643
[ "Apache-2.0" ]
null
null
null
36.666667
125
0.707918
8,738
package io.github.nichetoolkit.file.service.impl; import io.github.nichetoolkit.file.entity.FileChunkEntity; import io.github.nichetoolkit.file.filter.FileFilter; import io.github.nichetoolkit.file.mapper.FileChunkMapper; import io.github.nichetoolkit.file.model.FileChunk; import io.github.nichetoolkit.file.service.FileChunkService; import io.github.nichetoolkit.rest.RestException; import io.github.nichetoolkit.rest.util.GeneralUtils; import io.github.nichetoolkit.rice.RiceIdService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.Collections; import java.util.List; /** * <p>FileChunkServiceImpl</p> * @author Cyan (hzdkv@example.com) * @version v1.0.0 */ @Slf4j @Service public class FileChunkServiceImpl extends RiceIdService<FileChunk, FileChunkEntity, FileFilter> implements FileChunkService { @Override public FileChunk queryByFileIdAndChunkIndex(String fileId, Integer chunkIndex) throws RestException { if (GeneralUtils.isEmpty(fileId) || GeneralUtils.isEmpty(chunkIndex)) { return null; } FileChunkEntity entity = ((FileChunkMapper) supperMapper).findByFileIdAndChunkIndex(fileId,chunkIndex); if (GeneralUtils.isNotEmpty(entity)) { return modelActuator(entity); } return null; } @Override public FileChunk queryByFileIdFirstChunk(String fileId) throws RestException { if (GeneralUtils.isEmpty(fileId)) { return null; } FileChunkEntity entity = ((FileChunkMapper) supperMapper).findByFileIdFirstChunk(fileId); if (GeneralUtils.isNotEmpty(entity)) { return modelActuator(entity); } return null; } @Override public FileChunk queryByFileIdLastChunk(String fileId) throws RestException { if (GeneralUtils.isEmpty(fileId)) { return null; } FileChunkEntity entity = ((FileChunkMapper) supperMapper).findByFileIdLastChunk(fileId); if (GeneralUtils.isNotEmpty(entity)) { return modelActuator(entity); } return null; } @Override public List<FileChunk> queryAllByFileId(String fileId) throws RestException { if (GeneralUtils.isEmpty(fileId)) { return Collections.emptyList(); } List<FileChunkEntity> entityList = ((FileChunkMapper) supperMapper).findAllByFileId(fileId); log.debug("file chunk list has querying successful! size: {}", entityList.size()); return modelActuator(entityList); } @Override public List<FileChunk> queryAllByFileIds(Collection<String> fileIds) throws RestException { if (GeneralUtils.isEmpty(fileIds)) { return Collections.emptyList(); } List<FileChunkEntity> entityList = ((FileChunkMapper) supperMapper).findAllByFileIds(fileIds); log.debug("file chunk list has querying successful! size: {}", entityList.size()); return modelActuator(entityList); } @Override public String queryWhereSql(FileFilter filter) throws RestException { return filter.toFileChunkSql().toTimeSql("chunk_time").toOperateSql().toIdSql().addSorts("chunk_time").toSql(); } @Override public String deleteWhereSql(FileFilter filter) throws RestException { return filter.toIdSql().toSql(); } }
3e149851fee2b63db44d7396e4ac2e12c20224a0
1,334
java
Java
java/InterviewPreparation/src/main/java/othon/org/leetcode/PascalTriangle_Kth_row.java
othonreyes/code_problems
6e65b26120b0b9d6e5ac7342a4d964696b7bd5bf
[ "MIT" ]
null
null
null
java/InterviewPreparation/src/main/java/othon/org/leetcode/PascalTriangle_Kth_row.java
othonreyes/code_problems
6e65b26120b0b9d6e5ac7342a4d964696b7bd5bf
[ "MIT" ]
null
null
null
java/InterviewPreparation/src/main/java/othon/org/leetcode/PascalTriangle_Kth_row.java
othonreyes/code_problems
6e65b26120b0b9d6e5ac7342a4d964696b7bd5bf
[ "MIT" ]
null
null
null
27.791667
73
0.490255
8,739
package othon.org.leetcode; import java.util.ArrayList; import java.util.List; public class PascalTriangle_Kth_row { public static void main(String[] args) { Solution s = new Solution(); List<Integer> r = s.getRow(1); r = s.getRow(2); r = s.getRow(3); System.out.println(r); } static class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> result = new ArrayList<>(rowIndex + 1); result.add(1); getRow2(rowIndex, result); return result; } /** * Pascal solution using a top-down approach and memoization * @param rowIndex * @param result * @return */ Integer getRow2(int rowIndex, List<Integer> result) { if (rowIndex == 0) { return 1; } if (rowIndex < 0) { return 0; } if (rowIndex<result.size() && result.get(rowIndex) != null) { return result.get(rowIndex); } for (int i = 1; i < rowIndex; i++) { int pt = getRow2(i-1, result) + getRow2(i, result); result.set(i, pt); } result.add(1); return result.get(rowIndex); } } }
3e149864400dd4f0fc8361e3de4cb9a06a3da0e0
708
java
Java
plot/src/main/java/com/adefruandta/plot/binder/IntegerBinder.java
teslacode/plot
a15fdbacf9d271be24082d53d94dc50545ea5931
[ "Apache-2.0" ]
1
2019-06-16T07:23:17.000Z
2019-06-16T07:23:17.000Z
plot/src/main/java/com/adefruandta/plot/binder/IntegerBinder.java
adef145/PlotAndroid
a15fdbacf9d271be24082d53d94dc50545ea5931
[ "Apache-2.0" ]
2
2016-08-22T09:02:57.000Z
2016-08-24T10:43:29.000Z
plot/src/main/java/com/adefruandta/plot/binder/IntegerBinder.java
adef145/PlotAndroid
a15fdbacf9d271be24082d53d94dc50545ea5931
[ "Apache-2.0" ]
1
2016-08-25T06:08:06.000Z
2016-08-25T06:08:06.000Z
24.413793
99
0.69774
8,740
package com.adefruandta.plot.binder; import android.os.Bundle; import java.lang.reflect.Field; public class IntegerBinder implements TypeBinder<Integer> { @Override public void setBundle(Bundle bundle, String key, Integer value) { bundle.putInt(key, value); } @Override public Integer getBundle(Bundle bundle, String key) { return bundle.getInt(key); } @Override public void setField(Field field, Object target, Integer value) throws IllegalAccessException { field.set(target, value); } @Override public Integer getField(Field field, Object target) throws IllegalAccessException { return (Integer) field.get(target); } }
3e149a0f6d343f841239e6d73a9d9c2b9d5b6e92
549
java
Java
minimalism/minimalism-android/src/com/kompetensum/minimalism/MainActivity.java
hypp/ld26
f79e05047430691cfbc2b6ffaf4a91f8a05c92ba
[ "MIT" ]
null
null
null
minimalism/minimalism-android/src/com/kompetensum/minimalism/MainActivity.java
hypp/ld26
f79e05047430691cfbc2b6ffaf4a91f8a05c92ba
[ "MIT" ]
null
null
null
minimalism/minimalism-android/src/com/kompetensum/minimalism/MainActivity.java
hypp/ld26
f79e05047430691cfbc2b6ffaf4a91f8a05c92ba
[ "MIT" ]
null
null
null
30.5
84
0.744991
8,741
package com.kompetensum.minimalism; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; public class MainActivity extends AndroidApplication { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); cfg.useGL20 = false; initialize(new Minimalism(), cfg); } }
3e149a278cf0fa848c1d290a97202e11cc30863f
1,523
java
Java
moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/metal/enums/MTLCommandBufferError.java
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
null
null
null
moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/metal/enums/MTLCommandBufferError.java
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
null
null
null
moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/metal/enums/MTLCommandBufferError.java
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
null
null
null
40.078947
85
0.783322
8,742
/* Copyright 2014-2016 Intel Corporation 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 apple.metal.enums; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.NUInt; @Generated public final class MTLCommandBufferError { @Generated @NUInt public static final long None = 0x0000000000000000L; @Generated @NUInt public static final long Internal = 0x0000000000000001L; @Generated @NUInt public static final long Timeout = 0x0000000000000002L; @Generated @NUInt public static final long PageFault = 0x0000000000000003L; @Generated @NUInt public static final long Blacklisted = 0x0000000000000004L; @Generated @NUInt public static final long NotPermitted = 0x0000000000000007L; @Generated @NUInt public static final long OutOfMemory = 0x0000000000000008L; @Generated @NUInt public static final long InvalidResource = 0x0000000000000009L; @Generated @NUInt public static final long Memoryless = 0x000000000000000AL; @Generated private MTLCommandBufferError() { } }
3e149bb37bb000e367ddcf29d4f62ffb1a625386
2,275
java
Java
qinsql-common/src/main/java/com/facebook/presto/common/type/AbstractVariableWidthType.java
codefollower/QinSQL
d85650206b3d2d7374520d344e4745fe1847b2a5
[ "Apache-2.0" ]
9,782
2016-03-18T15:16:19.000Z
2022-03-31T07:49:41.000Z
qinsql-common/src/main/java/com/facebook/presto/common/type/AbstractVariableWidthType.java
codefollower/QinSQL
d85650206b3d2d7374520d344e4745fe1847b2a5
[ "Apache-2.0" ]
10,310
2016-03-18T01:03:00.000Z
2022-03-31T23:54:08.000Z
qinsql-common/src/main/java/com/facebook/presto/common/type/AbstractVariableWidthType.java
codefollower/QinSQL
d85650206b3d2d7374520d344e4745fe1847b2a5
[ "Apache-2.0" ]
3,803
2016-03-18T22:54:24.000Z
2022-03-31T07:49:46.000Z
38.559322
134
0.738022
8,743
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.common.type; import com.facebook.presto.common.block.BlockBuilder; import com.facebook.presto.common.block.BlockBuilderStatus; import com.facebook.presto.common.block.PageBuilderStatus; import com.facebook.presto.common.block.VariableWidthBlockBuilder; import static java.lang.Math.min; public abstract class AbstractVariableWidthType extends AbstractType implements VariableWidthType { private static final int EXPECTED_BYTES_PER_ENTRY = 32; protected AbstractVariableWidthType(TypeSignature signature, Class<?> javaType) { super(signature, javaType); } @Override public BlockBuilder createBlockBuilder(BlockBuilderStatus blockBuilderStatus, int expectedEntries, int expectedBytesPerEntry) { int maxBlockSizeInBytes; if (blockBuilderStatus == null) { maxBlockSizeInBytes = PageBuilderStatus.DEFAULT_MAX_PAGE_SIZE_IN_BYTES; } else { maxBlockSizeInBytes = blockBuilderStatus.getMaxPageSizeInBytes(); } // it is guaranteed Math.min will not overflow; safe to cast int expectedBytes = (int) min((long) expectedEntries * expectedBytesPerEntry, maxBlockSizeInBytes); return new VariableWidthBlockBuilder( blockBuilderStatus, expectedBytesPerEntry == 0 ? expectedEntries : Math.min(expectedEntries, maxBlockSizeInBytes / expectedBytesPerEntry), expectedBytes); } @Override public BlockBuilder createBlockBuilder(BlockBuilderStatus blockBuilderStatus, int expectedEntries) { return createBlockBuilder(blockBuilderStatus, expectedEntries, EXPECTED_BYTES_PER_ENTRY); } }
3e149cf83cb09637124f228ce16c2140ba079182
5,834
java
Java
plugins/j2ee/geronimo-j2ee-schema/src/main/java/org/apache/geronimo/xbeans/geronimo/naming/impl/GerGbeanLocatorTypeImpl.java
fideoman/geronimo
c78546a9c0e1007e65179da780727de8672f9289
[ "Apache-2.0" ]
null
null
null
plugins/j2ee/geronimo-j2ee-schema/src/main/java/org/apache/geronimo/xbeans/geronimo/naming/impl/GerGbeanLocatorTypeImpl.java
fideoman/geronimo
c78546a9c0e1007e65179da780727de8672f9289
[ "Apache-2.0" ]
null
null
null
plugins/j2ee/geronimo-j2ee-schema/src/main/java/org/apache/geronimo/xbeans/geronimo/naming/impl/GerGbeanLocatorTypeImpl.java
fideoman/geronimo
c78546a9c0e1007e65179da780727de8672f9289
[ "Apache-2.0" ]
null
null
null
29.917949
172
0.57902
8,744
/* * XML Type: gbean-locatorType * Namespace: http://geronimo.apache.org/xml/ns/naming-1.2 * Java type: org.apache.geronimo.xbeans.geronimo.naming.GerGbeanLocatorType * * Automatically generated - do not modify. */ package org.apache.geronimo.xbeans.geronimo.naming.impl; /** * An XML gbean-locatorType(@http://geronimo.apache.org/xml/ns/naming-1.2). * * This is a complex type. */ public class GerGbeanLocatorTypeImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements org.apache.geronimo.xbeans.geronimo.naming.GerGbeanLocatorType { private static final long serialVersionUID = 1L; public GerGbeanLocatorTypeImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName PATTERN$0 = new javax.xml.namespace.QName("http://geronimo.apache.org/xml/ns/naming-1.2", "pattern"); private static final javax.xml.namespace.QName GBEANLINK$2 = new javax.xml.namespace.QName("http://geronimo.apache.org/xml/ns/naming-1.2", "gbean-link"); /** * Gets the "pattern" element */ public org.apache.geronimo.xbeans.geronimo.naming.GerPatternType getPattern() { synchronized (monitor()) { check_orphaned(); org.apache.geronimo.xbeans.geronimo.naming.GerPatternType target = null; target = (org.apache.geronimo.xbeans.geronimo.naming.GerPatternType)get_store().find_element_user(PATTERN$0, 0); if (target == null) { return null; } return target; } } /** * True if has "pattern" element */ public boolean isSetPattern() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(PATTERN$0) != 0; } } /** * Sets the "pattern" element */ public void setPattern(org.apache.geronimo.xbeans.geronimo.naming.GerPatternType pattern) { synchronized (monitor()) { check_orphaned(); org.apache.geronimo.xbeans.geronimo.naming.GerPatternType target = null; target = (org.apache.geronimo.xbeans.geronimo.naming.GerPatternType)get_store().find_element_user(PATTERN$0, 0); if (target == null) { target = (org.apache.geronimo.xbeans.geronimo.naming.GerPatternType)get_store().add_element_user(PATTERN$0); } target.set(pattern); } } /** * Appends and returns a new empty "pattern" element */ public org.apache.geronimo.xbeans.geronimo.naming.GerPatternType addNewPattern() { synchronized (monitor()) { check_orphaned(); org.apache.geronimo.xbeans.geronimo.naming.GerPatternType target = null; target = (org.apache.geronimo.xbeans.geronimo.naming.GerPatternType)get_store().add_element_user(PATTERN$0); return target; } } /** * Unsets the "pattern" element */ public void unsetPattern() { synchronized (monitor()) { check_orphaned(); get_store().remove_element(PATTERN$0, 0); } } /** * Gets the "gbean-link" element */ public java.lang.String getGbeanLink() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(GBEANLINK$2, 0); if (target == null) { return null; } return target.getStringValue(); } } /** * Gets (as xml) the "gbean-link" element */ public org.apache.xmlbeans.XmlString xgetGbeanLink() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlString target = null; target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(GBEANLINK$2, 0); return target; } } /** * True if has "gbean-link" element */ public boolean isSetGbeanLink() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(GBEANLINK$2) != 0; } } /** * Sets the "gbean-link" element */ public void setGbeanLink(java.lang.String gbeanLink) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(GBEANLINK$2, 0); if (target == null) { target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(GBEANLINK$2); } target.setStringValue(gbeanLink); } } /** * Sets (as xml) the "gbean-link" element */ public void xsetGbeanLink(org.apache.xmlbeans.XmlString gbeanLink) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlString target = null; target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(GBEANLINK$2, 0); if (target == null) { target = (org.apache.xmlbeans.XmlString)get_store().add_element_user(GBEANLINK$2); } target.set(gbeanLink); } } /** * Unsets the "gbean-link" element */ public void unsetGbeanLink() { synchronized (monitor()) { check_orphaned(); get_store().remove_element(GBEANLINK$2, 0); } } }
3e149e1f279a157e5712012dd9b329756e20b420
1,989
java
Java
java-8/src/main/java/com/challenge/desafio/CalculadorDeClasses.java
rlsanlo/AcceleraDev-Java
d95ea116a308435ae0d7c70e7075cffdb9f89601
[ "MIT" ]
null
null
null
java-8/src/main/java/com/challenge/desafio/CalculadorDeClasses.java
rlsanlo/AcceleraDev-Java
d95ea116a308435ae0d7c70e7075cffdb9f89601
[ "MIT" ]
null
null
null
java-8/src/main/java/com/challenge/desafio/CalculadorDeClasses.java
rlsanlo/AcceleraDev-Java
d95ea116a308435ae0d7c70e7075cffdb9f89601
[ "MIT" ]
null
null
null
36.163636
182
0.632981
8,745
package com.challenge.desafio; import com.challenge.annotation.Somar; import com.challenge.annotation.Subtrair; import com.challenge.interfaces.Calculavel; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; public class CalculadorDeClasses implements Calculavel { @Override public BigDecimal somar(Object object) { return somaValoresDaAnnotation(object, Somar.class); } @Override public BigDecimal subtrair(Object object) { return somaValoresDaAnnotation(object, Subtrair.class); } @Override public BigDecimal totalizar(Object object) { return this.somar(object).subtract(this.subtrair(object)); } private BigDecimal somaValoresDaAnnotation(Object classe, Class<? extends Annotation> annotationClass) { BigDecimal soma = BigDecimal.ZERO; BigDecimal value = BigDecimal.ZERO; for (Field atributo: classe.getClass().getDeclaredFields()) { if(atributo.isAnnotationPresent(annotationClass)) { try { Method m = classe.getClass().getMethod(("get" + atributo.getName().substring(0, 1).toUpperCase() + atributo.getName().substring(1, atributo.getName().length()))); value = (BigDecimal) m.invoke(classe); } catch (IllegalArgumentException e) { return BigDecimal.ZERO; } catch (NoSuchMethodException e) { return BigDecimal.ZERO; } catch (SecurityException e) { return BigDecimal.ZERO; } catch (IllegalAccessException e) { return BigDecimal.ZERO; } catch (InvocationTargetException e) { return BigDecimal.ZERO; } soma = soma.add(value); } } return soma; } }
3e149f070ddad36516cd670c244ad17ee8b0fb30
2,174
java
Java
src/main/java/gui/pages/AlgorithmParametersComponent.java
kikimickey/rec
42944eb35d0844a73ee9e17ad41ff679275dcf66
[ "MIT" ]
2
2017-02-05T08:19:42.000Z
2020-05-31T13:00:52.000Z
src/main/java/gui/pages/AlgorithmParametersComponent.java
kikimickey/rec
42944eb35d0844a73ee9e17ad41ff679275dcf66
[ "MIT" ]
1
2019-09-03T11:17:27.000Z
2019-09-03T11:17:27.000Z
src/main/java/gui/pages/AlgorithmParametersComponent.java
kikimickey/rec
42944eb35d0844a73ee9e17ad41ff679275dcf66
[ "MIT" ]
4
2018-12-23T16:33:53.000Z
2020-11-15T17:46:50.000Z
24.426966
90
0.692272
8,746
package gui.pages; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import gui.model.ConfigData; import javafx.beans.property.SimpleStringProperty; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; /** * @author FBM * */ public class AlgorithmParametersComponent { private GridPane grid; private final int id; private Map<String,TextField> parametersMap; /** * @param id * */ public AlgorithmParametersComponent(int id) { this.id = id; grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); parametersMap= new HashMap<>(); } /** * @param map */ public void setParameters(final Map<String, Map<String, String>> map) { int i = 0; this.grid.getChildren().clear(); this.parametersMap.clear(); for (Map<String, String> subMap : map.values()) { for (Entry<String, String> entity : subMap.entrySet()) { final String value = entity.getValue(); final Label parameterName = new Label(value); final TextField parameterValue = new TextField(); grid.add(parameterName, 0, i); grid.add(parameterValue, 1, i); i++; final String key = "ALGORITHM_" + id + "_" + entity.getKey(); ConfigData.instance.ALGORITHM_PARAMETERS.put(key, new SimpleStringProperty("")); ConfigData.instance.ALGORITHM_PARAMETERS.get(key).bind(parameterValue.textProperty()); this.parametersMap.put(value,parameterValue); } } } public Parent getLayout() { return grid; } /** * @return */ public String validate() { final StringBuilder totalError = new StringBuilder(); for(Entry<String, TextField> entry:this.parametersMap.entrySet()){ try{ Double.parseDouble(entry.getValue().getText()); }catch(final Exception exception){ totalError.append("The value of \""+entry.getKey()+"\" is not valid").append("\n"); } } return totalError.toString(); } /** * */ public void fillWithSampleData() { for(Entry<String, TextField> entry:parametersMap.entrySet()){ entry.getValue().setText("10"); } } }
3e149fef559c45056a250bcba29f1a0aa12d5921
4,003
java
Java
src/main/java/org/d2ab/collection/ReverseList.java
danielaborg/sequence
b88248bfc5848dfaba6b17f83f82af96b0c1c6c8
[ "Apache-2.0" ]
null
null
null
src/main/java/org/d2ab/collection/ReverseList.java
danielaborg/sequence
b88248bfc5848dfaba6b17f83f82af96b0c1c6c8
[ "Apache-2.0" ]
null
null
null
src/main/java/org/d2ab/collection/ReverseList.java
danielaborg/sequence
b88248bfc5848dfaba6b17f83f82af96b0c1c6c8
[ "Apache-2.0" ]
null
null
null
21.994505
101
0.674244
8,747
/* * Copyright 2016 Daniel Skogquist Åborg * * 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.d2ab.collection; import java.util.*; /** * A {@link List} that presents a reverse view over a backing {@link List}. */ public class ReverseList<T> extends AbstractList<T> implements SizedIterable<T> { private final List<T> original; private final SizeType sizeType; public static <T> List<T> from(List<T> original) { return new ReverseList<>(original); } private ReverseList(List<T> original) { this.original = original; this.sizeType = Iterables.sizeType(original); } @Override public int size() { return original.size(); } @Override public SizeType sizeType() { return sizeType; } @Override public boolean isEmpty() { return original.isEmpty(); } @Override public boolean contains(Object o) { return original.contains(o); } @Override public Iterator<T> iterator() { return listIterator(); } @Override public boolean addAll(Collection<? extends T> c) { return addAll(size(), c); } @Override public boolean addAll(int index, Collection<? extends T> c) { int start = original.size() - index; boolean modified = original.addAll(start, c); for (int i = 0, size = c.size(); i < size / 2; i++) swap(start + i, start + size - i - 1); return modified; } private void swap(int i, int j) { T temp = original.get(i); original.set(i, original.get(j)); original.set(j, temp); } @Override public void sort(Comparator<? super T> c) { original.sort(c); Collections.reverse(original); } @Override public void clear() { original.clear(); } @Override public T get(int index) { return original.get(original.size() - index - 1); } @Override public T set(int index, T element) { return original.set(original.size() - index - 1, element); } @Override public void add(int index, T element) { original.add(original.size() - index, element); } @Override public T remove(int index) { return original.remove(original.size() - index - 1); } @Override public int indexOf(Object o) { int lastIndexOf = original.lastIndexOf(o); return lastIndexOf == -1 ? -1 : original.size() - 1 - lastIndexOf; } @Override public int lastIndexOf(Object o) { int indexOf = original.indexOf(o); return indexOf == -1 ? -1 : original.size() - 1 - indexOf; } @Override public ListIterator<T> listIterator(int index) { ListIterator<T> listIterator = original.listIterator(original.size() - index); return new ListIterator<T>() { @Override public boolean hasNext() { return listIterator.hasPrevious(); } @Override public T next() { return listIterator.previous(); } @Override public boolean hasPrevious() { return listIterator.hasNext(); } @Override public T previous() { return listIterator.next(); } @Override public int nextIndex() { return original.size() - listIterator.previousIndex() - 1; } @Override public int previousIndex() { return original.size() - listIterator.nextIndex() - 1; } @Override public void remove() { listIterator.remove(); } @Override public void set(T o) { listIterator.set(o); } @Override public void add(T o) { listIterator.add(o); listIterator.previous(); } }; } @Override public List<T> subList(int fromIndex, int toIndex) { return new ReverseList<>(original.subList(original.size() - toIndex, original.size() - fromIndex)); } }
3e14a09b58c17c701d41ea6ff10d414d813190ba
1,210
java
Java
mapping-context/src/main/java/com/garethahealy/mapstructpoc/mappingcontext/processors/BeerToLagerProcessor.java
garethahealy/mapstruct-poc
43b12ccd8a2a7a5113dfcb00a3bf760950095b5c
[ "Apache-2.0" ]
null
null
null
mapping-context/src/main/java/com/garethahealy/mapstructpoc/mappingcontext/processors/BeerToLagerProcessor.java
garethahealy/mapstruct-poc
43b12ccd8a2a7a5113dfcb00a3bf760950095b5c
[ "Apache-2.0" ]
null
null
null
mapping-context/src/main/java/com/garethahealy/mapstructpoc/mappingcontext/processors/BeerToLagerProcessor.java
garethahealy/mapstruct-poc
43b12ccd8a2a7a5113dfcb00a3bf760950095b5c
[ "Apache-2.0" ]
null
null
null
34.571429
117
0.75124
8,748
/*- * #%L * GarethHealy :: MapStruct PoC :: Mapping Context * %% * Copyright (C) 2013 - 2017 Gareth Healy * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.garethahealy.mapstructpoc.mappingcontext.processors; import com.garethahealy.mapstructpoc.mappingmodel.BeerMapper; import com.garethahealy.mapstructpoc.mappingmodel.entities.Lager; import org.apache.camel.Exchange; import org.apache.camel.Processor; public class BeerToLagerProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setBody(BeerMapper.INSTANCE.largerToBitter(exchange.getIn().getMandatoryBody(Lager.class))); } }
3e14a1f9d163d1fcc2e3c8668ca8ac98d938a07b
301
java
Java
order/src/main/java/com/eric/order/config/RestConfig.java
feiyongjing/spring-cloud-alibaba-template
2e2277ce945ffc28e38558fc5c38deab8fe8bbc8
[ "Apache-2.0" ]
null
null
null
order/src/main/java/com/eric/order/config/RestConfig.java
feiyongjing/spring-cloud-alibaba-template
2e2277ce945ffc28e38558fc5c38deab8fe8bbc8
[ "Apache-2.0" ]
null
null
null
order/src/main/java/com/eric/order/config/RestConfig.java
feiyongjing/spring-cloud-alibaba-template
2e2277ce945ffc28e38558fc5c38deab8fe8bbc8
[ "Apache-2.0" ]
null
null
null
23.153846
69
0.727575
8,749
package com.eric.order.config; import org.springframework.context.annotation.Configuration; @Configuration public class RestConfig { // @LoadBalanced // 使用Ribbon实现负载均衡调用 // @Bean // public RestTemplate restTemplate(RestTemplateBuilder builder) { // return builder.build(); // } }
3e14a374aa3030e402d0201fe7b7a30b75d35264
1,357
java
Java
presto-tests/src/test/java/com/facebook/presto/tests/TestLocalVerboseMemoryExceededErrors.java
ahouzheng/presto
c2ac1469eea9da9c6e29c8c4d43e00b851400c8b
[ "Apache-2.0" ]
9,782
2016-03-18T15:16:19.000Z
2022-03-31T07:49:41.000Z
presto-tests/src/test/java/com/facebook/presto/tests/TestLocalVerboseMemoryExceededErrors.java
ahouzheng/presto
c2ac1469eea9da9c6e29c8c4d43e00b851400c8b
[ "Apache-2.0" ]
10,310
2016-03-18T01:03:00.000Z
2022-03-31T23:54:08.000Z
presto-tests/src/test/java/com/facebook/presto/tests/TestLocalVerboseMemoryExceededErrors.java
ahouzheng/presto
c2ac1469eea9da9c6e29c8c4d43e00b851400c8b
[ "Apache-2.0" ]
3,803
2016-03-18T22:54:24.000Z
2022-03-31T07:49:46.000Z
33.097561
90
0.72955
8,750
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.tests; import com.facebook.presto.Session; import com.facebook.presto.testing.QueryRunner; import static com.facebook.presto.SystemSessionProperties.QUERY_MAX_TOTAL_MEMORY_PER_NODE; import static com.facebook.presto.tests.TestLocalQueries.createLocalQueryRunner; public class TestLocalVerboseMemoryExceededErrors extends AbstractTestVerboseMemoryExceededErrors { @Override protected QueryRunner createQueryRunner() throws Exception { return createLocalQueryRunner(); } @Override protected Session getSession() { return Session.builder(super.getSession()) .setSchema("sf1") .setSystemProperty(QUERY_MAX_TOTAL_MEMORY_PER_NODE, "50MB") .build(); } }
3e14a512db8fa5d3523c0c4baa396985c14bd000
380
java
Java
openfoodfacts/src/main/java/pl/coderion/openfoodfacts/openfoodfactsjavawrapper/model/SelectedImageItem.java
coderion/openfoodfacts-java-wrapper
1378f872ad0259380f7778a85d297e3e4d222ee5
[ "MIT" ]
null
null
null
openfoodfacts/src/main/java/pl/coderion/openfoodfacts/openfoodfactsjavawrapper/model/SelectedImageItem.java
coderion/openfoodfacts-java-wrapper
1378f872ad0259380f7778a85d297e3e4d222ee5
[ "MIT" ]
1
2020-12-07T09:25:40.000Z
2021-06-10T15:52:34.000Z
openfoodfacts/src/main/java/pl/coderion/openfoodfacts/openfoodfactsjavawrapper/model/SelectedImageItem.java
coderion/openfoodfacts-java-wrapper
1378f872ad0259380f7778a85d297e3e4d222ee5
[ "MIT" ]
null
null
null
17.272727
65
0.7
8,751
package pl.coderion.openfoodfacts.openfoodfactsjavawrapper.model; import lombok.Data; import org.apache.commons.lang3.ObjectUtils; /** * Copyright (C) Coderion sp. z o.o. */ @Data public class SelectedImageItem { private String en; private String fr; private String pl; public String getUrl() { return ObjectUtils.firstNonNull(en, fr, pl); } }
3e14a53f04581134dbeccad1de50dfa1ea11eaf6
1,425
java
Java
rxandroidble/src/main/java/com/polidea/rxandroidble/internal/scan/ScanPreconditionsVerifierApi18.java
huangweicai/RxAndroidBle
d2a603290cba0cc014171cfb6439922ed18148b1
[ "Apache-2.0" ]
null
null
null
rxandroidble/src/main/java/com/polidea/rxandroidble/internal/scan/ScanPreconditionsVerifierApi18.java
huangweicai/RxAndroidBle
d2a603290cba0cc014171cfb6439922ed18148b1
[ "Apache-2.0" ]
null
null
null
rxandroidble/src/main/java/com/polidea/rxandroidble/internal/scan/ScanPreconditionsVerifierApi18.java
huangweicai/RxAndroidBle
d2a603290cba0cc014171cfb6439922ed18148b1
[ "Apache-2.0" ]
null
null
null
40.714286
131
0.777544
8,752
package com.polidea.rxandroidble.internal.scan; import com.polidea.rxandroidble.exceptions.BleScanException; import com.polidea.rxandroidble.internal.util.LocationServicesStatus; import com.polidea.rxandroidble.internal.util.RxBleAdapterWrapper; import javax.inject.Inject; @SuppressWarnings("WeakerAccess") public class ScanPreconditionsVerifierApi18 implements ScanPreconditionsVerifier { final RxBleAdapterWrapper rxBleAdapterWrapper; final LocationServicesStatus locationServicesStatus; @Inject public ScanPreconditionsVerifierApi18(RxBleAdapterWrapper rxBleAdapterWrapper, LocationServicesStatus locationServicesStatus) { this.rxBleAdapterWrapper = rxBleAdapterWrapper; this.locationServicesStatus = locationServicesStatus; } @Override public void verify() { if (!rxBleAdapterWrapper.hasBluetoothAdapter()) { throw new BleScanException(BleScanException.BLUETOOTH_NOT_AVAILABLE); } else if (!rxBleAdapterWrapper.isBluetoothEnabled()) { throw new BleScanException(BleScanException.BLUETOOTH_DISABLED); } else if (!locationServicesStatus.isLocationPermissionOk()) { throw new BleScanException(BleScanException.LOCATION_PERMISSION_MISSING); } else if (!locationServicesStatus.isLocationProviderOk()) { throw new BleScanException(BleScanException.LOCATION_SERVICES_DISABLED); } } }
3e14a6af8571e285384f67b3bb2c83d0ae1c0d90
10,355
java
Java
examples/petri/ReachabilityGraph.java
cjljohnson/jgraphx
5205d9a7f01e2f3281416a0868683dd97715b6f5
[ "BSD-3-Clause" ]
null
null
null
examples/petri/ReachabilityGraph.java
cjljohnson/jgraphx
5205d9a7f01e2f3281416a0868683dd97715b6f5
[ "BSD-3-Clause" ]
null
null
null
examples/petri/ReachabilityGraph.java
cjljohnson/jgraphx
5205d9a7f01e2f3281416a0868683dd97715b6f5
[ "BSD-3-Clause" ]
null
null
null
32.258567
115
0.623757
8,753
package petri; import java.awt.GridLayout; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.TreeMap; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import org.w3c.dom.Element; import com.mxgraph.model.mxCell; import com.mxgraph.model.mxGraphModel; import com.mxgraph.util.mxConstants; import com.mxgraph.view.mxGraph; import com.mxgraph.view.mxStylesheet; public class ReachabilityGraph extends mxGraph{ private Map<Map<String, Integer>, mxCell> nodeMap; private int size; private PetriGraph graph; int i; private Set<Object> liveSet; private boolean isComplete; private Map<String, Integer> boundedness; public ReachabilityGraph(PetriGraph graph, int size) { nodeMap = new HashMap<Map<String, Integer>, mxCell>(); this.size = size; this.graph = graph; liveSet = new HashSet<Object>(); isComplete = false; boundedness = new TreeMap<String, Integer>(); initStyles(); setCellsEditable(false); calcReachability(); showLive(); showBounded(); } public void showLive() { String message = "The following transitions are live:\n"; for (Object vertex : liveSet) { message += " t" + graph.getCellMarkingName(vertex); } message += "\nThe following transitions are dead:\n"; for (Object vertex : graph.getChildVertices(graph.getDefaultParent())) { if (vertex instanceof mxCell) { Object value = ((mxCell) vertex).getValue(); if (value instanceof Element) { Element elt = (Element) value; if (elt.getTagName().equalsIgnoreCase("transition") && !liveSet.contains(vertex)) { message += " t" + graph.getCellMarkingName(vertex); } } } } if (!isComplete) { message += "\nNOTE: Reachability graph was terminated after " + i + " markings were assessed. Some dead markings may be live."; } JOptionPane.showMessageDialog(null, message); } public void showBounded() { String message = "Boundedness for all places:\n"; for (Map<String, Integer> map : nodeMap.keySet()) { for (String id : map.keySet()) { int val = map.get(id); boundedness.put(id, Math.max(boundedness.getOrDefault(id, 0), val)); } } for (String id : boundedness.keySet()) { message += " p" + graph.getCellMarkingName(((mxGraphModel)graph.getModel()).getCell(id)) + ": " + boundedness.get(id) + "\n"; } if (!isComplete) { message += "\nNOTE: Reachability graph was terminated after " + i + " markings were assessed. Values given are only a lower bound."; } JOptionPane.showMessageDialog(null, message); } public boolean isCellSelectable(Object cell) { if (getModel().isEdge(cell)) { //return false; } return super.isCellSelectable(cell); } public void calcReachability() { Queue<Map<String, Integer>> queue = new ArrayDeque<Map<String, Integer>>(); i = 0; Map<String, Integer> s1 = graph.getPlaceTokens(); queue.add(s1); try { getModel().beginUpdate(); mxCell node = (mxCell)insertVertex(getDefaultParent(), null, s1, i * 50, i * 50, 40, 40, "NODE"); nodeMap.put(s1, node); while (queue.size() > 0 && i < size) { calcNodeReachability(queue.poll(), queue); i++; } graph.setPlaceTokens(s1); setCellStyle(node.getStyle() + ";CURRENT", new Object[] {node}); } finally { getModel().endUpdate(); } if (queue.isEmpty()) { isComplete = true; } } private void calcNodeReachability(Map<String, Integer> state, Queue<Map<String, Integer>> queue) { graph.setPlaceTokens(state); mxCell node1 = nodeMap.get(state); int j = 0; for (Object vertex : graph.getChildVertices(graph.getDefaultParent())) { if (vertex instanceof mxCell) { Object value = ((mxCell) vertex).getValue(); if (value instanceof Element) { Element elt = (Element) value; if (elt.getTagName().equalsIgnoreCase("transition") && graph.isFirable(vertex)) { graph.fireTransition(vertex); Map<String, Integer> newState = graph.getPlaceTokens(); mxCell node = nodeMap.get(newState); if (node == null) { node = (mxCell)insertVertex(getDefaultParent(), null, newState, i * 50, j * 50, 40, 40, "NODE"); nodeMap.put(newState, node); queue.add(newState); } Object[] edges = graph.getEdgesBetween(node1, node, true); if (edges.length > 0) { //System.out.println(Arrays.toString(edges)); mxCell edge = (mxCell) edges[0]; String label = (String) edge.getValue(); label += ", t" + graph.getCellMarkingName(vertex); edge.setValue(label); } else { insertEdge(getDefaultParent(), null, "t" + graph.getCellMarkingName(vertex), node1, node, null); } graph.setPlaceTokens(state); j++; // Add to liveSet liveSet.add(vertex); } } } } setCellStyle(node1.getStyle() + ";COMPLETE", new Object[] {node1}); } private void initStyles() { mxStylesheet stylesheet = getStylesheet(); Hashtable<String, Object> nodeStyle = new Hashtable<String, Object>(); nodeStyle.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); nodeStyle.put(mxConstants.STYLE_OPACITY, 100); nodeStyle.put(mxConstants.STYLE_FONTCOLOR, "#000000"); nodeStyle.put(mxConstants.STYLE_FILLCOLOR, "#FFFFFF"); nodeStyle.put(mxConstants.STYLE_STROKECOLOR, "#FF0000"); nodeStyle.put(mxConstants.STYLE_STROKEWIDTH, 2); //nodeStyle.put(mxConstants.STYLE_NOLABEL, true); stylesheet.putCellStyle("NODE", nodeStyle); Hashtable<String, Object> completeStyle = new Hashtable<String, Object>(); completeStyle.put(mxConstants.STYLE_STROKECOLOR, "#000000"); stylesheet.putCellStyle("COMPLETE", completeStyle); Hashtable<String, Object> currentStyle = new Hashtable<String, Object>(); currentStyle.put(mxConstants.STYLE_FILLCOLOR, "#00FF00"); stylesheet.putCellStyle("CURRENT", currentStyle); Map<String, Object> edge = new HashMap<String, Object>(); edge.put(mxConstants.STYLE_ROUNDED, true); edge.put(mxConstants.STYLE_ORTHOGONAL, false); edge.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_CONNECTOR); edge.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_CLASSIC); edge.put(mxConstants.STYLE_VERTICAL_ALIGN, mxConstants.ALIGN_BOTTOM); edge.put(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_LEFT); edge.put(mxConstants.STYLE_STROKECOLOR, "#000000"); edge.put(mxConstants.STYLE_STROKEWIDTH, 2); edge.put(mxConstants.STYLE_FONTCOLOR, "#000000"); edge.put(mxConstants.STYLE_EDGE, "PETRI_STYLE"); getStylesheet().setDefaultEdgeStyle(edge); } public void setActiveState(Object obj) { if (obj instanceof mxCell) { mxCell vertex = (mxCell)obj; if (vertex.getValue() instanceof Map<?,?>) { Map<String, Integer> currentState = graph.getPlaceTokens(); mxCell currentCell = nodeMap.get(currentState); String style = currentCell.getStyle().replaceFirst(";CURRENT", ""); setCellStyle(style, new Object[] {currentCell}); setCellStyle(vertex.getStyle() + ";CURRENT", new Object[] {vertex}); Map<String, Integer> state = (Map<String, Integer>)vertex.getValue(); graph.setPlaceTokens(state); graph.checkEnabledTransitions(); graph.refresh(); } } } @Override public String convertValueToString(Object cell) { if (cell instanceof mxCell) { Object value = ((mxCell) cell).getValue(); if (value instanceof Map<?,?>) { Map<String, Integer> map = (Map<String, Integer>)value; StringBuilder sb = new StringBuilder(); for (String id : map.keySet()) { Object vertex = ((mxGraphModel)graph.getModel()).getCell(id); sb.append('p'); sb.append(graph.getCellMarkingName(vertex)); sb.append(": "); sb.append(map.get(id)); sb.append('\n'); } return sb.toString(); } } return super.convertValueToString(cell); } public void findNodes() { Map<String, Integer> key = (Map<String, Integer>) nodeMap.keySet().toArray()[0]; JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); List<JTextField> values = new ArrayList<JTextField>(); mxGraphModel model = (mxGraphModel) graph.getModel(); panel.add(new JLabel("Define marking:")); for (String id : key.keySet()) { System.out.println(id); JTextField valField = new JTextField(5); JPanel panel2 = new JPanel(); panel2.add(new JLabel("p" + graph.getCellMarkingName(model.getCell(id)) + ": ")); panel2.add(valField); panel.add(panel2); values.add(valField); } int result = JOptionPane.showConfirmDialog(null, panel, "Find Marking", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { Map<String, Integer> goal = new TreeMap<String, Integer>(); Iterator<JTextField> iter = values.iterator(); for (String id : key.keySet()) { try { int n = Integer.parseInt(iter.next().getText()); goal.put(id, n); } catch (Exception e) { } } if (nodeMap.containsKey(goal)) { setSelectionCell(nodeMap.get(goal)); } else { JOptionPane.showMessageDialog(null, "Marking not in reachability graph."); } } } }
3e14a78bb3553564a7f850ad2599ade395f4a257
3,560
java
Java
common/src/com/thoughtworks/go/domain/materials/tfs/Changeset.java
saschaglo/gocd
fb9075d3155d82d481ba062ead6fe36262c7785c
[ "Apache-2.0" ]
null
null
null
common/src/com/thoughtworks/go/domain/materials/tfs/Changeset.java
saschaglo/gocd
fb9075d3155d82d481ba062ead6fe36262c7785c
[ "Apache-2.0" ]
4
2021-05-18T20:51:22.000Z
2022-02-01T01:04:46.000Z
common/src/com/thoughtworks/go/domain/materials/tfs/Changeset.java
saschaglo/gocd
fb9075d3155d82d481ba062ead6fe36262c7785c
[ "Apache-2.0" ]
null
null
null
32.363636
208
0.646348
8,754
/*************************GO-LICENSE-START********************************* * Copyright 2014 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. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.domain.materials.tfs; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.domain.materials.ModifiedFile; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias("changeset") public class Changeset { @XStreamAsAttribute private String id; @XStreamAsAttribute private String committer; @XStreamAsAttribute private String date; @XStreamAlias("comment") private Comment comment; @XStreamImplicit private List<Item> items; @XStreamImplicit private List<CheckInNote> checkInNotes; private static final SimpleDateFormat CHANGESET_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); public Changeset(String id) { this.id = id; } public Modification getModification() { Date parse = parseDate(date, CHANGESET_DATE_FORMAT); Modification modification = new Modification(committer, getComment(), null, new Date(parse.getYear(), parse.getMonth(), parse.getDate(), parse.getHours(), parse.getMinutes(), parse.getSeconds()), id); ArrayList<ModifiedFile> files = new ArrayList<ModifiedFile>(); for (Item item : items) { files.add(item.getModifiedFile()); } modification.setModifiedFiles(files); return modification; } private String getComment() { return comment == null ? "" : comment.getContent(); } public void setCommitter(String committer) { this.committer = committer; } public void setDate(String dateValue) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy h:mm:ss a"); this.date = CHANGESET_DATE_FORMAT.format(parseDate(dateValue, simpleDateFormat)); } public void setComment(String comment) { this.comment = new Comment(comment); } private Date parseDate(String date, SimpleDateFormat dateFormat) { Date parse = null; try { parse = dateFormat.parse(date); } catch (ParseException e) { throw new RuntimeException(e); } return parse; } @Override public String toString() { return "Changeset{" + "id='" + id + '\'' + ", committer='" + committer + '\'' + ", date='" + date + '\'' + ", comment=" + comment + ", items=" + items + '}'; } public void setItems(List<Item> items) { this.items = items; } }
3e14a82fd8aee9228281f7421e079493e3359199
7,999
java
Java
plugins/inwebo/src/main/java/org/gluu/casa/plugins/inwebo/InweboService.java
alexandre-zia-ifood/casa
dd805f2a8c54342a642d43c07fbf98f30a726196
[ "Apache-2.0" ]
15
2018-08-02T15:51:28.000Z
2021-11-08T07:06:57.000Z
plugins/inwebo/src/main/java/org/gluu/casa/plugins/inwebo/InweboService.java
alexandre-zia-ifood/casa
dd805f2a8c54342a642d43c07fbf98f30a726196
[ "Apache-2.0" ]
157
2018-07-12T16:32:06.000Z
2022-03-26T02:23:04.000Z
plugins/inwebo/src/main/java/org/gluu/casa/plugins/inwebo/InweboService.java
alexandre-zia-ifood/casa
dd805f2a8c54342a642d43c07fbf98f30a726196
[ "Apache-2.0" ]
12
2018-12-18T19:37:37.000Z
2022-01-28T00:19:54.000Z
28.773381
114
0.730466
8,755
package org.gluu.casa.plugins.inwebo; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.gluu.casa.core.model.CustomScript; import org.gluu.casa.misc.Utils; import org.gluu.casa.service.IPersistenceService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zkoss.zk.ui.Executions; import com.fasterxml.jackson.databind.ObjectMapper; import com.inwebo.api.sample.User; import com.inwebo.api.sample.UserList; import com.inwebo.console.ConsoleAdmin; import com.inwebo.console.ConsoleAdminService; import com.inwebo.console.LoginCreateResult; import com.inwebo.console.LoginQueryResult; import com.inwebo.console.LoginSearchResult; import com.inwebo.support.Util; /** * Class that holds the logic to list and enroll inwebo devices * * @author madhumita * */ //TODO:check if this should be a singleton class public class InweboService { private static InweboService SINGLE_INSTANCE = null; public static Map<String, String> properties; private Logger logger = LoggerFactory.getLogger(getClass()); public static String ACR = "inwebo"; private static String CERTIFICATE_PATH_PROP = "iw_cert_path"; private static String CERTIFICATE_PASSPHRASE_JSON_FILE = "iw_creds_file"; private static String PASSPHRASE_FOR_CERTIFICATE = "CERT_PASSWORD"; private static String SERVICE_ID = "iw_service_id"; private IPersistenceService ldapService; private final ConsoleAdminService cas; private final ConsoleAdmin consoleAdmin; private final long serviceId; private final String p12password; private final String p12file; private InweboService() { ldapService = Utils.managedBean(IPersistenceService.class); reloadConfiguration(); cas = new ConsoleAdminService(); consoleAdmin = cas.getConsoleAdmin(); p12file = properties.get(CERTIFICATE_PATH_PROP); // "/etc/certs/Gluu_dev.p12"; // This is the password to access your certificate file p12password = this.getCertificatePassphrase(properties.get(CERTIFICATE_PASSPHRASE_JSON_FILE)); serviceId = Long.valueOf(properties.get(SERVICE_ID)); // 5686; // This is the id of your service. Util.activeSoapLog(false); try { Util.setHttpsClientCert(p12file, p12password); } catch (final Exception e1) { e1.printStackTrace(); } } public static InweboService getInstance() { if (SINGLE_INSTANCE == null) { synchronized (InweboService.class) { SINGLE_INSTANCE = new InweboService(); } } return SINGLE_INSTANCE; } public void reloadConfiguration() { ObjectMapper mapper = new ObjectMapper(); properties = getCustScriptConfigProperties(ACR); if (properties == null) { logger.warn( "Config. properties for custom script '{}' could not be read. Features related to {} will not be accessible", ACR, ACR.toUpperCase()); } else { try { logger.info("Inwebo settings found were: {}", mapper.writeValueAsString(properties)); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public String getScriptPropertyValue(String value) { return properties.get(value); } public List<InweboCredential> getDevices(String userName) { User user = getUser(userName); if (user == null) { return null; } final LoginQueryResult result = consoleAdmin.loginQuery(0, user.getId()); if (result != null && "ok".equalsIgnoreCase(result.getErr())) { List<InweboCredential> credList = new ArrayList<InweboCredential>(); for (int i = 0; i < result.getNva(); i++) { InweboCredential credential = new InweboCredential(result.getVaname().get(i), 0); credential.setCredentialId(result.getVaid().get(i)); credential.setCredentialType(InweboCredential.VIRTUAL_AUTHENTICATOR); credList.add(credential); } for (int i = 0; i < result.getNma(); i++) { InweboCredential credential = new InweboCredential(result.getManame().get(i), 0); credential.setCredentialId(result.getMaid().get(i)); credential.setCredentialType(InweboCredential.MOBILE_AUTHENTICATOR); credList.add(credential); } return credList; } else { return null; } } public int getDeviceTotal(String userName) { List<InweboCredential> credList = getDevices(userName); if (credList == null) return 0; else return credList.size(); } public User getUser(String username) { int offset = 0; int nmax = 1; int sort = 1; int exactmatch = 1; LoginSearchResult result = consoleAdmin.loginSearch(0, serviceId, username, exactmatch, offset, nmax, sort); if (result != null && "ok".equalsIgnoreCase(result.getErr())) { List<User> userList = new UserList(result); if (userList == null || userList.size() == 0) return null; else return (User) userList.get(0); } else { return null; } } public String getLongCode(long userId) { String result = consoleAdmin.loginAddDevice(0, serviceId, userId, CodeType.ACTIVATION_LINK_VALID_FOR_3_WEEKS.getCodeType()); return result; } public long getUserId(String userName) { User user = getUser(userName); if (user == null) { return 0; } else { return user.getId(); } } public String getActivationCode(String longCode) { LoginCreateResult info = consoleAdmin.loginGetInfoFromLink(longCode); String err = info.getErr(); if (!err.equalsIgnoreCase("ok")) { return null; } else { return info.getCode(); } } public boolean deleteInWeboDevice(String userName, long deviceId, String tooltype) { User user = getUser(userName); if (user == null) return false; String result = consoleAdmin.loginDeleteTool(user.getId(), serviceId, deviceId, tooltype); if ("OK".equalsIgnoreCase(result)) return true; else return false; } public boolean updateInWeboDevice(String userName, long deviceId, String tooltype, String newName) { // User user = getUser(userName); // This method is available only for inWebo Safe Transactions or Enterprise. /*String result = consoleAdmin.loginUpdateTool(0, serviceId, deviceId, tooltype, newName); if ("OK".equalsIgnoreCase(result)) return true; else*/ return false; } public boolean sendEmailForLinkActivation(String userName) { User user = getUser(userName); if (user == null) return false; // for email to work, you have to call loginAddDevice once more String longCode = consoleAdmin.loginAddDevice(0, serviceId, user.getId(), CodeType.ACTIVATION_LINK_VALID_FOR_3_WEEKS.getCodeType()); String result = consoleAdmin.loginSendByMail(0, serviceId, user.getId()); if (result.equalsIgnoreCase("nok")) { return false; } else { return true; } } public Map<String, String> getCustScriptConfigProperties(String acr) { CustomScript script = new CustomScript(); script.setDisplayName(acr); script.setBaseDn(ldapService.getCustomScriptsDn()); List<CustomScript> list = ldapService.find(script); script = list.size() > 0 ? list.get(0) : null; if (script != null) { Map<String, String> props = Utils.scriptConfigPropertiesAsMap(script); return props; } return null; } private String getCertificatePassphrase(String fileName) { // converting json to Map byte[] mapData; try { mapData = Files.readAllBytes(Paths.get(fileName)); Map<String, String> myMap = new HashMap<String, String>(); ObjectMapper objectMapper = new ObjectMapper(); myMap = objectMapper.readValue(mapData, HashMap.class); return myMap.get(PASSPHRASE_FOR_CERTIFICATE); } catch (IOException e) { logger.debug("Error parsing the file containing the passphrase for the certificate"); return null; } } public String getUserName(String id) { return ldapService.getPersonDn(id); } public String buildURLForActivation(String code) { StringBuilder url = new StringBuilder().append("https://").append(Executions.getCurrent().getServerName()); url.append("/casa/pl/inwebo-plugin/add_cred.zul?code=").append(code); return url.toString(); } }
3e14a8d99827b868c8f2aac937e7a48bf74585a4
4,106
java
Java
com.sap.cloud.lm.sl.cf.core/src/test/java/com/sap/cloud/lm/sl/cf/core/helpers/v2_0/ConfigurationSubscriptionFactoryTest.java
kgavrailov/multiapps-controller
e7461fc64fb149a66f26c4102ad25563c4c3174c
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/test/java/com/sap/cloud/lm/sl/cf/core/helpers/v2_0/ConfigurationSubscriptionFactoryTest.java
kgavrailov/multiapps-controller
e7461fc64fb149a66f26c4102ad25563c4c3174c
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/test/java/com/sap/cloud/lm/sl/cf/core/helpers/v2_0/ConfigurationSubscriptionFactoryTest.java
kgavrailov/multiapps-controller
e7461fc64fb149a66f26c4102ad25563c4c3174c
[ "Apache-2.0" ]
null
null
null
42.770833
154
0.718948
8,756
package com.sap.cloud.lm.sl.cf.core.helpers.v2_0; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.sap.cloud.lm.sl.cf.core.dao.filters.ConfigurationFilter; import com.sap.cloud.lm.sl.cf.core.model.CloudTarget; import com.sap.cloud.lm.sl.cf.core.model.ResolvedConfigurationReference; import com.sap.cloud.lm.sl.common.util.TestUtil; import com.sap.cloud.lm.sl.mta.handlers.v2_0.DescriptorHandler; import com.sap.cloud.lm.sl.mta.handlers.v2_0.DescriptorParser; import com.sap.cloud.lm.sl.mta.model.v2_0.DeploymentDescriptor; import com.sap.cloud.lm.sl.mta.model.v2_0.Resource; @RunWith(Parameterized.class) public class ConfigurationSubscriptionFactoryTest { @Parameters public static Iterable<Object[]> getParameters() { return Arrays.asList(new Object[][] { // @formatter:off // (0) The required dependency is managed, so a subscription should be created: { "subscriptions-mtad-00.yaml", Arrays.asList("plugins"), "SPACE_ID_1", "R:subscriptions-00.json", }, // (1) The required dependency is not managed, so a subscription should not be created: { "subscriptions-mtad-01.yaml", Arrays.asList("plugins"), "SPACE_ID_1", "[]", }, // (2) The required dependency is not managed, so a subscription should not be created: { "subscriptions-mtad-02.yaml", Arrays.asList("plugins"), "SPACE_ID_1", "[]", }, // @formatter:on }); } private String mtadFilePath; private List<String> configurationResources; private String spaceId; private String expected; public ConfigurationSubscriptionFactoryTest(String mtadFilePath, List<String> configurationResources, String spaceId, String expected) { this.mtadFilePath = mtadFilePath; this.configurationResources = configurationResources; this.spaceId = spaceId; this.expected = expected; } @Test public void testCreate() throws Exception { String mtadString = TestUtil.getResourceAsString(mtadFilePath, getClass()); DeploymentDescriptor mtad = getDescriptorParser().parseDeploymentDescriptorYaml(mtadString); Map<String, ResolvedConfigurationReference> resolvedResources = getResolvedConfigurationReferences(mtad); testCreate(mtad, resolvedResources, spaceId, expected); } protected void testCreate(DeploymentDescriptor mtad, Map<String, ResolvedConfigurationReference> resolvedResources, String spaceId, String expected) { TestUtil.test(() -> { return new ConfigurationSubscriptionFactory().create(mtad, resolvedResources, spaceId); }, expected, getClass()); } private Map<String, ResolvedConfigurationReference> getResolvedConfigurationReferences(DeploymentDescriptor descriptor) { Map<String, ResolvedConfigurationReference> result = new HashMap<>(); for (String configurationResource : configurationResources) { result.put(configurationResource, getResolvedConfigurationReference(descriptor, configurationResource)); } return result; } private ResolvedConfigurationReference getResolvedConfigurationReference(DeploymentDescriptor descriptor, String configurationResource) { DescriptorHandler handler = new DescriptorHandler(); Resource resource = (Resource) handler.findResource(descriptor, configurationResource); return new ResolvedConfigurationReference(createDummyFilter(), resource, Collections.emptyList()); } private ConfigurationFilter createDummyFilter() { return new ConfigurationFilter("mta", "com.sap.other.mta", "1.0.0", new CloudTarget("ORG", "SPACE"), Collections.emptyMap()); } protected DescriptorParser getDescriptorParser() { return new DescriptorParser(); } }
3e14a90f80e783835f449e06f65737accd43f233
217
java
Java
src/main/java/br/com/finances/config/errors/ErrorDTO.java
WesleyMime/Finances-API
ff1414806d50d148e503a0bc2afd5d388743b486
[ "MIT" ]
null
null
null
src/main/java/br/com/finances/config/errors/ErrorDTO.java
WesleyMime/Finances-API
ff1414806d50d148e503a0bc2afd5d388743b486
[ "MIT" ]
null
null
null
src/main/java/br/com/finances/config/errors/ErrorDTO.java
WesleyMime/Finances-API
ff1414806d50d148e503a0bc2afd5d388743b486
[ "MIT" ]
null
null
null
12.764706
38
0.695853
8,757
package br.com.finances.config.errors; public class ErrorDTO { private String message; public ErrorDTO(String message) { this.message = message; } public String getMessage() { return message; } }
3e14a9bbe9cbe874e9d6731fde606474157a073c
6,104
java
Java
MPChartLib/src/main/java/com/github/mikephil/charting/components/LimitLine.java
Saritasa/MPAndroidChart
acfc85aae729d231e5e4b43e21414df872abc9bd
[ "Apache-2.0" ]
1
2020-11-20T12:35:07.000Z
2020-11-20T12:35:07.000Z
MPChartLib/src/main/java/com/github/mikephil/charting/components/LimitLine.java
Saritasa/MPAndroidChart
acfc85aae729d231e5e4b43e21414df872abc9bd
[ "Apache-2.0" ]
null
null
null
MPChartLib/src/main/java/com/github/mikephil/charting/components/LimitLine.java
Saritasa/MPAndroidChart
acfc85aae729d231e5e4b43e21414df872abc9bd
[ "Apache-2.0" ]
3
2020-11-20T12:35:08.000Z
2021-04-09T03:11:19.000Z
24.318725
84
0.600426
8,758
package com.github.mikephil.charting.components; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.drawable.Drawable; import com.github.mikephil.charting.utils.Utils; /** * The limit line is an additional feature for all Line-, Bar- and * ScatterCharts. It allows the displaying of an additional line in the chart * that marks a certain maximum / limit on the specified axis (x- or y-axis). * * @author Philipp Jahoda */ public class LimitLine extends ComponentBase { /** limit / maximum (the y-value or xIndex) */ private float mLimit = 0f; /** the width of the limit line */ private float mLineWidth = 2f; /** the color of the limit line */ private int mLineColor = Color.rgb(237, 91, 91); /** the style of the label text */ private Paint.Style mTextStyle = Paint.Style.FILL_AND_STROKE; /** * label string that is drawn next to the limit line */ private String mLabel = ""; /** * the path effect of this LimitLine that makes dashed lines possible */ private DashPathEffect mDashPathEffect = null; /** * indicates the position of the LimitLine label */ private LimitLabelPosition mLabelPosition = LimitLabelPosition.RIGHT_TOP; public float mIconOffset = 0f; public int mIconSize = 0; private Drawable mIcon = null; /** * enum that indicates the position of the LimitLine label */ public enum LimitLabelPosition{ LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM } /** * Constructor with limit. * * @param limit - the position (the value) on the y-axis (y-value) or x-axis * (xIndex) where this line should appear */ public LimitLine(float limit) { mLimit = limit; } /** * Constructor with limit and label. * * @param limit - the position (the value) on the y-axis (y-value) or x-axis * (xIndex) where this line should appear * @param label - provide "" if no label is required */ public LimitLine(float limit, String label) { mLimit = limit; mLabel = label; } /** * Returns the limit that is set for this line. * * @return */ public float getLimit(){ return mLimit; } /** * returns the width of limit line * * @return */ public float getLineWidth(){ return mLineWidth; } /** * set the line width of the chart (min = 0.2f, max = 12f); default 2f NOTE: * thinner line == better performance, thicker line == worse performance * * @param width */ public void setLineWidth(float width) { if (width < 0.2f) width = 0.2f; if (width > 12.0f) width = 12.0f; mLineWidth = Utils.convertDpToPixel(width); } /** * Returns the color that is used for this LimitLine * * @return */ public int getLineColor() { return mLineColor; } /** * Sets the linecolor for this LimitLine. Make sure to use * getResources().getColor(...) * * @param color */ public void setLineColor(int color) { mLineColor = color; } /** * Enables the line to be drawn in dashed mode, e.g. like this "- - - - - -" * * @param lineLength the length of the line pieces * @param spaceLength the length of space inbetween the pieces * @param phase offset, in degrees (normally, use 0) */ public void enableDashedLine(float lineLength, float spaceLength, float phase) { mDashPathEffect = new DashPathEffect(new float[] { lineLength, spaceLength }, phase); } /** * Disables the line to be drawn in dashed mode. */ public void disableDashedLine() { mDashPathEffect = null; } /** * Returns true if the dashed-line effect is enabled, false if not. Default: * disabled * * @return */ public boolean isDashedLineEnabled() { return mDashPathEffect == null ? false : true; } /** * returns the DashPathEffect that is set for this LimitLine * * @return */ public DashPathEffect getDashPathEffect() { return mDashPathEffect; } /** * Sets the color of the value-text that is drawn next to the LimitLine. * Default: Paint.Style.FILL_AND_STROKE * * @param style */ public void setTextStyle(Paint.Style style){ this.mTextStyle = style; } /** * Returns the color of the value-text that is drawn next to the LimitLine. * * @return */ public Paint.Style getTextStyle(){ return mTextStyle; } /** * Returns the position of the LimitLine label (value). * * @return */ public LimitLabelPosition getLabelPosition(){ return mLabelPosition; } /** * Sets the position of the LimitLine value label (either on the right or on * the left edge of the chart). Not supported for RadarChart. * * @param pos */ public void setLabelPosition(LimitLabelPosition pos){ mLabelPosition = pos; } /** * Returns the label that is drawn next to the limit line. * * @return */ public String getLabel(){ return mLabel; } /** * Sets the label that is drawn next to the limit line. Provide "" if no * label is required. * * @param label */ public void setLabel(String label){ mLabel = label; } public Drawable getIcon(){ return mIcon; } public void setIcon(final Drawable aIcon){ mIcon = aIcon; } public float getIconOffset(){ return mIconOffset; } public void setIconOffset(final float iconOffset){ mIconOffset = iconOffset; } public int getIconSize(){ return mIconSize; } public void setIconSize(final int iconSize){ mIconSize = iconSize; } }
3e14a9ce1fa932cecb8f8bce75dce0f6355cc308
488
java
Java
hercules-sentry-sink/src/main/java/ru/kontur/vostok/hercules/sentry/api/model/OrganizationInfo.java
petr-stb/hercules
dc029ab831f9669bc115b7042da9ec5ac6da181c
[ "MIT" ]
24
2019-04-19T14:58:11.000Z
2022-02-14T06:01:07.000Z
hercules-sentry-sink/src/main/java/ru/kontur/vostok/hercules/sentry/api/model/OrganizationInfo.java
petr-stb/hercules
dc029ab831f9669bc115b7042da9ec5ac6da181c
[ "MIT" ]
2
2019-04-18T13:38:07.000Z
2021-06-21T12:17:15.000Z
hercules-sentry-sink/src/main/java/ru/kontur/vostok/hercules/sentry/api/model/OrganizationInfo.java
petr-stb/hercules
dc029ab831f9669bc115b7042da9ec5ac6da181c
[ "MIT" ]
9
2019-01-18T06:42:54.000Z
2021-11-03T06:17:20.000Z
20.333333
62
0.69877
8,759
package ru.kontur.vostok.hercules.sentry.api.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * The model of organization in Sentry. * It is a model which may be got from JSON in Sentry response * * @author Kirill Sulim */ @JsonIgnoreProperties(ignoreUnknown = true) public class OrganizationInfo { private String slug; public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } }
3e14ac271680c537092f529fbd849a502bbd209b
3,663
java
Java
Study-lemon-message/lemon-server-order-service/src/test/java/DubboProvider.java
hualongchen/studytree
829b934861a445fb33c3468247216089afce3ba3
[ "Apache-2.0" ]
1
2018-11-20T08:37:14.000Z
2018-11-20T08:37:14.000Z
Study-lemon-message/lemon-server-order-service/src/test/java/DubboProvider.java
hualongchen/studytree
829b934861a445fb33c3468247216089afce3ba3
[ "Apache-2.0" ]
null
null
null
Study-lemon-message/lemon-server-order-service/src/test/java/DubboProvider.java
hualongchen/studytree
829b934861a445fb33c3468247216089afce3ba3
[ "Apache-2.0" ]
null
null
null
27.222222
125
0.649796
8,760
/* * ==================================================================== * 龙果学院: www.roncoo.com (微信公众号:RonCoo_com) * 超级教程系列:《微服务架构的分布式事务解决方案》视频教程 * nnheo@example.com * 课程地址:http://www.roncoo.com/details/7ae3d7eddc4742f78b0548aa8bd9ccdb * ==================================================================== */ import com.alibaba.fastjson.JSONObject; import com.lemon.core.utils.UUIDUtil; import com.lemon.core.vo.ResultVO; import com.lemon.message.api.RpTransactionMessageService; import com.lemon.message.entity.RpTransactionMessage; import com.lemon.order.api.LemonOrderService; import com.lemon.order.entiry.LemonOrderServiceDTO; import com.lemon.order.service.dao.bean.LemonOrderInfoPO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Date; /** * * @描述: 启动Dubbo服务用的MainClass. * @作者: WuShuicheng . * @创建时间: 2016-06-22,下午9:47:55 . * @版本: 1.0 . */ public class DubboProvider { private static final Log log = LogFactory.getLog(DubboProvider.class); public static void main(String[] args) { try { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml"); context.start(); // 1. 建立订单,待支付状态 // 2. 预发信息, 准备扣钱。 // 3. 操作扣钱,并修改订单,为支付成功状态。 // 4. 确认发送信息 // 5. 增加用户积分 // 6. 删除消息 System.out.println("==================订单系统启动完毕========================="); for (int i = 0; i <30000 ; i++) { //1.建立订单 LemonOrderService lemonOrderService =(LemonOrderService)context.getBean("lemonOrderServiceImpl"); ResultVO resultVO =lemonOrderService.createLemonOrder(); System.out.println("========================1. 建立订单成功=================="); //获取订单 LemonOrderServiceDTO lemonOrderServiceDTO = (LemonOrderServiceDTO)resultVO.getData(); System.out.println("========================2. 获取订单成功=================="); //2. 发送信息 RpTransactionMessageService messageService =(RpTransactionMessageService)context.getBean("rpTransactionMessageService"); RpTransactionMessage rpTransactionMessage = new RpTransactionMessage(); String messageId= UUIDUtil.returnUUID(); lemonOrderServiceDTO.setMessageId(messageId); rpTransactionMessage.setMessageId(messageId); rpTransactionMessage.setMessageBody(JSONObject.toJSONString(lemonOrderServiceDTO)); rpTransactionMessage.setConsumerQueue("积分队列"); rpTransactionMessage.setVersion(0); rpTransactionMessage.setId(UUIDUtil.returnUUID()); rpTransactionMessage.setCreater("lemon"); rpTransactionMessage.setStatus("WAIT_PAY"); rpTransactionMessage.setCreateTime(new Date()); rpTransactionMessage.setField1(lemonOrderServiceDTO.getOrderId()); messageService.saveMessageWaitingConfirm(rpTransactionMessage); System.out.println("========================3. 预发送信息成功=================="); //3.默认去支付成功 Thread.sleep(1000); //3.1 假装几个单子异常 //4. 修改订单成功状态 lemonOrderService.updateLemonOrder(lemonOrderServiceDTO.getOrderId()); System.out.println("========================4. 本地事务成功=================="); //5. 发送成功信息 messageService.confirmAndSendMessage(messageId); //6. 监听调用信息,进行修改和删除 System.out.println("=======================6. 发送成功消息成功=================="); } } catch (Exception e) { log.error("== DubboProvider context start error:", e); } synchronized (DubboProvider.class) { while (true) { try { DubboProvider.class.wait(); } catch (InterruptedException e) { log.error("== synchronized error:", e); } } } } }
3e14ac545052688096ec6502c88362323e22a72e
274
java
Java
ui/src/pandas/marcexport/PublisherType.java
nla/pandas4
2cee9b8fae88cf5bee46472b305fa91e1f3d2976
[ "Apache-2.0" ]
1
2022-01-03T16:51:53.000Z
2022-01-03T16:51:53.000Z
ui/src/pandas/marcexport/PublisherType.java
nla/pandas4
2cee9b8fae88cf5bee46472b305fa91e1f3d2976
[ "Apache-2.0" ]
22
2021-02-22T14:36:01.000Z
2022-02-20T12:07:44.000Z
ui/src/pandas/marcexport/PublisherType.java
nla/pandas4
2cee9b8fae88cf5bee46472b305fa91e1f3d2976
[ "Apache-2.0" ]
2
2021-06-10T09:13:31.000Z
2021-11-18T19:15:12.000Z
19.571429
69
0.638686
8,761
package pandas.marcexport; public enum PublisherType { GOVERNMENT, ORGANISATION, EDUCATION, COMMERCIAL, PERSONAL, OTHER; static PublisherType byId(int id) { return PublisherType.values()[id - 1]; } int id() { return ordinal() + 1; } }
3e14ac5b47c0b9f2501b17642949f2feea671128
657
java
Java
src/main/java/com/meti/feature/render/PassPrototype.java
SirMathhman/MagmaBootstrap
e06cbe363fc2a71adffb5e3c6e061b91292a29b9
[ "MIT" ]
null
null
null
src/main/java/com/meti/feature/render/PassPrototype.java
SirMathhman/MagmaBootstrap
e06cbe363fc2a71adffb5e3c6e061b91292a29b9
[ "MIT" ]
null
null
null
src/main/java/com/meti/feature/render/PassPrototype.java
SirMathhman/MagmaBootstrap
e06cbe363fc2a71adffb5e3c6e061b91292a29b9
[ "MIT" ]
null
null
null
21.193548
63
0.668189
8,762
package com.meti.feature.render; import java.util.List; public abstract class PassPrototype implements Node.Prototype { @Override public Node.Prototype withField(Field field) { return this; } @Override public Node.Prototype withChild(Node child) { return this; } @Override public List<Node> listChildren() { throw new UnsupportedOperationException(); } @Override public List<Field> listFields() { throw new UnsupportedOperationException(); } @Override public Node.Prototype merge(Node.Prototype other) { throw new UnsupportedOperationException(); } }
3e14ac75bd5db05a2624ca2c6dd1a2064672304f
788
java
Java
app/src/main/java/com/osacky/hipsterviz/api/thomasApi/ThomasApi.java
runningcode/Hipster-Visualization
7fb78fa717e9793940efcc53f81f8b1400d78443
[ "ECL-2.0", "CC-BY-3.0", "Apache-2.0" ]
2
2015-01-07T01:46:18.000Z
2015-08-28T18:09:54.000Z
app/src/main/java/com/osacky/hipsterviz/api/thomasApi/ThomasApi.java
runningcode/Hipster-Visualization
7fb78fa717e9793940efcc53f81f8b1400d78443
[ "ECL-2.0", "CC-BY-3.0", "Apache-2.0" ]
1
2018-06-05T16:14:03.000Z
2018-06-05T16:14:03.000Z
app/src/main/java/com/osacky/hipsterviz/api/thomasApi/ThomasApi.java
runningcode/Hipster-Visualization
7fb78fa717e9793940efcc53f81f8b1400d78443
[ "ECL-2.0", "CC-BY-3.0", "Apache-2.0" ]
null
null
null
27.172414
113
0.748731
8,763
package com.osacky.hipsterviz.api.thomasApi; import com.osacky.hipsterviz.models.ArtistDataResponse; import java.util.List; import retrofit.Callback; import retrofit.http.Body; import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import retrofit.mime.TypedInput; @SuppressWarnings("unused") interface ThomasApi { @GET("/requestArtists") ArtistDataResponse.ArtistList requestArtists(@Query("limit") int limit); @POST("/rankArtists") List<ArtistDataResponse> rankArtists(@Body TypedInput body); @POST("/rank") void rank(@Query("id") String id, @Query("classification") String classification, Callback<String> callback); @POST("/rank") String rank(@Query("id") String id, @Query("classification") String classification); }
3e14ad0eb28554e1d6b1776a7cf908ed21d5462f
16,161
java
Java
addon/de.dc.javafx.xcore.workbench.chart/de.dc.javafx.xcore.workbench.chart.editor/src-gen/de/dc/javafx/xcore/workbench/chart/presentation/ChartModelWizard.java
chqu1012/de.dc.emf.javafx.xtext.lang
c6e6c8686285c8cb852c057693427b47e3662b84
[ "Apache-2.0" ]
5
2019-04-14T12:15:30.000Z
2019-05-17T15:19:29.000Z
addon/de.dc.javafx.xcore.workbench.chart/de.dc.javafx.xcore.workbench.chart.editor/src-gen/de/dc/javafx/xcore/workbench/chart/presentation/ChartModelWizard.java
chqu1012/de.dc.emf.javafx.xtext.lang
c6e6c8686285c8cb852c057693427b47e3662b84
[ "Apache-2.0" ]
456
2019-04-09T08:22:26.000Z
2019-06-29T09:19:32.000Z
addon/de.dc.javafx.xcore.workbench.chart/de.dc.javafx.xcore.workbench.chart.editor/src-gen/de/dc/javafx/xcore/workbench/chart/presentation/ChartModelWizard.java
chqu1012/de.dc.emf.javafx.xtext.lang
c6e6c8686285c8cb852c057693427b47e3662b84
[ "Apache-2.0" ]
null
null
null
27.768041
108
0.655652
8,764
/** */ package de.dc.javafx.xcore.workbench.chart.presentation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.MissingResourceException; import java.util.StringTokenizer; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import de.dc.javafx.xcore.workbench.chart.ChartFactory; import de.dc.javafx.xcore.workbench.chart.ChartPackage; import de.dc.javafx.xcore.workbench.chart.provider.ChartEditPlugin; import java.io.File; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Text; /** * This is a simple wizard for creating a new model file. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ChartModelWizard extends Wizard implements INewWizard { /** * The supported extensions for created files. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<String> FILE_EXTENSIONS = Collections.unmodifiableList(Arrays .asList(ChartEditorPlugin.INSTANCE.getString("_UI_ChartEditorFilenameExtensions").split("\\s*,\\s*"))); /** * A formatted list of supported file extensions, suitable for display. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final String FORMATTED_FILE_EXTENSIONS = ChartEditorPlugin.INSTANCE .getString("_UI_ChartEditorFilenameExtensions").replaceAll("\\s*,\\s*", ", "); /** * This caches an instance of the model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ChartPackage chartPackage = ChartPackage.eINSTANCE; /** * This caches an instance of the model factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ChartFactory chartFactory = chartPackage.getChartFactory(); /** * This is the initial object creation page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ChartModelWizardInitialObjectCreationPage initialObjectCreationPage; /** * Remember the selection during initialization for populating the default container. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IStructuredSelection selection; /** * Remember the workbench during initialization. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IWorkbench workbench; /** * Caches the names of the types that can be created as the root object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected List<String> initialObjectNames; /** * This just records the information. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void init(IWorkbench workbench, IStructuredSelection selection) { this.workbench = workbench; this.selection = selection; setWindowTitle(ChartEditorPlugin.INSTANCE.getString("_UI_Wizard_label")); setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE .getImageDescriptor(ChartEditorPlugin.INSTANCE.getImage("full/wizban/NewChart"))); } /** * Returns the names of the types that can be created as the root object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<String> getInitialObjectNames() { if (initialObjectNames == null) { initialObjectNames = new ArrayList<String>(); for (EClassifier eClassifier : chartPackage.getEClassifiers()) { if (eClassifier instanceof EClass) { EClass eClass = (EClass) eClassifier; if (!eClass.isAbstract()) { initialObjectNames.add(eClass.getName()); } } } Collections.sort(initialObjectNames, java.text.Collator.getInstance()); } return initialObjectNames; } /** * Create a new model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EObject createInitialModel() { EClass eClass = (EClass) chartPackage.getEClassifier(initialObjectCreationPage.getInitialObjectName()); EObject rootObject = chartFactory.create(eClass); return rootObject; } /** * Do the work after everything is specified. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean performFinish() { try { // Get the URI of the model file. // final URI fileURI = getModelURI(); if (new File(fileURI.toFileString()).exists()) { if (!MessageDialog.openQuestion(getShell(), ChartEditorPlugin.INSTANCE.getString("_UI_Question_title"), ChartEditorPlugin.INSTANCE.getString("_WARN_FileConflict", new String[] { fileURI.toFileString() }))) { initialObjectCreationPage.selectFileField(); return false; } } // Do the work within an operation. // IRunnableWithProgress operation = new IRunnableWithProgress() { @Override public void run(IProgressMonitor progressMonitor) { try { // Create a resource set // ResourceSet resourceSet = new ResourceSetImpl(); // Create a resource for this file. // Resource resource = resourceSet.createResource(fileURI); // Add the initial model object to the contents. // EObject rootObject = createInitialModel(); if (rootObject != null) { resource.getContents().add(rootObject); } // Save the contents of the resource to the file system. // Map<Object, Object> options = new HashMap<Object, Object>(); options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding()); resource.save(options); } catch (Exception exception) { ChartEditorPlugin.INSTANCE.log(exception); } finally { progressMonitor.done(); } } }; getContainer().run(false, false, operation); return ChartEditorAdvisor.openEditor(workbench, fileURI); } catch (Exception exception) { ChartEditorPlugin.INSTANCE.log(exception); return false; } } /** * This is the page where the type of object to create is selected. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ChartModelWizardInitialObjectCreationPage extends WizardPage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Text fileField; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Combo initialObjectField; /** * @generated * <!-- begin-user-doc --> * <!-- end-user-doc --> */ protected List<String> encodings; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Combo encodingField; /** * Pass in the selection. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ChartModelWizardInitialObjectCreationPage(String pageId) { super(pageId); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); { GridLayout layout = new GridLayout(); layout.numColumns = 1; layout.verticalSpacing = 12; composite.setLayout(layout); GridData data = new GridData(); data.verticalAlignment = GridData.FILL; data.grabExcessVerticalSpace = true; data.horizontalAlignment = GridData.FILL; composite.setLayoutData(data); } Label resourceURILabel = new Label(composite, SWT.LEFT); { resourceURILabel.setText(ChartEditorPlugin.INSTANCE.getString("_UI_File_label")); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; resourceURILabel.setLayoutData(data); } Composite fileComposite = new Composite(composite, SWT.NONE); { GridData data = new GridData(); data.horizontalAlignment = GridData.END; fileComposite.setLayoutData(data); GridLayout layout = new GridLayout(); data.horizontalAlignment = GridData.FILL; layout.marginHeight = 0; layout.marginWidth = 0; layout.numColumns = 2; fileComposite.setLayout(layout); } fileField = new Text(fileComposite, SWT.BORDER); { GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; data.horizontalSpan = 1; fileField.setLayoutData(data); } fileField.addModifyListener(validator); Button resourceURIBrowseFileSystemButton = new Button(fileComposite, SWT.PUSH); resourceURIBrowseFileSystemButton.setText(ChartEditorPlugin.INSTANCE.getString("_UI_Browse_label")); resourceURIBrowseFileSystemButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { String[] filters = ChartEditor.FILE_EXTENSION_FILTERS .toArray(new String[ChartEditor.FILE_EXTENSION_FILTERS.size()]); String[] files = ChartEditorAdvisor.openFilePathDialog(getShell(), SWT.SAVE, filters); if (files.length > 0) { fileField.setText(files[0]); } } }); Label containerLabel = new Label(composite, SWT.LEFT); { containerLabel.setText(ChartEditorPlugin.INSTANCE.getString("_UI_ModelObject")); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; containerLabel.setLayoutData(data); } initialObjectField = new Combo(composite, SWT.BORDER); { GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; initialObjectField.setLayoutData(data); } for (String objectName : getInitialObjectNames()) { initialObjectField.add(getLabel(objectName)); } if (initialObjectField.getItemCount() == 1) { initialObjectField.select(0); } initialObjectField.addModifyListener(validator); Label encodingLabel = new Label(composite, SWT.LEFT); { encodingLabel.setText(ChartEditorPlugin.INSTANCE.getString("_UI_XMLEncoding")); GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; encodingLabel.setLayoutData(data); } encodingField = new Combo(composite, SWT.BORDER); { GridData data = new GridData(); data.horizontalAlignment = GridData.FILL; data.grabExcessHorizontalSpace = true; encodingField.setLayoutData(data); } for (String encoding : getEncodings()) { encodingField.add(encoding); } encodingField.select(0); encodingField.addModifyListener(validator); setPageComplete(validatePage()); setControl(composite); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ModifyListener validator = new ModifyListener() { @Override public void modifyText(ModifyEvent e) { setPageComplete(validatePage()); } }; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean validatePage() { URI fileURI = getFileURI(); if (fileURI == null || fileURI.isEmpty()) { setErrorMessage(null); return false; } String extension = fileURI.fileExtension(); if (extension == null || !FILE_EXTENSIONS.contains(extension)) { String key = FILE_EXTENSIONS.size() > 1 ? "_WARN_FilenameExtensions" : "_WARN_FilenameExtension"; setErrorMessage(ChartEditorPlugin.INSTANCE.getString(key, new Object[] { FORMATTED_FILE_EXTENSIONS })); return false; } setErrorMessage(null); return getInitialObjectName() != null && getEncodings().contains(encodingField.getText()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { initialObjectField.clearSelection(); encodingField.clearSelection(); fileField.setFocus(); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getInitialObjectName() { String label = initialObjectField.getText(); for (String name : getInitialObjectNames()) { if (getLabel(name).equals(label)) { return name; } } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getEncoding() { return encodingField.getText(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public URI getFileURI() { try { return URI.createFileURI(fileField.getText()); } catch (Exception exception) { // Ignore } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void selectFileField() { initialObjectField.clearSelection(); encodingField.clearSelection(); fileField.selectAll(); fileField.setFocus(); } /** * Returns the label for the specified type name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected String getLabel(String typeName) { try { return ChartEditPlugin.INSTANCE.getString("_UI_" + typeName + "_type"); } catch (MissingResourceException mre) { ChartEditorPlugin.INSTANCE.log(mre); } return typeName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<String> getEncodings() { if (encodings == null) { encodings = new ArrayList<String>(); for (StringTokenizer stringTokenizer = new StringTokenizer( ChartEditorPlugin.INSTANCE.getString("_UI_XMLEncodingChoices")); stringTokenizer .hasMoreTokens();) { encodings.add(stringTokenizer.nextToken()); } } return encodings; } } /** * The framework calls this to create the contents of the wizard. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void addPages() { initialObjectCreationPage = new ChartModelWizardInitialObjectCreationPage("Whatever2"); initialObjectCreationPage.setTitle(ChartEditorPlugin.INSTANCE.getString("_UI_ChartModelWizard_label")); initialObjectCreationPage .setDescription(ChartEditorPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description")); addPage(initialObjectCreationPage); } /** * Get the URI from the page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public URI getModelURI() { return initialObjectCreationPage.getFileURI(); } }
3e14ad6a8c83ea9d3f0f7fb28fde4a8ae84f07e7
5,729
java
Java
modules/flowable-event-registry/src/main/java/org/flowable/eventregistry/impl/model/EventModelBuilderImpl.java
poum/flowable-engine
4ee72a8a0328e11a4f5e94cea05ca067655a1c27
[ "Apache-2.0" ]
2
2021-05-27T15:37:45.000Z
2021-05-27T15:38:55.000Z
modules/flowable-event-registry/src/main/java/org/flowable/eventregistry/impl/model/EventModelBuilderImpl.java
poum/flowable-engine
4ee72a8a0328e11a4f5e94cea05ca067655a1c27
[ "Apache-2.0" ]
null
null
null
modules/flowable-event-registry/src/main/java/org/flowable/eventregistry/impl/model/EventModelBuilderImpl.java
poum/flowable-engine
4ee72a8a0328e11a4f5e94cea05ca067655a1c27
[ "Apache-2.0" ]
1
2021-03-08T15:01:24.000Z
2021-03-08T15:01:24.000Z
32.185393
109
0.700646
8,765
/* 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.flowable.eventregistry.impl.model; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.flowable.common.engine.api.FlowableIllegalArgumentException; import org.flowable.eventregistry.api.EventDeployment; import org.flowable.eventregistry.api.model.EventModelBuilder; import org.flowable.eventregistry.impl.EventRepositoryServiceImpl; import org.flowable.eventregistry.json.converter.EventJsonConverter; import org.flowable.eventregistry.model.EventCorrelationParameter; import org.flowable.eventregistry.model.EventModel; import org.flowable.eventregistry.model.EventPayload; /** * @author Joram Barrez */ public class EventModelBuilderImpl implements EventModelBuilder { protected EventRepositoryServiceImpl eventRepository; protected String deploymentName; protected String resourceName; protected String category; protected String parentDeploymentId; protected String tenantId; protected String key; protected Collection<String> inboundChannelKeys; protected Collection<String> outboundChannelKeys; protected Map<String, EventCorrelationParameter> correlationParameterDefinitions = new LinkedHashMap<>(); protected Map<String, EventPayload> eventPayloadDefinitions = new LinkedHashMap<>(); public EventModelBuilderImpl(EventRepositoryServiceImpl eventRepository) { this.eventRepository = eventRepository; } @Override public EventModelBuilder key(String key) { this.key = key; return this; } @Override public EventModelBuilder deploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } @Override public EventModelBuilder resourceName(String resourceName) { this.resourceName = resourceName; return this; } @Override public EventModelBuilder category(String category) { this.category = category; return this; } @Override public EventModelBuilder parentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; return this; } @Override public EventModelBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public EventModelBuilder inboundChannelKey(String channelKey) { if (inboundChannelKeys == null) { inboundChannelKeys = new HashSet<>(); } inboundChannelKeys.add(channelKey); return this; } @Override public EventModelBuilder inboundChannelKeys(Collection<String> channelKeys) { channelKeys.forEach(this::inboundChannelKey); return this; } @Override public EventModelBuilder outboundChannelKey(String channelKey) { if (outboundChannelKeys == null) { outboundChannelKeys = new HashSet<>(); } outboundChannelKeys.add(channelKey); return this; } @Override public EventModelBuilder outboundChannelKeys(Collection<String> channelKeys) { channelKeys.forEach(this::outboundChannelKey); return this; } @Override public EventModelBuilder correlationParameter(String name, String type) { correlationParameterDefinitions.put(name, new EventCorrelationParameter(name, type)); payload(name, type); return this; } @Override public EventModelBuilder payload(String name, String type) { eventPayloadDefinitions.put(name, new EventPayload(name, type)); return this; } @Override public EventModel createEventModel() { return buildEventModel(); } @Override public EventDeployment deploy() { if (resourceName == null) { throw new FlowableIllegalArgumentException("A resource name is mandatory"); } EventModel eventModel = buildEventModel(); EventDeployment eventDeployment = eventRepository.createDeployment() .name(deploymentName) .addEventDefinition(resourceName, new EventJsonConverter().convertToJson(eventModel)) .category(category) .parentDeploymentId(parentDeploymentId) .tenantId(tenantId) .deploy(); return eventDeployment; } protected EventModel buildEventModel() { EventModel eventModel = new EventModel(); if (StringUtils.isNotEmpty(key)) { eventModel.setKey(key); } else { throw new FlowableIllegalArgumentException("An event definition key is mandatory"); } if (inboundChannelKeys != null) { eventModel.setInboundChannelKeys(inboundChannelKeys); } if (outboundChannelKeys != null) { eventModel.setOutboundChannelKeys(outboundChannelKeys); } eventModel.getCorrelationParameters().addAll(correlationParameterDefinitions.values()); eventModel.getPayload().addAll(eventPayloadDefinitions.values()); return eventModel; } }
3e14add6cce1db5e1dcee048cd448d6671251f81
864
java
Java
services/service-openldap/src/main/gui/org/platformlayer/service/openldap/client/LdapServiceEditor.java
eric-erki/Everything-as-a-service
e7a8cdff2aefa658cb41cffdd8c33d19e3b5bc3c
[ "BSD-3-Clause" ]
6
2015-01-16T04:58:49.000Z
2020-12-30T09:24:56.000Z
services/service-openldap/src/main/gui/org/platformlayer/service/openldap/client/LdapServiceEditor.java
platformlayer/platformlayer
e7a8cdff2aefa658cb41cffdd8c33d19e3b5bc3c
[ "BSD-3-Clause" ]
5
2019-11-13T03:01:19.000Z
2021-06-04T00:57:30.000Z
services/service-openldap/src/main/gui/org/platformlayer/service/openldap/client/LdapServiceEditor.java
eric-erki/Everything-as-a-service
e7a8cdff2aefa658cb41cffdd8c33d19e3b5bc3c
[ "BSD-3-Clause" ]
1
2020-12-30T09:24:57.000Z
2020-12-30T09:24:57.000Z
32
86
0.790509
8,766
package org.platformlayer.service.openldap.client; import org.platformlayer.service.openldap.shared.LdapServiceProxy; import com.google.gwt.core.client.GWT; import com.google.gwt.editor.client.Editor; import com.google.gwt.editor.ui.client.ValueBoxEditorDecorator; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; public class LdapServiceEditor extends Composite implements Editor<LdapServiceProxy> { interface Binder extends UiBinder<Widget, LdapServiceEditor> { } @UiField ValueBoxEditorDecorator<String> dnsName; @UiField ValueBoxEditorDecorator<String> ldapServerPassword; public LdapServiceEditor() { initWidget(GWT.<Binder> create(Binder.class).createAndBindUi(this)); } }
3e14af16706f33435bb1c80d0247add5ae5590d6
2,383
java
Java
src/main/java/consumer/kafka/client/KafkaReceiver.java
brkyvz/kafka-spark-consumer
b445749508c65efadf27d1342a54a8e24ff94309
[ "Apache-2.0" ]
null
null
null
src/main/java/consumer/kafka/client/KafkaReceiver.java
brkyvz/kafka-spark-consumer
b445749508c65efadf27d1342a54a8e24ff94309
[ "Apache-2.0" ]
null
null
null
src/main/java/consumer/kafka/client/KafkaReceiver.java
brkyvz/kafka-spark-consumer
b445749508c65efadf27d1342a54a8e24ff94309
[ "Apache-2.0" ]
1
2021-01-13T11:29:46.000Z
2021-01-13T11:29:46.000Z
30.551282
79
0.762484
8,767
/** * 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 consumer.kafka.client; import java.util.Properties; import org.apache.spark.storage.StorageLevel; import org.apache.spark.streaming.receiver.Receiver; import consumer.kafka.KafkaConfig; import consumer.kafka.KafkaConsumer; import consumer.kafka.MessageAndMetadata; import consumer.kafka.ZkState; public class KafkaReceiver extends Receiver<MessageAndMetadata> { private static final long serialVersionUID = -4927707326026616451L; private final Properties _props; private int _partitionId; private KafkaConsumer _kConsumer; private transient Thread _consumerThread; public KafkaReceiver(Properties props, int partitionId) { super(StorageLevel.MEMORY_ONLY()); this._props = props; _partitionId = partitionId; } @Override public void onStart() { start(); } public void start() { // Start the thread that receives data over a connection KafkaConfig kafkaConfig = new KafkaConfig(_props); ZkState zkState = new ZkState(kafkaConfig); _kConsumer = new KafkaConsumer(kafkaConfig, zkState, this); _kConsumer.open(_partitionId); Thread.UncaughtExceptionHandler eh = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { restart("Restarting Receiver for Partition " + _partitionId , ex, 5000); } }; _consumerThread = new Thread(_kConsumer); _consumerThread.setDaemon(true); _consumerThread.setUncaughtExceptionHandler(eh); _consumerThread.start(); } @Override public void onStop() { if(_consumerThread.isAlive()) _consumerThread.interrupt(); } }
3e14b01fa961b3a00b23bf123806ee44dce15e95
6,698
java
Java
spring-security-oauth2/src/test/java/org/springframework/security/oauth2/common/exception/OAuth2ExceptionJackson2DeserializerTests.java
rei/spring-security-oauth
3d37444a991104dd7f23edb2812e9f57620a1395
[ "Apache-2.0" ]
4,409
2015-01-04T04:45:14.000Z
2022-03-27T12:24:04.000Z
spring-security-oauth2/src/test/java/org/springframework/security/oauth2/common/exception/OAuth2ExceptionJackson2DeserializerTests.java
rei/spring-security-oauth
3d37444a991104dd7f23edb2812e9f57620a1395
[ "Apache-2.0" ]
1,594
2015-01-03T00:58:10.000Z
2022-03-31T08:27:31.000Z
spring-security-oauth2/src/test/java/org/springframework/security/oauth2/common/exception/OAuth2ExceptionJackson2DeserializerTests.java
rei/spring-security-oauth
3d37444a991104dd7f23edb2812e9f57620a1395
[ "Apache-2.0" ]
4,158
2015-01-02T08:27:03.000Z
2022-03-31T06:12:39.000Z
40.841463
132
0.782024
8,768
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.springframework.security.oauth2.common.exception; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.security.oauth2.common.exceptions.*; import com.fasterxml.jackson.databind.ObjectMapper; /** * * @author Rob Winch * @author Dave Syer * */ public class OAuth2ExceptionJackson2DeserializerTests { private static final String DETAILS = "some detail"; private static ObjectMapper mapper; @BeforeClass public static void setUpClass() { mapper = new ObjectMapper(); } @Test public void readValueInvalidGrant() throws Exception { String accessToken = createResponse(OAuth2Exception.INVALID_GRANT); InvalidGrantException result = (InvalidGrantException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueInvalidRequest() throws Exception { String accessToken = createResponse(OAuth2Exception.INVALID_REQUEST); InvalidRequestException result = (InvalidRequestException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueInvalidScope() throws Exception { String accessToken = createResponse(OAuth2Exception.INVALID_SCOPE); InvalidScopeException result = (InvalidScopeException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueIsufficientScope() throws Exception { String accessToken = "{\"error\": \"insufficient_scope\", \"error_description\": \"insufficient scope\", \"scope\": \"bar foo\"}"; InsufficientScopeException result = (InsufficientScopeException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals("insufficient scope",result.getMessage()); assertEquals("bar foo",result.getAdditionalInformation().get("scope").toString()); } @Test public void readValueUnsupportedGrantType() throws Exception { String accessToken = createResponse(OAuth2Exception.UNSUPPORTED_GRANT_TYPE); UnsupportedGrantTypeException result = (UnsupportedGrantTypeException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueUnauthorizedClient() throws Exception { String accessToken = createResponse(OAuth2Exception.UNAUTHORIZED_CLIENT); UnauthorizedClientException result = (UnauthorizedClientException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueAccessDenied() throws Exception { String accessToken = createResponse(OAuth2Exception.ACCESS_DENIED); UserDeniedAuthorizationException result = (UserDeniedAuthorizationException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueRedirectUriMismatch() throws Exception { String accessToken = createResponse(OAuth2Exception.INVALID_GRANT, "Redirect URI mismatch."); RedirectMismatchException result = (RedirectMismatchException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals("Redirect URI mismatch.",result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueInvalidToken() throws Exception { String accessToken = createResponse(OAuth2Exception.INVALID_TOKEN); InvalidTokenException result = (InvalidTokenException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueUndefinedException() throws Exception { String accessToken = createResponse("notdefinedcode"); OAuth2Exception result = mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueInvalidClient() throws Exception { String accessToken = createResponse(OAuth2Exception.INVALID_CLIENT); InvalidClientException result = (InvalidClientException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals(null,result.getAdditionalInformation()); } @Test public void readValueWithAdditionalDetails() throws Exception { String accessToken = "{\"error\": \"invalid_client\", \"error_description\": \"some detail\", \"foo\": \"bar\"}"; InvalidClientException result = (InvalidClientException) mapper.readValue(accessToken, OAuth2Exception.class); assertEquals(DETAILS,result.getMessage()); assertEquals("{foo=bar}",result.getAdditionalInformation().toString()); } @Test public void readValueWithObjects() throws Exception { String accessToken = "{\"error\": [\"invalid\",\"client\"], \"error_description\": {\"some\":\"detail\"}, \"foo\": [\"bar\"]}"; OAuth2Exception result = mapper.readValue(accessToken, OAuth2Exception.class); assertEquals("{some=detail}",result.getMessage()); assertEquals("{foo=[bar]}",result.getAdditionalInformation().toString()); } // gh-594 @Test public void readValueWithNullErrorDescription() throws Exception { OAuth2Exception ex = new OAuth2Exception(null); OAuth2Exception result = mapper.readValue(mapper.writeValueAsString(ex), OAuth2Exception.class); // Null error description defaults to error code when deserialized assertEquals(ex.getOAuth2ErrorCode(), result.getMessage()); } private String createResponse(String error, String message) { return "{\"error\":\"" + error + "\",\"error_description\":\""+message+"\"}"; } private String createResponse(String error) { return createResponse(error, DETAILS); } }
3e14b0e75cf890e972764e18f14a6e1b17de68f9
8,312
java
Java
src/org/ojalgo/matrix/decomposition/CholeskyDecomposition.java
shahimclt/ojAlgoAndroid
f394edf79cc3a0766f745aef3f46daee067cdec2
[ "MIT" ]
2
2017-05-14T17:58:12.000Z
2021-03-11T20:09:37.000Z
src/org/ojalgo/matrix/decomposition/CholeskyDecomposition.java
shahimclt/ojAlgoAndroid
f394edf79cc3a0766f745aef3f46daee067cdec2
[ "MIT" ]
null
null
null
src/org/ojalgo/matrix/decomposition/CholeskyDecomposition.java
shahimclt/ojAlgoAndroid
f394edf79cc3a0766f745aef3f46daee067cdec2
[ "MIT" ]
2
2017-04-30T09:13:54.000Z
2017-05-04T00:31:25.000Z
31.366038
118
0.661935
8,769
/* * Copyright 1997-2014 Optimatika (www.optimatika.se) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.ojalgo.matrix.decomposition; import java.math.BigDecimal; import org.ojalgo.access.Access2D; import org.ojalgo.array.BasicArray; import org.ojalgo.function.UnaryFunction; import org.ojalgo.function.aggregator.AggregatorFunction; import org.ojalgo.matrix.MatrixUtils; import org.ojalgo.matrix.jama.JamaCholesky; import org.ojalgo.matrix.store.BigDenseStore; import org.ojalgo.matrix.store.ComplexDenseStore; import org.ojalgo.matrix.store.MatrixStore; import org.ojalgo.matrix.store.PrimitiveDenseStore; import org.ojalgo.scalar.ComplexNumber; import org.ojalgo.type.context.NumberContext; /** * You create instances of (some subclass of) this class by calling one of the static factory methods: * {@linkplain #makeBig()}, {@linkplain #makeComplex()}, {@linkplain #makePrimitive()} or {@linkplain #makeJama()}. * * @author apete */ public abstract class CholeskyDecomposition<N extends Number> extends InPlaceDecomposition<N> implements Cholesky<N> { static final class Big extends CholeskyDecomposition<BigDecimal> { Big() { super(BigDenseStore.FACTORY); } } static final class Complex extends CholeskyDecomposition<ComplexNumber> { Complex() { super(ComplexDenseStore.FACTORY); } } static final class Primitive extends CholeskyDecomposition<Double> { Primitive() { super(PrimitiveDenseStore.FACTORY); } } @SuppressWarnings("unchecked") public static final <N extends Number> Cholesky<N> make(final Access2D<N> aTypical) { final N tmpNumber = aTypical.get(0, 0); if (tmpNumber instanceof BigDecimal) { return (Cholesky<N>) CholeskyDecomposition.makeBig(); } else if (tmpNumber instanceof ComplexNumber) { return (Cholesky<N>) CholeskyDecomposition.makeComplex(); } else if (tmpNumber instanceof Double) { if ((aTypical.countColumns() <= 32) || (aTypical.countColumns() >= 46340)) { //64,16,16 return (Cholesky<N>) CholeskyDecomposition.makeJama(); } else { return (Cholesky<N>) CholeskyDecomposition.makePrimitive(); } } else { throw new IllegalArgumentException(); } } public static final Cholesky<BigDecimal> makeBig() { return new CholeskyDecomposition.Big(); } public static final Cholesky<ComplexNumber> makeComplex() { return new CholeskyDecomposition.Complex(); } public static final Cholesky<Double> makeJama() { return new JamaCholesky(); } public static final Cholesky<Double> makePrimitive() { return new CholeskyDecomposition.Primitive(); } private boolean mySPD = false; protected CholeskyDecomposition(final DecompositionStore.Factory<N, ? extends DecompositionStore<N>> aFactory) { super(aFactory); } public final N calculateDeterminant(final Access2D<N> matrix) { this.compute(matrix); return this.getDeterminant(); } public final boolean compute(final Access2D<?> aStore) { return this.compute(aStore, false); } public final boolean compute(final Access2D<?> matrix, final boolean checkHermitian) { this.reset(); final DecompositionStore<N> tmpInPlace = this.setInPlace(matrix); final int tmpRowDim = this.getRowDim(); final int tmpColDim = this.getColDim(); final int tmpMinDim = Math.min(tmpRowDim, tmpColDim); // true if (Hermitian) Positive Definite boolean tmpPositiveDefinite = tmpRowDim == tmpColDim; final BasicArray<N> tmpMultipliers = this.makeArray(tmpRowDim); // Check if hermitian, maybe if (tmpPositiveDefinite && checkHermitian) { tmpPositiveDefinite &= MatrixUtils.isHermitian(tmpInPlace); } final UnaryFunction<N> tmpSqrtFunc = this.getFunctionSet().sqrt(); // Main loop - along the diagonal for (int ij = 0; tmpPositiveDefinite && (ij < tmpMinDim); ij++) { // Do the calculations... if (tmpInPlace.isPositive(ij, ij)) { tmpInPlace.modifyOne(ij, ij, tmpSqrtFunc); // Calculate multipliers and copy to local column // Current column, below the diagonal tmpInPlace.divideAndCopyColumn(ij, ij, tmpMultipliers); // Remaining columns, below the diagonal tmpInPlace.applyCholesky(ij, tmpMultipliers); } else { tmpPositiveDefinite = false; } } return this.computed(mySPD = tmpPositiveDefinite); } public final boolean equals(final MatrixStore<N> aStore, final NumberContext context) { return MatrixUtils.equals(aStore, this, context); } public N getDeterminant() { final AggregatorFunction<N> tmpAggrFunc = this.getAggregatorCollection().product2(); this.getInPlace().visitDiagonal(0, 0, tmpAggrFunc); return tmpAggrFunc.getNumber(); } @Override public final MatrixStore<N> getInverse() { return this.invert(this.makeEye(this.getColDim(), this.getRowDim())); } @Override public final MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) { preallocated.fillAll(this.getStaticZero()); preallocated.fillDiagonal(0, 0, this.getStaticOne()); return this.invert(preallocated); } public MatrixStore<N> getL() { return this.getInPlace().builder().triangular(false, false).build(); } public final boolean isFullSize() { return true; } public boolean isSolvable() { return this.isComputed() && mySPD; } public boolean isSPD() { return mySPD; } public MatrixStore<N> reconstruct() { return MatrixUtils.reconstruct(this); } @Override public void reset() { super.reset(); mySPD = false; } /** * Solves [this][X] = [aRHS] by first solving * * <pre> * [L][Y] = [aRHS] * </pre> * * and then * * <pre> * [U][X] = [Y] * </pre> * * . * * @param rhs The right hand side * @return [X] The solution will be written to "preallocated" and then returned. * @see org.ojalgo.matrix.decomposition.AbstractDecomposition#solve(Access2D, * org.ojalgo.matrix.decomposition.DecompositionStore) */ @Override public final MatrixStore<N> solve(final Access2D<N> rhs, final DecompositionStore<N> preallocated) { preallocated.fillMatching(rhs); final DecompositionStore<N> tmpBody = this.getInPlace(); preallocated.substituteForwards(tmpBody, false, false); preallocated.substituteBackwards(tmpBody, true); return preallocated; } private final MatrixStore<N> invert(final DecompositionStore<N> retVal) { final DecompositionStore<N> tmpBody = this.getInPlace(); retVal.substituteForwards(tmpBody, false, true); retVal.substituteBackwards(tmpBody, true); return retVal; } }
3e14b1bff7562e30d0d73aeb23477f2ef876663f
727
java
Java
5th_sem_C_Java_VB/Java/number.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
16
2018-11-26T08:39:42.000Z
2019-05-08T10:09:52.000Z
5th_sem_C_Java_VB/Java/number.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
8
2020-05-04T06:29:26.000Z
2022-02-12T05:33:16.000Z
5th_sem_C_Java_VB/Java/number.java
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
5
2020-02-11T16:02:21.000Z
2021-02-05T07:48:30.000Z
21.382353
78
0.456671
8,770
import java.io.*; class number { public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s; int l,f,fa,i,na; long n=0; System.out.print("Enter a number = "); s=br.readLine(); l=s.length(); fa=s.charAt(0)-48; f=fa; if(fa<l) { for(i=1;i<=fa;i++) { na=s.charAt(i)-48; n=n+na*(long)Math.pow(10,--f); } } else { f=l-1; for(i=1;i<l;i++) { na=s.charAt(i)-48; n=n+na*(long)Math.pow(10,--f); } } System.out.println("The number "+n+" * 3 = "+n*3); } }
3e14b1d5fa1d428abf18481339e25550c62e6af6
1,399
java
Java
FMS SPRING/StudentUserService/src/main/java/com/cg/feedback/student_user/dto/NewStudentDTO.java
Amangoel998/Feedback-Management-Microservice
0778dc9e4c8ec29a41d6f897eb688622a4df2d89
[ "MIT" ]
null
null
null
FMS SPRING/StudentUserService/src/main/java/com/cg/feedback/student_user/dto/NewStudentDTO.java
Amangoel998/Feedback-Management-Microservice
0778dc9e4c8ec29a41d6f897eb688622a4df2d89
[ "MIT" ]
1
2022-03-02T08:39:47.000Z
2022-03-02T08:39:47.000Z
FMS SPRING/StudentUserService/src/main/java/com/cg/feedback/student_user/dto/NewStudentDTO.java
Amangoel998/Feedback-Management-Microservice
0778dc9e4c8ec29a41d6f897eb688622a4df2d89
[ "MIT" ]
null
null
null
22.564516
119
0.651894
8,771
package com.cg.feedback.student_user.dto; public class NewStudentDTO { private String studentId; private String studentName; private String studentEmail; private String studentPass; private String batch; public NewStudentDTO() { } public NewStudentDTO(String studentId, String studentName, String studentEmail, String studentPass, String batch) { this.studentId = studentId; this.studentName = studentName; this.studentEmail = studentEmail; this.studentPass = studentPass; this.batch = batch; } public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentEmail() { return studentEmail; } public void setStudentEmail(String studentEmail) { this.studentEmail = studentEmail; } public String getStudentPass() { return studentPass; } public void setStudentPass(String studentPass) { this.studentPass = studentPass; } public String getBatch() { return batch; } public void setBatch(String batch) { this.batch = batch; } }
3e14b35b50baf89ad9f627ab013b47b0a368e3db
1,789
java
Java
_src/Chapter04/beosbank-datagrid-labs/src/main/java/com/beosbank/jbdevg/jbdatagrid/EmbeddedCacheListenerDemo.java
paullewallencom/jboss-978-1-7882-9619-9
2eca826d021cba64453e5d863e19e078f0589ca2
[ "Apache-2.0" ]
7
2017-09-12T19:19:30.000Z
2021-11-08T13:10:36.000Z
_src/Chapter04/beosbank-datagrid-labs/src/main/java/com/beosbank/jbdevg/jbdatagrid/EmbeddedCacheListenerDemo.java
paullewallencom/jboss-978-1-7882-9619-9
2eca826d021cba64453e5d863e19e078f0589ca2
[ "Apache-2.0" ]
null
null
null
_src/Chapter04/beosbank-datagrid-labs/src/main/java/com/beosbank/jbdevg/jbdatagrid/EmbeddedCacheListenerDemo.java
paullewallencom/jboss-978-1-7882-9619-9
2eca826d021cba64453e5d863e19e078f0589ca2
[ "Apache-2.0" ]
1
2017-10-18T20:48:16.000Z
2017-10-18T20:48:16.000Z
30.844828
96
0.743432
8,772
package com.beosbank.jbdevg.jbdatagrid; import java.io.File; import java.io.IOException; import org.beanio.StreamFactory; import org.beanio.Unmarshaller; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import com.beosbank.jbdevg.jbdatagrid.domain.MoneyTransfert; import com.beosbank.jbdevg.jbdatagrid.listener.DatagridListener; import com.mchange.io.FileUtils; public class EmbeddedCacheListenerDemo { private static final String INPUT_DIR = "src/main/resources/input/"; public static void main(String[] args) { String[] inputFileNames = { "data1.xml", "data2.xml", "data3.xml", "data4.xml", "data5.xml" }; // Create a Money Transfer Object from XML Message using BeaoIO API try { StreamFactory factory = StreamFactory.newInstance(); factory.loadResource("mapping.xml"); Unmarshaller unmarshaller = factory.createUnmarshaller("MoneyTransferStream"); String record; ConfigurationBuilder builder = new ConfigurationBuilder(); Cache<String, Object> cache = new DefaultCacheManager(builder.build()).getCache(); cache.addListener(new DatagridListener()); //Read Transactions and put in cache for (String inputFile : inputFileNames) { record = FileUtils.getContentsAsString(new File(INPUT_DIR + inputFile)); MoneyTransfert mt = (MoneyTransfert) unmarshaller.unmarshal(record); cache.put(mt.getId() + "", mt); } //Inspect the cache . System.out.println(cache.size()); System.out.println(cache.getStatus()); System.out.println(cache.get("3")); //Stop the cache cache.stop(); System.out.println(cache.getStatus()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3e14b3bae39502c543d9543aa6227ebec2932f22
818
java
Java
TaskSchedulerCommons/src/main/java/org/dixantmittal/exception/InternalServerException.java
dixantmittal/scalable-task-scheduler
746982fab54c67283d514ccedead25cf2e7ced9b
[ "MIT" ]
6
2017-11-16T04:54:38.000Z
2022-03-10T09:09:25.000Z
TaskSchedulerCommons/src/main/java/org/dixantmittal/exception/InternalServerException.java
dixantmittal/scalable-task-scheduler
746982fab54c67283d514ccedead25cf2e7ced9b
[ "MIT" ]
null
null
null
TaskSchedulerCommons/src/main/java/org/dixantmittal/exception/InternalServerException.java
dixantmittal/scalable-task-scheduler
746982fab54c67283d514ccedead25cf2e7ced9b
[ "MIT" ]
1
2019-02-16T05:04:29.000Z
2019-02-16T05:04:29.000Z
31.461538
82
0.722494
8,773
package org.dixantmittal.exception; import org.dixantmittal.exception.codes.CommonExceptionCodes; public class InternalServerException extends GenericException { public InternalServerException(String errCode, String errMsg) { super(errCode, errMsg); } public InternalServerException(Throwable cause) { super(CommonExceptionCodes.INTERNAL_SERVER_EXCEPTION.code(), CommonExceptionCodes.INTERNAL_SERVER_EXCEPTION.message(), cause); } public InternalServerException() { super(CommonExceptionCodes.INTERNAL_SERVER_EXCEPTION.code(), CommonExceptionCodes.INTERNAL_SERVER_EXCEPTION.message()); } public InternalServerException(String code, String message, Throwable cause) { super(code, message, cause); } }
3e14b441fd807b4ba27bb2f5d7999508a57568f1
1,728
java
Java
modules/core/src/main/java/org/gridgain/grid/ggfs/GridGgfsParentNotDirectoryException.java
gridgentoo/gridgain
735b7859d9f87e74a06172bd7847b7db418fcb83
[ "Apache-2.0" ]
1
2019-04-22T08:48:55.000Z
2019-04-22T08:48:55.000Z
modules/core/src/main/java/org/gridgain/grid/ggfs/GridGgfsParentNotDirectoryException.java
cybernetics/gridgain
39f3819c9769b04caca62b263581c0458f21c4d6
[ "Apache-2.0" ]
null
null
null
modules/core/src/main/java/org/gridgain/grid/ggfs/GridGgfsParentNotDirectoryException.java
cybernetics/gridgain
39f3819c9769b04caca62b263581c0458f21c4d6
[ "Apache-2.0" ]
null
null
null
30.315789
87
0.648727
8,774
/* Copyright (C) GridGain Systems. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.ggfs; import org.jetbrains.annotations.*; /** * Exception thrown when parent supposed to be a directory is a file. */ public class GridGgfsParentNotDirectoryException extends GridGgfsInvalidPathException { /** */ private static final long serialVersionUID = 0L; /** * @param msg Error message. */ public GridGgfsParentNotDirectoryException(String msg) { super(msg); } /** * @param cause Exception cause. */ public GridGgfsParentNotDirectoryException(Throwable cause) { super(cause); } /** * @param msg Error message. * @param cause Exception cause. */ public GridGgfsParentNotDirectoryException(String msg, @Nullable Throwable cause) { super(msg, cause); } }
3e14b4fab0339949035fb16becc9995f1f6a66e9
2,442
java
Java
mongodb/src/main/java/info/Mr/Yang/mongodb/controller/ProductController.java
hezijian6338/Mr.Yang
c24609997133166b23d0d0cc08c589a4a67d79af
[ "MIT" ]
null
null
null
mongodb/src/main/java/info/Mr/Yang/mongodb/controller/ProductController.java
hezijian6338/Mr.Yang
c24609997133166b23d0d0cc08c589a4a67d79af
[ "MIT" ]
null
null
null
mongodb/src/main/java/info/Mr/Yang/mongodb/controller/ProductController.java
hezijian6338/Mr.Yang
c24609997133166b23d0d0cc08c589a4a67d79af
[ "MIT" ]
null
null
null
30.924051
123
0.704462
8,775
package info.Mr.Yang.mongodb.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import info.Mr.Yang.core.base.Result; import info.Mr.Yang.core.constant.CodeConst; import info.Mr.Yang.mongodb.model.Product; import info.Mr.Yang.mongodb.service.ProductService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * 把今天最好的表现当作明天最新的起点..~ * いま 最高の表現 として 明日最新の始発..~ * Today the best performance as tomorrow newest starter! * Created by IntelliJ IDEA. * * @author : xiaomo * github: https://github.com/xiaomoinfo * email: kenaa@example.com * <p> * Date: 2016/11/15 15:49 * Copyright(©) 2015 by xiaomo. **/ @RestController @RequestMapping("product") @Api("产品信息操作Api") public class ProductController { private final ProductService service; @Autowired public ProductController(ProductService service) { this.service = service; } @RequestMapping(value = "{id}", method = RequestMethod.GET) public Result get(@PathVariable("id") String id) { Product product = service.findById(id); return new Result<>(product); } @RequestMapping(value = "findAll", method = RequestMethod.GET) public Result findAll(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) { PageHelper.startPage(page, size); PageInfo pageInfo = new PageInfo(service.findAll()); return new Result<>(pageInfo); } @RequestMapping(value = "add", method = RequestMethod.POST) public Result add(@RequestBody Product product) { // product.setImg(file); return new Result<>(service.add(product)); } @RequestMapping(value = "delete/{id}", method = RequestMethod.GET) public Result delete(@PathVariable("id") String id) { service.delete(id); return new Result(CodeConst.SUCCESS.getResultCode(), CodeConst.SUCCESS.getMessage()); } @ApiOperation(value = "根据id更新具体的键值对") @RequestMapping(value = "{id}", method = RequestMethod.PATCH) public Result update(@PathVariable("id") String id, @RequestBody Map updateFieldMap) { service.update(id, updateFieldMap); return new Result(CodeConst.SUCCESS.getResultCode(), CodeConst.SUCCESS.getMessage()); } }
3e14b4fad19ae25fd80181f153dd9da91e4017ef
7,546
java
Java
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/fragments/MyDownloadAdapter.java
YouKnowWhoIAmD/SmartIndiaHackathonD
998c8b7c38b5a6ca341ef256dae364015c15a7f3
[ "MIT" ]
2
2022-01-07T22:45:53.000Z
2022-01-08T05:46:51.000Z
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/fragments/MyDownloadAdapter.java
YouKnowWhoIAmD/SmartIndiaHackathonD
998c8b7c38b5a6ca341ef256dae364015c15a7f3
[ "MIT" ]
null
null
null
PocketMaps/app/src/main/java/com/junjunguo/pocketmaps/fragments/MyDownloadAdapter.java
YouKnowWhoIAmD/SmartIndiaHackathonD
998c8b7c38b5a6ca341ef256dae364015c15a7f3
[ "MIT" ]
null
null
null
36.631068
121
0.609992
8,776
package com.junjunguo.pocketmaps.fragments; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.junjunguo.pocketmaps.R; import com.junjunguo.pocketmaps.model.MyMap; import com.junjunguo.pocketmaps.model.listeners.MapFABonClickListener; import com.junjunguo.pocketmaps.model.listeners.OnDownloadingListener; import com.junjunguo.pocketmaps.util.Constant; import com.junjunguo.pocketmaps.util.Variable; import java.util.List; /** * This file is part of PocketMaps * <p/> * Created by GuoJunjun <junjunguo.com> on July 04, 2015. */ public class MyDownloadAdapter extends RecyclerView.Adapter<MyDownloadAdapter.ViewHolder> { private List<MyMap> myMaps; private MapFABonClickListener mapFABonClick; OnDownloadingListener dlListener; // private int downloadingPosition; public static class ViewHolder extends RecyclerView.ViewHolder { public FloatingActionButton flag; public TextView name, continent, size, downloadStatus; public ProgressBar progressBar; public MapFABonClickListener mapFABonClick; OnDownloadingListener dlListener; public ViewHolder(View itemView, MapFABonClickListener mapFABonClick, OnDownloadingListener dlListener) { super(itemView); this.mapFABonClick = mapFABonClick; this.dlListener = dlListener; this.flag = (FloatingActionButton) itemView.findViewById(R.id.my_download_item_flag); this.name = (TextView) itemView.findViewById(R.id.my_download_item_name); this.continent = (TextView) itemView.findViewById(R.id.my_download_item_continent); this.size = (TextView) itemView.findViewById(R.id.my_download_item_size); this.downloadStatus = (TextView) itemView.findViewById(R.id.my_download_item_download_status); this.progressBar = (ProgressBar) itemView.findViewById(R.id.my_download_item_progress_bar); } public void setItemData(MyMap myMap) { int status = myMap.getStatus(); switch (status) { case Constant.DOWNLOADING: { flag.setImageResource(R.drawable.ic_pause_orange_24dp); downloadStatus.setText("Downloading ..." + String.format("%1$" + 3 + "s", Variable.getVariable().getMapFinishedPercentage()) + "%"); progressBar.setVisibility(View.VISIBLE); // progressBar.setProgress(Variable.getVariable().getMapFinishedPercentage()); dlListener.progressbarReady(downloadStatus, progressBar, getAdapterPosition()); break; } case Constant.COMPLETE: { if (myMap.isUpdateAvailable()) { flag.setImageResource(R.drawable.ic_cloud_download_white_24dp); } else { flag.setImageResource(R.drawable.ic_map_white_24dp); } downloadStatus.setText("Downloaded"); progressBar.setVisibility(View.INVISIBLE); break; } case Constant.PAUSE: { flag.setImageResource(R.drawable.ic_play_arrow_light_green_a700_24dp); downloadStatus.setText("Paused ..." + String.format("%1$" + 3 + "s", Variable.getVariable().getMapFinishedPercentage()) + "%"); progressBar.setVisibility(View.VISIBLE); // progressBar.setProgress(Variable.getVariable().getMapFinishedPercentage()); dlListener.progressbarReady(downloadStatus, progressBar, getAdapterPosition()); break; } default: { flag.setImageResource(R.drawable.ic_cloud_download_white_24dp); downloadStatus.setText(""); progressBar.setVisibility(View.INVISIBLE); break; } } name.setText(myMap.getCountry()); continent.setText(myMap.getContinent()); size.setText(myMap.getSize()); flag.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mapFABonClick.mapFABonClick(itemView, ViewHolder.this.getAdapterPosition()); } }); } } // Provide a suitable constructor (depends on the kind of dataset) public MyDownloadAdapter(List<MyMap> myMaps, MapFABonClickListener mapFABonClick, OnDownloadingListener dlListener) { this.myMaps = myMaps; this.mapFABonClick = mapFABonClick; this.dlListener = dlListener; // downloadingPosition = 999; } // Create new views (invoked by the layout manager) @Override public MyDownloadAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_download_item, parent, false); ViewHolder vh = new ViewHolder(v, mapFABonClick, dlListener); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element holder.setItemData(myMaps.get(position)); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return myMaps.size(); } /** * @param position index * @return MyMap item at the position */ public MyMap getItem(int position) { return myMaps.get(position); } /** * get MyMap object position by its mapName variable * * @param mapName map name * @return -1 if not found; */ public int getPosition(String mapName) { for (int i = 0; i < myMaps.size(); i++) { if (myMaps.get(i).getMapName().equalsIgnoreCase(mapName)) { return i; } } return -1; } /** * remove item at the given position * * @param position index */ public MyMap remove(int position) { MyMap mm = null; if (position >= 0 && position < getItemCount()) { mm = myMaps.remove(position); notifyItemRemoved(position); } return mm; } /** * clear the list (remove all elements) */ public void clearList() { this.myMaps.clear(); } /** * add a list of MyMap * * @param maps list of MyMap */ public void addAll(List<MyMap> maps) { this.myMaps.addAll(maps); notifyItemRangeInserted(myMaps.size() - maps.size(), maps.size()); } /** * insert the object to the end of the list * * @param myMap MyMap */ public void insert(MyMap myMap) { myMaps.add(0, myMap); notifyItemInserted(0); } /** * @return MyMaps list */ public List<MyMap> getMaps() { return myMaps; } }
3e14b5837da18e9096f188d01c48b3844b8e6fb0
1,646
java
Java
plugins/git4idea/src/git4idea/commands/GitHttpAuthenticator.java
liveqmock/platform-tools-idea
1c4b76108add6110898a7e3f8f70b970e352d3d4
[ "Apache-2.0" ]
2
2015-05-08T15:07:10.000Z
2022-03-09T05:47:53.000Z
plugins/git4idea/src/git4idea/commands/GitHttpAuthenticator.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
null
null
null
plugins/git4idea/src/git4idea/commands/GitHttpAuthenticator.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
2
2017-04-24T15:48:40.000Z
2022-03-09T05:48:05.000Z
29.927273
99
0.719927
8,777
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.commands; import org.jetbrains.annotations.NotNull; /** * Performs HTTP authentication, i. e. handles "ask username" and "ask password" requests from Git: * * @author Kirill Likhodedov */ public interface GitHttpAuthenticator { /** * Asks the password to access the specified URL. * @param url URL which needs authentication. * @return Password to access the URL. */ @NotNull String askPassword(@NotNull String url); /** * Asks the username to access the specified URL. Password request will follow. * @param url URL which needs authentication, without username in it. * @return Username to access the URL. */ @NotNull String askUsername(@NotNull String url); /** * Saves the entered username and password to the database for the future access. * This is called when authentication succeeds. */ void saveAuthData(); /** * Makes sure the entered password is removed from the database. * This is called when authentication fails. */ void forgetPassword(); }
3e14b64f814d0737448a42a04a0319b12c15c513
908
java
Java
src/main/java/cn/yuan/blog/domain/Blog.java
yuanjs2019/yn-manage-system
390a585919ddcc56d5ac651060f977b59bcfc3be
[ "Apache-2.0" ]
2
2020-11-28T01:50:02.000Z
2021-06-24T07:32:54.000Z
src/main/java/cn/yuan/blog/domain/Blog.java
yuanjs2019/yn-manage-system
390a585919ddcc56d5ac651060f977b59bcfc3be
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/yuan/blog/domain/Blog.java
yuanjs2019/yn-manage-system
390a585919ddcc56d5ac651060f977b59bcfc3be
[ "Apache-2.0" ]
1
2020-11-28T09:21:31.000Z
2020-11-28T09:21:31.000Z
17.803922
60
0.620044
8,778
package cn.yuan.blog.domain; import java.io.Serializable; import java.util.List; /** * 实体对象BLOG. * * @author yjs * @since 2020-10-26 */ public class Blog extends BaseBlog implements Serializable { private static final long serialVersionUID = 1L; private String seriesName; /** * 查询时返回的标签 */ private List<Tag> tags; /** * 查询时返回的分类 */ private List<Classify> classifies; public String getSeriesName() { return seriesName; } public void setSeriesName(String seriesName) { this.seriesName = seriesName; } public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public List<Classify> getClassifies() { return classifies; } public void setClassifies(List<Classify> classifies) { this.classifies = classifies; } }
3e14b71ae00f411bf5da3eae858f7b7cf1f930c4
1,618
java
Java
CS5200-Database-Management-System/Assignment-3/cs5200_fall2018_tian_jiyu_jdbc/src/main/java/edu/northeastern/cs5200/models/User.java
tjyiiuan/Graduate-Courses
7f8b018dc92431d8f054a38e1a7fd2c284e1cce0
[ "MIT" ]
null
null
null
CS5200-Database-Management-System/Assignment-3/cs5200_fall2018_tian_jiyu_jdbc/src/main/java/edu/northeastern/cs5200/models/User.java
tjyiiuan/Graduate-Courses
7f8b018dc92431d8f054a38e1a7fd2c284e1cce0
[ "MIT" ]
null
null
null
CS5200-Database-Management-System/Assignment-3/cs5200_fall2018_tian_jiyu_jdbc/src/main/java/edu/northeastern/cs5200/models/User.java
tjyiiuan/Graduate-Courses
7f8b018dc92431d8f054a38e1a7fd2c284e1cce0
[ "MIT" ]
null
null
null
27.423729
154
0.745365
8,779
package edu.northeastern.cs5200.models; import java.sql.Date; public class User extends Person { private String userKey; private boolean userAgreement; public User() { super(); } public User(int id, String firstName, String lastName, String username, String password, String email, Date dob, String userKey, boolean userAgreement) { super(id, firstName, lastName, username, password, email, dob); this.userKey = userKey; this.userAgreement= userAgreement; } public User(String firstName, String lastName, String username, String password, String email, String userKey, boolean userAgreement) { super(firstName, lastName, username, password, email); this.userKey = userKey; this.userAgreement= userAgreement; } public User(String firstName, String lastName, String username, String password, String email, boolean userAgreement) { super(firstName, lastName, username, password, email); this.userAgreement= userAgreement; } public User(int id, String firstName, String lastName, String username, String password, String email) { super(id, firstName, lastName, username, password, email, null); this.userAgreement= false; } public User(int id, String firstName, String lastName) { super(id, firstName, lastName); this.userKey = "undefined"; this.userAgreement= false; } public String getUserKey() { return userKey; } public void setUserKey(String userKey) { this.userKey = userKey; } public boolean isUserAgreement() { return userAgreement; } public void setUserAgreement(boolean userAgreement) { this.userAgreement = userAgreement; } }
3e14b73b03bdb6a676de9e9972bf6f1ab49ad58d
2,564
java
Java
src/servlets/ShelterServlet.java
nick-paul/INN
aa977ff54f06c968fbb7c1f1b7f09e7520a0223d
[ "MIT" ]
null
null
null
src/servlets/ShelterServlet.java
nick-paul/INN
aa977ff54f06c968fbb7c1f1b7f09e7520a0223d
[ "MIT" ]
null
null
null
src/servlets/ShelterServlet.java
nick-paul/INN
aa977ff54f06c968fbb7c1f1b7f09e7520a0223d
[ "MIT" ]
null
null
null
30.164706
121
0.649766
8,780
package servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import controllers.ShelterController; public class ShelterServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ShelterServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); return; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); return; } /* * The processRequest() method is were we will be doing the decision-making * */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //First, we get the command that the client has sent to the server String command = request.getParameter("command"); command = command == null ? "" : command; //This is the jsp page that we will forward the user to after we have done // any computations that we need String forwardToPage = "home.jsp"; //Based on the command, we will decide what to do switch(command) { case "newShelter": forwardToPage = ShelterController.newShelter(request); break; case "updateShelter": forwardToPage = ShelterController.updateShelter(request); break; case "getAllShelters": forwardToPage=ShelterController.getAllShelters(request); break; case "shelterLogin": forwardToPage = ShelterController.getShelterLogin(request); break; case "viewDashboard": forwardToPage = ShelterController.getViewDashBoard(request); break; case "clearClient": forwardToPage = ShelterController.getClearClient(request); break; default: //Default, return back to the home page forwardToPage = "home.jsp"; } //Redirect the user if(!response.isCommitted()) { request.getRequestDispatcher(forwardToPage).forward(request, response); } return; } }
3e14b7adc176fc63d6f6f534e25b0b4caffe650f
283
java
Java
src/main/java/tasklists/models/Task.java
amgs-ual/aas-tasklists
1d5ba6281babd0e5b62d5da59f40396b026f2e65
[ "BSD-3-Clause" ]
null
null
null
src/main/java/tasklists/models/Task.java
amgs-ual/aas-tasklists
1d5ba6281babd0e5b62d5da59f40396b026f2e65
[ "BSD-3-Clause" ]
1
2022-01-21T23:44:05.000Z
2022-01-21T23:44:05.000Z
src/main/java/tasklists/models/Task.java
amgs-ual/aas-tasklists
1d5ba6281babd0e5b62d5da59f40396b026f2e65
[ "BSD-3-Clause" ]
null
null
null
14.894737
46
0.713781
8,781
package tasklists.models; import javax.json.JsonObjectBuilder; public interface Task { String getDescription(); String getStatus(); int getId(); void setDescription(String taskDescription); void toggle(); JsonObjectBuilder getJsonObjectBuilder(); }
3e14b7c8f58c3dfd7805132e54bada9df133dfac
3,400
java
Java
src/java/fr/paris/lutece/portal/business/dashboard/AdminDashboardFilter.java
DiogoSobralCapgemini/lutece-core
da9efa1737ed47a004c6fe2dfac94f5b3b232a76
[ "BSD-3-Clause" ]
1
2020-05-14T13:36:30.000Z
2020-05-14T13:36:30.000Z
src/java/fr/paris/lutece/portal/business/dashboard/AdminDashboardFilter.java
DiogoSobralCapgemini/lutece-core
da9efa1737ed47a004c6fe2dfac94f5b3b232a76
[ "BSD-3-Clause" ]
null
null
null
src/java/fr/paris/lutece/portal/business/dashboard/AdminDashboardFilter.java
DiogoSobralCapgemini/lutece-core
da9efa1737ed47a004c6fe2dfac94f5b3b232a76
[ "BSD-3-Clause" ]
null
null
null
29.059829
127
0.626176
8,782
/* * Copyright (c) 2002-2017, Mairie de Paris * All rights reserved. * * 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 * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.portal.business.dashboard; /** * Admin Dashboard filter * */ public class AdminDashboardFilter { private Integer _nFilterColumn; private Integer _nFilterOrder; /** * Filter column * * @return Filter column */ public Integer getFilterColumn( ) { return _nFilterColumn; } /** * Filter column * * @param nFilterColumn * the Filter column */ public void setFilterColumn( Integer nFilterColumn ) { _nFilterColumn = nFilterColumn; } /** * Filter order * * @return Filter order */ public Integer getFilterOrder( ) { return _nFilterOrder; } /** * Filter order * * @param nFilterOrder * the Filter order */ public void setFilterOrder( Integer nFilterOrder ) { _nFilterOrder = nFilterOrder; } /** * true if {@link #getFilterOrder()} != null * * @return <code>true</code> if {@link #getFilterOrder()} != null, <code>false</code> otherwise. */ public boolean containsFilterOrder( ) { return _nFilterOrder != null; } /** * true if {@link #getFilterColumn()} != null * * @return <code>true</code> if {@link #getFilterColumn()} != null, <code>false</code> otherwise */ public boolean containsFilterColumn( ) { return _nFilterColumn != null; } /** * * {@inheritDoc} */ @Override public String toString( ) { return this.getClass( ).getName( ) + "[column=" + this.getFilterColumn( ) + ", order=" + this.getFilterOrder( ) + "]"; } }
3e14b7e947b887c248e1f56920bd6ae324a8b32d
664
java
Java
jnc-runtime/src/test/java/jnc/foreign/GetPidTest.java
java-native-call/jnc
5fd9a08142650f40b95c4ddc8bb7b8de9d89476a
[ "Apache-2.0" ]
1
2022-01-17T10:17:22.000Z
2022-01-17T10:17:22.000Z
jnc-runtime/src/test/java/jnc/foreign/GetPidTest.java
java-native-call/jnc
5fd9a08142650f40b95c4ddc8bb7b8de9d89476a
[ "Apache-2.0" ]
10
2019-06-01T14:16:50.000Z
2020-10-13T05:08:39.000Z
jnc-runtime/src/test/java/jnc/foreign/GetPidTest.java
java-native-call/jnc
5fd9a08142650f40b95c4ddc8bb7b8de9d89476a
[ "Apache-2.0" ]
2
2019-06-08T07:03:28.000Z
2022-01-13T23:50:53.000Z
20.121212
106
0.631024
8,783
package jnc.foreign; import jnc.foreign.typedef.pid_t; import static org.junit.Assume.assumeFalse; import org.junit.Before; import org.junit.Test; public class GetPidTest { @Before public void setUp() { assumeFalse("os.name", Platform.getNativePlatform().getOS().isWindows()); } @Test public void test() { for (int i = 0; i < 2000000; ++i) { LibC.INSTANCE.getpid(); } } @SuppressWarnings("UnusedReturnValue") private interface LibC { LibC INSTANCE = LibraryLoader.create(LibC.class).load(Platform.getNativePlatform().getLibcName()); @pid_t long getpid(); } }
3e14b8a6488ffc32475e50d0904cd4370731678d
12,826
java
Java
hbase-server/src/test/java/org/apache/hadoop/hbase/quotas/TestQuotaStatusRPCs.java
mahuacai/hbase
f4f2b68238a094d7b1931dc8b7939742ccbb2b57
[ "Apache-2.0" ]
2
2020-08-03T15:53:04.000Z
2020-08-27T10:14:50.000Z
hbase-server/src/test/java/org/apache/hadoop/hbase/quotas/TestQuotaStatusRPCs.java
mahuacai/hbase
f4f2b68238a094d7b1931dc8b7939742ccbb2b57
[ "Apache-2.0" ]
131
2019-01-25T07:53:30.000Z
2021-07-07T07:17:14.000Z
hbase-server/src/test/java/org/apache/hadoop/hbase/quotas/TestQuotaStatusRPCs.java
mahuacai/hbase
f4f2b68238a094d7b1931dc8b7939742ccbb2b57
[ "Apache-2.0" ]
3
2018-09-18T09:15:49.000Z
2019-05-21T08:27:29.000Z
41.108974
102
0.718307
8,784
/** * 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.hadoop.hbase.quotas; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.Waiter; import org.apache.hadoop.hbase.Waiter.Predicate; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException; import org.apache.hadoop.hbase.master.HMaster; import org.apache.hadoop.hbase.quotas.SpaceQuotaSnapshot.SpaceQuotaStatus; import org.apache.hadoop.hbase.quotas.policies.MissingSnapshotViolationPolicyEnforcement; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Test class for the quota status RPCs in the master and regionserver. */ @Category({MediumTests.class}) public class TestQuotaStatusRPCs { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestQuotaStatusRPCs.class); private static final Logger LOG = LoggerFactory.getLogger(TestQuotaStatusRPCs.class); private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private static final AtomicLong COUNTER = new AtomicLong(0); @Rule public TestName testName = new TestName(); private SpaceQuotaHelperForTests helper; @BeforeClass public static void setUp() throws Exception { Configuration conf = TEST_UTIL.getConfiguration(); // Increase the frequency of some of the chores for responsiveness of the test SpaceQuotaHelperForTests.updateConfigForQuotas(conf); TEST_UTIL.startMiniCluster(1); } @AfterClass public static void tearDown() throws Exception { TEST_UTIL.shutdownMiniCluster(); } @Before public void setupForTest() throws Exception { helper = new SpaceQuotaHelperForTests(TEST_UTIL, testName, COUNTER); } @Test public void testRegionSizesFromMaster() throws Exception { final long tableSize = 1024L * 10L; // 10KB final int numRegions = 10; final TableName tn = helper.createTableWithRegions(numRegions); // Will write at least `tableSize` data helper.writeData(tn, tableSize); final HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster(); final MasterQuotaManager quotaManager = master.getMasterQuotaManager(); // Make sure the master has all of the reports Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() { @Override public boolean evaluate() throws Exception { Map<RegionInfo,Long> regionSizes = quotaManager.snapshotRegionSizes(); LOG.trace("Region sizes=" + regionSizes); return numRegions == countRegionsForTable(tn, regionSizes) && tableSize <= getTableSize(tn, regionSizes); } }); Map<TableName,Long> sizes = QuotaTableUtil.getMasterReportedTableSizes(TEST_UTIL.getConnection()); Long size = sizes.get(tn); assertNotNull("No reported size for " + tn, size); assertTrue("Reported table size was " + size, size.longValue() >= tableSize); } @Test public void testQuotaSnapshotsFromRS() throws Exception { final long sizeLimit = 1024L * 1024L; // 1MB final long tableSize = 1024L * 10L; // 10KB final int numRegions = 10; final TableName tn = helper.createTableWithRegions(numRegions); // Define the quota QuotaSettings settings = QuotaSettingsFactory.limitTableSpace( tn, sizeLimit, SpaceViolationPolicy.NO_INSERTS); TEST_UTIL.getAdmin().setQuota(settings); // Write at least `tableSize` data helper.writeData(tn, tableSize); final HRegionServer rs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0); final RegionServerSpaceQuotaManager manager = rs.getRegionServerSpaceQuotaManager(); Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() { @Override public boolean evaluate() throws Exception { SpaceQuotaSnapshot snapshot = manager.copyQuotaSnapshots().get(tn); if (snapshot == null) { return false; } return snapshot.getUsage() >= tableSize; } }); Map<TableName, SpaceQuotaSnapshot> snapshots = QuotaTableUtil.getRegionServerQuotaSnapshots( TEST_UTIL.getConnection(), rs.getServerName()); SpaceQuotaSnapshot snapshot = snapshots.get(tn); assertNotNull("Did not find snapshot for " + tn, snapshot); assertTrue( "Observed table usage was " + snapshot.getUsage(), snapshot.getUsage() >= tableSize); assertEquals(sizeLimit, snapshot.getLimit()); SpaceQuotaStatus pbStatus = snapshot.getQuotaStatus(); assertFalse(pbStatus.isInViolation()); } @Test public void testQuotaEnforcementsFromRS() throws Exception { final long sizeLimit = 1024L * 8L; // 8KB final long tableSize = 1024L * 10L; // 10KB final int numRegions = 10; final TableName tn = helper.createTableWithRegions(numRegions); // Define the quota QuotaSettings settings = QuotaSettingsFactory.limitTableSpace( tn, sizeLimit, SpaceViolationPolicy.NO_INSERTS); TEST_UTIL.getAdmin().setQuota(settings); // Write at least `tableSize` data try { helper.writeData(tn, tableSize); } catch (RetriesExhaustedWithDetailsException | SpaceLimitingException e) { // Pass } final HRegionServer rs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0); final RegionServerSpaceQuotaManager manager = rs.getRegionServerSpaceQuotaManager(); Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() { @Override public boolean evaluate() throws Exception { ActivePolicyEnforcement enforcements = manager.getActiveEnforcements(); SpaceViolationPolicyEnforcement enforcement = enforcements.getPolicyEnforcement(tn); // Signifies that we're waiting on the quota snapshot to be fetched if (enforcement instanceof MissingSnapshotViolationPolicyEnforcement) { return false; } return enforcement.getQuotaSnapshot().getQuotaStatus().isInViolation(); } }); // We obtain the violations for a RegionServer by observing the snapshots Map<TableName,SpaceQuotaSnapshot> snapshots = QuotaTableUtil.getRegionServerQuotaSnapshots(TEST_UTIL.getConnection(), rs.getServerName()); SpaceQuotaSnapshot snapshot = snapshots.get(tn); assertNotNull("Did not find snapshot for " + tn, snapshot); assertTrue(snapshot.getQuotaStatus().isInViolation()); assertEquals(SpaceViolationPolicy.NO_INSERTS, snapshot.getQuotaStatus().getPolicy()); } @Test public void testQuotaStatusFromMaster() throws Exception { final long sizeLimit = 1024L * 25L; // 25KB // As of 2.0.0-beta-2, this 1KB of "Cells" actually results in about 15KB on disk (HFiles) // This is skewed a bit since we're writing such little data, so the test needs to keep // this in mind; else, the quota will be in violation before the test expects it to be. final long tableSize = 1024L * 1; // 1KB final long nsLimit = Long.MAX_VALUE; final int numRegions = 10; final TableName tn = helper.createTableWithRegions(numRegions); // Define the quota QuotaSettings settings = QuotaSettingsFactory.limitTableSpace( tn, sizeLimit, SpaceViolationPolicy.NO_INSERTS); TEST_UTIL.getAdmin().setQuota(settings); QuotaSettings nsSettings = QuotaSettingsFactory.limitNamespaceSpace( tn.getNamespaceAsString(), nsLimit, SpaceViolationPolicy.NO_INSERTS); TEST_UTIL.getAdmin().setQuota(nsSettings); // Write at least `tableSize` data helper.writeData(tn, tableSize); final Connection conn = TEST_UTIL.getConnection(); // Make sure the master has a snapshot for our table Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() { @Override public boolean evaluate() throws Exception { SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot(conn, tn); LOG.info("Table snapshot after initial ingest: " + snapshot); if (snapshot == null) { return false; } return snapshot.getLimit() == sizeLimit && snapshot.getUsage() > 0L; } }); final AtomicReference<Long> nsUsage = new AtomicReference<>(); // If we saw the table snapshot, we should also see the namespace snapshot Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000 * 1000, new Predicate<Exception>() { @Override public boolean evaluate() throws Exception { SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot( conn, tn.getNamespaceAsString()); LOG.debug("Namespace snapshot after initial ingest: " + snapshot); if (snapshot == null) { return false; } nsUsage.set(snapshot.getUsage()); return snapshot.getLimit() == nsLimit && snapshot.getUsage() > 0; } }); // Sanity check: the below assertions will fail if we somehow write too much data // and force the table to move into violation before we write the second bit of data. SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot(conn, tn); assertTrue("QuotaSnapshot for " + tn + " should be non-null and not in violation", snapshot != null && !snapshot.getQuotaStatus().isInViolation()); try { helper.writeData(tn, tableSize * 2L); } catch (RetriesExhaustedWithDetailsException | SpaceLimitingException e) { // Pass } // Wait for the status to move to violation Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() { @Override public boolean evaluate() throws Exception { SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot(conn, tn); LOG.info("Table snapshot after second ingest: " + snapshot); if (snapshot == null) { return false; } return snapshot.getQuotaStatus().isInViolation(); } }); // The namespace should still not be in violation, but have a larger usage than previously Waiter.waitFor(TEST_UTIL.getConfiguration(), 30 * 1000, new Predicate<Exception>() { @Override public boolean evaluate() throws Exception { SpaceQuotaSnapshot snapshot = QuotaTableUtil.getCurrentSnapshot( conn, tn.getNamespaceAsString()); LOG.debug("Namespace snapshot after second ingest: " + snapshot); if (snapshot == null) { return false; } return snapshot.getUsage() > nsUsage.get() && !snapshot.getQuotaStatus().isInViolation(); } }); } private int countRegionsForTable(TableName tn, Map<RegionInfo,Long> regionSizes) { int size = 0; for (RegionInfo regionInfo : regionSizes.keySet()) { if (tn.equals(regionInfo.getTable())) { size++; } } return size; } private int getTableSize(TableName tn, Map<RegionInfo,Long> regionSizes) { int tableSize = 0; for (Entry<RegionInfo,Long> entry : regionSizes.entrySet()) { RegionInfo regionInfo = entry.getKey(); long regionSize = entry.getValue(); if (tn.equals(regionInfo.getTable())) { tableSize += regionSize; } } return tableSize; } }
3e14b8c1a37724493174bf9c729d8e0f74e9f369
976
java
Java
pdf/document-model/src/main/java/org/bndly/document/xml/XPageTemplate.java
bndly/bndly-commons
e0fee12a6a549dff931ed1c8563f00798224786a
[ "Apache-2.0" ]
1
2020-07-24T08:58:39.000Z
2020-07-24T08:58:39.000Z
pdf/document-model/src/main/java/org/bndly/document/xml/XPageTemplate.java
bndly/bndly-commons
e0fee12a6a549dff931ed1c8563f00798224786a
[ "Apache-2.0" ]
2
2020-12-02T18:45:34.000Z
2022-01-21T23:45:25.000Z
pdf/document-model/src/main/java/org/bndly/document/xml/XPageTemplate.java
bndly/bndly-commons
e0fee12a6a549dff931ed1c8563f00798224786a
[ "Apache-2.0" ]
2
2020-07-21T17:44:10.000Z
2020-07-22T13:31:10.000Z
30.5
75
0.744877
8,785
package org.bndly.document.xml; /*- * #%L * PDF XML Document Model * %% * Copyright (C) 2013 - 2020 Cybercon GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "pageTemplate") @XmlAccessorType(XmlAccessType.NONE) public final class XPageTemplate extends XContainer { }
3e14b8ca28a2e38c30593fe142edfcd6386b4533
419
java
Java
MVP/MVPDemo2/src/main/java/jp/sinya/mvpdemo2/framework/ContentView.java
KoizumiSinya/DemoProject
01aae447bdc02b38b73b2af085e3e28e662764be
[ "Apache-2.0" ]
null
null
null
MVP/MVPDemo2/src/main/java/jp/sinya/mvpdemo2/framework/ContentView.java
KoizumiSinya/DemoProject
01aae447bdc02b38b73b2af085e3e28e662764be
[ "Apache-2.0" ]
null
null
null
MVP/MVPDemo2/src/main/java/jp/sinya/mvpdemo2/framework/ContentView.java
KoizumiSinya/DemoProject
01aae447bdc02b38b73b2af085e3e28e662764be
[ "Apache-2.0" ]
null
null
null
24.647059
48
0.792363
8,786
package jp.sinya.mvpdemo2.framework; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //类注解 //Target:作用目标->作用在类身上(ElementType.TYPE) @Target(ElementType.TYPE) //Retention:生命周期->运行时注解(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME) public @interface ContentView { //布局ID int value(); }
3e14b9420537631f8241cce176a5c13d0c27e65d
1,165
java
Java
src/main/java/tk/martijn_heil/nincore/api/exceptions/validationexceptions/InvalidCommandSenderException.java
martijn-heil/NinCore-API
e5fc8c46008db4bcdd2a09d8539b4ef7784303de
[ "MIT" ]
1
2016-03-15T10:18:48.000Z
2016-03-15T10:18:48.000Z
src/main/java/tk/martijn_heil/nincore/api/exceptions/validationexceptions/InvalidCommandSenderException.java
martijn-heil/NinCore-API
e5fc8c46008db4bcdd2a09d8539b4ef7784303de
[ "MIT" ]
null
null
null
src/main/java/tk/martijn_heil/nincore/api/exceptions/validationexceptions/InvalidCommandSenderException.java
martijn-heil/NinCore-API
e5fc8c46008db4bcdd2a09d8539b4ef7784303de
[ "MIT" ]
null
null
null
41.607143
127
0.758798
8,787
package tk.martijn_heil.nincore.api.exceptions.validationexceptions; import org.bukkit.command.CommandSender; import tk.martijn_heil.nincore.api.NinCore; import tk.martijn_heil.nincore.api.exceptions.ValidationException; import tk.martijn_heil.nincore.api.messaging.MessageRecipient; import tk.martijn_heil.nincore.api.util.TranslationUtils; import java.util.ResourceBundle; public class InvalidCommandSenderException extends ValidationException { public InvalidCommandSenderException(CommandSender commandSender) { super(commandSender, TranslationUtils.getStaticMsg(ResourceBundle.getBundle("tk.martijn_heil.nincore.api.res.messages", NinCore.get().getEntityManager().getNinCommandSender(commandSender).getMinecraftLocale(). toLocale()), "error.InvalidCommandSender"), null); } public InvalidCommandSenderException(MessageRecipient target) { super(target, TranslationUtils.getStaticMsg(ResourceBundle.getBundle("tk.martijn_heil.nincore.api.res.messages", target.getMinecraftLocale(). toLocale()), "error.InvalidCommandSender"), null); } }
3e14ba36865d176eee6c280729f87ae356b3fc72
27,433
java
Java
app/src/main/java/com/example/animation/activity/MainActivity.java
NicoLiutong/miaosou
0e3de35b9c461083f2ee05f632178d0afac1ac39
[ "Apache-2.0" ]
3
2017-11-12T11:23:37.000Z
2018-07-03T14:25:35.000Z
app/src/main/java/com/example/animation/activity/MainActivity.java
NicoLiutong/miaosou
0e3de35b9c461083f2ee05f632178d0afac1ac39
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/animation/activity/MainActivity.java
NicoLiutong/miaosou
0e3de35b9c461083f2ee05f632178d0afac1ac39
[ "Apache-2.0" ]
null
null
null
42.73053
207
0.632559
8,788
package com.example.animation.activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.example.animation.R; import com.example.animation.Util.CheckUpdataApplication; import com.example.animation.Util.SHA; import com.example.animation.Util.SavePicture; import com.example.animation.Util.SetStatueBarStyle; import com.example.animation.customSystem.bease.MainImage; import com.example.animation.customSystem.bease.User; import com.example.animation.customSystem.view.UserMessageActivity; import com.example.animation.fragments.AnimationFragment; import com.example.animation.fragments.ComicFragment; import com.example.animation.pay.AliZhi; import com.example.animation.pay.Config; import com.example.animation.pay.MiniPayUtils; import com.example.animation.server.UpdateMyFavority; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.Random; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.BmobUser; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.FindListener; import de.hdodenhof.circleimageview.CircleImageView; public class MainActivity extends AppCompatActivity implements OnRefreshListener,View.OnClickListener,NavigationView.OnNavigationItemSelectedListener{ private static final int ANIMATION = 0; private static final int COMIC = 1; private DrawerLayout mDrawerLayout; private NavigationView nvMenu; private ImageView nvHeardImage; private CircleImageView nvHeadUserPicture; private TextView nvHeadUserName; private Handler mHandler; private boolean isCloseApp = false; private CollapsingToolbarLayout collapsingToolbar; private AppBarLayout appBarLayout; private Toolbar toolbar; //private SwipeRefreshLayout swipeRefreshLayout; private SmartRefreshLayout smartRefreshLayout; private ImageView smartImageView; private CardView animationPageCardview; private CardView comicPageCardview; private ImageView mainactivityToolbarImageview; private ImageView mainBackgroungImageView; private int pagesName; private SharedPreferences pref; private String animationTitle; private AnimationFragment animationFragment; private ComicFragment comicFragment; private Intent service; private String imagePrintUrl = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pref = PreferenceManager.getDefaultSharedPreferences(this); SetStatueBarStyle style = new SetStatueBarStyle(this); style.setHalfTransparent(); Bmob.initialize(this,"df1a802c660365ec34c26730bc5b641d"); service = new Intent(this, UpdateMyFavority.class); this.startService(service); CheckUpdataApplication.checkUpdata(this,0); toolbar = (Toolbar) findViewById(R.id.toolbar); collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.main_collapsingToolbar); collapsingToolbar.setExpandedTitleColor(ContextCompat.getColor(MainActivity.this,R.color.colorAccent)); //設置toolbar背景色 setSupportActionBar(toolbar); //設置ActionBar mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_menu); nvMenu = (NavigationView) findViewById(R.id.nv_menu); nvHeardImage = (ImageView) nvMenu.getHeaderView(0).findViewById(R.id.nv_heard_image); nvHeadUserPicture = (CircleImageView) nvMenu.getHeaderView(0).findViewById(R.id.nv_head_user_picture); nvHeadUserName = (TextView) nvMenu.getHeaderView(0).findViewById(R.id.nv_head_user_name); nvMenu.setNavigationItemSelectedListener(this); smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.smart_main_refresh); smartRefreshLayout.setOnRefreshListener(this); smartRefreshLayout.setDisableContentWhenRefresh(true); smartImageView = (ImageView) findViewById(R.id.smart_main_image_view); Glide.with(this).load(R.drawable.loading_image).asGif().into(smartImageView); //swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); //swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent); appBarLayout = (AppBarLayout) findViewById(R.id.app_bar); animationPageCardview = (CardView) findViewById(R.id.animation_pageCard); comicPageCardview = (CardView) findViewById(R.id.comic_pageCard); mainactivityToolbarImageview = (ImageView) findViewById(R.id.animation_toobarImage); mainBackgroungImageView = (ImageView) findViewById(R.id.main_backgroung_iv); setToolbarImage(); //設置ToolBarImage setAnimationTitle(); //設置Title setToolBarNavigation(); setPayAuthor(); animationFragment = new AnimationFragment(); //設置AnimationFragment comicFragment = new ComicFragment(); //設置comicFragment animationFragment.setSmartRefreshLayout(smartRefreshLayout); comicFragment.setSmartRefreshLayout(smartRefreshLayout); animationPageSet(animationFragment); //初始化為animationFragment isInternetOk(); //判斷網絡是否打開 nvHeadUserPicture.setOnClickListener(this); animationPageCardview.setOnClickListener(this); comicPageCardview.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); setNvHeardImage(); //设置NavigationView的heard图片 mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 1: isCloseApp = false; } } }; } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); this.stopService(service); } private void setAnimationTitle(){ //設置title,獲取datename,如果有則將其設置為title;否則設置默認的 animationTitle = pref.getString("datename",""); if(animationTitle == null){ animationTitle = "日本新番动画放送列表"; }else { animationTitle = animationTitle + "动画列表"; } } private void animationPageSet(Fragment fragment){ //動漫頁面設置,先設置button顏色,設置顯示的Fragment,設置title,設置標籤 animationPageCardview.setCardBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.affirm_pink)); comicPageCardview.setCardBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.affirm_blue)); replaceFragenment(fragment,"animationFragmentTag"); collapsingToolbar.setTitle(animationTitle); pagesName = ANIMATION; } private void comicPageSet(Fragment fragment){ //漫畫頁面設置,先設置button顏色,設置顯示的Fragment,設置title,設置標籤 animationPageCardview.setCardBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.affirm_blue)); comicPageCardview.setCardBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.affirm_pink)); replaceFragenment(fragment,"animationFragmentTag"); collapsingToolbar.setTitle("漫画列表"); pagesName = COMIC; } private void replaceFragenment(Fragment fragment,String tag){ //Fragment的更換,傳入Fragment和tag FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.fragment,fragment,tag); transaction.commit(); } /*判斷網絡是否ok 1、獲取ConnectivityManager 2、獲取NetworkInfo 3、判斷是否有連接,沒有彈出對話框 4、對話框的確認button,點擊進入設置頁面 */ public void isInternetOk(){ ConnectivityManager manger = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manger.getActiveNetworkInfo(); if (info != null && info.isConnected()) { } else { Toast.makeText(this, "无网络连接", Toast.LENGTH_SHORT).show(); AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle("点击确认设置网路"); dialog.setNegativeButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (android.os.Build.VERSION.SDK_INT > 10) { startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); } else { startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS)); } } }); dialog.show(); } } /** * 設置toolbar顯示的image */ private void setToolbarImage(){ String filepath = pref.getString("backgroundFilepath",""); boolean isNetwork = pref.getBoolean("isUseNetworkBackground",true); if(filepath!=null&&new File(filepath).exists()){ if(isNetwork){ setNetworkBackground(filepath); }else { setLocalBackground(filepath); } }else { if(isNetwork){ setNetworkBackground(null); }else { setLocalBackground(null); } } } private void setLocalBackground(String filePath) { if(filePath!=null){ Glide.with(this).load(filePath).crossFade().thumbnail(0.5f).into(mainBackgroungImageView); }else { Glide.with(this).load(R.drawable.ic_main_girl).crossFade().thumbnail(0.5f).into(mainBackgroungImageView); } } private void setNetworkBackground(final String filePath){ final Bitmap[] saveBitmap = {null}; final String[] saveName = {null}; BmobQuery<MainImage> query = new BmobQuery<>(); query.findObjects(new FindListener<MainImage>() { @Override public void done(final List<MainImage> list, BmobException e) { if(e==null){ Random random = new Random(); final int number = random.nextInt(list.size() - 1); imagePrintUrl = list.get(number).getAnimationUrl(); saveName[0] = imagePrintUrl.substring(imagePrintUrl.lastIndexOf("/")+1,imagePrintUrl.lastIndexOf(".")); Glide.with(MainActivity.this).load(list.get(number).getVerticalPicture().getUrl()).asBitmap().thumbnail(0.5f).listener(new RequestListener<String, Bitmap>() { @Override public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) { Toast.makeText(MainActivity.this,"背景图片加载失败",Toast.LENGTH_SHORT).show(); if(filePath!=null){ mainBackgroungImageView.setImageURI(Uri.parse(filePath)); }else { mainBackgroungImageView.setImageResource(R.drawable.ic_main_girl); } return false; } @Override public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) { saveBitmap[0] = resource; return false; } }).into(mainBackgroungImageView); mainactivityToolbarImageview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = creatBackgroundImageBuilder(saveBitmap[0],saveName[0]); builder.show(); } }); }else { if(filePath!=null){ Glide.with(MainActivity.this).load(filePath).crossFade().thumbnail(0.5f).into(mainBackgroungImageView); }else { Glide.with(MainActivity.this).load(R.drawable.ic_main_girl).crossFade().thumbnail(0.5f).into(mainBackgroungImageView); } } } }); } private AlertDialog.Builder creatBackgroundImageBuilder(final Bitmap saveBitmap,final String saveName){ AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(imagePrintUrl.substring(imagePrintUrl.lastIndexOf("/")+1,imagePrintUrl.lastIndexOf("."))); builder.setMessage("是否进入对应的动画列表"); builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(MainActivity.this,DownloadActivity.class); intent.putExtra(AnimationFragment.ANIMATION_URL,imagePrintUrl); intent.putExtra(AnimationFragment.ANIMATION_NAME,imagePrintUrl.substring(imagePrintUrl.lastIndexOf("/")+1,imagePrintUrl.lastIndexOf("."))); MainActivity.this.startActivity(intent); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if(saveBitmap!=null&&saveName!=null) { builder.setNeutralButton("仅保存图片", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { boolean isSuccess = false; String filepath = Environment.getExternalStorageDirectory().toString() + File.separator + "miaosou" + File.separator + "backgroundpicture" + File.separator; isSuccess = SavePicture.savePicture(pref.getString("backgroundSaveFilepath",filepath), saveBitmap, saveName, MainActivity.this); if (isSuccess) { Toast.makeText(MainActivity.this, "图片保存成功,路径"+ pref.getString("backgroundSaveFilepath",filepath), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "图片保存失败,请确认已开启读写SD卡权限", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "请开启读写SD卡权限", Toast.LENGTH_SHORT).show(); } dialog.dismiss(); } }); } return builder; } private void setToolBarNavigation(){ toolbar.setNavigationIcon(R.drawable.ic_menu); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDrawerLayout.openDrawer(GravityCompat.START); } }); } private void setNvHeardImage(){ User currentUser = BmobUser.getCurrentUser(User.class); if(currentUser!=null){ Glide.with(MainActivity.this).load(currentUser.getUesrImage()).into(nvHeadUserPicture); nvHeadUserName.setText(currentUser.getName()); }else { Glide.with(MainActivity.this).load(R.drawable.user_picture).into(nvHeadUserPicture); nvHeadUserName.setText("未登录"); } Glide.with(MainActivity.this).load(R.drawable.ic_main_girl).into(nvHeardImage); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.animation_pageCard: animationPageSet(animationFragment); break; case R.id.comic_pageCard: comicPageSet(comicFragment); break; case R.id.nv_head_user_picture: Intent userMessage = new Intent(MainActivity.this, UserMessageActivity.class); this.startActivity(userMessage); break; } } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Intent intent = null; switch (item.getItemId()){ case R.id.animation_news: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,AnimationNewActivity.class); MainActivity.this.startActivity(intent); break; case R.id.my_favourity: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(MainActivity.this,MyFavourityActivity.class); MainActivity.this.startActivity(intent); break; case R.id.my_signin: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,SignInActivity.class); MainActivity.this.startActivity(intent); break; case R.id.pay_author: mDrawerLayout.closeDrawer(GravityCompat.START); MiniPayUtils.setupPay(this,new Config.Builder("FKX01294KSKKFN2F9ESS47",R.drawable.ic_zhufubao_pay,R.drawable.ic_weixin_pay).build()); break; case R.id.about_author: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,AboutActivity.class); this.startActivity(intent); break; case R.id.about_check_updata: mDrawerLayout.closeDrawer(GravityCompat.START); CheckUpdataApplication.checkUpdata(this,1); break; case R.id.setting: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,SettingActivity.class); this.startActivity(intent); break; case R.id.animation_picture: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,AnimationPicture.class); this.startActivity(intent); break; case R.id.cosplay_picture: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,CosplayPicture.class); this.startActivity(intent); break; case R.id.chatting: mDrawerLayout.closeDrawer(GravityCompat.START); openChatting(); break; case R.id.image_search: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,BasicWebActivity.class); intent.putExtra(AnimationFragment.ANIMATION_URL,"http://image.baidu.com/wiseshitu?guess=1&queryImageUrl=http://bmob-cdn-16552.b0.upaiyun.com/2018/01/28/8252b4b740101b3980dae801ebbb08a9.png"); this.startActivity(intent); break; case R.id.download_manager: mDrawerLayout.closeDrawer(GravityCompat.START); intent = new Intent(this,DownloadManagerActivity.class); this.startActivity(intent); break; } return true; } private void closeApp(){ if(isCloseApp){ finish(); }else { isCloseApp = true; Toast.makeText(this,"再次点击关闭喵搜",Toast.LENGTH_SHORT).show(); mHandler.sendEmptyMessageDelayed(1,3000); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){ mDrawerLayout.closeDrawer(GravityCompat.START); return true; }else { closeApp(); return true; } } return false; } private void setPayAuthor(){ final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences.Editor editor = preferences.edit(); String keyCode = preferences.getString("payKey","1.0.0"); if(!keyCode.equals("1.38.0")){ AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.MyDialog); View view = LayoutInflater.from(this).inflate(R.layout.main_dialog,null,false); Button paybt = (Button) view.findViewById(R.id.dialog_pay); final Button weixinbt = (Button) view.findViewById(R.id.dialog_weixin); Button qqbt = (Button) view.findViewById(R.id.dialog_qq); Button sharebt = (Button) view.findViewById(R.id.dialog_share); Button closebt = (Button) view.findViewById(R.id.dialog_close); builder.setView(view); builder.setCancelable(false); final Dialog dialog = builder.show(); paybt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.putString("payKey","1.38.0"); editor.commit(); AliZhi.startAlipayClient(MainActivity.this,"FKX01294KSKKFN2F9ESS47"); dialog.dismiss(); } }); weixinbt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.putString("payKey","1.38.0"); editor.commit(); Intent intent = new Intent(MainActivity.this,WeiXinHao.class); intent.putExtra(WeiXinHao.TYPE,WeiXinHao.WEIXIN); MainActivity.this.startActivity(intent); dialog.dismiss(); } }); qqbt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.putString("payKey","1.38.0"); editor.commit(); Intent intent = new Intent(MainActivity.this,WeiXinHao.class); intent.putExtra(WeiXinHao.TYPE,WeiXinHao.QQQUN); MainActivity.this.startActivity(intent); dialog.dismiss(); } }); sharebt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.putString("payKey","1.38.0"); editor.commit(); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,getString(R.string.share_app,"喵搜")); startActivity(Intent.createChooser(intent,getString(R.string.share))); dialog.dismiss(); } }); closebt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.putString("payKey","1.38.0"); editor.commit(); dialog.dismiss(); } }); } } private void openChatting() { User user = BmobUser.getCurrentUser(User.class); long timestamp = System.currentTimeMillis()/1000; String userName = ""; String imageUrl = user.getUesrImage(); try { userName = URLEncoder.encode(user.getName(),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String xlm = "12483_"+user.getObjectId()+"_"+timestamp+"_jWr4HgC3hIFhgWTudvoclclZYwjBvwK4"; String xlmHash = SHA.shaEncrypt(xlm); String url = "https://xianliao.me/s/12483?mobile=1&uid="+user.getObjectId()+"&username="+userName+"&avatar="+imageUrl+"&ts="+timestamp+"&token="+xlmHash; Intent intent = new Intent(this,BasicWebActivity.class); intent.putExtra(AnimationFragment.ANIMATION_URL,url); this.startActivity(intent); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public void onRefresh(RefreshLayout refreshlayout) { if(pagesName == ANIMATION){ animationFragment.queryAnimation(); animationFragment.setSmartRefreshLayout(smartRefreshLayout); setAnimationTitle(); }else { comicFragment.refreshComic(); comicFragment.setSmartRefreshLayout(smartRefreshLayout); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_more,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.search_more: Intent intent = new Intent(MainActivity.this,SearchActivity.class); intent.putExtra("type",0); MainActivity.this.startActivity(intent); break; } return super.onOptionsItemSelected(item); } }
3e14bba4b1ceb1a7d0bc702077ea05eeb17d452b
1,801
java
Java
web/src/main/java/com/navercorp/pinpoint/web/dao/UserGroupDao.java
richardy2012/pinpoint
c50696734a2f7fcc37f8fea879ed4c84946e58f8
[ "Apache-2.0" ]
1,473
2020-10-14T02:18:07.000Z
2022-03-31T11:43:49.000Z
web/src/main/java/com/navercorp/pinpoint/web/dao/UserGroupDao.java
richardy2012/pinpoint
c50696734a2f7fcc37f8fea879ed4c84946e58f8
[ "Apache-2.0" ]
995
2020-10-14T05:09:43.000Z
2022-03-31T12:04:05.000Z
web/src/main/java/com/navercorp/pinpoint/web/dao/UserGroupDao.java
richardy2012/pinpoint
c50696734a2f7fcc37f8fea879ed4c84946e58f8
[ "Apache-2.0" ]
446
2020-10-14T02:42:50.000Z
2022-03-31T03:03:53.000Z
30.016667
75
0.767907
8,789
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.web.dao; import java.util.List; import com.navercorp.pinpoint.web.vo.UserGroup; import com.navercorp.pinpoint.web.vo.UserGroupMember; import com.navercorp.pinpoint.web.vo.UserPhoneInfo; /** * @author minwoo.jung */ public interface UserGroupDao { String createUserGroup(UserGroup userGroup); List<UserGroup> selectUserGroup(); List<UserGroup> selectUserGroupByUserId(String userId); List<UserGroup> selectUserGroupByUserGroupId(String userGroupId); void updateUserGroup(UserGroup userGroup); void deleteUserGroup(UserGroup userGroup); void insertMember(UserGroupMember userGroupMember); void deleteMember(UserGroupMember userGroupMember); List<UserGroupMember> selectMember(String userGroupId); void updateMember(UserGroupMember userGroupMember); List<String> selectPhoneNumberOfMember(String userGroupId); List<String> selectEmailOfMember(String userGroupId); void deleteMemberByUserGroupId(String userGroupId); void updateUserGroupIdOfMember(UserGroup userGroup); boolean isExistUserGroup(String userGroupId); List<UserPhoneInfo> selectPhoneInfoOfMember(String userGroupId); }
3e14bc6faf9d7a23fdcc01d8ad43fcb287f2946f
446
java
Java
src/main/java/com/future/cinemaxx/dtos/TicketDTO.java
solvemate2018/CInema-XX
dd467bf3aed632d1786193c4ff6144293ed35fc8
[ "MIT" ]
null
null
null
src/main/java/com/future/cinemaxx/dtos/TicketDTO.java
solvemate2018/CInema-XX
dd467bf3aed632d1786193c4ff6144293ed35fc8
[ "MIT" ]
null
null
null
src/main/java/com/future/cinemaxx/dtos/TicketDTO.java
solvemate2018/CInema-XX
dd467bf3aed632d1786193c4ff6144293ed35fc8
[ "MIT" ]
null
null
null
22.3
52
0.811659
8,790
package com.future.cinemaxx.dtos; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class TicketDTO { private int ticketRow; private int ticketColumn; private boolean sold; private ProjectionDTO projection; }
3e14bcac1de5962c743d2eee3fa3f4f5dd22081c
1,888
java
Java
gateway/src/main/java/ru/discloud/gateway/web/GroupController.java
zharkov-eu/discloud.cloud
b4272ae29d22ec234a5153b82985fa7772fb5667
[ "Apache-2.0" ]
1
2018-07-09T10:14:12.000Z
2018-07-09T10:14:12.000Z
gateway/src/main/java/ru/discloud/gateway/web/GroupController.java
zharkov-eu/discloud.cloud
b4272ae29d22ec234a5153b82985fa7772fb5667
[ "Apache-2.0" ]
null
null
null
gateway/src/main/java/ru/discloud/gateway/web/GroupController.java
zharkov-eu/discloud.cloud
b4272ae29d22ec234a5153b82985fa7772fb5667
[ "Apache-2.0" ]
null
null
null
34.327273
120
0.778072
8,791
package ru.discloud.gateway.web; import com.fasterxml.jackson.core.JsonProcessingException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import ru.discloud.gateway.service.GroupService; import ru.discloud.gateway.web.model.GroupResponse; import ru.discloud.shared.web.core.GroupRequest; import javax.validation.Valid; import javax.validation.ValidationException; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/api/group") public class GroupController { private final GroupService groupService; @Autowired public GroupController(GroupService groupService) { this.groupService = groupService; } @PostMapping() public Mono<GroupResponse> createGroup(@Valid @RequestBody GroupRequest groupRequest) throws ValidationException, JsonProcessingException { return groupService.createGroup(groupRequest).map(GroupResponse::new); } @GetMapping(path = "/") public Mono<List<GroupResponse>> getGroups() { return groupService.getGroups().map(groups -> groups.stream().map(GroupResponse::new).collect(Collectors.toList())); } @GetMapping(path = "/{id}") public Mono<GroupResponse> getGroup(@PathVariable Integer id) { return groupService.getGroupById(id).map(GroupResponse::new); } @PatchMapping(path = "/{id}") public Mono<GroupResponse> updateGroup(@PathVariable Integer id, @Valid @RequestBody GroupRequest groupRequest) throws ValidationException, JsonProcessingException { return groupService.updateGroup(id, groupRequest).map(GroupResponse::new); } @DeleteMapping(path = "/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public Mono<Void> deleteGroup(@PathVariable Integer id) { return groupService.deleteGroup(id); } }
3e14bd5ee8922cec5cc433cad796a1695bc038f2
1,578
java
Java
src/main/java/lu/uni/serval/commons/git/api/github/Github.java
UL-SnT-Serval/java-commons-git-utils
49aea88364a80cd347e2dbb4dddccd6c711fd950
[ "Apache-2.0" ]
null
null
null
src/main/java/lu/uni/serval/commons/git/api/github/Github.java
UL-SnT-Serval/java-commons-git-utils
49aea88364a80cd347e2dbb4dddccd6c711fd950
[ "Apache-2.0" ]
null
null
null
src/main/java/lu/uni/serval/commons/git/api/github/Github.java
UL-SnT-Serval/java-commons-git-utils
49aea88364a80cd347e2dbb4dddccd6c711fd950
[ "Apache-2.0" ]
null
null
null
33.574468
132
0.749683
8,792
package lu.uni.serval.commons.git.api.github; /*- * #%L * GIT Utils * %% * Copyright (C) 2020 - 2021 University of Luxembourg, Renaud RWEMALIKA * %% * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import lu.uni.serval.commons.git.utils.LocalRepository; import lu.uni.serval.commons.git.api.GitEngine; import lu.uni.serval.commons.git.exception.InvalidGitRepositoryException; import java.io.IOException; import java.util.Collections; import java.util.Set; public class Github extends GitEngine { @Override public Set<LocalRepository> cloneProjectsFromNames(Set<String> projectNames) throws IOException, InvalidGitRepositoryException { return Collections.emptySet(); } @Override public Set<LocalRepository> cloneProjectsFromGroup(String group) throws IOException, InvalidGitRepositoryException { return Collections.emptySet(); } @Override public Set<LocalRepository> cloneProjectsFromUser(String user) throws IOException, InvalidGitRepositoryException { return Collections.emptySet(); } }
3e14bfaaa4b32833a9f28468e7b1a2c7381f0881
1,465
java
Java
app/src/main/java/com/fastaccess/cheaphlight/ui/modules/setup/view/SetupPagerView.java
k0shk0sh/Cheaphlight
468c9f1f342acf9649837532120fb313758bc4b6
[ "MIT" ]
3
2016-08-11T10:29:21.000Z
2022-01-18T01:36:14.000Z
app/src/main/java/com/fastaccess/cheaphlight/ui/modules/setup/view/SetupPagerView.java
k0shk0sh/Cheaphlight
468c9f1f342acf9649837532120fb313758bc4b6
[ "MIT" ]
null
null
null
app/src/main/java/com/fastaccess/cheaphlight/ui/modules/setup/view/SetupPagerView.java
k0shk0sh/Cheaphlight
468c9f1f342acf9649837532120fb313758bc4b6
[ "MIT" ]
null
null
null
25.701754
81
0.711945
8,793
package com.fastaccess.cheaphlight.ui.modules.setup.view; import android.os.Bundle; import com.fastaccess.cheaphlight.R; import com.fastaccess.cheaphlight.ui.base.BaseActivity; import com.fastaccess.cheaphlight.ui.modules.setup.model.SetupPagerMvp; import com.fastaccess.cheaphlight.ui.modules.setup.presenter.SetupPagerPresenter; import com.fastaccess.cheaphlight.ui.widgets.ViewPagerView; import butterknife.BindView; /** * Created by Kosh on 29 May 2016, 12:40 AM */ public class SetupPagerView extends BaseActivity implements SetupPagerMvp.View { @BindView(R.id.pager) ViewPagerView pager; private SetupPagerPresenter presenter; @Override protected int layout() { return R.layout.setup_layout; } @Override protected boolean isTransparent() { return false; } @Override protected boolean canBack() { return false; } @Override protected boolean isSecured() { return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPresenter().initializePager(this, pager); } @Override public void onNext() { getPresenter().onNext(pager); } @Override public void onFinishActivity() { getPresenter().onFinish(this); } public SetupPagerPresenter getPresenter() { if (presenter == null) presenter = SetupPagerPresenter.with(this); return presenter; } }
3e14bfe42ad80223ee1b1a3831180260857f83ca
957
java
Java
spring-boot-with-configuration-processor-sample/src/main/java/com/xingyun/springbootwithconfigurationprocessorsample/SpringBootWithConfigurationProcessorSampleApplication.java
geekxingyun/spring-boot-best-practices-sample
b8e68e31448c9e1652e60063dd83f6898b13bae6
[ "Apache-2.0" ]
13
2020-02-14T00:58:59.000Z
2021-09-24T04:54:02.000Z
spring-boot-with-configuration-processor-sample/src/main/java/com/xingyun/springbootwithconfigurationprocessorsample/SpringBootWithConfigurationProcessorSampleApplication.java
geekxingyun/spring-boot-best-practices-sample
b8e68e31448c9e1652e60063dd83f6898b13bae6
[ "Apache-2.0" ]
null
null
null
spring-boot-with-configuration-processor-sample/src/main/java/com/xingyun/springbootwithconfigurationprocessorsample/SpringBootWithConfigurationProcessorSampleApplication.java
geekxingyun/spring-boot-best-practices-sample
b8e68e31448c9e1652e60063dd83f6898b13bae6
[ "Apache-2.0" ]
3
2020-02-14T02:13:46.000Z
2021-07-16T08:01:26.000Z
39
97
0.820513
8,794
package com.xingyun.springbootwithconfigurationprocessorsample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Spring Boot 需要一个应用引导类,引导类的作用是让Spring Boot 框架启动并初始化应用. * @SpringBootApplication 该注解告诉Spring 容器,使用该类作为所有Bean源,通过该起点构建应用上下文 * @SpringBootApplication 继承自 @ComponentScan 和 @EnableAutoConfiguration * 系统启动后会对该类所属目录下的包进行扫描并根据Spring Boot 的自动配置机制进行配置 * 因此该类必须放在项目的根包中,否则可能部分配置可能不会被扫描到. * 如果特殊情况不能放到根包,可以使用@ComponentScan显示指定包名,配置扫描包的位置如:@ComponentScan("com.xingyun.**") * nnheo@example.com.**,com.swallow.**") * @author qing-feng.zhao */ @SpringBootApplication public class SpringBootWithConfigurationProcessorSampleApplication { public static void main(String[] args) { //SpringApplication.run方法会构建一个Spring容器,并且返回一个ApplicationContext对象,也就是项目的上下文 SpringApplication.run(SpringBootWithConfigurationProcessorSampleApplication.class, args); } }
3e14c0929fd5d3cca2698a8a1708f459a2d966d4
1,220
java
Java
testData/after/equalsandhashcode/EqualsAndHashCodeWithExistingMethods.java
1337c0der/lombok-intellij-plugin
32374a4fa1428873fdb7ecf35dc7baa5b67a0003
[ "BSD-3-Clause" ]
1
2018-09-20T09:09:19.000Z
2018-09-20T09:09:19.000Z
testData/after/equalsandhashcode/EqualsAndHashCodeWithExistingMethods.java
1337c0der/lombok-intellij-plugin
32374a4fa1428873fdb7ecf35dc7baa5b67a0003
[ "BSD-3-Clause" ]
3
2021-12-10T01:53:27.000Z
2021-12-14T21:56:48.000Z
testData/after/EqualsAndHashCodeWithExistingMethods.java
whitemike889/lombok-intellij-plugin
d2e20aebc9de554557b1f6179f66da112c902d23
[ "BSD-3-Clause" ]
2
2019-10-15T18:51:15.000Z
2019-10-15T18:51:17.000Z
24.4
96
0.736885
8,795
// Generated by delombok at Sat Jun 11 11:12:44 CEST 2016 class EqualsAndHashCodeWithExistingMethods { int x; public int hashCode() { return 42; } } final class EqualsAndHashCodeWithExistingMethods2 { int x; public boolean equals(Object other) { return false; } } final class EqualsAndHashCodeWithExistingMethods3 extends EqualsAndHashCodeWithExistingMethods { int x; private boolean canEqual(Object other) { return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof EqualsAndHashCodeWithExistingMethods3)) return false; final EqualsAndHashCodeWithExistingMethods3 other = (EqualsAndHashCodeWithExistingMethods3) o; if (!other.canEqual((java.lang.Object) this)) return false; if (!super.equals(o)) return false; if (this.x != other.x) return false; return true; } @java.lang.Override @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + super.hashCode(); result = result * PRIME + this.x; return result; } }
3e14c0a11fc56f934af056b4a568025a2d19104a
3,585
java
Java
src/main/java/com/hwy/shipyard/service/impl/PurchaseServiceImpl.java
JinHong1134/ShipyadrDev
4afcd1595b8bea7ca8fe87d3084e034241fbfb5e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hwy/shipyard/service/impl/PurchaseServiceImpl.java
JinHong1134/ShipyadrDev
4afcd1595b8bea7ca8fe87d3084e034241fbfb5e
[ "Apache-2.0" ]
1
2022-02-09T22:20:59.000Z
2022-02-09T22:20:59.000Z
src/main/java/com/hwy/shipyard/service/impl/PurchaseServiceImpl.java
JinHong1134/ShipyadrDev
4afcd1595b8bea7ca8fe87d3084e034241fbfb5e
[ "Apache-2.0" ]
null
null
null
34.471154
111
0.694561
8,796
package com.hwy.shipyard.service.impl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.hwy.shipyard.dataobject.Purchase; import com.hwy.shipyard.service.PurchaseService; import com.hwy.shipyard.enums.PurchaseStateEnum; import com.hwy.shipyard.mapper.PurchaseMapper; import com.hwy.shipyard.utils.JsonData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; /** * @program: shipyard * @author: huangwenyu * @create: 2019-08-24 */ @Service public class PurchaseServiceImpl implements PurchaseService { @Autowired private PurchaseMapper purchaseMapper; @Override public int createPurchase(Purchase purchase) { int result = purchaseMapper.insertByObject(purchase); return result; } @Override public Purchase findPurchaseById(String purchaseId) { Purchase purchase = purchaseMapper.findById(purchaseId); return purchase; } @Override public Page<Purchase> findByTime(Date startTime, Date endTime, int pageNum, int pageSize) { return null; } @Override public Page<Purchase> findByName(String operatorName, int pageNum, int pageSize) { Page<Purchase> purchasePage = PageHelper.startPage(pageNum, pageSize); List<Purchase> purchaseList = purchaseMapper.findByOperator(operatorName); return purchasePage; } @Override public int deleteById(String purchaseId) { return purchaseMapper.deleteById(purchaseId); } @Override public PageInfo<Purchase> findByState(int state, int pageNum, int pageSize) { if (state == PurchaseStateEnum.All.getCode()) { PageHelper.startPage(pageNum, pageSize); List<Purchase> purchaseList = purchaseMapper.findAll(); PageInfo<Purchase> purchasePageInfo = new PageInfo<Purchase>(purchaseList); return purchasePageInfo; } else if (state == PurchaseStateEnum.UNCHECK.getCode()) { PageHelper.startPage(pageNum, pageSize); List<Purchase> purchaseList = purchaseMapper.findByState(PurchaseStateEnum.UNCHECK.getCode()); PageInfo<Purchase> purchasePageInfo = new PageInfo<Purchase>(purchaseList); return purchasePageInfo; } else if (state == PurchaseStateEnum.APPROVED.getCode()) { PageHelper.startPage(pageNum, pageSize); List<Purchase> purchaseList = purchaseMapper.findByState(PurchaseStateEnum.APPROVED.getCode()); PageInfo<Purchase> purchasePageInfo = new PageInfo<Purchase>(purchaseList); return purchasePageInfo; } else if (state == PurchaseStateEnum.NOT_APPROVED.getCode()) { PageHelper.startPage(pageNum, pageSize); List<Purchase> purchaseList = purchaseMapper.findByState(PurchaseStateEnum.NOT_APPROVED.getCode()); PageInfo<Purchase> purchasePageInfo = new PageInfo<Purchase>(purchaseList); return purchasePageInfo; } else { return null; } } @Override public int updateState(String purchaseId, int purchaseState) { return purchaseMapper.updateById(purchaseId, purchaseState); } @Override public Object getStateNum() { try{ return JsonData.buildSuccess(purchaseMapper.getStateNum()); } catch (Exception e) { e.printStackTrace(); return JsonData.buildError("查找失败"); } } }
3e14c121128915c1c59c86109f4d48caaa9cf465
598
java
Java
offer/src/main/java/leetCode/L10221_MaxSquare.java
seawindnick/javaFamily
d8a6cf8b185e98d6e60961e306a4bbeb4e7360dc
[ "MIT" ]
null
null
null
offer/src/main/java/leetCode/L10221_MaxSquare.java
seawindnick/javaFamily
d8a6cf8b185e98d6e60961e306a4bbeb4e7360dc
[ "MIT" ]
null
null
null
offer/src/main/java/leetCode/L10221_MaxSquare.java
seawindnick/javaFamily
d8a6cf8b185e98d6e60961e306a4bbeb4e7360dc
[ "MIT" ]
null
null
null
11.283019
50
0.404682
8,797
package leetCode; //在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。 // // // // 示例 1: // // //输入:matrix = [ // ["1","0","1","0","0"], // ["1","0","1","1","1"], // ["1","1","1","1","1"] //,["1","0","0","1","0"] // ] //输出:4 // // // 示例 2: // // //输入:matrix = [["0","1"],["1","0"]] //输出:1 // // // 示例 3: // // //输入:matrix = [["0"]] //输出:0 // // // // // 提示: // // // m == matrix.length // n == matrix[i].length // 1 <= m, n <= 300 // matrix[i][j] 为 '0' 或 '1' // // Related Topics 动态规划 // 👍 762 👎 0 public class L10221_MaxSquare { // // public static int maximalSquare(int[][] m) { // // } }
3e14c30bb78bef4fabada0ffb1afa513f340b806
157
java
Java
hook/src/test/java/io/gunmetal/benchmarks/testmocks/D.java
rsby/gunmetal
f5907a839af6808c9e4bbe80af92b7e4357f6a3b
[ "Apache-2.0" ]
2
2017-10-25T09:11:58.000Z
2021-08-06T20:26:08.000Z
hook/src/test/java/io/gunmetal/benchmarks/testmocks/D.java
rsby/gunmetal
f5907a839af6808c9e4bbe80af92b7e4357f6a3b
[ "Apache-2.0" ]
null
null
null
hook/src/test/java/io/gunmetal/benchmarks/testmocks/D.java
rsby/gunmetal
f5907a839af6808c9e4bbe80af92b7e4357f6a3b
[ "Apache-2.0" ]
null
null
null
10.466667
41
0.547771
8,798
package io.gunmetal.benchmarks.testmocks; /** * @author rees.byars */ public class D { public E e; public D(E e) { this.e = e; } }
3e14c30dc30771a063f7e34a0d9644750c52c84a
989
java
Java
configuration-detector/subjects/randoop/randoop-src/randoop/util/IMultiMap.java
zhang-sai/config-errors
d02c2ce1c3808ea1f3c8f59411c0af913eab2617
[ "MIT" ]
1
2021-10-20T13:06:31.000Z
2021-10-20T13:06:31.000Z
configuration-detector/subjects/randoop/randoop-src/randoop/util/IMultiMap.java
zhang-sai/config-errors
d02c2ce1c3808ea1f3c8f59411c0af913eab2617
[ "MIT" ]
1
2021-05-24T06:07:05.000Z
2021-05-24T06:07:05.000Z
configuration-detector/subjects/randoop/randoop-src/randoop/util/IMultiMap.java
zhang-sai/config-errors
d02c2ce1c3808ea1f3c8f59411c0af913eab2617
[ "MIT" ]
1
2021-02-16T22:01:33.000Z
2021-02-16T22:01:33.000Z
19.78
68
0.610718
8,799
package randoop.util; import java.util.Set; /** * Represents a relation from a set of T1s (the keys) to * another set of T2s (the values). * In partucular, each key maps to a set of values. */ public interface IMultiMap<T1, T2> { /** * Precondition: the mapping key->value is not already in the map. * * @param key cannot be null. * @param value cannot be null. */ void add(T1 key, T2 value); /** * Precondition: the mapping key->value is in the map. * * @param key cannot be null. * @param value cannot be null. */ void remove(T1 key, T2 value); /** * Returns the values that the given key maps to. * @param key cannot be null. */ Set<T2> getValues(T1 key); /** * Returns the set of keys in this map (the domain). */ Set<T1> keySet(); /** * Returns the size of this map: the number of mappings. */ int size(); /** * Returns a String representation of this map. */ String toString(); }
3e14c4a5eb2318b3b42b159cde1ab9ba88a34120
844
java
Java
MuzeiGram/app/src/main/java/com/cstewart/android/muzeigram/controller/MuzeiGramActivity.java
cstew/MuzeiGram
c6fffbaf0fe5fca0d00203f6eae84366b277bf5b
[ "Apache-2.0" ]
3
2015-06-08T16:20:02.000Z
2019-11-21T12:00:37.000Z
MuzeiGram/app/src/main/java/com/cstewart/android/muzeigram/controller/MuzeiGramActivity.java
cstew/MuzeiGram
c6fffbaf0fe5fca0d00203f6eae84366b277bf5b
[ "Apache-2.0" ]
1
2018-07-16T06:54:45.000Z
2018-07-16T14:39:52.000Z
MuzeiGram/app/src/main/java/com/cstewart/android/muzeigram/controller/MuzeiGramActivity.java
cstew/MuzeiGram
c6fffbaf0fe5fca0d00203f6eae84366b277bf5b
[ "Apache-2.0" ]
3
2017-04-16T11:44:16.000Z
2020-01-10T15:41:54.000Z
26.375
75
0.67654
8,800
package com.cstewart.android.muzeigram.controller; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.cstewart.android.muzeigram.MuzeiGramApplication; public class MuzeiGramActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MuzeiGramApplication.get(this).inject(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // I'm cheating here in all Activities and just calling finish. // At least the code is in one place. case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } }
3e14c50ec89451d06ebdacb90bbd55d4ac9e58e9
6,186
java
Java
zippy/edu.uci.python/src/edu/uci/python/nodes/control/GetIteratorNode.java
lucapele/pele-c
ff6d06794a171f8e1b08fc6246446d9777116f56
[ "BSD-3-Clause" ]
319
2016-09-22T15:54:48.000Z
2022-03-18T02:36:58.000Z
zippy/edu.uci.python/src/edu/uci/python/nodes/control/GetIteratorNode.java
lucapele/pele-c
ff6d06794a171f8e1b08fc6246446d9777116f56
[ "BSD-3-Clause" ]
9
2016-11-03T21:56:41.000Z
2020-08-09T19:27:37.000Z
zippy/edu.uci.python/src/edu/uci/python/nodes/control/GetIteratorNode.java
lucapele/pele-c
ff6d06794a171f8e1b08fc6246446d9777116f56
[ "BSD-3-Clause" ]
27
2016-10-06T16:05:32.000Z
2022-03-18T02:37:00.000Z
30.623762
89
0.686389
8,801
/* * Copyright (c) 2013, Regents of the University of California * All rights reserved. * * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.python.nodes.control; import com.oracle.truffle.api.*; import com.oracle.truffle.api.dsl.*; import com.oracle.truffle.api.frame.*; import com.oracle.truffle.api.nodes.*; import edu.uci.python.ast.VisitorIF; import edu.uci.python.nodes.*; import edu.uci.python.nodes.expression.*; import edu.uci.python.nodes.truffle.*; import edu.uci.python.runtime.array.*; import edu.uci.python.runtime.datatype.*; import edu.uci.python.runtime.iterator.*; import edu.uci.python.runtime.object.*; import edu.uci.python.runtime.sequence.*; import edu.uci.python.runtime.sequence.storage.*; @GenerateNodeFactory public abstract class GetIteratorNode extends UnaryOpNode { public abstract Object executeWith(VirtualFrame frame, Object value); @Specialization(guards = "isIntStorage(primary)") public Object doPListInt(PList primary) { return new PIntegerSequenceIterator((IntSequenceStorage) primary.getStorage()); } @Specialization(guards = "isLongStorage(primary)") public Object doPListLong(PList primary) { return new PLongSequenceIterator((LongSequenceStorage) primary.getStorage()); } @Specialization(guards = "isDoubleStorage(primary)") public Object doPListDouble(PList primary) { return new PDoubleSequenceIterator((DoubleSequenceStorage) primary.getStorage()); } @Specialization public Object doPList(PList value) { return value.__iter__(); } @Specialization public Object doPRange(PRange value) { return value.__iter__(); } @Specialization public Object doPIntArray(PIntArray value) { return value.__iter__(); } @Specialization public Object doPDoubleArray(PDoubleArray value) { return value.__iter__(); } @Specialization public Object doCharArray(PCharArray value) { return value.__iter__(); } @Specialization public Object doPSequence(PSequence value) { return value.__iter__(); } @Specialization public Object doPBaseSet(PBaseSet value) { return value.__iter__(); } @Specialization public Object doString(String value) { return new PStringIterator(value); } @Specialization public Object doPDictionary(PDict value) { return value.__iter__(); } @Specialization public Object doPEnumerate(PEnumerate value) { return value.__iter__(); } @Specialization public Object doPZip(PZip value) { return value.__iter__(); } @Specialization public PIntegerIterator doPIntegerIterator(PIntegerIterator value) { return value; } @Specialization public PIterator doPIterable(PIterable value) { return value.__iter__(); } @Specialization public PGenerator doPGenerator(PGenerator value) { replace(new GetGeneratorIteratorNode(getOperand())); return value; } @Specialization public PIterator doPIterator(PIterator value) { return value; } @Specialization public Object doPythonObject(VirtualFrame frame, PythonObject value) { return doSpecialMethodCall(frame, "__iter__", value); } @Fallback public PIterator doGeneric(Object value) { throw new RuntimeException("tuple does not support iterable object " + value); } public static class GetGeneratorIteratorNode extends GetIteratorNode { @Child PNode operandNode; private PGenerator cachedGenerator; public GetGeneratorIteratorNode(PNode operandNode) { this.operandNode = operandNode; } protected GetGeneratorIteratorNode(GetGeneratorIteratorNode prev) { this.operandNode = prev.getOperand(); } public final PGenerator getGenerator() { return cachedGenerator; } @Override public PNode getOperand() { return operandNode; } @Override public Object executeWith(VirtualFrame frame, Object value) { PGenerator generator; try { generator = PythonTypesGen.expectPGenerator(value); } catch (UnexpectedResultException e) { throw new IllegalStateException(); } if (CompilerDirectives.inInterpreter()) { if (cachedGenerator == null) { cachedGenerator = generator; } } return generator; } @Override public Object execute(VirtualFrame frame) { return executeWith(frame, operandNode.execute(frame)); } } @Override public <R> R accept(VisitorIF<R> visitor) throws Exception { return visitor.visitGetIteratorNode(this); } }
3e14c7a6c687fcd4d4051c642b17fd697e5aabf4
5,680
java
Java
platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurableProxy.java
kirpichik/intellij-community
bc2fe124431bd9d73d694517777790c8a119e773
[ "Apache-2.0" ]
1
2019-08-28T13:18:50.000Z
2019-08-28T13:18:50.000Z
platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurableProxy.java
kirpichik/intellij-community
bc2fe124431bd9d73d694517777790c8a119e773
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurableProxy.java
kirpichik/intellij-community
bc2fe124431bd9d73d694517777790c8a119e773
[ "Apache-2.0" ]
null
null
null
32.272727
140
0.736972
8,802
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins; import com.intellij.ide.ui.UINumericRange; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; /** * @author Alexander Lobas */ public class PluginManagerConfigurableProxy implements SearchableConfigurable, Configurable.NoScroll, Configurable.NoMargin, Configurable.TopComponentProvider { private final SearchableConfigurable myConfigurable; public PluginManagerConfigurableProxy() { if (Registry.is("show.new.layout.plugin.page", false)) { myConfigurable = new PluginManagerConfigurableNewLayout(); } else if (Registry.is("show.new.plugin.page", false)) { myConfigurable = new PluginManagerConfigurableNew(); } else { myConfigurable = new PluginManagerConfigurable(PluginManagerUISettings.getInstance()); } } @NotNull @Override public String getId() { return myConfigurable.getId(); } @Nullable @Override public Runnable enableSearch(String option) { return myConfigurable.enableSearch(option); } @Nls(capitalization = Nls.Capitalization.Title) @Override public String getDisplayName() { return myConfigurable.getDisplayName(); } @Nullable @Override public String getHelpTopic() { return myConfigurable.getHelpTopic(); } @Override public boolean isModified(@NotNull JTextField textField, @NotNull String value) { return myConfigurable.isModified(textField, value); } @Override public boolean isModified(@NotNull JTextField textField, int value, @NotNull UINumericRange range) { return myConfigurable.isModified(textField, value, range); } @Override public boolean isModified(@NotNull JToggleButton toggleButton, boolean value) { return myConfigurable.isModified(toggleButton, value); } @Override public <T> boolean isModified(@NotNull ComboBox<T> comboBox, T value) { return myConfigurable.isModified(comboBox, value); } @Override public JComponent getPreferredFocusedComponent() { return myConfigurable.getPreferredFocusedComponent(); } @Override public boolean isAvailable() { return myConfigurable instanceof Configurable.TopComponentProvider; } @NotNull @Override public Component getCenterComponent(@NotNull TopComponentController controller) { return ((Configurable.TopComponentProvider)myConfigurable).getCenterComponent(controller); } @Nullable @Override public JComponent createComponent() { JComponent component = myConfigurable.createComponent(); if (component != null && myConfigurable instanceof PluginManagerConfigurable) { if (!component.getClass().equals(JPanel.class)) { // some custom components do not support borders JPanel panel = new JPanel(new BorderLayout()); panel.add(BorderLayout.CENTER, component); component = panel; } component.setBorder(JBUI.Borders.empty(5, 10, 10, 10)); } return component; } @Override public boolean isModified() { return myConfigurable.isModified(); } @Override public void apply() throws ConfigurationException { myConfigurable.apply(); } @Override public void reset() { myConfigurable.reset(); } @Override public void disposeUIResources() { myConfigurable.disposeUIResources(); } public void select(@NotNull IdeaPluginDescriptor... descriptors) { if (myConfigurable instanceof PluginManagerConfigurableInfo) { ((PluginManagerConfigurableInfo)myConfigurable).select(descriptors); } else { ((PluginManagerConfigurable)myConfigurable).select(descriptors); } } public void enable(@NotNull IdeaPluginDescriptor... descriptors) { if (myConfigurable instanceof PluginManagerConfigurableInfo) { ((PluginManagerConfigurableInfo)myConfigurable).getPluginModel().changeEnableDisable(descriptors, true); } else { ((InstalledPluginsTableModel)((PluginManagerConfigurable)myConfigurable).getOrCreatePanel().getPluginsModel()) .enableRows(descriptors, Boolean.TRUE); } } public static void showPluginConfigurableAndEnable(@Nullable Project project, @NotNull IdeaPluginDescriptor... descriptors) { PluginManagerConfigurableProxy configurable = new PluginManagerConfigurableProxy(); ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> { configurable.enable(descriptors); configurable.select(descriptors); }); } public static void showPluginConfigurable(@Nullable Component parent, @Nullable Project project, @NotNull IdeaPluginDescriptor... descriptors) { PluginManagerConfigurableProxy configurable = new PluginManagerConfigurableProxy(); Runnable init = () -> configurable.select(descriptors); ShowSettingsUtil util = ShowSettingsUtil.getInstance(); if (parent != null) { util.editConfigurable(parent, configurable, init); } else { util.editConfigurable(project, configurable, init); } } }
3e14c7e9b2e0ce12b44da91a1fd7eff536d44a04
21,690
java
Java
dataverse-webapp/src/test/java/edu/harvard/iq/dataverse/datafile/DataFileCreatorTest.java
CeON/dataverse
6e657572cf000532a8660f57e5484817f0d016c4
[ "Apache-2.0" ]
7
2019-12-13T22:30:06.000Z
2021-12-28T20:38:48.000Z
dataverse-webapp/src/test/java/edu/harvard/iq/dataverse/datafile/DataFileCreatorTest.java
CeON/dataverse
6e657572cf000532a8660f57e5484817f0d016c4
[ "Apache-2.0" ]
1,294
2019-01-08T18:55:57.000Z
2022-03-31T09:47:19.000Z
dataverse-webapp/src/test/java/edu/harvard/iq/dataverse/datafile/DataFileCreatorTest.java
CeON/dataverse
6e657572cf000532a8660f57e5484817f0d016c4
[ "Apache-2.0" ]
5
2020-02-22T14:30:40.000Z
2020-02-27T18:07:02.000Z
55.19084
165
0.701337
8,803
package edu.harvard.iq.dataverse.datafile; import edu.harvard.iq.dataverse.UnitTestUtils; import edu.harvard.iq.dataverse.datasetutility.FileExceedsMaxSizeException; import edu.harvard.iq.dataverse.datasetutility.VirusFoundException; import edu.harvard.iq.dataverse.license.TermsOfUseFactory; import edu.harvard.iq.dataverse.license.TermsOfUseFormMapper; import edu.harvard.iq.dataverse.persistence.datafile.DataFile; import edu.harvard.iq.dataverse.persistence.datafile.DataFile.ChecksumType; import edu.harvard.iq.dataverse.persistence.datafile.ingest.IngestError; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import edu.harvard.iq.dataverse.settings.SettingsServiceBean.Key; import edu.harvard.iq.dataverse.util.JhoveConfigurationInitializer; import edu.harvard.iq.dataverse.util.SystemConfig; import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.inject.Inject; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.atIndex; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) public class DataFileCreatorTest { @InjectMocks private DataFileCreator dataFileCreator = new DataFileCreator(); @Mock private SettingsServiceBean settingsService; @Mock private AntivirFileScanner antivirFileScanner; @Mock private FileTypeDetector fileTypeDetector; @Mock private ArchiveUncompressedSizeCalculator uncompressedCalculator; @Mock private TermsOfUseFactory termsOfUseFactory; @Mock private TermsOfUseFormMapper termsOfUseFormMapper; @TempDir Path tempDir; @BeforeEach void before() throws IOException { System.setProperty(SystemConfig.FILES_DIRECTORY, tempDir.toString()); } @AfterEach void after() { System.clearProperty(SystemConfig.FILES_DIRECTORY); } // -------------------- TESTS -------------------- @Test void createDataFiles_shouldThrowExceptionOnTooBigFile() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("images/coffeeshop_thumbnail_64.png"); when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024L); // when & then assertThatThrownBy(() -> dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "filename.png", "image/png")) .isInstanceOf(FileExceedsMaxSizeException.class); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)).isEmpty(); } @ParameterizedTest @CsvSource({ "application/supplied, application/x-stata, application/x-stata", "application/supplied, application/fits-gzipped, application/fits-gzipped", "application/supplied, application/zip, application/zip", "application/octet-stream, application/detected, application/detected", "text/csv, application/detected, text/csv", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/detected, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/supplied, image/jpeg, application/supplied"}) void createDataFiles_shouldPickCorrectContentType(String suppliedContentType, String detectedContentType, String expectedContentType) throws IOException { // given when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024L); when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); when(fileTypeDetector.determineFileType(any(), any())).thenReturn(detectedContentType); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(new byte[0]), "filename", suppliedContentType); // then assertThat(datafiles).hasSize(1); assertThat(datafiles).element(0).extracting(DataFile::getContentType).isEqualTo(expectedContentType); } @Test void createDataFiles_shouldThrowExceptionOnVirusInfectedFile() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("images/coffeeshop_thumbnail_64.png"); when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024L*1024L); when(settingsService.isTrueForKey(Key.AntivirusScannerEnabled)).thenReturn(true); when(antivirFileScanner.isFileOverSizeLimit(any(), any())).thenReturn(false); when(antivirFileScanner.scan(any())).thenReturn(new AntivirScannerResponse(true, "Infected file")); when(fileTypeDetector.determineFileType(any(), any())).thenReturn("image/png"); // when & then assertThatThrownBy(() -> dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "filename.png", "image/png")) .isInstanceOf(VirusFoundException.class); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)).isEmpty(); } @Test void createDataFiles_shouldUnpackGzippedFitsFile() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/sample.fits.gz"); when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024L*1024L); when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); when(fileTypeDetector.determineFileType(any(), any())).thenReturn("application/fits-gzipped"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "sample.fits.gz", "application/fits-gzipped"); // then assertThat(datafiles).hasSize(1) .satisfies(dataFile -> { assertThat(dataFile.getContentType()).isEqualTo("application/fits"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("a4791e42cd1045892f9c41f11b50bad8"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("sample.fits"); }, atIndex(0)); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)).hasSize(1) .element(0, InstanceOfAssertFactories.PATH) .hasFileName(datafiles.get(0).getStorageIdentifier()); } @Test void createDataFiles_shouldNotUnpackGzippedFitsFileIfTooBigAfterUnpack() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/sample.fits.gz"); when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(zipBytes.length + 1L); when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); when(fileTypeDetector.determineFileType(any(), any())).thenReturn("application/fits-gzipped"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "sample.fits.gz", "application/fits-gzipped"); // then assertThat(datafiles).hasSize(1) .satisfies(dataFile -> { assertThat(dataFile.getContentType()).isEqualTo("application/fits-gzipped"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("bb566e4c4afef02a279471c64e964602"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("sample.fits.gz"); }, atIndex(0)); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)).hasSize(1) .element(0, InstanceOfAssertFactories.PATH) .hasFileName(datafiles.get(0).getStorageIdentifier()); } @Test void createDataFiles_shouldUnpackZipFile() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/archive.zip"); lenient().when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024*1024L); lenient().when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); lenient().when(settingsService.getValueForKeyAsLong(Key.ZipUploadFilesLimit)).thenReturn(1000L); when(fileTypeDetector.determineFileType(any(), any())).thenReturn("application/zip"); when(fileTypeDetector.determineFileType(any(), eq("plaintext_ascii.txt"))).thenReturn("text/plain"); when(fileTypeDetector.determineFileType(any(), eq("plaintext_utf8.txt"))).thenReturn("text/plain"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "archive.zip", "application/zip"); // then assertThat(datafiles).hasSize(2) .satisfies(dataFile -> { assertThat(dataFile.getContentType()).isEqualTo("text/plain"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("0cc175b9c0f1b6a831c399e269772661"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("plaintext_ascii.txt"); }, atIndex(0)) .satisfies(dataFile -> { assertThat(dataFile.getContentType()).isEqualTo("text/plain"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("d5c256b294dabd02bd496a2b1de99bd2"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("plaintext_utf8.txt"); }, atIndex(1)); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)) .extracting(f -> f.getFileName().toString()) .containsExactlyInAnyOrder( datafiles.get(0).getStorageIdentifier(), datafiles.get(1).getStorageIdentifier()); } @Test void createDataFiles_shouldNotUnpackMacOsFilesystemFiles() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/archive_with_dirs_and_mac_fake_files.zip"); lenient().when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024*1024L); lenient().when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); lenient().when(settingsService.getValueForKeyAsLong(Key.ZipUploadFilesLimit)).thenReturn(1000L); when(fileTypeDetector.determineFileType(any(), any())).thenReturn("application/zip"); when(fileTypeDetector.determineFileType(any(), eq("plaintext_ascii.txt"))).thenReturn("text/plain"); when(fileTypeDetector.determineFileType(any(), eq("plaintext_utf8.txt"))).thenReturn("text/plain"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "archive.zip", "application/zip"); // then assertThat(datafiles).hasSize(2) .satisfies(dataFile -> { assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("plaintext_utf8.txt"); assertThat(dataFile.getFileMetadatas().get(0).getDirectoryLabel()).isEqualTo("folder1"); assertThat(dataFile.getContentType()).isEqualTo("text/plain"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("d5c256b294dabd02bd496a2b1de99bd2"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); }, atIndex(0)) .satisfies(dataFile -> { assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("plaintext_ascii.txt"); assertThat(dataFile.getFileMetadatas().get(0).getDirectoryLabel()).isEqualTo("folder1"); assertThat(dataFile.getContentType()).isEqualTo("text/plain"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("0cc175b9c0f1b6a831c399e269772661"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); }, atIndex(1)); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)) .extracting(f -> f.getFileName().toString()) .containsExactlyInAnyOrder( datafiles.get(0).getStorageIdentifier(), datafiles.get(1).getStorageIdentifier()); } @Test void createDataFiles_shouldPreserveDirectoryStructure() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/archive_with_dirs_and_mac_fake_files.zip"); lenient().when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024*1024L); lenient().when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); lenient().when(settingsService.getValueForKeyAsLong(Key.ZipUploadFilesLimit)).thenReturn(1000L); lenient().when(fileTypeDetector.determineFileType(any(), eq("archive.zip"))).thenReturn("application/zip"); lenient().when(fileTypeDetector.determineFileType(any(), eq("plaintext_utf8.txt"))).thenReturn("text/plain"); lenient().when(fileTypeDetector.determineFileType(any(), eq("plaintext_ascii.txt"))).thenReturn("text/plain"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "archive.zip", "application/zip"); // then assertThat(datafiles).hasSize(2) .satisfies(dataFile -> { assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("plaintext_utf8.txt"); assertThat(dataFile.getFileMetadatas().get(0).getDirectoryLabel()).isEqualTo("folder1"); assertThat(dataFile.getContentType()).isEqualTo("text/plain"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("d5c256b294dabd02bd496a2b1de99bd2"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); }, atIndex(0)) .satisfies(dataFile -> { assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("plaintext_ascii.txt"); assertThat(dataFile.getFileMetadatas().get(0).getDirectoryLabel()).isEqualTo("folder1"); assertThat(dataFile.getContentType()).isEqualTo("text/plain"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("0cc175b9c0f1b6a831c399e269772661"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); }, atIndex(1)); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)) .extracting(f -> f.getFileName().toString()) .containsExactlyInAnyOrder( datafiles.get(0).getStorageIdentifier(), datafiles.get(1).getStorageIdentifier()); } @Test void createDataFiles_shouldNotUnpackZipFileIfTooManyFilesToUnpack() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/archive.zip"); lenient().when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024*1024L); lenient().when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); lenient().when(settingsService.getValueForKeyAsLong(Key.ZipUploadFilesLimit)).thenReturn(1L); lenient().when(fileTypeDetector.determineFileType(any(), eq("archive.zip"))).thenReturn("application/zip"); lenient().when(fileTypeDetector.determineFileType(any(), eq("plaintext_utf8.txt"))).thenReturn("text/plain"); lenient().when(fileTypeDetector.determineFileType(any(), eq("plaintext_ascii.txt"))).thenReturn("text/plain"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "archive.zip", "application/zip"); // then assertThat(datafiles).hasSize(1) .satisfies(dataFile -> { assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("archive.zip"); assertThat(dataFile.getContentType()).isEqualTo("application/zip"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("6246a24606128a4f34ae799d1e0d457d"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); assertThat(dataFile.getIngestReport().getErrorKey()).isEqualTo(IngestError.UNZIP_FILE_LIMIT_FAIL); }, atIndex(0)); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)) .extracting(f -> f.getFileName().toString()) .contains(datafiles.get(0).getStorageIdentifier()); } @Test void createDataFiles_shouldNotUnpackZipFileIfContainsTooBigFile() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/archive_single_file.zip"); lenient().when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(zipBytes.length + 1L); lenient().when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); lenient().when(settingsService.getValueForKeyAsLong(Key.ZipUploadFilesLimit)).thenReturn(1000L); when(fileTypeDetector.determineFileType(any(), any())).thenReturn("application/zip"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "archive.zip", "application/zip"); // then assertThat(datafiles).hasSize(1) .satisfies(dataFile -> { assertThat(dataFile.getFileMetadatas().get(0).getLabel()).isEqualTo("archive.zip"); assertThat(dataFile.getContentType()).isEqualTo("application/zip"); assertThat(dataFile.getChecksumType()).isEqualTo(ChecksumType.MD5); assertThat(dataFile.getChecksumValue()).isEqualTo("a1e42cad3947efd6e5d10bdb43e8e074"); assertThat(dataFile.getStorageIdentifier()).isNotEmpty(); assertThat(dataFile.getIngestReport().getErrorKey()).isEqualTo(IngestError.UNZIP_SIZE_FAIL); }, atIndex(0)); assertThat(Files.walk(tempDir).filter(Files::isRegularFile)).hasSize(1) .element(0, InstanceOfAssertFactories.PATH) .hasFileName(datafiles.get(0).getStorageIdentifier()); } @Test void createDataFiles_shouldRezipShapefiles() throws IOException { // given byte[] zipBytes = UnitTestUtils.readFileToByteArray("jhove/fake_shapefile.zip"); lenient().when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024*1024L); lenient().when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); lenient().when(fileTypeDetector.determineFileType(any(), any())).thenReturn("application/zipped-shapefile"); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(zipBytes), "fake_shapefile.zip", "application/zipped-shapefile"); // then assertThat(datafiles).hasSize(5).extracting(df -> df.getLatestFileMetadata().getLabel()) .containsExactlyInAnyOrder("shape1.zip", "shape2.zip", "shape2", "shape2.txt", "README.txt"); } @Test void createDataFiles_shouldCalculateUncompressedSize() throws IOException { // given lenient().when(settingsService.getValueForKeyAsLong(Key.MaxFileUploadSizeInBytes)).thenReturn(1024*1024L); lenient().when(settingsService.getValueForKey(Key.FileFixityChecksumAlgorithm)).thenReturn("MD5"); lenient().when(fileTypeDetector.determineFileType(any(), any())).thenReturn("application/something"); when(uncompressedCalculator.calculateUncompressedSize(any(), any(), any())).thenReturn(101L); // when List<DataFile> datafiles = dataFileCreator.createDataFiles(new ByteArrayInputStream(new byte[0]), "name", "application/something"); // then assertThat(datafiles).hasSize(1); assertThat(datafiles.get(0).getUncompressedSize()).isEqualTo(101L); } }
3e14c997fa3ff48cf42bc13348a57799080df485
468
java
Java
src/com/supermariorun/main/Interfaceable.java
hungle546/super-mario-run
7d74a65794fc394d2afaed7f5ac41edccd836a14
[ "Apache-2.0" ]
2
2021-02-09T06:17:10.000Z
2021-02-15T15:00:46.000Z
src/com/supermariorun/main/Interfaceable.java
hungle546/super-mario-run
7d74a65794fc394d2afaed7f5ac41edccd836a14
[ "Apache-2.0" ]
3
2022-01-25T02:46:44.000Z
2022-02-01T02:54:38.000Z
src/com/supermariorun/main/Interfaceable.java
hungle546/super-mario-run
7d74a65794fc394d2afaed7f5ac41edccd836a14
[ "Apache-2.0" ]
1
2021-01-31T22:17:38.000Z
2021-01-31T22:17:38.000Z
31.2
52
0.805556
8,804
package com.supermariorun.main; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public interface Interfaceable extends Displayable { public void mousePressed(MouseEvent e); public void mouseReleased(MouseEvent e); public void mouseClicked(MouseEvent e); public void mouseDragged(MouseEvent e); public void mouseMoved(MouseEvent e); public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e); }
3e14c9a1b822625f7fa4f3819d8357b60b342e35
6,906
java
Java
security/src/main/org/jboss/security/plugins/DefaultLoginConfig.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
security/src/main/org/jboss/security/plugins/DefaultLoginConfig.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
security/src/main/org/jboss/security/plugins/DefaultLoginConfig.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
31.266968
108
0.665412
8,805
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.security.plugins; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.ReflectionException; import javax.security.auth.login.Configuration; import javax.security.auth.login.AppConfigurationEntry; import org.jboss.logging.Logger; /** An mbean that uses the default JAAS login configuration file based implementation. @author hzdkv@example.com @version $Revision: 57203 $ */ public class DefaultLoginConfig implements DynamicMBean { private static Logger log = Logger.getLogger(DefaultLoginConfig.class); private String authConfig = "auth.conf"; private Configuration theConfig; /** Creates a new instance of DefaultLoginConfig */ public DefaultLoginConfig() { } /** Get the resource path to the JAAS login configuration file to use. */ public String getAuthConfig() { return authConfig; } /** Set the resource path or URL to the JAAS login configuration file to use. The default is "auth.conf". */ public void setAuthConfig(String authConfURL) throws MalformedURLException { this.authConfig = authConfURL; // Set the JAAS login config file if not already set ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL loginConfig = loader.getResource(authConfig); if( loginConfig != null ) { System.setProperty("java.security.auth.login.config", loginConfig.toExternalForm()); if (log.isInfoEnabled()) log.info("Using JAAS LoginConfig: "+loginConfig.toExternalForm()); } else { log.warn("Resource: "+authConfig+" not found"); } } /** Return the Configuration instance managed by this mbean. This simply obtains the default Configuration by calling Configuration.getConfiguration. Note that this means this mbean must be the first pushed onto the config stack if it is used. @see javax.security.auth.login.Configuration */ public Configuration getConfiguration(Configuration currentConfig) { if( theConfig == null ) { theConfig = Configuration.getConfiguration(); log.debug("theConfig set to: "+theConfig); } return theConfig; } // Begin DynamicMBean interfaces public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException { if( name.equals("AuthConfig") ) return getAuthConfig(); throw new AttributeNotFoundException(name+": is not an attribute"); } public AttributeList getAttributes(String[] names) { AttributeList list = new AttributeList(); for(int n = 0; n < names.length; n ++) { String name = names[n]; try { Object value = getAttribute(name); Attribute attr = new Attribute(name, value); list.add(attr); } catch(Exception e) { } } return list; } public MBeanInfo getMBeanInfo() { Class c = getClass(); MBeanAttributeInfo[] attrInfo = { new MBeanAttributeInfo("AuthConfig", "java.lang.String", "", true, true, false) }; Constructor ctor = null; try { Class[] sig = {}; ctor = c.getDeclaredConstructor(sig); } catch(Exception e) { } MBeanConstructorInfo[] ctorInfo = { new MBeanConstructorInfo("Default ctor", ctor) }; Method getConfiguration = null; try { Class[] sig = {Configuration.class}; getConfiguration = c.getDeclaredMethod("getConfiguration", sig); } catch(Exception e) { } MBeanOperationInfo[] opInfo = { new MBeanOperationInfo("Access the LoginConfiguration", getConfiguration) }; MBeanInfo info = new MBeanInfo(c.getName(), "Default JAAS LoginConfig", attrInfo, ctorInfo, opInfo, null); return info; } public Object invoke(String method, Object[] args, String[] signature) throws MBeanException, ReflectionException { Object value = null; if( method.equals("getConfiguration") ) { Configuration currentConfig = (Configuration) args[0]; value = this.getConfiguration(currentConfig); } return value; } public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { String name = attribute.getName(); String value = (String) attribute.getValue(); if( name.equals("AuthConfig") ) { try { setAuthConfig(value); } catch(Exception e) { throw new MBeanException(e); } } else throw new AttributeNotFoundException(name+": is not an attribute"); } public AttributeList setAttributes(AttributeList attributeList) { AttributeList list = new AttributeList(); for(int n = 0; n < attributeList.size(); n ++) { Attribute attr = (Attribute) attributeList.get(n); try { setAttribute(attr); list.add(attr); } catch(Exception e) { } } return list; } // End DynamicMBean interfaces }
3e14c9ce18d2cd64caa62e683e1c838403bbda2d
10,950
java
Java
endo-server/src/main/java/org/endofusion/endoserver/repository/InstrumentRepositoryImpl.java
VagTsop/endo-project
865cf2a4ecc17936d0ca39740259546f731c1ce6
[ "MIT" ]
null
null
null
endo-server/src/main/java/org/endofusion/endoserver/repository/InstrumentRepositoryImpl.java
VagTsop/endo-project
865cf2a4ecc17936d0ca39740259546f731c1ce6
[ "MIT" ]
null
null
null
endo-server/src/main/java/org/endofusion/endoserver/repository/InstrumentRepositoryImpl.java
VagTsop/endo-project
865cf2a4ecc17936d0ca39740259546f731c1ce6
[ "MIT" ]
null
null
null
44.693878
137
0.663288
8,806
package org.endofusion.endoserver.repository; import org.endofusion.endoserver.dto.InstrumentDto; import org.endofusion.endoserver.dto.SortField; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @Repository("InstrumentRepository") public class InstrumentRepositoryImpl implements InstrumentRepository { @Autowired protected NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Override public List<InstrumentDto> fetchInstruments() { String sqlQuery = "select distinct(i.name) as instrumentName \n" + "from instruments as i\n" + "order by i.name asc"; return namedParameterJdbcTemplate.query(sqlQuery, new BeanPropertyRowMapper<>(InstrumentDto.class)); } @Override public List<InstrumentDto> fetchInstrumentsSeriesCodes() { String sqlQuery = "select ins.instrument_series_qr_code as instrumentSeriesCode \n" + "from instruments_series as ins \n"; return namedParameterJdbcTemplate.query(sqlQuery, new BeanPropertyRowMapper<>(InstrumentDto.class)); } @Override public List<InstrumentDto> fetchInstrumentsByInstrumentSeriesCode(long qrCode) { MapSqlParameterSource in = new MapSqlParameterSource(); String sqlQuery = "Select i.name as instrumentName\n" + "From instruments as i \n" + "where i.instrument_series_id = :qrCode \n"; in.addValue("qrCode", qrCode); return namedParameterJdbcTemplate.query(sqlQuery, in, new BeanPropertyRowMapper<>(InstrumentDto.class)); } @Override public Page<InstrumentDto> getInstrumentsList(Pageable pageable, InstrumentDto dto) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String sqlFromClause = "From instruments as i\n" + "left join instruments_series as os on i.instrument_series_id = os.instrument_series_id\n"; String sqlWhereClause = "WHERE i.instrument_id is not null\n"; MapSqlParameterSource in = new MapSqlParameterSource(); if (dto.getInstrumentName() != null && !dto.getInstrumentName().isEmpty()) { sqlWhereClause += "AND i.name like :instrumentName\n"; in.addValue("instrumentName", "%" + dto.getInstrumentName() + "%"); } if (dto.getPurchaseDateFrom() != null) { sqlWhereClause += "AND i.purchase_date >= :purchaseDateFrom "; in.addValue("purchaseDateFrom", formatter.format(dto.getPurchaseDateFrom())); } if (dto.getPurchaseDateTo() != null) { sqlWhereClause += "AND i.purchase_date <= :purchaseDateTo "; in.addValue("purchaseDateTo", formatter.format(dto.getPurchaseDateTo())); } if (dto.getInstrumentSeriesCodesList() != null) { sqlWhereClause += "AND i.instrument_series_id in ( :instrumentSeriesCodesList)"; in.addValue("instrumentSeriesCodesList", dto.getInstrumentSeriesCodesList()); } List<String> validSortColumns = new ArrayList<String>(); validSortColumns.add("INSTRUMENT_NAME"); validSortColumns.add("INSTRUMENT_REF"); validSortColumns.add("INSTRUMENT_LOT"); validSortColumns.add("INSTRUMENT_MANUFACTURER"); validSortColumns.add("INSTRUMENT_PURCHASE_DATE"); validSortColumns.add("INSTRUMENT_SERIES_CODE"); List<Sort.Order> sortOrders = pageable.getSort().stream().collect(Collectors.toList()); Sort.Order order = sortOrders.get(0); String sqlPaginationClause = "ORDER BY "; if (validSortColumns.contains(order.getProperty())) { sqlPaginationClause += SortField.Field.valueOf(order.getProperty()).getValue(); if (order.getDirection().isAscending()) { sqlPaginationClause += " ASC "; } else { sqlPaginationClause += " DESC "; } } sqlPaginationClause += "limit :offset,:size"; in.addValue("offset", pageable.getOffset()); in.addValue("size", pageable.getPageSize()); String rowCountSql = "SELECT count(*) AS row_count " + sqlFromClause + sqlWhereClause; ; int total = this.namedParameterJdbcTemplate.queryForObject( rowCountSql, in, Integer.class); String sqlQuery = "Select i.instrument_id as instrumentId, i.name as instrumentName, i.description as instrumentDescription,\n" + "i.ref as instrumentRef, i.lot as instrumentLot, i.manufacturer as instrumentManufacturer,\n" + "i.purchase_date as instrumentPurchaseDate, i.notes as instrumentNotes,\n" + "os.instrument_series_qr_code as instrumentSeriesQrCode \n" + sqlFromClause + sqlWhereClause + sqlPaginationClause; List<InstrumentDto> res = namedParameterJdbcTemplate.query(sqlQuery, in, new BeanPropertyRowMapper<>(InstrumentDto.class)); return new PageImpl<>(res, pageable, total); } @Override public long createInstrument(InstrumentDto instrumentDto) { String sqlQuery = " INSERT INTO instruments (\n" + "name,\n" + "description,\n" + "ref,\n" + "lot,\n" + "manufacturer,\n" + "purchase_date,\n" + "user_photo,\n" + "notes\n" + ") VALUES (\n" + ":instrumentName,\n" + ":instrumentDescription,\n" + ":instrumentRef,\n" + ":instrumentLot,\n" + ":instrumentManufacturer,\n" + ":instrumentPurchaseDate,\n" + ":userPhoto,\n" + ":instrumentNotes" + ")"; MapSqlParameterSource in = new MapSqlParameterSource(); in.addValue("instrumentName", instrumentDto.getInstrumentName()); in.addValue("instrumentDescription", instrumentDto.getInstrumentDescription()); in.addValue("instrumentRef", instrumentDto.getInstrumentRef()); in.addValue("instrumentLot", instrumentDto.getInstrumentLot()); in.addValue("instrumentLot", instrumentDto.getInstrumentLot()); in.addValue("instrumentManufacturer", instrumentDto.getInstrumentManufacturer()); in.addValue("instrumentPurchaseDate", instrumentDto.getInstrumentPurchaseDate()); in.addValue("userPhoto", instrumentDto.getUserPhoto()); in.addValue("instrumentNotes", instrumentDto.getInstrumentNotes()); KeyHolder keyHolder = new GeneratedKeyHolder(); namedParameterJdbcTemplate.update(sqlQuery, in, keyHolder); return Objects.requireNonNull(keyHolder.getKey()).longValue(); } @Override public boolean updateInstrument(InstrumentDto instrumentDto) { String sqlQuery = "UPDATE instruments SET\n " + "name = :instrumentName,\n " + "description = :instrumentDescription,\n " + "ref = :instrumentRef,\n " + "lot = :instrumentLot,\n " + "manufacturer = :instrumentManufacturer,\n " + "purchase_date = :instrumentPurchaseDate,\n " + "user_photo = :userPhoto,\n " + "notes = :instrumentNotes\n " + "WHERE instrument_id = :instrumentId"; MapSqlParameterSource in = new MapSqlParameterSource(); in.addValue("instrumentId", instrumentDto.getInstrumentId()); in.addValue("instrumentName", instrumentDto.getInstrumentName()); in.addValue("instrumentDescription", instrumentDto.getInstrumentDescription()); in.addValue("instrumentRef", instrumentDto.getInstrumentRef()); in.addValue("instrumentLot", instrumentDto.getInstrumentLot()); in.addValue("instrumentManufacturer", instrumentDto.getInstrumentManufacturer()); in.addValue("instrumentPurchaseDate", instrumentDto.getInstrumentPurchaseDate()); in.addValue("userPhoto", instrumentDto.getUserPhoto()); in.addValue("instrumentNotes", instrumentDto.getInstrumentNotes()); return namedParameterJdbcTemplate.update(sqlQuery, in) > 0; } @Override public InstrumentDto getInstrumentById(long id) { String sqlQuery = "SELECT i.instrument_id as instrumentId,\n" + "i.name as instrumentName,\n" + "i.description as instrumentDescription,\n" + "i.ref as instrumentRef,\n" + "i.lot as instrumentLot,\n" + "i.manufacturer as instrumentManufacturer,\n" + "i.purchase_date as instrumentPurchaseDate,\n" + "i.user_photo as userPhoto,\n" + "i.notes as instrumentNotes \n" + "FROM instruments AS i\n" + "WHERE i.instrument_Id = :instrumentId"; MapSqlParameterSource in = new MapSqlParameterSource("instrumentId", id); return namedParameterJdbcTemplate.queryForObject(sqlQuery, in, (resultSet, i) -> { InstrumentDto instrumentDto = new InstrumentDto(); instrumentDto.setInstrumentId(resultSet.getLong("instrumentId")); instrumentDto.setInstrumentName(resultSet.getNString("instrumentName")); instrumentDto.setInstrumentDescription(resultSet.getNString("instrumentDescription")); instrumentDto.setInstrumentRef(resultSet.getNString("instrumentRef")); instrumentDto.setInstrumentLot(resultSet.getNString("instrumentLot")); instrumentDto.setInstrumentManufacturer(resultSet.getNString("instrumentManufacturer")); instrumentDto.setInstrumentPurchaseDate(resultSet.getDate("instrumentPurchaseDate")); instrumentDto.setUserPhoto(resultSet.getBytes("userPhoto")); instrumentDto.setInstrumentNotes(resultSet.getNString("instrumentNotes")); return instrumentDto; }); } @Override public boolean deleteInstrument(Long id) { MapSqlParameterSource in = new MapSqlParameterSource("id", id); String sqlQuery = "DELETE FROM instruments WHERE instrument_id = :id"; return namedParameterJdbcTemplate.update(sqlQuery, in) > 0; } }
3e14ca7f074fe0566575d209705041cd4600d85e
3,331
java
Java
src/main/java/com/spittr/location/model/Location.java
wususu/secret
a6c6f5d885dcda7f9b6a9474b20d855efbf35c05
[ "Apache-2.0" ]
2
2017-08-19T08:44:13.000Z
2017-08-19T11:23:28.000Z
src/main/java/com/spittr/location/model/Location.java
wususu/secret
a6c6f5d885dcda7f9b6a9474b20d855efbf35c05
[ "Apache-2.0" ]
12
2017-09-03T03:59:11.000Z
2017-09-26T03:18:32.000Z
src/main/java/com/spittr/location/model/Location.java
wususu/secret
a6c6f5d885dcda7f9b6a9474b20d855efbf35c05
[ "Apache-2.0" ]
3
2018-05-29T07:18:55.000Z
2021-11-02T11:18:12.000Z
21.62987
110
0.675773
8,807
package com.spittr.location.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @JsonIgnoreProperties({"tmCreated", "isDelete", "tmDelete"}) public class Location implements Serializable{ /** * */ private static final long serialVersionUID = 7295262773090140574L; @Id @GeneratedValue private Long lid; @Column(length=10, unique=true) private String locale; @Temporal(TemporalType.TIMESTAMP) private Date tmCreated; private Boolean isDelete; @Temporal(TemporalType.TIMESTAMP) private Date tmDelete; public Location(){ } public Location(String locale){ this(locale, new Date(), false, null); } public Location(String locale, Date tmCreated, Boolean isDelete, Date tmDelete) { // TODO Auto-generated constructor stub this.locale = locale; this.tmCreated = tmCreated; this.tmDelete = tmDelete; this.isDelete = isDelete; } public Long getLid() { return lid; } public void setLid(Long lid) { this.lid = lid; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } public Date getTmCreated() { return tmCreated; } public void setTmCreated(Date tmCreated) { this.tmCreated = tmCreated; } public Boolean getIsDelete() { return isDelete; } public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } public Date getTmDelete() { return tmDelete; } public void setTmDelete(Date tmDelete) { this.tmDelete = tmDelete; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((isDelete == null) ? 0 : isDelete.hashCode()); result = prime * result + ((lid == null) ? 0 : lid.hashCode()); result = prime * result + ((locale == null) ? 0 : locale.hashCode()); result = prime * result + ((tmCreated == null) ? 0 : tmCreated.hashCode()); result = prime * result + ((tmDelete == null) ? 0 : tmDelete.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Location other = (Location) obj; if (isDelete == null) { if (other.isDelete != null) return false; } else if (!isDelete.equals(other.isDelete)) return false; if (lid == null) { if (other.lid != null) return false; } else if (!lid.equals(other.lid)) return false; if (locale == null) { if (other.locale != null) return false; } else if (!locale.equals(other.locale)) return false; if (tmCreated == null) { if (other.tmCreated != null) return false; } else if (!tmCreated.equals(other.tmCreated)) return false; if (tmDelete == null) { if (other.tmDelete != null) return false; } else if (!tmDelete.equals(other.tmDelete)) return false; return true; } @Override public String toString() { return "Location [lid=" + lid + ", locale=" + locale + ", tmCreated=" + tmCreated + ", isDelete=" + isDelete + ", tmDelete=" + tmDelete + "]"; } }
3e14cad09ed6c545a25d78d4be3bbe33e2f2f14f
5,266
java
Java
src/main/java/work/eanson/controller/AdminController.java
eanson023/minzuchess-spring-boot
7bb864746f68f3c757ffc1a5f4cc9dbea4f5beda
[ "Apache-2.0" ]
3
2020-09-25T02:10:13.000Z
2021-05-06T15:23:21.000Z
src/main/java/work/eanson/controller/AdminController.java
eanson023/minzuchess-spring-boot
7bb864746f68f3c757ffc1a5f4cc9dbea4f5beda
[ "Apache-2.0" ]
null
null
null
src/main/java/work/eanson/controller/AdminController.java
eanson023/minzuchess-spring-boot
7bb864746f68f3c757ffc1a5f4cc9dbea4f5beda
[ "Apache-2.0" ]
1
2021-04-27T07:08:23.000Z
2021-04-27T07:08:23.000Z
33.329114
122
0.670908
8,808
package work.eanson.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import work.eanson.pojo.UserInfo; import work.eanson.pojo.UserLogin; import work.eanson.pojo.back.page.DataTablesBack; import work.eanson.pojo.back.page.DataTablesIn; import work.eanson.util.Context; /** * @author eanson * @create 2020-03-28 15:00 */ @Controller @RequestMapping("admin") @Api(tags = "管理员管理") public class AdminController extends AbstractController { private static final Logger logger = LogManager.getLogger(AdminController.class); @RequiresRoles("admin") @RequestMapping(value = {"", "index"}) @ApiOperation("打开管理员页面") public ModelAndView index(ModelAndView mv) throws Exception { mv.addObject("original", "/admin/index"); mv.setViewName("admin/index"); Context context = new Context("get_admin_index"); csgo.service(context); mv.addObject("code", context.get("code")); mv.addObject("categories", context.get("categories")); return mv; } /** * original用于导航栏active使用 * * @param mv * @return */ @RequiresRoles("admin") @RequestMapping("user/user_log") @ApiOperation("打开用户日志页面") public ModelAndView userLog(ModelAndView mv) { mv.setViewName("admin/user_log"); mv.addObject("original", "/admin/user/user_log"); return mv; } @RequiresRoles("admin") @RequestMapping("user/user_info") @ApiOperation("打开用户信息页面") public ModelAndView userInfo(ModelAndView mv) { mv.setViewName("admin/user_info"); mv.addObject("original", "/admin/user/user_info"); return mv; } @RequiresRoles("admin") @RequestMapping("cheep/cheep_info") @ApiOperation("打开棋谱信息页面") public ModelAndView trickInfo(ModelAndView mv) { mv.setViewName("admin/cheep_info"); mv.addObject("original", "/admin/cheep/cheep_info"); return mv; } @RequiresRoles("admin") @RequestMapping("chess/chess_info") @ApiOperation("打开棋盘信息页面") public ModelAndView chessInfo(ModelAndView mv) { mv.setViewName("admin/chess_info"); mv.addObject("original", "/admin/chess/chess_info"); return mv; } @RequiresRoles("admin") @PostMapping("/user/user_add") @ApiOperation("打开添加用户页面") public ModelAndView addUser(ModelAndView mv, UserInfo userInfo, UserLogin userLogin) throws Exception { Context context = new Context("admin_add_user"); context.put("user_info", userInfo); context.put("user_login", userLogin); csgo.service(context); mv.addObject("msg", context.get("msg")); mv.setViewName("forward:/admin"); return mv; } @RequiresRoles("admin") @PostMapping("/chess/cb_add") @ApiOperation("打开棋盘添加页面") public ModelAndView addCb(ModelAndView mv, String code, @RequestParam("category") Byte categoryKey) throws Exception { Context context = new Context("admin_add_cb"); context.put("code", code); context.put("category_key", categoryKey); csgo.service(context); mv.addObject("msg", context.get("msg")); mv.setViewName("forward:/admin"); return mv; } @RequiresRoles("admin") @PostMapping("/user/user_log.json") @ResponseBody @ApiOperation("根据筛选条件获取用户日志") public DataTablesBack getUserLog(@RequestBody DataTablesIn dti) throws Exception { Context context = new Context("get_user_log"); context.put("data_tables_in", dti); csgo.service(context); return (DataTablesBack) context.getResult().getData(); } @RequiresRoles("admin") @PostMapping("/user/user_info.json") @ResponseBody @ApiOperation("根据筛选条件获取用户信息") public DataTablesBack getUserInfo(@RequestBody DataTablesIn dti) { Context context = new Context("get_user_info"); context.put("data_tables_in", dti); try { csgo.service(context); } catch (Exception e) { e.printStackTrace(); } return (DataTablesBack) context.getResult().getData(); } @RequiresRoles("admin") @PostMapping("/cheep/cheep_info.json") @ResponseBody @ApiOperation("根据筛选条件获取棋谱信息") public DataTablesBack getCheepInfo(@RequestBody DataTablesIn dti) throws Exception { Context context = new Context("get_cheep_info"); context.put("data_tables_in", dti); csgo.service(context); return (DataTablesBack) context.getResult().getData(); } @RequiresRoles("admin") @PostMapping("/chess/chess_info.json") @ResponseBody @ApiOperation("根据筛选条件获取棋盘信息") public DataTablesBack getChessInfo(@RequestBody DataTablesIn dti) throws Exception { Context context = new Context("get_chess_info"); context.put("data_tables_in", dti); csgo.service(context); return (DataTablesBack) context.getResult().getData(); } }
3e14cbe67b940e68272bf97b405c4d2b620901d8
1,479
java
Java
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/newway/action/v4/connector/PlatformSecurityGroupsAction.java
nbathra/cloudbreak
6e784b9ebd4804de1dcd2d0efd14de65def2abdd
[ "Apache-2.0" ]
null
null
null
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/newway/action/v4/connector/PlatformSecurityGroupsAction.java
nbathra/cloudbreak
6e784b9ebd4804de1dcd2d0efd14de65def2abdd
[ "Apache-2.0" ]
null
null
null
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/newway/action/v4/connector/PlatformSecurityGroupsAction.java
nbathra/cloudbreak
6e784b9ebd4804de1dcd2d0efd14de65def2abdd
[ "Apache-2.0" ]
null
null
null
44.818182
101
0.675456
8,809
package com.sequenceiq.it.cloudbreak.newway.action.v4.connector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sequenceiq.it.cloudbreak.newway.CloudbreakClient; import com.sequenceiq.it.cloudbreak.newway.action.Action; import com.sequenceiq.it.cloudbreak.newway.context.TestContext; import com.sequenceiq.it.cloudbreak.newway.dto.connector.PlatformSecurityGroupsTestDto; public class PlatformSecurityGroupsAction implements Action<PlatformSecurityGroupsTestDto> { private static final Logger LOGGER = LoggerFactory.getLogger(PlatformSecurityGroupsAction.class); @Override public PlatformSecurityGroupsTestDto action(TestContext testContext, PlatformSecurityGroupsTestDto testDto, CloudbreakClient cloudbreakClient) throws Exception { String logInitMessage = "Obtaining security groups by credential"; LOGGER.info("{}", logInitMessage); testDto.setResponse( cloudbreakClient.getCloudbreakClient().connectorV4Endpoint().getSecurityGroups( cloudbreakClient.getWorkspaceId(), testDto.getCredentialName(), testDto.getRegion(), testDto.getPlatformVariant(), testDto.getAvailabilityZone()) ); LOGGER.info("{} was successful", logInitMessage); return testDto; } }
3e14cbee6a7b7aff4ea0c949e0948f46c3d77fc2
1,243
java
Java
extensions/server/kyuubi-server-plugin/src/main/java/org/apache/kyuubi/plugin/SessionConfAdvisor.java
TyrealBM/incubator-kyuubi
4ec707b7427e90c9a50e70b78d7b5ccf24884d59
[ "Apache-2.0", "MIT" ]
1
2018-12-07T01:52:35.000Z
2018-12-07T01:52:35.000Z
extensions/server/kyuubi-server-plugin/src/main/java/org/apache/kyuubi/plugin/SessionConfAdvisor.java
TyrealBM/incubator-kyuubi
4ec707b7427e90c9a50e70b78d7b5ccf24884d59
[ "Apache-2.0", "MIT" ]
19
2019-02-20T14:47:49.000Z
2019-04-15T02:44:17.000Z
extensions/server/kyuubi-server-plugin/src/main/java/org/apache/kyuubi/plugin/SessionConfAdvisor.java
TyrealBM/incubator-kyuubi
4ec707b7427e90c9a50e70b78d7b5ccf24884d59
[ "Apache-2.0", "MIT" ]
null
null
null
40.096774
92
0.761062
8,810
/* * 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.kyuubi.plugin; import java.util.Collections; import java.util.Map; /** Provide the session configuration according to the user and session configuration. */ public interface SessionConfAdvisor { /** The returned conf will overwrite the session conf */ @SuppressWarnings("unchecked") default Map<String, String> getConfOverlay(String user, Map<String, String> sessionConf) { return Collections.EMPTY_MAP; } }
3e14cbf190d0c10b104c125f029c021f69ed4d7e
1,662
java
Java
src/test/java/io/cdap/plugin/gcp/bigquery/sqlengine/BigQuerySQLEngineConfigTest.java
asishgoudo/google-cloud
20296cb46cf2e71b134303867f4e0bb6e62fd16b
[ "Apache-2.0" ]
1
2021-10-21T17:21:07.000Z
2021-10-21T17:21:07.000Z
src/test/java/io/cdap/plugin/gcp/bigquery/sqlengine/BigQuerySQLEngineConfigTest.java
ksahilCF/google-cloud
d26af871f90ced5018b83da135c294c435e8c279
[ "Apache-2.0" ]
9
2022-03-03T04:31:49.000Z
2022-03-30T14:07:38.000Z
src/test/java/io/cdap/plugin/gcp/bigquery/sqlengine/BigQuerySQLEngineConfigTest.java
ksahilCF/google-cloud
d26af871f90ced5018b83da135c294c435e8c279
[ "Apache-2.0" ]
5
2021-12-06T06:21:46.000Z
2021-12-15T06:23:21.000Z
31.961538
105
0.709386
8,811
/* * Copyright © 2020 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.gcp.bigquery.sqlengine; import org.junit.Assert; import org.junit.Test; import java.util.HashSet; import java.util.Set; /** * Test for {@link BigQuerySQLEngineConfig} class */ public class BigQuerySQLEngineConfigTest { @Test public void testSplitStages() { Set<String> stages = new HashSet<>(); Assert.assertEquals(stages, BigQuerySQLEngineConfig.splitStages(null)); Assert.assertEquals(stages, BigQuerySQLEngineConfig.splitStages("")); stages.add(" "); Assert.assertEquals(stages, BigQuerySQLEngineConfig.splitStages(" ")); stages.add("a"); Assert.assertEquals(stages, BigQuerySQLEngineConfig.splitStages(" \u0001a")); stages.add("this is some stage"); Assert.assertEquals(stages, BigQuerySQLEngineConfig.splitStages(" \u0001a\u0001this is some stage")); stages.add(" this is another "); Assert.assertEquals(stages, BigQuerySQLEngineConfig.splitStages( " \u0001a\u0001this is some stage\u0001 this is another ")); } }
3e14ccc7cc213b7b372c3baa315c33b92a831baa
271
java
Java
shopping-service/shopping-api/src/main/java/com/mall/shopping/dto/ProductDetailResponse.java
Liangsh7/micro_mall
4c0286fe31eea12589d424d3a6938fdfeb45b842
[ "Apache-2.0" ]
null
null
null
shopping-service/shopping-api/src/main/java/com/mall/shopping/dto/ProductDetailResponse.java
Liangsh7/micro_mall
4c0286fe31eea12589d424d3a6938fdfeb45b842
[ "Apache-2.0" ]
null
null
null
shopping-service/shopping-api/src/main/java/com/mall/shopping/dto/ProductDetailResponse.java
Liangsh7/micro_mall
4c0286fe31eea12589d424d3a6938fdfeb45b842
[ "Apache-2.0" ]
null
null
null
18.066667
61
0.767528
8,812
package com.mall.shopping.dto; import com.mall.commons.result.AbstractResponse; import lombok.Data; /** * ciggar * create-date: 2019/7/24-16:27 */ @Data public class ProductDetailResponse extends AbstractResponse { private ProductDetailDto productDetailDto; }
3e14cd43d286520983ab0eb3db376f7db6bd1b77
276
java
Java
ultimate-breakfast-web/src/main/java/fr/ultimate/breakfast/web/jsConsole/Command.java
exanpe/ultimate-breakfast
947c0d339a2861204d7f77e750e708b36e83eebe
[ "Apache-2.0" ]
1
2015-01-16T09:57:43.000Z
2015-01-16T09:57:43.000Z
ultimate-breakfast-web/src/main/java/fr/ultimate/breakfast/web/jsConsole/Command.java
exanpe/ultimate-breakfast
947c0d339a2861204d7f77e750e708b36e83eebe
[ "Apache-2.0" ]
null
null
null
ultimate-breakfast-web/src/main/java/fr/ultimate/breakfast/web/jsConsole/Command.java
exanpe/ultimate-breakfast
947c0d339a2861204d7f77e750e708b36e83eebe
[ "Apache-2.0" ]
1
2016-08-04T08:33:07.000Z
2016-08-04T08:33:07.000Z
16.235294
62
0.753623
8,813
/** * */ package fr.ultimate.breakfast.web.jsConsole; import org.apache.tapestry5.json.JSONArray; import fr.ultimate.breakfast.web.util.JsConsoleResponseHolder; /** * @author lguerin */ public interface Command { JsConsoleResponseHolder execute(JSONArray args); }
3e14cd533262bd06a118165bfece6a17a7572301
5,834
java
Java
resource-manager/implementation/src/main/yang-gen-config/eu/virtuwind/resourcemanager/impl/AbstractResourcemanagerModuleFactory.java
ali2251/Virtuwind
bea3e00be2bc1d07b8fbb05a5354f1748207c8aa
[ "MIT" ]
null
null
null
resource-manager/implementation/src/main/yang-gen-config/eu/virtuwind/resourcemanager/impl/AbstractResourcemanagerModuleFactory.java
ali2251/Virtuwind
bea3e00be2bc1d07b8fbb05a5354f1748207c8aa
[ "MIT" ]
null
null
null
resource-manager/implementation/src/main/yang-gen-config/eu/virtuwind/resourcemanager/impl/AbstractResourcemanagerModuleFactory.java
ali2251/Virtuwind
bea3e00be2bc1d07b8fbb05a5354f1748207c8aa
[ "MIT" ]
null
null
null
58.929293
337
0.785396
8,814
/* * Generated file * * Generated from: yang module name: resourcemanager-impl yang module local name: resourcemanager-impl * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator * Generated at: Tue Apr 17 16:40:14 BST 2018 * * Do not modify this file unless it is present under src/main directory */ package eu.virtuwind.resourcemanager.impl; import org.opendaylight.controller.config.spi.Module; import org.opendaylight.controller.config.api.ModuleIdentifier; @org.opendaylight.yangtools.yang.binding.annotations.ModuleQName(namespace = "urn:eu:virtuwind:resourcemanager:impl", name = "resourcemanager-impl", revision = "2016-10-17") public abstract class AbstractResourcemanagerModuleFactory implements org.opendaylight.controller.config.spi.ModuleFactory { public static final java.lang.String NAME = "resourcemanager-impl"; private static final java.util.Set<Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface>> serviceIfcs; @Override public final String getImplementationName() { return NAME; } static { serviceIfcs = java.util.Collections.emptySet(); } @Override public final boolean isModuleImplementingServiceInterface(Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface> serviceInterface) { for (Class<?> ifc: serviceIfcs) { if (serviceInterface.isAssignableFrom(ifc)){ return true; } } return false; } @Override public java.util.Set<Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface>> getImplementedServiceIntefaces() { return serviceIfcs; } @Override public org.opendaylight.controller.config.spi.Module createModule(String instanceName, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.osgi.framework.BundleContext bundleContext) { return instantiateModule(instanceName, dependencyResolver, bundleContext); } @Override public org.opendaylight.controller.config.spi.Module createModule(String instanceName, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.api.DynamicMBeanWithInstance old, org.osgi.framework.BundleContext bundleContext) throws Exception { eu.virtuwind.resourcemanager.impl.ResourcemanagerModule oldModule; try { oldModule = (eu.virtuwind.resourcemanager.impl.ResourcemanagerModule) old.getModule(); } catch(Exception e) { return handleChangedClass(dependencyResolver, old, bundleContext); } eu.virtuwind.resourcemanager.impl.ResourcemanagerModule module = instantiateModule(instanceName, dependencyResolver, oldModule, old.getInstance(), bundleContext); module.setRpcRegistry(oldModule.getRpcRegistry()); module.setDataBroker(oldModule.getDataBroker()); module.setNotificationService(oldModule.getNotificationService()); return module; } public eu.virtuwind.resourcemanager.impl.ResourcemanagerModule instantiateModule(String instanceName, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, eu.virtuwind.resourcemanager.impl.ResourcemanagerModule oldModule, java.lang.AutoCloseable oldInstance, org.osgi.framework.BundleContext bundleContext) { return new eu.virtuwind.resourcemanager.impl.ResourcemanagerModule(new org.opendaylight.controller.config.api.ModuleIdentifier(NAME, instanceName), dependencyResolver, oldModule, oldInstance); } public eu.virtuwind.resourcemanager.impl.ResourcemanagerModule instantiateModule(String instanceName, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.osgi.framework.BundleContext bundleContext) { return new eu.virtuwind.resourcemanager.impl.ResourcemanagerModule(new org.opendaylight.controller.config.api.ModuleIdentifier(NAME, instanceName), dependencyResolver); } public eu.virtuwind.resourcemanager.impl.ResourcemanagerModule handleChangedClass(org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.api.DynamicMBeanWithInstance old, org.osgi.framework.BundleContext bundleContext) throws Exception { String instanceName = old.getModule().getIdentifier().getInstanceName(); eu.virtuwind.resourcemanager.impl.ResourcemanagerModule newModule = new eu.virtuwind.resourcemanager.impl.ResourcemanagerModule(new ModuleIdentifier(NAME, instanceName), dependencyResolver); Module oldModule = old.getModule(); Class<? extends Module> oldModuleClass = oldModule.getClass(); newModule.setRpcRegistry( (javax.management.ObjectName) oldModuleClass.getMethod("getRpcRegistry").invoke(oldModule)); newModule.setDataBroker( (javax.management.ObjectName) oldModuleClass.getMethod("getDataBroker").invoke(oldModule)); newModule.setNotificationService( (javax.management.ObjectName) oldModuleClass.getMethod("getNotificationService").invoke(oldModule)); return newModule; } @Deprecated public eu.virtuwind.resourcemanager.impl.ResourcemanagerModule handleChangedClass(org.opendaylight.controller.config.api.DynamicMBeanWithInstance old) throws Exception { throw new UnsupportedOperationException("Class reloading is not supported"); } @Override public java.util.Set<eu.virtuwind.resourcemanager.impl.ResourcemanagerModule> getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory dependencyResolverFactory, org.osgi.framework.BundleContext bundleContext) { return new java.util.HashSet<eu.virtuwind.resourcemanager.impl.ResourcemanagerModule>(); } }
3e14cdc9ba399fbe068cb77a2c8a1f0fa80b7e2b
1,430
java
Java
odin-core/src/main/java/io/jcoder/odin/web/ServletCallerHttpServletRequest.java
jcoderltd/odin
65571bf439dc6cc825ec8d7ac1097a4794b68e65
[ "Apache-2.0" ]
null
null
null
odin-core/src/main/java/io/jcoder/odin/web/ServletCallerHttpServletRequest.java
jcoderltd/odin
65571bf439dc6cc825ec8d7ac1097a4794b68e65
[ "Apache-2.0" ]
null
null
null
odin-core/src/main/java/io/jcoder/odin/web/ServletCallerHttpServletRequest.java
jcoderltd/odin
65571bf439dc6cc825ec8d7ac1097a4794b68e65
[ "Apache-2.0" ]
null
null
null
27.5
109
0.716084
8,815
/* * Copyright 2019 JCoder Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jcoder.odin.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * * @author Camilo Gonzalez */ public class ServletCallerHttpServletRequest extends HttpServletRequestWrapper { private final String servletPath; private final String pathInfo; public ServletCallerHttpServletRequest(HttpServletRequest request, String servletPath, String pathInfo) { super(request); this.servletPath = servletPath; this.pathInfo = pathInfo; } @Override public HttpServletRequest getRequest() { return (HttpServletRequest) super.getRequest(); } @Override public String getServletPath() { return servletPath; } @Override public String getPathInfo() { return pathInfo; } }
3e14ce21085e1238e5c3a228d9719e48416ff266
5,776
java
Java
app/src/main/java/com/codepath/apps/twitterclient/ComposeTweetActivity.java
johnpaulfernandez/Tweetly
03360f88db9f92332efc45d147f3e56ef2999793
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/twitterclient/ComposeTweetActivity.java
johnpaulfernandez/Tweetly
03360f88db9f92332efc45d147f3e56ef2999793
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/twitterclient/ComposeTweetActivity.java
johnpaulfernandez/Tweetly
03360f88db9f92332efc45d147f3e56ef2999793
[ "MIT" ]
1
2018-10-08T18:14:05.000Z
2018-10-08T18:14:05.000Z
34.586826
174
0.624654
8,816
package com.codepath.apps.twitterclient; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Movie; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.codepath.apps.twitterclient.models.User; import com.loopj.android.http.JsonHttpResponseHandler; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; import static com.codepath.apps.twitterclient.R.string.tweet; /** * Created by John on 4/30/2017. */ public class ComposeTweetActivity extends AppCompatActivity{ private TwitterClient client; private static Context context; TextView tvName; TextView tvScreenName; ImageView ivProfileImage; EditText etNewTweet; TextView tvCounter; Button btnTweet; User user; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_compose_tweet); tvName = (TextView) findViewById(R.id.tvName); tvScreenName = (TextView) findViewById(R.id.tvScreenName); ivProfileImage = (ImageView) findViewById(R.id.ivProfileImage); etNewTweet = (EditText) findViewById(R.id.etNewTweet); tvCounter = (TextView) findViewById(R.id.tvCounter); btnTweet = (Button) findViewById(R.id.btnTweet); client = TwitterApplication.getRestClient(); // Singleton client instance user = new User(); getCurrentUser(); tweetListener(); } public static void setContext(Context mContext) { ComposeTweetActivity.context = mContext; } public static Context getContext() { return context; } // Send an API request to get the current user's account details private void getCurrentUser() { client.getVerifyCredentials(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject) { Log.d("DEBUG", "onSuccess: " + jsonObject.toString()); try { // Deserialize JSON user.setName(jsonObject.getString("name")); user.setScreenName(jsonObject.getString("screen_name")); user.setProfileImageUrl(jsonObject.getString("profile_image_url")); // Set values into views tvName.setText(user.getName()); tvScreenName.setText(user.getScreenName()); ivProfileImage.setImageResource(android.R.color.transparent); // Clear out the old image for a recycled view and put a transparent placeholder // Or, Picasso.with(this).load(user.getProfileImageUrl()) // Use (this) because it is an activity Picasso.with(getContext()) .load(user.getProfileImageUrl()) .into(ivProfileImage); // Send an API request using Picasso library, load the imageURL, retrieve the data, and insert it into the imageView } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("DEBUG", "onFailure: " + errorResponse.toString()); } }); } public void onTweet(View view) { String tweet = etNewTweet.getText().toString(); client.postUpdate(new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { Log.d("DEBUG", "onSuccess: " + response.toString()); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { Log.d("DEBUG", "onFailure: " + errorResponse.toString()); } }, tweet); // Prepare data intent Intent data = new Intent(); // Pass relevant data back as a result data.putExtra("tweet", tweet); data.putExtra("user", user); // Activity finished ok, return the data setResult(RESULT_OK, data); // set result code and bundle data for response finish(); // closes the activity, pass data to parent } private void tweetListener() { etNewTweet.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Show remaining characters tvCounter.setText(String.valueOf(140 - s.length())); } @Override public void afterTextChanged(Editable s) { if (s.length() > 140) { btnTweet.setEnabled(false); tvCounter.setTextColor(Color.RED); } else { btnTweet.setEnabled(true); tvCounter.setTextColor(Color.BLACK); } } }); } }
3e14ce2b13e4ea22f8821d9c9d071d2790f7e5cd
3,365
java
Java
dubbo-switch/src/main/java/com/github/xburning/dubboswitch/view/consumer/ZookeeperConsumerAddUI.java
learningtcc/dubbox
19cec2b821cd5eddd2f38889227241495ed2ab80
[ "Apache-2.0" ]
15
2017-04-09T05:10:26.000Z
2020-08-10T15:16:13.000Z
dubbo-switch/src/main/java/com/github/xburning/dubboswitch/view/consumer/ZookeeperConsumerAddUI.java
learningtcc/dubbox
19cec2b821cd5eddd2f38889227241495ed2ab80
[ "Apache-2.0" ]
6
2020-11-16T20:30:21.000Z
2022-02-01T00:57:13.000Z
dubbo-switch/src/main/java/com/github/xburning/dubboswitch/view/consumer/ZookeeperConsumerAddUI.java
learningtcc/dubbox
19cec2b821cd5eddd2f38889227241495ed2ab80
[ "Apache-2.0" ]
20
2017-04-05T05:14:19.000Z
2020-03-11T12:41:08.000Z
30.87156
92
0.643388
8,817
package com.github.xburning.dubboswitch.view.consumer; import com.github.xburning.dubboswitch.entity.ZookeeperApp; import com.github.xburning.dubboswitch.entity.ZookeeperConsumer; import com.github.xburning.dubboswitch.repository.ZookeeperAppRepository; import com.github.xburning.dubboswitch.repository.ZookeeperConsumerRepository; import com.vaadin.server.FontAwesome; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.ui.*; import com.vaadin.ui.themes.ValoTheme; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; /** * 添加消费者Zookeeper */ @SpringUI public class ZookeeperConsumerAddUI extends Window{ private final ZookeeperConsumerRepository zookeeperConsumerRepository; //是否添加成功 public boolean isAddSuccess = false; private TextField nameField; private TextField ipField; private TextField portField; @Autowired public ZookeeperConsumerAddUI(ZookeeperConsumerRepository zookeeperConsumerRepository) { super("添加消费者"); this.zookeeperConsumerRepository = zookeeperConsumerRepository; center(); setModal(true); setClosable(true); setDraggable(false); setResizable(false); setWidth(330,Unit.PIXELS); setHeight(260,Unit.PIXELS); createSubmitForm(); } /** * 创建提交表单 */ private void createSubmitForm() { FormLayout formLayout = new FormLayout(); nameField = new TextField(); nameField.setCaption("消费者名称"); ipField = new TextField(); ipField.setCaption("IP"); portField = new TextField(); portField.setCaption("端口"); formLayout.addComponent(nameField); formLayout.addComponent(ipField); formLayout.addComponent(portField); formLayout.addComponent(createSaveButton()); formLayout.setMargin(true); setContent(formLayout); } /** * 创建保存按钮 * @return */ private Button createSaveButton() { Button saveButton = new Button("保存", FontAwesome.CHECK); saveButton.addStyleName(ValoTheme.BUTTON_PRIMARY); saveButton.addClickListener((Button.ClickListener) clickEvent -> { String name = nameField.getValue(); if (StringUtils.isEmpty(name)) { Notification.show("消费者名称不能为空!",Notification.Type.ERROR_MESSAGE); return; } String ip = ipField.getValue(); if (StringUtils.isEmpty(ip)) { Notification.show("IP不能为空!",Notification.Type.ERROR_MESSAGE); return; } String port = portField.getValue(); if (StringUtils.isEmpty(port)) { Notification.show("端口不能为空!",Notification.Type.ERROR_MESSAGE); return; } //insert data ZookeeperConsumer consumer = new ZookeeperConsumer(); consumer.setName(name); consumer.setIp(ip); consumer.setPort(Integer.parseInt(port)); zookeeperConsumerRepository.save(consumer); isAddSuccess = true; close(); }); return saveButton; } /** * 重置表单 */ public void clearForm() { nameField.clear(); ipField.clear(); portField.clear(); } }
3e14cfc01c2a63f3f6911629d0bd74677872dfad
1,790
java
Java
src/test/java/com/somedomain/algos/sorting/DutchNationalFlagTest.java
agrawalnishant/algoholism
ad173127b29315759b2979b85b09c04dabfc573c
[ "Apache-2.0" ]
null
null
null
src/test/java/com/somedomain/algos/sorting/DutchNationalFlagTest.java
agrawalnishant/algoholism
ad173127b29315759b2979b85b09c04dabfc573c
[ "Apache-2.0" ]
null
null
null
src/test/java/com/somedomain/algos/sorting/DutchNationalFlagTest.java
agrawalnishant/algoholism
ad173127b29315759b2979b85b09c04dabfc573c
[ "Apache-2.0" ]
null
null
null
47.105263
371
0.531285
8,818
package com.somedomain.algos.sorting; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertArrayEquals; class DutchNationalFlagTest { @ParameterizedTest(name = "Dutch National Flag for {0} should be {1}.") @CsvSource({ "2 2 1 2 1 1 1 0 0 2 1 0 2 1 2 2 1 1 1 1 1 0 2 0 2 0 2 2 1 0 2 1 0 2 1 2 0 0 0 0 2 1 1 2 0 1 2 2 0 0 2 2 0 1 0 1 0 0 1 1 1 0 0 2 2 2 1 0 0 2 1 0 1 0 2 2 1 2 1 1 2 1 1 0 0 2 1 0 0, 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2", "2 1 2, 1 2 2", "0 0 1 1 0 1 2 0 1 0 1 2 2 0 1 , 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2", "0 1 2, 0 1 2", "0 1 2 1 2, 0 1 1 2 2", "0 1 1 2 1 2, 0 1 1 1 2 2", "0 2 2 2 0 2 1 1, 0 0 1 1 2 2 2 2", "2 0 2 1 1 0 , 0 0 1 1 2 2", "0 1 0 , 0 0 1", "0 0 0 , 0 0 0", "0 2 0 , 0 0 2", "1 1 1 , 1 1 1", "2 2 2, 2 2 2", "2 2 2, 2 2 2", "0 0 2 1 1 2 1 1 1 0 2 1 0 1 2 1 0 1 1 1 2 2 1 2 0 0 1 0 2 1 2 2 2 0, 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2" }) void sortForDutchNationalFlag(String input, String expected) { int[] result = DutchNationalFlag.sort(Arrays.stream(input.split(" ")).mapToInt(Integer::parseInt).toArray()); int[] expectedArr = Arrays.stream(expected.split(" ")).mapToInt(Integer::parseInt).toArray(); assertArrayEquals(expectedArr, result, "Expected flag to look like : " + expected + " but was: " + Arrays.toString(result)); } }
3e14cfc485d9f8de06602fd1125f470cd44b9adb
235
java
Java
antproject/ligang16/ch7/InstanceofTest2.java
chenwei182729/Three-questions-a-day
4dd81666e46b849a648372c963d9c5f8d3957b66
[ "Apache-2.0" ]
null
null
null
antproject/ligang16/ch7/InstanceofTest2.java
chenwei182729/Three-questions-a-day
4dd81666e46b849a648372c963d9c5f8d3957b66
[ "Apache-2.0" ]
null
null
null
antproject/ligang16/ch7/InstanceofTest2.java
chenwei182729/Three-questions-a-day
4dd81666e46b849a648372c963d9c5f8d3957b66
[ "Apache-2.0" ]
null
null
null
33.571429
82
0.604255
8,819
public class InstanceofTest2{ public static void main(String[] args){ // Object str = "hello"; // Math math = (Math)str; // System.out.println("hello instanceof String"+(math instanceof String)); } }
3e14d08347e4c1fbd7f1c06b4ff7997634e121be
8,249
java
Java
src/com/gitblit/wicket/pages/EditUserPage.java
vs/gitblit
4e89ed699a8073b91af3e2c066d963ce4651cf4a
[ "Apache-2.0" ]
null
null
null
src/com/gitblit/wicket/pages/EditUserPage.java
vs/gitblit
4e89ed699a8073b91af3e2c066d963ce4651cf4a
[ "Apache-2.0" ]
null
null
null
src/com/gitblit/wicket/pages/EditUserPage.java
vs/gitblit
4e89ed699a8073b91af3e2c066d963ce4651cf4a
[ "Apache-2.0" ]
null
null
null
35.252137
121
0.696569
8,820
/* * Copyright 2011 gitblit.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.gitblit.wicket.pages; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.wicket.PageParameters; import org.apache.wicket.behavior.SimpleAttributeModifier; import org.apache.wicket.extensions.markup.html.form.palette.Palette; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.PasswordTextField; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.util.CollectionModel; import org.apache.wicket.model.util.ListModel; import com.gitblit.Constants.AccessRestrictionType; import com.gitblit.GitBlit; import com.gitblit.GitBlitException; import com.gitblit.Keys; import com.gitblit.models.RepositoryModel; import com.gitblit.models.TeamModel; import com.gitblit.models.UserModel; import com.gitblit.utils.StringUtils; import com.gitblit.wicket.RequiresAdminRole; import com.gitblit.wicket.StringChoiceRenderer; import com.gitblit.wicket.WicketUtils; @RequiresAdminRole public class EditUserPage extends RootSubPage { private final boolean isCreate; public EditUserPage() { // create constructor super(); isCreate = true; setupPage(new UserModel("")); } public EditUserPage(PageParameters params) { // edit constructor super(params); isCreate = false; String name = WicketUtils.getUsername(params); UserModel model = GitBlit.self().getUserModel(name); setupPage(model); } protected void setupPage(final UserModel userModel) { if (isCreate) { super.setupPage(getString("gb.newUser"), ""); } else { super.setupPage(getString("gb.edit"), userModel.username); } final Model<String> confirmPassword = new Model<String>( StringUtils.isEmpty(userModel.password) ? "" : userModel.password); CompoundPropertyModel<UserModel> model = new CompoundPropertyModel<UserModel>(userModel); List<String> repos = new ArrayList<String>(); for (String repo : GitBlit.self().getRepositoryList()) { RepositoryModel repositoryModel = GitBlit.self().getRepositoryModel(repo); if (repositoryModel.accessRestriction.exceeds(AccessRestrictionType.NONE)) { repos.add(repo); } } List<String> userTeams = new ArrayList<String>(); for (TeamModel team : userModel.teams) { userTeams.add(team.name); } Collections.sort(userTeams); final String oldName = userModel.username; final Palette<String> repositories = new Palette<String>("repositories", new ListModel<String>(new ArrayList<String>(userModel.repositories)), new CollectionModel<String>(repos), new StringChoiceRenderer(), 10, false); final Palette<String> teams = new Palette<String>("teams", new ListModel<String>( new ArrayList<String>(userTeams)), new CollectionModel<String>(GitBlit.self() .getAllTeamnames()), new StringChoiceRenderer(), 10, false); Form<UserModel> form = new Form<UserModel>("editForm", model) { private static final long serialVersionUID = 1L; /* * (non-Javadoc) * * @see org.apache.wicket.markup.html.form.Form#onSubmit() */ @Override protected void onSubmit() { if (StringUtils.isEmpty(userModel.username)) { error("Please enter a username!"); return; } // force username to lower-case userModel.username = userModel.username.toLowerCase(); String username = userModel.username; if (isCreate) { UserModel model = GitBlit.self().getUserModel(username); if (model != null) { error(MessageFormat.format("Username ''{0}'' is unavailable.", username)); return; } } boolean rename = !StringUtils.isEmpty(oldName) && !oldName.equalsIgnoreCase(username); if (!userModel.password.equals(confirmPassword.getObject())) { error("Passwords do not match!"); return; } String password = userModel.password; if (!password.toUpperCase().startsWith(StringUtils.MD5_TYPE) && !password.toUpperCase().startsWith(StringUtils.COMBINED_MD5_TYPE)) { // This is a plain text password. // Check length. int minLength = GitBlit.getInteger(Keys.realm.minPasswordLength, 5); if (minLength < 4) { minLength = 4; } if (password.trim().length() < minLength) { error(MessageFormat.format( "Password is too short. Minimum length is {0} characters.", minLength)); return; } // Optionally store the password MD5 digest. String type = GitBlit.getString(Keys.realm.passwordStorage, "md5"); if (type.equalsIgnoreCase("md5")) { // store MD5 digest of password userModel.password = StringUtils.MD5_TYPE + StringUtils.getMD5(userModel.password); } else if (type.equalsIgnoreCase("combined-md5")) { // store MD5 digest of username+password userModel.password = StringUtils.COMBINED_MD5_TYPE + StringUtils.getMD5(username + userModel.password); } } else if (rename && password.toUpperCase().startsWith(StringUtils.COMBINED_MD5_TYPE)) { error("Gitblit is configured for combined-md5 password hashing. You must enter a new password on account rename."); return; } Iterator<String> selectedRepositories = repositories.getSelectedChoices(); List<String> repos = new ArrayList<String>(); while (selectedRepositories.hasNext()) { repos.add(selectedRepositories.next().toLowerCase()); } userModel.repositories.clear(); userModel.repositories.addAll(repos); Iterator<String> selectedTeams = teams.getSelectedChoices(); userModel.teams.clear(); while (selectedTeams.hasNext()) { TeamModel team = GitBlit.self().getTeamModel(selectedTeams.next()); if (team == null) { continue; } userModel.teams.add(team); } try { GitBlit.self().updateUserModel(oldName, userModel, isCreate); } catch (GitBlitException e) { error(e.getMessage()); return; } setRedirect(false); if (isCreate) { // create another user info(MessageFormat.format("New user ''{0}'' successfully created.", userModel.username)); setResponsePage(EditUserPage.class); } else { // back to users page setResponsePage(UsersPage.class); } } }; // do not let the browser pre-populate these fields form.add(new SimpleAttributeModifier("autocomplete", "off")); // field names reflective match UserModel fields form.add(new TextField<String>("username")); PasswordTextField passwordField = new PasswordTextField("password"); passwordField.setResetPassword(false); form.add(passwordField); PasswordTextField confirmPasswordField = new PasswordTextField("confirmPassword", confirmPassword); confirmPasswordField.setResetPassword(false); form.add(confirmPasswordField); form.add(new CheckBox("canAdmin")); form.add(new CheckBox("excludeFromFederation")); form.add(repositories); form.add(teams); form.add(new Button("save")); Button cancel = new Button("cancel") { private static final long serialVersionUID = 1L; @Override public void onSubmit() { setResponsePage(UsersPage.class); } }; cancel.setDefaultFormProcessing(false); form.add(cancel); add(form); } }
3e14d1af9d3c8ea4658fd47f24c0ba94f6044c7a
128
java
Java
src/main/java/azzy/fabric/lumen/api/Capacitor.java
Dragonoidzero/Lumen
632dfa0cfbb6d8480e68ca336f0823e288cae415
[ "CC0-1.0" ]
null
null
null
src/main/java/azzy/fabric/lumen/api/Capacitor.java
Dragonoidzero/Lumen
632dfa0cfbb6d8480e68ca336f0823e288cae415
[ "CC0-1.0" ]
null
null
null
src/main/java/azzy/fabric/lumen/api/Capacitor.java
Dragonoidzero/Lumen
632dfa0cfbb6d8480e68ca336f0823e288cae415
[ "CC0-1.0" ]
null
null
null
11.636364
33
0.71875
8,821
package azzy.fabric.lumen.api; public interface Capacitor { long getLumenEnergy(); boolean acceptsLumenEnergy(); }
3e14d1e7e92958461b4c7efd7122040f939ee2e8
2,891
java
Java
src/main/java/com/lujianbo/app/shadowsocks/local/connector/socks/SocksRequestHandler.java
lujianbo/moonlight-ss
52c3346926ff96534652c3056665ec09344e0d8f
[ "MIT" ]
11
2017-03-25T22:42:58.000Z
2021-06-07T13:10:03.000Z
src/main/java/com/lujianbo/app/shadowsocks/local/connector/socks/SocksRequestHandler.java
lujianbo/moonlight-ss
52c3346926ff96534652c3056665ec09344e0d8f
[ "MIT" ]
null
null
null
src/main/java/com/lujianbo/app/shadowsocks/local/connector/socks/SocksRequestHandler.java
lujianbo/moonlight-ss
52c3346926ff96534652c3056665ec09344e0d8f
[ "MIT" ]
3
2016-07-03T02:44:14.000Z
2017-10-16T20:45:27.000Z
38.546667
110
0.610515
8,822
package com.lujianbo.app.shadowsocks.local.connector.socks; import com.lujianbo.app.shadowsocks.common.codec.ShadowSocksAddressType; import com.lujianbo.app.shadowsocks.common.codec.ShadowSocksRequest; import com.lujianbo.app.shadowsocks.common.utils.NetUtils; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.socks.*; public class SocksRequestHandler extends SimpleChannelInboundHandler<SocksRequest> { @Override public void channelRead0(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception { switch (socksRequest.requestType()) { case INIT: //初始化 ctx.pipeline().addFirst(new SocksCmdRequestDecoder()); ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH)); break; case AUTH://鉴权 ctx.pipeline().addFirst(new SocksCmdRequestDecoder()); ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS)); break; case CMD: //代理 SocksCmdRequest req = (SocksCmdRequest) socksRequest; if (req.cmdType() == SocksCmdType.CONNECT) { ctx.pipeline().remove(this); //response ok ctx.writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, req.addressType())).sync(); ctx.pipeline().remove(SocksMessageEncoder.class); ctx.fireChannelRead(buildShadowSocksRequest(req)); } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } } private ShadowSocksRequest buildShadowSocksRequest(SocksCmdRequest request) { SocksAddressType addressType = request.addressType(); String host = request.host(); int port = request.port(); ShadowSocksRequest shadowSocksRequest = null; switch (addressType) { case IPv4: { shadowSocksRequest = new ShadowSocksRequest(ShadowSocksAddressType.IPv4, host, port); break; } case DOMAIN: { shadowSocksRequest = new ShadowSocksRequest(ShadowSocksAddressType.hostname, host, port); break; } case IPv6: { shadowSocksRequest = new ShadowSocksRequest(ShadowSocksAddressType.IPv6, host, port); break; } case UNKNOWN: break; } return shadowSocksRequest; } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { NetUtils.closeOnFlush(ctx.channel()); } }
3e14d22686a5ea0d6441190ec363e3d551f25a07
2,844
java
Java
cf-nats/src/main/java/cf/nats/message/StagingStart.java
cloudfoundry-community/cf-java-component
442468f0bad4645847362f8a55f371540b2bdfea
[ "Apache-2.0" ]
8
2015-03-12T05:07:03.000Z
2021-03-03T13:02:28.000Z
cf-nats/src/main/java/cf/nats/message/StagingStart.java
cloudfoundry-community/cf-java-component
442468f0bad4645847362f8a55f371540b2bdfea
[ "Apache-2.0" ]
13
2015-05-22T07:21:26.000Z
2021-12-30T00:43:32.000Z
cf-nats/src/main/java/cf/nats/message/StagingStart.java
cloudfoundry-community/cf-java-component
442468f0bad4645847362f8a55f371540b2bdfea
[ "Apache-2.0" ]
3
2015-03-03T20:12:37.000Z
2019-04-23T03:17:24.000Z
29.625
159
0.763713
8,823
/* * Copyright (c) 2012 Intellectual Reserve, Inc. 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 cf.nats.message; import java.util.Map; import cf.common.JsonObject; import cf.nats.MessageBody; import cf.nats.NatsSubject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Listens for staging messages. Useful when you want to apply certain changes to an application only when it re-stages/restarts with service binding changes. * @author youngstrommj */ @NatsSubject("staging.*.start") public class StagingStart extends JsonObject implements MessageBody<Void> { private final String appId; private final String taskId; private final String downloadUri; private final String uploadUri; private final String buildpackCacheDownloadUri; private final String buildpackCacheUploadUri; private final DeaStart startMessage; private final Map<String, Object> properties; @JsonCreator public StagingStart( @JsonProperty("app_id") String appId, @JsonProperty("task_id") String taskId, @JsonProperty("download_uri") String downloadUri, @JsonProperty("upload_uri") String uploadUri, @JsonProperty("buildpack_cache_download_uri") String buildpackCacheDownloadUri, @JsonProperty("buildpack_cache_upload_uri") String buildpackCacheUploadUri, @JsonProperty("start_message") DeaStart startMessage, @JsonProperty("properties") Map<String, Object> properties) { this.appId = appId; this.taskId = taskId; this.downloadUri = downloadUri; this.uploadUri = uploadUri; this.buildpackCacheDownloadUri = buildpackCacheDownloadUri; this.buildpackCacheUploadUri = buildpackCacheUploadUri; this.startMessage = startMessage; this.properties = properties; } public String getAppId() { return appId; } public String getTaskId() { return taskId; } public String getDownloadUri() { return downloadUri; } public String getUploadUri() { return uploadUri; } public String getBuildpackCacheDownloadUri() { return buildpackCacheDownloadUri; } public String getBuildpackCacheUploadUri() { return buildpackCacheUploadUri; } public DeaStart getStartMessage() { return startMessage; } public Map<String, Object> getProperties() { return properties; } }
3e14d3f07b7b94fcb1e748c8cf8d4910c7474bcf
1,473
java
Java
Mage.Sets/src/mage/cards/e/Enfeeblement.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/e/Enfeeblement.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/e/Enfeeblement.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
32.021739
130
0.753564
8,824
package mage.cards.e; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.continuous.BoostEnchantedEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; /** * @author Loki */ public final class Enfeeblement extends CardImpl { public Enfeeblement(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{B}{B}"); this.subtype.add(SubType.AURA); TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.Detriment)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostEnchantedEffect(-2, -2, Duration.WhileOnBattlefield))); } private Enfeeblement(final Enfeeblement card) { super(card); } @Override public Enfeeblement copy() { return new Enfeeblement(this); } }
3e14d406ca077adb4df9226c171ef8fe72c82018
1,592
java
Java
io.joel.tck/src/test/java/com/sun/ts/tests/el/common/elcontext/BarELContext.java
Thihup/joel
9278bf44d0c128b2d76b108c892f17e66eb76ff9
[ "MIT" ]
3
2021-04-08T13:51:59.000Z
2021-10-02T16:28:01.000Z
io.joel.tck/src/test/java/com/sun/ts/tests/el/common/elcontext/BarELContext.java
Thihup/joel
9278bf44d0c128b2d76b108c892f17e66eb76ff9
[ "MIT" ]
2
2021-09-23T10:24:27.000Z
2021-10-09T14:23:30.000Z
io.joel.tck/src/test/java/com/sun/ts/tests/el/common/elcontext/BarELContext.java
Thihup/joel
9278bf44d0c128b2d76b108c892f17e66eb76ff9
[ "MIT" ]
null
null
null
25.677419
76
0.711055
8,825
/* * Copyright (c) 2009, 2020 Oracle and/or its affiliates and others. * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ /* * $Id$ */ package com.sun.ts.tests.el.common.elcontext; import com.sun.ts.tests.common.el.api.resolver.BarELResolver; import jakarta.el.ELContext; import jakarta.el.ELResolver; import jakarta.el.FunctionMapper; import jakarta.el.VariableMapper; /* This ELContext contains only a simple EL resolver used to resolve expressions handled by the BarELResolver. */ public class BarELContext extends ELContext { private final ELResolver elResolver; /* * Constructor. */ public BarELContext() { this.elResolver = new BarELResolver(); } public ELResolver getELResolver() { return elResolver; } public ELContext getELContext() { return this; } public VariableMapper getVariableMapper() { return null; } public FunctionMapper getFunctionMapper() { return null; } }
3e14d4268ae2e1fddc00777fd3564326c5311f07
856
java
Java
Mage.Sets/src/mage/cards/l/LightningBolt.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage.Sets/src/mage/cards/l/LightningBolt.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage.Sets/src/mage/cards/l/LightningBolt.java
dsenginr/mage
94e9aeedc20dcb74264e58fd198f46215828ef5c
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
25.176471
73
0.712617
8,826
package mage.cards.l; import java.util.UUID; import mage.abilities.effects.common.DamageTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.common.TargetAnyTarget; /** * * @author BetaSteward_at_googlemail.com */ public final class LightningBolt extends CardImpl { public LightningBolt(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{R}"); // Lightning Bolt deals 3 damage to any target. this.getSpellAbility().addTarget(new TargetAnyTarget()); this.getSpellAbility().addEffect(new DamageTargetEffect(3)); } private LightningBolt(final LightningBolt card) { super(card); } @Override public LightningBolt copy() { return new LightningBolt(this); } }
3e14d461f53f4d01b3c5d683040071025536d95b
597
java
Java
projects/OG-Financial/src/main/java/com/opengamma/financial/generator/PortfolioNodeGenerator.java
emcleod/OG-Platform
dbd4e1c64907f6a2dd27a62d252e9c61e609f779
[ "Apache-2.0" ]
12
2017-03-10T13:56:52.000Z
2021-10-03T01:21:20.000Z
projects/OG-Financial/src/main/java/com/opengamma/financial/generator/PortfolioNodeGenerator.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
10
2017-01-19T13:32:36.000Z
2021-09-20T20:41:48.000Z
projects/OG-Financial/src/main/java/com/opengamma/financial/generator/PortfolioNodeGenerator.java
antikas/OG-Platform
aa683c63e58d33e34cca691290370d71a454077c
[ "Apache-2.0" ]
16
2017-01-12T10:31:58.000Z
2019-04-19T08:17:33.000Z
25.956522
136
0.742044
8,827
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.generator; import com.opengamma.core.position.PortfolioNode; /** * Service interface for constructing a random, but reasonable, portfolio node. */ public interface PortfolioNodeGenerator { /** * Creates a new portfolio node object. The implementing class will determine the structure of the portfolio and content of positions. * * @return the new node, not null */ PortfolioNode createPortfolioNode(); }
3e14d592e12d445f91bfc6ec8b44ae3105fa9a15
708
java
Java
src/main/java/com/rambots4571/rampage/joystick/component/DPadHandler.java
frc4571/RamHorns
92ff76948a2409a7f856f4858f906d3bade5abc4
[ "MIT" ]
null
null
null
src/main/java/com/rambots4571/rampage/joystick/component/DPadHandler.java
frc4571/RamHorns
92ff76948a2409a7f856f4858f906d3bade5abc4
[ "MIT" ]
null
null
null
src/main/java/com/rambots4571/rampage/joystick/component/DPadHandler.java
frc4571/RamHorns
92ff76948a2409a7f856f4858f906d3bade5abc4
[ "MIT" ]
null
null
null
25.285714
71
0.751412
8,828
package com.rambots4571.rampage.joystick.component; import com.rambots4571.rampage.joystick.component.DPadButton.Direction; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj2.command.button.Button; import java.util.HashMap; public class DPadHandler { private final HashMap<Direction, Button> buttons; private final Joystick joystick; public DPadHandler(Joystick joystick) { this.joystick = joystick; buttons = new HashMap<>(); } public Button get(Direction direction) { if (buttons.containsKey(direction)) return buttons.get(direction); Button button = new DPadButton(joystick, direction); buttons.put(direction, button); return button; } }
3e14d5e4b7682abca507d1cc666bb9d19b09fd01
10,001
java
Java
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java
rvhub/MultipathODL
0abd8fd47d6504cc21bdb042f60e830edf9b1bd4
[ "Apache-2.0" ]
null
null
null
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java
rvhub/MultipathODL
0abd8fd47d6504cc21bdb042f60e830edf9b1bd4
[ "Apache-2.0" ]
null
null
null
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java
rvhub/MultipathODL
0abd8fd47d6504cc21bdb042f60e830edf9b1bd4
[ "Apache-2.0" ]
null
null
null
44.647321
126
0.677932
8,829
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.md.sal.common.impl.util.compat; import static com.google.common.base.Preconditions.checkArgument; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.api.SimpleNode; import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.MixinNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer; import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode; import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode; import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl; import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; public class DataNormalizer { private final DataNormalizationOperation<?> operation; public DataNormalizer(final SchemaContext ctx) { operation = DataNormalizationOperation.from(ctx); } public YangInstanceIdentifier toNormalized(final YangInstanceIdentifier legacy) { ImmutableList.Builder<PathArgument> normalizedArgs = ImmutableList.builder(); DataNormalizationOperation<?> currentOp = operation; Iterator<PathArgument> arguments = legacy.getPathArguments().iterator(); try { while (arguments.hasNext()) { PathArgument legacyArg = arguments.next(); currentOp = currentOp.getChild(legacyArg); checkArgument(currentOp != null, "Legacy Instance Identifier %s is not correct. Normalized Instance Identifier so far %s", legacy, normalizedArgs.build()); while (currentOp.isMixin()) { normalizedArgs.add(currentOp.getIdentifier()); currentOp = currentOp.getChild(legacyArg.getNodeType()); } normalizedArgs.add(legacyArg); } } catch (DataNormalizationException e) { throw new IllegalArgumentException(String.format("Failed to normalize path %s", legacy), e); } return YangInstanceIdentifier.create(normalizedArgs.build()); } public DataNormalizationOperation<?> getOperation(final YangInstanceIdentifier legacy) throws DataNormalizationException { DataNormalizationOperation<?> currentOp = operation; Iterator<PathArgument> arguments = legacy.getPathArguments().iterator(); while (arguments.hasNext()) { currentOp = currentOp.getChild(arguments.next()); } return currentOp; } public Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized( final Map.Entry<YangInstanceIdentifier, CompositeNode> legacy) { return toNormalized(legacy.getKey(), legacy.getValue()); } public Map.Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalized(final YangInstanceIdentifier legacyPath, final CompositeNode legacyData) { YangInstanceIdentifier normalizedPath = toNormalized(legacyPath); DataNormalizationOperation<?> currentOp = operation; for (PathArgument arg : normalizedPath.getPathArguments()) { try { currentOp = currentOp.getChild(arg); } catch (DataNormalizationException e) { throw new IllegalArgumentException(String.format("Failed to validate normalized path %s", normalizedPath), e); } } // Write Augmentation data resolution if (legacyData.getValue().size() == 1) { final DataNormalizationOperation<?> potentialOp; try { final QName childType = legacyData.getValue().get(0).getNodeType(); potentialOp = currentOp.getChild(childType); } catch (DataNormalizationException e) { throw new IllegalArgumentException(String.format("Failed to get child operation for %s", legacyData), e); } if (potentialOp.getIdentifier() instanceof AugmentationIdentifier) { currentOp = potentialOp; normalizedPath = normalizedPath.node(potentialOp.getIdentifier()); } } Preconditions.checkArgument(currentOp != null, "Instance Identifier %s does not reference correct schema Node.", normalizedPath); return new AbstractMap.SimpleEntry<YangInstanceIdentifier, NormalizedNode<?, ?>>(normalizedPath, currentOp.normalize(legacyData)); } public YangInstanceIdentifier toLegacy(final YangInstanceIdentifier normalized) throws DataNormalizationException { ImmutableList.Builder<PathArgument> legacyArgs = ImmutableList.builder(); DataNormalizationOperation<?> currentOp = operation; for (PathArgument normalizedArg : normalized.getPathArguments()) { currentOp = currentOp.getChild(normalizedArg); if (!currentOp.isMixin()) { legacyArgs.add(normalizedArg); } } return YangInstanceIdentifier.create(legacyArgs.build()); } public CompositeNode toLegacy(final YangInstanceIdentifier normalizedPath, final NormalizedNode<?, ?> normalizedData) { // Preconditions.checkArgument(normalizedData instanceof // DataContainerNode<?>,"Node object %s, %s should be of type DataContainerNode",normalizedPath,normalizedData); if (normalizedData instanceof DataContainerNode<?>) { return toLegacyFromDataContainer((DataContainerNode<?>) normalizedData); } else if (normalizedData instanceof AnyXmlNode) { Node<?> value = ((AnyXmlNode) normalizedData).getValue(); return value instanceof CompositeNode ? (CompositeNode) value : null; } return null; } public static Node<?> toLegacy(final NormalizedNode<?, ?> node) { if (node instanceof MixinNode) { /** * Direct reading of MixinNodes is not supported, since it is not * possible in legacy APIs create pointer to Mixin Nodes. * */ return null; } if (node instanceof DataContainerNode<?>) { return toLegacyFromDataContainer((DataContainerNode<?>) node); } else if (node instanceof AnyXmlNode) { return ((AnyXmlNode) node).getValue(); } return toLegacySimple(node); } private static SimpleNode<?> toLegacySimple(final NormalizedNode<?, ?> node) { return new SimpleNodeTOImpl<Object>(node.getNodeType(), null, node.getValue()); } @SuppressWarnings({ "unchecked", "rawtypes" }) private static CompositeNode toLegacyFromDataContainer(final DataContainerNode<?> node) { CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder(); builder.setQName(node.getNodeType()); for (NormalizedNode<?, ?> child : node.getValue()) { if (child instanceof MixinNode && child instanceof NormalizedNodeContainer<?, ?, ?>) { builder.addAll(toLegacyNodesFromMixin((NormalizedNodeContainer) child)); } else if (child instanceof UnkeyedListNode) { builder.addAll(toLegacyNodesFromUnkeyedList((UnkeyedListNode) child)); } else { addToBuilder(builder, toLegacy(child)); } } return builder.toInstance(); } private static Iterable<? extends Node<?>> toLegacyNodesFromUnkeyedList(final UnkeyedListNode mixin) { ArrayList<Node<?>> ret = new ArrayList<>(); for (NormalizedNode<?, ?> child : mixin.getValue()) { ret.add(toLegacy(child)); } return FluentIterable.from(ret).filter(Predicates.notNull()); } private static void addToBuilder(final CompositeNodeBuilder<ImmutableCompositeNode> builder, final Node<?> legacy) { if (legacy != null) { builder.add(legacy); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private static Iterable<Node<?>> toLegacyNodesFromMixin( final NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>> mixin) { ArrayList<Node<?>> ret = new ArrayList<>(); for (NormalizedNode<?, ?> child : mixin.getValue()) { if (child instanceof MixinNode && child instanceof NormalizedNodeContainer<?, ?, ?>) { Iterables.addAll(ret, toLegacyNodesFromMixin((NormalizedNodeContainer) child)); } else { ret.add(toLegacy(child)); } } return FluentIterable.from(ret).filter(Predicates.notNull()); } public DataNormalizationOperation<?> getRootOperation() { return operation; } }
3e14d65955c81bd4b4a92a5e4c8f7f305a2690a1
4,985
java
Java
src/main/java/com/quantech/entities/doctor/DoctorService.java
quantech-bristol/electronic-handover-v2
00aa0b4d3a94d810bcf382b5fd48fa94bb3c7e92
[ "MIT" ]
null
null
null
src/main/java/com/quantech/entities/doctor/DoctorService.java
quantech-bristol/electronic-handover-v2
00aa0b4d3a94d810bcf382b5fd48fa94bb3c7e92
[ "MIT" ]
null
null
null
src/main/java/com/quantech/entities/doctor/DoctorService.java
quantech-bristol/electronic-handover-v2
00aa0b4d3a94d810bcf382b5fd48fa94bb3c7e92
[ "MIT" ]
null
null
null
36.925926
123
0.687663
8,830
package com.quantech.entities.doctor; import com.quantech.entities.patient.Patient; import com.quantech.entities.team.Team; import com.quantech.entities.user.UserCore; import org.springframework.stereotype.Service; import java.util.List; import java.util.function.Predicate; @Service public interface DoctorService { /** * @return A list of all doctors stored in the doctor repository. */ public List<Doctor> getAllDoctors(); /** * Sort the given list of doctors by their last date of renewal, most recent first. * @param list The list of doctors. * @return A sorted list of doctors, by first name. */ public List<Doctor> sortDoctorsByDateRenewedMostRecentFirst(List<Doctor> list); /** * Sort the given list of doctors by their last date of renewal, most recent last. * @param list The list of doctors. * @return A sorted list of doctors, by first name. */ public List<Doctor> sortDoctorsByDateRenewedMostRecentLast(List<Doctor> list); /** * Sort the given list of doctors by their first name, alphabetically. * @param list The list of doctors. * @return A sorted list of doctors, by first name. */ public List<Doctor> sortDoctorsByFirstName(List<Doctor> list); /** * Sort the given list of doctors by their last name, alphabetically. * @param list The list of doctors. * @return A sorted list of doctors, by last name. */ public List<Doctor> sortDoctorsByLastName(List<Doctor> list); /** * Finds the doctor object corresponding to a given unique id. * @param user The user that has been assigned doctor privileges. * @return The doctor object that corresponds to the id if it exists, null if a doctor with the given id doesn't exist. */ public Doctor getDoctor(UserCore user); /** * Saves the given doctor object into the repository. * @param doctor The doctor object to save. * @throws NullPointerException If the user or title has not been set, that is, is null. * @throws IllegalArgumentException If the user object is already associated with a user. * @throws IllegalArgumentException If the user object assigned hasn't got doctor permissions. */ public void saveDoctor(Doctor doctor) throws NullPointerException, IllegalArgumentException; /** * Deletes the doctor with the corresponding id from the repository. * @param id The id corresponding to the doctor to be deleted. */ public void deleteDoctor(Long id); /** * Adds the given team to the doctor's list. * @param team The team for which the doctor should be added to. * @param user The user corresponding to the doctor in the repository. */ public void addTeamToDoctor(Team team, UserCore user); /** * Removes the given team from the doctor's list. * @param team The team for which the doctor should be removed from. * @param user The user corresponding to the doctor in the repository. */ public void removeTeamFromDoctor(Team team, UserCore user); /** * Returns a list of patients under the doctor's care. * @param user The user object of the given doctor. * @return A list of patients under the doctor's care. */ public List<Patient> getPatientsUnderCareOf(UserCore user); /** * Filter list of a doctors by a given predicate. * @param list A list of doctors. * @param predicate A predicate to test the doctors against. * @return A list of doctors filtered by the given predicate. */ public List<Doctor> filterDoctorsBy(List<Doctor> list, Predicate<Doctor> predicate); /** * Filter list of a doctors by a given predicate. * @param list A list of doctors. * @param predicates A collection of predicates to test the doctors against. * @return A list of doctors filtered by the given predicate. */ public List<Doctor> filterDoctorsBy(List<Doctor> list, Iterable<Predicate<Doctor>> predicates); /** * Returns a predicate that checks if a doctor is on a given set of teams. * @param team The iterable of teams to check. * @return A predicate. */ public Predicate<Doctor> doctorIsInTeam(Iterable<Team> team); /** * Returns a predicate that checks if a doctor is on a given team. * @param team The team to check. * @return A predicate. */ public Predicate<Doctor> doctorIsInTeam(Team team); /** * Returns a predicate that checks if a doctor's first name starts with the given string. * @param str The string to check. * @return A predicate. */ public Predicate<Doctor> doctorsFirstNameStartsWith(String str); /** * Returns a predicate that checks if a doctor's last name starts with the given string. * @param str The string to check. * @return A predicate. */ public Predicate<Doctor> doctorsLastNameStartsWith(String str); }
3e14d79822d35d2adcc30db55308a051a6431870
471
java
Java
Jeff/Sweeper.java
BrightNightE/RHUL-CS1820-Robotics
5511c55e015919d99296288ee1fd665f0d4a2d2c
[ "MIT" ]
null
null
null
Jeff/Sweeper.java
BrightNightE/RHUL-CS1820-Robotics
5511c55e015919d99296288ee1fd665f0d4a2d2c
[ "MIT" ]
null
null
null
Jeff/Sweeper.java
BrightNightE/RHUL-CS1820-Robotics
5511c55e015919d99296288ee1fd665f0d4a2d2c
[ "MIT" ]
null
null
null
20.478261
55
0.653928
8,831
import lejos.robotics.RegulatedMotor; public class Sweeper extends Thread { private RegulatedMotor sc; public Sweeper(RegulatedMotor sc) { this.sc = sc; } @Override public void run() { super.run(); // always call super // make a motor sc.setSpeed((int) MoveList.SWEEPER_SPEED.getMove()); while (true) { // move sc.rotate((int) MoveList.ARM_ROTATION.getMove()); sc.rotate(-(int) MoveList.ARM_ROTATION.getMove()); } } }
3e14d7da0e2d42034dcfe4112d09c42c658e38f4
651
java
Java
src/main/java/xyz/cafeconleche/web/thebride/service/impl/FollowServicePojoImpl.java
topiltzin-butron/thebride
1e1498a36bd52b802186367b73f623153e8d09a1
[ "MIT" ]
null
null
null
src/main/java/xyz/cafeconleche/web/thebride/service/impl/FollowServicePojoImpl.java
topiltzin-butron/thebride
1e1498a36bd52b802186367b73f623153e8d09a1
[ "MIT" ]
null
null
null
src/main/java/xyz/cafeconleche/web/thebride/service/impl/FollowServicePojoImpl.java
topiltzin-butron/thebride
1e1498a36bd52b802186367b73f623153e8d09a1
[ "MIT" ]
null
null
null
23.25
62
0.812596
8,832
package xyz.cafeconleche.web.thebride.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import xyz.cafeconleche.web.thebride.dao.FollowDao; import xyz.cafeconleche.web.thebride.service.FollowService; @Service public class FollowServicePojoImpl implements FollowService{ @Autowired private FollowDao followingDao; @Override public List<String> getFollowing(String username) { return followingDao.getFollowing(username); } @Override public List<String> getFollowers(String username) { return followingDao.getFollowers(username); } }
3e14d846adcd8e74624c6aa105ce92c80d43c10a
36,279
java
Java
sdk/core/azure-core/src/main/java/com/azure/core/util/BinaryData.java
blackbaud/azure-sdk-for-java
76951c7e366b0dbb95c8dfb600acd855092e0a35
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
sdk/core/azure-core/src/main/java/com/azure/core/util/BinaryData.java
omziv/azure-sdk-for-java
868c2c06ec7188459fea96a1e4533b9d826061e7
[ "MIT" ]
2
2021-12-24T05:47:16.000Z
2022-01-10T09:47:03.000Z
sdk/core/azure-core/src/main/java/com/azure/core/util/BinaryData.java
omziv/azure-sdk-for-java
868c2c06ec7188459fea96a1e4533b9d826061e7
[ "MIT" ]
1
2020-12-24T04:02:44.000Z
2020-12-24T04:02:44.000Z
50.882188
149
0.693128
8,833
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.util; import com.azure.core.util.implementation.BinaryDataContent; import com.azure.core.util.implementation.ByteArrayContent; import com.azure.core.util.implementation.FileContent; import com.azure.core.util.implementation.FluxByteBufferContent; import com.azure.core.util.implementation.InputStreamContent; import com.azure.core.util.implementation.SerializableContent; import com.azure.core.util.implementation.StringContent; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.serializer.JsonSerializer; import com.azure.core.util.serializer.JsonSerializerProvider; import com.azure.core.util.serializer.JsonSerializerProviders; import com.azure.core.util.serializer.ObjectSerializer; import com.azure.core.util.serializer.TypeReference; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.ReadOnlyBufferException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Objects; import static com.azure.core.util.FluxUtil.monoError; import static com.azure.core.util.implementation.BinaryDataContent.STREAM_READ_SIZE; /** * * BinaryData is a convenient data interchange class for use throughout the Azure SDK for Java. Put simply, BinaryData * enables developers to bring data in from external sources, and read it back from Azure services, in formats that * appeal to them. This leaves BinaryData, and the Azure SDK for Java, the task of converting this data into appropriate * formats to be transferred to and from these external services. This enables developers to focus on their business * logic, and enables the Azure SDK for Java to optimize operations for best performance. * <p> * BinaryData in its simplest form can be thought of as a container for content. Often this content is already in-memory * as a String, byte array, or an Object that can be serialized into a String or byte[]. When the BinaryData is about to * be sent to an Azure Service, this in-memory content is copied into the network request and sent to the service. * </p> * <p> * In more performance critical scenarios, where copying data into memory results in increased memory pressure, it is * possible to create a BinaryData instance from a stream of data. From this, BinaryData can be connected directly to * the outgoing network connection so that the stream is read directly to the network, without needing to first be read * into memory on the system. Similarly, it is possible to read a stream of data from a BinaryData returned from an * Azure Service without it first being read into memory. In many situations, these streaming operations can drastically * reduce the memory pressure in applications, and so it is encouraged that all developers very carefully consider their * ability to use the most appropriate API in BinaryData whenever they encounter an client library that makes use of * BinaryData. * </p> * <p> * Refer to the documentation of each method in the BinaryData class to better understand its performance * characteristics, and refer to the samples below to understand the common usage scenarios of this class. * </p> * * {@link BinaryData} can be created from an {@link InputStream}, a {@link Flux} of {@link ByteBuffer}, a {@link * String}, an {@link Object}, a {@link Path file}, or a byte array. * * <p><strong>A note on data mutability</strong></p> * * {@link BinaryData} does not copy data on construction. BinaryData keeps a reference to the source content * and is accessed when a read request is made. So, any modifications to the underlying source before the content is * read can result in undefined behavior. * <p> * To create an instance of {@link BinaryData}, use the various * static factory methods available. They all start with {@code 'from'} prefix, for example * {@link BinaryData#fromBytes(byte[])}. *</p> * * <p><strong>Create an instance from a byte array</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromBytes#byte} * * <p><strong>Create an instance from a String</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromString#String} * * <p><strong>Create an instance from an InputStream</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromStream#InputStream} * * <p><strong>Create an instance from an Object</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromObject#Object} * * <p><strong>Create an instance from {@code Flux<ByteBuffer>}</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromFlux#Flux} * * <p><strong>Create an instance from a file</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromFile} * * @see ObjectSerializer * @see JsonSerializer * @see <a href="https://aka.ms/azsdk/java/docs/serialization" target="_blank">More about serialization</a> */ public final class BinaryData { private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class); static final JsonSerializer SERIALIZER = JsonSerializerProviders.createInstance(true); private final BinaryDataContent content; BinaryData(BinaryDataContent content) { this.content = Objects.requireNonNull(content, "'content' cannot be null."); } /** * Creates an instance of {@link BinaryData} from the given {@link InputStream}. Depending on the type of * inputStream, the BinaryData instance created may or may not allow reading the content more than once. The * stream content is not cached if the stream is not read into a format that requires the content to be fully read * into memory. * <p> * <b>NOTE:</b> The {@link InputStream} is not closed by this function. * </p> * * <p><strong>Create an instance from an InputStream</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromStream#InputStream} * * @param inputStream The {@link InputStream} that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the {@link InputStream}. * @throws UncheckedIOException If any error happens while reading the {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. */ public static BinaryData fromStream(InputStream inputStream) { return new BinaryData(new InputStreamContent(inputStream)); } /** * Creates an instance of {@link BinaryData} from the given {@link InputStream}. * <b>NOTE:</b> The {@link InputStream} is not closed by this function. * * <p><strong>Create an instance from an InputStream</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromStreamAsync#InputStream} * * @param inputStream The {@link InputStream} that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the {@link InputStream}. * @throws UncheckedIOException If any error happens while reading the {@link InputStream}. * @throws NullPointerException If {@code inputStream} is null. */ public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) { return Mono.fromCallable(() -> fromStream(inputStream)); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. The source flux * is subscribed to as many times as the content is read. The flux, therefore, must be replayable. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromFlux#Flux} * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws NullPointerException If {@code data} is null. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) { if (data == null) { return monoError(LOGGER, new NullPointerException("'content' cannot be null.")); } return Mono.just(new BinaryData(new FluxByteBufferContent(data))); } /** * Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}. The source flux * is subscribed to as many times as the content is read. The flux, therefore, must be replayable. * * <p><strong>Create an instance from a Flux of ByteBuffer</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromFlux#Flux} * * @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent. * @param length The length of {@code data} in bytes. * @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}. * @throws IllegalArgumentException if the length is less than zero. * @throws NullPointerException if {@code data} is null. */ public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data, Long length) { if (data == null) { return monoError(LOGGER, new NullPointerException("'content' cannot be null.")); } if (length < 0) { return monoError(LOGGER, new IllegalArgumentException("'length' cannot be less than 0.")); } return Mono.just(new BinaryData(new FluxByteBufferContent(data, length))); } /** * Creates an instance of {@link BinaryData} from the given {@link String}. * <p> * The {@link String} is converted into bytes using {@link String#getBytes(Charset)} passing {@link * StandardCharsets#UTF_8}. * </p> * <p><strong>Create an instance from a String</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromString#String} * * @param data The {@link String} that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the {@link String}. * @throws NullPointerException If {@code data} is null. */ public static BinaryData fromString(String data) { return new BinaryData(new StringContent(data)); } /** * Creates an instance of {@link BinaryData} from the given byte array. * <p> * If the byte array is null or zero length an empty {@link BinaryData} will be returned. Note that the input * byte array is used as a reference by this instance of {@link BinaryData} and any changes to the byte array * outside of this instance will result in the contents of this BinaryData instance being updated as well. To * safely update the byte array without impacting the BinaryData instance, perform an array copy first. * </p> * * <p><strong>Create an instance from a byte array</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromBytes#byte} * * @param data The byte array that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the byte array. * @throws NullPointerException If {@code data} is null. */ public static BinaryData fromBytes(byte[] data) { return new BinaryData(new ByteArrayContent(data)); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link * JsonSerializer}. * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to serialize the object. *</p> * <p><strong>Creating an instance from an Object</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromObject#Object} * * @param data The object that will be JSON serialized that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the JSON serialized object. * @throws NullPointerException If {@code data} is null. * @see JsonSerializer */ public static BinaryData fromObject(Object data) { return fromObject(data, SERIALIZER); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link * JsonSerializer}. * * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to serialize the object. * </p> * <p><strong>Creating an instance from an Object</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync#Object} * * @param data The object that will be JSON serialized that {@link BinaryData} will represent. * @return A {@link Mono} of {@link BinaryData} representing the JSON serialized object. * @see JsonSerializer */ public static Mono<BinaryData> fromObjectAsync(Object data) { return fromObjectAsync(data, SERIALIZER); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link * ObjectSerializer}. * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * </p> * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-jackson" target="_blank">Jackson JSON serializer</a></li> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-gson" target="_blank">GSON JSON serializer</a></li> * </ul> * * <p><strong>Create an instance from an Object</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromObject#Object-ObjectSerializer} * * @param data The object that will be serialized that {@link BinaryData} will represent. The {@code serializer} * determines how {@code null} data is serialized. * @param serializer The {@link ObjectSerializer} used to serialize object. * @return A {@link BinaryData} representing the serialized object. * @throws NullPointerException If {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https://aka.ms/azsdk/java/docs/serialization" target="_blank">More about serialization</a> */ public static BinaryData fromObject(Object data, ObjectSerializer serializer) { return new BinaryData(new SerializableContent(data, serializer)); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link * ObjectSerializer}. * * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * </p> * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-jackson" target="_blank">Jackson JSON serializer</a></li> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-gson" target="_blank">GSON JSON serializer</a></li> * </ul> * * <p><strong>Create an instance from an Object</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync#Object-ObjectSerializer} * * @param data The object that will be serialized that {@link BinaryData} will represent. The {@code serializer} * determines how {@code null} data is serialized. * @param serializer The {@link ObjectSerializer} used to serialize object. * @return A {@link Mono} of {@link BinaryData} representing the serialized object. * @throws NullPointerException If {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https://aka.ms/azsdk/java/docs/serialization" target="_blank">More about serialization</a> */ public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) { return Mono.fromCallable(() -> fromObject(data, serializer)); } /** * Creates a {@link BinaryData} that uses the content of the file at {@link Path} as its data. This method checks * for the existence of the file at the time of creating an instance of {@link BinaryData}. The file, however, is * not read until there is an attempt to read the contents of the returned BinaryData instance. * * <p><strong>Create an instance from a file</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromFile} * * @param file The {@link Path} that will be the {@link BinaryData} data. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code file} is null. */ public static BinaryData fromFile(Path file) { return fromFile(file, STREAM_READ_SIZE); } /** * Creates a {@link BinaryData} that uses the content of the file at {@link Path file} as its data. This method * checks for the existence of the file at the time of creating an instance of {@link BinaryData}. The file, * however, is not read until there is an attempt to read the contents of the returned BinaryData instance. * * <p><strong>Create an instance from a file</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.fromFile#Path-int} * * @param file The {@link Path} that will be the {@link BinaryData} data. * @param chunkSize The requested size for each read of the path. * @return A new {@link BinaryData}. * @throws NullPointerException If {@code file} is null. * @throws IllegalArgumentException If {@code offset} or {@code length} are negative or {@code offset} plus {@code * length} is greater than the file size or {@code chunkSize} is less than or equal to 0. * @throws UncheckedIOException if the file does not exist. */ public static BinaryData fromFile(Path file, int chunkSize) { return new BinaryData(new FileContent(file, chunkSize)); } /** * Returns a byte array representation of this {@link BinaryData}. This method returns a reference to the * underlying byte array. Modifying the contents of the returned byte array will also change the content of this * BinaryData instance. If the content source of this BinaryData instance is a file, an Inputstream or a * {@code Flux<ByteBuffer>} the source is not modified. To safely update the byte array, it is recommended * to make a copy of the contents first. * * @return A byte array representing this {@link BinaryData}. */ public byte[] toBytes() { return content.toBytes(); } /** * Returns a {@link String} representation of this {@link BinaryData} by converting its data using the UTF-8 * character set. A new instance of String is created each time this method is called. * * @return A {@link String} representing this {@link BinaryData}. */ public String toString() { return content.toString(); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * #toObject(TypeReference)}. * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObject#Class} * * @param <T> Type of the deserialized Object. * @param clazz The {@link Class} representing the Object's type. * @return An {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} is null. * @see JsonSerializer */ public <T> T toObject(Class<T> clazz) { return toObject(TypeReference.createInstance(clazz), SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference#createInstance(Class)}. * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObject#TypeReference} * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObject#TypeReference-generic} * * @param typeReference The {@link TypeReference} representing the Object's type. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} is null. * @see JsonSerializer */ public <T> T toObject(TypeReference<T> typeReference) { return toObject(typeReference, SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * #toObject(TypeReference, ObjectSerializer)}. * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-jackson" target="_blank">Jackson JSON serializer</a></li> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-gson" target="_blank">GSON JSON serializer</a></li> * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObject#Class-ObjectSerializer} * * @param clazz The {@link Class} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https://aka.ms/azsdk/java/docs/serialization" target="_blank">More about serialization</a> */ public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) { return toObject(TypeReference.createInstance(clazz), serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference#createInstance(Class)}. * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-jackson" target="_blank">Jackson JSON serializer</a></li> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-gson" target="_blank">GSON JSON serializer</a></li> * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObject#TypeReference-ObjectSerializer} * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObject#TypeReference-ObjectSerializer-generic} * * @param typeReference The {@link TypeReference} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return An {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https://aka.ms/azsdk/java/docs/serialization" target="_blank">More about serialization</a> */ public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) { Objects.requireNonNull(typeReference, "'typeReference' cannot be null."); Objects.requireNonNull(serializer, "'serializer' cannot be null."); return content.toObject(typeReference, serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * #toObject(TypeReference)}. * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObjectAsync#Class} * * @param clazz The {@link Class} representing the Object's type. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} is null. * @see JsonSerializer */ public <T> Mono<T> toObjectAsync(Class<T> clazz) { return toObjectAsync(TypeReference.createInstance(clazz), SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default * {@link JsonSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference#createInstance(Class)}. * <p> * <b>Note:</b> This method first looks for a {@link JsonSerializerProvider} implementation on the classpath. If no * implementation is found, a default Jackson-based implementation will be used to deserialize the object. * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObjectAsync#TypeReference} * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObjectAsync#TypeReference-generic} * * @param typeReference The {@link TypeReference} representing the Object's type. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} is null. * @see JsonSerializer */ public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference) { return toObjectAsync(typeReference, SERIALIZER); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link * #toObject(TypeReference, ObjectSerializer)}. * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-jackson" target="_blank">Jackson JSON serializer</a></li> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-gson" target="_blank">GSON JSON serializer</a></li> * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObjectAsync#Class-ObjectSerializer} * * @param clazz The {@link Class} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code clazz} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https://aka.ms/azsdk/java/docs/serialization" target="_blank">More about serialization</a> */ public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { return toObjectAsync(TypeReference.createInstance(clazz), serializer); } /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of * type {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the * same type is not recommended. * <p> * The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is * generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link * TypeReference#createInstance(Class)}. * <p> * The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your * own implementation. * * <p><strong>Azure SDK implementations</strong></p> * <ul> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-jackson" target="_blank">Jackson JSON serializer</a></li> * <li><a href="https://mvnrepository.com/artifact/com.azure/azure-core-serializer-json-gson" target="_blank">GSON JSON serializer</a></li> * </ul> * * <p><strong>Get a non-generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObjectAsync#TypeReference-ObjectSerializer} * * <p><strong>Get a generic Object from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toObjectAsync#TypeReference-ObjectSerializer-generic} * * @param typeReference The {@link TypeReference} representing the Object's type. * @param serializer The {@link ObjectSerializer} used to deserialize object. * @param <T> Type of the deserialized Object. * @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}. * @throws NullPointerException If {@code typeReference} or {@code serializer} is null. * @see ObjectSerializer * @see JsonSerializer * @see <a href="https://aka.ms/azsdk/java/docs/serialization" target="_blank">More about serialization</a> */ public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) { return Mono.fromCallable(() -> toObject(typeReference, serializer)); } /** * Returns an {@link InputStream} representation of this {@link BinaryData}. * * <p><strong>Get an InputStream from the BinaryData</strong></p> * * {@codesnippet com.azure.core.util.BinaryData.toStream} * * @return An {@link InputStream} representing the {@link BinaryData}. */ public InputStream toStream() { return content.toStream(); } /** * Returns a read-only {@link ByteBuffer} representation of this {@link BinaryData}. * <p> * Attempting to mutate the returned {@link ByteBuffer} will throw a {@link ReadOnlyBufferException}. * * <p><strong>Get a read-only ByteBuffer from the BinaryData</strong></p> * * {@codesnippet com.azure.util.BinaryData.toByteBuffer} * * @return A read-only {@link ByteBuffer} representing the {@link BinaryData}. */ public ByteBuffer toByteBuffer() { return content.toByteBuffer(); } /** * Returns the content of this {@link BinaryData} instance as a flux of {@link ByteBuffer ByteBuffers}. The * content is not read from the underlying data source until the {@link Flux} is subscribed to. * * @return the content of this {@link BinaryData} instance as a flux of {@link ByteBuffer ByteBuffers}. */ public Flux<ByteBuffer> toFluxByteBuffer() { return content.toFluxByteBuffer(); } /** * Returns the length of the content, if it is known. The length can be {@code null} if the source did not * specify the length or the length cannot be determined without reading the whole content. * * @return the length of the content, if it is known. */ public Long getLength() { return content.getLength(); } }
3e14d852f9134ac07b54c4c9ee21542e1a2f8ea3
729
java
Java
Labs/src/com/company/exam/rmi/ClientRmiTask2.java
Megarekrut65/Destributed-Programming-labs
a500cad447716b392f8e090d87f8be82ec3d3e1b
[ "MIT" ]
null
null
null
Labs/src/com/company/exam/rmi/ClientRmiTask2.java
Megarekrut65/Destributed-Programming-labs
a500cad447716b392f8e090d87f8be82ec3d3e1b
[ "MIT" ]
null
null
null
Labs/src/com/company/exam/rmi/ClientRmiTask2.java
Megarekrut65/Destributed-Programming-labs
a500cad447716b392f8e090d87f8be82ec3d3e1b
[ "MIT" ]
null
null
null
34.714286
89
0.687243
8,834
package com.company.exam.rmi; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; public class ClientRmiTask2 { public static void main(String[] args) { try { CustomerManagerRemote managerRemote = (CustomerManagerRemote) Naming.lookup("//localhost/CustomerManager"); System.out.println(managerRemote.getCustomers()); System.out.println(managerRemote.getSortedCustomers()); System.out.println(managerRemote.getCustomersByCard(100,5000)); } catch (NotBoundException | MalformedURLException | RemoteException e) { e.printStackTrace(); } } }
3e14d8964f6b38f9ed4ed48e4dfcd1659b476e7c
37,499
java
Java
fe/fe-core/src/main/java/org/apache/doris/analysis/AggregateInfo.java
xu20160924/incubator-doris
f93dae98e41752663ff12a443c5a46914c7aae7a
[ "Apache-2.0" ]
3,562
2018-08-30T05:26:10.000Z
2022-03-31T10:01:56.000Z
fe/fe-core/src/main/java/org/apache/doris/analysis/AggregateInfo.java
hf200012/incubator-doris
9c12060db3616051359d9ac500a124cecf3c358e
[ "Apache-2.0" ]
5,199
2018-09-11T07:57:21.000Z
2022-03-31T16:17:50.000Z
fe/fe-core/src/main/java/org/apache/doris/analysis/AggregateInfo.java
hf200012/incubator-doris
9c12060db3616051359d9ac500a124cecf3c358e
[ "Apache-2.0" ]
1,234
2018-08-31T09:34:54.000Z
2022-03-31T06:01:02.000Z
45.563791
110
0.647537
8,835
// 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.doris.analysis; import org.apache.doris.catalog.FunctionSet; import org.apache.doris.common.AnalysisException; import org.apache.doris.planner.DataPartition; import org.apache.doris.thrift.TPartitionType; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; /** * Encapsulates all the information needed to compute the aggregate functions of a single * Select block, including a possible 2nd phase aggregation step for DISTINCT aggregate * functions and merge aggregation steps needed for distributed execution. * * The latter requires a tree structure of AggregateInfo objects which express the * original aggregate computations as well as the necessary merging aggregate * computations. * TODO: get rid of this by transforming * SELECT COUNT(DISTINCT a, b, ..) GROUP BY x, y, ... * into an equivalent query with a inline view: * SELECT COUNT(*) FROM (SELECT DISTINCT a, b, ..., x, y, ...) GROUP BY x, y, ... * * The tree structure looks as follows: * - for non-distinct aggregation: * - aggInfo: contains the original aggregation functions and grouping exprs * - aggInfo.mergeAggInfo: contains the merging aggregation functions (grouping * exprs are identical) * - for distinct aggregation (for an explanation of the phases, see * SelectStmt.createDistinctAggInfo()): * - aggInfo: contains the phase 1 aggregate functions and grouping exprs * - aggInfo.2ndPhaseDistinctAggInfo: contains the phase 2 aggregate functions and * grouping exprs * - aggInfo.mergeAggInfo: contains the merging aggregate functions for the phase 1 * computation (grouping exprs are identical) * - aggInfo.2ndPhaseDistinctAggInfo.mergeAggInfo: contains the merging aggregate * functions for the phase 2 computation (grouping exprs are identical) * * In general, merging aggregate computations are idempotent; in other words, * aggInfo.mergeAggInfo == aggInfo.mergeAggInfo.mergeAggInfo. * * TODO: move the merge construction logic from SelectStmt into AggregateInfo * TODO: Add query tests for aggregation with intermediate tuples with num_nodes=1. */ public final class AggregateInfo extends AggregateInfoBase { private final static Logger LOG = LogManager.getLogger(AggregateInfo.class); public enum AggPhase { FIRST, FIRST_MERGE, SECOND, SECOND_MERGE; public boolean isMerge() { return this == FIRST_MERGE || this == SECOND_MERGE; } }; // created by createMergeAggInfo() private AggregateInfo mergeAggInfo_; // created by createDistinctAggInfo() private AggregateInfo secondPhaseDistinctAggInfo_; private final AggPhase aggPhase_; // Map from all grouping and aggregate exprs to a SlotRef referencing the corresp. slot // in the intermediate tuple. Identical to outputTupleSmap_ if no aggregateExpr has an // output type that is different from its intermediate type. protected ExprSubstitutionMap intermediateTupleSmap_ = new ExprSubstitutionMap(); // Map from all grouping and aggregate exprs to a SlotRef referencing the corresp. slot // in the output tuple. protected ExprSubstitutionMap outputTupleSmap_ = new ExprSubstitutionMap(); // Map from slots of outputTupleSmap_ to the corresponding slot in // intermediateTupleSmap_. protected ExprSubstitutionMap outputToIntermediateTupleSmap_ = new ExprSubstitutionMap(); // if set, a subset of groupingExprs_; set and used during planning private List<Expr> partitionExprs_; // indices into aggregateExprs for those that need to be materialized; // shared between this, mergeAggInfo and secondPhaseDistinctAggInfo private ArrayList<Integer> materializedAggregateSlots_ = Lists.newArrayList(); // if true, this AggregateInfo is the first phase of a 2-phase DISTINCT computation private boolean isDistinctAgg = false; // If true, the sql has MultiDistinct private boolean isMultiDistinct_; // the multi distinct's begin pos and end pos in groupby exprs private ArrayList<Integer> firstIdx_ = Lists.newArrayList(); private ArrayList<Integer> lastIdx_ = Lists.newArrayList(); // C'tor creates copies of groupingExprs and aggExprs. private AggregateInfo(ArrayList<Expr> groupingExprs, ArrayList<FunctionCallExpr> aggExprs, AggPhase aggPhase) { this(groupingExprs, aggExprs, aggPhase, false); } private AggregateInfo(ArrayList<Expr> groupingExprs, ArrayList<FunctionCallExpr> aggExprs, AggPhase aggPhase, boolean isMultiDistinct) { super(groupingExprs, aggExprs); aggPhase_ = aggPhase; isMultiDistinct_ = isMultiDistinct; } /** * C'tor for cloning. */ private AggregateInfo(AggregateInfo other) { super(other); if (other.mergeAggInfo_ != null) { mergeAggInfo_ = other.mergeAggInfo_.clone(); } if (other.secondPhaseDistinctAggInfo_ != null) { secondPhaseDistinctAggInfo_ = other.secondPhaseDistinctAggInfo_.clone(); } aggPhase_ = other.aggPhase_; outputTupleSmap_ = other.outputTupleSmap_.clone(); if (other.requiresIntermediateTuple()) { intermediateTupleSmap_ = other.intermediateTupleSmap_.clone(); } else { Preconditions.checkState(other.intermediateTupleDesc_ == other.outputTupleDesc_); intermediateTupleSmap_ = outputTupleSmap_; } partitionExprs_ = (other.partitionExprs_ != null) ? Expr.cloneList(other.partitionExprs_) : null; } public List<Expr> getPartitionExprs() { return partitionExprs_; } public void setPartitionExprs(List<Expr> exprs) { partitionExprs_ = exprs; } /** * Creates complete AggregateInfo for groupingExprs and aggExprs, including * aggTupleDesc and aggTupleSMap. If parameter tupleDesc != null, sets aggTupleDesc to * that instead of creating a new descriptor (after verifying that the passed-in * descriptor is correct for the given aggregation). * Also creates mergeAggInfo and secondPhaseDistinctAggInfo, if needed. * If an aggTupleDesc is created, also registers eq predicates between the * grouping exprs and their respective slots with 'analyzer'. */ static public AggregateInfo create( ArrayList<Expr> groupingExprs, ArrayList<FunctionCallExpr> aggExprs, TupleDescriptor tupleDesc, Analyzer analyzer) throws AnalysisException { Preconditions.checkState( (groupingExprs != null && !groupingExprs.isEmpty()) || (aggExprs != null && !aggExprs.isEmpty())); AggregateInfo result = new AggregateInfo(groupingExprs, aggExprs, AggPhase.FIRST); // collect agg exprs with DISTINCT clause ArrayList<FunctionCallExpr> distinctAggExprs = Lists.newArrayList(); if (aggExprs != null) { for (FunctionCallExpr aggExpr : aggExprs) { if (aggExpr.isDistinct()) { distinctAggExprs.add(aggExpr); } } } // aggregation algorithm includes two kinds:one stage aggregation, tow stage aggregation. // for case: // 1: if aggExprs don't have distinct or have multi distinct , create aggregate info for // one stage aggregation. // 2: if aggExprs have one distinct , create aggregate info for two stage aggregation boolean isMultiDistinct = result.estimateIfContainsMultiDistinct(distinctAggExprs); if (distinctAggExprs.isEmpty() || isMultiDistinct) { // It is used to map new aggr expr to old expr to help create an external // reference to the aggregation node tuple result.setIsMultiDistinct(isMultiDistinct); if (tupleDesc == null) { result.createTupleDescs(analyzer); result.createSmaps(analyzer); } else { // A tupleDesc should only be given for UNION DISTINCT. Preconditions.checkState(aggExprs == null); result.outputTupleDesc_ = tupleDesc; result.intermediateTupleDesc_ = tupleDesc; } result.createMergeAggInfo(analyzer); } else { // case 2: // we don't allow you to pass in a descriptor for distinct aggregation // (we need two descriptors) Preconditions.checkState(tupleDesc == null); result.createDistinctAggInfo(groupingExprs, distinctAggExprs, analyzer); } if (LOG.isDebugEnabled()) LOG.debug("agg info:\n{}", result.debugString()); return result; } /** * estimate if functions contains multi distinct * @param distinctAggExprs * @return */ public static boolean estimateIfContainsMultiDistinct(List<FunctionCallExpr> distinctAggExprs) throws AnalysisException { if (distinctAggExprs == null || distinctAggExprs.size() <= 0) { return false; } ArrayList<Expr> expr0Children = Lists.newArrayList(); if (distinctAggExprs.get(0).getFnName().getFunction().equalsIgnoreCase("group_concat")) { // Ignore separator parameter, otherwise the same would have to be present for all // other distinct aggregates as well. // TODO: Deal with constant exprs more generally, instead of special-casing // group_concat(). expr0Children.add(distinctAggExprs.get(0).getChild(0).ignoreImplicitCast()); } else { for (Expr expr : distinctAggExprs.get(0).getChildren()) { expr0Children.add(expr.ignoreImplicitCast()); } } boolean hasMultiDistinct = false; for (int i = 1; i < distinctAggExprs.size(); ++i) { ArrayList<Expr> exprIChildren = Lists.newArrayList(); if (distinctAggExprs.get(i).getFnName().getFunction().equalsIgnoreCase("group_concat")) { exprIChildren.add(distinctAggExprs.get(i).getChild(0).ignoreImplicitCast()); } else { for (Expr expr : distinctAggExprs.get(i).getChildren()) { exprIChildren.add(expr.ignoreImplicitCast()); } } if (!Expr.equalLists(expr0Children, exprIChildren)) { if (exprIChildren.size() > 1 || expr0Children.size() > 1) { throw new AnalysisException("The query contains multi count distinct or " + "sum distinct, each can't have multi columns."); } hasMultiDistinct = true; } } return hasMultiDistinct; } /** * Create aggregate info for select block containing aggregate exprs with * DISTINCT clause. * This creates: * - aggTupleDesc * - a complete secondPhaseDistinctAggInfo * - mergeAggInfo * * At the moment, we require that all distinct aggregate * functions be applied to the same set of exprs (ie, we can't do something * like SELECT COUNT(DISTINCT id), COUNT(DISTINCT address)). * Aggregation happens in two successive phases: * - the first phase aggregates by all grouping exprs plus all parameter exprs * of DISTINCT aggregate functions * * Example: * SELECT a, COUNT(DISTINCT b, c), MIN(d), COUNT(*) FROM T GROUP BY a * - 1st phase grouping exprs: a, b, c * - 1st phase agg exprs: MIN(d), COUNT(*) * - 2nd phase grouping exprs: a * - 2nd phase agg exprs: COUNT(*), MIN(<MIN(d) from 1st phase>), * SUM(<COUNT(*) from 1st phase>) * * TODO: expand implementation to cover the general case; this will require * a different execution strategy */ private void createDistinctAggInfo( ArrayList<Expr> origGroupingExprs, ArrayList<FunctionCallExpr> distinctAggExprs, Analyzer analyzer) throws AnalysisException { Preconditions.checkState(!distinctAggExprs.isEmpty()); // make sure that all DISTINCT params are the same; // ignore top-level implicit casts in the comparison, we might have inserted // those during analysis ArrayList<Expr> expr0Children = Lists.newArrayList(); if (distinctAggExprs.get(0).getFnName().getFunction().equalsIgnoreCase("group_concat")) { // Ignore separator parameter, otherwise the same would have to be present for all // other distinct aggregates as well. // TODO: Deal with constant exprs more generally, instead of special-casing // group_concat(). expr0Children.add(distinctAggExprs.get(0).getChild(0).ignoreImplicitCast()); } else { for (Expr expr : distinctAggExprs.get(0).getChildren()) { expr0Children.add(expr.ignoreImplicitCast()); } } this.isMultiDistinct_= estimateIfContainsMultiDistinct(distinctAggExprs); isDistinctAgg = true; // add DISTINCT parameters to grouping exprs if (!isMultiDistinct_) { groupingExprs_.addAll(expr0Children); } // remove DISTINCT aggregate functions from aggExprs aggregateExprs_.removeAll(distinctAggExprs); createTupleDescs(analyzer); createSmaps(analyzer); createMergeAggInfo(analyzer); createSecondPhaseAggInfo(origGroupingExprs, distinctAggExprs, analyzer); } public ArrayList<FunctionCallExpr> getMaterializedAggregateExprs() { ArrayList<FunctionCallExpr> result = Lists.newArrayList(); for (Integer i: materializedSlots_) { result.add(aggregateExprs_.get(i)); } return result; } public AggregateInfo getMergeAggInfo() { return mergeAggInfo_; } public boolean isMerge() { return aggPhase_.isMerge(); } public boolean isDistinctAgg() { return secondPhaseDistinctAggInfo_ != null; } public ExprSubstitutionMap getIntermediateSmap() { return intermediateTupleSmap_; } public ExprSubstitutionMap getOutputSmap() { return outputTupleSmap_; } public ExprSubstitutionMap getOutputToIntermediateSmap() { return outputToIntermediateTupleSmap_; } public boolean hasAggregateExprs() { return !aggregateExprs_.isEmpty() || (secondPhaseDistinctAggInfo_ != null && !secondPhaseDistinctAggInfo_.getAggregateExprs().isEmpty()); } public void setIsMultiDistinct(boolean value) { this.isMultiDistinct_ = value; } public boolean isMultiDistinct() { return isMultiDistinct_; } public AggregateInfo getSecondPhaseDistinctAggInfo() { return secondPhaseDistinctAggInfo_; } /** * Return the tuple id produced in the final aggregation step. */ public TupleId getResultTupleId() { if (isDistinctAgg()) return secondPhaseDistinctAggInfo_.getOutputTupleId(); return getOutputTupleId(); } /** * Append ids of all slots that are being referenced in the process * of performing the aggregate computation described by this AggregateInfo. */ public void getRefdSlots(List<SlotId> ids) { Preconditions.checkState(outputTupleDesc_ != null); if (groupingExprs_ != null) { Expr.getIds(groupingExprs_, null, ids); } Expr.getIds(aggregateExprs_, null, ids); // The backend assumes that the entire aggTupleDesc is materialized for (int i = 0; i < outputTupleDesc_.getSlots().size(); ++i) { ids.add(outputTupleDesc_.getSlots().get(i).getId()); } } /** * Substitute all the expressions (grouping expr, aggregate expr) and update our * substitution map according to the given substitution map: * - smap typically maps from tuple t1 to tuple t2 (example: the smap of an * inline view maps the virtual table ref t1 into a base table ref t2) * - our grouping and aggregate exprs need to be substituted with the given * smap so that they also reference t2 * - aggTupleSMap needs to be recomputed to map exprs based on t2 * onto our aggTupleDesc (ie, the left-hand side needs to be substituted with * smap) * - mergeAggInfo: this is not affected, because * * its grouping and aggregate exprs only reference aggTupleDesc_ * * its smap is identical to aggTupleSMap_ * - 2ndPhaseDistinctAggInfo: * * its grouping and aggregate exprs also only reference aggTupleDesc_ * and are therefore not affected * * its smap needs to be recomputed to map exprs based on t2 to its own * aggTupleDesc */ public void substitute(ExprSubstitutionMap smap, Analyzer analyzer) { groupingExprs_ = Expr.substituteList(groupingExprs_, smap, analyzer, true); if (LOG.isTraceEnabled()) { LOG.trace("AggInfo: grouping_exprs=" + Expr.debugString(groupingExprs_)); } // The smap in this case should not substitute the aggs themselves, only // their subexpressions. List<Expr> substitutedAggs = Expr.substituteList(aggregateExprs_, smap, analyzer, false); aggregateExprs_.clear(); for (Expr substitutedAgg: substitutedAggs) { aggregateExprs_.add((FunctionCallExpr) substitutedAgg); } outputTupleSmap_.substituteLhs(smap, analyzer); intermediateTupleSmap_.substituteLhs(smap, analyzer); if (secondPhaseDistinctAggInfo_ != null) { secondPhaseDistinctAggInfo_.substitute(smap, analyzer); } } /** * Create the info for an aggregation node that merges its pre-aggregated inputs: * - pre-aggregation is computed by 'this' * - tuple desc and smap are the same as that of the input (we're materializing * the same logical tuple) * - grouping exprs: slotrefs to the input's grouping slots * - aggregate exprs: aggregation of the input's aggregateExprs slots * * The returned AggregateInfo shares its descriptor and smap with the input info; * createAggTupleDesc() must not be called on it. */ private void createMergeAggInfo(Analyzer analyzer) { Preconditions.checkState(mergeAggInfo_ == null); TupleDescriptor inputDesc = intermediateTupleDesc_; // construct grouping exprs ArrayList<Expr> groupingExprs = Lists.newArrayList(); for (int i = 0; i < getGroupingExprs().size(); ++i) { groupingExprs.add(new SlotRef(inputDesc.getSlots().get(i))); } // construct agg exprs ArrayList<FunctionCallExpr> aggExprs = Lists.newArrayList(); for (int i = 0; i < getAggregateExprs().size(); ++i) { FunctionCallExpr inputExpr = getAggregateExprs().get(i); Preconditions.checkState(inputExpr.isAggregateFunction()); Expr aggExprParam = new SlotRef(inputDesc.getSlots().get(i + getGroupingExprs().size())); FunctionCallExpr aggExpr = FunctionCallExpr.createMergeAggCall( inputExpr, Lists.newArrayList(aggExprParam)); aggExpr.analyzeNoThrow(analyzer); aggExprs.add(aggExpr); } AggPhase aggPhase = (aggPhase_ == AggPhase.FIRST) ? AggPhase.FIRST_MERGE : AggPhase.SECOND_MERGE; mergeAggInfo_ = new AggregateInfo(groupingExprs, aggExprs, aggPhase, isMultiDistinct_); mergeAggInfo_.intermediateTupleDesc_ = intermediateTupleDesc_; mergeAggInfo_.outputTupleDesc_ = outputTupleDesc_; mergeAggInfo_.intermediateTupleSmap_ = intermediateTupleSmap_; mergeAggInfo_.outputTupleSmap_ = outputTupleSmap_; mergeAggInfo_.materializedSlots_ = materializedSlots_; } /** * Creates an IF function call that returns NULL if any of the slots * at indexes [firstIdx, lastIdx] return NULL. * For example, the resulting IF function would like this for 3 slots: * IF(IsNull(slot1), NULL, IF(IsNull(slot2), NULL, slot3)) * Returns null if firstIdx is greater than lastIdx. * Returns a SlotRef to the last slot if there is only one slot in range. */ private Expr createCountDistinctAggExprParam(int firstIdx, int lastIdx, ArrayList<SlotDescriptor> slots) { if (firstIdx > lastIdx) { return null; } Expr elseExpr = new SlotRef(slots.get(lastIdx)); if (firstIdx == lastIdx) { return elseExpr; } for (int i = lastIdx - 1; i >= firstIdx; --i) { ArrayList<Expr> ifArgs = Lists.newArrayList(); SlotRef slotRef = new SlotRef(slots.get(i)); // Build expr: IF(IsNull(slotRef), NULL, elseExpr) Expr isNullPred = new IsNullPredicate(slotRef, false); ifArgs.add(isNullPred); ifArgs.add(new NullLiteral()); ifArgs.add(elseExpr); elseExpr = new FunctionCallExpr("if", ifArgs); } return elseExpr; } /** * Create the info for an aggregation node that computes the second phase of * DISTINCT aggregate functions. * (Refer to createDistinctAggInfo() for an explanation of the phases.) * - 'this' is the phase 1 aggregation * - grouping exprs are those of the original query (param origGroupingExprs) * - aggregate exprs for the DISTINCT agg fns: these are aggregating the grouping * slots that were added to the original grouping slots in phase 1; * count is mapped to count(*) and sum is mapped to sum * - other aggregate exprs: same as the non-DISTINCT merge case * (count is mapped to sum, everything else stays the same) * * This call also creates the tuple descriptor and smap for the returned AggregateInfo. */ private void createSecondPhaseAggInfo( ArrayList<Expr> origGroupingExprs, ArrayList<FunctionCallExpr> distinctAggExprs, Analyzer analyzer) throws AnalysisException { Preconditions.checkState(secondPhaseDistinctAggInfo_ == null); Preconditions.checkState(!distinctAggExprs.isEmpty()); // The output of the 1st phase agg is the 1st phase intermediate. TupleDescriptor inputDesc = intermediateTupleDesc_; // construct agg exprs for original DISTINCT aggregate functions // (these aren't part of this.aggExprs) ArrayList<FunctionCallExpr> secondPhaseAggExprs = Lists.newArrayList(); int distinctExprPos = 0; for (FunctionCallExpr inputExpr : distinctAggExprs) { Preconditions.checkState(inputExpr.isAggregateFunction()); FunctionCallExpr aggExpr = null; if (!isMultiDistinct_) { if (inputExpr.getFnName().getFunction().equalsIgnoreCase(FunctionSet.COUNT)) { // COUNT(DISTINCT ...) -> // COUNT(IF(IsNull(<agg slot 1>), NULL, IF(IsNull(<agg slot 2>), NULL, ...))) // We need the nested IF to make sure that we do not count // column-value combinations if any of the distinct columns are NULL. // This behavior is consistent with MySQL. Expr ifExpr = createCountDistinctAggExprParam(origGroupingExprs.size(), origGroupingExprs.size() + inputExpr.getChildren().size() - 1, inputDesc.getSlots()); Preconditions.checkNotNull(ifExpr); ifExpr.analyzeNoThrow(analyzer); aggExpr = new FunctionCallExpr(FunctionSet.COUNT, Lists.newArrayList(ifExpr)); } else if (inputExpr.getFnName().getFunction().equals("group_concat")) { // Syntax: GROUP_CONCAT([DISTINCT] expression [, separator]) ArrayList<Expr> exprList = Lists.newArrayList(); // Add "expression" parameter. Need to get it from the inputDesc's slots so the // tuple reference is correct. exprList.add(new SlotRef(inputDesc.getSlots().get(origGroupingExprs.size()))); // Check if user provided a custom separator if (inputExpr.getChildren().size() == 2) exprList.add(inputExpr.getChild(1)); aggExpr = new FunctionCallExpr(inputExpr.getFnName(), exprList); } else { // SUM(DISTINCT <expr>) -> SUM(<last grouping slot>); // (MIN(DISTINCT ...) and MAX(DISTINCT ...) have their DISTINCT turned // off during analysis, and AVG() is changed to SUM()/COUNT()) Expr aggExprParam = new SlotRef(inputDesc.getSlots().get(origGroupingExprs.size())); aggExpr = new FunctionCallExpr(inputExpr.getFnName(), Lists.newArrayList(aggExprParam)); } } else { // multi distinct can't run here Preconditions.checkState(false); } secondPhaseAggExprs.add(aggExpr); } // map all the remaining agg fns for (int i = 0; i < aggregateExprs_.size(); ++i) { FunctionCallExpr inputExpr = aggregateExprs_.get(i); Preconditions.checkState(inputExpr.isAggregateFunction()); // we're aggregating an output slot of the 1st agg phase Expr aggExprParam = new SlotRef(inputDesc.getSlots().get(i + getGroupingExprs().size())); FunctionCallExpr aggExpr = FunctionCallExpr.createMergeAggCall( inputExpr, Lists.newArrayList(aggExprParam)); secondPhaseAggExprs.add(aggExpr); } Preconditions.checkState( secondPhaseAggExprs.size() == aggregateExprs_.size() + distinctAggExprs.size()); for (FunctionCallExpr aggExpr : secondPhaseAggExprs) { aggExpr.analyzeNoThrow(analyzer); Preconditions.checkState(aggExpr.isAggregateFunction()); } ArrayList<Expr> substGroupingExprs = Expr.substituteList(origGroupingExprs, intermediateTupleSmap_, analyzer, false); secondPhaseDistinctAggInfo_ = new AggregateInfo(substGroupingExprs, secondPhaseAggExprs, AggPhase.SECOND, isMultiDistinct_); secondPhaseDistinctAggInfo_.createTupleDescs(analyzer); secondPhaseDistinctAggInfo_.createSecondPhaseAggSMap(this, distinctAggExprs); secondPhaseDistinctAggInfo_.createMergeAggInfo(analyzer); } /** * Create smap to map original grouping and aggregate exprs onto output * of secondPhaseDistinctAggInfo. */ private void createSecondPhaseAggSMap( AggregateInfo inputAggInfo, ArrayList<FunctionCallExpr> distinctAggExprs) { outputTupleSmap_.clear(); int slotIdx = 0; ArrayList<SlotDescriptor> slotDescs = outputTupleDesc_.getSlots(); int numDistinctParams = 0; if (!isMultiDistinct_) { numDistinctParams = distinctAggExprs.get(0).getChildren().size(); // If we are counting distinct params of group_concat, we cannot include the custom // separator since it is not a distinct param. if (distinctAggExprs.get(0).getFnName().getFunction().equalsIgnoreCase("group_concat") && numDistinctParams == 2) { --numDistinctParams; } } else { for (int i = 0; i < distinctAggExprs.size(); i++) { numDistinctParams += distinctAggExprs.get(i).getChildren().size(); } } int numOrigGroupingExprs = inputAggInfo.getGroupingExprs().size() - numDistinctParams; Preconditions.checkState( slotDescs.size() == numOrigGroupingExprs + distinctAggExprs.size() + inputAggInfo.getAggregateExprs().size()); // original grouping exprs -> first m slots for (int i = 0; i < numOrigGroupingExprs; ++i, ++slotIdx) { Expr groupingExpr = inputAggInfo.getGroupingExprs().get(i); outputTupleSmap_.put( groupingExpr.clone(), new SlotRef(slotDescs.get(slotIdx))); } // distinct agg exprs -> next n slots for (int i = 0; i < distinctAggExprs.size(); ++i, ++slotIdx) { Expr aggExpr = distinctAggExprs.get(i); outputTupleSmap_.put(aggExpr.clone(), (new SlotRef(slotDescs.get(slotIdx)))); } // remaining agg exprs -> remaining slots for (int i = 0; i < inputAggInfo.getAggregateExprs().size(); ++i, ++slotIdx) { Expr aggExpr = inputAggInfo.getAggregateExprs().get(i); outputTupleSmap_.put(aggExpr.clone(), new SlotRef(slotDescs.get(slotIdx))); } } /** * Populates the output and intermediate smaps based on the output and intermediate * tuples that are assumed to be set. If an intermediate tuple is required, also * populates the output-to-intermediate smap and registers auxiliary equivalence * predicates between the grouping slots of the two tuples. */ public void createSmaps(Analyzer analyzer) { Preconditions.checkNotNull(outputTupleDesc_); Preconditions.checkNotNull(intermediateTupleDesc_); List<Expr> exprs = Lists.newArrayListWithCapacity( groupingExprs_.size() + aggregateExprs_.size()); exprs.addAll(groupingExprs_); exprs.addAll(aggregateExprs_); for (int i = 0; i < exprs.size(); ++i) { Expr expr = exprs.get(i); if (expr.isImplicitCast()) { outputTupleSmap_.put(expr.getChild(0).clone(), new SlotRef(outputTupleDesc_.getSlots().get(i))); } else { outputTupleSmap_.put(expr.clone(), new SlotRef(outputTupleDesc_.getSlots().get(i))); } if (!requiresIntermediateTuple()) continue; intermediateTupleSmap_.put(expr.clone(), new SlotRef(intermediateTupleDesc_.getSlots().get(i))); outputToIntermediateTupleSmap_.put( new SlotRef(outputTupleDesc_.getSlots().get(i)), new SlotRef(intermediateTupleDesc_.getSlots().get(i))); if (i < groupingExprs_.size()) { analyzer.createAuxEquivPredicate( new SlotRef(outputTupleDesc_.getSlots().get(i)), new SlotRef(intermediateTupleDesc_.getSlots().get(i))); } } if (!requiresIntermediateTuple()) intermediateTupleSmap_ = outputTupleSmap_; if (LOG.isTraceEnabled()) { LOG.trace("output smap=" + outputTupleSmap_.debugString()); LOG.trace("intermediate smap=" + intermediateTupleSmap_.debugString()); } } /** * Changing type of slot ref which is the same as the type of slot desc. * Putting this logic in here is helpless. * If Doris could analyze mv column in the future, please move this logic before reanalyze. * <p> * - The parameters of the sum function may involve the columns of a materialized view. * - The type of this column may happen to be inconsistent with the column type of the base table. * - In order to ensure the correctness of the result, * the parameter type needs to be changed to the type of the materialized view column * to ensure the correctness of the result. * - Currently only the sum function will involve this problem. */ public void updateTypeOfAggregateExprs() { for (FunctionCallExpr functionCallExpr : aggregateExprs_) { if (!functionCallExpr.getFnName().getFunction().equalsIgnoreCase("sum")) { continue; } List<SlotRef> slots = new ArrayList<>(); functionCallExpr.collect(SlotRef.class, slots); if (slots.size() != 1) { continue; } SlotRef slotRef = slots.get(0); if (slotRef.getDesc() == null) { continue; } if (slotRef.getType() != slotRef.getDesc().getType()) { slotRef.setType(slotRef.getDesc().getType()); } } } /** * Mark slots required for this aggregation as materialized: * - all grouping output slots as well as grouping exprs * - for non-distinct aggregation: the aggregate exprs of materialized aggregate slots; * this assumes that the output slots corresponding to aggregate exprs have already * been marked by the consumer of this select block * - for distinct aggregation, we mark all aggregate output slots in order to keep * things simple * Also computes materializedAggregateExprs. * This call must be idempotent because it may be called more than once for Union stmt. */ @Override public void materializeRequiredSlots(Analyzer analyzer, ExprSubstitutionMap smap) { for (int i = 0; i < groupingExprs_.size(); ++i) { outputTupleDesc_.getSlots().get(i).setIsMaterialized(true); intermediateTupleDesc_.getSlots().get(i).setIsMaterialized(true); } // collect input exprs: grouping exprs plus aggregate exprs that need to be // materialized materializedSlots_.clear(); List<Expr> exprs = Lists.newArrayList(); exprs.addAll(groupingExprs_); int aggregateExprsSize = aggregateExprs_.size(); int groupExprsSize = groupingExprs_.size(); boolean isDistinctAgg = isDistinctAgg(); for (int i = 0; i < aggregateExprsSize; ++i) { FunctionCallExpr functionCallExpr = aggregateExprs_.get(i); SlotDescriptor slotDesc = outputTupleDesc_.getSlots().get(groupExprsSize + i); SlotDescriptor intermediateSlotDesc = intermediateTupleDesc_.getSlots().get(groupExprsSize + i); if (isDistinctAgg || isMultiDistinct_) { slotDesc.setIsMaterialized(true); intermediateSlotDesc.setIsMaterialized(true); } if (!slotDesc.isMaterialized()) continue; intermediateSlotDesc.setIsMaterialized(true); exprs.add(functionCallExpr); materializedSlots_.add(i); } List<Expr> resolvedExprs = Expr.substituteList(exprs, smap, analyzer, false); analyzer.materializeSlots(resolvedExprs); if (isDistinctAgg()) { secondPhaseDistinctAggInfo_.materializeRequiredSlots(analyzer, null); } } /** * Returns DataPartition derived from grouping exprs. * Returns unpartitioned spec if no grouping. * TODO: this won't work when we start supporting range partitions, * because we could derive both hash and order-based partitions */ public DataPartition getPartition() { if (groupingExprs_.isEmpty()) { return DataPartition.UNPARTITIONED; } else { return new DataPartition(TPartitionType.HASH_PARTITIONED, groupingExprs_); } } public String debugString() { StringBuilder out = new StringBuilder(super.debugString()); out.append(MoreObjects.toStringHelper(this) .add("phase", aggPhase_) .add("intermediate_smap", intermediateTupleSmap_.debugString()) .add("output_smap", outputTupleSmap_.debugString()) .toString()); if (mergeAggInfo_ != this && mergeAggInfo_ != null) { out.append("\nmergeAggInfo:\n" + mergeAggInfo_.debugString()); } if (secondPhaseDistinctAggInfo_ != null) { out.append("\nsecondPhaseDistinctAggInfo:\n" + secondPhaseDistinctAggInfo_.debugString()); } return out.toString(); } @Override protected String tupleDebugName() { return "agg-tuple"; } @Override public AggregateInfo clone() { return new AggregateInfo(this); } public List<Expr> getInputPartitionExprs() { return partitionExprs_ != null ? partitionExprs_ : groupingExprs_; } }
3e14d92c4b60070dc0222d3a62283bbd6144d835
3,946
java
Java
app/src/main/java/jxpl/scnu/curb/data/local/PersistenceContract.java
Dawnman/Curb
b2f03a4e8f2aeafad465c4219a222506fcc8ee3a
[ "Apache-2.0" ]
3
2017-10-16T07:50:53.000Z
2018-03-26T14:51:24.000Z
app/src/main/java/jxpl/scnu/curb/data/local/PersistenceContract.java
Dawnman/Curb
b2f03a4e8f2aeafad465c4219a222506fcc8ee3a
[ "Apache-2.0" ]
1
2018-04-21T01:26:39.000Z
2018-04-21T01:26:39.000Z
app/src/main/java/jxpl/scnu/curb/data/local/PersistenceContract.java
Dawnman/Curb
b2f03a4e8f2aeafad465c4219a222506fcc8ee3a
[ "Apache-2.0" ]
2
2018-03-24T05:10:13.000Z
2018-03-24T11:19:38.000Z
42.430108
71
0.707805
8,836
package jxpl.scnu.curb.data.local; import android.provider.BaseColumns; /** * @author iri-jwj * @version 2 * update 3/25 * 更新了information的表结构 * update 3/27 * 新增了scholat的数据表 */ final class PersistenceContract { private PersistenceContract() { } static abstract class informationEntry implements BaseColumns { static final String COLUMN_NAME_ID = "id"; static final String TABLE_NAME = "information"; static final String COLUMN_NAME_TITLE = "title"; //static final String COLUMN_NAME_DATE = "datetime"; static final String COLUMN_NAME_CONTENT = "content"; static final String COLUMN_NAME_BELONG = "belong"; static final String COLUMN_NAME_CREATETIME = "create_time"; static final String COLUMN_NAME_TIME = "time"; static final String COLUMN_NAME_ADDRESS = "address"; //static final String COLUMN_NAME_CONTENT_URL = "contentUrl"; } static abstract class ScholatEntry implements BaseColumns { static final String TABLE_NAME = "scholatHomework"; static final String COLUMN_NAME_ID = "id"; static final String COLUMN_NAME_TITLE = "title"; static final String COLUMN_NAME_CONTENT = "content"; static final String COLMN_NAME_ENDTIME = "endtime"; static final String COLUMN_NAME_CREATETIME = "createtime"; } static abstract class AccountEntry implements BaseColumns { static final String COLUMN_NAME_ID = "id"; static final String TABLE_NAME = "accountManage"; static final String COLUMN_NAME_ACCOUNT = "account"; static final String COLUMN_NAME_PASSWORD = "password"; static final String COLUMN_NAME_LEVEL = "level"; } static abstract class SDSummary implements BaseColumns { static final String TABLE_NAME = "SmallDataSummary"; static final String COLUMN_NAME_ID = "id"; static final String COLUMN_NAME_TITLE = "title"; static final String COLUMN_NAME_DESCRIPTION = "description"; static final String COLUMN_NAME_IMG = "img_url"; static final String COLUMN_NAME_CREATE_TIME = "create_time"; static final String COLUMN_NAME_CREATOR = "creator"; static final String COLUMN_NAME_HAVEFINISHED = "have_finished"; } static abstract class SDDetail implements BaseColumns { static final String TABLE_NAME = "SmallDataDetail"; static final String COLUMN_NAME_SUMMARYID = "summary_id"; static final String COLUMN_NAME_NUM = "question_num"; static final String COLUMN_NAME_QUESTION = "question"; static final String COLUMN_NAME_OPTION1 = "option1"; static final String COLUMN_NAME_OPTION2 = "option2"; } static abstract class SDAnswer implements BaseColumns { static final String TABLE_NAME = "SmallDataAnswer"; static final String COLUMN_NAME_NUM = "question_num"; static final String COLUMN_NAME_SUMMARYID = "summary_id"; static final String COLUMN_NAME_ANSWER = "answer"; } static abstract class SDSummaryCreate implements BaseColumns { static final String TABLE_NAME = "SmallDataSummaryCreated"; static final String COLUMN_NAME_ID = "id"; static final String COLUMN_NAME_TITLE = "title"; static final String COLUMN_NAME_IMGURL = "img_url"; static final String COLUMN_NAME_DESCRIPTION = "description"; static final String COLUMN_NAME_CREATE_TIME = "create_time"; } static abstract class SDDetailCreate implements BaseColumns { static final String TABLE_NAME = "SmallDataDetailCreated"; static final String COLUMN_NAME_SUMMARYID = "summary_id"; static final String COLUMN_NAME_NUM = "question_num"; static final String COLUMN_NAME_QUESTION = "question"; static final String COLUMN_NAME_OPTION1 = "option1"; static final String COLUMN_NAME_OPTION2 = "option2"; } }