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
sequence
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
sequence
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
sequence
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
9244a183b172885782366f419fbb78f8d2fb3880
1,054
java
Java
src/main/java/com/sallyf/sallyf/JTwig/JTwigResponseTransformer.java
sallyf/sallyf
d3d3694d8eabd1eb4c48afac334c09c8ebef1f88
[ "MIT" ]
2
2018-01-15T08:08:41.000Z
2021-08-31T19:05:48.000Z
src/main/java/com/sallyf/sallyf/JTwig/JTwigResponseTransformer.java
sallyf/sallyf
d3d3694d8eabd1eb4c48afac334c09c8ebef1f88
[ "MIT" ]
15
2018-01-03T12:01:26.000Z
2018-03-10T14:31:55.000Z
src/main/java/com/sallyf/sallyf/JTwig/JTwigResponseTransformer.java
raphaelvigee/Sally
d3d3694d8eabd1eb4c48afac334c09c8ebef1f88
[ "MIT" ]
1
2021-09-02T10:58:08.000Z
2021-09-02T10:58:08.000Z
27.736842
120
0.721063
1,003,079
package com.sallyf.sallyf.JTwig; import com.sallyf.sallyf.Router.ResponseTransformerInterface; import com.sallyf.sallyf.Server.RuntimeBag; import com.sallyf.sallyf.Server.RuntimeBagContext; import org.jtwig.JtwigModel; import org.jtwig.JtwigTemplate; public class JTwigResponseTransformer implements ResponseTransformerInterface<JTwigResponse, String> { private JTwig jtwig; public JTwigResponseTransformer(JTwig jtwig) { this.jtwig = jtwig; } @Override public boolean supports(Object response) { return response instanceof JTwigResponse; } @Override public String transform(JTwigResponse response) { RuntimeBag runtimeBag = RuntimeBagContext.get(); JtwigTemplate jtwigTemplate = JtwigTemplate.classpathTemplate(response.getTemplate(), jtwig.getConfiguration()); JtwigModel model = JtwigModel.newModel(response.getData()) .with("_", runtimeBag) .with("runtimeBag", runtimeBag); return jtwigTemplate.render(model); } }
9244a3000effc12c104e9e3f7047099647562987
1,410
java
Java
app/models/thing/ThingDrop.java
xiaoji-wang/jianghu-manager
cc6410005e58bbd48d8d7360633c35ba0f78c434
[ "Apache-2.0" ]
null
null
null
app/models/thing/ThingDrop.java
xiaoji-wang/jianghu-manager
cc6410005e58bbd48d8d7360633c35ba0f78c434
[ "Apache-2.0" ]
null
null
null
app/models/thing/ThingDrop.java
xiaoji-wang/jianghu-manager
cc6410005e58bbd48d8d7360633c35ba0f78c434
[ "Apache-2.0" ]
null
null
null
19.859155
55
0.621277
1,003,080
package models.thing; import models.character.Monster; import models.character.Npc; import javax.persistence.*; import java.math.BigDecimal; /** * Created by wxji on 2017-09-30. */ @Entity @Table(name = "thing_drop") public class ThingDrop { private Long id; private Npc npc; private Monster monster; private Thing thing; private BigDecimal dropRate; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "thing_drop_id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "npc_id") public Npc getNpc() { return npc; } public void setNpc(Npc npc) { this.npc = npc; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "monster_id") public Monster getMonster() { return monster; } public void setMonster(Monster monster) { this.monster = monster; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "thing_id") public Thing getThing() { return thing; } public void setThing(Thing thing) { this.thing = thing; } @Column(name = "drop_rate") public BigDecimal getDropRate() { return dropRate; } public void setDropRate(BigDecimal dropRate) { this.dropRate = dropRate; } }
9244a46320fc2627af1c8ee0cd7d676474eaf1f4
3,957
java
Java
base/config/src/test/java/org/artifactory/util/FilesTest.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
3
2016-01-21T11:49:08.000Z
2018-12-11T21:02:11.000Z
base/config/src/test/java/org/artifactory/util/FilesTest.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
null
null
null
base/config/src/test/java/org/artifactory/util/FilesTest.java
alancnet/artifactory
7ac3ea76471a00543eaf60e82b554d8edd894c0f
[ "Apache-2.0" ]
5
2015-12-08T10:22:21.000Z
2021-06-15T16:14:00.000Z
38.794118
111
0.713167
1,003,081
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory 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 3 of the License, or * (at your option) any later version. * * Artifactory 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 Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.util; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * @author Yossi Shaul */ @Test public class FilesTest { private File baseTestDir; @BeforeMethod public void createTempDir() { baseTestDir = new File(System.getProperty("java.io.tmpdir"), "fileutilstest"); baseTestDir.mkdirs(); assertTrue(baseTestDir.exists(), "Failed to create base test dir"); } @AfterMethod public void dleteTempDir() throws IOException { org.apache.commons.io.FileUtils.deleteDirectory(baseTestDir); } public void cleanupEmptyDirectoriesNonExistentDir() { File nonExistentFile = new File("pampam123"); assertFalse(nonExistentFile.exists()); Files.cleanupEmptyDirectories(nonExistentFile); } public void cleanupEmptyDirectoriesEmptyDir() { Files.cleanupEmptyDirectories(baseTestDir); assertTrue(baseTestDir.exists(), "Method should not delete base directory"); Assert.assertEquals(baseTestDir.listFiles().length, 0, "Expected empty directory"); } public void cleanupEmptyDirectoriesDirWithEmptyNestedDirectories() { File nested1 = createNestedDirectory("org/test"); File nested2 = createNestedDirectory("org/apache"); createNestedDirectory("org/apache/empty"); Files.cleanupEmptyDirectories(baseTestDir); assertTrue(baseTestDir.exists(), "Method should not delete base directory"); assertFalse(nested1.exists() || nested2.exists(), "Nested empty directory wasn't deleted"); File[] files = baseTestDir.listFiles(); Assert.assertEquals(files.length, 0, "Expected empty directory but received: " + Arrays.asList(files)); } public void cleanupEmptyDirectoriesDirWithFiles() throws IOException { File nested1 = createNestedDirectory("org/test"); File nested2 = createNestedDirectory("org/apache"); // create empty file File file = new File(nested2, "emptyfile"); org.apache.commons.io.FileUtils.touch(file); Files.cleanupEmptyDirectories(baseTestDir); assertTrue(baseTestDir.exists(), "Method should not delete base directory"); assertFalse(nested1.exists(), "Nested empty directory wasn't deleted"); assertTrue(nested2.exists(), "Nested directory was deleted but wasn't empty"); Assert.assertEquals(nested2.listFiles().length, 1, "One file expected"); Assert.assertEquals(nested2.listFiles()[0], file, "Unexpected file found " + file); File[] files = baseTestDir.listFiles(); Assert.assertEquals(files.length, 1, "Expected 1 directory but received: " + Arrays.asList(files)); } private File createNestedDirectory(String relativePath) { File nested = new File(baseTestDir, relativePath); assertTrue(nested.mkdirs(), "Failed to create nested directory" + nested); return nested; } }
9244a7c0074d43b7bcc072b08cff5ce41b978599
941
java
Java
stickypunch-http/src/main/java/com/comandante/stickypunch/http/model/jackson/HttpObjectMapper.java
chriskearney/stickypunch
0f68376f7ae516178ca27394b259376c4de4f224
[ "MIT" ]
5
2016-11-01T15:01:37.000Z
2020-07-20T01:47:59.000Z
stickypunch-http/src/main/java/com/comandante/stickypunch/http/model/jackson/HttpObjectMapper.java
chriskearney/stickypunch
0f68376f7ae516178ca27394b259376c4de4f224
[ "MIT" ]
null
null
null
stickypunch-http/src/main/java/com/comandante/stickypunch/http/model/jackson/HttpObjectMapper.java
chriskearney/stickypunch
0f68376f7ae516178ca27394b259376c4de4f224
[ "MIT" ]
null
null
null
29.40625
92
0.74814
1,003,082
package com.comandante.stickypunch.http.model.jackson; import com.comandante.stickypunch.api.model.WebPushUser; import com.comandante.stickypunch.http.resource.jackson.LogDeserializer; import com.comandante.stickypunch.http.resource.jackson.WebPushUserSerializer; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.module.SimpleModule; public class HttpObjectMapper { private static final ObjectMapper MAPPER = new ObjectMapper(); static { SimpleModule httpModule = new SimpleModule("HttpModule", new Version(1, 0, 0, null)) .addDeserializer(WebPushLog.class, LogDeserializer.INSTANCE) .addSerializer(WebPushUser.class, WebPushUserSerializer.INSTANCE); MAPPER.registerModule(httpModule); } public static ObjectMapper getInstance() { return MAPPER; } private HttpObjectMapper() { } }
9244a8a13fd3e7f5f598f1632c2f6e779471818a
1,830
java
Java
text-serializer-gson-legacy-impl/src/main/java/net/kyori/adventure/text/serializer/gson/legacyimpl/NBTLegacyHoverEventSerializer.java
syldium/adventure
f96e97b5a1277a73106e6d72797887c92e291f53
[ "MIT" ]
3
2021-07-07T12:54:49.000Z
2022-01-17T17:39:21.000Z
text-serializer-gson-legacy-impl/src/main/java/net/kyori/adventure/text/serializer/gson/legacyimpl/NBTLegacyHoverEventSerializer.java
syldium/adventure
f96e97b5a1277a73106e6d72797887c92e291f53
[ "MIT" ]
8
2020-10-02T06:01:42.000Z
2021-02-02T05:48:04.000Z
text-serializer-gson-legacy-impl/src/main/java/net/kyori/adventure/text/serializer/gson/legacyimpl/NBTLegacyHoverEventSerializer.java
syldium/adventure
f96e97b5a1277a73106e6d72797887c92e291f53
[ "MIT" ]
null
null
null
39.782609
83
0.760109
1,003,083
/* * This file is part of adventure, licensed under the MIT License. * * Copyright (c) 2017-2021 KyoriPowered * * 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 net.kyori.adventure.text.serializer.gson.legacyimpl; import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.serializer.gson.LegacyHoverEventSerializer; import org.jetbrains.annotations.NotNull; /** * A legacy {@link HoverEvent} serializer. * * @since 4.3.0 */ public interface NBTLegacyHoverEventSerializer extends LegacyHoverEventSerializer { /** * Gets the legacy {@link HoverEvent} serializer. * * @return a legacy {@link HoverEvent} serializer * @since 4.3.0 */ static @NotNull LegacyHoverEventSerializer get() { return NBTLegacyHoverEventSerializerImpl.INSTANCE; } }
9244a8d03abb05ccb84103be5ae3651e51541ab2
23,789
java
Java
proto-google-cloud-speech-v1p1beta1/src/main/java/com/google/cloud/speech/v1p1beta1/SpeakerDiarizationConfig.java
chingor13/java-speech
3b671f3d8dc1bfceee35a1ba5c5561cbc743f39d
[ "Apache-2.0" ]
2
2019-08-25T15:16:57.000Z
2019-08-25T15:17:04.000Z
proto-google-cloud-speech-v1p1beta1/src/main/java/com/google/cloud/speech/v1p1beta1/SpeakerDiarizationConfig.java
chingor13/java-speech
3b671f3d8dc1bfceee35a1ba5c5561cbc743f39d
[ "Apache-2.0" ]
3
2019-05-22T14:12:27.000Z
2019-07-09T14:16:23.000Z
proto-google-cloud-speech-v1p1beta1/src/main/java/com/google/cloud/speech/v1p1beta1/SpeakerDiarizationConfig.java
chingor13/java-speech
3b671f3d8dc1bfceee35a1ba5c5561cbc743f39d
[ "Apache-2.0" ]
null
null
null
33.647808
108
0.700786
1,003,084
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/speech/v1p1beta1/cloud_speech.proto package com.google.cloud.speech.v1p1beta1; /** * * * <pre> * *Optional* Config to enable speaker diarization. * </pre> * * Protobuf type {@code google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig} */ public final class SpeakerDiarizationConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) SpeakerDiarizationConfigOrBuilder { private static final long serialVersionUID = 0L; // Use SpeakerDiarizationConfig.newBuilder() to construct. private SpeakerDiarizationConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SpeakerDiarizationConfig() {} @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SpeakerDiarizationConfig( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { enableSpeakerDiarization_ = input.readBool(); break; } case 16: { minSpeakerCount_ = input.readInt32(); break; } case 24: { maxSpeakerCount_ = input.readInt32(); break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1p1beta1.SpeechProto .internal_static_google_cloud_speech_v1p1beta1_SpeakerDiarizationConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1p1beta1.SpeechProto .internal_static_google_cloud_speech_v1p1beta1_SpeakerDiarizationConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig.class, com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig.Builder.class); } public static final int ENABLE_SPEAKER_DIARIZATION_FIELD_NUMBER = 1; private boolean enableSpeakerDiarization_; /** * * * <pre> * *Optional* If 'true', enables speaker detection for each recognized word in * the top alternative of the recognition result using a speaker_tag provided * in the WordInfo. * </pre> * * <code>bool enable_speaker_diarization = 1;</code> */ public boolean getEnableSpeakerDiarization() { return enableSpeakerDiarization_; } public static final int MIN_SPEAKER_COUNT_FIELD_NUMBER = 2; private int minSpeakerCount_; /** * * * <pre> * *Optional* * Minimum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 2. * </pre> * * <code>int32 min_speaker_count = 2;</code> */ public int getMinSpeakerCount() { return minSpeakerCount_; } public static final int MAX_SPEAKER_COUNT_FIELD_NUMBER = 3; private int maxSpeakerCount_; /** * * * <pre> * *Optional* * Maximum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 6. * </pre> * * <code>int32 max_speaker_count = 3;</code> */ public int getMaxSpeakerCount() { return maxSpeakerCount_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (enableSpeakerDiarization_ != false) { output.writeBool(1, enableSpeakerDiarization_); } if (minSpeakerCount_ != 0) { output.writeInt32(2, minSpeakerCount_); } if (maxSpeakerCount_ != 0) { output.writeInt32(3, maxSpeakerCount_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (enableSpeakerDiarization_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, enableSpeakerDiarization_); } if (minSpeakerCount_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, minSpeakerCount_); } if (maxSpeakerCount_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, maxSpeakerCount_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig)) { return super.equals(obj); } com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig other = (com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) obj; if (getEnableSpeakerDiarization() != other.getEnableSpeakerDiarization()) return false; if (getMinSpeakerCount() != other.getMinSpeakerCount()) return false; if (getMaxSpeakerCount() != other.getMaxSpeakerCount()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ENABLE_SPEAKER_DIARIZATION_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getEnableSpeakerDiarization()); hash = (37 * hash) + MIN_SPEAKER_COUNT_FIELD_NUMBER; hash = (53 * hash) + getMinSpeakerCount(); hash = (37 * hash) + MAX_SPEAKER_COUNT_FIELD_NUMBER; hash = (53 * hash) + getMaxSpeakerCount(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * *Optional* Config to enable speaker diarization. * </pre> * * Protobuf type {@code google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v1p1beta1.SpeechProto .internal_static_google_cloud_speech_v1p1beta1_SpeakerDiarizationConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v1p1beta1.SpeechProto .internal_static_google_cloud_speech_v1p1beta1_SpeakerDiarizationConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig.class, com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig.Builder.class); } // Construct using com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); enableSpeakerDiarization_ = false; minSpeakerCount_ = 0; maxSpeakerCount_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.speech.v1p1beta1.SpeechProto .internal_static_google_cloud_speech_v1p1beta1_SpeakerDiarizationConfig_descriptor; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig getDefaultInstanceForType() { return com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig build() { com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig buildPartial() { com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig result = new com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig(this); result.enableSpeakerDiarization_ = enableSpeakerDiarization_; result.minSpeakerCount_ = minSpeakerCount_; result.maxSpeakerCount_ = maxSpeakerCount_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) { return mergeFrom((com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig other) { if (other == com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig.getDefaultInstance()) return this; if (other.getEnableSpeakerDiarization() != false) { setEnableSpeakerDiarization(other.getEnableSpeakerDiarization()); } if (other.getMinSpeakerCount() != 0) { setMinSpeakerCount(other.getMinSpeakerCount()); } if (other.getMaxSpeakerCount() != 0) { setMaxSpeakerCount(other.getMaxSpeakerCount()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private boolean enableSpeakerDiarization_; /** * * * <pre> * *Optional* If 'true', enables speaker detection for each recognized word in * the top alternative of the recognition result using a speaker_tag provided * in the WordInfo. * </pre> * * <code>bool enable_speaker_diarization = 1;</code> */ public boolean getEnableSpeakerDiarization() { return enableSpeakerDiarization_; } /** * * * <pre> * *Optional* If 'true', enables speaker detection for each recognized word in * the top alternative of the recognition result using a speaker_tag provided * in the WordInfo. * </pre> * * <code>bool enable_speaker_diarization = 1;</code> */ public Builder setEnableSpeakerDiarization(boolean value) { enableSpeakerDiarization_ = value; onChanged(); return this; } /** * * * <pre> * *Optional* If 'true', enables speaker detection for each recognized word in * the top alternative of the recognition result using a speaker_tag provided * in the WordInfo. * </pre> * * <code>bool enable_speaker_diarization = 1;</code> */ public Builder clearEnableSpeakerDiarization() { enableSpeakerDiarization_ = false; onChanged(); return this; } private int minSpeakerCount_; /** * * * <pre> * *Optional* * Minimum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 2. * </pre> * * <code>int32 min_speaker_count = 2;</code> */ public int getMinSpeakerCount() { return minSpeakerCount_; } /** * * * <pre> * *Optional* * Minimum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 2. * </pre> * * <code>int32 min_speaker_count = 2;</code> */ public Builder setMinSpeakerCount(int value) { minSpeakerCount_ = value; onChanged(); return this; } /** * * * <pre> * *Optional* * Minimum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 2. * </pre> * * <code>int32 min_speaker_count = 2;</code> */ public Builder clearMinSpeakerCount() { minSpeakerCount_ = 0; onChanged(); return this; } private int maxSpeakerCount_; /** * * * <pre> * *Optional* * Maximum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 6. * </pre> * * <code>int32 max_speaker_count = 3;</code> */ public int getMaxSpeakerCount() { return maxSpeakerCount_; } /** * * * <pre> * *Optional* * Maximum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 6. * </pre> * * <code>int32 max_speaker_count = 3;</code> */ public Builder setMaxSpeakerCount(int value) { maxSpeakerCount_ = value; onChanged(); return this; } /** * * * <pre> * *Optional* * Maximum number of speakers in the conversation. This range gives you more * flexibility by allowing the system to automatically determine the correct * number of speakers. If not set, the default value is 6. * </pre> * * <code>int32 max_speaker_count = 3;</code> */ public Builder clearMaxSpeakerCount() { maxSpeakerCount_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig) private static final com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig(); } public static com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SpeakerDiarizationConfig> PARSER = new com.google.protobuf.AbstractParser<SpeakerDiarizationConfig>() { @java.lang.Override public SpeakerDiarizationConfig parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SpeakerDiarizationConfig(input, extensionRegistry); } }; public static com.google.protobuf.Parser<SpeakerDiarizationConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SpeakerDiarizationConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
9244a8ef523eb34a4eb921ecbd69a183ee37f43d
4,779
java
Java
activiti-core/activiti-engine/src/test/java/org/activiti/standalone/escapeclause/ProcessDefinitionQueryEscapeClauseTest.java
HurryUpWb/Activiti
a0cc6985d29695c8043b8e2413729348478b3828
[ "Apache-2.0" ]
8,599
2015-01-01T01:29:48.000Z
2022-03-30T03:23:40.000Z
activiti-core/activiti-engine/src/test/java/org/activiti/standalone/escapeclause/ProcessDefinitionQueryEscapeClauseTest.java
LoveMyOrange/Activiti
e39053d02c47cfebbece7a4978ab4dd1eaf2d620
[ "Apache-2.0" ]
2,988
2015-01-03T19:45:21.000Z
2022-03-31T04:08:38.000Z
activiti-core/activiti-engine/src/test/java/org/activiti/standalone/escapeclause/ProcessDefinitionQueryEscapeClauseTest.java
Harshit51435/Activiti
03a0e06921a9ff51c0e700a8c14770ca2c2eb49d
[ "Apache-2.0" ]
7,097
2015-01-02T06:32:21.000Z
2022-03-31T08:17:25.000Z
40.846154
127
0.731115
1,003,085
/* * Copyright 2010-2020 Alfresco Software, 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 org.activiti.standalone.escapeclause; import static org.assertj.core.api.Assertions.assertThat; import org.activiti.engine.repository.ProcessDefinitionQuery; public class ProcessDefinitionQueryEscapeClauseTest extends AbstractEscapeClauseTestCase { private String deploymentOneId; private String deploymentTwoId; @Override protected void setUp() throws Exception { deploymentOneId = repositoryService .createDeployment() .tenantId("One%") .name("one%") .category("testCategory") .addClasspathResource("org/activiti/engine/test/repository/one%.bpmn20.xml") .deploy() .getId(); deploymentTwoId = repositoryService .createDeployment() .tenantId("Two_") .name("two_") .addClasspathResource("org/activiti/engine/test/repository/two_.bpmn20.xml") .deploy() .getId(); super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); repositoryService.deleteDeployment(deploymentOneId, true); repositoryService.deleteDeployment(deploymentTwoId, true); } public void testQueryByNameLike() { ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionNameLike("%\\%%"); assertThat(query.singleResult().getName()).isEqualTo("One%"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); query = repositoryService.createProcessDefinitionQuery().processDefinitionNameLike("%\\_%"); assertThat(query.singleResult().getName()).isEqualTo("Two_"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); } public void testQueryByCategoryLike() { ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionCategoryLike("%\\_%"); assertThat(query.singleResult().getCategory()).isEqualTo("Examples_"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); } public void testQueryByKeyLike() { ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionKeyLike("%\\_%"); assertThat(query.singleResult().getKey()).isEqualTo("two_"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); } public void testQueryByResourceNameLike() { ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionResourceNameLike("%\\%%"); assertThat(query.singleResult().getResourceName()).isEqualTo("org/activiti/engine/test/repository/one%.bpmn20.xml"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); query = repositoryService.createProcessDefinitionQuery().processDefinitionResourceNameLike("%\\_%"); assertThat(query.singleResult().getResourceName()).isEqualTo("org/activiti/engine/test/repository/two_.bpmn20.xml"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); } public void testQueryByTenantIdLike() { ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("%\\%%"); assertThat(query.singleResult().getTenantId()).isEqualTo("One%"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); query = repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("%\\_%"); assertThat(query.singleResult().getTenantId()).isEqualTo("Two_"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); query = repositoryService.createProcessDefinitionQuery().latestVersion().processDefinitionTenantIdLike("%\\%%"); assertThat(query.singleResult().getTenantId()).isEqualTo("One%"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); query = repositoryService.createProcessDefinitionQuery().latestVersion().processDefinitionTenantIdLike("%\\_%"); assertThat(query.singleResult().getTenantId()).isEqualTo("Two_"); assertThat(query.list()).hasSize(1); assertThat(query.count()).isEqualTo(1); } }
9244a92ecd12dde516ac2be4f18b37426e18e1e0
9,249
java
Java
tools-preview-jodconverter/src/main/java/examples/preview/jodconverter/ConverterController.java
xieshaohu/spring-activemq-example
12cbc1ebfcbf95dee4508ffcaf8d5f57aad5930e
[ "Apache-2.0" ]
1
2020-03-22T14:51:17.000Z
2020-03-22T14:51:17.000Z
tools-preview-jodconverter/src/main/java/examples/preview/jodconverter/ConverterController.java
xieshaohu/spring-activemq-example
12cbc1ebfcbf95dee4508ffcaf8d5f57aad5930e
[ "Apache-2.0" ]
null
null
null
tools-preview-jodconverter/src/main/java/examples/preview/jodconverter/ConverterController.java
xieshaohu/spring-activemq-example
12cbc1ebfcbf95dee4508ffcaf8d5f57aad5930e
[ "Apache-2.0" ]
null
null
null
42.62212
104
0.687101
1,003,086
/* * Copyright 2004 - 2012 Mirko Nasato and contributors * 2016 - 2020 Simon Braconnier and contributors * * This file is part of JODConverter - Java OpenDocument Converter. * * 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 examples.preview.jodconverter; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.jodconverter.core.DocumentConverter; import org.jodconverter.core.document.DefaultDocumentFormatRegistry; import org.jodconverter.core.document.DocumentFormat; import org.jodconverter.core.office.OfficeException; import org.jodconverter.core.office.OfficeManager; import org.jodconverter.local.LocalConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * Controller that will process conversion requests. The mapping is the same as LibreOffice Online * (/lool/convert-to) so we can use the jodconverter-remote module to send request to this * controller. This controller does the same as LibreOffice Online, and also support custom * conversions through filters and custom load/store properties. */ @Controller @RequestMapping("/lool/convert-to") public class ConverterController { private static final Logger LOGGER = LoggerFactory.getLogger(ConverterController.class); private static final String FILTER_DATA = "FilterData"; private static final String FILTER_DATA_PREFIX_PARAM = "fd"; private static final String LOAD_PROPERTIES_PREFIX_PARAM = "l"; private static final String LOAD_FILTER_DATA_PREFIX_PARAM = LOAD_PROPERTIES_PREFIX_PARAM + FILTER_DATA_PREFIX_PARAM; private static final String STORE_PROPERTIES_PREFIX_PARAM = "s"; private static final String STORE_FILTER_DATA_PREFIX_PARAM = STORE_PROPERTIES_PREFIX_PARAM + FILTER_DATA_PREFIX_PARAM; private final OfficeManager officeManager; @Value("${browser.type}") private String browserType = "inline"; /** * Creates a new controller. * * @param officeManager The manager used to execute conversions. */ public ConverterController(final OfficeManager officeManager) { super(); this.officeManager = officeManager; } @PostMapping(produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public Object convertToUsingParam( @RequestParam("data") final MultipartFile inputFile, @RequestParam(name = "format") final String convertToFormat, @RequestParam(required = false) final Map<String, String> parameters) { LOGGER.debug("convertUsingRequestParam > Converting file to {}", convertToFormat); return convert(inputFile, convertToFormat, parameters); } @PostMapping(value = "/{format}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public Object convertToUsingPath( @RequestParam("data") final MultipartFile inputFile, @PathVariable(name = "format") final String convertToFormat, @RequestParam(required = false) final Map<String, String> parameters) { LOGGER.debug("convertUsingPathVariable > Converting file to {}", convertToFormat); return convert(inputFile, convertToFormat, parameters); } private void addFilterDataProperty( final String paramName, final Map.Entry<String, String> param, final Map<String, Object> properties) { final String name = param.getKey().substring(paramName.length()); final String value = param.getValue(); final Boolean bool = BooleanUtils.toBooleanObject(value); if (bool != null) { properties.put(name, bool); } try { final int ival = Integer.parseInt(value); properties.put(name, ival); } catch (NumberFormatException nfe) { properties.put(name, value); } } private void decodeParameters( final Map<String, String> parameters, final Map<String, Object> loadProperties, final Map<String, Object> storeProperties) { if (parameters == null || parameters.isEmpty()) { return; } final Map<String, Object> loadFilterDataProperties = new HashMap<>(); final Map<String, Object> storeFilterDataProperties = new HashMap<>(); for (final Map.Entry<String, String> param : parameters.entrySet()) { final String key = param.getKey().toLowerCase(Locale.ROOT); if (key.startsWith(LOAD_FILTER_DATA_PREFIX_PARAM)) { addFilterDataProperty(LOAD_FILTER_DATA_PREFIX_PARAM, param, loadFilterDataProperties); } else if (key.startsWith(LOAD_PROPERTIES_PREFIX_PARAM)) { addFilterDataProperty(LOAD_PROPERTIES_PREFIX_PARAM, param, loadProperties); } else if (key.startsWith(STORE_FILTER_DATA_PREFIX_PARAM)) { addFilterDataProperty(STORE_FILTER_DATA_PREFIX_PARAM, param, storeFilterDataProperties); } else if (key.startsWith(STORE_PROPERTIES_PREFIX_PARAM)) { addFilterDataProperty(STORE_PROPERTIES_PREFIX_PARAM, param, storeProperties); } } if (!loadFilterDataProperties.isEmpty()) { loadProperties.put(FILTER_DATA, loadFilterDataProperties); } if (!storeFilterDataProperties.isEmpty()) { storeProperties.put(FILTER_DATA, storeFilterDataProperties); } } private ResponseEntity<Object> convert( final MultipartFile inputFile, final String outputFormat, final Map<String, String> parameters) { if (inputFile.isEmpty()) { return ResponseEntity.badRequest().build(); } if (StringUtils.isBlank(outputFormat)) { return ResponseEntity.badRequest().build(); } // Here, we could have a dedicated service that would convert document try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { final DocumentFormat targetFormat = DefaultDocumentFormatRegistry.getFormatByExtension(outputFormat); Assert.notNull(targetFormat, "targetFormat must not be null"); // Decode the parameters to load and store properties. final Map<String, Object> loadProperties = new HashMap<>(LocalConverter.DEFAULT_LOAD_PROPERTIES); final Map<String, Object> storeProperties = new HashMap<>(); decodeParameters(parameters, loadProperties, storeProperties); // Create a converter with the properties. final DocumentConverter converter = LocalConverter.builder() .officeManager(officeManager) .loadProperties(loadProperties) .storeProperties(storeProperties) .build(); // Convert... converter.convert(inputFile.getInputStream()).to(baos).as(targetFormat).execute(); final HttpHeaders headers = new HttpHeaders(); String targetMediaType = targetFormat.getMediaType(); MediaType parseMediaType = MediaType.parseMediaType(targetMediaType); LOGGER.debug("targetMediaType: {}, parseMediaType: {}", targetFormat, parseMediaType); headers.setContentType(parseMediaType); headers.add( "Content-Disposition", browserType + "; filename=" + FilenameUtils.getBaseName(inputFile.getOriginalFilename()) + "." + targetFormat.getExtension()); return ResponseEntity.ok().headers(headers).body(baos.toByteArray()); } catch (OfficeException | IOException ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex); } } }
9244a988e09add162ca6033132a8acccd720f67d
1,190
java
Java
test-luban/src/main/java/com/luban/mapper/ZiluBeanFactoryPostprocessor.java
WeiYongqiang55/spring-framework
c8910713c859b7815cbd9c800a3333b3455247d8
[ "Apache-2.0" ]
null
null
null
test-luban/src/main/java/com/luban/mapper/ZiluBeanFactoryPostprocessor.java
WeiYongqiang55/spring-framework
c8910713c859b7815cbd9c800a3333b3455247d8
[ "Apache-2.0" ]
null
null
null
test-luban/src/main/java/com/luban/mapper/ZiluBeanFactoryPostprocessor.java
WeiYongqiang55/spring-framework
c8910713c859b7815cbd9c800a3333b3455247d8
[ "Apache-2.0" ]
2
2020-09-09T01:27:54.000Z
2021-03-08T10:47:53.000Z
42.5
117
0.841176
1,003,087
package com.luban.mapper; import com.luban.services.TestService; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.GenericBeanDefinition; //beanFactoryPostProcessor 这个方法的执行时机是在完成初始扫描,二次扫描的时候调用的 //打开这个注解之后会执行修改的操作了 //@Component public class ZiluBeanFactoryPostprocessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { // BeanDefinition beanService = beanFactory.getBeanDefinition("beanService"); GenericBeanDefinition beanServiceDefinition = (GenericBeanDefinition) beanFactory.getBeanDefinition("beanService"); // 修改beanDefinitonMap 中的数据,将BeanService 的beanDefiniton 中的对象改成了testService ,容器中将不存在beanService 的bean // 取而代之的是有了一个新的TestService的bean beanServiceDefinition.setBeanClass(TestService.class); // GenericBeanDefinition a = (GenericBeanDefinition) // beanFactory.getBeanDefinition("a"); // //打印A 的注入模型 // System.out.println("a mode="+a.getAutowireMode()); } }
9244a98cb229fd3213f9caea2e17090fbe5ef85a
1,423
java
Java
support/cas-server-support-inwebo-mfa/src/main/java/org/apereo/cas/support/inwebo/service/soap/generated/LoginSearchResponse.java
chulei926/cas
2ad43ec75016fb43fff98b37922c2daecefffeb9
[ "Apache-2.0" ]
8,772
2016-05-08T04:44:50.000Z
2022-03-31T06:02:13.000Z
support/cas-server-support-inwebo-mfa/src/main/java/org/apereo/cas/support/inwebo/service/soap/generated/LoginSearchResponse.java
chulei926/cas
2ad43ec75016fb43fff98b37922c2daecefffeb9
[ "Apache-2.0" ]
2,911
2016-05-07T23:07:52.000Z
2022-03-31T15:09:08.000Z
support/cas-server-support-inwebo-mfa/src/main/java/org/apereo/cas/support/inwebo/service/soap/generated/LoginSearchResponse.java
chulei926/cas
2ad43ec75016fb43fff98b37922c2daecefffeb9
[ "Apache-2.0" ]
3,675
2016-05-08T04:45:46.000Z
2022-03-31T09:34:54.000Z
24.118644
104
0.631764
1,003,088
// CHECKSTYLE:OFF package org.apereo.cas.support.inwebo.service.soap.generated; import javax.xml.bind.annotation.*; /** * The generated SOAP class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="loginSearchReturn" type="{http://console.inwebo.com}LoginSearchResult"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * @author Jerome LELEU * @since 6.4.0 */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "loginSearchReturn" }) @XmlRootElement(name = "loginSearchResponse") public class LoginSearchResponse { @XmlElement(required = true) protected LoginSearchResult loginSearchReturn; /** * Obtient la valeur de la propriété loginSearchReturn. * * @return * possible object is * {@link LoginSearchResult } * */ public LoginSearchResult getLoginSearchReturn() { return loginSearchReturn; } /** * Définit la valeur de la propriété loginSearchReturn. * * @param value * allowed object is * {@link LoginSearchResult } * */ public void setLoginSearchReturn(LoginSearchResult value) { this.loginSearchReturn = value; } }
9244a9f8c850843c384e042965f9141cd66a2238
3,130
java
Java
collector/src/main/java/sinc/hinc/abstraction/ResourceDriver/utils/FilesScanner.java
SINCConcept/HINC
2e94321f2f31b4deff08d08a4c128b958a469a3f
[ "Apache-2.0" ]
1
2016-05-23T04:13:52.000Z
2016-05-23T04:13:52.000Z
collector/src/main/java/sinc/hinc/abstraction/ResourceDriver/utils/FilesScanner.java
rdsea/HINC
2e94321f2f31b4deff08d08a4c128b958a469a3f
[ "Apache-2.0" ]
11
2020-07-16T03:17:28.000Z
2022-02-12T03:05:48.000Z
collector/src/main/java/sinc/hinc/abstraction/ResourceDriver/utils/FilesScanner.java
rdsea/HINC
2e94321f2f31b4deff08d08a4c128b958a469a3f
[ "Apache-2.0" ]
1
2018-04-13T07:45:28.000Z
2018-04-13T07:45:28.000Z
32.604167
95
0.6
1,003,089
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sinc.hinc.abstraction.ResourceDriver.utils; import java.io.File; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Default driver to get raw information from list of files. Needed settings: * <p> * <ul> * <li>path: the folder to scan * <li>filter: the file name pattern * </ul><p> * @author hungld */ public class FilesScanner { /** * Get the list of Text file in recursive folder - path: the base folder - * filter: the extension of the file E.g. getItems("/tmp","txt") * * @param settings path and filter * @return Map<filePath,fileContents> */ public static Map<String, String> getItems(Map<String, String> settings) { final String mainFolder = settings.get("path"); final String nameFilter = settings.get("filter"); System.out.println("Checking folder:" + mainFolder); // scan and read all file in dir recursively List<String> fileNames = new ArrayList<>(); getFileNames(fileNames, Paths.get(mainFolder)); if (nameFilter != null && !nameFilter.isEmpty()) { filterFileNames(fileNames, nameFilter); } Map<String, String> result = new HashMap<>(); System.out.println("There are " + fileNames.size() + " files in the folder to read !"); // each file contains info of single sensor/actuator for (String filePath : fileNames) { System.out.println("Reading file: " + filePath); String json; try { json = new String(Files.readAllBytes(Paths.get(filePath))); System.out.println("OK, Loaded the Json file content: \n " + json); result.put(filePath, json); } catch (IOException ex) { ex.printStackTrace(); } } return result; } static private List<String> getFileNames(List<String> fileNames, Path dir) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path path : stream) { if (path.toFile().isDirectory()) { getFileNames(fileNames, path); } else { fileNames.add(path.toAbsolutePath().toString()); } } } catch (IOException e) { e.printStackTrace(); } return fileNames; } static private void filterFileNames(List<String> fileNames, String endWith) { Iterator<String> ite = fileNames.iterator(); while (ite.hasNext()) { File f = new File(ite.next()); if (f.isDirectory() || (!f.getName().endsWith(endWith))) { ite.remove(); } } } }
9244ab5a471f24bc969228182c1f76323bd1b541
14,034
java
Java
src/main/java/com/saankaa/rapidxend/service/device/DeviceService.java
jocelindegni/rapixend
a2013b0187a397d9a0a25324394053282d561414
[ "MIT" ]
null
null
null
src/main/java/com/saankaa/rapidxend/service/device/DeviceService.java
jocelindegni/rapixend
a2013b0187a397d9a0a25324394053282d561414
[ "MIT" ]
null
null
null
src/main/java/com/saankaa/rapidxend/service/device/DeviceService.java
jocelindegni/rapixend
a2013b0187a397d9a0a25324394053282d561414
[ "MIT" ]
null
null
null
40.915452
176
0.654553
1,003,090
package com.saankaa.rapidxend.service.device; import com.saankaa.rapidxend.model.*; import com.saankaa.rapidxend.repository.IDeviceRepository; import com.saankaa.rapidxend.repository.IPeerRepository; import com.saankaa.rapidxend.service.device.Exception.*; import com.saankaa.rapidxend.service.notification.INotificationService; import com.saankaa.rapidxend.service.transfer.exception.FileTooLargeException; import dev.samstevens.totp.secret.DefaultSecretGenerator; import org.apache.tika.Tika; import org.bson.BsonBinarySubType; import org.bson.types.Binary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; @Service public class DeviceService implements IDeviceService { private final IDeviceRepository deviceRepository; private final IPeerRepository peerRepository; private final Logger LOGGER = LoggerFactory.getLogger(DeviceService.class); private final INotificationService notificationService; public DeviceService(@Autowired IDeviceRepository deviceRepository, @Autowired IPeerRepository peerRepository, @Autowired INotificationService notificationService) { this.deviceRepository = deviceRepository; this.peerRepository = peerRepository; this.notificationService = notificationService; } @Override public Device getDeviceByNameOrId(String s) throws DeviceNotFoundException { LOGGER.info("Get device by name"); if (s == null) { LOGGER.debug("Name is null"); throw new IllegalArgumentException("Name is null"); } Device device = deviceRepository.findByName(s.toLowerCase()); if (device == null) { device = deviceRepository.findById(s).orElseThrow( () -> { LOGGER.error("Device not found"); return new DeviceNotFoundException("Device not found"); } ); } return device; } /** * Check if deviceName contains valid characters * * @param deviceName device name * @return true if device name is valid */ private boolean deviceNameIsValid(String deviceName) { return Pattern.matches("^[a-z]+[0-9_]*$", deviceName); } @Override public boolean checkIfDeviceNameIsFree(String deviceName) throws IllegalArgumentException, InvalidDeviceNameException { LOGGER.info("Check if device name is valid"); LOGGER.debug("deviceName=" + deviceName); if (deviceName == null || deviceName.isEmpty()) throw new IllegalArgumentException("Device name is null"); deviceName = deviceName.toLowerCase(); if (!this.deviceNameIsValid(deviceName)) { LOGGER.error("Device name is not valid"); throw new InvalidDeviceNameException("Device name is not valid"); } return deviceRepository.findByName(deviceName) == null; } @Override public Device register(Device device) throws IllegalArgumentException, InvalidDeviceNameException { LOGGER.info("Register new device"); LOGGER.debug("" + device); if (device == null) { LOGGER.error("Device is null"); throw new IllegalArgumentException("Device is null"); } device.setName(device.getName().toLowerCase()); checkIfDeviceNameIsFree(device.getName()); device.setId(null); // To avoid modification of another device // Generate totp (Time based one time password) secret key // This secret key will be used for authenticating websocket connection and REST request device.setSecretKey(new DefaultSecretGenerator().generate()); return deviceRepository.save(device); } @Override public Device clone(String oldDeviceId, String oldDeviceSecretKey, Device newDevice) throws IllegalArgumentException, DeviceNotFoundException, BadDeviceSecretKeyException { LOGGER.info("Clone device"); LOGGER.debug("oldDeviceId=" + oldDeviceId + " oldSecretKey=" + oldDeviceSecretKey + " " + newDevice); if (oldDeviceId == null) { LOGGER.error("Old device id is null"); throw new IllegalArgumentException("Old device id must be not null"); } if (oldDeviceSecretKey == null) { LOGGER.error("Secret key is null"); throw new IllegalArgumentException("Old device secret key must be not null"); } if (newDevice == null) { LOGGER.error("New device info is null"); throw new IllegalArgumentException("newDevice object must be not null"); } Optional<Device> oldDeviceOptional = deviceRepository.findById(oldDeviceId); if (oldDeviceOptional.isEmpty()) throw new DeviceNotFoundException("old device id is not valid"); Device oldDevice = oldDeviceOptional.get(); // Verify old secret key if (!oldDevice.getSecretKey().equals(oldDeviceSecretKey)) { LOGGER.error("Old secret key is not valid"); throw new BadDeviceSecretKeyException("Old secret key is not valid"); } // Update all device info by new device oldDevice.setSecretKey(new DefaultSecretGenerator().generate()); oldDevice.setBrand(newDevice.getBrand()); oldDevice.setModel(newDevice.getModel()); return deviceRepository.save(oldDevice); } @Override public Peer peering(String requesterDeviceId, String applicantDeviceId) throws IllegalArgumentException, DeviceNotFoundException, PeerConflictException { LOGGER.info("Peering..."); LOGGER.debug("requesterDeviceId=" + requesterDeviceId + " applicantDeviceId=" + applicantDeviceId); if (requesterDeviceId == null || applicantDeviceId == null) { LOGGER.error("One of arguments is null"); throw new IllegalArgumentException("Device Ids must not be null"); } //Verify if Ids are valid Optional<Device> requesterDeviceOptional = deviceRepository.findById(requesterDeviceId); if (requesterDeviceOptional.isEmpty()) { LOGGER.error("Requester device not found"); throw new DeviceNotFoundException("Requester device not found"); } Optional<Device> applicantDeviceOptional = deviceRepository.findById(applicantDeviceId); if (applicantDeviceOptional.isEmpty()) { LOGGER.error("Applicant device not found"); throw new DeviceNotFoundException("Applicant device not found"); } Device requesterDevice = requesterDeviceOptional.get(); Device applicantDevice = applicantDeviceOptional.get(); // Check if they are all right peered Peer peer = peerRepository.findByRequesterDevice_IdAndApplicantDevice_Id(requesterDeviceId, applicantDeviceId); if (peer != null) { // Peering all right exist if (peer.isAccepted()) { LOGGER.debug("Peering all right exist"); throw new PeerConflictException("Peering all right exist"); } else { peer.setCreatedDate(new Date()); // update date return peerRepository.save(peer); } } // Check if peering exist when current requester is applicant peer = peerRepository.findByRequesterDevice_IdAndApplicantDevice_Id(applicantDeviceId, requesterDeviceId); if (peer != null) { if (!peer.isAccepted()) { peer.setAccepted(true); peerRepository.save(peer); } return peer; } peer = new Peer(); peer.setRequesterDevice(requesterDevice); peer.setApplicantDevice(applicantDevice); peer.setAccepted(false); peerRepository.save(peer); LOGGER.info("Notify peer"); Notification notification = new NotificationBuilder() .notificationType(NotificationType.PEERING_REQUEST.getValue()) .senderDeviceId(requesterDeviceId) .receiverDeviceId(applicantDeviceId).build(); notificationService.notifyDevice(notification); return peer; } @Override public List<Device> getPeerDevices(String deviceId) { if (deviceId == null) { LOGGER.error("Device id must not be null"); throw new IllegalArgumentException("Device id must not be null"); } final List<Device> devices = new ArrayList<>(); for (Peer p : peerRepository.findByRequesterDevice_IdOrApplicantDevice_Id(deviceId, deviceId)) { if (p.isAccepted()) { if (p.getApplicantDevice().getId().equals(deviceId)) devices.add(p.getRequesterDevice()); else devices.add(p.getApplicantDevice()); } } return devices; } @Override public void acceptPeering(String requesterDeviceId, String applicantDeviceId, boolean accepted) throws IllegalArgumentException, DeviceNotFoundException { LOGGER.debug("requesterDeviceId=" + requesterDeviceId + " applicantDeviceId=" + applicantDeviceId); if (requesterDeviceId == null || applicantDeviceId == null) { LOGGER.error("One of arguments is null"); throw new IllegalArgumentException("Device Ids must not be null"); } Peer peer = peerRepository.findByRequesterDevice_IdAndApplicantDevice_Id(requesterDeviceId, applicantDeviceId); if (peer == null) { LOGGER.error("Requester device id or applicant device id is not valid"); throw new DeviceNotFoundException("Requester device id or applicant device id is not valid"); } if (accepted) { peer.setAccepted(true); peerRepository.save(peer); } else { peerRepository.delete(peer); } // Notify peer Notification notification = new NotificationBuilder() .notificationType(accepted ? NotificationType.PEERING_ACCEPTED.getValue() : NotificationType.PEERING_DENIED.getValue()) .senderDeviceId(applicantDeviceId).receiverDeviceId(requesterDeviceId).build(); notificationService.notifyDevice(notification); } @Override public void dissociate(String deviceId, String peerDeviceId) { if (deviceId == null) { LOGGER.debug("Device id must not be null"); throw new IllegalArgumentException("Device id must not be null"); } if (peerDeviceId == null) { LOGGER.debug("Peer device id must be not null"); throw new IllegalArgumentException("Peer device id must not be null"); } Peer peer = peerRepository.findByRequesterDevice_IdAndApplicantDevice_Id(deviceId, peerDeviceId); if (peer != null) { peerRepository.delete(peer); Notification notification = new NotificationBuilder() .notificationType(NotificationType.DISSOCIATED.getValue()) .senderDeviceId(deviceId).receiverDeviceId(peerDeviceId).build(); notificationService.notifyDevice(notification); return; } peer = peerRepository.findByRequesterDevice_IdAndApplicantDevice_Id(peerDeviceId, deviceId); if (peer != null) { peerRepository.delete(peer); Notification notification = new NotificationBuilder() .notificationType(NotificationType.DISSOCIATED.getValue()) .receiverDeviceId(peerDeviceId) .senderDeviceId(deviceId).build(); notificationService.notifyDevice(notification); } } @Override public void updatePhoto(String deviceId, MultipartFile multipartFile) throws FileTooLargeException, InvalidFileType, DeviceNotFoundException, IOException { if (deviceId == null) { LOGGER.error("Device id is required"); throw new IllegalArgumentException("Device id is required"); } if (multipartFile == null) { LOGGER.error("File is required"); throw new IllegalArgumentException("File is required"); } Device device = deviceRepository.findById(deviceId).orElseThrow(() -> { LOGGER.error("Device not found"); return new DeviceNotFoundException("Device not found"); }); LOGGER.info("Checking file type"); String mimetype = new Tika().detect(multipartFile.getBytes()); if (!mimetype.contains("image/")) { LOGGER.error("Invalid file type. File type must be an image"); throw new InvalidFileType("Invalid file type. File type must be an image"); } LOGGER.info("Checking file size..."); if (multipartFile.getBytes().length > 1024 * 1024) { LOGGER.error("File is too large (>1Mio)"); throw new FileTooLargeException("File is too large (>1Mio)"); } device.setPhoto( new Binary(BsonBinarySubType.BINARY, multipartFile.getBytes()) ); deviceRepository.save(device); } @Override public byte[] getPhoto(String deviceId) throws DeviceNotFoundException { if (deviceId == null) { LOGGER.error("Device id is required"); throw new IllegalArgumentException("Device id is required"); } Device device = deviceRepository.findById(deviceId).orElseThrow(() -> { LOGGER.error("Device not found"); return new DeviceNotFoundException("Device not found"); }); return device.getPhoto().getData(); } }
9244ab95144484d4bced106f6a305f3d13c59e33
15,662
java
Java
hibiscus/src/test/java/com/github/i49/hibiscus/validation/StringValidationTest.java
i49/Hibiscus
57243818260f62faa77bbb09be60e43bd2ba7cc2
[ "Apache-2.0" ]
2
2016-11-03T14:40:53.000Z
2016-11-08T12:57:14.000Z
hibiscus/src/test/java/com/github/i49/hibiscus/validation/StringValidationTest.java
i49/Hibiscus
57243818260f62faa77bbb09be60e43bd2ba7cc2
[ "Apache-2.0" ]
null
null
null
hibiscus/src/test/java/com/github/i49/hibiscus/validation/StringValidationTest.java
i49/Hibiscus
57243818260f62faa77bbb09be60e43bd2ba7cc2
[ "Apache-2.0" ]
null
null
null
32.834382
96
0.693462
1,003,091
package com.github.i49.hibiscus.validation; import static com.github.i49.hibiscus.schema.SchemaComponents.*; import static org.junit.Assert.*; import java.io.StringReader; import java.util.Set; import javax.json.JsonString; import org.junit.Before; import org.junit.Test; import com.github.i49.hibiscus.common.TypeId; import com.github.i49.hibiscus.problems.AssertionFailureProblem; import com.github.i49.hibiscus.problems.StringLengthProblem; import com.github.i49.hibiscus.problems.StringPatternProblem; import com.github.i49.hibiscus.problems.StringTooLongProblem; import com.github.i49.hibiscus.problems.StringTooShortProblem; import com.github.i49.hibiscus.problems.TypeMismatchProblem; import com.github.i49.hibiscus.problems.NoSuchEnumeratorProblem; import com.github.i49.hibiscus.schema.Schema; import static com.github.i49.hibiscus.validation.CustomAssertions.*; public class StringValidationTest { /** * Tests of various kinds of values. */ public static class StringValueTest { @Test public void emptyString() { String json = "[\"\"]"; Schema schema = schema(array(string())); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void oneLetter() { String json = "[\"a\"]"; Schema schema = schema(array(string())); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void multipleLetters() { String json = "[\"abc\"]"; Schema schema = schema(array(string())); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } } public static class TypeMismatchTest { @Test public void notStringButInteger() { String json = "[123]"; Schema schema = schema(array(string())); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof TypeMismatchProblem); TypeMismatchProblem p = (TypeMismatchProblem)result.getProblems().get(0); assertEquals(TypeId.INTEGER, p.getActualType()); assertNotNull(p.getDescription()); } } public static class EnumerationTest { @Test public void notExistInNone() { String json = "[\"Spring\"]"; Schema schema = schema(array(string().enumeration())); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof NoSuchEnumeratorProblem); NoSuchEnumeratorProblem p = (NoSuchEnumeratorProblem)result.getProblems().get(0); assertEquals("\"Spring\"", p.getCauseValue().toString()); Set<Object> expected = p.getEnumerators(); assertEquals(0, expected.size()); assertNotNull(p.getDescription()); } @Test public void existInOne() { String json = "[\"Spring\"]"; Schema schema = schema(array(string().enumeration("Spring"))); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void notExistInOne() { String json = "[\"Spring\"]"; Schema schema = schema(array(string().enumeration("Summer"))); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof NoSuchEnumeratorProblem); NoSuchEnumeratorProblem p = (NoSuchEnumeratorProblem)result.getProblems().get(0); assertEquals("\"Spring\"", p.getCauseValue().toString()); Set<Object> expected = p.getEnumerators(); assertEquals(1, expected.size()); assertEquals("Summer", (String)expected.iterator().next()); assertNotNull(p.getDescription()); } @Test public void existInMany() { String json = "[\"Spring\"]"; Schema schema = schema(array(string().enumeration("Spring", "Summer", "Autumn", "Winter"))); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void notExistInMany() { String json = "[\"Q2\"]"; Schema schema = schema(array(string().enumeration("Spring", "Summer", "Autumn", "Winter"))); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof NoSuchEnumeratorProblem); NoSuchEnumeratorProblem p = (NoSuchEnumeratorProblem)result.getProblems().get(0); assertEquals("\"Q2\"", p.getCauseValue().toString()); Set<Object> expected = p.getEnumerators(); assertEquals(4, expected.size()); assertNotNull(p.getDescription()); } } public static class MinLengthTest { private Schema schema; @Before public void setUp() { schema = schema(array(string().minLength(3))); } @Test public void moreThanMinLength() { String json = "[\"abcd\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void minLength() { String json = "[\"abc\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void lessThanMinLength() { String json = "[\"ab\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringTooShortProblem); StringTooShortProblem p = (StringTooShortProblem)result.getProblems().get(0); assertEquals(2, p.getActualLength()); assertEquals(3, p.getLimitLength()); assertNotNull(p.getDescription()); } } public static class MaxLengthTest { private Schema schema; @Before public void setUp() { schema = schema(array(string().maxLength(3))); } @Test public void lessThanMaxLength() { String json = "[\"ab\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void maxLength() { String json = "[\"abc\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void moreThantMaxLength() { String json = "[\"abcd\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringTooLongProblem); StringTooLongProblem p = (StringTooLongProblem)result.getProblems().get(0); assertEquals(4, p.getActualLength()); assertEquals(3, p.getLimitLength()); assertNotNull(p.getDescription()); } } public static class MinAndMaxLengthTest { private Schema schema; @Before public void setUp() { schema = schema(array(string().minLength(3).maxLength(5))); } @Test public void lessThanMinLength() { String json = "[\"ab\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringTooShortProblem); StringTooShortProblem p = (StringTooShortProblem)result.getProblems().get(0); assertEquals(2, p.getActualLength()); assertEquals(3, p.getLimitLength()); assertNotNull(p.getDescription()); } @Test public void minLength() { String json = "[\"abc\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void betweenMinAndMaxLength() { String json = "[\"abcd\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void maxLength() { String json = "[\"abcde\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void moreThanMaxLength() { String json = "[\"abcdef\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringTooLongProblem); StringTooLongProblem p = (StringTooLongProblem)result.getProblems().get(0); assertEquals(6, p.getActualLength()); assertEquals(5, p.getLimitLength()); assertNotNull(p.getDescription()); } } public static class LenghTest { private Schema schema; @Before public void setUp() { schema = schema(array(string().length(3))); } @Test public void same() { String json = "[\"abc\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void lessThanExpected() { String json = "[\"ab\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringLengthProblem); StringLengthProblem p = (StringLengthProblem)result.getProblems().get(0); assertEquals(2, p.getActualLength()); assertEquals(3, p.getExpectedLength()); assertNotNull(p.getDescription()); } @Test public void moreThanExpected() { String json = "[\"abcd\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringLengthProblem); StringLengthProblem p = (StringLengthProblem)result.getProblems().get(0); assertEquals(4, p.getActualLength()); assertEquals(3, p.getExpectedLength()); assertNotNull(p.getDescription()); } } public static class ZeroLenghTest { private Schema schema; @Before public void setUp() { schema = schema(array(string().length(0))); } @Test public void same() { String json = "[\"\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void notSame() { String json = "[\"a\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringLengthProblem); StringLengthProblem p = (StringLengthProblem)result.getProblems().get(0); assertEquals(1, p.getActualLength()); assertEquals(0, p.getExpectedLength()); assertNotNull(p.getDescription()); } } public static class PatternTest { @Test public void valid() { String json = "[\"123-45-6789\"]"; Schema schema = schema(array(string().pattern("\\d{3}-?\\d{2}-?\\d{4}"))); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void invalid() { String json = "[\"9876-54-321\"]"; Schema schema = schema(array(string().pattern("\\d{3}-?\\d{2}-?\\d{4}"))); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof StringPatternProblem); StringPatternProblem p = (StringPatternProblem)result.getProblems().get(0); assertEquals("9876-54-321", p.getCauseValue().getString()); assertNotNull(p.getDescription()); } } public static class AssertionTest { private Schema schema; @Before public void setUp() { schema = schema(array(string().assertion( v->((v.getString().length() % 2) == 0), (v, l)->"Length must be a even number." ))); } @Test public void success() { String json = "[\"abcd\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertFalse(result.hasProblems()); } @Test public void failure() { String json = "[\"abc\"]"; JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof AssertionFailureProblem); AssertionFailureProblem<?> p = (AssertionFailureProblem<?>)result.getProblems().get(0); assertEquals("abc", ((JsonString)p.getCauseValue()).getString()); assertEquals("Length must be a even number.", p.getDescription()); } } }
9244acdb9a1499c0e67bf4f0218ea3a02dee66ae
1,874
java
Java
src/main/java/com/googlecode/charts4j/GridChart.java
anuradax/charts4j
64bb3014522f9227a6b0bdb02f788a26e4b28a7b
[ "MIT" ]
95
2015-02-17T13:16:20.000Z
2022-02-26T10:24:06.000Z
src/main/java/com/googlecode/charts4j/GridChart.java
anuradax/charts4j
64bb3014522f9227a6b0bdb02f788a26e4b28a7b
[ "MIT" ]
4
2016-01-04T10:47:32.000Z
2020-07-24T20:15:57.000Z
src/main/java/com/googlecode/charts4j/GridChart.java
anuradax/charts4j
64bb3014522f9227a6b0bdb02f788a26e4b28a7b
[ "MIT" ]
32
2015-02-25T21:47:05.000Z
2022-03-30T04:33:53.000Z
37.48
136
0.705977
1,003,092
/** * * The MIT License * * Copyright (c) 2011 the original author or authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.googlecode.charts4j; /** * Interface for all charts that support grids. * * @author Julien Chastang (julien.c.chastang at gmail dot com) * */ public interface GridChart { /** * Define a grid for this chart. * * @param xAxisStepSize * x step size. must be > 0. * @param yAxisStepSize * y step size. must be > 0. * @param lengthOfLineSegment * length of line segment. must be >= 0. * @param lengthOfBlankSegment * length of blank segment. must be >= 0. */ void setGrid(final double xAxisStepSize, final double yAxisStepSize, final int lengthOfLineSegment, final int lengthOfBlankSegment); }
9244ada90e5f9d45dd4a2ef90ed73c77c09b07b8
2,116
java
Java
src/net/qldarch/security/DbSessionStore.java
UQ-RCC/qldarch-backend
b6b6bad1a3f9d31c355a5796566a491e42064f9c
[ "MIT" ]
null
null
null
src/net/qldarch/security/DbSessionStore.java
UQ-RCC/qldarch-backend
b6b6bad1a3f9d31c355a5796566a491e42064f9c
[ "MIT" ]
null
null
null
src/net/qldarch/security/DbSessionStore.java
UQ-RCC/qldarch-backend
b6b6bad1a3f9d31c355a5796566a491e42064f9c
[ "MIT" ]
null
null
null
24.604651
105
0.627127
1,003,093
package net.qldarch.security; import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; import lombok.extern.slf4j.Slf4j; import net.qldarch.db.Db; import net.qldarch.db.Rsc; import net.qldarch.guice.Bind; import net.qldarch.util.M; import net.qldarch.util.RandomString; @Bind(to=SessionStore.class) @Singleton @Slf4j public class DbSessionStore implements SessionStore { @Inject private Db db; @Inject private RandomString rstr; @Inject private UserStore users; private void removeExpired() { try { db.execute("delete from session where created < now() - Interval '12 hour'"); } catch(Exception e) { log.debug("remove expired sessions failed", e); } } @Override public Session newSession(User user) { removeExpired(); try { if(user != null) { final Session session = new Session(rstr.next()); db.execute("insert into session(session, appuser) values(:session, :appuser)", M.of("session", session.getSessionId(), "appuser", user.getId())); return session; } } catch(Exception e) { log.debug("new session failed for user {}", user, e); } return null; } @Override public void expire(Session session) { removeExpired(); try { if(session != null) { db.execute("delete from session where session = :session", M.of("session", session.getSessionId())); } } catch(Exception e) { log.debug("expire session {} failed", session, e); } } @Override public User get(Session session) { removeExpired(); // TODO use session to user cache here try { if(session != null) { Map<String, Object> row = db.executeQuery("select appuser from session where session = :session", M.of("session", session.getSessionId()), Rsc::fetchFirst); if(row != null) { long userId = ((Number)row.get("appuser")).longValue(); return users.get(userId); } } } catch(Exception e) { log.debug("get session {} failed", e); } return null; } }
9244adc4eeea29d340437d0033cd9ed2730352ff
1,016
java
Java
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/client/renderer/entity/PigRenderer.java
AlgorithmLX/IndustrialLevel
727d90a9404c2967ec2d3ba8dadbd1276b1ad81f
[ "MIT" ]
null
null
null
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/client/renderer/entity/PigRenderer.java
AlgorithmLX/IndustrialLevel
727d90a9404c2967ec2d3ba8dadbd1276b1ad81f
[ "MIT" ]
1
2022-02-23T20:43:13.000Z
2022-02-23T21:04:55.000Z
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/client/renderer/entity/PigRenderer.java
AlgorithmLX/IndustrialLevel
727d90a9404c2967ec2d3ba8dadbd1276b1ad81f
[ "MIT" ]
null
null
null
44.173913
166
0.797244
1,003,094
package net.minecraft.client.renderer.entity; import net.minecraft.client.model.PigModel; import net.minecraft.client.model.geom.ModelLayers; import net.minecraft.client.renderer.entity.layers.SaddleLayer; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.animal.Pig; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class PigRenderer extends MobRenderer<Pig, PigModel<Pig>> { private static final ResourceLocation PIG_LOCATION = new ResourceLocation("textures/entity/pig/pig.png"); public PigRenderer(EntityRendererProvider.Context p_174340_) { super(p_174340_, new PigModel<>(p_174340_.bakeLayer(ModelLayers.PIG)), 0.7F); this.addLayer(new SaddleLayer<>(this, new PigModel<>(p_174340_.bakeLayer(ModelLayers.PIG_SADDLE)), new ResourceLocation("textures/entity/pig/pig_saddle.png"))); } public ResourceLocation getTextureLocation(Pig p_115697_) { return PIG_LOCATION; } }
9244ae82aeebe2ac8dee7a69721c78a25cd5b3b5
1,031
java
Java
src/main/java/com/lordjoe/lib/xml/RequiredAttributeNotFoundException.java
lordjoe/SparkHydraV2
ab039d3bd93a06da442207eed709e8ceb0ccea26
[ "Apache-2.0" ]
1
2016-03-24T09:41:37.000Z
2016-03-24T09:41:37.000Z
src/main/java/com/lordjoe/lib/xml/RequiredAttributeNotFoundException.java
lordjoe/SparkHydraV2
ab039d3bd93a06da442207eed709e8ceb0ccea26
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lordjoe/lib/xml/RequiredAttributeNotFoundException.java
lordjoe/SparkHydraV2
ab039d3bd93a06da442207eed709e8ceb0ccea26
[ "Apache-2.0" ]
1
2016-01-27T17:46:34.000Z
2016-01-27T17:46:34.000Z
32.21875
85
0.663434
1,003,095
package com.lordjoe.lib.xml; /** * An unknown property was requested * com.lordjoe.lib.xml.UnknownPropertyException */ public class RequiredAttributeNotFoundException extends RuntimeException { public RequiredAttributeNotFoundException(String needed,NameValue[] attributes) { super(buildMessage(needed, attributes)); } protected static String buildMessage(String needed,NameValue[] attributes) { StringBuilder sb = new StringBuilder(); //noinspection StringConcatenationInsideStringBufferAppend sb.append("The required attribute \'" + needed + "\' was not found \n" + "Found attributes are: "); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < attributes.length; i++) { NameValue attribute = attributes[i]; //noinspection StringConcatenationInsideStringBufferAppend sb.append(attribute.getName() + "='" + attribute.getValue() + "', "); } return sb.toString(); } }
9244af78b71bbef12f2648689320be47e2069949
1,737
java
Java
src/main/java/com/b3tuning/b3jfxmobile/plugin/ios/task/IosInstall.java
b3tuning/b3jfxmobile
c7c027813f3c4a8fcf8134ae545f2c8b3f15f95a
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/b3tuning/b3jfxmobile/plugin/ios/task/IosInstall.java
b3tuning/b3jfxmobile
c7c027813f3c4a8fcf8134ae545f2c8b3f15f95a
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/b3tuning/b3jfxmobile/plugin/ios/task/IosInstall.java
b3tuning/b3jfxmobile
c7c027813f3c4a8fcf8134ae545f2c8b3f15f95a
[ "BSD-3-Clause" ]
null
null
null
45.710526
81
0.770294
1,003,096
/* * BSD 3-Clause License * * Copyright (c) 2018, Gluon Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the copyright holder 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 HOLDER 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 com.b3tuning.b3jfxmobile.plugin.ios.task; import org.gradle.api.DefaultTask; public class IosInstall extends DefaultTask { }
9244b087c8006e08314269c64ecafa21018c5c91
2,088
java
Java
ace-dev-base/ace-common/src/main/java/com/github/wxiaoqi/security/common/util/jwt/JWTInfo.java
476096278/Spring-Cloud-Platform
80e9c1a1f2f191ae11a23c0e1843cb782b95d075
[ "Apache-2.0" ]
1,800
2020-06-07T12:55:23.000Z
2022-03-31T15:56:17.000Z
ace-dev-base/ace-common/src/main/java/com/github/wxiaoqi/security/common/util/jwt/JWTInfo.java
476096278/Spring-Cloud-Platform
80e9c1a1f2f191ae11a23c0e1843cb782b95d075
[ "Apache-2.0" ]
18
2020-06-07T11:07:12.000Z
2022-03-31T18:56:19.000Z
ace-dev-base/ace-common/src/main/java/com/github/wxiaoqi/security/common/util/jwt/JWTInfo.java
476096278/Spring-Cloud-Platform
80e9c1a1f2f191ae11a23c0e1843cb782b95d075
[ "Apache-2.0" ]
671
2020-06-07T11:10:15.000Z
2022-03-30T13:50:30.000Z
22.695652
95
0.590996
1,003,097
package com.github.wxiaoqi.security.common.util.jwt; import com.github.wxiaoqi.security.common.util.UUIDUtils; import java.io.Serializable; /** * Created by ace on 2017/9/10. */ public class JWTInfo implements Serializable,IJWTInfo { private String username; private String userId; private String name; private String tokenId; public JWTInfo(String username, String userId, String name) { this.username = username; this.userId = userId; this.name = name; this.tokenId = UUIDUtils.generateShortUuid(); } public JWTInfo(String username, String userId, String name,String tokenId) { this.username = username; this.userId = userId; this.name = name; this.tokenId = tokenId; } @Override public String getUniqueName() { return username; } public void setUsername(String username) { this.username = username; } @Override public String getId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public String getName() { return name; } @Override public String getTokenId() { return tokenId; } public void setTokenId(String tokenId) { this.tokenId = tokenId; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } JWTInfo jwtInfo = (JWTInfo) o; if (username != null ? !username.equals(jwtInfo.username) : jwtInfo.username != null) { return false; } return userId != null ? userId.equals(jwtInfo.userId) : jwtInfo.userId == null; } @Override public int hashCode() { int result = username != null ? username.hashCode() : 0; result = 31 * result + (userId != null ? userId.hashCode() : 0); return result; } }
9244b0d954355c6b87fbe551c8ff16f8b33cf361
2,446
java
Java
feign-reactor-cloud/src/test/java/reactivefeign/cloud2/PathVariableInTargetUrlTest.java
gracesleon/feign-reactive
e79df9083325a52dc609a31b8676594d8bd58588
[ "Apache-2.0" ]
428
2018-10-19T12:47:02.000Z
2022-03-29T15:36:20.000Z
feign-reactor-cloud/src/test/java/reactivefeign/cloud2/PathVariableInTargetUrlTest.java
gracesleon/feign-reactive
e79df9083325a52dc609a31b8676594d8bd58588
[ "Apache-2.0" ]
286
2018-11-14T16:41:29.000Z
2022-03-31T16:26:40.000Z
feign-reactor-cloud/src/test/java/reactivefeign/cloud2/PathVariableInTargetUrlTest.java
gracesleon/feign-reactive
e79df9083325a52dc609a31b8676594d8bd58588
[ "Apache-2.0" ]
78
2018-10-18T12:34:57.000Z
2022-03-22T07:12:59.000Z
33.506849
115
0.718316
1,003,098
package reactivefeign.cloud2; import com.github.tomakehurst.wiremock.junit.WireMockClassRule; import feign.Param; import feign.RequestLine; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer; import reactivefeign.BaseReactorTest; import reactivefeign.ReactiveFeignBuilder; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; public class PathVariableInTargetUrlTest extends BaseReactorTest { @ClassRule public static WireMockClassRule server1 = new WireMockClassRule(wireMockConfig().dynamicPort()); protected static String serviceName = "PathVariableInTargetUrlTest"; private static ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerFactory; @BeforeClass public static void setupServersList() { loadBalancerFactory = LoadBalancingReactiveHttpClientTest.loadBalancerFactory(serviceName, server1.port()); } @Before public void resetServers() { server1.resetAll(); } @Test public void shouldCorrectlyProcessPathVariableInUrl(){ String body = "Success"; mockSuccessMono(server1, body); TestMonoInterface client = this.<TestMonoInterface>cloudBuilderWithLoadBalancerEnabled() .target(TestMonoInterface.class, serviceName, "http://"+serviceName+"/mono/{id}"); StepVerifier.create(client.getMono(1).subscribeOn(testScheduler())) .expectNext(body) .verifyComplete(); } static void mockSuccessMono(WireMockClassRule server, String body) { server.stubFor(get(urlPathMatching("/mono/1")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(body))); } interface TestMonoInterface { @RequestLine("GET") Mono<String> getMono(@Param("id") long id); } protected <T> ReactiveFeignBuilder<T> cloudBuilderWithLoadBalancerEnabled() { return BuilderUtils.<T>cloudBuilder() .enableLoadBalancer(loadBalancerFactory); } }
9244b13690d353e4816e33ab1c5fd0a05a42887b
11,314
java
Java
src/main/java/mekanism/common/network/to_server/PacketDropperUse.java
ramidzkh/Mekanism
51524311c255f8bc09e4d4cd1dbeb3fbcdfd2376
[ "MIT" ]
534
2019-04-19T23:49:31.000Z
2022-03-29T12:37:06.000Z
src/main/java/mekanism/common/network/to_server/PacketDropperUse.java
ramidzkh/Mekanism
51524311c255f8bc09e4d4cd1dbeb3fbcdfd2376
[ "MIT" ]
2,015
2019-04-19T05:59:28.000Z
2022-03-29T00:54:46.000Z
src/main/java/mekanism/common/network/to_server/PacketDropperUse.java
ramidzkh/Mekanism
51524311c255f8bc09e4d4cd1dbeb3fbcdfd2376
[ "MIT" ]
309
2019-04-19T20:32:55.000Z
2022-03-31T02:16:26.000Z
48.767241
163
0.638855
1,003,099
package mekanism.common.network.to_server; import java.util.Collections; import java.util.List; import java.util.Optional; import mekanism.api.Action; import mekanism.api.Coord4D; import mekanism.api.MekanismAPI; import mekanism.api.chemical.Chemical; import mekanism.api.chemical.ChemicalStack; import mekanism.api.chemical.IChemicalHandler; import mekanism.api.chemical.IChemicalTank; import mekanism.api.chemical.IMekanismChemicalHandler; import mekanism.api.chemical.gas.IGasTank; import mekanism.api.fluid.IExtendedFluidTank; import mekanism.api.fluid.IMekanismFluidHandler; import mekanism.api.inventory.AutomationType; import mekanism.api.tier.BaseTier; import mekanism.common.block.attribute.Attribute; import mekanism.common.block.attribute.AttributeTier; import mekanism.common.capabilities.chemical.dynamic.IGasTracker; import mekanism.common.capabilities.chemical.dynamic.IInfusionTracker; import mekanism.common.capabilities.chemical.dynamic.IPigmentTracker; import mekanism.common.capabilities.chemical.dynamic.ISlurryTracker; import mekanism.common.item.ItemGaugeDropper; import mekanism.common.lib.multiblock.MultiblockData; import mekanism.common.network.IMekanismPacket; import mekanism.common.tile.base.TileEntityMekanism; import mekanism.common.tile.prefab.TileEntityMultiblock; import mekanism.common.util.ChemicalUtil; import mekanism.common.util.MekanismUtils; import mekanism.common.util.WorldUtils; import net.minecraft.block.Block; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fml.network.NetworkEvent; public class PacketDropperUse implements IMekanismPacket { private final BlockPos pos; private final DropperAction action; private final TankType tankType; private final int tankId; public PacketDropperUse(BlockPos pos, DropperAction action, TankType tankType, int tankId) { this.pos = pos; this.action = action; this.tankType = tankType; this.tankId = tankId; } @Override public void handle(NetworkEvent.Context context) { PlayerEntity player = context.getSender(); if (player == null || tankId < 0) { return; } ItemStack stack = player.inventory.getCarried(); if (!stack.isEmpty() && stack.getItem() instanceof ItemGaugeDropper) { TileEntityMekanism tile = WorldUtils.getTileEntity(TileEntityMekanism.class, player.level, pos); if (tile != null) { if (tile instanceof TileEntityMultiblock) { MultiblockData structure = ((TileEntityMultiblock<?>) tile).getMultiblock(); if (structure.isFormed()) { handleTankType(structure, player, stack, new Coord4D(structure.getBounds().getCenter(), player.level)); } } else { if (action == DropperAction.DUMP_TANK && !player.isCreative()) { //If the dropper is being used to dump the tank and the player is not in creative // check if the block the tank is in is a tiered block and if it is and it is creative // don't allow clearing the tank Block block = tile.getBlockType(); if (Attribute.has(block, AttributeTier.class) && Attribute.get(block, AttributeTier.class).getTier().getBaseTier() == BaseTier.CREATIVE) { return; } } handleTankType(tile, player, stack, tile.getTileCoord()); } } } } private <HANDLER extends IMekanismFluidHandler & IGasTracker & IInfusionTracker & IPigmentTracker & ISlurryTracker> void handleTankType(HANDLER handler, PlayerEntity player, ItemStack stack, Coord4D coord) { if (tankType == TankType.FLUID_TANK) { IExtendedFluidTank fluidTank = handler.getFluidTank(tankId, null); if (fluidTank != null) { handleFluidTank(player, stack, fluidTank); } } else { List<? extends IChemicalTank<?, ?>> tanks = Collections.emptyList(); if (tankType == TankType.GAS_TANK) { tanks = handler.getGasTanks(null); } else if (tankType == TankType.INFUSION_TANK) { tanks = handler.getInfusionTanks(null); } else if (tankType == TankType.PIGMENT_TANK) { tanks = handler.getPigmentTanks(null); } else if (tankType == TankType.SLURRY_TANK) { tanks = handler.getSlurryTanks(null); } if (tankId < tanks.size()) { handleChemicalTank(player, stack, tanks.get(tankId), coord); } } } private <CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>> void handleChemicalTank(PlayerEntity player, ItemStack stack, IChemicalTank<CHEMICAL, STACK> tank, Coord4D coord) { if (action == DropperAction.DUMP_TANK) { //Dump the tank if (!tank.isEmpty()) { if (tank instanceof IGasTank) { //If the tank is a gas tank and has radioactive substances in it make sure we properly emit the radiation to the environment MekanismAPI.getRadiationManager().dumpRadiation(coord, ((IGasTank) tank).getStack()); } tank.setEmpty(); } } else { Optional<IChemicalHandler<CHEMICAL, STACK>> cap = stack.getCapability(ChemicalUtil.getCapabilityForChemical(tank)).resolve(); if (cap.isPresent()) { IChemicalHandler<CHEMICAL, STACK> handler = cap.get(); if (handler instanceof IMekanismChemicalHandler) { IChemicalTank<CHEMICAL, STACK> itemTank = ((IMekanismChemicalHandler<CHEMICAL, STACK, ?>) handler).getChemicalTank(0, null); //It is a chemical tank if (itemTank != null) { //Validate something didn't go terribly wrong and we actually do have the tank we expect to have if (action == DropperAction.FILL_DROPPER) { //Insert chemical into dropper transferBetweenTanks(tank, itemTank, player); } else if (action == DropperAction.DRAIN_DROPPER) { //Extract chemical from dropper transferBetweenTanks(itemTank, tank, player); } } } } } } private void handleFluidTank(PlayerEntity player, ItemStack stack, IExtendedFluidTank fluidTank) { if (action == DropperAction.DUMP_TANK) { //Dump the tank fluidTank.setEmpty(); return; } Optional<IFluidHandlerItem> capability = FluidUtil.getFluidHandler(stack).resolve(); if (capability.isPresent()) { IFluidHandlerItem fluidHandlerItem = capability.get(); if (fluidHandlerItem instanceof IMekanismFluidHandler) { IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null); if (itemFluidTank != null) { if (action == DropperAction.FILL_DROPPER) { //Insert fluid into dropper transferBetweenTanks(fluidTank, itemFluidTank, player); } else if (action == DropperAction.DRAIN_DROPPER) { //Extract fluid from dropper transferBetweenTanks(itemFluidTank, fluidTank, player); } } } } } private static <CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>> void transferBetweenTanks(IChemicalTank<CHEMICAL, STACK> drainTank, IChemicalTank<CHEMICAL, STACK> fillTank, PlayerEntity player) { if (!drainTank.isEmpty() && fillTank.getNeeded() > 0) { STACK chemicalInDrainTank = drainTank.getStack(); STACK simulatedRemainder = fillTank.insert(chemicalInDrainTank, Action.SIMULATE, AutomationType.MANUAL); long remainder = simulatedRemainder.getAmount(); long amount = chemicalInDrainTank.getAmount(); if (remainder < amount) { //We are able to fit at least some of the chemical from our drain tank into the fill tank STACK extractedChemical = drainTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL); if (!extractedChemical.isEmpty()) { //If we were able to actually extract it from our tank, then insert it into the tank MekanismUtils.logMismatchedStackSize(fillTank.insert(extractedChemical, Action.EXECUTE, AutomationType.MANUAL).getAmount(), 0); ((ServerPlayerEntity) player).refreshContainer(player.containerMenu); } } } } private static void transferBetweenTanks(IExtendedFluidTank drainTank, IExtendedFluidTank fillTank, PlayerEntity player) { if (!drainTank.isEmpty() && fillTank.getNeeded() > 0) { FluidStack fluidInDrainTank = drainTank.getFluid(); FluidStack simulatedRemainder = fillTank.insert(fluidInDrainTank, Action.SIMULATE, AutomationType.MANUAL); int remainder = simulatedRemainder.getAmount(); int amount = fluidInDrainTank.getAmount(); if (remainder < amount) { //We are able to fit at least some of the fluid from our drain tank into the fill tank FluidStack extractedFluid = drainTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL); if (!extractedFluid.isEmpty()) { //If we were able to actually extract it from our tank, then insert it into the tank MekanismUtils.logMismatchedStackSize(fillTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).getAmount(), 0); ((ServerPlayerEntity) player).refreshContainer(player.containerMenu); } } } } @Override public void encode(PacketBuffer buffer) { buffer.writeBlockPos(pos); buffer.writeEnum(action); buffer.writeEnum(tankType); buffer.writeVarInt(tankId); } public static PacketDropperUse decode(PacketBuffer buffer) { return new PacketDropperUse(buffer.readBlockPos(), buffer.readEnum(DropperAction.class), buffer.readEnum(TankType.class), buffer.readVarInt()); } public enum DropperAction { FILL_DROPPER, DRAIN_DROPPER, DUMP_TANK } public enum TankType { GAS_TANK, FLUID_TANK, INFUSION_TANK, PIGMENT_TANK, SLURRY_TANK } }
9244b1a1d6cbfa13d066b93b2fcd53fec7e10001
747
java
Java
wip/protocol-model/generated/org/jetbrains/wip/protocol/page/CanOverrideDeviceMetrics.java
develar/chromedevtools
432da766271737a0a78dd16534f1dca39bb52a09
[ "BSD-3-Clause" ]
2
2016-08-24T21:52:50.000Z
2017-04-07T17:57:18.000Z
wip/protocol-model/generated/org/jetbrains/wip/protocol/page/CanOverrideDeviceMetrics.java
develar/chromedevtools
432da766271737a0a78dd16534f1dca39bb52a09
[ "BSD-3-Clause" ]
null
null
null
wip/protocol-model/generated/org/jetbrains/wip/protocol/page/CanOverrideDeviceMetrics.java
develar/chromedevtools
432da766271737a0a78dd16534f1dca39bb52a09
[ "BSD-3-Clause" ]
null
null
null
41.5
263
0.819277
1,003,100
// Generated source package org.jetbrains.wip.protocol.page; /** * Checks whether <code>setDeviceMetricsOverride</code> can be invoked. */ public final class CanOverrideDeviceMetrics extends org.jetbrains.wip.protocol.WipRequest implements org.jetbrains.jsonProtocol.RequestWithResponse<org.jetbrains.wip.protocol.page.CanOverrideDeviceMetricsResult, org.jetbrains.wip.protocol.ProtocolReponseReader> { @Override public String getMethodName() { return "Page.canOverrideDeviceMetrics"; } @Override public CanOverrideDeviceMetricsResult readResult(com.google.gson.stream.JsonReaderEx jsonReader, org.jetbrains.wip.protocol.ProtocolReponseReader reader) { return reader.readPageCanOverrideDeviceMetricsResult(jsonReader); } }
9244b2a0cf8f644a8e61884b7269fa2765601c86
967
java
Java
dao/src/test/java/life/catalogue/es/query/TermQueryTest.java
cgendreau/backend
ff8e8add1c6a936313e215d7653617a6990945e1
[ "Apache-2.0" ]
6
2020-03-14T12:25:02.000Z
2022-03-17T20:26:46.000Z
dao/src/test/java/life/catalogue/es/query/TermQueryTest.java
cgendreau/backend
ff8e8add1c6a936313e215d7653617a6990945e1
[ "Apache-2.0" ]
546
2020-03-13T10:53:07.000Z
2022-03-30T05:17:48.000Z
dao/src/test/java/life/catalogue/es/query/TermQueryTest.java
cgendreau/backend
ff8e8add1c6a936313e215d7653617a6990945e1
[ "Apache-2.0" ]
9
2020-04-17T16:02:43.000Z
2022-03-26T15:57:07.000Z
24.175
72
0.707342
1,003,101
package life.catalogue.es.query; import life.catalogue.es.EsNameUsage; import life.catalogue.es.EsReadTestBase; import java.util.List; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TermQueryTest extends EsReadTestBase { @Before public void before() { destroyAndCreateIndex(); } @Test public void test1() { EsNameUsage doc1 = new EsNameUsage(); doc1.setDatasetKey(1); EsNameUsage doc2 = new EsNameUsage(); doc2.setDatasetKey(2); EsNameUsage doc3 = new EsNameUsage(); doc3.setDatasetKey(3); EsNameUsage doc4 = new EsNameUsage(); doc4.setDatasetKey(3); EsNameUsage doc5 = new EsNameUsage(); doc5.setDatasetKey(3); EsNameUsage doc6 = new EsNameUsage(); doc6.setDatasetKey(6); indexRaw(doc1, doc2, doc3, doc4, doc5, doc6); List<EsNameUsage> result = queryRaw(new TermQuery("datasetKey", 3)); assertEquals(3, result.size()); } }
9244b2c541e0a922a5ccb2af8a7fa416c032a071
2,619
java
Java
src/main/java/com/jhbim/bimvr/system/shiro/SessionManager.java
bimvrproject/bimvrServer
caabe0073ab23a7e2d96d5b2da0c78ce13bcd041
[ "Apache-2.0" ]
1
2020-06-02T11:29:30.000Z
2020-06-02T11:29:30.000Z
src/main/java/com/jhbim/bimvr/system/shiro/SessionManager.java
bimvrproject/bimvrServer
caabe0073ab23a7e2d96d5b2da0c78ce13bcd041
[ "Apache-2.0" ]
4
2019-11-21T07:41:51.000Z
2021-09-20T20:52:44.000Z
src/main/java/com/jhbim/bimvr/system/shiro/SessionManager.java
bimvrproject/bimvrServer
caabe0073ab23a7e2d96d5b2da0c78ce13bcd041
[ "Apache-2.0" ]
null
null
null
36.375
117
0.701031
1,003,102
package com.jhbim.bimvr.system.shiro; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.session.Session; import org.apache.shiro.session.UnknownSessionException; import org.apache.shiro.session.mgt.SessionKey; import org.apache.shiro.web.servlet.ShiroHttpServletRequest; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.apache.shiro.web.session.mgt.WebSessionKey; import org.apache.shiro.web.util.WebUtils; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.Serializable; public class SessionManager extends DefaultWebSessionManager { private static final String AUTHORIZATION = "Token"; private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request"; public SessionManager() { } @Override protected Serializable getSessionId(ServletRequest request, ServletResponse response) { //获取请求头,或者请求参数中的Token String id = StringUtils.isEmpty(WebUtils.toHttp(request).getHeader(AUTHORIZATION)) ? request.getParameter(AUTHORIZATION) : WebUtils.toHttp(request).getHeader(AUTHORIZATION); // 如果请求头中有 Token 则其值为sessionId if (StringUtils.isNotEmpty(id)) { request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE); return id; } else { // 否则按默认规则从cookie取sessionId return super.getSessionId(request, response); } } /** * 获取session 优化单次请求需要多次访问redis的问题 * * @param sessionKey * @return * @throws UnknownSessionException */ @Override protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException { Serializable sessionId = getSessionId(sessionKey); ServletRequest request = null; if (sessionKey instanceof WebSessionKey) { request = ((WebSessionKey) sessionKey).getServletRequest(); } if (request != null && null != sessionId) { Object sessionObj = request.getAttribute(sessionId.toString()); if (sessionObj != null) { return (Session) sessionObj; } } Session session = super.retrieveSession(sessionKey); if (request != null && null != sessionId) { request.setAttribute(sessionId.toString(), session); } return session; } }
9244b35d7efb87aa6439ce62620a31d2aa4fc4d9
1,177
java
Java
app/src/main/java/com/github/greatwing/WebResourceResponseAdapter.java
greatwing/CacheWebview-CrossWalk
91b2e2a28a0575e66bb249eb66c2afd5927c2787
[ "MIT" ]
null
null
null
app/src/main/java/com/github/greatwing/WebResourceResponseAdapter.java
greatwing/CacheWebview-CrossWalk
91b2e2a28a0575e66bb249eb66c2afd5927c2787
[ "MIT" ]
null
null
null
app/src/main/java/com/github/greatwing/WebResourceResponseAdapter.java
greatwing/CacheWebview-CrossWalk
91b2e2a28a0575e66bb249eb66c2afd5927c2787
[ "MIT" ]
1
2021-08-14T02:35:48.000Z
2021-08-14T02:35:48.000Z
33.628571
135
0.717077
1,003,103
package com.github.greatwing; import android.os.Build; import org.xwalk.core.XWalkResourceClient; import org.xwalk.core.XWalkWebResourceResponse; import java.io.InputStream; import java.util.Map; public class WebResourceResponseAdapter { public static XWalkWebResourceResponse adapter(XWalkResourceClient client, android.webkit.WebResourceResponse webResourceResponse){ if (webResourceResponse == null){ return null; } String mimeType = webResourceResponse.getMimeType(); String encoding = webResourceResponse.getEncoding(); InputStream data = webResourceResponse.getData(); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { int statusCode = webResourceResponse.getStatusCode(); String reasonPhrase = webResourceResponse.getReasonPhrase(); Map<String, String> headers = webResourceResponse.getResponseHeaders(); return client.createXWalkWebResourceResponse(mimeType, encoding, data, statusCode, reasonPhrase, headers); } else { return client.createXWalkWebResourceResponse(mimeType, encoding, data); } } }
9244b3a93acf39718530abafbca1d77d84c551c7
13,340
java
Java
core/src/main/java/io/cucumber/core/runner/CachingGlue.java
johnsebastian-c/cucumber-jvm
a6de8d078495c194822c7b371291b1826412a63e
[ "MIT" ]
1
2020-01-19T17:17:29.000Z
2020-01-19T17:17:29.000Z
core/src/main/java/io/cucumber/core/runner/CachingGlue.java
johnsebastian-c/cucumber-jvm
a6de8d078495c194822c7b371291b1826412a63e
[ "MIT" ]
null
null
null
core/src/main/java/io/cucumber/core/runner/CachingGlue.java
johnsebastian-c/cucumber-jvm
a6de8d078495c194822c7b371291b1826412a63e
[ "MIT" ]
null
null
null
42.484076
135
0.733133
1,003,104
package io.cucumber.core.runner; import io.cucumber.core.backend.DataTableTypeDefinition; import io.cucumber.core.backend.DefaultDataTableCellTransformerDefinition; import io.cucumber.core.backend.DefaultDataTableEntryTransformerDefinition; import io.cucumber.core.backend.DefaultParameterTransformerDefinition; import io.cucumber.core.backend.DocStringTypeDefinition; import io.cucumber.core.backend.Glue; import io.cucumber.core.backend.HookDefinition; import io.cucumber.core.backend.ParameterTypeDefinition; import io.cucumber.core.backend.ScenarioScoped; import io.cucumber.core.backend.StepDefinition; import io.cucumber.core.eventbus.EventBus; import io.cucumber.core.gherkin.Step; import io.cucumber.core.stepexpression.Argument; import io.cucumber.core.stepexpression.StepTypeRegistry; import io.cucumber.cucumberexpressions.ParameterByTypeTransformer; import io.cucumber.datatable.TableCellByTypeTransformer; import io.cucumber.datatable.TableEntryByTypeTransformer; import io.cucumber.plugin.event.StepDefinedEvent; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; final class CachingGlue implements Glue { private static final Comparator<CoreHookDefinition> ASCENDING = Comparator .comparingInt(CoreHookDefinition::getOrder) .thenComparing((a, b) -> { boolean aScenarioScoped = (a instanceof ScenarioScoped); boolean bScenarioScoped = (b instanceof ScenarioScoped); return Boolean.compare(aScenarioScoped, bScenarioScoped); }); private final List<ParameterTypeDefinition> parameterTypeDefinitions = new ArrayList<>(); private final List<DataTableTypeDefinition> dataTableTypeDefinitions = new ArrayList<>(); private final List<DefaultParameterTransformerDefinition> defaultParameterTransformers = new ArrayList<>(); private final List<CoreDefaultDataTableEntryTransformerDefinition> defaultDataTableEntryTransformers = new ArrayList<>(); private final List<DefaultDataTableCellTransformerDefinition> defaultDataTableCellTransformers = new ArrayList<>(); private final List<DocStringTypeDefinition> docStringTypeDefinitions = new ArrayList<>(); private final List<CoreHookDefinition> beforeHooks = new ArrayList<>(); private final List<CoreHookDefinition> beforeStepHooks = new ArrayList<>(); private final List<StepDefinition> stepDefinitions = new ArrayList<>(); private final List<CoreHookDefinition> afterStepHooks = new ArrayList<>(); private final List<CoreHookDefinition> afterHooks = new ArrayList<>(); /* * Storing the pattern that matches the step text allows us to cache the rather slow * regex comparisons in `stepDefinitionMatches`. * This cache does not need to be cleaned. The matching pattern be will used to look * up a pickle specific step definition from `stepDefinitionsByPattern`. */ private final Map<String, String> stepPatternByStepText = new HashMap<>(); private final Map<String, CoreStepDefinition> stepDefinitionsByPattern = new TreeMap<>(); private final EventBus bus; CachingGlue(EventBus bus) { this.bus = bus; } @Override public void addStepDefinition(StepDefinition stepDefinition) { stepDefinitions.add(stepDefinition); } @Override public void addBeforeHook(HookDefinition hookDefinition) { beforeHooks.add(CoreHookDefinition.create(hookDefinition)); beforeHooks.sort(ASCENDING); } @Override public void addBeforeStepHook(HookDefinition hookDefinition) { beforeStepHooks.add(CoreHookDefinition.create(hookDefinition)); beforeStepHooks.sort(ASCENDING); } @Override public void addAfterHook(HookDefinition hookDefinition) { afterHooks.add(CoreHookDefinition.create(hookDefinition)); afterHooks.sort(ASCENDING); } @Override public void addAfterStepHook(HookDefinition hookDefinition) { afterStepHooks.add(CoreHookDefinition.create(hookDefinition)); afterStepHooks.sort(ASCENDING); } @Override public void addParameterType(ParameterTypeDefinition parameterType) { parameterTypeDefinitions.add(parameterType); } @Override public void addDataTableType(DataTableTypeDefinition dataTableType) { dataTableTypeDefinitions.add(dataTableType); } @Override public void addDefaultParameterTransformer(DefaultParameterTransformerDefinition defaultParameterTransformer) { defaultParameterTransformers.add(defaultParameterTransformer); } @Override public void addDefaultDataTableEntryTransformer(DefaultDataTableEntryTransformerDefinition defaultDataTableEntryTransformer) { defaultDataTableEntryTransformers.add(CoreDefaultDataTableEntryTransformerDefinition.create(defaultDataTableEntryTransformer)); } @Override public void addDefaultDataTableCellTransformer(DefaultDataTableCellTransformerDefinition defaultDataTableCellTransformer) { defaultDataTableCellTransformers.add(defaultDataTableCellTransformer); } @Override public void addDocStringType(DocStringTypeDefinition docStringType) { docStringTypeDefinitions.add(docStringType); } Collection<CoreHookDefinition> getBeforeHooks() { return new ArrayList<>(beforeHooks); } Collection<CoreHookDefinition> getBeforeStepHooks() { return new ArrayList<>(beforeStepHooks); } Collection<CoreHookDefinition> getAfterHooks() { List<CoreHookDefinition> hooks = new ArrayList<>(afterHooks); Collections.reverse(hooks); return hooks; } Collection<CoreHookDefinition> getAfterStepHooks() { List<CoreHookDefinition> hooks = new ArrayList<>(afterStepHooks); Collections.reverse(hooks); return hooks; } Collection<ParameterTypeDefinition> getParameterTypeDefinitions() { return parameterTypeDefinitions; } Collection<DataTableTypeDefinition> getDataTableTypeDefinitions() { return dataTableTypeDefinitions; } Collection<StepDefinition> getStepDefinitions() { return stepDefinitions; } Map<String, String> getStepPatternByStepText() { return stepPatternByStepText; } Map<String, CoreStepDefinition> getStepDefinitionsByPattern() { return stepDefinitionsByPattern; } Collection<DefaultParameterTransformerDefinition> getDefaultParameterTransformers() { return defaultParameterTransformers; } Collection<CoreDefaultDataTableEntryTransformerDefinition> getDefaultDataTableEntryTransformers() { return defaultDataTableEntryTransformers; } Collection<DefaultDataTableCellTransformerDefinition> getDefaultDataTableCellTransformers() { return defaultDataTableCellTransformers; } List<DocStringTypeDefinition> getDocStringTypeDefinitions() { return docStringTypeDefinitions; } void prepareGlue(StepTypeRegistry stepTypeRegistry) throws DuplicateStepDefinitionException { parameterTypeDefinitions.forEach(ptd -> stepTypeRegistry.defineParameterType(ptd.parameterType())); dataTableTypeDefinitions.forEach(dtd -> stepTypeRegistry.defineDataTableType(dtd.dataTableType())); docStringTypeDefinitions.forEach(dtd -> stepTypeRegistry.defineDocStringType(dtd.docStringType())); if (defaultParameterTransformers.size() == 1) { DefaultParameterTransformerDefinition definition = defaultParameterTransformers.get(0); ParameterByTypeTransformer transformer = definition.parameterByTypeTransformer(); stepTypeRegistry.setDefaultParameterTransformer(transformer); } else if (defaultParameterTransformers.size() > 1) { throw new DuplicateDefaultParameterTransformers(defaultParameterTransformers); } if (defaultDataTableEntryTransformers.size() == 1) { DefaultDataTableEntryTransformerDefinition definition = defaultDataTableEntryTransformers.get(0); TableEntryByTypeTransformer transformer = definition.tableEntryByTypeTransformer(); stepTypeRegistry.setDefaultDataTableEntryTransformer(transformer); } else if (defaultDataTableEntryTransformers.size() > 1) { throw new DuplicateDefaultDataTableEntryTransformers(defaultDataTableEntryTransformers); } if (defaultDataTableCellTransformers.size() == 1) { DefaultDataTableCellTransformerDefinition definition = defaultDataTableCellTransformers.get(0); TableCellByTypeTransformer transformer = definition.tableCellByTypeTransformer(); stepTypeRegistry.setDefaultDataTableCellTransformer(transformer); } else if (defaultDataTableCellTransformers.size() > 1) { throw new DuplicateDefaultDataTableCellTransformers(defaultDataTableCellTransformers); } stepDefinitions.forEach(stepDefinition -> { CoreStepDefinition coreStepDefinition = new CoreStepDefinition(stepDefinition, stepTypeRegistry); CoreStepDefinition previous = stepDefinitionsByPattern.get(stepDefinition.getPattern()); if (previous != null) { throw new DuplicateStepDefinitionException(previous.getStepDefinition(), stepDefinition); } stepDefinitionsByPattern.put(coreStepDefinition.getPattern(), coreStepDefinition); bus.send( new StepDefinedEvent( bus.getInstant(), new io.cucumber.plugin.event.StepDefinition( stepDefinition.getLocation(), stepDefinition.getPattern() ) ) ); }); } PickleStepDefinitionMatch stepDefinitionMatch(URI uri, Step step) throws AmbiguousStepDefinitionsException { PickleStepDefinitionMatch cachedMatch = cachedStepDefinitionMatch(uri, step); if (cachedMatch != null) { return cachedMatch; } return findStepDefinitionMatch(uri, step); } private PickleStepDefinitionMatch cachedStepDefinitionMatch(URI uri, Step step) { String stepDefinitionPattern = stepPatternByStepText.get(step.getText()); if (stepDefinitionPattern == null) { return null; } CoreStepDefinition coreStepDefinition = stepDefinitionsByPattern.get(stepDefinitionPattern); if (coreStepDefinition == null) { return null; } // Step definition arguments consists of parameters included in the step text and // gherkin step arguments (doc string and data table) which are not included in // the step text. As such the step definition arguments can not be cached and // must be recreated each time. List<Argument> arguments = coreStepDefinition.matchedArguments(step); return new PickleStepDefinitionMatch(arguments, coreStepDefinition.getStepDefinition(), uri, step); } private PickleStepDefinitionMatch findStepDefinitionMatch(URI uri, Step step) throws AmbiguousStepDefinitionsException { List<PickleStepDefinitionMatch> matches = stepDefinitionMatches(uri, step); if (matches.isEmpty()) { return null; } if (matches.size() > 1) { throw new AmbiguousStepDefinitionsException(step, matches); } PickleStepDefinitionMatch match = matches.get(0); stepPatternByStepText.put(step.getText(), match.getPattern()); return match; } private List<PickleStepDefinitionMatch> stepDefinitionMatches(URI uri, Step step) { List<PickleStepDefinitionMatch> result = new ArrayList<>(); for (CoreStepDefinition coreStepDefinition : stepDefinitionsByPattern.values()) { List<Argument> arguments = coreStepDefinition.matchedArguments(step); if (arguments != null) { result.add(new PickleStepDefinitionMatch(arguments, coreStepDefinition.getStepDefinition(), uri, step)); } } return result; } void removeScenarioScopedGlue() { stepDefinitionsByPattern.clear(); removeScenarioScopedGlue(beforeHooks); removeScenarioScopedGlue(beforeStepHooks); removeScenarioScopedGlue(afterHooks); removeScenarioScopedGlue(afterStepHooks); removeScenarioScopedGlue(stepDefinitions); removeScenarioScopedGlue(dataTableTypeDefinitions); removeScenarioScopedGlue(docStringTypeDefinitions); removeScenarioScopedGlue(parameterTypeDefinitions); removeScenarioScopedGlue(defaultParameterTransformers); removeScenarioScopedGlue(defaultDataTableEntryTransformers); removeScenarioScopedGlue(defaultDataTableCellTransformers); } private void removeScenarioScopedGlue(Iterable<?> glues) { Iterator<?> glueIterator = glues.iterator(); while (glueIterator.hasNext()) { Object glue = glueIterator.next(); if (glue instanceof ScenarioScoped) { glueIterator.remove(); } } } }
9244b3ad635c9fccf80611cbb0aad566c27a5cda
18,970
java
Java
runtime/ceylon/language/serialization/PartialImpl.java
unratito/ceylon.language
18fca576ea1b900df53649e428cb6fdd42a7a17c
[ "Apache-2.0" ]
null
null
null
runtime/ceylon/language/serialization/PartialImpl.java
unratito/ceylon.language
18fca576ea1b900df53649e428cb6fdd42a7a17c
[ "Apache-2.0" ]
null
null
null
runtime/ceylon/language/serialization/PartialImpl.java
unratito/ceylon.language
18fca576ea1b900df53649e428cb6fdd42a7a17c
[ "Apache-2.0" ]
null
null
null
50.452128
165
0.62952
1,003,105
package ceylon.language.serialization; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import com.redhat.ceylon.compiler.java.Util; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel; import com.redhat.ceylon.compiler.java.runtime.metamodel.meta.ClassImpl; import com.redhat.ceylon.compiler.java.runtime.metamodel.meta.MemberClassImpl; import com.redhat.ceylon.compiler.java.runtime.model.ReifiedType; import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor; import com.redhat.ceylon.compiler.java.runtime.serialization.$Serialization$; import com.redhat.ceylon.compiler.java.runtime.serialization.Serializable; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypedReference; import ceylon.language.AssertionError; import ceylon.language.Collection; import ceylon.language.Entry; import ceylon.language.String; import ceylon.language.Tuple; import ceylon.language.impl.ElementImpl; import ceylon.language.impl.MemberImpl; import ceylon.language.impl.rethrow_; import ceylon.language.meta.declaration.ClassDeclaration; import ceylon.language.meta.declaration.ValueDeclaration; import ceylon.language.meta.model.ClassModel; @Ceylon(major = 8, minor=0) @com.redhat.ceylon.compiler.java.metadata.Class class PartialImpl extends Partial { PartialImpl(java.lang.Object id) { super(id); } private TypeDescriptor.Class getClassTypeDescriptor() { ClassModel<?, ?> classModel = getClazz(); if (classModel == null) { throw new DeserializationException("no class specified for instance with id " + getId()); } if (classModel instanceof ClassImpl) { return ((TypeDescriptor.Class)((TypeDescriptor.Class)((ReifiedType)classModel).$getType$()).getTypeArgument(0)); } else if (classModel instanceof MemberClassImpl) { return ((TypeDescriptor.Class)((TypeDescriptor.Member)((TypeDescriptor.Class)((ReifiedType)classModel).$getType$()).getTypeArgument(1)).getMember()); } else { throw new AssertionError("unexpected class model for instance with id " + getId() + ": " + (classModel != null ? classModel.getClass().getName() : "null")); } } private TypeDescriptor.Class getOuterClassTypeDescriptor() { ClassModel<?, ?> classModel = getClazz(); if (classModel instanceof MemberClassImpl) { // MemberClass<Container, Type, Arguments> return (TypeDescriptor.Class)((TypeDescriptor.Class)((ReifiedType)classModel).$getType$()).getTypeArgument(0); } else { return null; } } @Override public java.lang.Object instantiate() { final ClassModel<?, ?> classModel = getClazz(); if (classModel == null) { throw new DeserializationException("no class specified for instance with id " + getId()); } final java.lang.Class<?> clazz = getClassTypeDescriptor().getKlass(); final Class<?> outerClass; Object outer; if (classModel instanceof ClassImpl) { // Class<Type, Arguments> outerClass = null; outer = null; } else if (classModel instanceof MemberClassImpl) { // MemberClass<Container, Type, Arguments> // the algorithm in DeserializationContext // should ensure the container exists by the point we're called. outerClass = getOuterClassTypeDescriptor().getKlass(); outer = super.getContainer(); if (outer instanceof Partial) { outer = ((Partial) outer).getInstance_(); } if (outer == null) { throw new DeserializationException("no containing instance specified for member instance with id" + getId()); } } else { throw new AssertionError("unexpected class model: " + (classModel != null ? classModel.getClass().getName() : "null")); } // Construct arrays for types and arguments for reflective instantiation // of the serialization constructor Collection<?> typeArgs = classModel.getTypeArguments().getItems(); Class<?>[] types = new Class[(outerClass != null ? 2 : 1) + Util.toInt(typeArgs.getSize())]; Object[] args = new Object[(outer != null ? 2 : 1) + Util.toInt(typeArgs.getSize())]; int ii = 0; if (outerClass != null) { types[ii] = outerClass; args[ii] = outer; ii++; } types[ii] = $Serialization$.class; args[ii] = null; ii++; for (int jj = 0 ; jj < typeArgs.getSize(); ii++, jj++) { types[ii] = TypeDescriptor.class; args[ii] = Metamodel.getTypeDescriptor((ceylon.language.meta.model.Type<?>)typeArgs.getFromFirst(jj)); } try { Constructor<?> ctor = clazz.getDeclaredConstructor(types); ctor.setAccessible(true); // Actually we need to pass something equivalent to the type descriptors here // because the companion instances can require those. But we don't have the deconstructed yet! // This means we have to obtain the type descriptors from the class model java.lang.Object newInstance = ctor.newInstance(args);// Pass a null $Serialization$ if (newInstance instanceof Serializable) { super.setInstance_(newInstance); } else { // we should never get here (a NoSuchMethodException should've been thrown and caught below) throw new AssertionError("instance class " + classModel + " is not serializable for instance with id " + getId()); } } catch (NoSuchMethodException e) { throw new DeserializationException("instance class " + classModel + " is not serializable for instance with id " + getId()); } catch (InvocationTargetException e) { // Should never happen: it's a compiler-generate constructor rethrow_.rethrow(e); } catch (SecurityException e) { // Should never happen rethrow_.rethrow(e); } catch (InstantiationException|IllegalAccessException|IllegalArgumentException e) { // Should never happen: it's a compiler-generate constructor rethrow_.rethrow(e); } return null; } @Override public <Id> java.lang.Object initialize(TypeDescriptor $reified$Id, DeserializationContextImpl<Id> context) { Object instance_ = getInstance_(); if (!(instance_ instanceof Serializable)) { // we should never get here throw new AssertionError("Cannot initialize instance that is not serializable"); } Serializable instance = (Serializable)instance_; if (instance_ instanceof ceylon.language.Array) { initializeArray(context, (ceylon.language.Array<?>)instance); } else if (instance_ instanceof ceylon.language.Tuple) { initializeTuple($reified$Id, context, (ceylon.language.Tuple<?,?,?>)instance); } else { initializeObject(context, instance); } setState(null); return null; } protected <Id> void initializeTuple(TypeDescriptor $reified$Id,DeserializationContextImpl<Id> context, ceylon.language.Tuple<?,?,?> instance) { NativeMap<ReachableReference, Id> state = (NativeMap<ReachableReference, Id>)getState(); ValueDeclaration firstAttribute = (ValueDeclaration) ((ClassDeclaration) Metamodel.getOrCreateMetamodel(Tuple.class)) .getMemberDeclaration(ValueDeclaration.$TypeDescriptor$, "first"); MemberImpl firstMember = new MemberImpl(firstAttribute); java.lang.Object first = getReferredInstance(context, state, firstMember); ValueDeclaration restAttribute = (ValueDeclaration) ((ClassDeclaration) Metamodel.getOrCreateMetamodel(Tuple.class)) .getMemberDeclaration(ValueDeclaration.$TypeDescriptor$, "rest"); MemberImpl restMember = new MemberImpl(restAttribute); Id restId = state.get(restMember); java.lang.Object referredRest = context.leakInstance(restId); if (referredRest instanceof Partial && !((PartialImpl)referredRest).getInitialized()) { // Safe because tuples are immutable => no cycles ((PartialImpl)referredRest).initialize($reified$Id, context); } java.lang.Object rest = getReferredInstance(context, state, restMember); ((Tuple<?,?,?>)instance).$completeInit$(first, rest); // now check compatibility (do this after initialization // because Tuple$getType$ requires the tuple is initialized! Type firstMemberType = Metamodel.getModuleManager().getCachedType(getClassTypeDescriptor().getTypeArgument(1)); Type firstInstanceType = Metamodel.getModuleManager().getCachedType( Metamodel.getTypeDescriptor(first)); if (!firstInstanceType.isSubtypeOf(firstMemberType)) { throw notAssignable(firstMember, firstMemberType, firstInstanceType); } Type restInstanceType = Metamodel.getModuleManager().getCachedType( Metamodel.getTypeDescriptor(rest)); Type restMemberType = Metamodel.getModuleManager().getCachedType(getClassTypeDescriptor().getTypeArgument(2)); if (!restInstanceType.isSubtypeOf(restMemberType)) { throw notAssignable(restMember, restMemberType, restInstanceType); } } protected <Id> void initializeArray(DeserializationContextImpl<Id> context, ceylon.language.Array<?> instance) { NativeMap<ReachableReference, Id> state = (NativeMap<ReachableReference, Id>)getState(); // In this case we statically know the $references$, and they are: // the array's size and each of its elements (as integers) ReachableReference sizeAttr = (ReachableReference)instance.$references$().iterator().next();//ceylon.language.String.instance("ceylon.language::Array.size"); ceylon.language.Integer size = (ceylon.language.Integer)getReferredInstance(context, state, sizeAttr); if (size == null) { throw insufficiantState(sizeAttr); } instance.$set$(sizeAttr, size); int sz = Util.toInt(size.longValue()); for (int ii = 0; ii < sz; ii++) { ElementImpl index = new ElementImpl(ii); Id id = state.get(index); if (id == null) { throw insufficiantState(index); } TypeDescriptor.Class arrayType = (TypeDescriptor.Class)Metamodel.getTypeDescriptor(instance); Type arrayElementType = Metamodel.getModuleManager().getCachedType(arrayType.getTypeArguments()[0]); Object element = getReferredInstance(context, id); Type elementType = Metamodel.getModuleManager().getCachedType(Metamodel.getTypeDescriptor(element)); if (elementType.isSubtypeOf(arrayElementType)) { instance.$set$(index, element); } else { throw notAssignable(index, arrayElementType, elementType); } } if (state.getSize() != sz + 1) { throw insufficiantState((ReachableReference)null); } } protected <Id> void initializeObject( DeserializationContextImpl<Id> context, Serializable instance) { NativeMap<ReachableReference, Id> state = (NativeMap<ReachableReference, Id>)getState(); // TODO If it were a map of java.lang.String we'd avoid pointless extra boxing java.util.Collection<ReachableReference> reachables = instance.$references$(); int numLate = 0; for (ReachableReference r : reachables) { if (r instanceof Member && ((Member)r).getAttribute().getLate()) { numLate++; } else if (r instanceof Outer) { numLate++; } } if (state.getSize() < reachables.size()-numLate) { HashSet<ReachableReference> missingNames = new HashSet<ReachableReference>(); java.util.Iterator<ReachableReference> it = reachables.iterator(); while (it.hasNext()) { missingNames.add(it.next()); } ceylon.language.Iterator<? extends ReachableReference> it2 = state.getKeys().iterator(); Object next; while (((next = it2.next()) instanceof ReachableReference)) { missingNames.remove(next); } throw insufficiantState(missingNames); } for (ReachableReference reference : reachables) { if (reference instanceof Member) { Member member = (Member)reference; if (member.getAttribute().getLate() && !state.contains(member) || state.get(member) == uninitializedLateValue_.get_()) { continue; } TypeDescriptor.Class classTypeDescriptor = getClassTypeDescriptor(); Entry<TypeDescriptor.Class,String> cacheKey = new Entry<TypeDescriptor.Class,String>( TypeDescriptor.klass(TypeDescriptor.Class.class), String.$TypeDescriptor$, classTypeDescriptor, String.instance(member.getAttribute().getQualifiedName())); Type memberType = (Type)context.getMemberTypeCache().get(cacheKey); if (memberType == null) { Type pt = Metamodel.getModuleManager().getCachedType(classTypeDescriptor); while (!pt.getDeclaration().getQualifiedNameString().equals(((ClassDeclaration)member.getAttribute().getContainer()).getQualifiedName())) { pt = pt.getExtendedType(); } FunctionOrValue attributeDeclaration = (FunctionOrValue)((TypeDeclaration)pt.getDeclaration()).getMember( member.getAttribute().getName(), null, false); TypedReference attributeType = pt.getTypedMember( attributeDeclaration, Collections.<Type>emptyList(), true); memberType = attributeType.getType(); context.getMemberTypeCache().put(cacheKey, memberType); } Object referredInstance = getReferredInstance(context, state, member); Type instanceType = Metamodel.getModuleManager().getCachedType( Metamodel.getTypeDescriptor(referredInstance)); if (!instanceType.isSubtypeOf(memberType)) { throw notAssignable(member, memberType, instanceType); } instance.$set$(member, referredInstance); // the JVM will check the assignability, but we need to // check assignability at the ceylon level, so we need to know /// type of the attribute an the type that we're assigning. // XXX this check is really expensive! // we should cache the attribute type on the context // when can we avoid this check. // XXX we can cache MethodHandle setters on the context! } else if (reference instanceof Outer) { // ignore it -- the DeserializationContext deals with // instantiating member classes continue; } else { throw new AssertionError("unexpected ReachableReference " + reference); } } } java.lang.String descriptor(ReachableReference reachable) { if (reachable instanceof Member) { return java.lang.String.valueOf(((Member)reachable).getAttribute()); } else if (reachable instanceof Element) { return "index " + ((Element)reachable).getIndex(); } else { return java.lang.String.valueOf(reachable); } } DeserializationException notAssignable(ReachableReference attributeOrIndex, Type attributeOrIndexType, Type instanceType) { return new DeserializationException("instance not assignable to " + descriptor(attributeOrIndex) + " of id " + getId() + ": " + instanceType.asString() + " is not assignable to " + attributeOrIndexType.asString()); } DeserializationException insufficiantState(java.util.Collection<ReachableReference> missingNames) { StringBuilder sb = new StringBuilder(); Iterator<ReachableReference> iterator = missingNames.iterator(); while (iterator.hasNext()) { ReachableReference r = iterator.next(); sb.append(descriptor(r)); if (iterator.hasNext()) { sb.append(", "); } } return new DeserializationException("lacking sufficient state for instance with id " + getId() + ": " + sb.toString()); } DeserializationException insufficiantState(ReachableReference missing) { return new DeserializationException("lacking sufficient state for instance with id " + getId() + (missing != null ? ": " + descriptor(missing) : "")); } /** Get the (leaked, partially constructed) instance with the given name. */ protected <Id> java.lang.Object getReferredInstance( DeserializationContextImpl<Id> context, NativeMap<ReachableReference, Id> state, ReachableReference reachable) { Id referredId = state.get(reachable); return getReferredInstance(context, referredId); } /** Get the (leaked, partially constructed) instance with the given id. */ protected <Id> java.lang.Object getReferredInstance( DeserializationContextImpl<Id> context, Id referredId) { java.lang.Object referred = context.leakInstance(referredId); if (referred instanceof Partial) { referred = ((Partial)referred).getInstance_(); } return referred; } public java.lang.String toString() { return "Partial " + getId() + (getInitialized() ? " initialized " : getInstantiated() ? " instantiated " : " uninstantiated ") + getClazz(); } }
9244b3eeda7a43c56cdc2263dddb2e02799c577a
2,721
java
Java
app/src/main/java/com/taihao/criminaintent/ui/crime/activity/CrimePagerActivity.java
barryailun/criminaintent
08cc62b6e831cacf24cc48ecda175ad590209378
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/taihao/criminaintent/ui/crime/activity/CrimePagerActivity.java
barryailun/criminaintent
08cc62b6e831cacf24cc48ecda175ad590209378
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/taihao/criminaintent/ui/crime/activity/CrimePagerActivity.java
barryailun/criminaintent
08cc62b6e831cacf24cc48ecda175ad590209378
[ "Apache-2.0" ]
null
null
null
35.337662
80
0.664829
1,003,106
package com.taihao.criminaintent.ui.crime.activity; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.ViewPager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.taihao.criminaintent.R; import com.taihao.criminaintent.ui.crime.bean.Crime; import com.taihao.criminaintent.ui.crime.bean.CrimeLab; import com.taihao.criminaintent.ui.crime.fragment.CrimeFragment; import com.taihao.criminaintent.ui.crime.fragment.CrimeListFragment; import java.util.List; import java.util.UUID; public class CrimePagerActivity extends AppCompatActivity { private static final String EXTRA_CRIME_ID = "com.taihao.criminalintent.crime_id"; private ViewPager mViewPager; private List<Crime> mCrimes; private Button jumpFirstBtn; private Button jumpLastBtn; public static Intent newIntent(Context packageContext, UUID crimeId) { Intent intent = new Intent(packageContext, CrimePagerActivity.class); intent.putExtra(EXTRA_CRIME_ID, crimeId); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crime_pager); UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID); mViewPager = findViewById(R.id.activity_crime_pager); mCrimes = CrimeLab.get(this).getCrimes(); FragmentManager fm = getSupportFragmentManager(); mViewPager.setAdapter(new FragmentStatePagerAdapter(fm) { @Override public Fragment getItem(int position) { Crime crime = mCrimes.get(position); return CrimeFragment.newInstance(crime.getmId()); } @Override public int getCount() { return mCrimes.size(); } }); for (int i = 0; i < mCrimes.size(); i++) { if (mCrimes.get(i).getmId().equals(crimeId)) { mViewPager.setCurrentItem(i); break; } } jumpFirstBtn = findViewById(R.id.jump_to_first); jumpLastBtn = findViewById(R.id.jump_to_last); jumpFirstBtn.setOnClickListener(v -> { mViewPager.setCurrentItem(0); }); jumpLastBtn.setOnClickListener(v -> { mViewPager.setCurrentItem(mCrimes.size()-1); }); } }
9244b3ff5ca022f54161ca8466cc7f16be870576
5,643
java
Java
itgen/src/main/java/data/model/schedule/CommentData.java
julja83/java_itgen
7b8dc5a7291564d10594c900e895ef3819256ddf
[ "Apache-2.0" ]
null
null
null
itgen/src/main/java/data/model/schedule/CommentData.java
julja83/java_itgen
7b8dc5a7291564d10594c900e895ef3819256ddf
[ "Apache-2.0" ]
null
null
null
itgen/src/main/java/data/model/schedule/CommentData.java
julja83/java_itgen
7b8dc5a7291564d10594c900e895ef3819256ddf
[ "Apache-2.0" ]
null
null
null
19.259386
77
0.60163
1,003,107
package data.model.schedule; import dev.morphia.annotations.Embedded; import dev.morphia.annotations.Entity; import dev.morphia.annotations.Id; import dev.morphia.annotations.Property; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; @Entity("comments") public class CommentData { @Id @Property("_id") private String id; @Property("owner") private String owner; @Property("target") private String target; @Property("s") private String s; @Property("w") private Double w; @Property("sTime") private Double sTime; @Property("eTime") private Double eTime; @Property("skillId") private String skillId; @Property("createdAt") private Date createdAt; @Property("text") private String text; @Property("done") private String done; @Property("hw") private String hw; @Property("textForParents") private String textForParents; @Property("t") private String t; @Property("topics") private String topics; @Embedded private Grades grades; @Embedded private List<HwMaterials> hwMaterials = new ArrayList<HwMaterials>(); @Embedded private List<DoneMaterials> doneMaterials = new ArrayList<DoneMaterials>(); public CommentData() {} public CommentData withId(String id) { this.id = id; return this; } public CommentData withOwner(String owner) { this.owner = owner; return this; } public CommentData withTarget(String target) { this.target = target; return this; } public CommentData withS(String s) { this.s = s; return this; } public CommentData withW(Double w) { this.w = w; return this; } public CommentData withSTime(Double sTime) { this.sTime = sTime; return this; } public CommentData withETime(Double eTime) { this.eTime = eTime; return this; } public CommentData withSkillId(String skillId) { this.skillId = skillId; return this; } public CommentData withCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public CommentData withText(String text) { this.text = text; return this; } public CommentData withDone(String done) { this.done = done; return this; } public CommentData withHw(String hw) { this.hw = hw; return this; } public CommentData withTextForParents(String textForParents) { this.textForParents = textForParents; return this; } public CommentData withT(String t) { this.t = t; return this; } public CommentData withTopics(String topics) { this.topics = topics; return this; } public CommentData withGrades(Grades grades) { this.grades = grades; return this; } public CommentData withHwMaterials(List<HwMaterials> hwMaterials) { this.hwMaterials = hwMaterials; return this; } public CommentData withDoneMaterials(List<DoneMaterials> doneMaterials) { this.doneMaterials = doneMaterials; return this; } public String getId() { return id; } public String getOwner() { return owner; } public String getTarget() { return target; } public String getS() { return s; } public Double getW() { return w; } public Double getsTime() { return sTime; } public Double geteTime() { return eTime; } public String getSkillId() { return skillId; } public Date getCreatedAt() { return createdAt; } public String getText() { return text; } public String getDone() { return done; } public String getHw() { return hw; } public String getTextForParents() { return textForParents; } public String getT() { return t; } public String getTopics() { return topics; } public Grades getGrades() { return grades; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CommentData that = (CommentData) o; return Objects.equals(id, that.id) && Objects.equals(owner, that.owner) && Objects.equals(target, that.target) && Objects.equals(s, that.s) && Objects.equals(w, that.w) && Objects.equals(sTime, that.sTime) && Objects.equals(eTime, that.eTime) && Objects.equals(skillId, that.skillId) && Objects.equals(text, that.text) && Objects.equals(done, that.done) && Objects.equals(hw, that.hw) && Objects.equals(textForParents, that.textForParents) && Objects.equals(t, that.t) && Objects.equals(topics, that.topics) && Objects.equals(grades, that.grades); } @Override public int hashCode() { return Objects.hash( id, owner, target, s, w, sTime, eTime, skillId, text, done, hw, textForParents, t, topics, grades); } @Override public String toString() { return "CommentData{" + "id='" + id + '\'' + ", owner='" + owner + '\'' + ", target='" + target + '\'' + ", s='" + s + '\'' + ", w=" + w + ", sTime=" + sTime + ", eTime=" + eTime + ", skillId='" + skillId + '\'' + ", createdAt=" + createdAt + ", text='" + text + '\'' + ", done='" + done + '\'' + ", hw='" + hw + '\'' + ", textForParents='" + textForParents + '\'' + ", finished='" + t + '\'' + ", topics='" + topics + '\'' + ", grades=" + grades + '}'; } }
9244b4aefc858e9f67143366f5e023441c2567b7
1,721
java
Java
spring-web-annotation/src/main/java/io/micronaut/spring/web/annotation/RestControllerAnnotationMapper.java
cemo/micronaut-spring
91210d4515a01d7a7e4924de5b7e0997f97889c1
[ "Apache-2.0" ]
148
2018-11-13T11:58:24.000Z
2022-01-26T07:05:54.000Z
spring-web-annotation/src/main/java/io/micronaut/spring/web/annotation/RestControllerAnnotationMapper.java
cemo/micronaut-spring
91210d4515a01d7a7e4924de5b7e0997f97889c1
[ "Apache-2.0" ]
123
2018-11-19T08:29:52.000Z
2022-03-31T11:27:06.000Z
spring-web-annotation/src/main/java/io/micronaut/spring/web/annotation/RestControllerAnnotationMapper.java
cemo/micronaut-spring
91210d4515a01d7a7e4924de5b7e0997f97889c1
[ "Apache-2.0" ]
55
2018-11-13T14:05:25.000Z
2022-02-10T04:14:56.000Z
36.617021
123
0.765834
1,003,108
/* * Copyright 2017-2020 original 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 io.micronaut.spring.web.annotation; import io.micronaut.core.annotation.AnnotationValue; import io.micronaut.http.annotation.Controller; import io.micronaut.inject.visitor.VisitorContext; import io.micronaut.spring.annotation.context.ComponentAnnotationMapper; import io.micronaut.validation.Validated; import java.lang.annotation.Annotation; import java.util.List; /** * Maps Spring RestController to Micronaut. * * @author graemerocher * @since 1.0 */ public class RestControllerAnnotationMapper extends ComponentAnnotationMapper { @Override public String getName() { return "org.springframework.web.bind.annotation.RestController"; } @Override protected List<AnnotationValue<?>> mapInternal(AnnotationValue<Annotation> annotation, VisitorContext visitorContext) { final List<AnnotationValue<?>> annotationValues = super.mapInternal(annotation, visitorContext); annotationValues.add(AnnotationValue.builder(Controller.class).build()); annotationValues.add(AnnotationValue.builder(Validated.class).build()); return annotationValues; } }
9244b5123b3e403e2b0fb68889fe321449d802c7
2,568
java
Java
ui/cli/dataloader/src/java/com/echothree/ui/cli/dataloader/util/data/handler/job/JobsHandler.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-09-01T08:39:01.000Z
2020-09-01T08:39:01.000Z
ui/cli/dataloader/src/java/com/echothree/ui/cli/dataloader/util/data/handler/job/JobsHandler.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
null
null
null
ui/cli/dataloader/src/java/com/echothree/ui/cli/dataloader/util/data/handler/job/JobsHandler.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-05-31T08:34:46.000Z
2020-05-31T08:34:46.000Z
37.764706
109
0.655763
1,003,109
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // 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.echothree.ui.cli.dataloader.util.data.handler.job; import com.echothree.control.user.job.common.JobUtil; import com.echothree.control.user.job.common.JobService; import com.echothree.control.user.job.common.form.CreateJobForm; import com.echothree.control.user.job.common.form.JobFormFactory; import com.echothree.ui.cli.dataloader.util.data.InitialDataParser; import com.echothree.ui.cli.dataloader.util.data.handler.BaseHandler; import javax.naming.NamingException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class JobsHandler extends BaseHandler { JobService jobService; /** Creates a new instance of JobsHandler */ public JobsHandler(InitialDataParser initialDataParser, BaseHandler parentHandler) throws SAXException { super(initialDataParser, parentHandler); try { jobService = JobUtil.getHome(); } catch (NamingException ne) { throw new SAXException(ne); } } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { if(localName.equals("job")) { CreateJobForm commandForm = JobFormFactory.getCreateJobForm(); commandForm.set(getAttrsMap(attrs)); jobService.createJob(initialDataParser.getUserVisit(), commandForm); initialDataParser.pushHandler(new JobHandler(initialDataParser, this, commandForm.getJobName())); } } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if(localName.equals("jobs")) { initialDataParser.popHandler(); } } }
9244b51c2fd1424f5600a37717b203bb12a3d377
2,160
java
Java
AutomationPortfolio/src/main/java/pages/HomePage.java
schh321/portfolio
7a2e1b88f607a9d8845dbe55c6926ba3ef0c125d
[ "MIT" ]
null
null
null
AutomationPortfolio/src/main/java/pages/HomePage.java
schh321/portfolio
7a2e1b88f607a9d8845dbe55c6926ba3ef0c125d
[ "MIT" ]
null
null
null
AutomationPortfolio/src/main/java/pages/HomePage.java
schh321/portfolio
7a2e1b88f607a9d8845dbe55c6926ba3ef0c125d
[ "MIT" ]
null
null
null
27
88
0.713889
1,003,110
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import common.ExcelUtil; import pages.CurrentMortgage.TestData; public class HomePage { WebDriver driver; public static class TestData { public static String dataSheetName = "HomePage"; public static int addressCol = 0; public static int address2Col = 1; public static int cityCol = 2; public static int stateCol=3; public static int zipcodeCol= 4; } @FindBy(xpath="//*[@name='address']") public WebElement address; @FindBy(xpath="//*[@name='address']") public WebElement address2; @FindBy (xpath ="//*[@name='city']") public WebElement city; @FindBy(xpath="//*[@name='state']") public WebElement state; @FindBy(xpath="//*[@name='zipCode']") public WebElement zipcode; @FindBy(xpath="//*[@type='submit']") public WebElement saveAndContinue; public HomePage(WebDriver driver) { this.driver= driver; PageFactory.initElements(driver, this); ExcelUtil.readSheet(TestData.dataSheetName); } public void HomeInfoPage2submit(int testDataRow) throws InterruptedException { submit(ExcelUtil.getValue(testDataRow, TestData.addressCol), ExcelUtil.getValue(testDataRow, TestData.address2Col), ExcelUtil.getValue(testDataRow, TestData.cityCol), ExcelUtil.getValue(testDataRow, TestData.stateCol), ExcelUtil.getValue(testDataRow, TestData.zipcodeCol)); } public HomeInfoPage2 submit(String inputAddress,String inputAddress2,String inputCity, String inputState,String inputZipcode) { address.clear(); address.sendKeys(inputAddress); address2.clear(); address2.sendKeys(inputAddress2); city.clear(); city.sendKeys(inputCity); Select s= new Select (state); s.selectByVisibleText(inputState); zipcode.clear(); zipcode.sendKeys(inputZipcode); saveAndContinue.click(); return new HomeInfoPage2(driver); } }
9244b54ee9acb588ab5b2eb26bcf7175e16c58da
906
java
Java
src/main/java/org/chromium/device/mojom/BluetoothSystemClient.java
ridi/chromium-aw
869b435e671da449e36ecb73f1e14c0ba691da74
[ "BSD-3-Clause" ]
47
2018-11-21T06:30:38.000Z
2022-02-17T10:02:50.000Z
src/main/java/org/chromium/device/mojom/BluetoothSystemClient.java
ridi/chromium-aw
869b435e671da449e36ecb73f1e14c0ba691da74
[ "BSD-3-Clause" ]
14
2019-08-20T11:36:23.000Z
2022-03-09T11:12:48.000Z
src/main/java/org/chromium/device/mojom/BluetoothSystemClient.java
ridi/chromium-aw
869b435e671da449e36ecb73f1e14c0ba691da74
[ "BSD-3-Clause" ]
13
2019-07-30T13:50:27.000Z
2022-02-14T10:03:06.000Z
23.230769
113
0.777042
1,003,111
// BluetoothSystemClient.java is auto generated by mojom_bindings_generator.py, do not edit // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by: // mojo/public/tools/bindings/mojom_bindings_generator.py // For: // services/device/public/mojom/bluetooth_system.mojom // package org.chromium.device.mojom; import androidx.annotation.IntDef; public interface BluetoothSystemClient extends org.chromium.mojo.bindings.Interface { public interface Proxy extends BluetoothSystemClient, org.chromium.mojo.bindings.Interface.Proxy { } Manager<BluetoothSystemClient, BluetoothSystemClient.Proxy> MANAGER = BluetoothSystemClient_Internal.MANAGER; void onStateChanged( int newState); void onScanStateChanged( int newState); }
9244b5cfbf5cd389a9da21c4bb15c52116d108d0
977
java
Java
src/main/java/com/rainbowluigi/soulmagic/item/ItemBlindedRage.java
jrcichra/SoulMagic
7fce8f85e7327bb7d6a11dfa151ac8716775f992
[ "CC0-1.0" ]
null
null
null
src/main/java/com/rainbowluigi/soulmagic/item/ItemBlindedRage.java
jrcichra/SoulMagic
7fce8f85e7327bb7d6a11dfa151ac8716775f992
[ "CC0-1.0" ]
null
null
null
src/main/java/com/rainbowluigi/soulmagic/item/ItemBlindedRage.java
jrcichra/SoulMagic
7fce8f85e7327bb7d6a11dfa151ac8716775f992
[ "CC0-1.0" ]
null
null
null
26.405405
106
0.778915
1,003,112
package com.rainbowluigi.soulmagic.item; import java.util.List; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.item.TooltipContext; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.text.LiteralText; import net.minecraft.text.Text; import net.minecraft.world.World; public class ItemBlindedRage extends Item implements Accessory { private AccessoryType type; public ItemBlindedRage(Settings setting, AccessoryType type) { super(setting); this.type = type; } public ItemBlindedRage(Settings setting) { this(setting, null); } @Override public AccessoryType getType() { return this.type; } @Environment(EnvType.CLIENT) public void appendTooltip(ItemStack stack, World world, List<Text> list, TooltipContext tooltipcontext) { list.add(new LiteralText("Increases magical strength at the")); list.add(new LiteralText("cost of less magical efficency.")); } }
9244b688747f865d28a42d41fe9e9bac6d2cbd24
672
java
Java
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n5/doma/healthLifesci/clazz/DrugPrescriptionStatusConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
1
2020-02-18T01:55:36.000Z
2020-02-18T01:55:36.000Z
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n5/doma/healthLifesci/clazz/DrugPrescriptionStatusConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
null
null
null
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n5/doma/healthLifesci/clazz/DrugPrescriptionStatusConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
null
null
null
29.217391
105
0.839286
1,003,113
package org.kyojo.schemaorg.m3n5.doma.healthLifesci.clazz; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaorg.m3n5.healthLifesci.impl.DRUG_PRESCRIPTION_STATUS; import org.kyojo.schemaorg.m3n5.healthLifesci.Clazz.DrugPrescriptionStatus; @ExternalDomain public class DrugPrescriptionStatusConverter implements DomainConverter<DrugPrescriptionStatus, String> { @Override public String fromDomainToValue(DrugPrescriptionStatus domain) { return domain.getNativeValue(); } @Override public DrugPrescriptionStatus fromValueToDomain(String value) { return new DRUG_PRESCRIPTION_STATUS(value); } }
9244b724b33fd5417a074ba6c0801bb932387b31
59
java
Java
Student.java
yilongyun1010/dinggo
ea0ab0c8128e9496d0666dd7b48e9076fff33f3e
[ "Apache-2.0" ]
null
null
null
Student.java
yilongyun1010/dinggo
ea0ab0c8128e9496d0666dd7b48e9076fff33f3e
[ "Apache-2.0" ]
null
null
null
Student.java
yilongyun1010/dinggo
ea0ab0c8128e9496d0666dd7b48e9076fff33f3e
[ "Apache-2.0" ]
null
null
null
11.8
21
0.745763
1,003,114
class Student{ private String id; private String name; }
9244b77ede10fd5ddf9b9fa6f436ff44244fff0c
5,120
java
Java
src/main/java/org/entitypedia/games/gameframework/common/api/IDeveloperAPI.java
EntitypediaGames/games-framework-common
27ed09c02de81ff0b0654183fd43990260a76ffb
[ "MIT" ]
null
null
null
src/main/java/org/entitypedia/games/gameframework/common/api/IDeveloperAPI.java
EntitypediaGames/games-framework-common
27ed09c02de81ff0b0654183fd43990260a76ffb
[ "MIT" ]
null
null
null
src/main/java/org/entitypedia/games/gameframework/common/api/IDeveloperAPI.java
EntitypediaGames/games-framework-common
27ed09c02de81ff0b0654183fd43990260a76ffb
[ "MIT" ]
null
null
null
37.101449
117
0.700391
1,003,115
package org.entitypedia.games.gameframework.common.api; import org.entitypedia.games.common.exceptions.AccessDeniedException; import org.entitypedia.games.common.model.ResultsPage; import org.entitypedia.games.gameframework.common.exceptions.DuplicateEmailException; import org.entitypedia.games.gameframework.common.exceptions.DeveloperNotFoundException; import org.entitypedia.games.gameframework.common.exceptions.InvalidPasswordResetCodeException; import org.entitypedia.games.gameframework.common.exceptions.PasswordResetCodeNotFoundException; import org.entitypedia.games.gameframework.common.exceptions.TooManyRecentPendingPasswordResetsException; import org.entitypedia.games.gameframework.common.model.Developer; /** * API for managing developers. * * @author <a href="http://autayeu.com/">Aliaksandr Autayeu</a> * @spring.mvc.doclet.path developers */ public interface IDeveloperAPI { String LOGIN_DEVELOPER = "developers/login"; String RESET_DEVELOPER_PASSWORD = "developers/resetPassword"; String REQUEST_DEVELOPER_PASSWORD_RESET = "developers/requestPasswordReset"; String READ_DEVELOPER = "developer/{developerID}"; String UPDATE_DEVELOPER_PASSWORD = "developers/updatePassword"; String UPDATE_DEVELOPER_EMAIL = "developers/updateEmail"; String UPDATE_DEVELOPER_FIRST_NAME = "developers/updateFirstName"; String UPDATE_DEVELOPER_LAST_NAME = "developers/updateLastName"; String LIST_DEVELOPERS = "developers"; /** * Login (just checks credentials). * <p> * Throws {@link AccessDeniedException} if authentication fails. * <p> * Available for developers. */ void loginDeveloper(); /** * Reads particular developer by id or uid. IDs are numerical. * <p> * Throws {@link DeveloperNotFoundException} is developer is not found.<br> * <p> * Available for developers and players. * * @param developerID id of the developer to read. * @return developer structure */ Developer readDeveloper(long developerID); /** * Resets the password of the account to the new one. * <p> * Throws {@link PasswordResetCodeNotFoundException} if password reset code is not found.<br> * Throws {@link InvalidPasswordResetCodeException} if password reset is already completed.<br> * <p> * Available without authentication. * * @param code password reset authorization code * @param password new password */ void resetDeveloperPassword(String code, String password); /** * Sends password reset code to the developer's email. * <p> * Throws {@link TooManyRecentPendingPasswordResetsException} if password reset count if over quota. * <p> * Available without authentication. * * @param email developer's email */ void requestDeveloperPasswordReset(String email); /** * Updates developer password. * <p> * Throws {@link DeveloperNotFoundException} is developer is not found.<br> * <p> * Available for the developer in question. * * @param developerID id of the developer * @param password new password */ void updateDeveloperPassword(long developerID, String password); /** * Updates developer email. * <p> * Throws {@link DeveloperNotFoundException} is developer is not found.<br> * Throws {@link DuplicateEmailException} if there is already a registered developer with the same email.<br> * <p> * Available for the developer in question. * * @param developerID id of the developer * @param email new email */ void updateDeveloperEmail(long developerID, String email); /** * Updates developer first name. * <p> * Throws {@link DeveloperNotFoundException} is developer is not found.<br> * <p> * Available for the developer in question. * * @param developerID id of the developer * @param firstName new first name */ void updateDeveloperFirstName(long developerID, String firstName); /** * Updates developer last name. * <p> * Throws {@link DeveloperNotFoundException} is developer is not found.<br> * <p> * Available for the developer in question. * * @param developerID id of the developer * @param lastName new last name */ void updateDeveloperLastName(long developerID, String lastName); /** * Lists developers. * <p> * Throws {@link IllegalArgumentException} if {@code pageNo} or {@code pageSize} is out of bounds.<br> * <p> * Available for developers and players. * * @param pageSize pageSize, default 9, max 100 * @param pageNo 0-based page number * @param filter filter expression. example: creator.id eq 1 or published eq true or creationTime ge '20130101' * @param order order expression. example: Alayout.rowCount-Dlayout.columnCount * @return a page of developers */ ResultsPage<Developer> listDevelopers(Integer pageSize, Integer pageNo, String filter, String order); }
9244b807cb4f87d8e27fa57bfcafc4c74aa5d038
603
java
Java
libs/ZUtils/src/com/kit/app/adapter/ViewHolder.java
BigAppLink/BigApp_Discuz_Android-master
ac47c7fca6cbfe107eb6b21cd95995ec6c38fc1d
[ "Apache-2.0" ]
79
2016-03-17T12:17:27.000Z
2021-09-27T12:12:16.000Z
libs/ZUtils/src/com/kit/app/adapter/ViewHolder.java
BigAppLink/BigApp_Discuz_Android-master
ac47c7fca6cbfe107eb6b21cd95995ec6c38fc1d
[ "Apache-2.0" ]
4
2016-05-24T02:09:59.000Z
2018-05-16T12:31:56.000Z
libs/ZUtils/src/com/kit/app/adapter/ViewHolder.java
BigAppLink/BigApp_Discuz_Android-master
ac47c7fca6cbfe107eb6b21cd95995ec6c38fc1d
[ "Apache-2.0" ]
78
2016-03-18T02:59:37.000Z
2021-12-23T11:14:39.000Z
24.12
74
0.709784
1,003,116
package com.kit.app.adapter; import android.util.SparseArray; import android.view.View; public class ViewHolder { private ViewHolder() { } @SuppressWarnings("unchecked") public static <T extends View> T get(View convertView, int id) { SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag(); if (viewHolder == null) { viewHolder = new SparseArray<View>(); convertView.setTag(viewHolder); } View childView = viewHolder.get(id); if (childView == null) { childView = convertView.findViewById(id); viewHolder.put(id, childView); } return (T) childView; } }
9244b96df726834a76e2f8450829bfeab7b06645
2,059
java
Java
src/test/java/de/fraunhofer/iais/eis/ids/connector/artifact/DirectoryWatcherTest.java
International-Data-Spaces-Association/IDS-Enterprise-Integration-Conntector
41cdd4dd204abb0c349642cdef32da040e9bfd6a
[ "Apache-2.0" ]
2
2021-01-22T15:23:21.000Z
2021-03-03T10:33:46.000Z
src/test/java/de/fraunhofer/iais/eis/ids/connector/artifact/DirectoryWatcherTest.java
International-Data-Spaces-Association/IDS-Enterprise-Integration-Conntector
41cdd4dd204abb0c349642cdef32da040e9bfd6a
[ "Apache-2.0" ]
6
2020-12-10T15:03:20.000Z
2021-03-25T07:56:09.000Z
src/test/java/de/fraunhofer/iais/eis/ids/connector/artifact/DirectoryWatcherTest.java
International-Data-Spaces-Association/IDS-Enterprise-Integration-Connector
41cdd4dd204abb0c349642cdef32da040e9bfd6a
[ "Apache-2.0" ]
1
2020-12-09T08:36:55.000Z
2020-12-09T08:36:55.000Z
27.092105
73
0.677513
1,003,117
package de.fraunhofer.iais.eis.ids.connector.artifact; import org.apache.commons.io.FileUtils; import org.junit.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class DirectoryWatcherTest { private static String tmpDir; private DirectoryWatcher watcher; private ExecutorService executor; private LoggingArtifactListener listener; private class LoggingArtifactListener implements ArtifactListener { Collection<String> addedFiles = new ArrayList<>(); Collection<String> removedFiles = new ArrayList<>(); @Override public void notifyAdd(File artifact) { addedFiles.add(artifact.getName()); } @Override public void notifyChange(File artifact) { } @Override public void notifyRemove(File artifact) { removedFiles.add(artifact.getName()); } } @BeforeClass public static void setUp() { tmpDir = "/tmp/" +System.currentTimeMillis(); File dir = new File(tmpDir); dir.mkdir(); } @AfterClass public static void cleanUp() throws IOException { FileUtils.deleteDirectory(new File(tmpDir)); } @Before public void init() throws IOException { watcher = new DirectoryWatcher(tmpDir); listener = new LoggingArtifactListener(); watcher.setArtifactListeners(Arrays.asList(listener)); executor = Executors.newSingleThreadExecutor(); executor.submit(watcher); } @Test public void watchAsync() throws InterruptedException, IOException { File newFile = new File(tmpDir + File.separator + "newFile.txt"); newFile.createNewFile(); executor.awaitTermination(1, TimeUnit.SECONDS); executor.shutdownNow(); Assert.assertEquals(1, listener.addedFiles.size()); } }
9244b9fef8571cb5e1912e0614e66fe21530426d
13,694
java
Java
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/DatanodeProtocolServerSideTranslatorPB.java
yellowflash/hadoop
aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
14,425
2015-01-01T15:34:43.000Z
2022-03-31T15:28:37.000Z
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/DatanodeProtocolServerSideTranslatorPB.java
yellowflash/hadoop
aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
3,805
2015-03-20T15:58:53.000Z
2022-03-31T23:58:37.000Z
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/DatanodeProtocolServerSideTranslatorPB.java
yellowflash/hadoop
aa9cdf2af6fd84aa24ec5a19da4f955472a8d5bd
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
9,521
2015-01-01T19:12:52.000Z
2022-03-31T03:07:51.000Z
44.032154
108
0.751789
1,003,118
/** * 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.hdfs.protocolPB; import java.io.IOException; import java.util.List; import org.apache.hadoop.hdfs.protocol.BlockListAsLongs; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.RollingUpgradeStatus; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockReceivedAndDeletedRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockReceivedAndDeletedResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockReportRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.BlockReportResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.CacheReportRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.CacheReportResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.CommitBlockSynchronizationRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.CommitBlockSynchronizationResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.ErrorReportRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.ErrorReportResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.HeartbeatRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.HeartbeatResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.ReceivedDeletedBlockInfoProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.RegisterDatanodeRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.RegisterDatanodeResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.ReportBadBlocksRequestProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.ReportBadBlocksResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.StorageBlockReportProto; import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos.StorageReceivedDeletedBlocksProto; import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.DatanodeIDProto; import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.LocatedBlockProto; import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.RollingUpgradeStatusProto; import org.apache.hadoop.hdfs.protocol.proto.HdfsServerProtos.VersionRequestProto; import org.apache.hadoop.hdfs.protocol.proto.HdfsServerProtos.VersionResponseProto; import org.apache.hadoop.hdfs.server.protocol.DatanodeCommand; import org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol; import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration; import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage; import org.apache.hadoop.hdfs.server.protocol.HeartbeatResponse; import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo; import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo; import org.apache.hadoop.hdfs.server.protocol.StorageBlockReport; import org.apache.hadoop.hdfs.server.protocol.StorageReceivedDeletedBlocks; import org.apache.hadoop.hdfs.server.protocol.StorageReport; import org.apache.hadoop.hdfs.server.protocol.VolumeFailureSummary; import org.apache.hadoop.thirdparty.com.google.common.base.Preconditions; import org.apache.hadoop.thirdparty.protobuf.RpcController; import org.apache.hadoop.thirdparty.protobuf.ServiceException; public class DatanodeProtocolServerSideTranslatorPB implements DatanodeProtocolPB { private final DatanodeProtocol impl; private final int maxDataLength; private static final ErrorReportResponseProto VOID_ERROR_REPORT_RESPONSE_PROTO = ErrorReportResponseProto.newBuilder().build(); private static final BlockReceivedAndDeletedResponseProto VOID_BLOCK_RECEIVED_AND_DELETE_RESPONSE = BlockReceivedAndDeletedResponseProto.newBuilder().build(); private static final ReportBadBlocksResponseProto VOID_REPORT_BAD_BLOCK_RESPONSE = ReportBadBlocksResponseProto.newBuilder().build(); private static final CommitBlockSynchronizationResponseProto VOID_COMMIT_BLOCK_SYNCHRONIZATION_RESPONSE_PROTO = CommitBlockSynchronizationResponseProto.newBuilder().build(); public DatanodeProtocolServerSideTranslatorPB(DatanodeProtocol impl, int maxDataLength) { this.impl = impl; this.maxDataLength = maxDataLength; } @Override public RegisterDatanodeResponseProto registerDatanode( RpcController controller, RegisterDatanodeRequestProto request) throws ServiceException { DatanodeRegistration registration = PBHelper.convert(request .getRegistration()); DatanodeRegistration registrationResp; try { registrationResp = impl.registerDatanode(registration); } catch (IOException e) { throw new ServiceException(e); } return RegisterDatanodeResponseProto.newBuilder() .setRegistration(PBHelper.convert(registrationResp)).build(); } @Override public HeartbeatResponseProto sendHeartbeat(RpcController controller, HeartbeatRequestProto request) throws ServiceException { HeartbeatResponse response; try { final StorageReport[] report = PBHelperClient.convertStorageReports( request.getReportsList()); VolumeFailureSummary volumeFailureSummary = request.hasVolumeFailureSummary() ? PBHelper.convertVolumeFailureSummary( request.getVolumeFailureSummary()) : null; response = impl.sendHeartbeat(PBHelper.convert(request.getRegistration()), report, request.getCacheCapacity(), request.getCacheUsed(), request.getXmitsInProgress(), request.getXceiverCount(), request.getFailedVolumes(), volumeFailureSummary, request.getRequestFullBlockReportLease(), PBHelper.convertSlowPeerInfo(request.getSlowPeersList()), PBHelper.convertSlowDiskInfo(request.getSlowDisksList())); } catch (IOException e) { throw new ServiceException(e); } HeartbeatResponseProto.Builder builder = HeartbeatResponseProto .newBuilder(); DatanodeCommand[] cmds = response.getCommands(); if (cmds != null) { for (int i = 0; i < cmds.length; i++) { if (cmds[i] != null) { builder.addCmds(PBHelper.convert(cmds[i])); } } } builder.setHaStatus(PBHelper.convert(response.getNameNodeHaState())); RollingUpgradeStatus rollingUpdateStatus = response .getRollingUpdateStatus(); if (rollingUpdateStatus != null) { // V2 is always set for newer datanodes. // To be compatible with older datanodes, V1 is set to null // if the RU was finalized. RollingUpgradeStatusProto rus = PBHelperClient. convertRollingUpgradeStatus(rollingUpdateStatus); builder.setRollingUpgradeStatusV2(rus); if (!rollingUpdateStatus.isFinalized()) { builder.setRollingUpgradeStatus(rus); } } builder.setFullBlockReportLeaseId(response.getFullBlockReportLeaseId()); return builder.build(); } @Override public BlockReportResponseProto blockReport(RpcController controller, BlockReportRequestProto request) throws ServiceException { DatanodeCommand cmd = null; StorageBlockReport[] report = new StorageBlockReport[request.getReportsCount()]; int index = 0; for (StorageBlockReportProto s : request.getReportsList()) { final BlockListAsLongs blocks; if (s.hasNumberOfBlocks()) { // new style buffer based reports int num = (int)s.getNumberOfBlocks(); Preconditions.checkState(s.getBlocksCount() == 0, "cannot send both blocks list and buffers"); blocks = BlockListAsLongs.decodeBuffers(num, s.getBlocksBuffersList(), maxDataLength); } else { blocks = BlockListAsLongs.decodeLongs(s.getBlocksList(), maxDataLength); } report[index++] = new StorageBlockReport(PBHelperClient.convert(s.getStorage()), blocks); } try { cmd = impl.blockReport(PBHelper.convert(request.getRegistration()), request.getBlockPoolId(), report, request.hasContext() ? PBHelper.convert(request.getContext()) : null); } catch (IOException e) { throw new ServiceException(e); } BlockReportResponseProto.Builder builder = BlockReportResponseProto.newBuilder(); if (cmd != null) { builder.setCmd(PBHelper.convert(cmd)); } return builder.build(); } @Override public CacheReportResponseProto cacheReport(RpcController controller, CacheReportRequestProto request) throws ServiceException { DatanodeCommand cmd = null; try { cmd = impl.cacheReport( PBHelper.convert(request.getRegistration()), request.getBlockPoolId(), request.getBlocksList()); } catch (IOException e) { throw new ServiceException(e); } CacheReportResponseProto.Builder builder = CacheReportResponseProto.newBuilder(); if (cmd != null) { builder.setCmd(PBHelper.convert(cmd)); } return builder.build(); } @Override public BlockReceivedAndDeletedResponseProto blockReceivedAndDeleted( RpcController controller, BlockReceivedAndDeletedRequestProto request) throws ServiceException { List<StorageReceivedDeletedBlocksProto> sBlocks = request.getBlocksList(); StorageReceivedDeletedBlocks[] info = new StorageReceivedDeletedBlocks[sBlocks.size()]; for (int i = 0; i < sBlocks.size(); i++) { StorageReceivedDeletedBlocksProto sBlock = sBlocks.get(i); List<ReceivedDeletedBlockInfoProto> list = sBlock.getBlocksList(); ReceivedDeletedBlockInfo[] rdBlocks = new ReceivedDeletedBlockInfo[list.size()]; for (int j = 0; j < list.size(); j++) { rdBlocks[j] = PBHelper.convert(list.get(j)); } if (sBlock.hasStorage()) { info[i] = new StorageReceivedDeletedBlocks( PBHelperClient.convert(sBlock.getStorage()), rdBlocks); } else { info[i] = new StorageReceivedDeletedBlocks( new DatanodeStorage(sBlock.getStorageUuid()), rdBlocks); } } try { impl.blockReceivedAndDeleted(PBHelper.convert(request.getRegistration()), request.getBlockPoolId(), info); } catch (IOException e) { throw new ServiceException(e); } return VOID_BLOCK_RECEIVED_AND_DELETE_RESPONSE; } @Override public ErrorReportResponseProto errorReport(RpcController controller, ErrorReportRequestProto request) throws ServiceException { try { impl.errorReport(PBHelper.convert(request.getRegistartion()), request.getErrorCode(), request.getMsg()); } catch (IOException e) { throw new ServiceException(e); } return VOID_ERROR_REPORT_RESPONSE_PROTO; } @Override public VersionResponseProto versionRequest(RpcController controller, VersionRequestProto request) throws ServiceException { NamespaceInfo info; try { info = impl.versionRequest(); } catch (IOException e) { throw new ServiceException(e); } return VersionResponseProto.newBuilder() .setInfo(PBHelper.convert(info)).build(); } @Override public ReportBadBlocksResponseProto reportBadBlocks(RpcController controller, ReportBadBlocksRequestProto request) throws ServiceException { List<LocatedBlockProto> lbps = request.getBlocksList(); LocatedBlock [] blocks = new LocatedBlock [lbps.size()]; for(int i=0; i<lbps.size(); i++) { blocks[i] = PBHelperClient.convertLocatedBlockProto(lbps.get(i)); } try { impl.reportBadBlocks(blocks); } catch (IOException e) { throw new ServiceException(e); } return VOID_REPORT_BAD_BLOCK_RESPONSE; } @Override public CommitBlockSynchronizationResponseProto commitBlockSynchronization( RpcController controller, CommitBlockSynchronizationRequestProto request) throws ServiceException { List<DatanodeIDProto> dnprotos = request.getNewTaragetsList(); DatanodeID[] dns = new DatanodeID[dnprotos.size()]; for (int i = 0; i < dnprotos.size(); i++) { dns[i] = PBHelperClient.convert(dnprotos.get(i)); } final List<String> sidprotos = request.getNewTargetStoragesList(); final String[] storageIDs = sidprotos.toArray(new String[sidprotos.size()]); try { impl.commitBlockSynchronization(PBHelperClient.convert(request.getBlock()), request.getNewGenStamp(), request.getNewLength(), request.getCloseFile(), request.getDeleteBlock(), dns, storageIDs); } catch (IOException e) { throw new ServiceException(e); } return VOID_COMMIT_BLOCK_SYNCHRONIZATION_RESPONSE_PROTO; } }
9244ba28e11771be1c0343cb60b67ffb193fab06
2,187
java
Java
pxf/pxf-api/src/test/java/org/apache/hawq/pxf/api/MetadataTest.java
pidefrem/hawq
b82d9410f890b41d4cf608f8bfbac84db75f232e
[ "Apache-2.0" ]
450
2015-09-05T09:12:51.000Z
2018-08-30T01:45:36.000Z
pxf/pxf-api/src/test/java/org/apache/hawq/pxf/api/MetadataTest.java
pidefrem/hawq
b82d9410f890b41d4cf608f8bfbac84db75f232e
[ "Apache-2.0" ]
1,274
2015-09-22T20:06:16.000Z
2018-08-31T22:14:00.000Z
pxf/pxf-api/src/test/java/org/apache/hawq/pxf/api/MetadataTest.java
pidefrem/hawq
b82d9410f890b41d4cf608f8bfbac84db75f232e
[ "Apache-2.0" ]
278
2015-09-21T19:15:06.000Z
2018-08-31T00:36:51.000Z
35.852459
93
0.676269
1,003,119
/* * 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.hawq.pxf.api; import org.apache.hawq.pxf.api.Metadata; import org.apache.hawq.pxf.api.utilities.EnumHawqType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; public class MetadataTest { @Test public void createFieldEmptyNameType() { try { Metadata.Field field = new Metadata.Field(null, null, false, null, null); fail("Empty name, type and source type shouldn't be allowed."); } catch (IllegalArgumentException e) { assertEquals("Field name, type and source type cannot be empty", e.getMessage()); } } @Test public void createFieldNullType() { try { Metadata.Field field = new Metadata.Field("col1", null, "string"); fail("Empty name, type and source type shouldn't be allowed."); } catch (IllegalArgumentException e) { assertEquals("Field name, type and source type cannot be empty", e.getMessage()); } } @Test public void createItemEmptyNameType() { try { Metadata.Item item = new Metadata.Item(null, null); fail("Empty item name and path shouldn't be allowed."); } catch (IllegalArgumentException e) { assertEquals("Item or path name cannot be empty", e.getMessage()); } } }
9244ba3b869e149305d26c5994fca9469afe1a38
23,570
java
Java
Core/src/org/sleuthkit/autopsy/texttranslation/translators/GoogleTranslatorSettingsPanel.java
Lazza/autopsy
45d98486dcfc91f947602b0f967e94032eddbf89
[ "Apache-2.0" ]
1
2020-05-26T16:06:51.000Z
2020-05-26T16:06:51.000Z
Core/src/org/sleuthkit/autopsy/texttranslation/translators/GoogleTranslatorSettingsPanel.java
Lazza/autopsy
45d98486dcfc91f947602b0f967e94032eddbf89
[ "Apache-2.0" ]
null
null
null
Core/src/org/sleuthkit/autopsy/texttranslation/translators/GoogleTranslatorSettingsPanel.java
Lazza/autopsy
45d98486dcfc91f947602b0f967e94032eddbf89
[ "Apache-2.0" ]
null
null
null
56.658654
217
0.695715
1,003,120
/* * Autopsy * * Copyright 2019 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.texttranslation.translators; import com.google.auth.Credentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.translate.Language; import com.google.cloud.translate.Translate; import com.google.cloud.translate.TranslateOptions; import com.google.cloud.translate.Translation; import java.awt.event.ItemListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.sleuthkit.autopsy.coreutils.Logger; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import org.apache.commons.lang3.StringUtils; import org.openide.util.NbBundle.Messages; /** * Settings panel for the GoogleTranslator */ public class GoogleTranslatorSettingsPanel extends javax.swing.JPanel { private static final Logger logger = Logger.getLogger(GoogleTranslatorSettingsPanel.class.getName()); private static final String JSON_EXTENSION = "json"; private static final String DEFUALT_TEST_STRING = "traducción exitoso"; //spanish which should translate to something along the lines of "successful translation" private static final long serialVersionUID = 1L; private final ItemListener listener = new ComboBoxSelectionListener(); private String targetLanguageCode = ""; /** * Creates new form GoogleTranslatorSettingsPanel */ public GoogleTranslatorSettingsPanel(String credentialsPath, String languageCode) { initComponents(); targetLanguageCode = languageCode; credentialsPathField.setText(credentialsPath); populateTargetLanguageComboBox(); } /** * Private method to make a temporary translation service given the current * settings with unsaved settings. * * @return A Translate object which is the translation service */ @Messages({"GoogleTranslatorSettingsPanel.errorMessage.fileNotFound=Credentials file not found, please set the location to be a valid JSON credentials file.", "GoogleTranslatorSettingsPanel.errorMessage.unableToReadCredentials=Unable to read credentials from credentials file, please set the location to be a valid JSON credentials file.", "GoogleTranslatorSettingsPanel.errorMessage.unableToMakeCredentials=Unable to construct credentials object from credentials file, please set the location to be a valid JSON credentials file.", "GoogleTranslatorSettingsPanel.errorMessage.unknownFailureGetting=Failure getting list of supported languages with current credentials file.",}) private Translate getTemporaryTranslationService() { //This method also has the side effect of more or less validating the JSON file which was selected as it is necessary to get the list of target languages try { InputStream credentialStream; try { credentialStream = new FileInputStream(credentialsPathField.getText()); } catch (FileNotFoundException ignored) { warningLabel.setText(Bundle.GoogleTranslatorSettingsPanel_errorMessage_fileNotFound()); return null; } Credentials creds; try { creds = ServiceAccountCredentials.fromStream(credentialStream); } catch (IOException ignored) { warningLabel.setText(Bundle.GoogleTranslatorSettingsPanel_errorMessage_unableToMakeCredentials()); return null; } if (creds == null) { warningLabel.setText(Bundle.GoogleTranslatorSettingsPanel_errorMessage_unableToReadCredentials()); logger.log(Level.WARNING, "Credentials were not successfully made, no translations will be available from the GoogleTranslator"); return null; } else { TranslateOptions.Builder builder = TranslateOptions.newBuilder(); builder.setCredentials(creds); builder.setTargetLanguage(targetLanguageCode); //localize the list to the currently selected target language warningLabel.setText(""); //clear any previous warning text return builder.build().getService(); } } catch (Throwable throwable) { //Catching throwables because some of this Google Translate code throws throwables warningLabel.setText(Bundle.GoogleTranslatorSettingsPanel_errorMessage_unknownFailureGetting()); logger.log(Level.WARNING, "Throwable caught while getting list of supported languages", throwable); return null; } } /** * Populate the target language selection combo box */ @Messages({"GoogleTranslatorSettingsPanel.errorMessage.noFileSelected=A JSON file must be selected to provide your credentials for Google Translate.", "GoogleTranslatorSettingsPanel.errorMessage.unknownFailurePopulating=Failure populating list of supported languages with current credentials file."}) private void populateTargetLanguageComboBox() { targetLanguageComboBox.removeItemListener(listener); try { if (!StringUtils.isBlank(credentialsPathField.getText())) { List<Language> listSupportedLanguages; Translate tempService = getTemporaryTranslationService(); if (tempService != null) { listSupportedLanguages = tempService.listSupportedLanguages(); } else { listSupportedLanguages = new ArrayList<>(); } targetLanguageComboBox.removeAllItems(); if (!listSupportedLanguages.isEmpty()) { listSupportedLanguages.forEach((lang) -> { targetLanguageComboBox.addItem(new LanguageWrapper(lang)); }); selectLanguageByCode(targetLanguageCode); targetLanguageComboBox.addItemListener(listener); enableControls(true); } else { enableControls(false); } } else { warningLabel.setText(Bundle.GoogleTranslatorSettingsPanel_errorMessage_noFileSelected()); enableControls(false); } } catch (Throwable throwable) { warningLabel.setText(Bundle.GoogleTranslatorSettingsPanel_errorMessage_unknownFailurePopulating()); logger.log(Level.WARNING, "Throwable caught while populating list of supported languages", throwable); enableControls(false); } } /** * Helper method to enable/disable all controls which are dependent on valid * credentials having been provided * * @param enabled true to enable the controls, false to disable them */ private void enableControls(boolean enabled) { targetLanguageComboBox.setEnabled(enabled); testButton.setEnabled(enabled); testResultValueLabel.setEnabled(enabled); testUntranslatedTextField.setEnabled(enabled); untranslatedLabel.setEnabled(enabled); resultLabel.setEnabled(enabled); } /** * Given a language code select the corresponding language in the combo box * if it is present * * @param code language code such as "en" for English */ private void selectLanguageByCode(String code) { for (int i = 0; i < targetLanguageComboBox.getModel().getSize(); i++) { if (targetLanguageComboBox.getItemAt(i).getLanguageCode().equals(code)) { targetLanguageComboBox.setSelectedIndex(i); return; } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { credentialsLabel = new javax.swing.JLabel(); credentialsPathField = new javax.swing.JTextField(); browseButton = new javax.swing.JButton(); targetLanguageComboBox = new javax.swing.JComboBox<>(); targetLanguageLabel = new javax.swing.JLabel(); warningLabel = new javax.swing.JLabel(); testResultValueLabel = new javax.swing.JLabel(); resultLabel = new javax.swing.JLabel(); untranslatedLabel = new javax.swing.JLabel(); testUntranslatedTextField = new javax.swing.JTextField(); testButton = new javax.swing.JButton(); instructionsScrollPane = new javax.swing.JScrollPane(); instructionsTextArea = new javax.swing.JTextArea(); org.openide.awt.Mnemonics.setLocalizedText(credentialsLabel, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.credentialsLabel.text")); // NOI18N credentialsPathField.setEditable(false); credentialsPathField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { credentialsPathFieldActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(browseButton, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.browseButton.text")); // NOI18N browseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseButtonActionPerformed(evt); } }); targetLanguageComboBox.setEnabled(false); org.openide.awt.Mnemonics.setLocalizedText(targetLanguageLabel, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.targetLanguageLabel.text")); // NOI18N warningLabel.setForeground(new java.awt.Color(255, 0, 0)); org.openide.awt.Mnemonics.setLocalizedText(warningLabel, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.warningLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(testResultValueLabel, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.testResultValueLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(resultLabel, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.resultLabel.text")); // NOI18N resultLabel.setEnabled(false); org.openide.awt.Mnemonics.setLocalizedText(untranslatedLabel, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.untranslatedLabel.text")); // NOI18N untranslatedLabel.setEnabled(false); testUntranslatedTextField.setText(DEFUALT_TEST_STRING); testUntranslatedTextField.setEnabled(false); org.openide.awt.Mnemonics.setLocalizedText(testButton, org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.testButton.text")); // NOI18N testButton.setEnabled(false); testButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { testButtonActionPerformed(evt); } }); instructionsScrollPane.setBorder(javax.swing.BorderFactory.createEtchedBorder()); instructionsScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); instructionsTextArea.setEditable(false); instructionsTextArea.setBackground(new java.awt.Color(240, 240, 240)); instructionsTextArea.setColumns(20); instructionsTextArea.setLineWrap(true); instructionsTextArea.setRows(2); instructionsTextArea.setText(org.openide.util.NbBundle.getMessage(GoogleTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.instructionsTextArea.text")); // NOI18N instructionsTextArea.setWrapStyleWord(true); instructionsScrollPane.setViewportView(instructionsTextArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(instructionsScrollPane) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(warningLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 551, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(testButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(credentialsLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(targetLanguageLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(credentialsPathField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(browseButton) .addGap(14, 14, 14)) .addGroup(layout.createSequentialGroup() .addComponent(targetLanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addGap(7, 7, 7) .addComponent(untranslatedLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(testUntranslatedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(resultLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(testResultValueLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(instructionsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(credentialsLabel) .addComponent(credentialsPathField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(browseButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(targetLanguageLabel) .addComponent(targetLanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(testButton) .addComponent(testUntranslatedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(untranslatedLabel) .addComponent(resultLabel) .addComponent(testResultValueLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(warningLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents @Messages({"GoogleTranslatorSettingsPanel.json.description=JSON Files", "GoogleTranslatorSettingsPanel.fileChooser.confirmButton=Select"}) private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed JFileChooser fileChooser = new JFileChooser(); fileChooser.setDragEnabled(false); //if they previously had a path set, start navigation there if (!StringUtils.isBlank(credentialsPathField.getText())) { fileChooser.setCurrentDirectory(new File(credentialsPathField.getText()).getParentFile()); } fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileFilter(new FileNameExtensionFilter(Bundle.GoogleTranslatorSettingsPanel_json_description(), JSON_EXTENSION)); int dialogResult = fileChooser.showDialog(this, Bundle.GoogleTranslatorSettingsPanel_fileChooser_confirmButton()); if (dialogResult == JFileChooser.APPROVE_OPTION) { credentialsPathField.setText(fileChooser.getSelectedFile().getPath()); populateTargetLanguageComboBox(); testResultValueLabel.setText(""); firePropertyChange("SettingChanged", true, false); } }//GEN-LAST:event_browseButtonActionPerformed @Messages({"GoogleTranslatorSettingsPanel.errorMessage.translationFailure=Translation failure with specified credentials"}) private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButtonActionPerformed testResultValueLabel.setText(""); Translate tempTranslate = getTemporaryTranslationService(); if (tempTranslate != null) { try { Translation translation = tempTranslate.translate(testUntranslatedTextField.getText()); testResultValueLabel.setText(translation.getTranslatedText()); warningLabel.setText(""); } catch (Exception ex) { warningLabel.setText(Bundle.GoogleTranslatorSettingsPanel_errorMessage_translationFailure()); logger.log(Level.WARNING, Bundle.GoogleTranslatorSettingsPanel_errorMessage_translationFailure(), ex); } } }//GEN-LAST:event_testButtonActionPerformed private void credentialsPathFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_credentialsPathFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_credentialsPathFieldActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton browseButton; private javax.swing.JLabel credentialsLabel; private javax.swing.JTextField credentialsPathField; private javax.swing.JScrollPane instructionsScrollPane; private javax.swing.JTextArea instructionsTextArea; private javax.swing.JLabel resultLabel; private javax.swing.JComboBox<org.sleuthkit.autopsy.texttranslation.translators.LanguageWrapper> targetLanguageComboBox; private javax.swing.JLabel targetLanguageLabel; private javax.swing.JButton testButton; private javax.swing.JLabel testResultValueLabel; private javax.swing.JTextField testUntranslatedTextField; private javax.swing.JLabel untranslatedLabel; private javax.swing.JLabel warningLabel; // End of variables declaration//GEN-END:variables /** * Get the currently selected target language code * * @return the target language code of the language selected in the combobox */ String getTargetLanguageCode() { return targetLanguageCode; } /** * Get the currently set path to the JSON credentials file * * @return the path to the credentials file specified in the textarea */ String getCredentialsPath() { return credentialsPathField.getText(); } /** * Listener to identfy when a combo box item has been selected and update * the combo box to reflect that */ private class ComboBoxSelectionListener implements ItemListener { @Override public void itemStateChanged(java.awt.event.ItemEvent evt) { String selectedCode = ((LanguageWrapper) targetLanguageComboBox.getSelectedItem()).getLanguageCode(); if (!StringUtils.isBlank(selectedCode) && !selectedCode.equals(targetLanguageCode)) { targetLanguageCode = selectedCode; populateTargetLanguageComboBox(); testResultValueLabel.setText(""); firePropertyChange("SettingChanged", true, false); } } } }
9244bbb17afb919b39bfe84fb786d13d85a69364
7,728
java
Java
src/java/org/apache/cassandra/io/sstable/format/big/BigFormat.java
jthelin/cassandra
97265ddb2c6c2364b91176e1b7e170d2d8a49e37
[ "Apache-2.0" ]
4
2020-09-03T10:40:12.000Z
2022-02-10T12:49:58.000Z
src/java/org/apache/cassandra/io/sstable/format/big/BigFormat.java
jthelin/cassandra
97265ddb2c6c2364b91176e1b7e170d2d8a49e37
[ "Apache-2.0" ]
27
2020-09-01T18:24:38.000Z
2022-03-09T21:59:36.000Z
src/java/org/apache/cassandra/io/sstable/format/big/BigFormat.java
jthelin/cassandra
97265ddb2c6c2364b91176e1b7e170d2d8a49e37
[ "Apache-2.0" ]
2
2020-10-29T15:58:27.000Z
2021-08-15T23:06:07.000Z
35.612903
215
0.695782
1,003,121
/* * 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.cassandra.io.sstable.format.big; import com.google.common.collect.ImmutableList; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.AbstractCell; import org.apache.cassandra.db.ColumnSerializer; import org.apache.cassandra.db.OnDiskAtom; import org.apache.cassandra.db.RowIndexEntry; import org.apache.cassandra.db.columniterator.OnDiskAtomIterator; import org.apache.cassandra.db.compaction.AbstractCompactedRow; import org.apache.cassandra.db.compaction.CompactionController; import org.apache.cassandra.db.compaction.LazilyCompactedRow; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.io.sstable.Component; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.IndexHelper; import org.apache.cassandra.io.sstable.format.SSTableFormat; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.sstable.format.SSTableWriter; import org.apache.cassandra.io.sstable.format.Version; import org.apache.cassandra.io.sstable.metadata.MetadataCollector; import org.apache.cassandra.io.sstable.metadata.StatsMetadata; import org.apache.cassandra.io.util.FileDataInput; import java.util.Iterator; import java.util.Set; /** * Legacy bigtable format */ public class BigFormat implements SSTableFormat { public static final BigFormat instance = new BigFormat(); public static final BigVersion latestVersion = new BigVersion(BigVersion.current_version); private static final SSTableReader.Factory readerFactory = new ReaderFactory(); private static final SSTableWriter.Factory writerFactory = new WriterFactory(); private BigFormat() { } @Override public Version getLatestVersion() { return latestVersion; } @Override public Version getVersion(String version) { return new BigVersion(version); } @Override public SSTableWriter.Factory getWriterFactory() { return writerFactory; } @Override public SSTableReader.Factory getReaderFactory() { return readerFactory; } @Override public Iterator<OnDiskAtom> getOnDiskIterator(FileDataInput in, ColumnSerializer.Flag flag, int expireBefore, CFMetaData cfm, Version version) { return AbstractCell.onDiskIterator(in, flag, expireBefore, version, cfm.comparator); } @Override public AbstractCompactedRow getCompactedRowWriter(CompactionController controller, ImmutableList<OnDiskAtomIterator> onDiskAtomIterators) { return new LazilyCompactedRow(controller, onDiskAtomIterators); } @Override public RowIndexEntry.IndexSerializer getIndexSerializer(CFMetaData cfMetaData) { return new RowIndexEntry.Serializer(new IndexHelper.IndexInfo.Serializer(cfMetaData.comparator)); } static class WriterFactory extends SSTableWriter.Factory { @Override public SSTableWriter open(Descriptor descriptor, long keyCount, long repairedAt, CFMetaData metadata, IPartitioner partitioner, MetadataCollector metadataCollector) { return new BigTableWriter(descriptor, keyCount, repairedAt, metadata, partitioner, metadataCollector); } } static class ReaderFactory extends SSTableReader.Factory { @Override public SSTableReader open(Descriptor descriptor, Set<Component> components, CFMetaData metadata, IPartitioner partitioner, Long maxDataAge, StatsMetadata sstableMetadata, SSTableReader.OpenReason openReason) { return new BigTableReader(descriptor, components, metadata, partitioner, maxDataAge, sstableMetadata, openReason); } } // versions are denoted as [major][minor]. Minor versions must be forward-compatible: // new fields are allowed in e.g. the metadata component, but fields can't be removed // or have their size changed. // // Minor versions were introduced with version "hb" for Cassandra 1.0.3; prior to that, // we always incremented the major version. static class BigVersion extends Version { public static final String current_version = "lb"; public static final String earliest_supported_version = "jb"; // jb (2.0.1): switch from crc32 to adler32 for compression checksums // checksum the compressed data // ka (2.1.0): new Statistics.db file format // index summaries can be downsampled and the sampling level is persisted // switch uncompressed checksums to adler32 // tracks presense of legacy (local and remote) counter shards // la (2.2.0): new file name format // lb (2.2.7): commit log lower bound included private final boolean isLatestVersion; private final boolean hasSamplingLevel; private final boolean newStatsFile; private final boolean hasAllAdlerChecksums; private final boolean hasRepairedAt; private final boolean tracksLegacyCounterShards; private final boolean newFileName; private final boolean hasCommitLogLowerBound; public BigVersion(String version) { super(instance,version); isLatestVersion = version.compareTo(current_version) == 0; hasSamplingLevel = version.compareTo("ka") >= 0; newStatsFile = version.compareTo("ka") >= 0; hasAllAdlerChecksums = version.compareTo("ka") >= 0; hasRepairedAt = version.compareTo("ka") >= 0; tracksLegacyCounterShards = version.compareTo("ka") >= 0; newFileName = version.compareTo("la") >= 0; hasCommitLogLowerBound = version.compareTo("lb") >= 0; } @Override public boolean isLatestVersion() { return isLatestVersion; } @Override public boolean hasSamplingLevel() { return hasSamplingLevel; } @Override public boolean hasNewStatsFile() { return newStatsFile; } @Override public boolean hasAllAdlerChecksums() { return hasAllAdlerChecksums; } @Override public boolean hasRepairedAt() { return hasRepairedAt; } @Override public boolean tracksLegacyCounterShards() { return tracksLegacyCounterShards; } @Override public boolean hasNewFileName() { return newFileName; } public boolean hasCommitLogLowerBound() { return hasCommitLogLowerBound; } @Override public boolean isCompatible() { return version.compareTo(earliest_supported_version) >= 0 && version.charAt(0) <= current_version.charAt(0); } } }
9244bc92c99d44a3282498a76f83ca89f961efd4
6,078
java
Java
CM5/Core/gui-client-impl/src/main/java/ru/intertrust/cm/core/gui/impl/client/plugins/collection/CollectionColumn.java
InterTurstCo/ActiveFrame5
a042afd5297be9636656701e502918bdbd63ce80
[ "Apache-2.0" ]
4
2019-11-24T14:14:05.000Z
2021-03-30T14:35:30.000Z
CM5/Core/gui-client-impl/src/main/java/ru/intertrust/cm/core/gui/impl/client/plugins/collection/CollectionColumn.java
InterTurstCo/ActiveFrame5
a042afd5297be9636656701e502918bdbd63ce80
[ "Apache-2.0" ]
4
2019-11-20T14:05:11.000Z
2021-12-06T16:59:54.000Z
CM5/Core/gui-client-impl/src/main/java/ru/intertrust/cm/core/gui/impl/client/plugins/collection/CollectionColumn.java
InterTurstCo/ActiveFrame5
a042afd5297be9636656701e502918bdbd63ce80
[ "Apache-2.0" ]
2
2019-12-26T15:19:53.000Z
2022-03-27T11:01:41.000Z
30.852792
166
0.643468
1,003,122
package ru.intertrust.cm.core.gui.impl.client.plugins.collection; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.dom.client.*; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.client.Window; import com.google.web.bindery.event.shared.EventBus; import ru.intertrust.cm.core.gui.impl.client.event.collection.CollectionAddElementEvent; import ru.intertrust.cm.core.gui.impl.client.event.collection.CollectionAddGroupEvent; import ru.intertrust.cm.core.gui.impl.client.event.collection.CollectionRowFilteredEvent; import ru.intertrust.cm.core.gui.impl.client.event.collection.CollectionRowStateChangedEvent; import ru.intertrust.cm.core.gui.impl.client.util.BusinessUniverseConstants; import ru.intertrust.cm.core.gui.model.plugin.collection.CollectionRowItem; import java.util.Arrays; /** * @author Denis Mitavskiy * Date: 21.01.14 * Time: 22:59 */ public abstract class CollectionColumn<T> extends Column<CollectionRowItem, T> { protected String fieldName; protected boolean resizable = true; private int userWidth; protected int minWidth; protected int maxWidth = BusinessUniverseConstants.MAX_COLUMN_WIDTH; protected boolean moveable = true; protected boolean visible; protected int drawWidth; protected EventBus eventBus; public CollectionColumn(AbstractCell cell) { super(cell); } public CollectionColumn(AbstractCell cell, String fieldName, EventBus eventBus, boolean resizable) { super(cell); this.fieldName = fieldName; this.eventBus = eventBus; this.resizable = resizable; } public String getFieldName() { return fieldName; } public Boolean isResizable() { return resizable; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public void setResizable(Boolean resizable) { this.resizable = resizable; } public int getUserWidth() { return userWidth; } public void setUserWidth(int userWidth) { this.userWidth = userWidth; } public int getMinWidth() { return minWidth == 0 ? BusinessUniverseConstants.MIN_RESIZE_COLUMN_WIDTH : minWidth; } public void setMinWidth(Integer minWidth) { this.minWidth = minWidth; } public int getMaxWidth() { return maxWidth; } public void setMaxWidth(Integer maxWidth) { this.maxWidth = maxWidth; } public boolean isMoveable() { return moveable; } public void setMoveable(boolean moveable) { this.moveable = moveable; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public int getDrawWidth() { return drawWidth; } public void setDrawWidth(int drawWidth) { this.drawWidth = drawWidth; } @Override public void onBrowserEvent(Cell.Context context, Element target, ru.intertrust.cm.core.gui.model.plugin.collection.CollectionRowItem rowItem, NativeEvent event) { String type = event.getType(); int keyCode = event.getKeyCode(); EventTarget eventTarget = event.getEventTarget(); Element element = Element.as(eventTarget); if (BrowserEvents.CLICK.equals(type)) { if (element.getClassName().startsWith("expandSign")) { eventBus.fireEvent(new CollectionRowStateChangedEvent(rowItem,true)); }else if(element.getClassName().startsWith("collapseSign")){ eventBus.fireEvent(new CollectionRowStateChangedEvent(rowItem, false)); } else if(element.getClassName().startsWith("createElement")){ eventBus.fireEvent(new CollectionAddElementEvent(rowItem, false)); } else if(element.getClassName().startsWith("createGroup")){ eventBus.fireEvent(new CollectionAddGroupEvent(rowItem, false)); } else if(element.getClassName().startsWith("actionCollectionColumn")){ performAction(context); } else { super.onBrowserEvent(context, target, rowItem, event); } }else if(BrowserEvents.KEYDOWN.equalsIgnoreCase(type) && KeyCodes.KEY_ENTER == keyCode && element.getClassName() .startsWith("hierarchicalFilterInput")){ String text = getInputElement(element).getValue(); rowItem.putFilterValues("name", Arrays.asList(text)); eventBus.fireEvent(new CollectionRowFilteredEvent(rowItem)); } else { super.onBrowserEvent(context, target, rowItem, event); } } private InputElement getInputElement(Element parent) { return parent.<InputElement> cast(); } protected void performAction(Cell.Context context){} @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CollectionColumn)) { return false; } CollectionColumn that = (CollectionColumn) o; if (maxWidth != that.maxWidth) { return false; } if (minWidth != that.minWidth) { return false; } if (moveable != that.moveable) { return false; } if (resizable != that.resizable) { return false; } if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { return false; } return true; } @Override public int hashCode() { int result = fieldName != null ? fieldName.hashCode() : 0; result = 31 * result + (resizable ? 1 : 0); result = 31 * result + minWidth; result = 31 * result + maxWidth; result = 31 * result + (moveable ? 1 : 0); return result; } }
9244bcc996cf20f826066643a8d34e4e234d9ac5
5,389
java
Java
src/test/java/com/rbkmoney/xrates/exchange/provider/CbrExchangeProviderTest.java
rbkmoney/xrates
f8afd021d397c743dbf1d06dbdb9d4c1647213d6
[ "Apache-2.0" ]
2
2020-03-21T06:56:09.000Z
2020-03-21T07:32:25.000Z
src/test/java/com/rbkmoney/xrates/exchange/provider/CbrExchangeProviderTest.java
rbkmoney/xrates
f8afd021d397c743dbf1d06dbdb9d4c1647213d6
[ "Apache-2.0" ]
null
null
null
src/test/java/com/rbkmoney/xrates/exchange/provider/CbrExchangeProviderTest.java
rbkmoney/xrates
f8afd021d397c743dbf1d06dbdb9d4c1647213d6
[ "Apache-2.0" ]
3
2020-03-20T09:58:17.000Z
2022-02-17T07:57:44.000Z
40.825758
111
0.595843
1,003,123
package com.rbkmoney.xrates.exchange.provider; import com.rbkmoney.xrates.domain.ExchangeRate; import com.rbkmoney.xrates.exception.ProviderUnavailableResultException; import com.rbkmoney.xrates.exchange.ExchangeProvider; import com.rbkmoney.xrates.exchange.impl.provider.cbr.CbrExchangeProvider; import com.rbkmoney.xrates.exchange.impl.provider.cbr.adapter.CbrLocalDateXmlAdapter; import org.joda.money.CurrencyUnit; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import static org.junit.Assert.assertEquals; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; public class CbrExchangeProviderTest { private RestTemplate restTemplate = new RestTemplate(); private MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build(); @Test public void testWithValidData() { String currencyCode = "AUD"; String valueString = "47.33523232"; LocalDate date = LocalDate.now(); mockServer.expect( requestTo(CbrExchangeProvider.DEFAULT_ENDPOINT + "?date_req=" + CbrExchangeProvider.DATE_TIME_FORMATTER.format(date)) ).andRespond( withSuccess( "<ValCurs Date=\"" + CbrLocalDateXmlAdapter.DATE_FORMATTER.format(date) + "\" name=\"Foreign Currency Market\">\n" + "<Valute ID=\"R01010\">\n" + "<NumCode>036</NumCode>\n" + "<CharCode>" + currencyCode + "</CharCode>\n" + "<Nominal>1</Nominal>\n" + "<Name>Австралийский доллар</Name>\n" + "<Value>" + valueString + "</Value>\n" + "</Valute>" + "</ValCurs>", MediaType.parseMediaType("application/xml; charset=windows-1251") ) ); ExchangeProvider exchangeProvider = new CbrExchangeProvider(restTemplate); List<ExchangeRate> exchangeRates = exchangeProvider.getExchangeRates( date.atStartOfDay() .atZone(CbrExchangeProvider.DEFAULT_TIMEZONE) .toInstant() ); assertEquals(1, exchangeRates.size()); ExchangeRate exchangeRate = exchangeRates.get(0); assertEquals(CurrencyUnit.of(currencyCode), exchangeRate.getSourceCurrency()); assertEquals(CbrExchangeProvider.DESTINATION_CURRENCY_UNIT, exchangeRate.getDestinationCurrency()); assertEquals(new BigDecimal(valueString), exchangeRate.getConversionRate()); mockServer.verify(); } @Test(expected = ProviderUnavailableResultException.class) public void testWhenReturnError() { LocalDate date = LocalDate.now(); mockServer.expect(requestTo(buildExpectedUrl(date))) .andRespond( withServerError() ); try { ExchangeProvider exchangeProvider = new CbrExchangeProvider(restTemplate); exchangeProvider.getExchangeRates( date.atStartOfDay() .atZone(CbrExchangeProvider.DEFAULT_TIMEZONE) .toInstant() ); } finally { mockServer.verify(); } } @Test(expected = ProviderUnavailableResultException.class) public void testWithEmptyData() { LocalDate date = LocalDate.now(); mockServer.expect(requestTo(buildExpectedUrl(date))) .andRespond( withSuccess() .contentType(MediaType.parseMediaType("application/xml; charset=windows-1251")) .body( "<ValCurs Date=\"" + CbrLocalDateXmlAdapter.DATE_FORMATTER.format(date) + "\" name=\"Foreign Currency Market\"></ValCurs>" ) ); try { ExchangeProvider exchangeProvider = new CbrExchangeProvider(restTemplate); providerRequest(exchangeProvider, date); } finally { mockServer.verify(); } } private String buildExpectedUrl(LocalDate date) { return CbrExchangeProvider.DEFAULT_ENDPOINT + "?date_req=" + CbrExchangeProvider.DATE_TIME_FORMATTER.format(date); } private List<ExchangeRate> providerRequest(ExchangeProvider exchangeProvider, LocalDate date) { return exchangeProvider.getExchangeRates( date.atStartOfDay() .atZone(CbrExchangeProvider.DEFAULT_TIMEZONE) .toInstant() ); } }
9244be426fe794dbf17d5508a0d7d798fa310ac6
7,597
java
Java
selenium_automation/products/wso2_IS/GoogleAppCBUrlUpdate/src/test/java/com/wso2/iamtest/GoogleWebAppUpdateHL.java
rmsamitha/wso2-qa-artifacts
c0a5ff78e40a62a1cf86c8f39aae2149f5112f86
[ "Apache-2.0" ]
7
2015-04-30T08:47:55.000Z
2022-02-17T14:21:19.000Z
selenium_automation/products/wso2_IS/GoogleAppCBUrlUpdate/src/test/java/com/wso2/iamtest/GoogleWebAppUpdateHL.java
rmsamitha/wso2-qa-artifacts
c0a5ff78e40a62a1cf86c8f39aae2149f5112f86
[ "Apache-2.0" ]
62
2015-08-31T04:30:09.000Z
2018-04-04T15:15:30.000Z
selenium_automation/products/wso2_IS/GoogleAppCBUrlUpdate/src/test/java/com/wso2/iamtest/GoogleWebAppUpdateHL.java
rmsamitha/wso2-qa-artifacts
c0a5ff78e40a62a1cf86c8f39aae2149f5112f86
[ "Apache-2.0" ]
85
2015-03-24T11:34:28.000Z
2020-09-11T10:48:55.000Z
41.513661
129
0.69488
1,003,124
/** * @Author: [email protected] * @Status: In-progress */ package com.wso2.iamtest; import java.awt.*; import java.awt.event.KeyEvent; import java.io.PrintWriter; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlPage; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.*; import static org.testng.Assert.*; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class GoogleWebAppUpdateHL { private WebDriver driver; //private HtmlUnitDriver driver; private String baseUrl; //PhantomJSDriver driver1; private boolean acceptNextAlert = true; private StringBuffer verificationErrors = new StringBuffer(); @BeforeClass(alwaysRun = true) public void setUp() throws Exception { //driver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER, true); baseUrl = "https://console.developers.google.com"; DesiredCapabilities caps = new DesiredCapabilities(); caps.setJavascriptEnabled(true); caps.setCapability("takesScreenshot", true); caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/Users/cjayawardena/Documents/Testing/workspace_idea/GoogleAppCBUrlUpdate/src/test/resources/phantomjs"); driver = new PhantomJSDriver(caps); driver.manage().window().maximize(); //driver.setJavascriptEnabled(true); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } @Parameters({"username","password","callbackUrl", "clientAppName"}) @Test public void testUntitledTestCase(String username, String password, String callbackUrl, String clientAppName) throws Exception { /*WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER); HtmlPage page = client.getPage(baseUrl+"/"); page.getHtmlElementById("identifierId").type(username)*/; driver.get(baseUrl+"/"); WebDriverWait wait = new WebDriverWait(driver,20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("identifierId"))); driver.findElement(By.id("identifierId")).clear(); driver.findElement(By.id("identifierId")).sendKeys(password); System.out.println(driver.switchTo().activeElement().getTagName()+"============="); //driver.findElement(By.id("identifierId")).sendKeys(Keys.ENTER); //driver.findElement(By.xpath("//div[@id='identifierNext']/content")).click(); //page.getHtmlElementById("identifierNext").click(); Actions builder = new Actions(driver); WebElement link = driver.findElement(By.xpath("//div[@id='identifierNext']")); if(link.isDisplayed()){ System.out.println("VISBLE-========"); } //driver.switchTo().activeElement().sendKeys(Keys.ENTER); System.out.println(driver.switchTo().activeElement().getTagName()+"============="); //driver.switchTo().activeElement().submit(); //builder.moveToElement(link).click().perform(); builder.moveToElement(link).contextClick().build().perform(); builder.sendKeys(Keys.ENTER).click().perform(); builder.release().perform(); //link.sendKeys(Keys.ENTER); Thread.sleep(2000); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h1[@id='headingText']"))); System.out.println(driver.switchTo().activeElement().getTagName()+"============="); //Robot rbt = new Robot(); //rbt.keyPress(KeyEvent.VK_ENTER); //rbt.keyRelease(KeyEvent.VK_ENTER); //((JavascriptExecutor)driver).executeScript("document.getElementById('identifierNext').click()"); //((JavascriptExecutor)driver).executeScript(mouseOverScript, link); //((JavascriptExecutor)driver).executeScript(onClickScript, link); //JavascriptExecutor executor = (JavascriptExecutor)driver; //executor.executeScript("arguments[0].click();", link); //executor.executeScript("window.document.getElementById('identifierNext').click()"); //executor.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", link); //Thread.sleep(3000); if(driver.findElement(By.xpath("//h1[@id='headingText']")).getText().equalsIgnoreCase("Welcome")){ System.out.println("Welcome displayed====="); if(driver.findElement(By.xpath("//div[@id='profileIdentifier']")).getText().equalsIgnoreCase(username)){ System.out.println("email exist========"); } } //System.out.print("URL :" + driver.getPageSource().toString()); PrintWriter out = new PrintWriter("filename.txt"); //driver.findElement(By.xpath("//span[text()='Next']")).click(); out.println(driver.getPageSource().toString()); out.close(); // out.println(driver.getPageSource().toString()); //page.getElementByName("password").setTextContent(password); driver.findElement(By.name("password")).clear(); driver.findElement(By.name("password")).sendKeys(password); // page.getHtmlElementById("passwordNext").click(); driver.findElement(By.xpath("//div[@id='passwordNext']/content/span")).click(); driver.findElement(By.xpath("//a[@id='p6ntest-vulcan-leftnav-credentials']/span")).click(); driver.findElement(By.linkText("Web client 2")).click(); Thread.sleep(3000); builder.sendKeys(Keys.TAB).perform(); builder.sendKeys(Keys.TAB).perform(); builder.sendKeys(Keys.DELETE).perform(); WebElement elm = driver.switchTo().activeElement(); elm.sendKeys("http://localhost:8080/selenium"); builder.sendKeys(Keys.ENTER).perform(); builder.sendKeys(Keys.TAB).perform(); builder.sendKeys(Keys.ENTER).perform(); //if(driver.findElement(By.xpath("span[text()='http://localhost:8080/new']")).isDisplayed()){ // System.out.println("TestValsu==="); //} //driver.findElement(By.xpath("//fieldset[2]/div/div/ng-form/ul/li/span")).click(); //driver.findElement(By.xpath("//fieldset[2]/div/div/ng-form/ul/li/span")).clear(); //driver.findElement(By.xpath("//fieldset[2]/div/div/ng-form/ul/li/span")).sendKeys("http://localhost:8080/selenium"); Thread.sleep(5000); } @AfterClass(alwaysRun = true) public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } private boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } } }
9244be4dc412dc0071f356d780ad70a23f097d97
1,350
java
Java
ServletExhibitions/src/main/java/ua/project/model/dao/mapper/TicketMapper.java
Nickeron-dev/FinalProject-ServletExhibitions
f5baec6715cfc619027811c499571592359e0a24
[ "Apache-2.0" ]
null
null
null
ServletExhibitions/src/main/java/ua/project/model/dao/mapper/TicketMapper.java
Nickeron-dev/FinalProject-ServletExhibitions
f5baec6715cfc619027811c499571592359e0a24
[ "Apache-2.0" ]
null
null
null
ServletExhibitions/src/main/java/ua/project/model/dao/mapper/TicketMapper.java
Nickeron-dev/FinalProject-ServletExhibitions
f5baec6715cfc619027811c499571592359e0a24
[ "Apache-2.0" ]
null
null
null
32.142857
86
0.688148
1,003,125
package ua.project.model.dao.mapper; import ua.project.model.entity.Ticket; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; /** * @author Illia Koshkin */ public class TicketMapper implements ObjectMapper<Ticket> { /** * This method takes Ticket from a ResultSet * @param resultSet ResultSet of an SQL statement * @return Ticket object * @throws SQLException if nothing was found */ @Override public Ticket extractFromResultSet(ResultSet resultSet) throws SQLException { Ticket ticket = new Ticket(); ticket.setId(resultSet.getInt("id")); ticket.setExhibitionTopic(resultSet.getString("exhibitionTopic")); ticket.setExhibitionId(Integer.parseInt(resultSet.getString("exhibitionId"))); ticket.setUserEmail(resultSet.getString("userEmail")); ticket.setUserId(Integer.parseInt(resultSet.getString("userId"))); return ticket; } /** * Removes all repeated values * @param cache Map with tickets * @param ticket Object of a ticket that will be put if absent * @return Ticket from Map with the same id */ @Override public Ticket makeUnique(Map<Integer, Ticket> cache, Ticket ticket) { cache.putIfAbsent(ticket.getId(), ticket); return cache.get(ticket.getId()); } }
9244be752dd96166947de6d8c780bb1c20666191
2,743
java
Java
deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/BaseLayerTest.java
renatoh/deeplearning4j
aaef2ad5dc216df2676e23b8bb0b70347d0f91ff
[ "Apache-2.0" ]
2
2020-10-07T18:23:06.000Z
2021-06-13T16:17:28.000Z
deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/BaseLayerTest.java
renatoh/deeplearning4j
aaef2ad5dc216df2676e23b8bb0b70347d0f91ff
[ "Apache-2.0" ]
2
2021-08-02T17:25:42.000Z
2021-08-02T17:25:49.000Z
deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/BaseLayerTest.java
renatoh/deeplearning4j
aaef2ad5dc216df2676e23b8bb0b70347d0f91ff
[ "Apache-2.0" ]
2
2021-03-23T03:19:31.000Z
2021-06-03T09:56:01.000Z
31.528736
103
0.671163
1,003,126
package org.deeplearning4j.nn.layers; import org.deeplearning4j.nn.api.Layer; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.layers.ConvolutionLayer; import org.deeplearning4j.nn.conf.layers.DenseLayer; import org.deeplearning4j.nn.conf.layers.OutputLayer; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.junit.Before; import org.junit.Test; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; /** * Created by nyghtowl on 11/15/15. */ public class BaseLayerTest { protected INDArray weight = Nd4j.create(new double[] {0.10, -0.20, -0.15, 0.05}, new int[] {2, 2}); protected INDArray bias = Nd4j.create(new double[] {0.5, 0.5}, new int[] {1, 2}); protected Map<String, INDArray> paramTable; @Before public void doBefore() { paramTable = new HashMap<>(); paramTable.put("W", weight); paramTable.put("b", bias); } @Test public void testSetExistingParamsConvolutionSingleLayer() { Layer layer = configureSingleLayer(); assertNotEquals(paramTable, layer.paramTable()); layer.setParamTable(paramTable); assertEquals(paramTable, layer.paramTable()); } @Test public void testSetExistingParamsDenseMultiLayer() { MultiLayerNetwork net = configureMultiLayer(); for (Layer layer : net.getLayers()) { assertNotEquals(paramTable, layer.paramTable()); layer.setParamTable(paramTable); assertEquals(paramTable, layer.paramTable()); } } public Layer configureSingleLayer() { int nIn = 2; int nOut = 2; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .layer(new ConvolutionLayer.Builder().nIn(nIn).nOut(nOut).build()).build(); int numParams = conf.getLayer().initializer().numParams(conf); INDArray params = Nd4j.create(1, numParams); return conf.getLayer().instantiate(conf, null, 0, params, true); } public MultiLayerNetwork configureMultiLayer() { int nIn = 2; int nOut = 2; MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder().list() .layer(0, new DenseLayer.Builder().nIn(nIn).nOut(nOut).build()) .layer(1, new OutputLayer.Builder().nIn(nIn).nOut(nOut).build()).build(); MultiLayerNetwork net = new MultiLayerNetwork(conf); net.init(); return net; } }
9244bfe759843ed78c87ee97e8108b16b714acc4
2,879
java
Java
src/main/java/org/nnsoft/trudeau/coloring/UncoloredOrderedNodes.java
trudeau/coloring
d991db21df220adbcf83418d287a09203eee888f
[ "Apache-2.0" ]
null
null
null
src/main/java/org/nnsoft/trudeau/coloring/UncoloredOrderedNodes.java
trudeau/coloring
d991db21df220adbcf83418d287a09203eee888f
[ "Apache-2.0" ]
null
null
null
src/main/java/org/nnsoft/trudeau/coloring/UncoloredOrderedNodes.java
trudeau/coloring
d991db21df220adbcf83418d287a09203eee888f
[ "Apache-2.0" ]
1
2018-09-24T16:55:26.000Z
2018-09-24T16:55:26.000Z
23.991667
91
0.518235
1,003,127
package org.nnsoft.trudeau.coloring; /* * Copyright 2013 - 2018 The Trudeau Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; /** * * * @param <N> */ final class UncoloredOrderedNodes<N> implements Comparator<Integer>, Iterable<N> { private final Map<Integer, Set<N>> orderedNodes = new TreeMap<Integer, Set<N>>( this ); public void addVertexDegree( N n, Integer degree ) { Set<N> nodes = orderedNodes.get( degree ); if ( nodes == null ) { nodes = new HashSet<N>(); } nodes.add( n ); orderedNodes.put( degree, nodes ); } /** * {@inheritDoc} */ public int compare( Integer o1, Integer o2 ) { return o2.compareTo( o1 ); } public Iterator<N> iterator() { return new Iterator<N>() { private Iterator<Integer> keys = orderedNodes.keySet().iterator(); private Iterator<N> pending = null; private N next = null; public boolean hasNext() { if ( next != null ) { return true; } while ( ( pending == null ) || !pending.hasNext() ) { if ( !keys.hasNext() ) { return false; } pending = orderedNodes.get( keys.next() ).iterator(); } next = pending.next(); return true; } public N next() { if ( !hasNext() ) { throw new NoSuchElementException(); } N returned = next; next = null; return returned; } public void remove() { pending.remove(); } }; } /** * Returns the number of nodes degrees in the graph. * * @return the number of nodes degrees in the graph. */ public int size() { return orderedNodes.size(); } }
9244c12270a6250c446d3698346c4da47d4701cb
22,285
java
Java
classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/print/attribute/AttributeSetUtilities.java
Suyashtnt/Bytecoder
d957081d50f2d30b3206447b805b1ca9da69c8c2
[ "Apache-2.0" ]
543
2017-06-14T14:53:33.000Z
2022-03-23T14:18:09.000Z
classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/print/attribute/AttributeSetUtilities.java
Suyashtnt/Bytecoder
d957081d50f2d30b3206447b805b1ca9da69c8c2
[ "Apache-2.0" ]
381
2017-10-31T14:29:54.000Z
2022-03-25T15:27:27.000Z
classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/print/attribute/AttributeSetUtilities.java
Suyashtnt/Bytecoder
d957081d50f2d30b3206447b805b1ca9da69c8c2
[ "Apache-2.0" ]
50
2018-01-06T12:35:14.000Z
2022-03-13T14:54:33.000Z
33.112927
80
0.638681
1,003,128
/* * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.print.attribute; import java.io.Serial; import java.io.Serializable; /** * Class {@code AttributeSetUtilities} provides static methods for manipulating * {@code AttributeSets}. * <ul> * <li>Methods for creating unmodifiable and synchronized views of attribute * sets. * <li>operations useful for building implementations of interface * {@link AttributeSet AttributeSet} * </ul> * An <b>unmodifiable view</b> <i>U</i> of an {@code AttributeSet} <i>S</i> * provides a client with "read-only" access to <i>S</i>. Query operations on * <i>U</i> "read through" to <i>S</i>; thus, changes in <i>S</i> are reflected * in <i>U</i>. However, any attempt to modify <i>U</i>, results in an * {@code UnmodifiableSetException}. The unmodifiable view object <i>U</i> will * be serializable if the attribute set object <i>S</i> is serializable. * <p> * A <b>synchronized view</b> <i>V</i> of an attribute set <i>S</i> provides a * client with synchronized (multiple thread safe) access to <i>S</i>. Each * operation of <i>V</i> is synchronized using <i>V</i> itself as the lock * object and then merely invokes the corresponding operation of <i>S</i>. In * order to guarantee mutually exclusive access, it is critical that all access * to <i>S</i> is accomplished through <i>V</i>. The synchronized view object * <i>V</i> will be serializable if the attribute set object <i>S</i> is * serializable. * <p> * As mentioned in the package description of {@code javax.print}, a * {@code null} reference parameter to methods is incorrect unless explicitly * documented on the method as having a meaningful interpretation. Usage to the * contrary is incorrect coding and may result in a run time exception either * immediately or at some later time. {@code IllegalArgumentException} and * {@code NullPointerException} are examples of typical and acceptable run time * exceptions for such cases. * * @author Alan Kaminsky */ public final class AttributeSetUtilities { /** * Suppress default constructor, ensuring non-instantiability. */ private AttributeSetUtilities() { } /** * Unmodifiable view of {@code AttributeSet}. * * @serial include */ private static class UnmodifiableAttributeSet implements AttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = -6131802583863447813L; /** * The attribute set. */ @SuppressWarnings("serial") // Not statically typed as Serializable private AttributeSet attrset; /** * Constructs unmodifiable view of the underlying attribute set. * * @param attributeSet the attribute set */ public UnmodifiableAttributeSet(AttributeSet attributeSet) { attrset = attributeSet; } public Attribute get(Class<?> key) { return attrset.get(key); } public boolean add(Attribute attribute) { throw new UnmodifiableSetException(); } public synchronized boolean remove(Class<?> category) { throw new UnmodifiableSetException(); } public boolean remove(Attribute attribute) { throw new UnmodifiableSetException(); } public boolean containsKey(Class<?> category) { return attrset.containsKey(category); } public boolean containsValue(Attribute attribute) { return attrset.containsValue(attribute); } public boolean addAll(AttributeSet attributes) { throw new UnmodifiableSetException(); } public int size() { return attrset.size(); } public Attribute[] toArray() { return attrset.toArray(); } public void clear() { throw new UnmodifiableSetException(); } public boolean isEmpty() { return attrset.isEmpty(); } public boolean equals(Object o) { return attrset.equals (o); } public int hashCode() { return attrset.hashCode(); } } /** * Unmodifiable view of {@code DocAttributeSet}. * * @serial include */ private static class UnmodifiableDocAttributeSet extends UnmodifiableAttributeSet implements DocAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = -6349408326066898956L; /** * Constructs a new unmodifiable doc attribute set. * * @param attributeSet the doc attribute set */ public UnmodifiableDocAttributeSet(DocAttributeSet attributeSet) { super (attributeSet); } } /** * Unmodifiable view of {@code PrintRequestAttributeSet}. * * @serial include */ private static class UnmodifiablePrintRequestAttributeSet extends UnmodifiableAttributeSet implements PrintRequestAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = 7799373532614825073L; /** * Constructs a new unmodifiable print request attribute set. * * @param attributeSet the print request attribute set */ public UnmodifiablePrintRequestAttributeSet (PrintRequestAttributeSet attributeSet) { super (attributeSet); } } /** * Unmodifiable view of {@code PrintJobAttributeSet}. * * @serial include */ private static class UnmodifiablePrintJobAttributeSet extends UnmodifiableAttributeSet implements PrintJobAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = -8002245296274522112L; /** * Constructs a new unmodifiable print job attribute set. * * @param attributeSet the print job attribute set */ public UnmodifiablePrintJobAttributeSet (PrintJobAttributeSet attributeSet) { super (attributeSet); } } /** * Unmodifiable view of {@code PrintServiceAttributeSet}. * * @serial include */ private static class UnmodifiablePrintServiceAttributeSet extends UnmodifiableAttributeSet implements PrintServiceAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = -7112165137107826819L; /** * Constructs a new unmodifiable print service attribute set. * * @param attributeSet the print service attribute set */ public UnmodifiablePrintServiceAttributeSet (PrintServiceAttributeSet attributeSet) { super (attributeSet); } } /** * Creates an unmodifiable view of the given attribute set. * * @param attributeSet underlying attribute set * @return unmodifiable view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static AttributeSet unmodifiableView(AttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new UnmodifiableAttributeSet(attributeSet); } /** * Creates an unmodifiable view of the given doc attribute set. * * @param attributeSet underlying doc attribute set * @return unmodifiable view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static DocAttributeSet unmodifiableView (DocAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new UnmodifiableDocAttributeSet(attributeSet); } /** * Creates an unmodifiable view of the given print request attribute set. * * @param attributeSet underlying print request attribute set * @return unmodifiable view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static PrintRequestAttributeSet unmodifiableView(PrintRequestAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new UnmodifiablePrintRequestAttributeSet(attributeSet); } /** * Creates an unmodifiable view of the given print job attribute set. * * @param attributeSet underlying print job attribute set * @return unmodifiable view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static PrintJobAttributeSet unmodifiableView(PrintJobAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new UnmodifiablePrintJobAttributeSet(attributeSet); } /** * Creates an unmodifiable view of the given print service attribute set. * * @param attributeSet underlying print service attribute set * @return unmodifiable view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static PrintServiceAttributeSet unmodifiableView(PrintServiceAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new UnmodifiablePrintServiceAttributeSet (attributeSet); } /** * Synchronized view of {@code AttributeSet}. * * @serial include */ private static class SynchronizedAttributeSet implements AttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = 8365731020128564925L; /** * The attribute set. */ @SuppressWarnings("serial") // Not statically typed as Serializable private AttributeSet attrset; /** * Constructs a new synchronized attribute set. * * @param attributeSet the attribute set */ public SynchronizedAttributeSet(AttributeSet attributeSet) { attrset = attributeSet; } public synchronized Attribute get(Class<?> category) { return attrset.get(category); } public synchronized boolean add(Attribute attribute) { return attrset.add(attribute); } public synchronized boolean remove(Class<?> category) { return attrset.remove(category); } public synchronized boolean remove(Attribute attribute) { return attrset.remove(attribute); } public synchronized boolean containsKey(Class<?> category) { return attrset.containsKey(category); } public synchronized boolean containsValue(Attribute attribute) { return attrset.containsValue(attribute); } public synchronized boolean addAll(AttributeSet attributes) { return attrset.addAll(attributes); } public synchronized int size() { return attrset.size(); } public synchronized Attribute[] toArray() { return attrset.toArray(); } public synchronized void clear() { attrset.clear(); } public synchronized boolean isEmpty() { return attrset.isEmpty(); } public synchronized boolean equals(Object o) { return attrset.equals (o); } public synchronized int hashCode() { return attrset.hashCode(); } } /** * Synchronized view of {@code DocAttributeSet}. * * @serial include */ private static class SynchronizedDocAttributeSet extends SynchronizedAttributeSet implements DocAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = 6455869095246629354L; /** * Constructs a new synchronized doc attribute set. * * @param attributeSet the doc attribute set */ public SynchronizedDocAttributeSet(DocAttributeSet attributeSet) { super(attributeSet); } } /** * Synchronized view of {@code PrintRequestAttributeSet}. * * @serial include */ private static class SynchronizedPrintRequestAttributeSet extends SynchronizedAttributeSet implements PrintRequestAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = 5671237023971169027L; /** * Constructs a new synchronized print request attribute set. * * @param attributeSet the print request attribute set */ public SynchronizedPrintRequestAttributeSet (PrintRequestAttributeSet attributeSet) { super(attributeSet); } } /** * Synchronized view of {@code PrintJobAttributeSet}. * * @serial include */ private static class SynchronizedPrintJobAttributeSet extends SynchronizedAttributeSet implements PrintJobAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = 2117188707856965749L; /** * Constructs a new synchronized print job attribute set. * * @param attributeSet the print job attribute set */ public SynchronizedPrintJobAttributeSet (PrintJobAttributeSet attributeSet) { super(attributeSet); } } /** * Synchronized view of {@code PrintServiceAttributeSet}. * * @serial include */ private static class SynchronizedPrintServiceAttributeSet extends SynchronizedAttributeSet implements PrintServiceAttributeSet, Serializable { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = -2830705374001675073L; /** * Constructs a new synchronized print service attribute set. * * @param attributeSet the print service attribute set */ public SynchronizedPrintServiceAttributeSet (PrintServiceAttributeSet attributeSet) { super(attributeSet); } } /** * Creates a synchronized view of the given attribute set. * * @param attributeSet underlying attribute set * @return synchronized view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static AttributeSet synchronizedView (AttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new SynchronizedAttributeSet(attributeSet); } /** * Creates a synchronized view of the given doc attribute set. * * @param attributeSet underlying doc attribute set * @return synchronized view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static DocAttributeSet synchronizedView(DocAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new SynchronizedDocAttributeSet(attributeSet); } /** * Creates a synchronized view of the given print request attribute set. * * @param attributeSet underlying print request attribute set * @return synchronized view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static PrintRequestAttributeSet synchronizedView(PrintRequestAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new SynchronizedPrintRequestAttributeSet(attributeSet); } /** * Creates a synchronized view of the given print job attribute set. * * @param attributeSet underlying print job attribute set * @return synchronized view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static PrintJobAttributeSet synchronizedView(PrintJobAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new SynchronizedPrintJobAttributeSet(attributeSet); } /** * Creates a synchronized view of the given print service attribute set. * * @param attributeSet underlying print service attribute set * @return synchronized view of {@code attributeSet} * @throws NullPointerException if {@code attributeSet} is {@code null} */ public static PrintServiceAttributeSet synchronizedView(PrintServiceAttributeSet attributeSet) { if (attributeSet == null) { throw new NullPointerException(); } return new SynchronizedPrintServiceAttributeSet(attributeSet); } /** * Verify that the given object is a {@link Class Class} that implements the * given interface, which is assumed to be interface * {@link Attribute Attribute} or a subinterface thereof. * * @param object {@code Object} to test * @param interfaceName interface the object must implement * @return if {@code object} is a {@link Class Class} that implements * {@code interfaceName}, {@code object} is returned downcast to * type {@link Class Class}; otherwise an exception is thrown * @throws NullPointerException if {@code object} is {@code null} * @throws ClassCastException if {@code object} is not a * {@link Class Class} that implements {@code interfaceName} */ public static Class<?> verifyAttributeCategory(Object object, Class<?> interfaceName) { Class<?> result = (Class<?>) object; if (interfaceName.isAssignableFrom (result)) { return result; } else { throw new ClassCastException(); } } /** * Verify that the given object is an instance of the given interface, which * is assumed to be interface {@link Attribute Attribute} or a subinterface * thereof. * * @param object {@code Object} to test * @param interfaceName interface of which the object must be an instance * @return if {@code object} is an instance of {@code interfaceName}, * {@code object} is returned downcast to type * {@link Attribute Attribute}; otherwise an exception is thrown * @throws NullPointerException if {@code object} is {@code null} * @throws ClassCastException if {@code object} is not an instance of * {@code interfaceName} */ public static Attribute verifyAttributeValue(Object object, Class<?> interfaceName) { if (object == null) { throw new NullPointerException(); } else if (interfaceName.isInstance (object)) { return (Attribute) object; } else { throw new ClassCastException(); } } /** * Verify that the given attribute category object is equal to the category * of the given attribute value object. If so, this method returns doing * nothing. If not, this method throws an exception. * * @param category attribute category to test * @param attribute attribute value to test * @throws NullPointerException if the {@code category} or {@code attribute} * are {@code null} * @throws IllegalArgumentException if the {@code category} is not equal to * the category of the {@code attribute} */ public static void verifyCategoryForValue(Class<?> category, Attribute attribute) { if (!category.equals (attribute.getCategory())) { throw new IllegalArgumentException(); } } }
9244c207863170078bdec6669502e4608e536cdd
840
java
Java
beige-lib/src/main/java/org/beigesoft/ui/container/ContainerGuiSrvs.java
rudyENgithub/beige-uml
0f32391b9cd0c00696bf6fbd77c7cc7932f883cb
[ "Apache-2.0" ]
1
2016-12-14T01:58:36.000Z
2016-12-14T01:58:36.000Z
beige-lib/src/main/java/org/beigesoft/ui/container/ContainerGuiSrvs.java
rudyENgithub/beige-uml
0f32391b9cd0c00696bf6fbd77c7cc7932f883cb
[ "Apache-2.0" ]
null
null
null
beige-lib/src/main/java/org/beigesoft/ui/container/ContainerGuiSrvs.java
rudyENgithub/beige-uml
0f32391b9cd0c00696bf6fbd77c7cc7932f883cb
[ "Apache-2.0" ]
1
2019-06-28T08:16:28.000Z
2019-06-28T08:16:28.000Z
22.702703
70
0.753571
1,003,129
package org.beigesoft.ui.container; import org.beigesoft.graphic.SettingsGraphic; import org.beigesoft.service.ISrvI18n; import org.beigesoft.ui.service.ISrvDialog; public class ContainerGuiSrvs<DLI> implements IContainerSrvsGui<DLI> { private final ISrvDialog<DLI> dialogSrv; private final ISrvI18n i18nSrv; private final SettingsGraphic graphicSettings; public ContainerGuiSrvs(ISrvDialog<DLI> dialogSrv, ISrvI18n i18nSrv, SettingsGraphic graphicSettings) { this.dialogSrv = dialogSrv; this.i18nSrv = i18nSrv; this.graphicSettings = graphicSettings; } @Override public ISrvDialog<DLI> getSrvDialog() { return dialogSrv; } @Override public ISrvI18n getSrvI18n() { return i18nSrv; } @Override public SettingsGraphic getSettingsGraphic() { return graphicSettings; } }
9244c34ff0b67fe2d56d72e5dd4a7a2c1d759efa
1,795
java
Java
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/VmCheckpointDao.java
emesika/ovirt-engine
db6458e688eeb385b683a0c9c5530917cd6dfe5f
[ "Apache-2.0" ]
347
2015-01-20T14:13:21.000Z
2022-03-31T17:53:11.000Z
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/VmCheckpointDao.java
emesika/ovirt-engine
db6458e688eeb385b683a0c9c5530917cd6dfe5f
[ "Apache-2.0" ]
128
2015-05-22T19:14:32.000Z
2022-03-31T08:11:18.000Z
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/VmCheckpointDao.java
emesika/ovirt-engine
db6458e688eeb385b683a0c9c5530917cd6dfe5f
[ "Apache-2.0" ]
202
2015-01-04T06:20:49.000Z
2022-03-08T15:30:08.000Z
26.791045
110
0.656267
1,003,130
package org.ovirt.engine.core.dao; import java.util.List; import org.ovirt.engine.core.common.businessentities.VmCheckpoint; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.compat.Guid; /** * {@code VmCheckpointDao} defines a type which performs CRUD operations on instances of {@link VmCheckpoint}. */ public interface VmCheckpointDao extends GenericDao<VmCheckpoint, Guid> { /** * Retrieves the list of checkpoints for the given VM id. * * @param id * the VM id * @return the list of checkpoints */ List<VmCheckpoint> getAllForVm(Guid id); /** * Retrieves the child of the given checkpoint ID. * * @param checkpointId * the checkpoint id * @return child of the given checkpoint */ VmCheckpoint getChildCheckpoint(Guid checkpointId); /** * Adds the specified disk to checkpoint. * * @param checkpointId the checkpoint id * @param diskId the disk id to add */ void addDiskToCheckpoint(Guid checkpointId, Guid diskId); /** * Get disks associated with the VM checkpoint. * @param checkpointId the VM checkpoint id. * @return the list of associated disks. */ List<DiskImage> getDisksByCheckpointId(Guid checkpointId); /** * Remove all checkpoints of a VM * * @param vmId the VM id */ void removeAllCheckpointsByVmId(Guid vmId); /** * Invalidate all checkpoints of a VM * * @param vmId the VM id */ void invalidateAllCheckpointsByVmId(Guid vmId); /** * Return true if the disk is included in a VM checkpoint * * @param diskId the disk id */ boolean isDiskIncludedInCheckpoint(Guid diskId); }
9244c388216f8f5922d14b93a848a220970b1353
1,144
java
Java
src/main/java/com/zoowii/formutils/constraits/LengthConstrait.java
zoowii/form-utils
aeb7d3e56e2b39fb53ddc5c63da16c5be8b30e6b
[ "MIT" ]
null
null
null
src/main/java/com/zoowii/formutils/constraits/LengthConstrait.java
zoowii/form-utils
aeb7d3e56e2b39fb53ddc5c63da16c5be8b30e6b
[ "MIT" ]
null
null
null
src/main/java/com/zoowii/formutils/constraits/LengthConstrait.java
zoowii/form-utils
aeb7d3e56e2b39fb53ddc5c63da16c5be8b30e6b
[ "MIT" ]
null
null
null
38.133333
125
0.70542
1,003,131
package com.zoowii.formutils.constraits; import com.zoowii.formutils.Constrait; import com.zoowii.formutils.ValidateError; import com.zoowii.formutils.ValidateErrorGenerator; import com.zoowii.formutils.ValidateHelper; import com.zoowii.formutils.annotations.Length; /** * Created by zoowii on 14/10/30. */ public class LengthConstrait extends Constrait<Length> { @Override public boolean isValid(Object fieldValue) { if (fieldValue == null) { return true; } int fieldValueLength = fieldValue.toString().length(); return fieldValueLength >= validateAnnotation.min() && fieldValueLength <= validateAnnotation.max(); } @Override public ValidateError createValidateError(ValidateErrorGenerator validateErrorGenerator) { return validateErrorGenerator.generate(validateAnnotation, ValidateHelper.firstNotEmptyString(validateAnnotation.message(), String.format("Field %s's length must be %d to %d", validateErrorGenerator.getFieldName(), validateAnnotation.min(), validateAnnotation.max()))); } }
9244c3d49db5ce972b9a7388a2605cc54dca6a60
2,578
java
Java
nosql/mongo-demo/src/main/java/geektime/spring/data/mongodemo/MongoDemoApplication.java
xiang12835/spring-family
9cf8f33d2b03e150c3291a8f410276eddfdae5bb
[ "MIT" ]
1
2021-09-29T07:24:56.000Z
2021-09-29T07:24:56.000Z
nosql/mongo-demo/src/main/java/geektime/spring/data/mongodemo/MongoDemoApplication.java
xiang12835/spring-family
9cf8f33d2b03e150c3291a8f410276eddfdae5bb
[ "MIT" ]
null
null
null
nosql/mongo-demo/src/main/java/geektime/spring/data/mongodemo/MongoDemoApplication.java
xiang12835/spring-family
9cf8f33d2b03e150c3291a8f410276eddfdae5bb
[ "MIT" ]
1
2021-09-17T15:05:17.000Z
2021-09-17T15:05:17.000Z
36.309859
86
0.778898
1,003,132
package geektime.spring.data.mongodemo; import com.mongodb.client.result.UpdateResult; import geektime.spring.data.mongodemo.converter.MoneyReadConverter; import geektime.spring.data.mongodemo.model.Coffee; import lombok.extern.slf4j.Slf4j; import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; @SpringBootApplication @Slf4j public class MongoDemoApplication implements ApplicationRunner { @Autowired private MongoTemplate mongoTemplate; public static void main(String[] args) { SpringApplication.run(MongoDemoApplication.class, args); } @Bean public MongoCustomConversions mongoCustomConversions() { return new MongoCustomConversions(Arrays.asList(new MoneyReadConverter())); } @Override public void run(ApplicationArguments args) throws Exception { Coffee espresso = Coffee.builder() .name("espresso") .price(Money.of(CurrencyUnit.of("CNY"), 20.0)) .createTime(new Date()) .updateTime(new Date()).build(); Coffee saved = mongoTemplate.save(espresso); log.info("Coffee {}", saved); List<Coffee> list = mongoTemplate.find( Query.query(Criteria.where("name").is("espresso")), Coffee.class); log.info("Find {} Coffee", list.size()); list.forEach(c -> log.info("Coffee {}", c)); Thread.sleep(1000); // 为了看更新时间 UpdateResult result = mongoTemplate.updateFirst(query(where("name").is("espresso")), new Update().set("price", Money.ofMajor(CurrencyUnit.of("CNY"), 30)) .currentDate("updateTime"), Coffee.class); log.info("Update Result: {}", result.getModifiedCount()); Coffee updateOne = mongoTemplate.findById(saved.getId(), Coffee.class); log.info("Update Result: {}", updateOne); mongoTemplate.remove(updateOne); } }
9244c44e181d9c9d3ac80fabd832b0b11093c12c
282
java
Java
src/com/inubit/research/layouter/interfaces/PetriNetModelInterface.java
frapu78/processeditor
7a608d7fcc9a172a768a9907c9365a466164a7b1
[ "Apache-2.0" ]
5
2015-12-29T00:56:12.000Z
2021-03-27T15:52:37.000Z
src/com/inubit/research/layouter/interfaces/PetriNetModelInterface.java
frapu78/processeditor
7a608d7fcc9a172a768a9907c9365a466164a7b1
[ "Apache-2.0" ]
32
2015-02-26T21:09:45.000Z
2018-06-18T19:34:53.000Z
src/com/inubit/research/layouter/interfaces/PetriNetModelInterface.java
frapu78/processeditor
7a608d7fcc9a172a768a9907c9365a466164a7b1
[ "Apache-2.0" ]
6
2015-02-24T11:15:41.000Z
2021-12-26T07:01:44.000Z
14.842105
57
0.624113
1,003,133
/** * * Process Editor * * (C) 2009, 2010 inubit AG * (C) 2014 the authors * */ package com.inubit.research.layouter.interfaces; /** * extension which marks this model as a petri net model * @author ff * */ public interface PetriNetModelInterface { }
9244c4d27569fb0737d35ea7d79bfe2fd645dab0
3,453
java
Java
tools/idea/src/main/java/ch/raffael/meldioc/idea/ElementRendering.java
Abnaxos/compose
18737ba5db5b55b33f850366d927b146ecd4a8bf
[ "MIT" ]
3
2019-07-09T10:21:27.000Z
2019-08-18T07:49:10.000Z
tools/idea/src/main/java/ch/raffael/meldioc/idea/ElementRendering.java
Abnaxos/meldioc
9b1dd7d374133efa5a611ad411b6b56d5327a59a
[ "MIT" ]
63
2020-03-01T08:54:19.000Z
2022-02-15T09:03:06.000Z
tools/idea/src/main/java/ch/raffael/meldioc/idea/ElementRendering.java
Abnaxos/meldioc
9b1dd7d374133efa5a611ad411b6b56d5327a59a
[ "MIT" ]
1
2019-08-02T02:50:02.000Z
2019-08-02T02:50:02.000Z
33.852941
95
0.663481
1,003,134
/* * Copyright (c) 2021 Raffael Herzog * * 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 ch.raffael.meldioc.idea; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiParameter; import com.intellij.psi.util.PsiTreeUtil; import javax.annotation.Nullable; public final class ElementRendering { private static final Logger LOG = Logger.getInstance(ElementRendering.class); private ElementRendering() { } public static String renderElement(PsiElement e) { return renderElement(new StringBuilder(), e).toString(); } public static String renderClassName(@Nullable PsiClass psiClass) { return renderClassName(new StringBuilder(), psiClass).toString(); } public static StringBuilder renderElement(StringBuilder buf, PsiElement e) { if (e instanceof PsiClass) { var c = (PsiClass) e; if (c.isEnum()) { buf.append("enum "); } else if (c.isRecord()) { buf.append("record "); } else if (c.isAnnotationType()) { buf.append("annotation type "); } else if (c.isInterface()) { buf.append("interface "); } else { buf.append("class "); } renderClassName(buf, c); } else if (e instanceof PsiMethod){ var m = (PsiMethod) e; buf.append(m.getName()); buf.append("()"); buf.append(" in "); renderClassName(buf, m.getContainingClass()); } else if (e instanceof PsiParameter) { buf.append("parameter "); var p = (PsiParameter) e; var m = (PsiMethod) PsiTreeUtil.findFirstParent(p, PsiMethod.class::isInstance); if (m == null) { LOG.warn("Parameter " + p + ": could not get method"); } buf.append(p.getName()); if (m != null) { buf.append(" of "); renderElement(buf, m); } } else { LOG.warn("No renderer for type " + e.getClass() + " (" + e + ")"); return buf.append(e); } return buf; } public static StringBuilder renderClassName(StringBuilder buf, @Nullable PsiClass psiClass) { int offset = buf.length(); var c = psiClass; while (c != null) { if (buf.length() > offset) { buf.insert(offset, '.'); } buf.insert(offset, c.getName()); c = c.getContainingClass(); } return buf; } }
9244c51991f12f244cac7df8cccde4deaca31255
314
java
Java
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/hosting/web/OvhCronLanguageAvailable.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
12
2017-04-04T07:20:48.000Z
2021-04-20T07:54:21.000Z
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/hosting/web/OvhCronLanguageAvailable.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
7
2017-04-05T04:54:16.000Z
2019-09-24T11:17:05.000Z
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/hosting/web/OvhCronLanguageAvailable.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
3
2019-10-10T13:51:22.000Z
2020-11-13T14:30:45.000Z
14.952381
47
0.691083
1,003,135
package net.minidev.ovh.api.hosting.web; /** * Language available for cron script */ public class OvhCronLanguageAvailable { /** * Php versions * * canBeNull */ public OvhPhpVersionAvailableEnum[] php; /** * NodeJS versions * * canBeNull */ public OvhNodejsVersionAvailableEnum[] nodejs; }
9244c5adba796712286e7b9a834c0e06ec259b00
4,234
java
Java
sources/com/fasterxml/jackson/core/JsonLocation.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2019-10-01T11:34:10.000Z
2019-10-01T11:34:10.000Z
sources/com/fasterxml/jackson/core/JsonLocation.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
null
null
null
sources/com/fasterxml/jackson/core/JsonLocation.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2020-05-26T05:10:33.000Z
2020-05-26T05:10:33.000Z
32.320611
181
0.550779
1,003,136
package com.fasterxml.jackson.core; import java.io.Serializable; import java.nio.charset.Charset; public class JsonLocation implements Serializable { /* renamed from: NA */ public static final JsonLocation f12547NA; protected final int _columnNr; protected final int _lineNr; final transient Object _sourceRef; protected final long _totalBytes; protected final long _totalChars; static { JsonLocation jsonLocation = new JsonLocation(null, -1, -1, -1, -1); f12547NA = jsonLocation; } public JsonLocation(Object srcRef, long totalChars, int lineNr, int colNr) { this(srcRef, -1, totalChars, lineNr, colNr); } public JsonLocation(Object sourceRef, long totalBytes, long totalChars, int lineNr, int columnNr) { this._sourceRef = sourceRef; this._totalBytes = totalBytes; this._totalChars = totalChars; this._lineNr = lineNr; this._columnNr = columnNr; } public long getByteOffset() { return this._totalBytes; } public int hashCode() { Object obj = this._sourceRef; return ((((obj == null ? 1 : obj.hashCode()) ^ this._lineNr) + this._columnNr) ^ ((int) this._totalChars)) + ((int) this._totalBytes); } public boolean equals(Object other) { boolean z = true; if (other == this) { return true; } if (other == null || !(other instanceof JsonLocation)) { return false; } JsonLocation otherLoc = (JsonLocation) other; Object obj = this._sourceRef; if (obj == null) { if (otherLoc._sourceRef != null) { return false; } } else if (!obj.equals(otherLoc._sourceRef)) { return false; } if (!(this._lineNr == otherLoc._lineNr && this._columnNr == otherLoc._columnNr && this._totalChars == otherLoc._totalChars && getByteOffset() == otherLoc.getByteOffset())) { z = false; } return z; } public String toString() { StringBuilder sb = new StringBuilder(80); sb.append("[Source: "); _appendSourceDesc(sb); sb.append("; line: "); sb.append(this._lineNr); sb.append(", column: "); sb.append(this._columnNr); sb.append(']'); return sb.toString(); } /* access modifiers changed from: protected */ public StringBuilder _appendSourceDesc(StringBuilder sb) { int len; Object srcRef = this._sourceRef; if (srcRef == null) { sb.append("UNKNOWN"); return sb; } Class<?> srcType = srcRef instanceof Class ? (Class) srcRef : srcRef.getClass(); String tn = srcType.getName(); if (tn.startsWith("java.")) { tn = srcType.getSimpleName(); } else if (srcRef instanceof byte[]) { tn = "byte[]"; } else if (srcRef instanceof char[]) { tn = "char[]"; } sb.append('('); sb.append(tn); sb.append(')'); String charStr = " chars"; if (srcRef instanceof CharSequence) { CharSequence cs = (CharSequence) srcRef; int len2 = cs.length(); len = len2 - _append(sb, cs.subSequence(0, Math.min(len2, 500)).toString()); } else if (srcRef instanceof char[]) { char[] ch = (char[]) srcRef; int len3 = ch.length; len = len3 - _append(sb, new String(ch, 0, Math.min(len3, 500))); } else if (srcRef instanceof byte[]) { byte[] b = (byte[]) srcRef; int maxLen = Math.min(b.length, 500); _append(sb, new String(b, 0, maxLen, Charset.forName("UTF-8"))); len = b.length - maxLen; charStr = " bytes"; } else { len = 0; } if (len > 0) { sb.append("[truncated "); sb.append(len); sb.append(charStr); sb.append(']'); } return sb; } private int _append(StringBuilder sb, String content) { sb.append('\"'); sb.append(content); sb.append('\"'); return content.length(); } }
9244c62e919d1b052ff02e646545045930f2a892
1,428
java
Java
chapter_002_IO/src/test/java/ru/job4j/io/ConfigTest.java
anderson178/job4j_junior
0f3502f6b56c1d7d2cb1cd56cd64ba11f330889f
[ "Apache-2.0" ]
2
2019-03-17T14:49:04.000Z
2019-09-14T19:00:01.000Z
chapter_002_IO/src/test/java/ru/job4j/io/ConfigTest.java
anderson178/job4j_junior
0f3502f6b56c1d7d2cb1cd56cd64ba11f330889f
[ "Apache-2.0" ]
null
null
null
chapter_002_IO/src/test/java/ru/job4j/io/ConfigTest.java
anderson178/job4j_junior
0f3502f6b56c1d7d2cb1cd56cd64ba11f330889f
[ "Apache-2.0" ]
null
null
null
33.209302
101
0.667367
1,003,137
package ru.job4j.io; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * @author Денис Мироненко * @version $Id$ * @since 12.04.2019 */ public class ConfigTest { @Test public void whenApp() throws IOException { Map<String, String> map = new HashMap<>(); map.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); map.put("hibernate.connection.url", "jdbc:postgresql://127.0.0.1:5432/trackstudio"); map.put("hibernate.connection.driver_class", "org.postgresql.Driver"); map.put("hibernate.connection.username", "postgres"); map.put("hibernate.connection.password", "password"); assertThat(new Config(new File("./" + "app.properties").getAbsolutePath()).load(), is(map)); } @Test public void whenApp2() throws IOException { Map<String, String> map = new HashMap<>(); map.put("jdbc.connection.url", "jdbc:postgresql://127.0.0.1:5432/trackstudio"); map.put("jdbc.connection.driver_class", "org.postgresql.Driver"); map.put("jdbc.connection.username", "postgres"); map.put("jdbc.connection.password", "password"); assertThat(new Config(new File("./" + "app2.properties").getAbsolutePath()).load(), is(map)); } }
9244c6730c3a8fe02188590c0d13e2d395020f2a
10,982
java
Java
src/test/java/com/github/aguther/dds/discovery/observer/PublicationObserverTest.java
aguther/dds-examples
fb4d51fefd0f23fa7b0ffb6dee4b6f3c7ed719fa
[ "MIT" ]
3
2017-12-08T05:02:36.000Z
2020-05-12T23:19:10.000Z
src/test/java/com/github/aguther/dds/discovery/observer/PublicationObserverTest.java
aguther/dds-examples
fb4d51fefd0f23fa7b0ffb6dee4b6f3c7ed719fa
[ "MIT" ]
null
null
null
src/test/java/com/github/aguther/dds/discovery/observer/PublicationObserverTest.java
aguther/dds-examples
fb4d51fefd0f23fa7b0ffb6dee4b6f3c7ed719fa
[ "MIT" ]
1
2021-06-17T06:23:35.000Z
2021-06-17T06:23:35.000Z
36.006557
93
0.760881
1,003,138
/* * MIT License * * Copyright (c) 2018 Andreas Guther * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.aguther.dds.discovery.observer; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doAnswer; import static org.powermock.api.mockito.PowerMockito.doThrow; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import com.rti.dds.domain.DomainParticipant; import com.rti.dds.infrastructure.InstanceHandle_t; import com.rti.dds.infrastructure.RETCODE_ERROR; import com.rti.dds.infrastructure.RETCODE_NO_DATA; import com.rti.dds.publication.builtin.PublicationBuiltinTopicData; import com.rti.dds.publication.builtin.PublicationBuiltinTopicDataSeq; import com.rti.dds.publication.builtin.PublicationBuiltinTopicDataTypeSupport; import com.rti.dds.subscription.DataReader; import com.rti.dds.subscription.InstanceStateKind; import com.rti.dds.subscription.SampleInfo; import com.rti.dds.subscription.SampleInfoSeq; import com.rti.dds.subscription.Subscriber; import com.rti.dds.util.LoanableSequence; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.config.Configurator; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; @RunWith(PowerMockRunner.class) @PrepareForTest({ BuiltinTopicObserver.class, DomainParticipant.class, LoanableSequence.class, PublicationBuiltinTopicData.class, PublicationBuiltinTopicDataSeq.class, PublicationBuiltinTopicDataTypeSupport.class, PublicationObserver.class, SampleInfo.class, SampleInfoSeq.class, }) @SuppressStaticInitializationFor({ "com.rti.dds.domain.builtin.ParticipantBuiltinTopicDataTypeSupport", "com.rti.dds.domain.DomainParticipant", "com.rti.dds.publication.builtin.PublicationBuiltinTopicData", "com.rti.dds.publication.builtin.PublicationBuiltinTopicDataSeq", "com.rti.dds.publication.builtin.PublicationBuiltinTopicDataTypeSupport", "com.rti.dds.subscription.builtin.SubscriptionBuiltinTopicData", "com.rti.dds.subscription.builtin.SubscriptionBuiltinTopicDataTypeSupport", "com.rti.dds.subscription.SampleInfoSeq", "com.rti.dds.topic.AbstractBuiltinTopicData", "com.rti.dds.topic.builtin.ServiceRequestTypeSupport", "com.rti.dds.topic.builtin.TopicBuiltinTopicDataTypeSupport", "com.rti.dds.topic.builtin.TopicBuiltinTopicDataTypeSupport", "com.rti.dds.topic.TypeSupportImpl", "com.rti.dds.util.LoanableSequence", }) public class PublicationObserverTest { private DataReader dataReader; private PublicationObserver publicationObserver; private PublicationObserverListener publicationObserverListener; private PublicationBuiltinTopicData publicationBuiltinTopicData; private PublicationBuiltinTopicDataSeq publicationBuiltinTopicDataSeq; private SampleInfo sampleInfo; private SampleInfoSeq sampleInfoSeq; @Before public void setUp() throws Exception { DomainParticipant domainParticipant = mock(DomainParticipant.class); Subscriber subscriber = mock(Subscriber.class); dataReader = mock(DataReader.class); Whitebox.setInternalState( PublicationBuiltinTopicDataTypeSupport.class, "PUBLICATION_TOPIC_NAME", "PublicationBuiltinTopicName" ); publicationBuiltinTopicData = mock(PublicationBuiltinTopicData.class); publicationBuiltinTopicData.topic_name = "Square"; publicationBuiltinTopicData.type_name = "ShapeType"; PowerMockito.whenNew(PublicationBuiltinTopicData.class).withAnyArguments().thenReturn( publicationBuiltinTopicData); publicationBuiltinTopicDataSeq = mock(PublicationBuiltinTopicDataSeq.class); PowerMockito.whenNew(PublicationBuiltinTopicDataSeq.class).withAnyArguments().thenReturn( publicationBuiltinTopicDataSeq); sampleInfo = mock(SampleInfo.class); Whitebox.setInternalState(sampleInfo, "instance_handle", InstanceHandle_t.HANDLE_NIL); PowerMockito.whenNew(SampleInfo.class).withAnyArguments().thenReturn(sampleInfo); sampleInfoSeq = mock(SampleInfoSeq.class); PowerMockito.whenNew(SampleInfoSeq.class).withAnyArguments().thenReturn(sampleInfoSeq); when(domainParticipant.get_builtin_subscriber()).thenReturn(subscriber); when(subscriber.lookup_datareader(anyString())) .thenReturn(dataReader); publicationObserver = new PublicationObserver(domainParticipant); publicationObserverListener = mock(PublicationObserverListener.class); publicationObserver.addListener(publicationObserverListener, false); } @After public void tearDown() { publicationObserver.removeListener(publicationObserverListener); publicationObserver.close(); } @Test public void testInstantiation() { assertNotNull(publicationObserver); } @Test(timeout = 10000) public void testRunWithLevelDebug() { // remember current level Level originalLevel = LogManager.getRootLogger().getLevel(); try { // set logging to DEBUG Configurator.setRootLevel(Level.DEBUG); // execute run method testRun(); } finally { // restore level Configurator.setRootLevel(originalLevel); } } @Test(timeout = 10000) public void testRunWithLevelTrace() { // remember current level Level originalLevel = LogManager.getRootLogger().getLevel(); try { // set logging to TRACE Configurator.setRootLevel(Level.TRACE); // execute run method testRun(); } finally { // restore level Configurator.setRootLevel(originalLevel); } } private void testRun() { // prepare answers doAnswer( invocation -> { SampleInfo sampleInfo = invocation.getArgument(1); sampleInfo.valid_data = true; sampleInfo.instance_state = InstanceStateKind.ALIVE_INSTANCE_STATE; return null; } ).doAnswer( invocation -> { SampleInfo sampleInfo = invocation.getArgument(1); sampleInfo.valid_data = true; sampleInfo.instance_state = InstanceStateKind.ALIVE_INSTANCE_STATE; return null; } ).doAnswer( invocation -> { SampleInfo sampleInfo = invocation.getArgument(1); sampleInfo.valid_data = false; sampleInfo.instance_state = InstanceStateKind.NOT_ALIVE_INSTANCE_STATE; return null; } ).doThrow(new RETCODE_NO_DATA() ).when(dataReader).read_next_sample_untyped( eq(publicationBuiltinTopicData), eq(sampleInfo) ); // execute tested method publicationObserver.run(); // verify results verify(publicationObserverListener, times(1)).publicationDiscovered( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); verify(publicationObserverListener, times(1)).publicationModified( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); verify(publicationObserverListener, times(1)).publicationLost( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); } @Test(timeout = 10000) public void testRunError() { // prepare answers doThrow(new RETCODE_ERROR() ).when(dataReader).read_next_sample_untyped( eq(publicationBuiltinTopicData), eq(sampleInfo) ); // execute tested method publicationObserver.run(); // verify results verify(publicationObserverListener, times(0)).publicationDiscovered( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); verify(publicationObserverListener, times(0)).publicationLost( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); } @Test(timeout = 10000) public void testAddListenerWithReadSamples() { // create another listener PublicationObserverListener listener = mock(PublicationObserverListener.class); // prepare answers doAnswer( invocation -> { SampleInfo sampleInfo = invocation.getArgument(1); sampleInfo.valid_data = true; sampleInfo.instance_state = InstanceStateKind.ALIVE_INSTANCE_STATE; return null; } ).doThrow(new RETCODE_NO_DATA() ).when(dataReader).read_next_sample_untyped( eq(publicationBuiltinTopicData), eq(sampleInfo) ); // execute run method so sample is stored in cache publicationObserver.run(); // execute tested method publicationObserver.addListener(listener); // verify results verify(publicationObserverListener, times(1)).publicationDiscovered( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); verify(publicationObserverListener, times(0)).publicationLost( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); verify(listener, times(1)).publicationDiscovered( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); verify(listener, times(0)).publicationLost( any(DomainParticipant.class), any(InstanceHandle_t.class), any(PublicationBuiltinTopicData.class)); } }
9244c705c058795428848ea2726a1884455e1ce4
187
java
Java
miniwas/src/main/java/my/examples/was02/MiniWAS.java
JeremyShin/webTest
d021e433a1ee02fc1ccd34d837adcde35626abd8
[ "MIT" ]
null
null
null
miniwas/src/main/java/my/examples/was02/MiniWAS.java
JeremyShin/webTest
d021e433a1ee02fc1ccd34d837adcde35626abd8
[ "MIT" ]
null
null
null
miniwas/src/main/java/my/examples/was02/MiniWAS.java
JeremyShin/webTest
d021e433a1ee02fc1ccd34d837adcde35626abd8
[ "MIT" ]
null
null
null
18.7
50
0.641711
1,003,139
package my.examples.was02; public class MiniWAS extends Thread{ @Override public void run() { Connector connector = new Connector(8888); connector.run(); } }
9244c79ef9d7824f6b3255c48ba1ebc81ce00870
147
java
Java
src/main/java/com/rejoice/service/SecurityService.java
PogrebenniyAlex/Bitclave-Hackathon
718f82fd375320815bdacaf2785d10e2deeee588
[ "MIT" ]
null
null
null
src/main/java/com/rejoice/service/SecurityService.java
PogrebenniyAlex/Bitclave-Hackathon
718f82fd375320815bdacaf2785d10e2deeee588
[ "MIT" ]
null
null
null
src/main/java/com/rejoice/service/SecurityService.java
PogrebenniyAlex/Bitclave-Hackathon
718f82fd375320815bdacaf2785d10e2deeee588
[ "MIT" ]
null
null
null
18.375
37
0.741497
1,003,140
package com.rejoice.service; import com.rejoice.entity.user.User; public interface SecurityService { void autoLoginUser(User user); }
9244c909b1b1b968be614a85cccd8a56cb78039d
1,597
java
Java
src/api/web/gw2/mapping/v1/guilddetails/GuildDetailsEmblem.java
fabricebouye/GW2WebAPIMapping
d4e26f37293b2d96f1fc1d61cb9dd48b5f6d8415
[ "BSD-3-Clause" ]
null
null
null
src/api/web/gw2/mapping/v1/guilddetails/GuildDetailsEmblem.java
fabricebouye/GW2WebAPIMapping
d4e26f37293b2d96f1fc1d61cb9dd48b5f6d8415
[ "BSD-3-Clause" ]
null
null
null
src/api/web/gw2/mapping/v1/guilddetails/GuildDetailsEmblem.java
fabricebouye/GW2WebAPIMapping
d4e26f37293b2d96f1fc1d61cb9dd48b5f6d8415
[ "BSD-3-Clause" ]
null
null
null
24.953125
102
0.637445
1,003,141
/* * Copyright (C) 2015-2019 Fabrice Bouyé * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ package api.web.gw2.mapping.v1.guilddetails; import api.web.gw2.mapping.core.IdValue; import api.web.gw2.mapping.core.SetValue; import api.web.gw2.mapping.v1.APIv1; import java.util.Set; /** * Defines the emblem of a guild. * @author Fabrice Bouyé */ @APIv1(endpoint = "v1/guild_details.json") // NOI18N. public interface GuildDetailsEmblem { /** * Gets the id of the background image of this emblem. * @return An {@code int} &ge; 0. */ @IdValue int getBackgroundId(); /** * Gets the id of the background color of this emblem. * @return An {@code int} &ge; 0. */ @IdValue int getBackgroundColorId(); /** * Gets the id of the foreground image of this emblem. * @return An {@code int} &ge; 0. */ @IdValue int getForegroundId(); /** * Gets the id of the foreground primary color of this emblem. * @return An {@code int} &ge; 0. */ @IdValue int getForegroundPrimaryColorId(); /** * Gets the id of the foreground secondary color of this emblem. * @return An {@code int} &ge; 0. */ @IdValue int getForegroundSecondaryColorId(); /** * Gets a set of flags applied to this emblem. * @return A non-modifiable {@code Set<GuildDetailsEmblemFlag>}, never {@code null}, may be empty. */ @SetValue Set<GuildDetailsEmblemFlag> getFlags(); }
9244ca08b8487fbfa637ec0e314d16d23bf3ea28
430
java
Java
authentication/src/main/java/com/lukaspar/ep/authentication/repository/MessageRepository.java
lukaspar/noname
b44af7a5746f6b20614274c9aea3cae2ec3813bd
[ "Apache-2.0" ]
null
null
null
authentication/src/main/java/com/lukaspar/ep/authentication/repository/MessageRepository.java
lukaspar/noname
b44af7a5746f6b20614274c9aea3cae2ec3813bd
[ "Apache-2.0" ]
null
null
null
authentication/src/main/java/com/lukaspar/ep/authentication/repository/MessageRepository.java
lukaspar/noname
b44af7a5746f6b20614274c9aea3cae2ec3813bd
[ "Apache-2.0" ]
null
null
null
28.666667
73
0.830233
1,003,142
package com.lukaspar.ep.authentication.repository; import com.lukaspar.ep.authentication.model.Message; import com.lukaspar.ep.authentication.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface MessageRepository extends JpaRepository<Message, Long> { List<Message> findByReceiver(User receiver); }
9244caa31556f45b46903463de261482248c8b1a
1,491
java
Java
src/java/servlets/family/ItemDepositServlet.java
hepa/XMLHazi
a8c8d066e381d58f91815212b72e904a2bad76cc
[ "CC-BY-3.0" ]
null
null
null
src/java/servlets/family/ItemDepositServlet.java
hepa/XMLHazi
a8c8d066e381d58f91815212b72e904a2bad76cc
[ "CC-BY-3.0" ]
null
null
null
src/java/servlets/family/ItemDepositServlet.java
hepa/XMLHazi
a8c8d066e381d58f91815212b72e904a2bad76cc
[ "CC-BY-3.0" ]
null
null
null
28.673077
114
0.655265
1,003,143
package servlets.family; import business.Account; import business.Family; import business.Homework; import business.Item; import business.Student; import java.io.*; import java.sql.SQLException; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import org.apache.log4j.Logger; @WebServlet("/family/itemDeposit") public class ItemDepositServlet extends HttpServlet { Logger logger; private final String className = getClass().getName(); @Override public void init() { logger = Logger.getRootLogger(); logger.trace(className + " is initializing."); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { HttpSession session = req.getSession(); Family f = (Family) session.getAttribute("family"); f.setAccount(Account.getInstance(f.getAccount().getNumber())); Item i = Item.getInstance(Integer.parseInt(req.getParameter("id"))); if (i.getAmount() > f.getAccount().getBalance()) { resp.getWriter().print("error"); } else { i.deposit(f); } } catch (SQLException ex) { logger.error(ex.getMessage()); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
9244cb17079d4049a7470b9115f7e02b90d8ee7f
12,036
java
Java
src/main/java/com/plugins/mygetset/ui/setconvert.java
Link-Kou/intellij-getset
11ab3126338affcf1b2a12568b75e8cce29f6c9d
[ "MIT" ]
1
2021-03-31T04:24:54.000Z
2021-03-31T04:24:54.000Z
src/main/java/com/plugins/mygetset/ui/setconvert.java
Link-Kou/intellij-getset
11ab3126338affcf1b2a12568b75e8cce29f6c9d
[ "MIT" ]
null
null
null
src/main/java/com/plugins/mygetset/ui/setconvert.java
Link-Kou/intellij-getset
11ab3126338affcf1b2a12568b75e8cce29f6c9d
[ "MIT" ]
null
null
null
25.232704
134
0.676138
1,003,144
package com.plugins.mygetset.ui; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiParameterList; import com.intellij.psi.util.PsiUtil; import com.intellij.ui.CollectionListModel; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.AbstractTableModel; import java.awt.event.*; import java.util.ArrayList; import java.util.List; public class setconvert extends JDialog { private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JRadioButton linkRadioButton; private JRadioButton voidRadioButton; private JTable tablethis; private JTable tablefrom; private JLabel labelfrom; private JLabel labelthis; private JSpinner spinner1; private AnActionEvent a; private PsiMethod psiMethod; private PsiClass psiClass; private static List<Info[]> lfm; public setconvert(PsiClass psiClass,PsiMethod psiMethod,AnActionEvent e) { //#region 系统 setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { onOK(); } }); buttonCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { onCancel(); } }); ChangeListener listener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { //SpinnerModel source = (SpinnerModel) e.getSource(); MyAbstractTableModel1 myAbstractTableModel1 = new MyAbstractTableModel1(GetConstructTabelField(a), thisClass(a)); tablefrom.setModel(myAbstractTableModel1); tablefrom.setShowGrid(false); } }; spinner1.addChangeListener(listener); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { onCancel(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); //#endregion this.a = e; this.psiMethod = psiMethod; this.psiClass = psiClass; MyAbstractTableModel1 myAbstractTableModel1 = new MyAbstractTableModel1(GetConstructTabelField(e), thisClass(e)); tablefrom.setModel(myAbstractTableModel1); tablefrom.setShowGrid(false); MyAbstractTableModel2 myAbstractTableModel2 = new MyAbstractTableModel2(thisClass(e)); tablethis.setModel(myAbstractTableModel2); tablethis.setShowGrid(false); } /** * 获取类中所有的字段对应的Set与Get方法 * * @param e * @return */ private List<Info> thisClass(AnActionEvent e) { List<Info> infos = new ArrayList<Info>(); PsiClass paraname = psiClass; List<PsiField> fields = new CollectionListModel<PsiField>(paraname.getFields()).getItems(); List<PsiMethod> methods = new CollectionListModel<PsiMethod>(paraname.getMethods()).getItems(); for (PsiField pf : fields) { Info info = new Info(); for (PsiMethod pmd : methods) { if (pmd.getName().toLowerCase().equals("set" + pf.getName().toLowerCase())) { info.setPsimethod(pmd).setPsiField(pf); } } infos.add(info); } labelthis.setText(paraname.getName()); return infos; } /** * 获取当前的光标在的方法的类 * * @param e * @return */ private List<Info> thisMethodClass(AnActionEvent e) { PsiMethod pm = psiMethod; /** * 获取到类中的字段 */ PsiParameterList pl = pm.getParameterList(); List<Info> infos = new ArrayList<Info>(); if(pl.getParameters().length > 0){ String paramname = pl.getParameters()[0].getName(); PsiClass paraname = PsiUtil.resolveClassInType(pl.getParameters()[0].getTypeElement().getType()); List<PsiField> fields = new CollectionListModel<PsiField>(paraname.getFields()).getItems(); List<PsiMethod> methods = new CollectionListModel<PsiMethod>(paraname.getMethods()).getItems(); for (PsiField pf : fields) { Info info = new Info(); for (PsiMethod pmd : methods) { if (pmd.getName().toLowerCase().equals("get" + pf.getName().toLowerCase())) { info.setPsimethod(pmd).setPsiField(pf).setParaname(paramname); } } infos.add(info); } labelfrom.setText(paraname.getName()); return infos; } return null; } /** * 构建table * * @param e * @return */ private List<Info[]> GetConstructTabelField(AnActionEvent e) { List<Info> set = thisClass(e); List<Info> get = thisMethodClass(e); List<Info[]> setget = new ArrayList<Info[]>(); for (Info infoget : get) { int d = setget.size(); for (Info infoset : set) { if (infoset.getPsimethod() != null && infoget.getPsimethod() != null) { if (infoset.getPsiField().getName().equals(infoget.getPsiField().getName())) { Info[] infos = new Info[]{infoget, infoset}; setget.add(infos); } else if ((int) spinner1.getValue() > 0) { String met = infoget.getPsiField().getName().substring((Integer) spinner1.getValue(), infoget.getPsiField().getName().length()); if (infoset.getPsiField().getName().equals(met)) { Info[] infos = new Info[]{infoget, infoset}; setget.add(infos); } } } } if(d == setget.size()){ Info[] infos = new Info[]{infoget, null}; setget.add(infos); } } return setget; } private void GetConstructField(AnActionEvent e) { StringBuilder sb = new StringBuilder(); if (linkRadioButton.isSelected()) { sb.append("this"); } for (Info[] list : lfm) { if (list.length == 2 && list[0] != null && list[1] != null) { if (linkRadioButton.isSelected()) { thisset(list[1].getPsimethod(), list[0].getPsimethod(), list[0].getParaname(), sb); } else if (voidRadioButton.isSelected()) { voidset(list[1].getPsimethod(), list[0].getPsimethod(), list[0].getParaname(), sb); } } } String buil = sb.toString(); if (linkRadioButton.isSelected()) { buil = buil.substring(0, buil.length() - 1) + ";"; } else if (voidRadioButton.isSelected()) { buil = buil.substring(0, buil.length() - 1); } Editor editor = e.getData(PlatformDataKeys.EDITOR); final int start = editor.getSelectionModel().getSelectionStart(); final int end = editor.getSelectionModel().getSelectionEnd(); String finalBuil = buil; WriteCommandAction.runWriteCommandAction(e.getProject(), new Runnable() { @Override public void run() { editor.getDocument().replaceString( start, end, finalBuil); //CodeStyleManager.getInstance(e.getProject()).re; } }); editor.getSelectionModel().removeSelection(); } private class Info { private int row; private PsiField PsiField; private PsiMethod psimethod; private String paraname; public int getRow() { return row; } public Info setRow(int row) { this.row = row; return this; } public PsiField getPsiField() { return PsiField; } public Info setPsiField(PsiField psiField) { PsiField = psiField; return this; } public PsiMethod getPsimethod() { return psimethod; } public Info setPsimethod(PsiMethod psimethod) { this.psimethod = psimethod; return this; } public String getParaname() { return paraname; } public Info setParaname(String paraname) { this.paraname = paraname; return this; } } private void thisset(PsiMethod set, PsiMethod get, String getname, StringBuilder sb) { sb.append(".") .append(set.getName()) .append("(") .append(getname) .append(".") .append(get.getName()) .append("()") .append(")") .append("\n"); } private void voidset(PsiMethod set, PsiMethod get, String getname, StringBuilder sb) { sb.append(set.getName()) .append("(") .append(getname) .append(".") .append(get.getName()) .append("()") .append(");") .append("\n"); } @SuppressWarnings("serial") class MyAbstractTableModel1 extends AbstractTableModel { List<Object[]> lo = new ArrayList<Object[]>(); List<Info> thisClass; public MyAbstractTableModel1(List<Info[]> infos, List<Info> thisClass) { this.thisClass = thisClass; lfm = infos; int i = 0; for (Info[] fom : lfm) { if (fom.length == 2) { if (fom[0] != null && fom[1] != null) { fom[0].setRow(i++); lo.add(new Object[]{fom[0].getPsimethod().getName(), fom[1].getPsimethod().getName()}); } else if (fom[0] != null && fom[1] == null) { fom[0].setRow(i++); lo.add(new Object[]{fom[0].getPsimethod().getName(), null}); } } } data = lo.toArray(new Object[0][0]); } // 定义表头数据 String[] head = {"Name", "Set"}; Class[] typeArray = {Object.class, Object.class}; // 定义表的内容数据 Object[][] data; // 获得表格的列数 @Override public int getColumnCount() { return head.length; } // 获得表格的行数 @Override public int getRowCount() { return data.length; } // 获得表格的列名称 @Override public String getColumnName(int column) { return head[column]; } // 获得表格的单元格的数据 @Override public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } // 使表格具有可编辑性 @Override public boolean isCellEditable(int rowIndex, int columnIndex) { if (columnIndex == 0) { return false; } return true; } // 替换单元格的值 @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { for (Info[] infos : lfm) { if (infos[0].getRow() == rowIndex) { for (Info info : thisClass) { if (info.getPsimethod() != null) { if (info.getPsimethod().getName().equals(aValue)) { infos[1] = info; data[rowIndex][columnIndex] = aValue; fireTableCellUpdated(rowIndex, columnIndex); } } } } } } // 实现了如果是boolean自动转成JCheckbox @Override public Class getColumnClass(int columnIndex) { return typeArray[columnIndex];// 返回每一列的数据类型 } } @SuppressWarnings("serial") class MyAbstractTableModel2 extends AbstractTableModel { List<Object[]> lo = new ArrayList<Object[]>(); List<Info> lfm; public MyAbstractTableModel2(List<Info> infos) { this.lfm = infos; int i = 0; for (Info fom : lfm) { if (fom.getPsimethod() != null) { lo.add(new Object[]{fom.getPsimethod().getName()}); } } data = lo.toArray(new Object[0][0]); } // 定义表头数据 String[] head = {"Name"}; Class[] typeArray = {Object.class}; // 定义表的内容数据 Object[][] data; // 获得表格的列数 @Override public int getColumnCount() { return head.length; } // 获得表格的行数 @Override public int getRowCount() { return data.length; } // 获得表格的列名称 @Override public String getColumnName(int column) { return head[column]; } // 获得表格的单元格的数据 @Override public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } // 使表格具有可编辑性 @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } // 替换单元格的值 @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { /*data[rowIndex][columnIndex] = aValue; fireTableCellUpdated(rowIndex, columnIndex);*/ } // 实现了如果是boolean自动转成JCheckbox /* * 需要自己的celleditor这么麻烦吧。jtable自动支持Jcheckbox, * 只要覆盖tablemodel的getColumnClass返回一个boolean的class, jtable会自动画一个Jcheckbox给你, * 你的value是true还是false直接读table里那个cell的值就可以 */ @Override public Class getColumnClass(int columnIndex) { return typeArray[columnIndex];// 返回每一列的数据类型 } } private void onOK() { GetConstructField(a); // add your code here dispose(); } private void onCancel() { // add your code here if necessary dispose(); } }
9244cb24a271be55bcaa2c4cf67546a3291a4705
3,649
java
Java
chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/IncognitoTabModelTest.java
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/IncognitoTabModelTest.java
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/IncognitoTabModelTest.java
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
38.410526
99
0.73801
1,003,145
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.tabmodel; import android.support.test.filters.MediumTest; import android.support.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabLaunchType; import org.chromium.chrome.browser.tab.TabState; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.util.ApplicationTestUtils; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.test.util.CriteriaHelper; import org.chromium.content_public.browser.test.util.TestThreadUtils; /** * Tests for IncognitoTabModel. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class IncognitoTabModelTest { @Rule public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); private TabModel mTabModel; @Before public void setUp() throws InterruptedException { mActivityTestRule.startMainActivityOnBlankPage(); mTabModel = mActivityTestRule.getActivity().getTabModelSelector().getModel(true); } private class CloseAllDuringAddTabTabModelObserver extends EmptyTabModelObserver { @Override public void willAddTab(Tab tab, @TabLaunchType int type) { mTabModel.closeAllTabs(); } } private void createTabOnUiThread() { TestThreadUtils.runOnUiThreadBlocking(() -> { mActivityTestRule.getActivity().getTabCreator(true).createNewTab( new LoadUrlParams("about:blank"), TabLaunchType.FROM_CHROME_UI, null); }); } /** * Verify that a close all operation that occurs while a tab is being added does not crash the * browser and results in 1 valid tab. This test simulates the case where the user selects * "Close all incognito tabs" then quickly clicks the "+" button to add a new incognito tab. * See crbug.com/496651. */ @Test @SmallTest @Feature({"OffTheRecord"}) @RetryOnFailure public void testCloseAllDuringAddTabDoesNotCrash() { createTabOnUiThread(); Assert.assertEquals(1, mTabModel.getCount()); mTabModel.addObserver(new CloseAllDuringAddTabTabModelObserver()); createTabOnUiThread(); Assert.assertEquals(1, mTabModel.getCount()); } @Test @MediumTest @Feature({"OffTheRecord"}) public void testRecreateInIncognito() { createTabOnUiThread(); // Need to wait for contentsState to be initialized for the tab to restore correctly. CriteriaHelper.pollUiThread(() -> { return TabState.from(mActivityTestRule.getActivity().getActivityTab()).contentsState != null; }); ChromeTabbedActivity newActivity = ApplicationTestUtils.recreateActivity(mActivityTestRule.getActivity()); CriteriaHelper.pollUiThread(() -> newActivity.getTabModelSelector().isIncognitoSelected()); } }
9244cba2a562e09369feb2be20010c820e8ddd33
1,932
java
Java
app/src/main/java/com/android/batdemir/library/ui/ui_default/activities/maps/MapsActivity.java
batdemirorg/android.batdemir.library
8a1f06af3828f377f82b834bf2407f93cc5304f7
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/android/batdemir/library/ui/ui_default/activities/maps/MapsActivity.java
batdemirorg/android.batdemir.library
8a1f06af3828f377f82b834bf2407f93cc5304f7
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/android/batdemir/library/ui/ui_default/activities/maps/MapsActivity.java
batdemirorg/android.batdemir.library
8a1f06af3828f377f82b834bf2407f93cc5304f7
[ "Apache-2.0" ]
null
null
null
41.106383
117
0.745859
1,003,146
package com.android.batdemir.library.ui.ui_default.activities.maps; import android.os.Bundle; import androidx.fragment.app.FragmentActivity; import com.android.batdemir.library.R; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.Objects; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); Objects.requireNonNull(mapFragment).getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } }
9244cd1d7ca5ff86f72a03336818e2e47f8b0f68
328
java
Java
compiler/testData/asJava/ultraLightClasses/localClassDerived.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
45,293
2015-01-01T06:23:46.000Z
2022-03-31T21:55:51.000Z
compiler/testData/asJava/ultraLightClasses/localClassDerived.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
3,386
2015-01-12T13:28:50.000Z
2022-03-31T17:48:15.000Z
compiler/testData/asJava/ultraLightClasses/localClassDerived.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
6,351
2015-01-03T12:30:09.000Z
2022-03-31T20:46:54.000Z
20.5
78
0.661585
1,003,147
public final class Boo /* Boo*/ { public Boo();// .ctor() public final void fooBar();// fooBar() } public static final class LocalClassBase /* null*/ { public LocalClassBase();// .ctor() } public static final class LocalClassDerived /* null*/ extends LocalClassBase { public LocalClassDerived();// .ctor() }
9244ce305ded91e43022dc46612f63c9bcecb03c
1,764
java
Java
symbol/src/main/java/fr/itris/glips/library/color/SVGW3CColor.java
zhangdan660/jgdraw
7762908477af1c4bb56f73a6789342bbea810a6a
[ "Apache-2.0" ]
null
null
null
symbol/src/main/java/fr/itris/glips/library/color/SVGW3CColor.java
zhangdan660/jgdraw
7762908477af1c4bb56f73a6789342bbea810a6a
[ "Apache-2.0" ]
null
null
null
symbol/src/main/java/fr/itris/glips/library/color/SVGW3CColor.java
zhangdan660/jgdraw
7762908477af1c4bb56f73a6789342bbea810a6a
[ "Apache-2.0" ]
null
null
null
31.589286
73
0.647258
1,003,148
/* * Created on 18 févr. 2005 ============================================= GNU LESSER GENERAL PUBLIC LICENSE Version 2.1 ============================================= GLIPS Graffiti Editor, a SVG Editor Copyright (C) 2003 Jordi SUC, Philippe Gil, SARL ITRIS This library 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 library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact : [email protected]; [email protected] ============================================= */ package fr.itris.glips.library.color; import java.awt.*; /** * the class describing the standard w3c colors * * @author ITRIS, Jordi SUC */ public class SVGW3CColor extends SVGColor { /** * the constructor of the class * @param w3cName the name of the color in the w3c standards * @param shownColor the color that should be shown */ public SVGW3CColor(String w3cName, Color shownColor){ super(w3cName, shownColor); } /** * @return a string representation of this color */ public String getStringRepresentation(){ return id+" : rgb("+getRed()+", "+getGreen()+" ,"+getBlue()+")"; } }
9244ce39e8d108ac8b0bd163991d029c1973fbe7
475
java
Java
online-course-commons/src/main/java/com/course/commons/constant/TimeConstants.java
small-tangerine/online-course
4f89623c44a6ca05867969f605f66c543137d52a
[ "MIT" ]
null
null
null
online-course-commons/src/main/java/com/course/commons/constant/TimeConstants.java
small-tangerine/online-course
4f89623c44a6ca05867969f605f66c543137d52a
[ "MIT" ]
null
null
null
online-course-commons/src/main/java/com/course/commons/constant/TimeConstants.java
small-tangerine/online-course
4f89623c44a6ca05867969f605f66c543137d52a
[ "MIT" ]
null
null
null
22.619048
80
0.661053
1,003,149
package com.course.commons.constant; /** * 时间默认格式 * * @since 2022-01-25 */ public class TimeConstants { private TimeConstants(){ throw new IllegalStateException("Utility class"); } /** 默认日期时间格式 */ public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** 默认日期格式 */ public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; /** 默认时间格式 */ public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss"; }
9244d03e65aa4fef4253227ebdf24dc60eaba254
1,403
java
Java
app/src/main/java/demo2/com/example/liuqiuyue/shop/bean/Page.java
Liuqiuyue0/shop
ecc36dc894d5046cdcdae64f4ebe9859fe581c25
[ "MIT" ]
10
2017-12-04T02:51:57.000Z
2019-12-30T09:51:48.000Z
app/src/main/java/demo2/com/example/liuqiuyue/shop/bean/Page.java
Liuqiuyue0/shop
ecc36dc894d5046cdcdae64f4ebe9859fe581c25
[ "MIT" ]
null
null
null
app/src/main/java/demo2/com/example/liuqiuyue/shop/bean/Page.java
Liuqiuyue0/shop
ecc36dc894d5046cdcdae64f4ebe9859fe581c25
[ "MIT" ]
3
2019-10-16T17:03:16.000Z
2022-02-20T12:23:10.000Z
18.706667
49
0.610121
1,003,150
package demo2.com.example.liuqiuyue.shop.bean; import java.util.List; /** * Created by liuqiuyue on 2017/4/12. */ public class Page<T> { private String copyright; private int totalCount; private int currentPage; private int totalPage; private int pageSize; private List<T> orders; private List<T> list; public List<T> getOrders() { return orders; } public void setOrders(List<T> orders) { this.orders = orders; } public String getCopyright() { return copyright; } public void setCopyright(String copyright) { this.copyright = copyright; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } }
9244d172dc29c7fb893ec178c82957f99b5e7291
19,095
java
Java
gpff-commons/src/main/java/ve/com/sios/gpff/legacy/message/RECAPMFMMessage.java
jestevez/portfolio-trusts-funds
0ec2e8431587209f7b59b55b3692ec24a84a8b78
[ "Apache-2.0" ]
1
2019-07-02T10:01:31.000Z
2019-07-02T10:01:31.000Z
gpff-commons/src/main/java/ve/com/sios/gpff/legacy/message/RECAPMFMMessage.java
jestevez/portfolio-trusts-funds
0ec2e8431587209f7b59b55b3692ec24a84a8b78
[ "Apache-2.0" ]
null
null
null
gpff-commons/src/main/java/ve/com/sios/gpff/legacy/message/RECAPMFMMessage.java
jestevez/portfolio-trusts-funds
0ec2e8431587209f7b59b55b3692ec24a84a8b78
[ "Apache-2.0" ]
1
2021-04-21T18:52:59.000Z
2021-04-21T18:52:59.000Z
25.24106
79
0.578633
1,003,151
package ve.com.sios.gpff.legacy.message; import java.math.BigDecimal; import java.util.Hashtable; import ve.com.sios.gpff.legacy.sockets.CharacterField; import ve.com.sios.gpff.legacy.sockets.DecimalField; import ve.com.sios.gpff.legacy.sockets.MessageField; import ve.com.sios.gpff.legacy.sockets.MessageRecord; /** * Class generated by AS/400 CRTCLASS command from RECAPMFM physical file * definition. * * File level identifier is 1140322124747. Record format level identifier is * ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7. */ public class RECAPMFMMessage extends MessageRecord { final static String fldnames[] = { "HDAT", "HTIM", "HUSR", "HENV", "HXML", "HSEC", "HFIL", "HLEN", "INDICA", "REGCUR", "CAMCUR", "POSCUR", "CLAV", "FIDNOM", "TIPO", "CLINIF", "FECAP", "DISMNT", "MOVPGO", "TEXTO", "DATMIN", "DATMAE", "NOMBRE", "HMOINT", "CLINOM", "CLIAPE", "CLIAP2", "CTA", "TCT" }; final static String tnames[] = { "HDAT", "HTIM", "HUSR", "HENV", "HXML", "HSEC", "HFIL", "HLEN", "INDICA", "REGCUR", "CAMCUR", "POSCUR", "CLAV", "FIDNOM", "TIPO", "CLINIF", "FECAP", "DISMNT", "MOVPGO", "TEXTO", "DATMIN", "DATMAE", "NOMBRE", "HMOINT", "CLINOM", "CLIAPE", "CLIAP2", "CTA", "TCT" }; final static String fid = "1140322124747"; final static String rid = "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"; final static String fmtname = "RECAPMFM"; final int FIELDCOUNT = 29; private static Hashtable tlookup = new Hashtable(); private DecimalField fieldHDAT = null; private DecimalField fieldHTIM = null; private CharacterField fieldHUSR = null; private CharacterField fieldHENV = null; private CharacterField fieldHXML = null; private CharacterField fieldHSEC = null; private CharacterField fieldHFIL = null; private DecimalField fieldHLEN = null; private CharacterField fieldINDICA = null; private CharacterField fieldREGCUR = null; private CharacterField fieldCAMCUR = null; private DecimalField fieldPOSCUR = null; private CharacterField fieldCLAV = null; private CharacterField fieldFIDNOM = null; private CharacterField fieldTIPO = null; private CharacterField fieldCLINIF = null; private DecimalField fieldFECAP = null; private DecimalField fieldDISMNT = null; private DecimalField fieldMOVPGO = null; private CharacterField fieldTEXTO = null; private DecimalField fieldDATMIN = null; private DecimalField fieldDATMAE = null; private CharacterField fieldNOMBRE = null; private DecimalField fieldHMOINT = null; private CharacterField fieldCLINOM = null; private CharacterField fieldCLIAPE = null; private CharacterField fieldCLIAP2 = null; private CharacterField fieldCTA = null; private CharacterField fieldTCT = null; /** * Constructor for RECAPMFMMessage. */ public RECAPMFMMessage() { createFields(); initialize(); } /** * Create fields for this message. This method implements the abstract * method in the MessageRecord superclass. */ protected void createFields() { recordsize = 485; fileid = fid; recordid = rid; message = new byte[getByteLength()]; formatname = fmtname; fieldnames = fldnames; tagnames = tnames; fields = new MessageField[FIELDCOUNT]; fields[0] = fieldHDAT = new DecimalField(message, HEADERSIZE + 0, 7, 0, "HDAT"); fields[1] = fieldHTIM = new DecimalField(message, HEADERSIZE + 7, 7, 0, "HTIM"); fields[2] = fieldHUSR = new CharacterField(message, HEADERSIZE + 14, 10, "HUSR"); fields[3] = fieldHENV = new CharacterField(message, HEADERSIZE + 24, 1, "HENV"); fields[4] = fieldHXML = new CharacterField(message, HEADERSIZE + 25, 10, "HXML"); fields[5] = fieldHSEC = new CharacterField(message, HEADERSIZE + 35, 10, "HSEC"); fields[6] = fieldHFIL = new CharacterField(message, HEADERSIZE + 45, 10, "HFIL"); fields[7] = fieldHLEN = new DecimalField(message, HEADERSIZE + 55, 6, 0, "HLEN"); fields[8] = fieldINDICA = new CharacterField(message, HEADERSIZE + 61, 100, "INDICA"); fields[9] = fieldREGCUR = new CharacterField(message, HEADERSIZE + 161, 10, "REGCUR"); fields[10] = fieldCAMCUR = new CharacterField(message, HEADERSIZE + 171, 10, "CAMCUR"); fields[11] = fieldPOSCUR = new DecimalField(message, HEADERSIZE + 181, 5, 0, "POSCUR"); fields[12] = fieldCLAV = new CharacterField(message, HEADERSIZE + 186, 4, "CLAV"); fields[13] = fieldFIDNOM = new CharacterField(message, HEADERSIZE + 190, 40, "FIDNOM"); fields[14] = fieldTIPO = new CharacterField(message, HEADERSIZE + 230, 20, "TIPO"); fields[15] = fieldCLINIF = new CharacterField(message, HEADERSIZE + 250, 12, "CLINIF"); fields[16] = fieldFECAP = new DecimalField(message, HEADERSIZE + 262, 7, 0, "FECAP"); fields[17] = fieldDISMNT = new DecimalField(message, HEADERSIZE + 269, 17, 2, "DISMNT"); fields[18] = fieldMOVPGO = new DecimalField(message, HEADERSIZE + 286, 3, 0, "MOVPGO"); fields[19] = fieldTEXTO = new CharacterField(message, HEADERSIZE + 289, 30, "TEXTO"); fields[20] = fieldDATMIN = new DecimalField(message, HEADERSIZE + 319, 14, 2, "DATMIN"); fields[21] = fieldDATMAE = new DecimalField(message, HEADERSIZE + 333, 14, 2, "DATMAE"); fields[22] = fieldNOMBRE = new CharacterField(message, HEADERSIZE + 347, 50, "NOMBRE"); fields[23] = fieldHMOINT = new DecimalField(message, HEADERSIZE + 397, 17, 2, "HMOINT"); fields[24] = fieldCLINOM = new CharacterField(message, HEADERSIZE + 414, 20, "CLINOM"); fields[25] = fieldCLIAPE = new CharacterField(message, HEADERSIZE + 434, 15, "CLIAPE"); fields[26] = fieldCLIAP2 = new CharacterField(message, HEADERSIZE + 449, 15, "CLIAP2"); fields[27] = fieldCTA = new CharacterField(message, HEADERSIZE + 464, 20, "CTA"); fields[28] = fieldTCT = new CharacterField(message, HEADERSIZE + 484, 1, "TCT"); synchronized (tlookup) { if (tlookup.isEmpty()) { for (int i = 0; i < tnames.length; i++) { tlookup.put(tnames[i], new Integer(i)); } } } taglookup = tlookup; } /** * Set field HDAT using a String value. */ public void setHDAT(String newvalue) { fieldHDAT.setString(newvalue); } /** * Get value of field HDAT as a String. */ public String getHDAT() { return fieldHDAT.getString(); } /** * Set numeric field HDAT using a BigDecimal value. */ public void setHDAT(BigDecimal newvalue) { fieldHDAT.setBigDecimal(newvalue); } /** * Return value of numeric field HDAT as a BigDecimal. */ public BigDecimal getBigDecimalHDAT() { return fieldHDAT.getBigDecimal(); } /** * Set field HTIM using a String value. */ public void setHTIM(String newvalue) { fieldHTIM.setString(newvalue); } /** * Get value of field HTIM as a String. */ public String getHTIM() { return fieldHTIM.getString(); } /** * Set numeric field HTIM using a BigDecimal value. */ public void setHTIM(BigDecimal newvalue) { fieldHTIM.setBigDecimal(newvalue); } /** * Return value of numeric field HTIM as a BigDecimal. */ public BigDecimal getBigDecimalHTIM() { return fieldHTIM.getBigDecimal(); } /** * Set field HUSR using a String value. */ public void setHUSR(String newvalue) { fieldHUSR.setString(newvalue); } /** * Get value of field HUSR as a String. */ public String getHUSR() { return fieldHUSR.getString(); } /** * Set field HENV using a String value. */ public void setHENV(String newvalue) { fieldHENV.setString(newvalue); } /** * Get value of field HENV as a String. */ public String getHENV() { return fieldHENV.getString(); } /** * Set field HXML using a String value. */ public void setHXML(String newvalue) { fieldHXML.setString(newvalue); } /** * Get value of field HXML as a String. */ public String getHXML() { return fieldHXML.getString(); } /** * Set field HSEC using a String value. */ public void setHSEC(String newvalue) { fieldHSEC.setString(newvalue); } /** * Get value of field HSEC as a String. */ public String getHSEC() { return fieldHSEC.getString(); } /** * Set field HFIL using a String value. */ public void setHFIL(String newvalue) { fieldHFIL.setString(newvalue); } /** * Get value of field HFIL as a String. */ public String getHFIL() { return fieldHFIL.getString(); } /** * Set field HLEN using a String value. */ public void setHLEN(String newvalue) { fieldHLEN.setString(newvalue); } /** * Get value of field HLEN as a String. */ public String getHLEN() { return fieldHLEN.getString(); } /** * Set numeric field HLEN using a BigDecimal value. */ public void setHLEN(BigDecimal newvalue) { fieldHLEN.setBigDecimal(newvalue); } /** * Return value of numeric field HLEN as a BigDecimal. */ public BigDecimal getBigDecimalHLEN() { return fieldHLEN.getBigDecimal(); } /** * Set field INDICA using a String value. */ public void setINDICA(String newvalue) { fieldINDICA.setString(newvalue); } /** * Get value of field INDICA as a String. */ public String getINDICA() { return fieldINDICA.getString(); } /** * Set field REGCUR using a String value. */ public void setREGCUR(String newvalue) { fieldREGCUR.setString(newvalue); } /** * Get value of field REGCUR as a String. */ public String getREGCUR() { return fieldREGCUR.getString(); } /** * Set field CAMCUR using a String value. */ public void setCAMCUR(String newvalue) { fieldCAMCUR.setString(newvalue); } /** * Get value of field CAMCUR as a String. */ public String getCAMCUR() { return fieldCAMCUR.getString(); } /** * Set field POSCUR using a String value. */ public void setPOSCUR(String newvalue) { fieldPOSCUR.setString(newvalue); } /** * Get value of field POSCUR as a String. */ public String getPOSCUR() { return fieldPOSCUR.getString(); } /** * Set numeric field POSCUR using a BigDecimal value. */ public void setPOSCUR(BigDecimal newvalue) { fieldPOSCUR.setBigDecimal(newvalue); } /** * Return value of numeric field POSCUR as a BigDecimal. */ public BigDecimal getBigDecimalPOSCUR() { return fieldPOSCUR.getBigDecimal(); } /** * Set field CLAV using a String value. */ public void setCLAV(String newvalue) { fieldCLAV.setString(newvalue); } /** * Get value of field CLAV as a String. */ public String getCLAV() { return fieldCLAV.getString(); } /** * Set field FIDNOM using a String value. */ public void setFIDNOM(String newvalue) { fieldFIDNOM.setString(newvalue); } /** * Get value of field FIDNOM as a String. */ public String getFIDNOM() { return fieldFIDNOM.getString(); } /** * Set field TIPO using a String value. */ public void setTIPO(String newvalue) { fieldTIPO.setString(newvalue); } /** * Get value of field TIPO as a String. */ public String getTIPO() { return fieldTIPO.getString(); } /** * Set field CLINIF using a String value. */ public void setCLINIF(String newvalue) { fieldCLINIF.setString(newvalue); } /** * Get value of field CLINIF as a String. */ public String getCLINIF() { return fieldCLINIF.getString(); } /** * Set field FECAP using a String value. */ public void setFECAP(String newvalue) { fieldFECAP.setString(newvalue); } /** * Get value of field FECAP as a String. */ public String getFECAP() { return fieldFECAP.getString(); } /** * Set numeric field FECAP using a BigDecimal value. */ public void setFECAP(BigDecimal newvalue) { fieldFECAP.setBigDecimal(newvalue); } /** * Return value of numeric field FECAP as a BigDecimal. */ public BigDecimal getBigDecimalFECAP() { return fieldFECAP.getBigDecimal(); } /** * Set field DISMNT using a String value. */ public void setDISMNT(String newvalue) { fieldDISMNT.setString(newvalue); } /** * Get value of field DISMNT as a String. */ public String getDISMNT() { return fieldDISMNT.getString(); } /** * Set numeric field DISMNT using a BigDecimal value. */ public void setDISMNT(BigDecimal newvalue) { fieldDISMNT.setBigDecimal(newvalue); } /** * Return value of numeric field DISMNT as a BigDecimal. */ public BigDecimal getBigDecimalDISMNT() { return fieldDISMNT.getBigDecimal(); } /** * Set field MOVPGO using a String value. */ public void setMOVPGO(String newvalue) { fieldMOVPGO.setString(newvalue); } /** * Get value of field MOVPGO as a String. */ public String getMOVPGO() { return fieldMOVPGO.getString(); } /** * Set numeric field MOVPGO using a BigDecimal value. */ public void setMOVPGO(BigDecimal newvalue) { fieldMOVPGO.setBigDecimal(newvalue); } /** * Return value of numeric field MOVPGO as a BigDecimal. */ public BigDecimal getBigDecimalMOVPGO() { return fieldMOVPGO.getBigDecimal(); } /** * Set field TEXTO using a String value. */ public void setTEXTO(String newvalue) { fieldTEXTO.setString(newvalue); } /** * Get value of field TEXTO as a String. */ public String getTEXTO() { return fieldTEXTO.getString(); } /** * Set field DATMIN using a String value. */ public void setDATMIN(String newvalue) { fieldDATMIN.setString(newvalue); } /** * Get value of field DATMIN as a String. */ public String getDATMIN() { return fieldDATMIN.getString(); } /** * Set numeric field DATMIN using a BigDecimal value. */ public void setDATMIN(BigDecimal newvalue) { fieldDATMIN.setBigDecimal(newvalue); } /** * Return value of numeric field DATMIN as a BigDecimal. */ public BigDecimal getBigDecimalDATMIN() { return fieldDATMIN.getBigDecimal(); } /** * Set field DATMAE using a String value. */ public void setDATMAE(String newvalue) { fieldDATMAE.setString(newvalue); } /** * Get value of field DATMAE as a String. */ public String getDATMAE() { return fieldDATMAE.getString(); } /** * Set numeric field DATMAE using a BigDecimal value. */ public void setDATMAE(BigDecimal newvalue) { fieldDATMAE.setBigDecimal(newvalue); } /** * Return value of numeric field DATMAE as a BigDecimal. */ public BigDecimal getBigDecimalDATMAE() { return fieldDATMAE.getBigDecimal(); } /** * Set field NOMBRE using a String value. */ public void setNOMBRE(String newvalue) { fieldNOMBRE.setString(newvalue); } /** * Get value of field NOMBRE as a String. */ public String getNOMBRE() { return fieldNOMBRE.getString(); } /** * Set field HMOINT using a String value. */ public void setHMOINT(String newvalue) { fieldHMOINT.setString(newvalue); } /** * Get value of field HMOINT as a String. */ public String getHMOINT() { return fieldHMOINT.getString(); } /** * Set numeric field HMOINT using a BigDecimal value. */ public void setHMOINT(BigDecimal newvalue) { fieldHMOINT.setBigDecimal(newvalue); } /** * Return value of numeric field HMOINT as a BigDecimal. */ public BigDecimal getBigDecimalHMOINT() { return fieldHMOINT.getBigDecimal(); } /** * Set field CLINOM using a String value. */ public void setCLINOM(String newvalue) { fieldCLINOM.setString(newvalue); } /** * Get value of field CLINOM as a String. */ public String getCLINOM() { return fieldCLINOM.getString(); } /** * Set field CLIAPE using a String value. */ public void setCLIAPE(String newvalue) { fieldCLIAPE.setString(newvalue); } /** * Get value of field CLIAPE as a String. */ public String getCLIAPE() { return fieldCLIAPE.getString(); } /** * Set field CLIAP2 using a String value. */ public void setCLIAP2(String newvalue) { fieldCLIAP2.setString(newvalue); } /** * Get value of field CLIAP2 as a String. */ public String getCLIAP2() { return fieldCLIAP2.getString(); } /** * Set field CTA using a String value. */ public void setCTA(String newvalue) { fieldCTA.setString(newvalue); } /** * Get value of field CTA as a String. */ public String getCTA() { return fieldCTA.getString(); } /** * Set field TCT using a String value. */ public void setTCT(String newvalue) { fieldTCT.setString(newvalue); } /** * Get value of field TCT as a String. */ public String getTCT() { return fieldTCT.getString(); } }
9244d1748ec524e0e6193f5db42cd587f09ad4be
3,873
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Mark1/Auto/WarehousePark.java
garagebot15146/freight-frenzy
8179629538b441d61dc37e3b79e29a1eb618404a
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Mark1/Auto/WarehousePark.java
garagebot15146/freight-frenzy
8179629538b441d61dc37e3b79e29a1eb618404a
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Mark1/Auto/WarehousePark.java
garagebot15146/freight-frenzy
8179629538b441d61dc37e3b79e29a1eb618404a
[ "MIT" ]
null
null
null
39.520408
208
0.64188
1,003,152
//package org.firstinspires.ftc.teamcode.Mark1.Auto; // //import com.qualcomm.robotcore.eventloop.opmode.Autonomous; //import com.qualcomm.robotcore.eventloop.opmode.Disabled; //import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; //import com.qualcomm.robotcore.hardware.DcMotor; //import com.qualcomm.robotcore.util.ElapsedTime; //import org.firstinspires.ftc.teamcode.Settings.HWMapTeleOp; // // //@Autonomous(name = "Warehouse Park", group = "Autonomous") //@Disabled //public class WarehousePark extends LinearOpMode { // // //Runtime // private ElapsedTime runtime = new ElapsedTime(); // // //HWMap // HWMapTeleOp robot = new HWMapTeleOp(); // // // @Override // public void runOpMode() { // //Hardware map // robot.init(hardwareMap); // // // telemetry.addData("Status", "Pipeline Initializing"); // telemetry.update(); // // waitForStart(); // if (isStopRequested()) return; // telemetry.update(); // // encoderDrive(0.5, -30, -30, 5); // } // // // public void pause(double seconds){ // runtime.reset(); // while (opModeIsActive() && runtime.seconds() < seconds) { // } // // } // // public void encoderDrive(double speed, double leftInches, double rightInches, double timeoutS) { // int newLeftFrontTarget; // int newLeftRearTarget; // int newRightFrontTarget; // int newRightRearTarget; // // // // Ensure that the opmode is still active // if (opModeIsActive()) { // // // Determine new target position, and pass to motor controller // newLeftFrontTarget = robot.leftFrontMotor.getCurrentPosition() + (int)(leftInches * 50); // newLeftRearTarget = robot.leftBackMotor.getCurrentPosition() + (int)(leftInches * 200); // newRightFrontTarget = robot.rightFrontMotor.getCurrentPosition() + (int)(rightInches * 200); // newRightRearTarget = robot.rightBackMotor.getCurrentPosition() + (int)(rightInches * 200); // // robot.leftFrontMotor.setTargetPosition(newLeftFrontTarget); // robot.leftBackMotor.setTargetPosition(newLeftRearTarget); // robot.rightFrontMotor.setTargetPosition(newRightFrontTarget); // robot.rightBackMotor.setTargetPosition(newRightRearTarget); // // // Turn On RUN_TO_POSITION // robot.leftFrontMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); // robot.leftBackMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); // robot.rightFrontMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); // robot.rightBackMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); // // // reset the timeout time and start motion. // runtime.reset(); // robot.leftFrontMotor.setPower(speed); // robot.leftBackMotor.setPower(speed); // robot.rightFrontMotor.setPower(speed); // robot.rightBackMotor.setPower(speed); // // while (opModeIsActive() && (runtime.seconds() < timeoutS) && (robot.leftFrontMotor.isBusy() && robot.leftBackMotor.isBusy() && robot.rightFrontMotor.isBusy() && robot.rightBackMotor.isBusy())) { // robot.intakeMotor.setPower(1); // } // // // Stop all motion; // robot.leftFrontMotor.setPower(0); // robot.leftBackMotor.setPower(0); // robot.rightFrontMotor.setPower(0); // robot.rightBackMotor.setPower(0); // // // Turn off RUN_TO_POSITION // robot.leftFrontMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); // robot.leftBackMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); // robot.rightFrontMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); // robot.rightBackMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); // } // } //}
9244d204944ce0e06ab7d2718c1b7e2588cf6cba
2,678
java
Java
src/minecraft/net/minecraft/command/server/CommandPardonIp.java
SolarEntropy/Minecraft
2de569a3a13c0cce48404bca09bde425d8bde4a8
[ "Apache-2.0" ]
8
2016-03-11T08:37:03.000Z
2021-07-09T14:13:05.000Z
src/minecraft/net/minecraft/command/server/CommandPardonIp.java
SolarEntropy/Minecraft
2de569a3a13c0cce48404bca09bde425d8bde4a8
[ "Apache-2.0" ]
7
2016-03-24T19:12:58.000Z
2016-06-05T07:05:06.000Z
src/minecraft/net/minecraft/command/server/CommandPardonIp.java
SolarEntropy/Minecraft
2de569a3a13c0cce48404bca09bde425d8bde4a8
[ "Apache-2.0" ]
19
2016-03-06T21:44:04.000Z
2021-09-26T15:06:19.000Z
31.505882
156
0.658701
1,003,153
package net.minecraft.command.server; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.command.SyntaxErrorException; import net.minecraft.command.WrongUsageException; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; public class CommandPardonIp extends CommandBase { /** * Gets the name of the command */ public String getCommandName() { return "pardon-ip"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 3; } /** * Check if the given ICommandSender has permission to execute this command * * @param server The Minecraft server instance * @param sender The command sender who we are checking permission on */ public boolean checkPermission(MinecraftServer server, ICommandSender sender) { return server.getPlayerList().getBannedIPs().isLanServer() && super.checkPermission(server, sender); } /** * Gets the usage string for the command. */ public String getCommandUsage(ICommandSender sender) { return "commands.unbanip.usage"; } /** * Callback for when the command is executed * * @param server The Minecraft server instance * @param sender The source of the command invocation * @param args The arguments that were passed */ public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length == 1 && args[0].length() > 1) { Matcher matcher = CommandBanIp.field_147211_a.matcher(args[0]); if (matcher.matches()) { server.getPlayerList().getBannedIPs().removeEntry(args[0]); notifyOperators(sender, this, "commands.unbanip.success", new Object[] {args[0]}); } else { throw new SyntaxErrorException("commands.unbanip.invalid", new Object[0]); } } else { throw new WrongUsageException("commands.unbanip.usage", new Object[0]); } } public List<String> getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { return args.length == 1 ? getListOfStringsMatchingLastWord(args, server.getPlayerList().getBannedIPs().getKeys()) : Collections.<String>emptyList(); } }
9244d20fbf07ed20cc60a663f9279fd5d99e563c
1,020
java
Java
src/test/java/graph/SAXErrorHandler.java
NinePts/OntoGraph
c35aec2345b2e4e31ce78ee16f2feb639f7c832a
[ "Apache-2.0" ]
23
2017-09-12T22:51:07.000Z
2022-03-07T12:43:00.000Z
src/test/java/graph/SAXErrorHandler.java
NinePts/OntoGraph
c35aec2345b2e4e31ce78ee16f2feb639f7c832a
[ "Apache-2.0" ]
38
2017-09-12T03:11:14.000Z
2019-04-12T12:40:30.000Z
src/test/java/graph/SAXErrorHandler.java
NinePts/OntoGraph
c35aec2345b2e4e31ce78ee16f2feb639f7c832a
[ "Apache-2.0" ]
8
2017-10-06T18:56:51.000Z
2021-01-05T14:34:09.000Z
30
75
0.747059
1,003,154
/** * Copyright (c) Nine Points Solutions, LLC * * 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 graph; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class SAXErrorHandler extends DefaultHandler { public void warning(SAXParseException e) throws SAXException { } public void error(SAXParseException e) throws SAXException { } public void fatalError(SAXParseException e) throws SAXException { } }
9244d22051601118e3e66e89ffa64ab9409f5df5
22,224
java
Java
src/com/festp/utils/UtilsColor.java
festino/hodgepodge
5182f3c84ba411fa244ee43e07d0588701b15449
[ "MIT" ]
1
2018-10-23T13:35:29.000Z
2018-10-23T13:35:29.000Z
src/com/festp/utils/UtilsColor.java
festino/hodgepodge
5182f3c84ba411fa244ee43e07d0588701b15449
[ "MIT" ]
null
null
null
src/com/festp/utils/UtilsColor.java
festino/hodgepodge
5182f3c84ba411fa244ee43e07d0588701b15449
[ "MIT" ]
1
2018-10-23T13:35:30.000Z
2018-10-23T13:35:30.000Z
42.493308
121
0.804716
1,003,155
package com.festp.utils; import org.bukkit.DyeColor; import org.bukkit.Material; public class UtilsColor { //(wall) banner, bed, carpet, concrete, concrete powder, glass(pane), wool, shulker box, terracotta, glazed, dye or null public static DyeColor colorFromMaterial(Material m) { switch(m) { //banner case WHITE_BANNER: return DyeColor.WHITE; case ORANGE_BANNER: return DyeColor.ORANGE; case MAGENTA_BANNER: return DyeColor.MAGENTA; case LIGHT_BLUE_BANNER: return DyeColor.LIGHT_BLUE; case YELLOW_BANNER: return DyeColor.YELLOW; case LIME_BANNER: return DyeColor.LIME; case PINK_BANNER: return DyeColor.PINK; case GRAY_BANNER: return DyeColor.GRAY; case LIGHT_GRAY_BANNER: return DyeColor.LIGHT_GRAY; case CYAN_BANNER: return DyeColor.CYAN; case PURPLE_BANNER: return DyeColor.PURPLE; case BLUE_BANNER: return DyeColor.BLUE; case BROWN_BANNER: return DyeColor.BROWN; case GREEN_BANNER: return DyeColor.GREEN; case RED_BANNER: return DyeColor.RED; case BLACK_BANNER: return DyeColor.BLACK; //wall_banner case WHITE_WALL_BANNER: return DyeColor.WHITE; case ORANGE_WALL_BANNER: return DyeColor.ORANGE; case MAGENTA_WALL_BANNER: return DyeColor.MAGENTA; case LIGHT_BLUE_WALL_BANNER: return DyeColor.LIGHT_BLUE; case YELLOW_WALL_BANNER: return DyeColor.YELLOW; case LIME_WALL_BANNER: return DyeColor.LIME; case PINK_WALL_BANNER: return DyeColor.PINK; case GRAY_WALL_BANNER: return DyeColor.GRAY; case LIGHT_GRAY_WALL_BANNER: return DyeColor.LIGHT_GRAY; case CYAN_WALL_BANNER: return DyeColor.CYAN; case PURPLE_WALL_BANNER: return DyeColor.PURPLE; case BLUE_WALL_BANNER: return DyeColor.BLUE; case BROWN_WALL_BANNER: return DyeColor.BROWN; case GREEN_WALL_BANNER: return DyeColor.GREEN; case RED_WALL_BANNER: return DyeColor.RED; case BLACK_WALL_BANNER: return DyeColor.BLACK; //bed case WHITE_BED: return DyeColor.WHITE; case ORANGE_BED: return DyeColor.ORANGE; case MAGENTA_BED: return DyeColor.MAGENTA; case LIGHT_BLUE_BED: return DyeColor.LIGHT_BLUE; case YELLOW_BED: return DyeColor.YELLOW; case LIME_BED: return DyeColor.LIME; case PINK_BED: return DyeColor.PINK; case GRAY_BED: return DyeColor.GRAY; case LIGHT_GRAY_BED: return DyeColor.LIGHT_GRAY; case CYAN_BED: return DyeColor.CYAN; case PURPLE_BED: return DyeColor.PURPLE; case BLUE_BED: return DyeColor.BLUE; case BROWN_BED: return DyeColor.BROWN; case GREEN_BED: return DyeColor.GREEN; case RED_BED: return DyeColor.RED; case BLACK_BED: return DyeColor.BLACK; //carpet case WHITE_CARPET: return DyeColor.WHITE; case ORANGE_CARPET: return DyeColor.ORANGE; case MAGENTA_CARPET: return DyeColor.MAGENTA; case LIGHT_BLUE_CARPET: return DyeColor.LIGHT_BLUE; case YELLOW_CARPET: return DyeColor.YELLOW; case LIME_CARPET: return DyeColor.LIME; case PINK_CARPET: return DyeColor.PINK; case GRAY_CARPET: return DyeColor.GRAY; case LIGHT_GRAY_CARPET: return DyeColor.LIGHT_GRAY; case CYAN_CARPET: return DyeColor.CYAN; case PURPLE_CARPET: return DyeColor.PURPLE; case BLUE_CARPET: return DyeColor.BLUE; case BROWN_CARPET: return DyeColor.BROWN; case GREEN_CARPET: return DyeColor.GREEN; case RED_CARPET: return DyeColor.RED; case BLACK_CARPET: return DyeColor.BLACK; //concrete_powder case WHITE_CONCRETE_POWDER: return DyeColor.WHITE; case ORANGE_CONCRETE_POWDER: return DyeColor.ORANGE; case MAGENTA_CONCRETE_POWDER: return DyeColor.MAGENTA; case LIGHT_BLUE_CONCRETE_POWDER: return DyeColor.LIGHT_BLUE; case YELLOW_CONCRETE_POWDER: return DyeColor.YELLOW; case LIME_CONCRETE_POWDER: return DyeColor.LIME; case PINK_CONCRETE_POWDER: return DyeColor.PINK; case GRAY_CONCRETE_POWDER: return DyeColor.GRAY; case LIGHT_GRAY_CONCRETE_POWDER: return DyeColor.LIGHT_GRAY; case CYAN_CONCRETE_POWDER: return DyeColor.CYAN; case PURPLE_CONCRETE_POWDER: return DyeColor.PURPLE; case BLUE_CONCRETE_POWDER: return DyeColor.BLUE; case BROWN_CONCRETE_POWDER: return DyeColor.BROWN; case GREEN_CONCRETE_POWDER: return DyeColor.GREEN; case RED_CONCRETE_POWDER: return DyeColor.RED; case BLACK_CONCRETE_POWDER: return DyeColor.BLACK; //concrete case WHITE_CONCRETE: return DyeColor.WHITE; case ORANGE_CONCRETE: return DyeColor.ORANGE; case MAGENTA_CONCRETE: return DyeColor.MAGENTA; case LIGHT_BLUE_CONCRETE: return DyeColor.LIGHT_BLUE; case YELLOW_CONCRETE: return DyeColor.YELLOW; case LIME_CONCRETE: return DyeColor.LIME; case PINK_CONCRETE: return DyeColor.PINK; case GRAY_CONCRETE: return DyeColor.GRAY; case LIGHT_GRAY_CONCRETE: return DyeColor.LIGHT_GRAY; case CYAN_CONCRETE: return DyeColor.CYAN; case PURPLE_CONCRETE: return DyeColor.PURPLE; case BLUE_CONCRETE: return DyeColor.BLUE; case BROWN_CONCRETE: return DyeColor.BROWN; case GREEN_CONCRETE: return DyeColor.GREEN; case RED_CONCRETE: return DyeColor.RED; case BLACK_CONCRETE: return DyeColor.BLACK; //glass case WHITE_STAINED_GLASS: return DyeColor.WHITE; case ORANGE_STAINED_GLASS: return DyeColor.ORANGE; case MAGENTA_STAINED_GLASS: return DyeColor.MAGENTA; case LIGHT_BLUE_STAINED_GLASS: return DyeColor.LIGHT_BLUE; case YELLOW_STAINED_GLASS: return DyeColor.YELLOW; case LIME_STAINED_GLASS: return DyeColor.LIME; case PINK_STAINED_GLASS: return DyeColor.PINK; case GRAY_STAINED_GLASS: return DyeColor.GRAY; case LIGHT_GRAY_STAINED_GLASS: return DyeColor.LIGHT_GRAY; case CYAN_STAINED_GLASS: return DyeColor.CYAN; case PURPLE_STAINED_GLASS: return DyeColor.PURPLE; case BLUE_STAINED_GLASS: return DyeColor.BLUE; case BROWN_STAINED_GLASS: return DyeColor.BROWN; case GREEN_STAINED_GLASS: return DyeColor.GREEN; case RED_STAINED_GLASS: return DyeColor.RED; case BLACK_STAINED_GLASS: return DyeColor.BLACK; //glass_pane case WHITE_STAINED_GLASS_PANE: return DyeColor.WHITE; case ORANGE_STAINED_GLASS_PANE: return DyeColor.ORANGE; case MAGENTA_STAINED_GLASS_PANE: return DyeColor.MAGENTA; case LIGHT_BLUE_STAINED_GLASS_PANE: return DyeColor.LIGHT_BLUE; case YELLOW_STAINED_GLASS_PANE: return DyeColor.YELLOW; case LIME_STAINED_GLASS_PANE: return DyeColor.LIME; case PINK_STAINED_GLASS_PANE: return DyeColor.PINK; case GRAY_STAINED_GLASS_PANE: return DyeColor.GRAY; case LIGHT_GRAY_STAINED_GLASS_PANE: return DyeColor.LIGHT_GRAY; case CYAN_STAINED_GLASS_PANE: return DyeColor.CYAN; case PURPLE_STAINED_GLASS_PANE: return DyeColor.PURPLE; case BLUE_STAINED_GLASS_PANE: return DyeColor.BLUE; case BROWN_STAINED_GLASS_PANE: return DyeColor.BROWN; case GREEN_STAINED_GLASS_PANE: return DyeColor.GREEN; case RED_STAINED_GLASS_PANE: return DyeColor.RED; case BLACK_STAINED_GLASS_PANE: return DyeColor.BLACK; //wool case WHITE_WOOL: return DyeColor.WHITE; case ORANGE_WOOL: return DyeColor.ORANGE; case MAGENTA_WOOL: return DyeColor.MAGENTA; case LIGHT_BLUE_WOOL: return DyeColor.LIGHT_BLUE; case YELLOW_WOOL: return DyeColor.YELLOW; case LIME_WOOL: return DyeColor.LIME; case PINK_WOOL: return DyeColor.PINK; case GRAY_WOOL: return DyeColor.GRAY; case LIGHT_GRAY_WOOL: return DyeColor.LIGHT_GRAY; case CYAN_WOOL: return DyeColor.CYAN; case PURPLE_WOOL: return DyeColor.PURPLE; case BLUE_WOOL: return DyeColor.BLUE; case BROWN_WOOL: return DyeColor.BROWN; case GREEN_WOOL: return DyeColor.GREEN; case RED_WOOL: return DyeColor.RED; case BLACK_WOOL: return DyeColor.BLACK; //shulker_box case WHITE_SHULKER_BOX: return DyeColor.WHITE; case ORANGE_SHULKER_BOX: return DyeColor.ORANGE; case MAGENTA_SHULKER_BOX: return DyeColor.MAGENTA; case LIGHT_BLUE_SHULKER_BOX: return DyeColor.LIGHT_BLUE; case YELLOW_SHULKER_BOX: return DyeColor.YELLOW; case LIME_SHULKER_BOX: return DyeColor.LIME; case PINK_SHULKER_BOX: return DyeColor.PINK; case GRAY_SHULKER_BOX: return DyeColor.GRAY; case LIGHT_GRAY_SHULKER_BOX: return DyeColor.LIGHT_GRAY; case CYAN_SHULKER_BOX: return DyeColor.CYAN; case PURPLE_SHULKER_BOX: return DyeColor.PURPLE; case BLUE_SHULKER_BOX: return DyeColor.BLUE; case BROWN_SHULKER_BOX: return DyeColor.BROWN; case GREEN_SHULKER_BOX: return DyeColor.GREEN; case RED_SHULKER_BOX: return DyeColor.RED; case BLACK_SHULKER_BOX: return DyeColor.BLACK; //terracotta case WHITE_TERRACOTTA: return DyeColor.WHITE; case ORANGE_TERRACOTTA: return DyeColor.ORANGE; case MAGENTA_TERRACOTTA: return DyeColor.MAGENTA; case LIGHT_BLUE_TERRACOTTA: return DyeColor.LIGHT_BLUE; case YELLOW_TERRACOTTA: return DyeColor.YELLOW; case LIME_TERRACOTTA: return DyeColor.LIME; case PINK_TERRACOTTA: return DyeColor.PINK; case GRAY_TERRACOTTA: return DyeColor.GRAY; case LIGHT_GRAY_TERRACOTTA: return DyeColor.LIGHT_GRAY; case CYAN_TERRACOTTA: return DyeColor.CYAN; case PURPLE_TERRACOTTA: return DyeColor.PURPLE; case BLUE_TERRACOTTA: return DyeColor.BLUE; case BROWN_TERRACOTTA: return DyeColor.BROWN; case GREEN_TERRACOTTA: return DyeColor.GREEN; case RED_TERRACOTTA: return DyeColor.RED; case BLACK_TERRACOTTA: return DyeColor.BLACK; //glazed_terracotta case WHITE_GLAZED_TERRACOTTA: return DyeColor.WHITE; case ORANGE_GLAZED_TERRACOTTA: return DyeColor.ORANGE; case MAGENTA_GLAZED_TERRACOTTA: return DyeColor.MAGENTA; case LIGHT_BLUE_GLAZED_TERRACOTTA: return DyeColor.LIGHT_BLUE; case YELLOW_GLAZED_TERRACOTTA: return DyeColor.YELLOW; case LIME_GLAZED_TERRACOTTA: return DyeColor.LIME; case PINK_GLAZED_TERRACOTTA: return DyeColor.PINK; case GRAY_GLAZED_TERRACOTTA: return DyeColor.GRAY; case LIGHT_GRAY_GLAZED_TERRACOTTA: return DyeColor.LIGHT_GRAY; case CYAN_GLAZED_TERRACOTTA: return DyeColor.CYAN; case PURPLE_GLAZED_TERRACOTTA: return DyeColor.PURPLE; case BLUE_GLAZED_TERRACOTTA: return DyeColor.BLUE; case BROWN_GLAZED_TERRACOTTA: return DyeColor.BROWN; case GREEN_GLAZED_TERRACOTTA: return DyeColor.GREEN; case RED_GLAZED_TERRACOTTA: return DyeColor.RED; case BLACK_GLAZED_TERRACOTTA: return DyeColor.BLACK; //dyes case WHITE_DYE: return DyeColor.WHITE; case ORANGE_DYE: return DyeColor.ORANGE; case MAGENTA_DYE: return DyeColor.MAGENTA; case LIGHT_BLUE_DYE: return DyeColor.LIGHT_BLUE; case YELLOW_DYE: return DyeColor.YELLOW; case LIME_DYE: return DyeColor.LIME; case PINK_DYE: return DyeColor.PINK; case GRAY_DYE: return DyeColor.GRAY; case LIGHT_GRAY_DYE: return DyeColor.LIGHT_GRAY; case CYAN_DYE: return DyeColor.CYAN; case PURPLE_DYE: return DyeColor.PURPLE; case BLUE_DYE: return DyeColor.BLUE; case BROWN_DYE: return DyeColor.BROWN; case GREEN_DYE: return DyeColor.GREEN; case RED_DYE: return DyeColor.RED; case BLACK_DYE: return DyeColor.BLACK; default: return null; } } public static Material fromColor_banner(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_BANNER; case ORANGE: return Material.ORANGE_BANNER; case MAGENTA: return Material.MAGENTA_BANNER; case LIGHT_BLUE: return Material.LIGHT_BLUE_BANNER; case YELLOW: return Material.YELLOW_BANNER; case LIME: return Material.LIME_BANNER; case PINK: return Material.PINK_BANNER; case GRAY: return Material.GRAY_BANNER; case LIGHT_GRAY: return Material.LIGHT_GRAY_BANNER; case CYAN: return Material.CYAN_BANNER; case PURPLE: return Material.PURPLE_BANNER; case BLUE: return Material.BLUE_BANNER; case BROWN: return Material.BROWN_BANNER; case GREEN: return Material.GREEN_BANNER; case RED: return Material.RED_BANNER; case BLACK: return Material.BLACK_BANNER; default: return null; } } public static Material fromColor_wall_banner(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_WALL_BANNER; case ORANGE: return Material.ORANGE_WALL_BANNER; case MAGENTA: return Material.MAGENTA_WALL_BANNER; case LIGHT_BLUE: return Material.LIGHT_BLUE_WALL_BANNER; case YELLOW: return Material.YELLOW_WALL_BANNER; case LIME: return Material.LIME_WALL_BANNER; case PINK: return Material.PINK_WALL_BANNER; case GRAY: return Material.GRAY_WALL_BANNER; case LIGHT_GRAY: return Material.LIGHT_GRAY_WALL_BANNER; case CYAN: return Material.CYAN_WALL_BANNER; case PURPLE: return Material.PURPLE_WALL_BANNER; case BLUE: return Material.BLUE_WALL_BANNER; case BROWN: return Material.BROWN_WALL_BANNER; case GREEN: return Material.GREEN_WALL_BANNER; case RED: return Material.RED_WALL_BANNER; case BLACK: return Material.BLACK_WALL_BANNER; default: return null; } } public static Material fromColor_bed(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_BED; case ORANGE: return Material.ORANGE_BED; case MAGENTA: return Material.MAGENTA_BED; case LIGHT_BLUE: return Material.LIGHT_BLUE_BED; case YELLOW: return Material.YELLOW_BED; case LIME: return Material.LIME_BED; case PINK: return Material.PINK_BED; case GRAY: return Material.GRAY_BED; case LIGHT_GRAY: return Material.LIGHT_GRAY_BED; case CYAN: return Material.CYAN_BED; case PURPLE: return Material.PURPLE_BED; case BLUE: return Material.BLUE_BED; case BROWN: return Material.BROWN_BED; case GREEN: return Material.GREEN_BED; case RED: return Material.RED_BED; case BLACK: return Material.BLACK_BED; default: return null; } } public static Material fromColor_carpet(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_CARPET; case ORANGE: return Material.ORANGE_CARPET; case MAGENTA: return Material.MAGENTA_CARPET; case LIGHT_BLUE: return Material.LIGHT_BLUE_CARPET; case YELLOW: return Material.YELLOW_CARPET; case LIME: return Material.LIME_CARPET; case PINK: return Material.PINK_CARPET; case GRAY: return Material.GRAY_CARPET; case LIGHT_GRAY: return Material.LIGHT_GRAY_CARPET; case CYAN: return Material.CYAN_CARPET; case PURPLE: return Material.PURPLE_CARPET; case BLUE: return Material.BLUE_CARPET; case BROWN: return Material.BROWN_CARPET; case GREEN: return Material.GREEN_CARPET; case RED: return Material.RED_CARPET; case BLACK: return Material.BLACK_CARPET; default: return null; } } public static Material fromColor_concrete(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_CONCRETE; case ORANGE: return Material.ORANGE_CONCRETE; case MAGENTA: return Material.MAGENTA_CONCRETE; case LIGHT_BLUE: return Material.LIGHT_BLUE_CONCRETE; case YELLOW: return Material.YELLOW_CONCRETE; case LIME: return Material.LIME_CONCRETE; case PINK: return Material.PINK_CONCRETE; case GRAY: return Material.GRAY_CONCRETE; case LIGHT_GRAY: return Material.LIGHT_GRAY_CONCRETE; case CYAN: return Material.CYAN_CONCRETE; case PURPLE: return Material.PURPLE_CONCRETE; case BLUE: return Material.BLUE_CONCRETE; case BROWN: return Material.BROWN_CONCRETE; case GREEN: return Material.GREEN_CONCRETE; case RED: return Material.RED_CONCRETE; case BLACK: return Material.BLACK_CONCRETE; default: return null; } } public static Material fromColor_concrete_powder(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_CONCRETE_POWDER; case ORANGE: return Material.ORANGE_CONCRETE_POWDER; case MAGENTA: return Material.MAGENTA_CONCRETE_POWDER; case LIGHT_BLUE: return Material.LIGHT_BLUE_CONCRETE_POWDER; case YELLOW: return Material.YELLOW_CONCRETE_POWDER; case LIME: return Material.LIME_CONCRETE_POWDER; case PINK: return Material.PINK_CONCRETE_POWDER; case GRAY: return Material.GRAY_CONCRETE_POWDER; case LIGHT_GRAY: return Material.LIGHT_GRAY_CONCRETE_POWDER; case CYAN: return Material.CYAN_CONCRETE_POWDER; case PURPLE: return Material.PURPLE_CONCRETE_POWDER; case BLUE: return Material.BLUE_CONCRETE_POWDER; case BROWN: return Material.BROWN_CONCRETE_POWDER; case GREEN: return Material.GREEN_CONCRETE_POWDER; case RED: return Material.RED_CONCRETE_POWDER; case BLACK: return Material.BLACK_CONCRETE_POWDER; default: return null; } } public static Material fromColor_stained_glass(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_STAINED_GLASS; case ORANGE: return Material.ORANGE_STAINED_GLASS; case MAGENTA: return Material.MAGENTA_STAINED_GLASS; case LIGHT_BLUE: return Material.LIGHT_BLUE_STAINED_GLASS; case YELLOW: return Material.YELLOW_STAINED_GLASS; case LIME: return Material.LIME_STAINED_GLASS; case PINK: return Material.PINK_STAINED_GLASS; case GRAY: return Material.GRAY_STAINED_GLASS; case LIGHT_GRAY: return Material.LIGHT_GRAY_STAINED_GLASS; case CYAN: return Material.CYAN_STAINED_GLASS; case PURPLE: return Material.PURPLE_STAINED_GLASS; case BLUE: return Material.BLUE_STAINED_GLASS; case BROWN: return Material.BROWN_STAINED_GLASS; case GREEN: return Material.GREEN_STAINED_GLASS; case RED: return Material.RED_STAINED_GLASS; case BLACK: return Material.BLACK_STAINED_GLASS; default: return null; } } public static Material fromColor_stained_glass_pane(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_STAINED_GLASS_PANE; case ORANGE: return Material.ORANGE_STAINED_GLASS_PANE; case MAGENTA: return Material.MAGENTA_STAINED_GLASS_PANE; case LIGHT_BLUE: return Material.LIGHT_BLUE_STAINED_GLASS_PANE; case YELLOW: return Material.YELLOW_STAINED_GLASS_PANE; case LIME: return Material.LIME_STAINED_GLASS_PANE; case PINK: return Material.PINK_STAINED_GLASS_PANE; case GRAY: return Material.GRAY_STAINED_GLASS_PANE; case LIGHT_GRAY: return Material.LIGHT_GRAY_STAINED_GLASS_PANE; case CYAN: return Material.CYAN_STAINED_GLASS_PANE; case PURPLE: return Material.PURPLE_STAINED_GLASS_PANE; case BLUE: return Material.BLUE_STAINED_GLASS_PANE; case BROWN: return Material.BROWN_STAINED_GLASS_PANE; case GREEN: return Material.GREEN_STAINED_GLASS_PANE; case RED: return Material.RED_STAINED_GLASS_PANE; case BLACK: return Material.BLACK_STAINED_GLASS_PANE; default: return null; } } public static Material fromColor_wool(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_WOOL; case ORANGE: return Material.ORANGE_WOOL; case MAGENTA: return Material.MAGENTA_WOOL; case LIGHT_BLUE: return Material.LIGHT_BLUE_WOOL; case YELLOW: return Material.YELLOW_WOOL; case LIME: return Material.LIME_WOOL; case PINK: return Material.PINK_WOOL; case GRAY: return Material.GRAY_WOOL; case LIGHT_GRAY: return Material.LIGHT_GRAY_WOOL; case CYAN: return Material.CYAN_WOOL; case PURPLE: return Material.PURPLE_WOOL; case BLUE: return Material.BLUE_WOOL; case BROWN: return Material.BROWN_WOOL; case GREEN: return Material.GREEN_WOOL; case RED: return Material.RED_WOOL; case BLACK: return Material.BLACK_WOOL; default: return null; } } public static Material fromColor_shulker_box(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_SHULKER_BOX; case ORANGE: return Material.ORANGE_SHULKER_BOX; case MAGENTA: return Material.MAGENTA_SHULKER_BOX; case LIGHT_BLUE: return Material.LIGHT_BLUE_SHULKER_BOX; case YELLOW: return Material.YELLOW_SHULKER_BOX; case LIME: return Material.LIME_SHULKER_BOX; case PINK: return Material.PINK_SHULKER_BOX; case GRAY: return Material.GRAY_SHULKER_BOX; case LIGHT_GRAY: return Material.LIGHT_GRAY_SHULKER_BOX; case CYAN: return Material.CYAN_SHULKER_BOX; case PURPLE: return Material.PURPLE_SHULKER_BOX; case BLUE: return Material.BLUE_SHULKER_BOX; case BROWN: return Material.BROWN_SHULKER_BOX; case GREEN: return Material.GREEN_SHULKER_BOX; case RED: return Material.RED_SHULKER_BOX; case BLACK: return Material.BLACK_SHULKER_BOX; default: return null; } } public static Material fromColor_terracotta(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_TERRACOTTA; case ORANGE: return Material.ORANGE_TERRACOTTA; case MAGENTA: return Material.MAGENTA_TERRACOTTA; case LIGHT_BLUE: return Material.LIGHT_BLUE_TERRACOTTA; case YELLOW: return Material.YELLOW_TERRACOTTA; case LIME: return Material.LIME_TERRACOTTA; case PINK: return Material.PINK_TERRACOTTA; case GRAY: return Material.GRAY_TERRACOTTA; case LIGHT_GRAY: return Material.LIGHT_GRAY_TERRACOTTA; case CYAN: return Material.CYAN_TERRACOTTA; case PURPLE: return Material.PURPLE_TERRACOTTA; case BLUE: return Material.BLUE_TERRACOTTA; case BROWN: return Material.BROWN_TERRACOTTA; case GREEN: return Material.GREEN_TERRACOTTA; case RED: return Material.RED_TERRACOTTA; case BLACK: return Material.BLACK_TERRACOTTA; default: return null; } } public static Material fromColor_glazed_terracotta(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_GLAZED_TERRACOTTA; case ORANGE: return Material.ORANGE_GLAZED_TERRACOTTA; case MAGENTA: return Material.MAGENTA_GLAZED_TERRACOTTA; case LIGHT_BLUE: return Material.LIGHT_BLUE_GLAZED_TERRACOTTA; case YELLOW: return Material.YELLOW_GLAZED_TERRACOTTA; case LIME: return Material.LIME_GLAZED_TERRACOTTA; case PINK: return Material.PINK_GLAZED_TERRACOTTA; case GRAY: return Material.GRAY_GLAZED_TERRACOTTA; case LIGHT_GRAY: return Material.LIGHT_GRAY_GLAZED_TERRACOTTA; case CYAN: return Material.CYAN_GLAZED_TERRACOTTA; case PURPLE: return Material.PURPLE_GLAZED_TERRACOTTA; case BLUE: return Material.BLUE_GLAZED_TERRACOTTA; case BROWN: return Material.BROWN_GLAZED_TERRACOTTA; case GREEN: return Material.GREEN_GLAZED_TERRACOTTA; case RED: return Material.RED_GLAZED_TERRACOTTA; case BLACK: return Material.BLACK_GLAZED_TERRACOTTA; default: return null; } } public static Material fromColor_dye(DyeColor color) { switch(color) { case WHITE: return Material.WHITE_DYE; case ORANGE: return Material.ORANGE_DYE; case MAGENTA: return Material.MAGENTA_DYE; case LIGHT_BLUE: return Material.LIGHT_BLUE_DYE; case YELLOW: return Material.YELLOW_DYE; case LIME: return Material.LIME_DYE; case PINK: return Material.PINK_DYE; case GRAY: return Material.GRAY_DYE; case LIGHT_GRAY: return Material.LIGHT_GRAY_DYE; case CYAN: return Material.CYAN_DYE; case PURPLE: return Material.PURPLE_DYE; case BLUE: return Material.BLUE_DYE; case BROWN: return Material.BROWN_DYE; case GREEN: return Material.GREEN_DYE; case RED: return Material.RED_DYE; case BLACK: return Material.BLACK_DYE; default: return null; } } }
9244d229e19e49288e524a590d10a90d4ed9740a
2,367
java
Java
src/test/java/io/ebeaninternal/server/expression/DefaultExpressionFactoryTest.java
kevinobama/ebeanTesting
0aff81116e72abf7b4888c6dd516b1ee1b345f7f
[ "Apache-2.0" ]
null
null
null
src/test/java/io/ebeaninternal/server/expression/DefaultExpressionFactoryTest.java
kevinobama/ebeanTesting
0aff81116e72abf7b4888c6dd516b1ee1b345f7f
[ "Apache-2.0" ]
null
null
null
src/test/java/io/ebeaninternal/server/expression/DefaultExpressionFactoryTest.java
kevinobama/ebeanTesting
0aff81116e72abf7b4888c6dd516b1ee1b345f7f
[ "Apache-2.0" ]
1
2020-09-02T08:54:43.000Z
2020-09-02T08:54:43.000Z
31.56
82
0.763414
1,003,156
package io.ebeaninternal.server.expression; import io.ebean.Expression; import org.junit.Test; import static org.assertj.core.api.StrictAssertions.assertThat; public class DefaultExpressionFactoryTest { @Test public void testLowerILike() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(false, false); Expression expression = factory.ilike("name", "foo"); assertThat(expression).isInstanceOf(LikeExpression.class); } @Test public void testNativeILike() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(false, true); Expression expression = factory.ilike("name", "foo"); assertThat(expression).isInstanceOf(NativeILikeExpression.class); } @Test public void testEq() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(false, false); Expression expression = factory.eq("name", null); assertThat(expression).isInstanceOf(NullExpression.class); } @Test public void testNe() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(false, false); Expression expression = factory.ne("name", null); assertThat(expression).isInstanceOf(NullExpression.class); } @Test public void testIeq() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(false, false); Expression expression = factory.ieq("name", null); assertThat(expression).isInstanceOf(NullExpression.class); } @Test public void testEq_with_equalsWithNullAsNoop() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(true, false); Expression expression = factory.eq("name", null); assertThat(expression).isInstanceOf(NoopExpression.class); } @Test public void testNe_with_equalsWithNullAsNoop() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(true, false); Expression expression = factory.ne("name", null); assertThat(expression).isInstanceOf(NoopExpression.class); } @Test public void testIeq_with_equalsWithNullAsNoop() throws Exception { DefaultExpressionFactory factory = new DefaultExpressionFactory(true, false); Expression expression = factory.ieq("name", null); assertThat(expression).isInstanceOf(NoopExpression.class); } }
9244d44d322ec0d6aeff9f95e19ee0c550a9c516
337
java
Java
jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/resources/AuthResource.java
moove-it/swagger-jaxrs-doclet
37d07619f8e20f2ca01478e3f494470febd604fb
[ "Apache-2.0" ]
1
2018-05-23T08:35:15.000Z
2018-05-23T08:35:15.000Z
jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/resources/AuthResource.java
moove-it/swagger-jaxrs-doclet
37d07619f8e20f2ca01478e3f494470febd604fb
[ "Apache-2.0" ]
null
null
null
jaxrs-doclet-sample-dropwizard/src/main/java/com/hypnoticocelot/jaxrs/doclet/sample/resources/AuthResource.java
moove-it/swagger-jaxrs-doclet
37d07619f8e20f2ca01478e3f494470febd604fb
[ "Apache-2.0" ]
null
null
null
18.722222
57
0.652819
1,003,157
package com.hypnoticocelot.jaxrs.doclet.sample.resources; import com.yammer.dropwizard.auth.Auth; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/Auth") public class AuthResource { /** * @status 404 not found */ @GET public String authorize(@Auth String user) { return "USER = " + user; } }
9244d6158bc795e3a70252b2507b13d3216f7c4b
4,544
java
Java
src/main/java/com/matchandtrade/persistence/criteria/ArticleNativeQueryRepository.java
rafasantos/matchandtrade-api
203c6c41a5cb8237e38d05be5db2b45a1822049e
[ "MIT" ]
null
null
null
src/main/java/com/matchandtrade/persistence/criteria/ArticleNativeQueryRepository.java
rafasantos/matchandtrade-api
203c6c41a5cb8237e38d05be5db2b45a1822049e
[ "MIT" ]
3
2018-01-22T00:36:11.000Z
2018-02-18T14:14:53.000Z
src/main/java/com/matchandtrade/persistence/criteria/ArticleNativeQueryRepository.java
rafasantos/matchandtrade-web-api
203c6c41a5cb8237e38d05be5db2b45a1822049e
[ "MIT" ]
1
2020-01-30T15:56:32.000Z
2020-01-30T15:56:32.000Z
34.424242
117
0.71831
1,003,158
package com.matchandtrade.persistence.criteria; import com.matchandtrade.persistence.common.*; import com.matchandtrade.persistence.entity.ArticleEntity; import com.matchandtrade.rest.service.SearchRecipeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.persistence.EntityManager; import javax.persistence.Query; import java.math.BigInteger; import java.util.List; import static com.matchandtrade.rest.service.SearchRecipeService.Field.*; import static java.util.Collections.emptyList; @Component public class ArticleNativeQueryRepository { @Autowired private EntityManager entityManager; @SuppressWarnings(value = "unchecked") public SearchResult<ArticleEntity> search(SearchCriteria searchCriteria) { SqlBuilder sqlBuilder = new SqlBuilder(searchCriteria); Query queryContent = entityManager.createNativeQuery(sqlBuilder.buildSql(), ArticleEntity.class); Query queryCount = entityManager.createNativeQuery(sqlBuilder.buildCountSql()); for (Criterion c : searchCriteria.getCriteria()) { queryCount.setParameter(c.getField().toString(), c.getValue()); queryContent.setParameter(c.getField().toString(), c.getValue()); } Pagination pagination = searchCriteria.getPagination(); BigInteger count = (BigInteger) queryCount.getSingleResult(); if (count.intValue() < 1) { return new SearchResult<>(emptyList(), pagination); } List<ArticleEntity> articles = queryContent.getResultList(); return new SearchResult(articles, new Pagination(pagination.getNumber(), pagination.getSize(), count.longValue())); } private static class SqlBuilder { private List<Sort> sortList; private List<Criterion> criteria; private final String pagination; public SqlBuilder(SearchCriteria searchCriteria) { this.sortList = searchCriteria.getSorts(); this.criteria = searchCriteria.getCriteria(); this.pagination = " OFFSET " + (searchCriteria.getPagination().getNumber() - 1) * searchCriteria.getPagination().getSize() + " LIMIT " + searchCriteria.getPagination().getSize(); } private void addWhereClause(StringBuilder currentWhere, SearchRecipeService.Field field, Criterion criterion) { if (currentWhere.length() == 0) { currentWhere.append(" WHERE "); } else { currentWhere .append(" ") .append(criterion.getLogicalOperator()) .append(" "); } currentWhere .append(toFieldAlias(field)) .append(" = :") .append(criterion.getField().toString()); } public String buildCountSql() { return buildSqlWithoutPagination().replace("SELECT article.*", "SELECT COUNT(*)"); } public String buildSql() { return buildSqlWithoutPagination() + buildOrderBy() + pagination; } public String buildOrderBy() { if (this.sortList.isEmpty()) { return " ORDER BY article.article_id "; } StringBuffer result = new StringBuffer(); this.sortList.forEach(sort -> { result .append(" ORDER BY UPPER(") .append(toFieldAlias(sort.field())) .append(") ") .append(sort.type().name()); }); return result.toString(); } private String buildSqlWithoutPagination() { StringBuilder sql = new StringBuilder("SELECT article.* FROM article"); StringBuilder where = new StringBuilder(); for (Criterion c : criteria) { SearchRecipeService.Field field = (SearchRecipeService.Field) c.getField(); if (ARTICLE_ID == field || ARTICLE_NAME == field) { addWhereClause(where, field, c); } if (TRADE_ID == c.getField()) { sql.append(" INNER JOIN membership_to_article m2a ON m2a.article_id = article.article_id"); sql.append(" INNER JOIN membership ON membership.membership_id = m2a.membership_id"); sql.append(" INNER JOIN trade ON trade.trade_id = membership.trade_id"); addWhereClause(where, TRADE_ID, c); } else if (USER_ID == c.getField()) { sql.append(" INNER JOIN user_to_article u2a ON u2a.article_id = article.article_id"); addWhereClause(where, USER_ID, c); } } return sql.toString() + where.toString(); } private String toFieldAlias(Field field) { if (field.toString().equals(ARTICLE_ID.toString())) { return "article.article_id"; } else if (field.toString().equals(ARTICLE_NAME.toString())) { return "article.name"; }else if (field.toString().equals(USER_ID.toString())) { return "u2a.user_id"; } else if (field.toString().equals(TRADE_ID.toString())) { return "trade.trade_id"; } else { return ""; } } } }
9244d69a7a2914dd9cc6800206582bcec23b5dd5
1,080
java
Java
learnAndTest/src/main/java/GOF23/C8_Memento/ChessMan.java
wangyeIsClever/myProject
3b9d686db6929142ec4dc1bbc306b2e846f38d69
[ "MIT" ]
1
2019-07-29T06:09:00.000Z
2019-07-29T06:09:00.000Z
learnAndTest/src/main/java/GOF23/C8_Memento/ChessMan.java
wangyeIsClever/myProject
3b9d686db6929142ec4dc1bbc306b2e846f38d69
[ "MIT" ]
null
null
null
learnAndTest/src/main/java/GOF23/C8_Memento/ChessMan.java
wangyeIsClever/myProject
3b9d686db6929142ec4dc1bbc306b2e846f38d69
[ "MIT" ]
null
null
null
17.419355
112
0.541667
1,003,159
package GOF23.C8_Memento; /** * 棋子类,这是原发器,被保存的对象 */ public class ChessMan { private Color color; // 棋子颜色 private int x; // 棋子横坐标 private int y; // 棋子纵坐标 /** * 保存到备忘录 * @return 棋子的备忘录 */ public ChessMemento saveToMemento(){ return new ChessMemento(this.color,this.x,this.y); } /** * 从备忘录恢复棋子的状态 * @param chessMemento 备忘录 */ public void restoreToMemento(ChessMemento chessMemento){ this.color = chessMemento.getColor(); this.x = chessMemento.getX(); this.y = chessMemento.getY(); } public void show(){ System.out.println("当前棋子是 " + this.color.getColorDesc() + "棋子 ,位置: 横坐标 :" + this.x + " 纵坐标 :" + this.y); } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
9244d7aef9c954e108d417adb350a9530685c36f
827
java
Java
XiaoYuanFenApp/commonlibrary/src/main/java/foundation/util/ResUtils.java
fugx/XiaoYuanFen
6b936f023601fc6058ba112266d06c72147a2b62
[ "Apache-2.0" ]
null
null
null
XiaoYuanFenApp/commonlibrary/src/main/java/foundation/util/ResUtils.java
fugx/XiaoYuanFen
6b936f023601fc6058ba112266d06c72147a2b62
[ "Apache-2.0" ]
null
null
null
XiaoYuanFenApp/commonlibrary/src/main/java/foundation/util/ResUtils.java
fugx/XiaoYuanFen
6b936f023601fc6058ba112266d06c72147a2b62
[ "Apache-2.0" ]
null
null
null
19.232558
76
0.586457
1,003,160
package foundation.util; import android.content.Context; /** * Function:本地资源获取帮助类 */ public class ResUtils { /** * 从本地资源文件中获取字符串 * * @param c 上下文 * @param resId 资源文件id */ public static String getString(Context c, int resId) { return c.getApplicationContext().getResources().getString(resId); } /** * 从本地资源文件中获取浮点长度 * * @param c 上下文 * @param resId 资源文件id */ public static float getDimen(Context c, int resId) { return c.getApplicationContext().getResources().getDimension(resId); } /** * 从本地资源文件中获取颜色 * * @param c 上下文 * @param resId 资源文件id */ public static int getColor(Context c, int resId) { return c.getApplicationContext().getResources().getColor(resId); } }
9244d7e5faa3562610245af2722dbdbbbb59f11e
967
java
Java
ProjetoRest/src/br/com/projetoRest/util/Conexao.java
saviocode/PI-2018-2
cf1c5fd3fd5a997d9d261b39e1e58bb402c5e469
[ "MIT" ]
null
null
null
ProjetoRest/src/br/com/projetoRest/util/Conexao.java
saviocode/PI-2018-2
cf1c5fd3fd5a997d9d261b39e1e58bb402c5e469
[ "MIT" ]
null
null
null
ProjetoRest/src/br/com/projetoRest/util/Conexao.java
saviocode/PI-2018-2
cf1c5fd3fd5a997d9d261b39e1e58bb402c5e469
[ "MIT" ]
null
null
null
29.30303
114
0.617373
1,003,161
package br.com.projetoRest.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Conexao { private static Connection conexao; public static Connection getConexao(){ try { if(conexao == null || conexao.isClosed()) conexao = conectar(); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); } return conexao; } private static Connection conectar() throws Exception{ try { Class.forName("org.postgresql.Driver"); return DriverManager.getConnection("jdbc:postgresql://localhost:5432/sistemataxi","postgres","F#240924s"); }catch (ClassNotFoundException e) { throw new Exception("Nao foi encontrado a biblioteca postgres."); }catch (SQLException e){ throw new Exception("Banco/Usuario/Senha estaão erradas."); } } }
9244d9d73877c2bc0b4cbaeefe7949b248b305bb
817
java
Java
fhir-database-utils/src/main/java/com/ibm/fhir/database/utils/thread/ThreadHandler.java
IBM/FHIR
b44d66f83bc63587b57bd3726bf9236e82244d00
[ "Apache-2.0" ]
209
2019-08-14T15:11:17.000Z
2022-03-25T10:30:35.000Z
fhir-database-utils/src/main/java/com/ibm/fhir/database/utils/thread/ThreadHandler.java
IBM/FHIR
b44d66f83bc63587b57bd3726bf9236e82244d00
[ "Apache-2.0" ]
1,944
2019-08-29T20:03:24.000Z
2022-03-31T22:38:28.000Z
fhir-database-utils/src/main/java/com/ibm/fhir/database/utils/thread/ThreadHandler.java
IBM/FHIR
b44d66f83bc63587b57bd3726bf9236e82244d00
[ "Apache-2.0" ]
134
2019-09-02T10:36:17.000Z
2022-03-06T15:08:07.000Z
22.694444
59
0.631579
1,003,162
/* * (C) Copyright IBM Corp. 2021 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.database.utils.thread; /** * ThreadHandler is a common pattern used to control the * safe handling of a sleeping thread. */ public final class ThreadHandler { public static final long SECOND = 1000; public static final long FIVE_SECONDS = 5000; public static final long TEN_SECONDS = 10000; public static final long MINUTE = 60000; private ThreadHandler() { // NOP } /** * Sleep for the requested number of milliseconds * @param millis */ public static void safeSleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException x) { // NOP. Being woken up early, probably for exit } } }
9244da1f22f90b169722e17b744fe1096dca6153
747
java
Java
src/main/java/org/digitalmediaserver/cast/Message.java
DigitalMediaServer/chromecast-api
42bf93d8608b7f97275ffcd989788eab7009a2f5
[ "Apache-2.0" ]
null
null
null
src/main/java/org/digitalmediaserver/cast/Message.java
DigitalMediaServer/chromecast-api
42bf93d8608b7f97275ffcd989788eab7009a2f5
[ "Apache-2.0" ]
null
null
null
src/main/java/org/digitalmediaserver/cast/Message.java
DigitalMediaServer/chromecast-api
42bf93d8608b7f97275ffcd989788eab7009a2f5
[ "Apache-2.0" ]
null
null
null
32.565217
75
0.740988
1,003,163
/* * Copyright 2015 Vitaly Litvak ([email protected]) * * 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.digitalmediaserver.cast; /** * Generic message used in exchange with cast devices. */ public interface Message { }
9244da3c6952b97237a37d153a62d6c786727d2a
908
java
Java
app/src/main/java/com/example/android/quakereport/EarthquakeLoader.java
nilay1998/QuakeReport
a82cdadc7de8f15d913252588c2b22f2edead4e9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/quakereport/EarthquakeLoader.java
nilay1998/QuakeReport
a82cdadc7de8f15d913252588c2b22f2edead4e9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/quakereport/EarthquakeLoader.java
nilay1998/QuakeReport
a82cdadc7de8f15d913252588c2b22f2edead4e9
[ "Apache-2.0" ]
null
null
null
23.894737
73
0.661894
1,003,164
package com.example.android.quakereport; import android.content.AsyncTaskLoader; import android.content.Context; import android.util.Log; import java.io.IOException; import java.net.URL; import static com.example.android.quakereport.EarthquakeActivity.LOG_TAG; public class EarthquakeLoader extends AsyncTaskLoader<String> { private String mUrl; public EarthquakeLoader(Context context, String url) { super(context); mUrl=url; } @Override protected void onStartLoading() { forceLoad(); } @Override public String loadInBackground() { URL url= QueryUtils.createUrl(mUrl); String jsonResponse=""; try { jsonResponse=QueryUtils.makeHttpRequest(url); } catch (IOException e) { Log.e(LOG_TAG, "Problem making the HTTP request.", e); } return jsonResponse; } }
9244da3d757e225538540bd38eaa49f8d835ed19
4,283
java
Java
openjdk11/test/hotspot/jtreg/vmTestbase/nsk/jdwp/VirtualMachine/RedefineClasses/redefinecls001/TestDescription.java
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
test/hotspot/jtreg/vmTestbase/nsk/jdwp/VirtualMachine/RedefineClasses/redefinecls001/TestDescription.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
test/hotspot/jtreg/vmTestbase/nsk/jdwp/VirtualMachine/RedefineClasses/redefinecls001/TestDescription.java
desiyonan/OpenJDK8
74d4f56b6312c303642e053e5d428b44cc8326c5
[ "MIT" ]
null
null
null
46.053763
94
0.721223
1,003,165
/* * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * * @summary converted from VM Testbase nsk/jdwp/VirtualMachine/RedefineClasses/redefinecls001. * VM Testbase keywords: [quick, jpda, jdwp, redefine] * VM Testbase readme: * DESCRIPTION * This test performs checking for * command set: VirtualMachine * command: RedefineClasses * Test checks that debugee accept the command packet and * replies with correct reply packet. Also test checks that * after class redefinition invocation of static and object * methods resuts in invocation of redefined methods, and * no constructors are invoked. * Test consists of two compoments: * debugger: redefinecls001 * debuggee: redefinecls001a * First, debugger uses nsk.share support classes to launch debuggee * and obtain Transport object, that represents JDWP transport channel. * It also loads bytecode of redefined class from *.klass file. * Next, debugger waits for tested classes are loaded, and breakpoint * before class redefinition is reached. * Then, debugger creates command packet for VirtualMachine.RedefineClasses * command for the found classID and loaded bytecode, writes this packet * to the transport channel, and waits for a reply packet. * When reply packet is received, debugger parses the packet structure * and checks if no reply data returned in the packet. * Then, debugger resumes debuggee to allow methods of redefined class * to be invoked and waits for second breakpoint is reached. * Upon their invocation redefined methods puts proper value into * the special static fields of debuggee class. The debugger then * checks these fields to verify if the redefined methods were invoked * and no constructors were invoked. * Finally, debugger disconnects debuggee, waits for it exits * and exits too with the proper exit code. * COMMENTS * First positional argument for the test should be path to the test * work directory where loaded *.klass file should be located. * Test was updated according to rfe: * 4691123 TEST: some jdi tests contain precompiled .klass files undes SCCS. * redefinecl001b.ja was moved into newclass directory and renamed * to redefinecl001b.java. * The precompiled class file is created during test base build process. * * @library /vmTestbase /test/hotspot/jtreg/vmTestbase * /test/lib * @run driver jdk.test.lib.FileInstaller . . * @build ExecDriver * @build nsk.jdwp.VirtualMachine.RedefineClasses.redefinecls001 * nsk.jdwp.VirtualMachine.RedefineClasses.redefinecls001a * nsk.jdwp.VirtualMachine.RedefineClasses.redefinecls001b * @run driver PropertyResolvingWrapper ExecDriver --cmd * ${compile.jdk}/bin/javac * -cp ${test.class.path} * -d newclass * newclass/redefinecls001b.java * @run main/othervm PropertyResolvingWrapper * nsk.jdwp.VirtualMachine.RedefineClasses.redefinecls001 * . * -arch=${os.family}-${os.simpleArch} * -verbose * -waittime=5 * -debugee.vmkind=java * -transport.address=dynamic * -debugee.vmkeys="${test.vm.opts} ${test.java.opts}" */
9244dae65990f933d7815dd309adbaad70a49132
519
java
Java
javac-support/src/main/java/com/webcohesion/enunciate/javac/decorations/adaptors/TypeElementAdaptor.java
octetnest/enunciate
e571c6a7aa50a18c60a529be28d14619342940eb
[ "Apache-2.0" ]
431
2015-01-05T06:27:54.000Z
2022-03-29T22:01:03.000Z
javac-support/src/main/java/com/webcohesion/enunciate/javac/decorations/adaptors/TypeElementAdaptor.java
octetnest/enunciate
e571c6a7aa50a18c60a529be28d14619342940eb
[ "Apache-2.0" ]
1,020
2015-01-17T17:44:54.000Z
2022-03-30T14:11:06.000Z
javac-support/src/main/java/com/webcohesion/enunciate/javac/decorations/adaptors/TypeElementAdaptor.java
octetnest/enunciate
e571c6a7aa50a18c60a529be28d14619342940eb
[ "Apache-2.0" ]
180
2015-02-02T17:12:44.000Z
2022-03-05T10:51:47.000Z
25.95
79
0.803468
1,003,166
package com.webcohesion.enunciate.javac.decorations.adaptors; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import java.util.List; /** * @author Ryan Heaton */ public interface TypeElementAdaptor extends TypeElement, ElementAdaptor { Name getBinaryName(); List<? extends Element> getAllMembers(); boolean overrides(ExecutableElement overrider, ExecutableElement overridden); }
9244db92fd2b0543d39b986fe31c1073af34c7b5
3,501
java
Java
src/test/java/org/pebble/core/encoding/ints/datastructures/InvertedListIntReferenceListsIndexAddListIntoListsInvertedIndexTest.java
kennethdick/pebble
5947e8bb39f286cad19ed6e806a63fae4824b607
[ "Apache-2.0" ]
null
null
null
src/test/java/org/pebble/core/encoding/ints/datastructures/InvertedListIntReferenceListsIndexAddListIntoListsInvertedIndexTest.java
kennethdick/pebble
5947e8bb39f286cad19ed6e806a63fae4824b607
[ "Apache-2.0" ]
null
null
null
src/test/java/org/pebble/core/encoding/ints/datastructures/InvertedListIntReferenceListsIndexAddListIntoListsInvertedIndexTest.java
kennethdick/pebble
5947e8bb39f286cad19ed6e806a63fae4824b607
[ "Apache-2.0" ]
null
null
null
43.7625
112
0.702656
1,003,167
package org.pebble.core.encoding.ints.datastructures; /** * Copyright 2015 Groupon * * 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. */ import it.unimi.dsi.fastutil.ints.Int2ReferenceMap; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import org.junit.Test; import org.junit.experimental.categories.Category; import org.pebble.UnitTest; import org.pebble.core.encoding.Helper; import static org.junit.Assert.assertEquals; @Category(UnitTest.class) public class InvertedListIntReferenceListsIndexAddListIntoListsInvertedIndexTest { @Test public void whenIndexDoesNotHaveAnyPreviousIntersectingListItShouldIndexListAsExpected() { final Int2ReferenceMap<IntList> expectedListsInvertedIndex = new Int2ReferenceOpenHashMap<IntList>() {{ put(1, new IntArrayList(new int[] {0})); put(3, new IntArrayList(new int[] {0})); put(4, new IntArrayList(new int[] {0})); put(5, new IntArrayList(new int[] {0})); put(8, new IntArrayList(new int[] {0})); }}; final InvertedListIntReferenceListsIndex listsIndex = new InvertedListIntReferenceListsIndex(); final int index = 0; final IntList list = new IntArrayList(new int[] {1, 3, 4, 5, 8}); listsIndex.addListIntoListsInvertedIndex(index, list); assertEquals( Helper.<Integer, Int2ReferenceMap<IntList>>translateToUtilsCollection(expectedListsInvertedIndex), Helper.<Integer, Int2ReferenceMap<IntList>>translateToUtilsCollection(listsIndex.listsInvertedIndex) ); } @Test public void whenIndexHavePreviousIntersectingListItShouldIndexListAsExpected() { final Int2ReferenceMap<IntList> expectedListsInvertedIndex = new Int2ReferenceOpenHashMap<IntList>() {{ put(1, new IntArrayList(new int[] {1})); put(2, new IntArrayList(new int[] {0})); put(3, new IntArrayList(new int[] {0, 1})); put(4, new IntArrayList(new int[] {1})); put(5, new IntArrayList(new int[] {0, 1})); put(8, new IntArrayList(new int[] {1})); }}; final InvertedListIntReferenceListsIndex listsIndex = new InvertedListIntReferenceListsIndex(); listsIndex.listsInvertedIndex.put(2, new IntArrayList(new int[]{0})); listsIndex.listsInvertedIndex.put(3, new IntArrayList(new int[]{0})); listsIndex.listsInvertedIndex.put(5, new IntArrayList(new int[]{0})); final int index = 1; final IntList list = new IntArrayList(new int[] {1, 3, 4, 5, 8}); listsIndex.addListIntoListsInvertedIndex(index, list); assertEquals( Helper.<Integer, Int2ReferenceMap<IntList>>translateToUtilsCollection(expectedListsInvertedIndex), Helper.<Integer, Int2ReferenceMap<IntList>>translateToUtilsCollection(listsIndex.listsInvertedIndex) ); } }
9244db990046929ff7b852341fe3964b1f729ffe
483
java
Java
gulimall-auth-server/src/main/java/com/atguigu/gulimall/auth/vo/SocialUser.java
kLjSumi/gulimall_learning
4ededf44a1f005631181c6ff6973bb6261bb8603
[ "Apache-2.0" ]
null
null
null
gulimall-auth-server/src/main/java/com/atguigu/gulimall/auth/vo/SocialUser.java
kLjSumi/gulimall_learning
4ededf44a1f005631181c6ff6973bb6261bb8603
[ "Apache-2.0" ]
null
null
null
gulimall-auth-server/src/main/java/com/atguigu/gulimall/auth/vo/SocialUser.java
kLjSumi/gulimall_learning
4ededf44a1f005631181c6ff6973bb6261bb8603
[ "Apache-2.0" ]
1
2020-11-24T07:53:09.000Z
2020-11-24T07:53:09.000Z
19.32
58
0.648033
1,003,168
package com.atguigu.gulimall.auth.vo; import lombok.Data; /** * @author kLjSumi * @Date 2020/12/30 * * { * "access_token": "2.00y94ccG_5iktBfd202aba950ku43h", * "remind_in": "157679999", * "expires_in": 157679999, * "uid": "6067444432", * "isRealName": "true" * } */ @Data public class SocialUser { private String access_token; private String remind_in; private String expires_in; private String uid; private String isRealName; }
9244dc4fa1374d22e751dcea537ea5db98de937b
922
java
Java
src/main/java/com/kerbores/gitea/client/model/CreateStatusOption.java
Kerbores/gitea-integration
9de0e97fa0d101c51a9431df1bf2a9b458cb41cb
[ "Apache-2.0" ]
2
2021-03-17T19:43:21.000Z
2021-03-23T01:56:41.000Z
src/main/java/com/kerbores/gitea/client/model/CreateStatusOption.java
Kerbores/gitea-integration
9de0e97fa0d101c51a9431df1bf2a9b458cb41cb
[ "Apache-2.0" ]
1
2021-02-14T18:17:15.000Z
2021-02-14T18:17:15.000Z
src/main/java/com/kerbores/gitea/client/model/CreateStatusOption.java
Kerbores/gitea-integration
9de0e97fa0d101c51a9431df1bf2a9b458cb41cb
[ "Apache-2.0" ]
null
null
null
21.44186
79
0.735358
1,003,169
/* * Gitea API. This documentation describes the Gitea API. * * OpenAPI spec version: 1.1.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git Do not edit the class * manually. */ package com.kerbores.gitea.client.model; import com.alibaba.fastjson.annotation.JSONField; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * CreateStatusOption holds the information needed to create a new Status for a * Commit */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class CreateStatusOption { @JSONField(name = "context") private String context; @JSONField(name = "description") private String description; @JSONField(name = "state") private String state; @JSONField(name = "target_url") private String targetUrl; }
9244dd08020d6883d16827e11481db174c01877d
2,505
java
Java
oak-core-spi/src/main/java/org/apache/jackrabbit/oak/spi/whiteboard/CompositeRegistration.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
null
null
null
oak-core-spi/src/main/java/org/apache/jackrabbit/oak/spi/whiteboard/CompositeRegistration.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
2
2020-06-15T19:48:29.000Z
2021-02-08T21:25:54.000Z
oak-core-spi/src/main/java/org/apache/jackrabbit/oak/spi/whiteboard/CompositeRegistration.java
sho25/jackrabbit-oak
1bb8a341fdf907578298f9ed52a48458e4f6efdc
[ "Apache-2.0" ]
null
null
null
20.201613
815
0.792016
1,003,170
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|whiteboard package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_comment comment|/** * A composite of registrations that unregisters all its constituents * upon {@link #unregister()}. */ end_comment begin_class specifier|public class|class name|CompositeRegistration implements|implements name|Registration block|{ specifier|private specifier|final name|List argument_list|< name|Registration argument_list|> name|registrations decl_stmt|; specifier|public name|CompositeRegistration parameter_list|( name|Registration modifier|... name|registrations parameter_list|) block|{ name|this argument_list|( name|Arrays operator|. name|asList argument_list|( name|registrations argument_list|) argument_list|) expr_stmt|; block|} specifier|public name|CompositeRegistration parameter_list|( name|List argument_list|< name|Registration argument_list|> name|registrations parameter_list|) block|{ name|this operator|. name|registrations operator|= name|registrations expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|unregister parameter_list|() block|{ for|for control|( name|Registration name|reg range|: name|registrations control|) block|{ name|reg operator|. name|unregister argument_list|() expr_stmt|; block|} block|} block|} end_class end_unit
9244dd21fa2cb3f44011a8cd06a159875845378e
1,646
java
Java
ali-plugin-main/src/main/java/com/hp/alm/ali/idea/util/FileEditorManager.java
janotav/ali-idea-plugin
9726589b3f5a80827e666919a97dbd65fa4ca212
[ "Apache-2.0" ]
8
2015-01-12T07:56:03.000Z
2018-01-30T07:39:15.000Z
ali-plugin-main/src/main/java/com/hp/alm/ali/idea/util/FileEditorManager.java
janotav/ali-idea-plugin
9726589b3f5a80827e666919a97dbd65fa4ca212
[ "Apache-2.0" ]
19
2015-01-05T14:44:24.000Z
2017-02-14T20:21:32.000Z
ali-plugin-main/src/main/java/com/hp/alm/ali/idea/util/FileEditorManager.java
janotav/ali-idea-plugin
9726589b3f5a80827e666919a97dbd65fa4ca212
[ "Apache-2.0" ]
10
2015-03-20T08:12:11.000Z
2017-11-15T15:55:30.000Z
27.433333
114
0.710207
1,003,171
/* * Copyright 2013 Hewlett-Packard Development Company, L.P * * 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.hp.alm.ali.idea.util; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.TestOnly; public class FileEditorManager { private Selector selector = new DefaultSelector(); private Project project; public FileEditorManager(Project project) { this.project = project; } public Editor getSelectedTextEditor() { return selector.getSelectedTextEditor(); } @TestOnly public void _setSelector(Selector selector) { this.selector = selector; } @TestOnly public void _restore() { selector = new DefaultSelector(); } public static interface Selector { public Editor getSelectedTextEditor(); } private class DefaultSelector implements Selector { @Override public Editor getSelectedTextEditor() { return com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).getSelectedTextEditor(); } } }
9244dff0d01854fb43559bdb944b00c6278747e5
2,692
java
Java
css/css-formal/src/main/java/br/com/objectos/lexer/impl/ah/SpecCompiler02.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
css/css-formal/src/main/java/br/com/objectos/lexer/impl/ah/SpecCompiler02.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
css/css-formal/src/main/java/br/com/objectos/lexer/impl/ah/SpecCompiler02.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
32.047619
97
0.73997
1,003,172
/* * Copyright (C) 2017-2022 Objectos Software LTDA. * * 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 br.com.objectos.lexer.impl.ah; import br.com.objectos.lexer.charexp.CharExpression; import br.com.objectos.lexer.grammar.LexerGrammar; import br.com.objectos.lexer.grammar.LexerGrammarDsl02Add; import br.com.objectos.lexer.grammar.LexerGrammarDsl02Qty; import br.com.objectos.lexer.grammar.LexerGrammarDsl03AddBrick; import br.com.objectos.lexer.grammar.LexerGrammarDsl03AddString; import br.com.objectos.lexer.lang.Constructor2; import java.util.Objects; abstract class SpecCompiler02<QTY, E, T, B, A1, A2> extends AbstractSpecCompilerQuantifier<QTY, T, B> implements LexerGrammarDsl02Add<QTY, E, T, B, A1, A2>, LexerGrammarDsl02Qty<E, T, B, A1, A2> { SpecCompiler02(SpecBuilder spec) { super(spec); } @Override public final void andCreateWith(Constructor2<E, A1, A2> constructor) { spec.andCreateWith(constructor); } @Override public final void andPopLexer(Constructor2<E, A1, A2> constructor) { andPopLexer(constructor, 1); } @Override public final void andPopLexer(Constructor2<E, A1, A2> constructor, int count) { throw new UnsupportedOperationException("Implement me"); } @Override public final void andPushLexer(Constructor2<E, A1, A2> constructor, LexerGrammar<T, B> lexer) { Objects.requireNonNull(lexer); throw new UnsupportedOperationException("Implement me"); } @Override public <A3 extends B> LexerGrammarDsl03AddBrick<E, T, B, A1, A2, A3> addBrick(A3 brick) { spec.addBrickValue(brick); return new SpecCompiler03AddBrick<>(spec); } @Override public final LexerGrammarDsl03AddString<E, T, B, A1, A2> addChar(char value) { spec.addChar(value); return new SpecCompiler03AddString<>(spec); } @Override public LexerGrammarDsl03AddString<E, T, B, A1, A2> addChar(CharExpression expression) { spec.addChar(expression); return new SpecCompiler03AddString<>(spec); } @Override public LexerGrammarDsl03AddString<E, T, B, A1, A2> addString(String string) { spec.addString(string); return new SpecCompiler03AddString<>(spec); } }
9244e047b63bbcc12375115473c50373ba061ad1
1,374
java
Java
src/data/text/nyt/NYT_DeepTaggingPipeline_1stStage.java
hovinhthinh/Qsearch
ed450efbb0eebe1a5ad625422edb435b402b096e
[ "Apache-2.0" ]
7
2022-01-26T16:37:56.000Z
2022-02-19T09:31:55.000Z
src/data/text/nyt/NYT_DeepTaggingPipeline_1stStage.java
hovinhthinh/Qsearch
ed450efbb0eebe1a5ad625422edb435b402b096e
[ "Apache-2.0" ]
null
null
null
src/data/text/nyt/NYT_DeepTaggingPipeline_1stStage.java
hovinhthinh/Qsearch
ed450efbb0eebe1a5ad625422edb435b402b096e
[ "Apache-2.0" ]
null
null
null
30.533333
94
0.60262
1,003,173
package data.text.nyt; import model.text.Paragraph; import pipeline.text.*; import util.FileUtils; import util.Gson; import java.io.PrintWriter; @Deprecated public class NYT_DeepTaggingPipeline_1stStage { public static TaggingPipeline getDefaultTaggingPipeline() { return new TaggingPipeline( new NYT_EntityTaggingNode(0.5), new TimeTaggingNode(), new SentenceLengthFiltering(4, 40), new EntityFilteringNode(), new QuantityTaggingNode(), new QuantityFilteringNode()); } // Args: <input> <output> public static void main(String[] args) { // args = "/home/hvthinh/datasets/STICS/news-en-documents_20181120.tar.gz ./temp/output // ./deep/data/stics+nyt/length/model".split("\\s++"); TaggingPipeline pipeline = getDefaultTaggingPipeline(); PrintWriter out = FileUtils.getPrintWriter(args[1], "UTF-8"); FileUtils.LineStream stream = FileUtils.getLineStream(args[0], "UTF-8"); for (String line : stream) { Paragraph paragraph = NYT.parseFromJSON(line); if (paragraph == null) { continue; } if (!pipeline.tag(paragraph)) { continue; } out.println(Gson.toJson(paragraph)); } out.close(); } }
9244e1f348a0967889db690400c16a7e25271134
504
java
Java
app/src/main/java/app/coolweather/com/coolweather/model/Country.java
captainwong/coolweather
f0d52b708d072dabe1846e233004b54f99a18a1b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/app/coolweather/com/coolweather/model/Country.java
captainwong/coolweather
f0d52b708d072dabe1846e233004b54f99a18a1b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/app/coolweather/com/coolweather/model/Country.java
captainwong/coolweather
f0d52b708d072dabe1846e233004b54f99a18a1b
[ "Apache-2.0" ]
null
null
null
17.37931
53
0.613095
1,003,174
package app.coolweather.com.coolweather.model; /** * Created by Jack on 2016/8/15. */ public class Country { public static final String CHINA = "中国"; private long id; private String countryName; public long getId () { return id; } public void setId (long id) { this.id = id; } public String getCountryName () { return countryName; } public void setCountryName (String countryName) { this.countryName = countryName; } }
9244e21d0263cf020f68eee2fd14ce15b2b3f42b
4,286
java
Java
data-index/data-index-service/data-index-service-common/src/main/java/org/kie/kogito/index/json/UserTaskInstanceMetaMapper.java
triceo/kogito-apps
856838871a73db11980d9a1f98d742321d6fb0af
[ "Apache-2.0" ]
null
null
null
data-index/data-index-service/data-index-service-common/src/main/java/org/kie/kogito/index/json/UserTaskInstanceMetaMapper.java
triceo/kogito-apps
856838871a73db11980d9a1f98d742321d6fb0af
[ "Apache-2.0" ]
null
null
null
data-index/data-index-service/data-index-service-common/src/main/java/org/kie/kogito/index/json/UserTaskInstanceMetaMapper.java
triceo/kogito-apps
856838871a73db11980d9a1f98d742321d6fb0af
[ "Apache-2.0" ]
null
null
null
46.086022
166
0.691087
1,003,175
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.kogito.index.json; import java.util.Set; import java.util.function.Function; import org.kie.kogito.event.process.UserTaskInstanceDataEvent; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import static com.google.common.base.Strings.isNullOrEmpty; import static org.kie.kogito.index.Constants.ID; import static org.kie.kogito.index.Constants.KOGITO_DOMAIN_ATTRIBUTE; import static org.kie.kogito.index.Constants.LAST_UPDATE; import static org.kie.kogito.index.Constants.PROCESS_ID; import static org.kie.kogito.index.Constants.USER_TASK_INSTANCES_DOMAIN_ATTRIBUTE; import static org.kie.kogito.index.json.JsonUtils.getObjectMapper; public class UserTaskInstanceMetaMapper implements Function<UserTaskInstanceDataEvent, ObjectNode> { @Override public ObjectNode apply(UserTaskInstanceDataEvent event) { if (event == null) { return null; } ObjectNode json = getObjectMapper().createObjectNode(); json.put(ID, isNullOrEmpty(event.getData().getRootProcessInstanceId()) ? event.getData().getProcessInstanceId() : event.getData().getRootProcessInstanceId()); json.put(PROCESS_ID, isNullOrEmpty(event.getData().getRootProcessId()) ? event.getData().getProcessId() : event.getData().getRootProcessId()); ObjectNode kogito = getObjectMapper().createObjectNode(); kogito.put(LAST_UPDATE, event.getTime().toInstant().toEpochMilli()); kogito.withArray(USER_TASK_INSTANCES_DOMAIN_ATTRIBUTE).add(getUserTaskJson(event)); json.set(KOGITO_DOMAIN_ATTRIBUTE, kogito); return json; } private ObjectNode getUserTaskJson(UserTaskInstanceDataEvent event) { ObjectNode json = getObjectMapper().createObjectNode(); json.put(ID, event.getData().getId()); json.put("processInstanceId", event.getData().getProcessInstanceId()); json.put("state", event.getData().getState()); if (!isNullOrEmpty(event.getData().getTaskDescription())) { json.put("description", event.getData().getTaskDescription()); } if (!isNullOrEmpty(event.getData().getTaskName())) { json.put("name", event.getData().getTaskName()); } if (!isNullOrEmpty(event.getData().getTaskPriority())) { json.put("priority", event.getData().getTaskPriority()); } if (!isNullOrEmpty(event.getData().getActualOwner())) { json.put("actualOwner", event.getData().getActualOwner()); } mapArray("adminUsers", event.getData().getAdminUsers(), json); mapArray("adminGroups", event.getData().getAdminGroups(), json); mapArray("excludedUsers", event.getData().getExcludedUsers(), json); mapArray("potentialGroups", event.getData().getPotentialGroups(), json); mapArray("potentialUsers", event.getData().getPotentialUsers(), json); if (event.getData().getCompleteDate() != null) { json.put("completed", event.getData().getCompleteDate().toInstant().toEpochMilli()); } if (event.getData().getStartDate() != null) { json.put("started", event.getData().getStartDate().toInstant().toEpochMilli()); } if (event.getTime() != null) { json.put(LAST_UPDATE, event.getTime().toInstant().toEpochMilli()); } return json; } private void mapArray(String attribute, Set<String> strings, ObjectNode json) { if (strings != null && !strings.isEmpty()) { ArrayNode array = json.withArray(attribute); strings.forEach(s -> array.add(s)); } } }
9244e23253337ec046608ab94899c248887301e3
1,697
java
Java
src/main/java/org/cidarlab/phoenix/failuremode/SuperCoilingListener.java
CIDARLAB/alphaPhoenix
2c11529785304b5a557928eaa42bba26a4eccd47
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/cidarlab/phoenix/failuremode/SuperCoilingListener.java
CIDARLAB/alphaPhoenix
2c11529785304b5a557928eaa42bba26a4eccd47
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/cidarlab/phoenix/failuremode/SuperCoilingListener.java
CIDARLAB/alphaPhoenix
2c11529785304b5a557928eaa42bba26a4eccd47
[ "BSD-3-Clause" ]
null
null
null
32.634615
76
0.747201
1,003,176
// Generated from SuperCoiling.g4 by ANTLR 4.5.1 package org.cidarlab.phoenix.failuremode; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link SuperCoilingParser}. */ public interface SuperCoilingListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link SuperCoilingParser#root}. * @param ctx the parse tree */ void enterRoot(SuperCoilingParser.RootContext ctx); /** * Exit a parse tree produced by {@link SuperCoilingParser#root}. * @param ctx the parse tree */ void exitRoot(SuperCoilingParser.RootContext ctx); /** * Enter a parse tree produced by {@link SuperCoilingParser#module}. * @param ctx the parse tree */ void enterModule(SuperCoilingParser.ModuleContext ctx); /** * Exit a parse tree produced by {@link SuperCoilingParser#module}. * @param ctx the parse tree */ void exitModule(SuperCoilingParser.ModuleContext ctx); /** * Enter a parse tree produced by {@link SuperCoilingParser#super_coiling}. * @param ctx the parse tree */ void enterSuper_coiling(SuperCoilingParser.Super_coilingContext ctx); /** * Exit a parse tree produced by {@link SuperCoilingParser#super_coiling}. * @param ctx the parse tree */ void exitSuper_coiling(SuperCoilingParser.Super_coilingContext ctx); /** * Enter a parse tree produced by {@link SuperCoilingParser#wildcard}. * @param ctx the parse tree */ void enterWildcard(SuperCoilingParser.WildcardContext ctx); /** * Exit a parse tree produced by {@link SuperCoilingParser#wildcard}. * @param ctx the parse tree */ void exitWildcard(SuperCoilingParser.WildcardContext ctx); }
9244e27a70fa48dc502aadc3b79cad78d3581df3
3,313
java
Java
de.unidue.ltl.ctest/de.unidue.ltl.ctest.difficulty/src/main/java/de/unidue/ltl/ctest/difficulty/features/interItemDependency/RelativePositionExtractor.java
ltl-ude/c-test-tools
63c0938ebaadf7a4577d9f73e14eb232f2789b0a
[ "Apache-2.0" ]
null
null
null
de.unidue.ltl.ctest/de.unidue.ltl.ctest.difficulty/src/main/java/de/unidue/ltl/ctest/difficulty/features/interItemDependency/RelativePositionExtractor.java
ltl-ude/c-test-tools
63c0938ebaadf7a4577d9f73e14eb232f2789b0a
[ "Apache-2.0" ]
7
2018-10-05T21:55:42.000Z
2019-04-01T13:08:10.000Z
de.unidue.ltl.ctest/de.unidue.ltl.ctest.difficulty/src/main/java/de/unidue/ltl/ctest/difficulty/features/interItemDependency/RelativePositionExtractor.java
ltl-ude/c-test-tools
63c0938ebaadf7a4577d9f73e14eb232f2789b0a
[ "Apache-2.0" ]
null
null
null
39.915663
116
0.7377
1,003,177
/******************************************************************************* * Copyright 2015 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.unidue.ltl.ctest.difficulty.features.interItemDependency; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.dkpro.tc.api.exception.TextClassificationException; import org.dkpro.tc.api.features.Feature; import org.dkpro.tc.api.features.FeatureExtractor; import org.dkpro.tc.api.features.FeatureExtractorResource_ImplBase; import org.dkpro.tc.api.features.FeatureType; import org.dkpro.tc.api.type.TextClassificationTarget; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; import de.unidue.ltl.ctest.type.Gap; public class RelativePositionExtractor extends FeatureExtractorResource_ImplBase implements FeatureExtractor { public static final String FN_PREVIOUS_GAPS = "NumberOfPrecedingGaps"; public static final String FN_PREVIOUS_GAPS_IN_COVERSENTENCE = "NumberOfPrecedingGapsInCoverSentence"; public static final String FN_GAPS_IN_COVERSENTENCE = "NumberOfGapsInCoverSentence"; // This feature extractor extracts the position of the gap relative to other // gaps @Override public Set<Feature> extract(JCas jcas, TextClassificationTarget target) throws TextClassificationException { Set<Feature> featList = new HashSet<Feature>(); Sentence coverSent = JCasUtil.selectCovering(jcas, Sentence.class, target).get(0); Gap gap = JCasUtil.selectCovered(Gap.class, target).get(0); List<Gap> previousGaps = getPreviousGapList(jcas, gap); List<Gap> gapsinCoverSent = JCasUtil.selectCovered(Gap.class, coverSent); // get the intersection of the two lists List<Gap> previousGapsInCoverSent = new ArrayList<Gap>(); for (Gap gapInSentence : gapsinCoverSent) { if (previousGaps.contains(gapInSentence)) { previousGapsInCoverSent.add(gapInSentence); } } featList.add(new Feature(FN_PREVIOUS_GAPS, previousGaps.size(), FeatureType.NUMERIC)); featList.add(new Feature(FN_PREVIOUS_GAPS_IN_COVERSENTENCE, previousGapsInCoverSent.size(), FeatureType.NUMERIC)); featList.add(new Feature(FN_GAPS_IN_COVERSENTENCE, gapsinCoverSent.size(), FeatureType.NUMERIC)); return featList; } private static List<Gap> getPreviousGapList(JCas jcas, Gap gap) { List<Gap> gapList = new ArrayList<Gap>(); for (Gap g : JCasUtil.select(jcas, Gap.class)) { if (g.getBegin() == gap.getBegin() && g.getEnd() == gap.getEnd()) { return gapList; } else { gapList.add(g); } } return null; } }
9244e294fce89716ad7b9ab03ff037294f4a4f5e
389
java
Java
CustomComponent/app/src/main/java/com/android/omiplekevin/customcomponent/dao/CustomContent.java
omiplekevin/BywaveOJTTraining
ccf9ca3fd260d2430ab8ac95db97240c7f6cfacc
[ "Apache-2.0" ]
null
null
null
CustomComponent/app/src/main/java/com/android/omiplekevin/customcomponent/dao/CustomContent.java
omiplekevin/BywaveOJTTraining
ccf9ca3fd260d2430ab8ac95db97240c7f6cfacc
[ "Apache-2.0" ]
null
null
null
CustomComponent/app/src/main/java/com/android/omiplekevin/customcomponent/dao/CustomContent.java
omiplekevin/BywaveOJTTraining
ccf9ca3fd260d2430ab8ac95db97240c7f6cfacc
[ "Apache-2.0" ]
null
null
null
20.473684
53
0.706941
1,003,178
package com.android.omiplekevin.customcomponent.dao; /** * Created by OMIPLEKEVIN on February 13, 2018. * CustomComponent * com.android.omiplekevin.customcomponent.dao */ public class CustomContent { public int imageResId; public String content; public CustomContent(int resId, String content) { this.imageResId = resId; this.content = content; } }