hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
33ffc9ba42fc0f40227f5418b699cd44abf3258d
| 651
|
package me.zeroX150.cornos.features.module.impl.external;
import me.zeroX150.cornos.features.module.Module;
import me.zeroX150.cornos.features.module.ModuleType;
public class BudgetGraphics extends Module {
boolean prev;
public BudgetGraphics() {
super("BudgetGraphics", "Makes the client visuals ugly (and your fps higher)", ModuleType.RENDER);
}
@Override
public void onEnable() {
prev = Hud.themeColor.isRainbow();
}
@Override
public void onExecute() {
Hud.themeColor.setRainbow(false);
}
@Override
public void onDisable() {
Hud.themeColor.setRainbow(prev);
}
}
| 23.25
| 106
| 0.680492
|
67273f83364f7404f696976ac900173cabf080f9
| 118
|
package com.esotericsoftware.reflectasm;
public abstract class PublicConstructorAccess extends ConstructorAccess {
}
| 23.6
| 73
| 0.864407
|
20de88df7f3d686544e47005bcec3708b1e312e8
| 718
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.core.clients.workitem.category;
/**
* A work item category.
*
* @since TEE-SDK-10.1
*/
public interface Category {
/**
* @return the work item type category identifier.
*/
int getID();
/**
* @return the work item type category name.
*/
String getName();
/**
* @return the work item type category reference name.
*/
String getReferenceName();
/**
* @return the work item type identifier of the default work item type for
* this category.
*/
int getDefaultWorkItemTypeID();
}
| 21.757576
| 78
| 0.628134
|
76234c7e9b8a014470c46324859cb8f94f6560e6
| 126
|
package org.mindidea.circle.setter;
public class TestC {
private TestA a;
public void setA(TestA a) {
this.a = a;
}
}
| 11.454545
| 35
| 0.674603
|
eda41d63bd7a1aec563d71c771334ae5130ae361
| 141
|
package com.huifer.source.spring.ann;
import org.springframework.stereotype.Service;
@Service(value = "dhc")
public class DemoService {
}
| 15.666667
| 46
| 0.77305
|
844304ac41931007da708c0eefd111ac8e6116ee
| 2,389
|
/*
* Copyright 2019 Doordeck Limited
*
* 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.doordeck.sdk.jackson;
import com.doordeck.sdk.jackson.deserializer.DurationDeserializer;
import com.doordeck.sdk.jackson.deserializer.Ed25519PublicKeyDeserializer;
import com.doordeck.sdk.jackson.deserializer.PrivateKeyDeserializer;
import com.doordeck.sdk.jackson.serializer.DurationSerializer;
import com.doordeck.sdk.jackson.serializer.PrivateKeySerializer;
import com.doordeck.sdk.jackson.serializer.PublicKeySerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.joda.time.Duration;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Jackson {
private Jackson() { /* static class */ }
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.registerModule(new OptionalUpdateModule())
.registerModule(new GuavaModule())
.registerModule(new JodaModule())
.registerModule(new SimpleModule()
.addSerializer(new DurationSerializer())
.addDeserializer(Duration.class, new DurationDeserializer())
.addSerializer(PublicKey.class, new PublicKeySerializer())
.addSerializer(PrivateKey.class, new PrivateKeySerializer())
.addDeserializer(PublicKey.class, new Ed25519PublicKeyDeserializer())
.addDeserializer(PrivateKey.class, new PrivateKeyDeserializer())
)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
public static ObjectMapper sharedObjectMapper() {
return OBJECT_MAPPER;
}
}
| 41.189655
| 81
| 0.747593
|
9450202e03db6ebe79e29108dfb54fda5d3a4345
| 3,103
|
/*
* Copyright (c) 2017-2020 Evolveum
*
* 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.evolveum.midpoint.client.impl.restjaxb;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.apache.cxf.common.util.CollectionUtils;
import com.evolveum.midpoint.client.api.SearchResult;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
/**
*
* @author katkav
*
*/
public class JaxbSearchResult<O extends ObjectType> implements SearchResult<O> {
private List<O> list = null;
public JaxbSearchResult() {
}
public JaxbSearchResult(List<O> list) {
super();
this.list = list;
}
@Override
public int size() {
if (list == null) {
return 0;
}
return list.size();
}
@Override
public boolean isEmpty() {
return CollectionUtils.isEmpty(list);
}
@Override
public boolean contains(Object o) {
return list.contains(o);
}
@Override
public Iterator<O> iterator() {
return list.iterator();
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return list.toArray(a);
}
@Override
public boolean add(O e) {
return list.add(e);
}
@Override
public boolean remove(Object o) {
return list.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return list.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends O> c) {
return list.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends O> c) {
return list.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
@Override
public void clear() {
list.clear();
}
@Override
public O get(int index) {
return list.get(index);
}
@Override
public O set(int index, O element) {
return list.set(index, element);
}
@Override
public void add(int index, O element) {
list.add(index, element);
}
@Override
public O remove(int index) {
return list.remove(index);
}
@Override
public int indexOf(Object o) {
return list.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
@Override
public ListIterator<O> listIterator() {
return list.listIterator();
}
@Override
public ListIterator<O> listIterator(int index) {
return list.listIterator(index);
}
@Override
public List<O> subList(int fromIndex, int toIndex) {
return subList(fromIndex, toIndex);
}
}
| 18.580838
| 80
| 0.700935
|
0d32527cc36919d36861cfc610abcd2d356b2e27
| 135
|
package L15;
public class StackFullException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 12.272727
| 51
| 0.703704
|
585504155accaa9d2f08406827439904572e2df2
| 7,226
|
package com.example.rtuschedule;
public class Programs {
public static Program AD = getAD();
public static Program FI = getFI();
public static Program IT1 = getIT1();
public static Program IT2 = getIT2();
public static Program getProgram(int id) {
switch(id) {
case 0: return AD;
case 1: return AD;
case 2: return IT1;
case 3: return IT2;
default: return AD;
}
}
private static Program getAD() {
Class class2, class3, class4, class5;
Day day1, day2, day3;
class2 = new Class(Classrooms.D2_329, Subjects.CiparvadibasSistemas, Types.Lecture_PracticeWork, Teachers.Markovics);
class3 = class2;
class4 = new Class(Classrooms.D2_340, Subjects.Modelesana3D, Types.Lecture_LaboratoryWork, Teachers.Kovalovs);
class5 = class4;
day1 = new Day(Class.empty, class2, class3, class4, class5, Class.empty, Class.empty);
class3 = new Class(Classrooms.D2_348, Subjects.Arhitektura, Types.Lecture_LaboratoryWork, Teachers.Zagurskis);
class4 = class3;
class5 = new Class(Classrooms.Az12_K1_116, Subjects.Psihologija, Types.Lecture_PracticeWork, Teachers.Steinberga);
day2 = new Day(Class.empty, Class.empty, class3, class4, class5, Class.empty, Class.empty);
class2 = new Class(Classrooms.D2_340, Subjects.InteraktivaGrafika, Types.Lecture_LaboratoryWork, Teachers.Kovalovs);
class3 = new Class(Classrooms.D2_341, Subjects.ScenuAnalize, Types.Lecture_LaboratoryWork, Teachers.Sisojevs);
class4 = new Class(Classrooms.D2_340, Subjects.ScenuAnalize, Types.Lecture_LaboratoryWork, Teachers.Krutikova);
class5 = new Class(Classrooms.Kip6B_300, Subjects.SocialaPsihologija, Types.Lecture_PracticeWork, Teachers.Gudzuka);
day3 = new Day(Class.empty, class2, class3, class4, class5, Class.empty, Class.empty);
Week oddWeek = new Week(day1, day2, day3, Day.empty, Day.empty);
class2 = new Class(Classrooms.D2_341, Subjects.CiparvadibasSistemas, Types.Lecture_PracticeWork, Teachers.Markovics);
class3 = new Class(Classrooms.D2_341, Subjects.CiparvadibasSistemas, Types.Lecture_PracticeWork, Teachers.Markovics);
class4 = new Class(Classrooms.D2_340, Subjects.Modelesana3D, Types.Lecture_LaboratoryWork, Teachers.Kovalovs);
day1 = new Day(Class.empty, class2, class3, class4, Class.empty, Class.empty, Class.empty);
class3 = new Class(Classrooms.D2_348, Subjects.Arhitektura, Types.Lecture_LaboratoryWork, Teachers.Zagurskis);
class4 = new Class(Classrooms.D2_348, Subjects.Arhitektura, Types.Lecture_LaboratoryWork, Teachers.Zagurskis);
class5 = new Class(Classrooms.Az12_K1_116, Subjects.Psihologija, Types.Lecture_PracticeWork, Teachers.Steinberga);
day2 = new Day(Class.empty, Class.empty, class3, class4, class5, Class.empty, Class.empty);
class2 = new Class(Classrooms.D2_340, Subjects.InteraktivaGrafika, Types.Lecture_LaboratoryWork, Teachers.Kovalovs);
class3 = new Class(Classrooms.D2_341, Subjects.ScenuAnalize, Types.Lecture_LaboratoryWork, Teachers.Sisojevs);
class4 = class2;
class5 = new Class(Classrooms.Kip6B_300, Subjects.SocialaPsihologija, Types.Lecture_PracticeWork, Teachers.Gudzuka);
day3 = new Day(Class.empty, class2, class3, class4, class5, Class.empty, Class.empty);
Week evenWeek = new Week(day1, day2, day3, Day.empty, Day.empty);
return new Program(oddWeek, evenWeek);
}
private static Program getFI() {
return Program.empty;
}
private static Program getIT1() {
Class class3, class4, class5, class6, class7;
Day day1, day2, day3;
class3 = new Class(Classrooms.D2_435, Subjects.BiznesaModelesana, Types.Lecture_LaboratoryWork, Teachers.Bolsakovs);
class4 = new Class(Classrooms.D2_447, Subjects.LogistikasSistemas, Types.Lecture_LaboratoryWork, Teachers.Romanovs);
class5 = new Class(Classrooms.D2_447, Subjects.LogistikasSistemas + " (or ?)", Types.Lecture_LaboratoryWork, Teachers.Romanovs);
day1 = new Day(Class.empty, Class.empty, class3, class4, class5, Class.empty, Class.empty);
class4 = new Class(Classrooms.S1_413, Subjects.LemumuAnalize, Types.Lecture, Teachers.Aleksejeva);
class5 = new Class(Classrooms.Az12_K1_116, Subjects.Psihologija + " (or Pedagoģija)", Types.Lecture_PracticeWork, Teachers.Steinberga);
class6 = new Class(Classrooms.S1_407, Subjects.Portfelvadiba, Types.Lecture_LaboratoryWork, Teachers.Grabis);
class7 = new Class(Classrooms.S1_407, Subjects.Portfelvadiba, Types.Lecture_LaboratoryWork, Teachers.Grabis);
day2 = new Day(Class.empty, Class.empty, Class.empty, class4, class5, class6, class7);
class4 = new Class(Classrooms.S1_412, Subjects.ItParvaldiba, Types.Lecture, Teachers.Romanovs);
class5 = new Class(Classrooms.S1_407, Subjects.Transformacija, Types.Lecture, Teachers.Grabis);
class6 = new Class(Classrooms.S1_405, Subjects.Transformacija, Types.LaboratoryWork, Teachers.Grabis);
day3 = new Day(Class.empty, Class.empty, Class.empty, class4, class5, class6, Class.empty);
Week oddWeek = new Week(day1, day2, day3, Day.empty, Day.empty);
class3 = new Class(Classrooms.D2_435, Subjects.BiznesaModelesana, Types.Lecture_LaboratoryWork, Teachers.Bolsakovs);
class4 = new Class(Classrooms.S1_413, Subjects.LogistikasSistemas, Types.Lecture, Teachers.Romanovs);
class5 = new Class(Classrooms.S1_405, Subjects.WEB + " (or ?)", Types.Lecture_LaboratoryWork, Teachers.Kampars);
class6 = new Class(Classrooms.S1_407, Subjects.WEB, Types.Lecture, Teachers.Kampars);
day1 = new Day(Class.empty, Class.empty, class3, class4, class5, class6, Class.empty);
class4 = new Class(Classrooms.S1_413, Subjects.LemumuAnalize, Types.Lecture, Teachers.Aleksejeva);
class5 = new Class(Classrooms.Az12_K1_116, Subjects.Psihologija + " (or Pedagoģija)", Types.Lecture_PracticeWork, Teachers.Steinberga);
class6 = new Class(Classrooms.S1_407, Subjects.Portfelvadiba, Types.Lecture_LaboratoryWork, Teachers.Grabis);
class7 = new Class(Classrooms.S1_407, Subjects.Portfelvadiba, Types.Lecture_LaboratoryWork, Teachers.Grabis);
day2 = new Day(Class.empty, Class.empty, Class.empty, class4, class5, class6, class7);
class3 = new Class(Classrooms.S1_413, Subjects.LemumuAnalize, Types.LaboratoryWork, Teachers.Aleksejeva);
class4 = new Class(Classrooms.S1_412, Subjects.ItParvaldiba, Types.Lecture, Teachers.Romanovs);
class5 = new Class(Classrooms.S1_407, Subjects.Transformacija, Types.Lecture, Teachers.Grabis);
class6 = new Class(Classrooms.S1_405, Subjects.Transformacija, Types.LaboratoryWork, Teachers.Grabis);
day3 = new Day(Class.empty, Class.empty, class3, class4, class5, class6, Class.empty);
Week evenWeek = new Week(day1, day2, day3, Day.empty, Day.empty);
return new Program(oddWeek, evenWeek);
}
private static Program getIT2() {
Class class3, class4, class5;
Day day1;
class3 = new Class(Classrooms.S1_413, Subjects.Logistika, Types.Lecture, Teachers.Petuhova);
class4 = new Class(Classrooms.S1_413, Subjects.Logistika, Types.LaboratoryWork, Teachers.Petuhova);
class5 = new Class(Classrooms.S1_413, Subjects.Logistika, Types.LaboratoryWork, Teachers.Petuhova);
day1 = new Day(Class.empty, Class.empty, class3, class4, class5, Class.empty, Class.empty);
Week oddWeek = new Week(day1, Day.empty, Day.empty, Day.empty, Day.empty);
return new Program(oddWeek, Week.empty);
}
}
| 51.248227
| 137
| 0.77152
|
bddd2fe808ac487c1cee2a2dac64b12b801ffb2d
| 514
|
package me.zhengjie.modules.process.service.mapper;
import me.zhengjie.mapper.EntityMapper;
import me.zhengjie.modules.process.domain.ProcessRecipe;
import me.zhengjie.modules.process.service.dto.ProcessRecipeDTO;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author jie
* @date 2019-04-08
*/
@Mapper(componentModel = "spring", uses = {}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ProcessRecipeMapper extends EntityMapper<ProcessRecipeDTO, ProcessRecipe> {
}
| 32.125
| 92
| 0.805447
|
89d40548c2e8d15cf95d55092a64fc1c8899626b
| 1,582
|
/*
* Zynaptic Stash - An asynchronous persistence framework for Java.
*
* Copyright (c) 2009-2019, Zynaptic Limited.
*
* 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.
*
* Please visit www.zynaptic.com or contact reaction@zynaptic.com if you need
* additional information or have any questions.
*/
package com.zynaptic.stash;
import com.zynaptic.reaction.ReactionDefaultException;
/**
* Indicates that an invalid stash identifier has been supplied when attempting
* to manipulate the stash contents.
*
* @author Chris Holgate
*/
public final class InvalidStashIdException extends ReactionDefaultException {
private static final long serialVersionUID = -7584375301598387934L;
/**
* Provides default constructor for the invalid stash identifier exception
* object. The only supported constructor for this class of exception is the
* standard string message constructor.
*
* @param msg This is the message string which is used to describe the error
* condition.
*/
public InvalidStashIdException(String msg) {
super(msg);
}
}
| 33.659574
| 80
| 0.749684
|
72edf38cf7c9197738116606f30e1e688215fc3a
| 42,535
|
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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.xensource.xenapi;
import com.xensource.xenapi.Types.BadServerResponse;
import com.xensource.xenapi.Types.VersionException;
import com.xensource.xenapi.Types.XenAPIException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.xmlrpc.XmlRpcException;
/**
* A virtual block device
*
* @author Citrix Systems, Inc.
*/
public class VBD extends XenAPIObject {
/**
* The XenAPI reference (OpaqueRef) to this object.
*/
protected final String ref;
/**
* For internal use only.
*/
VBD(String ref) {
this.ref = ref;
}
/**
* @return The XenAPI reference (OpaqueRef) to this object.
*/
public String toWireString() {
return this.ref;
}
/**
* If obj is a VBD, compares XenAPI references for equality.
*/
@Override
public boolean equals(Object obj)
{
if (obj != null && obj instanceof VBD)
{
VBD other = (VBD) obj;
return other.ref.equals(this.ref);
} else
{
return false;
}
}
@Override
public int hashCode()
{
return ref.hashCode();
}
/**
* Represents all the fields in a VBD
*/
public static class Record implements Types.Record {
public String toString() {
StringWriter writer = new StringWriter();
PrintWriter print = new PrintWriter(writer);
print.printf("%1$20s: %2$s\n", "uuid", this.uuid);
print.printf("%1$20s: %2$s\n", "allowedOperations", this.allowedOperations);
print.printf("%1$20s: %2$s\n", "currentOperations", this.currentOperations);
print.printf("%1$20s: %2$s\n", "VM", this.VM);
print.printf("%1$20s: %2$s\n", "VDI", this.VDI);
print.printf("%1$20s: %2$s\n", "device", this.device);
print.printf("%1$20s: %2$s\n", "userdevice", this.userdevice);
print.printf("%1$20s: %2$s\n", "bootable", this.bootable);
print.printf("%1$20s: %2$s\n", "mode", this.mode);
print.printf("%1$20s: %2$s\n", "type", this.type);
print.printf("%1$20s: %2$s\n", "unpluggable", this.unpluggable);
print.printf("%1$20s: %2$s\n", "storageLock", this.storageLock);
print.printf("%1$20s: %2$s\n", "empty", this.empty);
print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig);
print.printf("%1$20s: %2$s\n", "currentlyAttached", this.currentlyAttached);
print.printf("%1$20s: %2$s\n", "statusCode", this.statusCode);
print.printf("%1$20s: %2$s\n", "statusDetail", this.statusDetail);
print.printf("%1$20s: %2$s\n", "runtimeProperties", this.runtimeProperties);
print.printf("%1$20s: %2$s\n", "qosAlgorithmType", this.qosAlgorithmType);
print.printf("%1$20s: %2$s\n", "qosAlgorithmParams", this.qosAlgorithmParams);
print.printf("%1$20s: %2$s\n", "qosSupportedAlgorithms", this.qosSupportedAlgorithms);
print.printf("%1$20s: %2$s\n", "metrics", this.metrics);
return writer.toString();
}
/**
* Convert a VBD.Record to a Map
*/
public Map<String,Object> toMap() {
Map<String,Object> map = new HashMap<String,Object>();
map.put("uuid", this.uuid == null ? "" : this.uuid);
map.put("allowed_operations", this.allowedOperations == null ? new LinkedHashSet<Types.VbdOperations>() : this.allowedOperations);
map.put("current_operations", this.currentOperations == null ? new HashMap<String, Types.VbdOperations>() : this.currentOperations);
map.put("VM", this.VM == null ? new VM("OpaqueRef:NULL") : this.VM);
map.put("VDI", this.VDI == null ? new VDI("OpaqueRef:NULL") : this.VDI);
map.put("device", this.device == null ? "" : this.device);
map.put("userdevice", this.userdevice == null ? "" : this.userdevice);
map.put("bootable", this.bootable == null ? false : this.bootable);
map.put("mode", this.mode == null ? Types.VbdMode.UNRECOGNIZED : this.mode);
map.put("type", this.type == null ? Types.VbdType.UNRECOGNIZED : this.type);
map.put("unpluggable", this.unpluggable == null ? false : this.unpluggable);
map.put("storage_lock", this.storageLock == null ? false : this.storageLock);
map.put("empty", this.empty == null ? false : this.empty);
map.put("other_config", this.otherConfig == null ? new HashMap<String, String>() : this.otherConfig);
map.put("currently_attached", this.currentlyAttached == null ? false : this.currentlyAttached);
map.put("status_code", this.statusCode == null ? 0 : this.statusCode);
map.put("status_detail", this.statusDetail == null ? "" : this.statusDetail);
map.put("runtime_properties", this.runtimeProperties == null ? new HashMap<String, String>() : this.runtimeProperties);
map.put("qos_algorithm_type", this.qosAlgorithmType == null ? "" : this.qosAlgorithmType);
map.put("qos_algorithm_params", this.qosAlgorithmParams == null ? new HashMap<String, String>() : this.qosAlgorithmParams);
map.put("qos_supported_algorithms", this.qosSupportedAlgorithms == null ? new LinkedHashSet<String>() : this.qosSupportedAlgorithms);
map.put("metrics", this.metrics == null ? new VBDMetrics("OpaqueRef:NULL") : this.metrics);
return map;
}
/**
* Unique identifier/object reference
*/
public String uuid;
/**
* list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
*/
public Set<Types.VbdOperations> allowedOperations;
/**
* links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
*/
public Map<String, Types.VbdOperations> currentOperations;
/**
* the virtual machine
*/
public VM VM;
/**
* the virtual disk
*/
public VDI VDI;
/**
* device seen by the guest e.g. hda1
*/
public String device;
/**
* user-friendly device name e.g. 0,1,2,etc.
*/
public String userdevice;
/**
* true if this VBD is bootable
*/
public Boolean bootable;
/**
* the mode the VBD should be mounted with
*/
public Types.VbdMode mode;
/**
* how the VBD will appear to the guest (e.g. disk or CD)
*/
public Types.VbdType type;
/**
* true if this VBD will support hot-unplug
*/
public Boolean unpluggable;
/**
* true if a storage level lock was acquired
*/
public Boolean storageLock;
/**
* if true this represents an empty drive
*/
public Boolean empty;
/**
* additional configuration
*/
public Map<String, String> otherConfig;
/**
* is the device currently attached (erased on reboot)
*/
public Boolean currentlyAttached;
/**
* error/success code associated with last attach-operation (erased on reboot)
*/
public Long statusCode;
/**
* error/success information associated with last attach-operation status (erased on reboot)
*/
public String statusDetail;
/**
* Device runtime properties
*/
public Map<String, String> runtimeProperties;
/**
* QoS algorithm to use
*/
public String qosAlgorithmType;
/**
* parameters for chosen QoS algorithm
*/
public Map<String, String> qosAlgorithmParams;
/**
* supported QoS algorithms for this VBD
*/
public Set<String> qosSupportedAlgorithms;
/**
* metrics associated with this VBD
*/
public VBDMetrics metrics;
}
/**
* Get a record containing the current state of the given VBD.
*
* @return all fields from the object
*/
public VBD.Record getRecord(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_record";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVBDRecord(result);
}
/**
* Get a reference to the VBD instance with the specified UUID.
*
* @param uuid UUID of object to return
* @return reference to the object
*/
public static VBD getByUuid(Connection c, String uuid) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_by_uuid";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVBD(result);
}
/**
* Create a new VBD instance, and return its handle.
*
* @param record All constructor arguments
* @return Task
*/
public static Task createAsync(Connection c, VBD.Record record) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.VBD.create";
String session = c.getSessionReference();
Map<String, Object> record_map = record.toMap();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Create a new VBD instance, and return its handle.
*
* @param record All constructor arguments
* @return reference to the newly created object
*/
public static VBD create(Connection c, VBD.Record record) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.create";
String session = c.getSessionReference();
Map<String, Object> record_map = record.toMap();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVBD(result);
}
/**
* Destroy the specified VBD instance.
*
* @return Task
*/
public Task destroyAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.VBD.destroy";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Destroy the specified VBD instance.
*
*/
public void destroy(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.destroy";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Get the uuid field of the given VBD.
*
* @return value of the field
*/
public String getUuid(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_uuid";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the allowed_operations field of the given VBD.
*
* @return value of the field
*/
public Set<Types.VbdOperations> getAllowedOperations(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_allowed_operations";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfVbdOperations(result);
}
/**
* Get the current_operations field of the given VBD.
*
* @return value of the field
*/
public Map<String, Types.VbdOperations> getCurrentOperations(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_current_operations";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringVbdOperations(result);
}
/**
* Get the VM field of the given VBD.
*
* @return value of the field
*/
public VM getVM(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_VM";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVM(result);
}
/**
* Get the VDI field of the given VBD.
*
* @return value of the field
*/
public VDI getVDI(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_VDI";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVDI(result);
}
/**
* Get the device field of the given VBD.
*
* @return value of the field
*/
public String getDevice(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_device";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the userdevice field of the given VBD.
*
* @return value of the field
*/
public String getUserdevice(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_userdevice";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the bootable field of the given VBD.
*
* @return value of the field
*/
public Boolean getBootable(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_bootable";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBoolean(result);
}
/**
* Get the mode field of the given VBD.
*
* @return value of the field
*/
public Types.VbdMode getMode(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_mode";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVbdMode(result);
}
/**
* Get the type field of the given VBD.
*
* @return value of the field
*/
public Types.VbdType getType(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_type";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVbdType(result);
}
/**
* Get the unpluggable field of the given VBD.
*
* @return value of the field
*/
public Boolean getUnpluggable(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_unpluggable";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBoolean(result);
}
/**
* Get the storage_lock field of the given VBD.
*
* @return value of the field
*/
public Boolean getStorageLock(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_storage_lock";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBoolean(result);
}
/**
* Get the empty field of the given VBD.
*
* @return value of the field
*/
public Boolean getEmpty(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_empty";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBoolean(result);
}
/**
* Get the other_config field of the given VBD.
*
* @return value of the field
*/
public Map<String, String> getOtherConfig(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringString(result);
}
/**
* Get the currently_attached field of the given VBD.
*
* @return value of the field
*/
public Boolean getCurrentlyAttached(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_currently_attached";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBoolean(result);
}
/**
* Get the status_code field of the given VBD.
*
* @return value of the field
*/
public Long getStatusCode(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_status_code";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toLong(result);
}
/**
* Get the status_detail field of the given VBD.
*
* @return value of the field
*/
public String getStatusDetail(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_status_detail";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the runtime_properties field of the given VBD.
*
* @return value of the field
*/
public Map<String, String> getRuntimeProperties(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_runtime_properties";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringString(result);
}
/**
* Get the qos/algorithm_type field of the given VBD.
*
* @return value of the field
*/
public String getQosAlgorithmType(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_qos_algorithm_type";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the qos/algorithm_params field of the given VBD.
*
* @return value of the field
*/
public Map<String, String> getQosAlgorithmParams(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_qos_algorithm_params";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringString(result);
}
/**
* Get the qos/supported_algorithms field of the given VBD.
*
* @return value of the field
*/
public Set<String> getQosSupportedAlgorithms(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_qos_supported_algorithms";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfString(result);
}
/**
* Get the metrics field of the given VBD.
*
* @return value of the field
*/
public VBDMetrics getMetrics(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_metrics";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toVBDMetrics(result);
}
/**
* Set the userdevice field of the given VBD.
*
* @param userdevice New value to set
*/
public void setUserdevice(Connection c, String userdevice) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_userdevice";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(userdevice)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the bootable field of the given VBD.
*
* @param bootable New value to set
*/
public void setBootable(Connection c, Boolean bootable) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_bootable";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(bootable)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the mode field of the given VBD.
*
* @param mode New value to set
*/
public void setMode(Connection c, Types.VbdMode mode) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_mode";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(mode)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the type field of the given VBD.
*
* @param type New value to set
*/
public void setType(Connection c, Types.VbdType type) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_type";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(type)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the unpluggable field of the given VBD.
*
* @param unpluggable New value to set
*/
public void setUnpluggable(Connection c, Boolean unpluggable) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_unpluggable";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(unpluggable)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the other_config field of the given VBD.
*
* @param otherConfig New value to set
*/
public void setOtherConfig(Connection c, Map<String, String> otherConfig) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Add the given key-value pair to the other_config field of the given VBD.
*
* @param key Key to add
* @param value Value to add
*/
public void addToOtherConfig(Connection c, String key, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.add_to_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the given key and its corresponding value from the other_config field of the given VBD. If the key is not in that Map, then do nothing.
*
* @param key Key to remove
*/
public void removeFromOtherConfig(Connection c, String key) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.remove_from_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the qos/algorithm_type field of the given VBD.
*
* @param algorithmType New value to set
*/
public void setQosAlgorithmType(Connection c, String algorithmType) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_qos_algorithm_type";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(algorithmType)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the qos/algorithm_params field of the given VBD.
*
* @param algorithmParams New value to set
*/
public void setQosAlgorithmParams(Connection c, Map<String, String> algorithmParams) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.set_qos_algorithm_params";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(algorithmParams)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Add the given key-value pair to the qos/algorithm_params field of the given VBD.
*
* @param key Key to add
* @param value Value to add
*/
public void addToQosAlgorithmParams(Connection c, String key, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.add_to_qos_algorithm_params";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the given key and its corresponding value from the qos/algorithm_params field of the given VBD. If the key is not in that Map, then do nothing.
*
* @param key Key to remove
*/
public void removeFromQosAlgorithmParams(Connection c, String key) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.remove_from_qos_algorithm_params";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the media from the device and leave it empty
*
* @return Task
*/
public Task ejectAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.VbdNotRemovableMedia,
Types.VbdIsEmpty {
String method_call = "Async.VBD.eject";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Remove the media from the device and leave it empty
*
*/
public void eject(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.VbdNotRemovableMedia,
Types.VbdIsEmpty {
String method_call = "VBD.eject";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Insert new media into the device
*
* @param vdi The new VDI to 'insert'
* @return Task
*/
public Task insertAsync(Connection c, VDI vdi) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.VbdNotRemovableMedia,
Types.VbdNotEmpty {
String method_call = "Async.VBD.insert";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(vdi)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Insert new media into the device
*
* @param vdi The new VDI to 'insert'
*/
public void insert(Connection c, VDI vdi) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.VbdNotRemovableMedia,
Types.VbdNotEmpty {
String method_call = "VBD.insert";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(vdi)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Hotplug the specified VBD, dynamically attaching it to the running VM
*
* @return Task
*/
public Task plugAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.VBD.plug";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Hotplug the specified VBD, dynamically attaching it to the running VM
*
*/
public void plug(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.plug";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Hot-unplug the specified VBD, dynamically unattaching it from the running VM
*
* @return Task
*/
public Task unplugAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.DeviceDetachRejected,
Types.DeviceAlreadyDetached {
String method_call = "Async.VBD.unplug";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Hot-unplug the specified VBD, dynamically unattaching it from the running VM
*
*/
public void unplug(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.DeviceDetachRejected,
Types.DeviceAlreadyDetached {
String method_call = "VBD.unplug";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Forcibly unplug the specified VBD
*
* @return Task
*/
public Task unplugForceAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.VBD.unplug_force";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Forcibly unplug the specified VBD
*
*/
public void unplugForce(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.unplug_force";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Throws an error if this VBD could not be attached to this VM if the VM were running. Intended for debugging.
*
* @return Task
*/
public Task assertAttachableAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.VBD.assert_attachable";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Throws an error if this VBD could not be attached to this VM if the VM were running. Intended for debugging.
*
*/
public void assertAttachable(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.assert_attachable";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Return a list of all the VBDs known to the system.
*
* @return references to all objects
*/
public static Set<VBD> getAll(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_all";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfVBD(result);
}
/**
* Return a map of VBD references to VBD records for all VBDs known to the system.
*
* @return records of all objects
*/
public static Map<VBD, VBD.Record> getAllRecords(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "VBD.get_all_records";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfVBDVBDRecord(result);
}
}
| 36.63652
| 165
| 0.638063
|
64c844537052d9d849fadfca7bbd4dcca2fe98be
| 854
|
//package jTraverser;
import java.beans.*;
import java.awt.*;
public class NodeInfoPropertyEditor implements PropertyEditor {
protected Data data;
public void setValue(Object o){data = (Data)o;}
public Object getValue() {return data;}
public void setAsText(String s){}
public String getAsText() {return null; }
public String []getTags() {return null;}
public boolean supportsCustomEditor() {return true;}
public Component getCustomEditor(){return new NodeEditor(); }
public boolean isPaintable() {return false; }
public void paintValue(Graphics g, Rectangle r){}
public String getJavaInitializationString() {return null; }
// event notification not used here
public void addPropertyChangeListener(PropertyChangeListener l){}
public void removePropertyChangeListener(PropertyChangeListener l){}
}
| 40.666667
| 72
| 0.738876
|
1db8172639d5a21d4a21920d2008cbb4a0161437
| 5,463
|
package com.example.springboot.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.springboot.Utils.LogGenerate;
import com.example.springboot.pojo.Country;
import com.example.springboot.pojo.SingleData;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;
import java.io.*;
import java.util.*;
/**
* vue 用法 <script>中
* export default {
* name: 'RequestSarsData',
* data () {
* return {
* DataForm: {
* country: '',
* year: '',
* month: '',
* day: ''
* },
* responseResult: []
* }
* },
* methods: {
* query () {
* this.$axios
* .post('/sars', {
* country: this.DataForm.country,
* year: this.DataForm.year,
* month: this.DataForm.month,
* day: this.DataForm.day
* })
* .then(successResponse => {
* document.getElementById('sars_res').innerText = successResponse.data
* })
* .catch(failResponse => {})
* }
* }
* }
*/
@RestController
public class SARSController implements ApplicationRunner {
static List<SingleData> lists = new ArrayList<>();
@Override
public void run(ApplicationArguments args) throws Exception {
// String path = SARSController.class.getClassLoader().getResource("static/sars.json").getPath();
String classPath = "static/sars.json";
// String s = readJsonFile(path);
String s = readJsonFileInputStream(classPath);
JSONArray jarr = JSON.parseArray(s);
lists = JSONArray.parseArray(jarr.toJSONString(), SingleData.class);
}
@CrossOrigin
@PostMapping(value = "api/sars")
@ResponseBody
public String requestSARSData(@RequestBody Country country){
// 传入 国家名, year, month, day
// 返回 "确诊-死亡-疑似"
String c_name = country.getCountry();
String date_year = country.getYear();
String date_month = country.getMonth();
String date_day = country.getDay();
int[] res = getCaseNumber(c_name, Integer.parseInt(date_year), Integer.parseInt(date_month)
, Integer.parseInt(date_day));
if(res != null) {
return res[0] + "-" + res[1] + "-" + res[2];
}else{
return null;
}
}
@RequestMapping(value = "/api/getAllSarsData", method = RequestMethod.GET)
public List<SingleData> getAllSarsData(
@RequestParam(value = "countryName", required = false) String countryName) {
System.out.println(LogGenerate.log(this.getClass(), "Request all SARS Data."));
return lists;
}
public SARSController() {
}
/**
* 根据国家[暂时不用], 年月日来返回当日SARS信息
* @param country
* @param year
* @param month
* @param day
* @return int数组, [0]->确诊, [1]->死亡, [2]->疑似
*/
private static int[] getCaseNumber(String country, int year, int month, int day){
System.out.println("Request: "+country+", "+year+", "+month+", "+day);
SingleData res = null;
for(SingleData sd: lists){
if(sd.getYear()==year && sd.getMonth()==month && sd.getDay()==day){
res = sd;
break;
}
}
if (res!=null){
int[] data = new int[]{res.getConfirm(), res.getDead(), res.getSuspect()};
System.out.println("Return: "+Arrays.toString(data));
return data;
}else{
System.out.println("Return: null");
return null;
}
}
private static String readJsonFile(String fileName){
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static String readJsonFileInputStream(String classPath) {
StringBuilder jsonStr = new StringBuilder();
try {
// 采用InputStream的方式进行读取,防止打包成jar之后无法获取到资源路径地址
InputStream is = new ClassPathResource(classPath).getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = reader.readLine())!=null) {
jsonStr.append(line);
}
return jsonStr.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
int[] res = getCaseNumber("China", 2003, 6, 25);
if(res!=null) {
System.out.println("Confirm: " + res[0] + ", Dead: " + res[1] + ", Suspect: " + res[2]);
}
}
}
| 31.396552
| 105
| 0.574593
|
2a0371b5941446131c07b898ab3dbd65f719affb
| 6,027
|
import java.util.*;
class HW6 {
public static String pantherID() {
return "002354500";
}
/**
Your adjacency matrix:
[null, null, 11, null, 6, null, 13]
[null, null, 3, null, null, 3, 1]
[ 11, 3, null, null, null, 14, null]
[null, null, null, null, null, 8, 14]
[ 6, null, null, null, null, 1, null]
[null, 3, 14, 8, 1, null, 14]
[ 13, 1, null, 14, null, 14, null]
**/
public static List<List<Pair>> adjList() {
return Arrays.asList(
Arrays.asList(pair(2, 11), pair(4, 6), pair(6, 13)),
Arrays.asList(pair(2, 3), pair(5, 3), pair(6, 1)),
Arrays.asList(pair(0, 11), pair(1, 3), pair(5, 14)),
Arrays.asList(pair(5, 8), pair(6, 14)),
Arrays.asList(pair(0, 6), pair(5, 1)),
Arrays.asList(pair(1, 3), pair(2, 14), pair(3, 8), pair(4, 1), pair(6, 14)),
Arrays.asList(pair(0, 13), pair(1, 1), pair(3, 14), pair(5, 14))
);
}
public static int[][] dist() {
int inf = Integer.MAX_VALUE;
return new int[][] {
{inf, inf, inf, inf, inf, inf, inf}, // (initial)
{0, inf, inf, inf, inf, inf, inf}, // (setting dist[s] = 0
{0, inf, 11, inf, inf, inf, inf}, // (0 <-> 2 edge)
{0, inf, 11, inf, 6, inf, inf}, // (0 <-> 4 edge)
{0, inf, 11, inf, 6, inf, 13}, // (0 <-> 6 edge)
{0, inf, 11, inf, 6, inf, 13}, // (4 <-> 0 edge)
{0, inf, 11, inf, 6, 7, 13}, // ( 4 <-> 5 edge)
{0, 10, 11, inf, 6, 7, 13}, // (4 <-> 1 edge)
{0, 10, 11, inf, 6, 7, 13}, // (1 <-> 0 edge)
{0, 10, 11, 15, 6, 7, 13}, // (4 <-> 3 edge)
{0, 10, 11, 15, 6, 7, 13}, // (6 <-> 1 edge)
{0, 10, 11, 15, 6, 7, 13}, // (6 <-> 3 edge)
{0, 10, 11, 15, 6, 7, 13}, // (6 <-> 5 edge)
{0, 10, 11, 15, 6, 7, 13}, // (5 <-> 1 edge)
{0, 10, 11, 15, 6, 7, 11}, // (5 <-> 2 edge)
{0, 10, 11, 15, 6, 7, 11}, // (5 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
{0, 10, 11, 15, 6, 7, 11}, // (1 <-> 6 edge)
};
}
public static Integer[][] prev() {
return new Integer[][] {
{null, null, null, null, null, null, null}, // (initial)
{null, null, 0, null, null, null, null}, // (0 <-> 2 edge)
{null, null, 0, null, 0, null, null}, // (0 <-> 3 edge)
{null, null, 0, null, 0, null, 0}, // (3 <-> 0 edge)
{null, null, 0, null, 0, null, 0}, // (3 <-> 4 edge)
{null, null, 0, null, 0, 4, 0}, // (3 <-> 6 edge)
{null, 5, 0, null, 0, 4, 0}, // (2 <-> 0 edge)
{null, 5, 0, null, 0, 4, 0}, // (2 <-> 5 edge)
{null, 5, 0, 5, 0, 4, 0}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 0}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 0}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 0}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 0}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
{null, 5, 0, 5, 0, 4, 1}, // (4 <-> 3 edge)
};
}
// DO NOT MODIFY ANYTHING AFTER THIS LINE
public static void main(String[] args) {
Verifier v = new Verifier(pantherID());
Integer[][] m = v.generate();
System.out.println("Your adjacency matrix:");
printMatrix(m);
System.out.println(
String.format("\nRun Dijktra's starting at node %d", findFirstNonNullRow(m))
);
v.verifyList(adjList());
v.verifyDist(dist());
v.verifyPrev(prev());
}
public static void printMatrix(Integer[][] m) {
for (Integer[] arr : m) {
String[] row = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
if (arr[i] != null) {
if (arr[i] > 9) {
row[i] = " " + arr[i]; // Gotta pad the double digits
} else {
row[i] = " " + arr[i]; // Gotta pad the single digits
}
}
}
System.out.println(Arrays.toString(row));
}
}
public static int findFirstNonNullRow(Integer[][] m) {
for (int i = 0; i < m.length; i++) {
for (Integer edge : m[i]) {
if (edge != null) {
return i;
}
}
}
return -1;
}
public static Pair pair(int label, int weight) {
return new Pair(label, weight);
}
}
| 40.18
| 82
| 0.396383
|
8d6b56d5e164457dc23f3cccaddf17ea5738d65f
| 771
|
package org.jboss.weld.tests.annotatedType.superclass;
import org.jboss.weld.util.annotated.ForwardingAnnotatedType;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
/**
* @author Gert Palok
*/
public class TestExtension implements Extension {
public void processAnnotatedType(@Observes ProcessAnnotatedType<Child> event) {
final AnnotatedType<Child> annotatedType = event.getAnnotatedType();
event.setAnnotatedType(new ForwardingAnnotatedType<Child>() {
@Override
public AnnotatedType<Child> delegate() {
return annotatedType;
}
});
}
}
| 32.125
| 83
| 0.727626
|
343e4155ceb06e1e2eac52c0407cf8e5b27f25c5
| 2,677
|
package com.livos.companionplants.plants;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.livos.companionplants.R;
import com.livos.companionplants.data.local.database.model.PlantAssociation;
import com.livos.companionplants.events.PlantSelectedEvent;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private List<PlantAssociation> plantAssociations;
Context context;
PlantSelectedEvent plantSelectedEvent;
public RecyclerViewAdapter(Context context, List<PlantAssociation> plantsAssociations, PlantSelectedEvent plantSelectedEvent) {
this.plantAssociations = plantsAssociations;
this.context = context;
this.plantSelectedEvent = plantSelectedEvent;
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_list_item, null);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(view, plantSelectedEvent);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int resourceId = context.getResources().getIdentifier(plantAssociations.get(position).getPicture2(),"drawable", context.getPackageName());
holder.getIvPlant().setImageResource(resourceId);
holder.getTvPlantName().setText(plantAssociations.get(position).getPlantDefinition2());
Long flagId = plantAssociations.get(position).getFlagId();
holder.getTvPlantName().setBackgroundColor(getFlagColor(flagId));
holder.getIvPlant().setTag(plantAssociations.get(position).getPlantId2());
holder.setPlantAssociation(plantAssociations.get(position));
}
public int getFlagColor(Long flagId) {
switch (flagId.intValue()) {
case 1 :
return context.getResources().getColor(R.color.colorGood);
case 2:
return context.getResources().getColor(R.color.colorNeutral);
case 3:
return context.getResources().getColor(R.color.colorDebate);
case 4:
return context.getResources().getColor(R.color.colorBad);
case 5:
return context.getResources().getColor(R.color.colorNeutral);
default:
return Color.BLACK;
}
}
@Override
public int getItemCount() {
return plantAssociations.size();
}
}
| 38.797101
| 146
| 0.713859
|
327215cfa65f382ebcf104c4dff9dd8859023b8c
| 1,771
|
package E2020_07_18And19;
import java.util.Scanner;
public class P02AddBags {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double luggagePriceOver20 = Double.parseDouble(scanner.nextLine());
double luggageWeight = Double.parseDouble(scanner.nextLine());
int daysToTrip = Integer.parseInt(scanner.nextLine());
int luggageNumber = Integer.parseInt(scanner.nextLine());
double totalPrice = 0;
if (luggageWeight < 10) {
totalPrice = luggagePriceOver20 * 0.20;
if (daysToTrip < 7) {
totalPrice = totalPrice + totalPrice * 0.40;
} else if (daysToTrip <= 30) {
totalPrice = totalPrice + totalPrice * 0.15;
} else {
totalPrice = totalPrice + totalPrice * 0.10;
}
} else if (luggageWeight <= 20) {
totalPrice = luggagePriceOver20 * 0.50;
if (daysToTrip < 7) {
totalPrice = totalPrice + totalPrice * 0.40;
} else if (daysToTrip <= 30) {
totalPrice = totalPrice + totalPrice * 0.15;
} else {
totalPrice = totalPrice + totalPrice * 0.10;
}
} else {
totalPrice = luggagePriceOver20;
if (daysToTrip < 7) {
totalPrice = totalPrice + totalPrice * 0.40;
} else if (daysToTrip <= 30) {
totalPrice = totalPrice + totalPrice * 0.15;
} else {
totalPrice = totalPrice + totalPrice * 0.10;
}
}
System.out.printf("The total price of bags is: %.2f lv.", totalPrice * luggageNumber);
}
}
| 37.680851
| 95
| 0.52908
|
293d799c3bc1f05b30c36dee89129bf01537724c
| 4,339
|
package com.jonathanrobertson.spotless;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.PluginContainer;
import org.gradle.api.tasks.TaskContainer;
import com.diffplug.gradle.spotless.SpotlessExtension;
import com.diffplug.gradle.spotless.SpotlessPlugin;
import com.jonathanrobertson.spotless.utils.Git;
public class AutoSpotlessPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
PluginContainer pluginContainer = project.getPlugins();
SpotlessExtension spotlessExtension = Optional
.ofNullable(pluginContainer.findPlugin(SpotlessPlugin.class))
.orElseGet(() -> pluginContainer.apply(SpotlessPlugin.class))
.getExtension();
configureFormatting(spotlessExtension);
if ("dev".equals(System.getenv("AUTO_SPOTLESS_ENV"))) {
configureDevDependencies(project.getTasks());
}
}
protected static File getAbsolutePathFromEmbeddedFile(String filename) {
File target = new File(System.getProperty("java.io.tmpdir"), filename);
try (InputStream is = AutoSpotlessPlugin.class.getClassLoader().getResourceAsStream(filename)) {
Files.copy(Objects.requireNonNull(is), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (NullPointerException | IOException e) {
throw new RuntimeException("unable to find " + filename + " in AutoSpotlessPlugin", e);
}
return target;
}
private void configureFormatting(SpotlessExtension spotlessExtension) {
spotlessExtension.java(format -> {
format.removeUnusedImports();
format.importOrderFile(getAbsolutePathFromEmbeddedFile("spotless.importorder"));
format.eclipse().configFile(getAbsolutePathFromEmbeddedFile("spotless.eclipseformat.xml"));
});
spotlessExtension.format("misc", format -> {
format.target("**/*.md", "**/*.gradle", "**/.gitignore", "**/*.yml", "**/*.yaml");
format.trimTrailingWhitespace();
format.endWithNewline();
format.replaceRegex("too many blank lines", "^\\n\\n+", "\n");
});
spotlessExtension.format("gradle", format -> {
format.target("**/*.gradle");
format.replaceRegex("blank lines following {", "\\{\\n\\s*\\n+", "{\n");
});
}
private void configureDevDependencies(TaskContainer taskContainer) {
if (Git.isPresent()) {
taskContainer.register("beforeFormatting", t -> {
t.finalizedBy("spotlessApply");
t.doFirst(task -> {
// confirm we do not already have a dangling auto-stash entry
Git.stashListAutoId().ifPresent(i -> {
String message = String.format("ERROR: must pop or remove auto-stash entry before retrying: `git stash drop %d`, `git stash pop %d`", i, i);
System.out.println(message);
System.exit(1);
});
// copy current state to stash for comparison after spotlessApply
if (Git.stashPush()) {
Git.stashListAutoId().ifPresent(Git::stashApply);
}
});
});
taskContainer.getByName("spotlessApply", t -> {
t.finalizedBy("afterFormatting");
});
taskContainer.register("afterFormatting", t -> {
t.finalizedBy("build");
t.doFirst(task -> {
// get id for existing auto-stash (if one exists)
Optional<Integer> id = Git.stashListAutoId();
// check for and display changes to user
List<String> results = id.map(Git::diffStat).orElseGet(Git::diffStat);
if (results.size() == 0) {
System.out.println("INFO: no changes were made to tracked files by spotlessApply");
} else {
String newline = System.getProperty("line.separator");
System.out.println("WARNING: the following files were changed by spotlessApply; be sure to include them in your commit(s)"
+ newline + String.join(newline, results));
}
// drop stash entry from before (if exists) since it's no longer needed
id.ifPresent(Git::stashDrop);
});
});
taskContainer.getByName("build", t -> {
t.dependsOn("beforeFormatting");
});
} else {
taskContainer.getByName("build", t -> {
t.dependsOn("spotlessApply");
t.doLast(task -> System.out.println("WARNING: spotlessApply was automatically run; files may've changed"));
});
}
}
}
| 35.276423
| 146
| 0.705923
|
8cfc473e25037e72606b2a754be1b4c21d5e8a73
| 6,140
|
/*
* This file is part of JICI, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/>
*
* 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 ca.sapon.jici.lexer;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Symbol extends Token {
private static final Map<String, Symbol> SYMBOLS = new HashMap<>();
private static final Symbol[] CHAR_SYMBOLS = new Symbol[256];
private final Symbol compoundAssignOperator;
static {
// punctuation
add(TokenID.SYMBOL_PERIOD, ".");
add(TokenID.SYMBOL_COMMA, ",");
add(TokenID.SYMBOL_COLON, ":");
add(TokenID.SYMBOL_SEMICOLON, ";");
// math
add(TokenID.SYMBOL_PLUS, "+");
add(TokenID.SYMBOL_MINUS, "-");
add(TokenID.SYMBOL_MULTIPLY, "*");
add(TokenID.SYMBOL_DIVIDE, "/");
add(TokenID.SYMBOL_MODULO, "%");
add(TokenID.SYMBOL_INCREMENT, "++", "+");
add(TokenID.SYMBOL_DECREMENT, "--", "-");
// bitwise
add(TokenID.SYMBOL_BITWISE_AND, "&");
add(TokenID.SYMBOL_BITWISE_OR, "|");
add(TokenID.SYMBOL_BITWISE_NOT, "~");
add(TokenID.SYMBOL_BITWISE_XOR, "^");
// shift
add(TokenID.SYMBOL_LOGICAL_LEFT_SHIFT, "<<");
add(TokenID.SYMBOL_ARITHMETIC_RIGHT_SHIFT, ">>");
add(TokenID.SYMBOL_LOGICAL_RIGHT_SHIFT, ">>>");
// boolean
add(TokenID.SYMBOL_BOOLEAN_NOT, "!");
add(TokenID.SYMBOL_BOOLEAN_AND, "&&");
add(TokenID.SYMBOL_BOOLEAN_OR, "||");
// comparison
add(TokenID.SYMBOL_LESSER, "<");
add(TokenID.SYMBOL_GREATER, ">");
add(TokenID.SYMBOL_GREATER_OR_EQUAL, ">=");
add(TokenID.SYMBOL_LESSER_OR_EQUAL, "<=");
add(TokenID.SYMBOL_EQUAL, "==");
add(TokenID.SYMBOL_NOT_EQUAL, "!=");
// assignment
add(TokenID.SYMBOL_ASSIGN, "=");
add(TokenID.SYMBOL_ADD_ASSIGN, "+=", "+");
add(TokenID.SYMBOL_SUBTRACT_ASSIGN, "-=", "-");
add(TokenID.SYMBOL_MULTIPLY_ASSIGN, "*=", "*");
add(TokenID.SYMBOL_DIVIDE_ASSIGN, "/=", "/");
add(TokenID.SYMBOL_REMAINDER_ASSIGN, "%=", "%");
add(TokenID.SYMBOL_BITWISE_AND_ASSIGN, "&=", "&");
add(TokenID.SYMBOL_BITWISE_OR_ASSIGN, "|=", "|");
add(TokenID.SYMBOL_BITWISE_XOR_ASSIGN, "^=", "^");
add(TokenID.SYMBOL_LOGICAL_LEFT_SHIFT_ASSIGN, "<<=", "<<");
add(TokenID.SYMBOL_ARITHMETIC_RIGHT_SHIFT_ASSIGN, ">>=", ">>");
add(TokenID.SYMBOL_LOGICAL_RIGHT_SHIFT_ASSIGN, ">>>=", ">>>");
// enclosing
add(TokenID.SYMBOL_OPEN_PARENTHESIS, "(");
add(TokenID.SYMBOL_CLOSE_PARENTHESIS, ")");
add(TokenID.SYMBOL_OPEN_BRACKET, "[");
add(TokenID.SYMBOL_CLOSE_BRACKET, "]");
add(TokenID.SYMBOL_OPEN_BRACE, "{");
add(TokenID.SYMBOL_CLOSE_BRACE, "}");
// comment
add(TokenID.SYMBOL_DOUBLE_SLASH, "//");
add(TokenID.SYMBOL_SLASH_STAR, "/*");
add(TokenID.SYMBOL_STAR_SLASH, "*/");
// other
add(TokenID.SYMBOL_QUESTION_MARK, "?");
add(TokenID.SYMBOL_DOUBLE_PERIOD, "..");
add(TokenID.SYMBOL_TRIPLE_PERIOD, "...");
add(TokenID.SYMBOL_DOUBLE_COLON, "::");
add(TokenID.SYMBOL_ARROW, "->");
add(TokenID.SYMBOL_AT, "@");
}
private Symbol(Symbol token, int index) {
this(token.getID(), token.getSource(), index, token.getCompoundAssignOperator());
}
private Symbol(TokenID id, String source, int index, Symbol compoundAssignOperator) {
super(id, source, index);
this.compoundAssignOperator = compoundAssignOperator;
}
public Symbol getCompoundAssignOperator() {
return compoundAssignOperator;
}
public static boolean is(char source) {
return CHAR_SYMBOLS[source] != null;
}
public static boolean is(String source) {
if (source.length() == 1) {
return is(source.charAt(0));
}
return SYMBOLS.containsKey(source);
}
public static Symbol from(char source, int index) {
final Symbol symbol = CHAR_SYMBOLS[source];
return symbol == null ? null : new Symbol(symbol, index);
}
public static Symbol from(String source, int index) {
if (source.length() == 1) {
return from(source.charAt(0), index);
}
final Symbol symbol = SYMBOLS.get(source);
return symbol == null ? null : new Symbol(symbol, index);
}
public static Collection<Symbol> all() {
return Collections.unmodifiableCollection(SYMBOLS.values());
}
private static void add(TokenID id, String source) {
add(id, source, null);
}
private static void add(TokenID id, String source, String compoundAssignOperator) {
final Symbol symbol = new Symbol(id, source, 0, SYMBOLS.get(compoundAssignOperator));
SYMBOLS.put(source, symbol);
if (source.length() == 1) {
CHAR_SYMBOLS[source.charAt(0)] = symbol;
}
}
}
| 39.358974
| 93
| 0.636156
|
fe1dcf083b7214165ebc38616858fcfce42f2448
| 352
|
package gnu.kawa.format;
import gnu.lists.Consumer;
public interface Printable
{
// Tempting to do: void print (Appendable out);
// in the JAVA5 case. However, then we have to deal
// with the complication that the append methods
// in Appendable are specified as 'throws IOException'.
// Sigh. Maybe later.
void print (Consumer out);
}
| 27.076923
| 57
| 0.71875
|
8965c2b7baab9559cfc99c4398ed781effeaf05e
| 572
|
package org.walkframework.batis.bean;
import org.apache.ibatis.executor.BatchExecutor;
/**
* @author shf675
*
*/
public class Batch {
private BatchExecutor batchExecutor;
private int counter;
public Batch(int counter){
this.counter = counter;
}
public BatchExecutor getBatchExecutor() {
return batchExecutor;
}
public int getCounter() {
if(counter > 0){
counter = counter - 1;
}
return counter;
}
public void setBatchExecutor(BatchExecutor batchExecutor) {
this.batchExecutor = batchExecutor;
}
}
| 16.342857
| 61
| 0.671329
|
456b25bb5e0ebd128b0ad42c03d7fa709543c694
| 890
|
package edu.fiuba.algo3.tp2N10.Modelo.Pregunta;
import edu.fiuba.algo3.tp2N10.Modelo.Respuesta.RespuestaOrderedChoice;
import java.util.List;
public class PreguntaOrderedChoice extends Pregunta {
public PreguntaOrderedChoice(String enunciado, List<String> opciones, List<Integer> ordenCorrecto) {
this.enunciado = enunciado;
this.opciones = opciones;
respuestaCorrecta = new RespuestaOrderedChoice(ordenCorrecto);
tipoPregunta = "Ordered Choice";
respuestaCorrectaFormateada = parsearRespuesta(ordenCorrecto);
}
private String parsearRespuesta(List<Integer> ordenCorrecto) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < opciones.size(); i++) {
builder.append(String.format("%d - %s\n", i + 1, opciones.get(ordenCorrecto.get(i))));
}
return builder.toString();
}
}
| 34.230769
| 104
| 0.695506
|
b6f10cd36c19215cdcbde987dda21a6f5c12eb4b
| 3,168
|
package dao.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
@Entity
public class Chirurgie implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id_Chirg;
private String refAnaPath;
@Temporal(javax.persistence.TemporalType.DATE)
private Date date;
private String service;
private int temps;
private int numDossier;
@OneToOne
private TypeExerese type;
@OneToOne
private Elargissement elargie;
@OneToOne
private Geste geste;
@OneToOne
private RRscoring scoring;
@OneToOne
private Complication complication;
@OneToOne(mappedBy="chirurgie")
private Traitement traitement;
public Chirurgie() {
super();
}
public Chirurgie(String refAnaPath, Date date, String service, int temps, TypeExerese type, Elargissement elargie,
Geste geste, RRscoring scoring, Complication complication) {
super();
this.refAnaPath = refAnaPath;
this.date = date;
this.service = service;
this.temps = temps;
this.type = type;
this.elargie = elargie;
this.geste = geste;
this.scoring = scoring;
this.complication = complication;
}
public int getId() {
return id_Chirg;
}
public void setId(int id) {
this.id_Chirg = id;
}
public String getRefAnaPath() {
return refAnaPath;
}
public void setRefAnaPath(String refAnaPath) {
this.refAnaPath = refAnaPath;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public int getTemps() {
return temps;
}
public void setTemps(int temps) {
this.temps = temps;
}
public int getNumDossier() {
return numDossier;
}
public void setNumDossier(int numDossier) {
this.numDossier = numDossier;
}
public TypeExerese getType() {
return type;
}
public void setType(TypeExerese type) {
this.type = type;
}
public Elargissement getElargie() {
return elargie;
}
public void setElargie(Elargissement elargie) {
this.elargie = elargie;
}
public Geste getGeste() {
return geste;
}
public void setGeste(Geste geste) {
this.geste = geste;
}
public RRscoring getScoring() {
return scoring;
}
public void setScoring(RRscoring scoring) {
this.scoring = scoring;
}
public Complication getComplication() {
return complication;
}
public void setComplication(Complication complication) {
this.complication = complication;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id_Chirg;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Chirurgie other = (Chirurgie) obj;
if (id_Chirg != other.id_Chirg)
return false;
return true;
}
}
| 20.842105
| 115
| 0.720013
|
4f5860d88a3e67255ef030bc8b56466451bc7ee3
| 4,114
|
package com.mytools.classmodifier.processor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;
import com.mytools.classmodifier.ClassModifier;
import com.mytools.classmodifier.ConsoleViewer;
import com.mytools.classmodifier.Utility;
public class SaveProcessor {
/**
* @param args
*/
public static void addSaveAction() {
// TODO Auto-generated method stub
ClassModifier.save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
// TODO Auto-generated method stub
try {
ConsoleViewer.cleanConsole();
int chosenIndex = TabsProcessor.getCurrentIndex();
String fileName = TabsProcessor
.getToolTipText(chosenIndex);
if (!fileName.contains(".smali")
&& !fileName.contains(Utility.practiseFile)) {
JOptionPane.showMessageDialog(null,
"Only Smali files can be changed");
return null;
}
RTextScrollPane htmlScroll = TabsProcessor
.getComponent(chosenIndex);
RSyntaxTextArea htmlPane = (RSyntaxTextArea) htmlScroll
.getViewport().getView();
File modifiedClass;
if (fileName.contains("TestEnv.smali")) {
File rough = new File(Utility
.getRoughFolderPath());
Utility.deleteFile(rough);
rough.mkdirs();
if (Utility.className.equals("doNotDelete")) {
Utility.prepareProject();
}
Utility.writeFile(
Utility.getRoughFilePath(Utility.practiseSmaliFile),
htmlPane.getText());
Utility.processSmaliPractiseFiles(new File(
Utility.getRoughFilePath(Utility.practiseSmaliFile)));
TabsProcessor
.refreshPractiseTabs(Utility.practiseFile);
} else if (fileName.contains("TestEnv.java")) {
File rough = new File(Utility
.getRoughFolderPath());
Utility.deleteFile(rough);
rough.mkdirs();
if (Utility.className.equals("doNotDelete")) {
Utility.prepareProject();
}
Utility.writeFile(
Utility.getRoughFilePath(Utility.practiseFile),
htmlPane.getText());
Utility.compileFile(Utility.practiseFile,
new File(Utility.getRoughFolderPath()));
File output = Utility.findFile(
new File(Utility.getRoughFolderPath()),
".class");
Utility.processPractiseClassFiles(output);
TabsProcessor
.refreshPractiseTabs(Utility.practiseSmaliFile);
} else {
ConsoleViewer
.setText("Cleaning previously generated files...");
Utility.rebuildProject();
ConsoleViewer
.setText("Cleaned previously generated files...");
String smaliPath = Utility.getSmaliPath()
+ File.separator
+ Utility.className.replace(".class",
".smali");
Utility.writeFile(smaliPath, htmlPane.getText());
modifiedClass = Utility
.processSmaliFiles(new File(smaliPath));
Utility.processClassFiles(modifiedClass);
TabsProcessor.refreshTabs();
}
String title = TabsProcessor
.getToolTitle(chosenIndex);
if (!title.startsWith("\\*")) {
title = title.replaceFirst("\\*", "");
}
TabsProcessor.setTitle(chosenIndex, title);
JOptionPane.showMessageDialog(null,
"Convertion Successful");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
null,
"Issue while converting.Please retry "
+ e.getMessage());
}
return null;
}
};
worker.execute();
}
});
}
}
| 33.447154
| 69
| 0.624696
|
e4166c369b4caaaa6ec76e847c2ee7b1720c6ca6
| 1,644
|
package com.pog.generator.entity;
import lombok.Data;
import java.io.Serializable;
public class ColumnEntity implements Serializable {
// 每列的名字
private String columnName;
// 数据类型
private String dataType;
// 数据属性 eg: PRI UNI
private String columnKey;
// 列的注释
private String comment;
// 转化为java实例名 eg: user_name = UserName
private String entityName;
//转化为java实例名 eg: user_name = userName
private String entityname;
// 转化为java的类型
private String entityType;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getColumnKey() {
return columnKey;
}
public void setColumnKey(String columnKey) {
this.columnKey = columnKey;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public String getEntityname() {
return entityname;
}
public void setEntityname(String entityname) {
this.entityname = entityname;
}
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
}
| 20.04878
| 51
| 0.640511
|
3b52a2ae8cdc9b67d6dd45ece6c389b791a2a7cb
| 13,700
|
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2016-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file SystemPreferencesWindow.java
/// @author Maximiliano Bottazzi
/// @date 2016
///
//
/****************************************************************************/
package de.dlr.ts.lisum.gui.options;
import de.dlr.ts.commons.javafx.buttons.tools.FileChooserCombo;
import de.dlr.ts.commons.javafx.buttonspanels.OkCancelButtonsPanel;
import de.dlr.ts.commons.javafx.messages.ConfirmationMessage;
import de.dlr.ts.commons.logger.LogLevel;
import de.dlr.ts.lisum.Constants;
import de.dlr.ts.lisum.gui.GlobalConfig;
import de.dlr.ts.lisum.gui.Actions;
import de.dlr.ts.lisum.gui.MainProgram;
import de.dlr.ts.lisum.gui.SystemProperties;
import java.io.File;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author @author <a href="mailto:maximiliano.bottazzi@dlr.de">Maximiliano Bottazzi</a>
*/
public class SystemPreferencesWindow {
private final AnchorPane root = new AnchorPane();
private final OkCancelButtonsPanel okCancelButtons = new OkCancelButtonsPanel();
private final Button okButton = okCancelButtons.getOkButton();
private final ChangeListener<String> activateOkButton = (ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
okButton.setDisable(false);
};
private final Scene scene;
private Stage stage;
private final TabPane mainTabPane = new TabPane();
private FileChooserCombo sumoExecFileChooser;
private FileChooserCombo lisaServerFileChooser;
private FileChooserCombo textEditorFileChooserCombo;
private FileChooserCombo filesExplorerFileChooserCombo;
private FileChooserCombo workspaceFileChooserCombo;
private final Tab sumoTab = new Tab("Sumo");
private final Tab lisaTab = new Tab("Lisa+");
private final Tab generalTab = new Tab("General");
//private FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Exe files (*.exe)", "*.exe");
/**
*
*/
public SystemPreferencesWindow() {
okCancelButtons.getOkButton().setOnAction((ActionEvent event) -> saveAndClose());
okCancelButtons.getCancelButton().setOnAction((ActionEvent event) -> stage.close());
okButton.setDisable(true);
scene = new Scene(root, 600, 450);
/**
*
*/
stage = new Stage();
stage.initStyle(StageStyle.UTILITY);
stage.setTitle("System Preferencies");
stage.setScene(scene);
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(MainProgram.getInstance().getScene().getWindow());
stage.getIcons().add(SystemProperties.getInstance().getMainIcon());
stage.setResizable(false);
stage.addEventHandler(KeyEvent.KEY_PRESSED, (KeyEvent event) -> {
if (event.getCode() == KeyCode.ESCAPE)
stage.close();
});
/**
*
*/
AnchorPane.setTopAnchor(mainTabPane, 5.);
AnchorPane.setLeftAnchor(mainTabPane, 5.);
AnchorPane.setRightAnchor(mainTabPane, 5.);
AnchorPane.setBottomAnchor(mainTabPane, okCancelButtons.getHeight() + 10.);
generalTab();
sumoTab();
lisaTab();
}
/**
*
*/
private void save() {
GlobalConfig.getInstance().setTextEditor(textEditorFileChooserCombo.getTextField().getText());
GlobalConfig.getInstance().setSumoExec(sumoExecFileChooser.getTextField().getText());
GlobalConfig.getInstance().setLoggingLevel(logLevelComboBox.getValue());
GlobalConfig.getInstance().setLisaRestFulServerDir(lisaServerFileChooser.getTextField().getText());
GlobalConfig.getInstance().setWorkspace(workspaceFileChooserCombo.getTextField().getText());
GlobalConfig.getInstance().setFilesExplorer(filesExplorerFileChooserCombo.getTextField().getText());
GlobalConfig.getInstance().saveProps();
okButton.setDisable(true);
}
/**
*
*/
private void saveAndClose() {
save();
stage.close();
}
/**
*
*/
private void generalTab() {
AnchorPane generalAnchorPane = new AnchorPane();
generalTab.setContent(generalAnchorPane);
generalTab.setClosable(false);
Label logLevelLabel = new Label("Default log level:");
AnchorPane.setTopAnchor(logLevelLabel, 24.);
AnchorPane.setLeftAnchor(logLevelLabel, 5.);
logLevelLabel.setFont(Font.font(10));
AnchorPane.setTopAnchor(logLevelComboBox, 20.);
AnchorPane.setLeftAnchor(logLevelComboBox, 105.);
logLevelComboBox.setValue(GlobalConfig.getInstance().getLoggingLevel());
logLevelComboBox.valueProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
okButton.setDisable(false);
});
/**
*
*/
textEditorFileChooserCombo = new FileChooserCombo("Text Editor:", new File("."), stage.getOwner());
Node textEditorNode = textEditorFileChooserCombo.getNode();
AnchorPane.setTopAnchor(textEditorNode, 55.);
AnchorPane.setLeftAnchor(textEditorNode, 5.);
textEditorFileChooserCombo.setDefaultValue(GlobalConfig.getInstance().getDefaultTextEditor());
textEditorFileChooserCombo.getTextField().setText(GlobalConfig.getInstance().getTextEditor());
textEditorFileChooserCombo.getTextField().textProperty().addListener(activateOkButton);
//textEditorFileChooserCombo.getFileChooser().setSelectedExtensionFilter(filter);
textEditorFileChooserCombo.setTextFieldWidth(330.);
textEditorFileChooserCombo.setFontSize(10);
/**
*
*/
filesExplorerFileChooserCombo = new FileChooserCombo("Files explorer: ", new File("."), stage.getOwner());
Node filesExplorerNode = filesExplorerFileChooserCombo.getNode();
AnchorPane.setTopAnchor(filesExplorerNode, 88.);
AnchorPane.setLeftAnchor(filesExplorerNode, 5.);
filesExplorerFileChooserCombo.setDefaultValue(GlobalConfig.getInstance().getDefaultFilesExplorer());
filesExplorerFileChooserCombo.getTextField().setText(GlobalConfig.getInstance().getFilesExplorer());
filesExplorerFileChooserCombo.getTextField().textProperty().addListener(activateOkButton);
filesExplorerFileChooserCombo.setTextFieldWidth(330.);
filesExplorerFileChooserCombo.setFontSize(10);
/**
*
*/
workspaceFileChooserCombo = new FileChooserCombo("Workspace:",
new File(GlobalConfig.getInstance().getWorkspace()), stage.getOwner());
Node simuNode = workspaceFileChooserCombo.getNode();
AnchorPane.setTopAnchor(simuNode, 121.);
AnchorPane.setLeftAnchor(simuNode, 5.);
workspaceFileChooserCombo.getTextField().setText(WorkspaceWindow.getWorkspace().getAbsolutePath());
workspaceFileChooserCombo.getTextField().setDisable(true);
workspaceFileChooserCombo.getTextField().setStyle("-fx-opacity: 0.8;");
workspaceFileChooserCombo.setTextFieldWidth(330.);
workspaceFileChooserCombo.enableDefaultButton(false);
workspaceFileChooserCombo.getBrowseButton().setText("Switch");
workspaceFileChooserCombo.setFontSize(10);
workspaceFileChooserCombo.getBrowseButton().setOnAction((ActionEvent event) -> {
if (!okButton.isDisabled()) {
ConfirmationMessage cm = new ConfirmationMessage("");
cm.setHeader("Save changes before proceeding?");
if (cm.showAndWait().get() == ButtonType.OK) {
save();
}
}
boolean switchWorkspace = Actions.getInstance().switchWorkspace();
if (switchWorkspace)
stage.close();
});
/**
*
*/
Button switchWorkspaceButton = new Button("Switch workspace");
AnchorPane.setBottomAnchor(switchWorkspaceButton, 5.);
AnchorPane.setRightAnchor(switchWorkspaceButton, 5.);
switchWorkspaceButton.setOnAction((ActionEvent event) -> {
boolean switchWorkspace = Actions.getInstance().switchWorkspace();
if (switchWorkspace)
stage.close();
});
generalAnchorPane.getChildren().addAll(/*logLevelLabel, logLevelComboBox,*/ textEditorNode,
filesExplorerNode, simuNode);
mainTabPane.getTabs().addAll(generalTab);
}
/**
*
*/
private void sumoTab() {
AnchorPane sumoAnchorPane = new AnchorPane();
sumoTab.setContent(sumoAnchorPane);
sumoTab.setClosable(false);
/**
*
*/
sumoExecFileChooser = new FileChooserCombo("SumoGUI exec:", new File("."), stage.getOwner());
Node sumoExecNode = sumoExecFileChooser.getNode();
AnchorPane.setTopAnchor(sumoExecNode, 20.);
AnchorPane.setLeftAnchor(sumoExecNode, 5.);
sumoExecFileChooser.setFontSize(10);
sumoAnchorPane.getChildren().add(sumoExecNode);
sumoExecFileChooser.setDefaultValue("");
sumoExecFileChooser.getTextField().setText(GlobalConfig.getInstance().getSumoExec());
sumoExecFileChooser.getTextField().textProperty().addListener(activateOkButton);
//sumoExecFileChooser.getFileChooser().setSelectedExtensionFilter(filter);
sumoExecFileChooser.enableDefaultButton(false);
sumoExecFileChooser.setTextFieldWidth(330.);
mainTabPane.getTabs().addAll(sumoTab);
}
/**
*
*/
private void lisaTab() {
AnchorPane lisaAnchorPane = new AnchorPane();
lisaTab.setContent(lisaAnchorPane);
lisaTab.setClosable(false);
lisaServerFileChooser = new FileChooserCombo("LISA+ RestFUL Server folder:", new File("."), stage.getOwner());
Node node = lisaServerFileChooser.getNode();
AnchorPane.setTopAnchor(node, 20.);
AnchorPane.setLeftAnchor(node, 5.);
lisaServerFileChooser.setDefaultValue(GlobalConfig.getInstance().getDefaultLisaRestFulServerDir());
lisaServerFileChooser.getTextField().setText(GlobalConfig.getInstance().getLisaRESTfulServerPath());
lisaServerFileChooser.getTextField().textProperty().addListener(activateOkButton);
lisaServerFileChooser.setLabelWidth(165);
lisaServerFileChooser.setDirectoryChooser(true);
lisaServerFileChooser.setFontSize(10);
Label warningLabel = new Label("System restart required!");
warningLabel.setTextFill(Color.RED);
AnchorPane.setTopAnchor(warningLabel, 50.);
AnchorPane.setLeftAnchor(warningLabel, 180.);
warningLabel.setVisible(false);
lisaServerFileChooser.getTextField().textProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
String lisaRestFulServerDir = GlobalConfig.getInstance().getLisaRESTfulServerPath();
if (!lisaServerFileChooser.getTextField().getText().equals(lisaRestFulServerDir))
warningLabel.setVisible(true);
else {
warningLabel.setVisible(false);
}
});
lisaAnchorPane.getChildren().addAll(node, warningLabel);
mainTabPane.getTabs().addAll(lisaTab);
}
/**
*
* @param tabIndex
*/
public void show(int tabIndex) {
Node okCancelNode = okCancelButtons.getNode();
AnchorPane.setBottomAnchor(okCancelNode, 0.);
AnchorPane.setLeftAnchor(okCancelNode, 0.);
AnchorPane.setRightAnchor(okCancelNode, 0.);
root.getChildren().addAll(okCancelNode, mainTabPane);
mainTabPane.getSelectionModel().select(tabIndex);
stage.show();
}
/**
*
*/
private final ComboBox<String> logLevelComboBox = new ComboBox<>();
{
for (LogLevel value : LogLevel.values()) {
logLevelComboBox.getItems().add(value.name());
}
logLevelComboBox.setEditable(false);
logLevelComboBox.setValue(Constants.DEFAULT_LOG_LEVEL);
logLevelComboBox.setTooltip(new Tooltip("Log level"));
}
}
| 39.941691
| 157
| 0.677007
|
8df625e74faf236e7a212ff5d0287b7f572c14f4
| 3,108
|
package ru.stqa.pft.addressbook.tests;
import com.thoughtworks.xstream.XStream;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.AddData;
import ru.stqa.pft.addressbook.model.Contacts;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class CreateNewUserTest extends TestBase {
// @DataProvider
// public Iterator<Object[]> validContact(){
//List<Object[]> list = new ArrayList<Object[]>();
//File photo = new File("src/test/resources/panda.png");
//list.add(new Object[] { new AddData().withFerstname("FerstName 1").withLastName("LastName 1").withEmail1("Email1 1").withGroup("test1").withPhoto(photo)});
//list.add(new Object[] { new AddData().withFerstname("FerstName 2").withLastName("LastName 2").withEmail1("Email1 2").withGroup("test1").withPhoto(photo)});
//list.add(new Object[] { new AddData().withFerstname("FerstName 3").withLastName("LastName 3").withEmail1("Email1 3").withGroup("test1").withPhoto(photo)});
//return list.iterator();
// }
@DataProvider
public Iterator<Object[]> validContact() throws IOException {
//public Iterator<Object[]> validGroups() throws IOException {
//List<Object[]> list = new ArrayList<Object[]>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/contacts.xml")))){
String xml = "";
String line = reader.readLine();
while (line != null) {
xml += line;
line = reader.readLine();
}
XStream xstream = new XStream();
xstream.processAnnotations(AddData.class);
List<AddData> contacts = (List<AddData>) xstream.fromXML(xml);
return contacts.stream().map((g) -> new Object[]{g}).collect(Collectors.toList()).iterator();
}
}
@Test (dataProvider = "validContact")
public void testCreateNewUser(AddData contact) throws Exception {
// File photo = new File("src/test/resources/panda.png");
//AddData newContact = new AddData().withFerstname("Анна").withLastName("lastname").withEmail1("email1")
//.inGroup(groups.iterator().next());
app.goTo().HomePage();
Contacts before = app.db().contacts();
app.contact().create(contact);
Contacts after = app.db().contacts();
assertThat(after.size(), equalTo(before.size() + 1));
assertThat(after, equalTo(before
.withAdded(contact.withId(after.stream().mapToInt((g)->g.getId()).max().getAsInt()))));
verifyContactListInUI();
}
@Test (enabled = false)
public void testCurrentDir (){
File currentDir = new File(".");
System.out.println(currentDir.getAbsolutePath());
File photo = new File("src/test/resources/panda.png");
System.out.println(photo.getAbsolutePath());
System.out.println(photo.exists());
}
}
| 38.85
| 161
| 0.682432
|
12783cb4939c7ce59cc6c3d9c3e85bba048d2438
| 3,463
|
/*
* Copyright (c) 2016 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.prism;
import static org.assertj.core.api.Assertions.assertThat;
import static com.evolveum.midpoint.prism.PrismInternalTestUtil.*;
import javax.xml.namespace.QName;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.evolveum.midpoint.prism.foo.AssignmentType;
import com.evolveum.midpoint.prism.foo.UserType;
import com.evolveum.midpoint.util.PrettyPrinter;
/**
* @author semancik
*/
public class TestPerformance extends AbstractPrismTest {
private static final int ITERATIONS = 10_000;
private static final double NANOS_TO_MILLIS_DOUBLE = 1_000_000d;
@BeforeSuite
public void initPrismContext() {
PrettyPrinter.setDefaultNamespacePrefix(DEFAULT_NAMESPACE_PREFIX);
}
/**
* Construct object with schema. Starts by instantiating a definition and working downwards.
* All the items in the object should have proper definition.
*/
@Test
public void testPerfContainerNewValue() throws Exception {
// GIVEN
PrismContext ctx = constructInitializedPrismContext();
PrismObjectDefinition<UserType> userDefinition = getFooSchema(ctx).findObjectDefinitionByElementName(new QName(NS_FOO, "user"));
PrismObject<UserType> user = userDefinition.instantiate();
PrismContainer<AssignmentType> assignmentContainer = user.findOrCreateContainer(UserType.F_ASSIGNMENT);
PerfRecorder recorderCreateNewValue = new PerfRecorder("createNewValue");
PerfRecorder recorderFindOrCreateProperty = new PerfRecorder("findOrCreateProperty");
PerfRecorder recorderSetRealValue = new PerfRecorder("setRealValue");
// WHEN
for (int i = 0; i < ITERATIONS; i++) {
long tsStart = System.nanoTime();
PrismContainerValue<AssignmentType> newValue = assignmentContainer.createNewValue();
long ts1 = System.nanoTime();
PrismProperty<String> descriptionProperty = newValue.findOrCreateProperty(AssignmentType.F_DESCRIPTION);
long ts2 = System.nanoTime();
descriptionProperty.setRealValue("ass " + i);
long tsEnd = System.nanoTime();
recorderCreateNewValue.record(i, (ts1 - tsStart) / NANOS_TO_MILLIS_DOUBLE);
recorderFindOrCreateProperty.record(i, (ts2 - ts1) / NANOS_TO_MILLIS_DOUBLE);
recorderSetRealValue.record(i, (tsEnd - ts2) / NANOS_TO_MILLIS_DOUBLE);
System.out.println("Run " + i + ": total " + ((tsEnd - tsStart) / NANOS_TO_MILLIS_DOUBLE) + "ms");
}
// THEN
System.out.println(recorderCreateNewValue.dump());
System.out.println(recorderFindOrCreateProperty.dump());
System.out.println(recorderCreateNewValue.dump());
// Do not assert maximum here. The maximum values may jump around
// quite wildly (e.g. because of garbage collector runs?)
recorderCreateNewValue.assertAverageBelow(0.05d);
recorderFindOrCreateProperty.assertAverageBelow(0.1d);
recorderCreateNewValue.assertAverageBelow(0.05d);
assertThat(assignmentContainer.size()).isEqualTo(ITERATIONS);
// we skip the 20k-line dump, it's heavy on some (*cough*Windows) consoles and crashes JVM
}
}
| 38.910112
| 136
| 0.713832
|
63b14367ba49b0c683d733558b2d651a5ffb84ed
| 1,159
|
/*
* Copyright 2014 Daniel Kurka
*
* 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.googlecode.mgwt.dom.client.event.touch;
import com.google.gwt.dom.client.Touch;
public class TouchCopy {
public static TouchCopy copy(Touch touch) {
return new TouchCopy(touch.getPageX(), touch.getPageY(), touch.getIdentifier());
}
private final int x;
private final int y;
private final int id;
public TouchCopy(int x, int y, int id) {
this.x = x;
this.y = y;
this.id = id;
}
public int getPageX() {
return x;
}
public int getPageY() {
return y;
}
public int getIdentifier() {
return id;
}
}
| 24.145833
| 84
| 0.69629
|
8ef859b9ce85da282f37ce49f0062df845e904a8
| 184
|
package cn.byk.pandora.sample.base;
import cn.byk.pandora.libs.base.BaseActivity;
/**
* Created by Byk on 2018/8/20.
**/
public abstract class AppActivity extends BaseActivity {
}
| 18.4
| 56
| 0.744565
|
e0153638477de068aa6462c2b40366583cf28c79
| 2,545
|
/*
* 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.streampipes.model.schema;
import org.streampipes.empire.annotations.RdfProperty;
import org.streampipes.empire.annotations.RdfsClass;
import org.apache.streampipes.vocabulary.RDFS;
import org.apache.streampipes.vocabulary.SO;
import org.apache.streampipes.vocabulary.StreamPipes;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
@RdfsClass(SO.Enumeration)
@Entity
public class Enumeration extends ValueSpecification {
private static final long serialVersionUID = 1L;
@RdfProperty(RDFS.LABEL)
private String label;
@RdfProperty(RDFS.DESCRIPTION)
private String description;
@OneToMany(fetch = FetchType.EAGER,
cascade = {CascadeType.ALL})
@RdfProperty(StreamPipes.HAS_RUNTIME_VALUE)
private List<String> runtimeValues;
public Enumeration() {
super();
}
public Enumeration(String label, String description, List<String> runtimeValues) {
super();
this.label = label;
this.description = description;
this.runtimeValues = runtimeValues;
}
public Enumeration(Enumeration other) {
super(other);
this.label = other.getLabel();
this.description = other.getDescription();
this.runtimeValues = other.getRuntimeValues();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getRuntimeValues() {
return runtimeValues;
}
public void setRuntimeValues(List<String> runtimeValues) {
this.runtimeValues = runtimeValues;
}
}
| 26.510417
| 83
| 0.763065
|
013469360d2eab08192e4f6b7ad77e9b55f4e658
| 200
|
package com.cloudTop.starshare.ui.wangyi.main.reminder;
public class ReminderId {
final static public int INVALID = -1;
final static public int SESSION = 0;
final static public int CONTACT = 1;
}
| 25
| 55
| 0.76
|
d38ecf97e023760628fcfa91d3e3d5c33581855c
| 6,448
|
/*
* Copyright 2016-2019 Tim Boudreau, Frédéric Yvon Vinet
*
* 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.nemesis.jfs.javac;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import org.nemesis.jfs.JFSFileObject;
/**
* Wrapper for Javac's Diagnostic class, to avoid holding references to any
* objects from a compile that could keep the compile trees in memory.
*
* @author Tim Boudreau
*/
public final class JavacDiagnostic {
private final String path;
private final String sourceCode;
private final Diagnostic.Kind kind;
private final long lineNumber;
private final long columnNumber;
private final long position;
private final long endPosition;
private final String message;
private final Path relativePath;
JavacDiagnostic(String path, String sourceCode, Diagnostic.Kind kind, long lineNumber, long columnNumber, long position, long endPosition, String message, Path sourceRoot) {
this.path = path;
this.sourceCode = sourceCode;
this.kind = kind;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.position = position;
this.endPosition = endPosition;
this.message = message;
this.relativePath = sourceRoot.relativize(Paths.get(path));
}
public static JavacDiagnostic create(String sourcePath, Path sourceRoot, Diagnostic<? extends JavaFileObject> diag) {
return new JavacDiagnostic(sourcePath, diag.getCode(), diag.getKind(), diag.getLineNumber(),
diag.getColumnNumber(), diag.getPosition(), diag.getEndPosition(),
diag.getMessage(Locale.getDefault()), sourceRoot);
}
public String context(JFSFileObject fo) {
StringBuilder sb = new StringBuilder();
try {
CharSequence txt = fo.getCharContent(true);
int nlcount = 0;
for (int start = (int) position; start >= 0 && start < txt.length(); start--) {
char c = txt.charAt(start);
if (c == '\n') {
if (++nlcount >= 2) {
break;
}
}
sb.insert(0, c);
}
int tail;
for (tail = (int) position + 1; tail >= 0 && tail < txt.length(); tail++) {
char c = txt.charAt(tail);
if (c == '\n') {
break;
}
sb.append(c);
}
if (sb.length() > 0) {
int len = (int) (columnNumber + (endPosition - position));
if (len > 0) {
char[] c = new char[len];
Arrays.fill(c, 0, (int) columnNumber, ' ');
Arrays.fill(c, (int) columnNumber, c.length, '^');
sb.append('\n').append(c);
}
for (int i = tail; i >= 0 && i < txt.length(); i++) {
sb.append(txt.charAt(i));
if (txt.charAt(i) == '\n') {
break;
}
}
}
} catch (IOException ex) {
Logger.getLogger(JavacDiagnostic.class.getName()).log(Level.INFO,
"File " + fo.path() + " may have been deleted before "
+ "trying to print diagnostics", ex);
}
return sb.toString();
}
@Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + Objects.hashCode(this.kind);
hash = 71 * hash + (int) (this.position ^ (this.position >>> 32));
hash = 71 * hash + (int) (this.endPosition ^ (this.endPosition >>> 32));
hash = 71 * hash + Objects.hashCode(this.message);
return hash;
}
public Throwable toThrowable() {
return new IOException(toString());
}
public String message() {
return message;
}
public String sourceCode() {
return sourceCode;
}
public Diagnostic.Kind kind() {
return kind;
}
public long lineNumber() {
return lineNumber;
}
public long columnNumber() {
return columnNumber;
}
public long position() {
return position;
}
public long endPosition() {
return endPosition;
}
public Path sourceRootRelativePath() {
return relativePath;
}
public Path sourcePath() {
return Paths.get(path);
}
@Override
public String toString() {
return kind.name().toLowerCase() + ": " + path
+ "(" + lineNumber + ":" + columnNumber + "/" + position + ":"
+ endPosition + ") " + message + "\n"
+ sourceCode;
}
public boolean isError() {
return kind == Diagnostic.Kind.ERROR;
}
public String fileName() {
int ix = path.lastIndexOf(File.separatorChar);
if (File.separatorChar != '/' && ix < 0) {
ix = path.lastIndexOf('/');
}
if (ix > 0 && ix < path.length() - 1) {
return path.substring(ix + 1);
}
return path;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (o == this) {
return true;
} else if (o instanceof JavacDiagnostic) {
JavacDiagnostic other = (JavacDiagnostic) o;
return kind == other.kind && position == other.position
&& endPosition == other.endPosition && fileName().equals(
other.fileName()) && Objects.equals(message, other.message);
}
return false;
}
}
| 32.24
| 177
| 0.560639
|
07d2caf6be4152ac9afe973e14e0d9074e3b47c8
| 1,371
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2012
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.index;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.MailConstants;
import com.zimbra.common.soap.Element;
import com.zimbra.common.util.ZimbraLog;
/**
* A {@link ZimbraHit} which is being proxied from another server: i.e. we did a SOAP request somewhere else and are now
* wrapping results we got from request.
*/
public final class ProxiedContactHit extends ProxiedHit {
/**
* @param sortValue - typically A_FILE_AS_STR rather than A_SORT_FIELD (the value for general ProxiedHits)
*/
public ProxiedContactHit(ZimbraQueryResultsImpl results, Element elt, String sortValue) {
super(results, elt, sortValue);
}
@Override
String getName() throws ServiceException {
return super.getElement().getAttribute(MailConstants.A_FILE_AS_STR);
}
}
| 33.439024
| 120
| 0.723559
|
02a75217cf30e80e3561f71fb69ae672cb10de3e
| 7,190
|
package com.example.neuralstyler;
import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import java.io.FileNotFoundException;
import java.io.InputStream;
@RequiresApi(api = Build.VERSION_CODES.M)
public class MainActivity extends AppCompatActivity {
ImageView inputImageView;
ImageButton takePhotoButton;
ImageButton loadPhotoButton;
ImageButton stylizePhotoButton;
private final String loggerTag = "MainActivityLogger";
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
// settings toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// main image display
inputImageView = findViewById(R.id.mainImageView);
// load controls
takePhotoButton = findViewById(R.id.takePhotoButton);
loadPhotoButton = findViewById(R.id.loadPhotoButton);
stylizePhotoButton = findViewById(R.id.runNeuralStylerButton);
// set listeners
takePhotoButton.setOnClickListener(takePhotoButtonOnClickListener);
loadPhotoButton.setOnClickListener(loadPhotoButtonOnClickListener);
stylizePhotoButton.setOnClickListener(stylizePhotoButtonOnClickListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/**
* Handle action bar item clicks here. The action bar will
* automatically handle clicks on the Home/Up button, so long
* as you specify a parent activity in AndroidManifest.xml.
*
* @param item Menu item clicked-on
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent enterSettingIntent = new Intent(this, SettingsActivity.class);
startActivity(enterSettingIntent);
return true;
}
if (id == R.id.action_add_style) {
Intent enterStyleManagementIntent = new Intent(this, StyleManagementActivity.class);
startActivity(enterStyleManagementIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Functions handling external camera to take pictures for inside the application
*/
private void startCameraActivityForResult() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(takePictureIntent, Const.REQUEST_IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
Log.e(loggerTag, "Error! Activity not found!" + e.toString());
}
}
/**
* Handles permissions and starts Camera Activity
*/
final View.OnClickListener takePhotoButtonOnClickListener = v -> {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
Log.w(loggerTag, "Permission not granted!");
requestPermissions(new String[]{ Manifest.permission.CAMERA }, Const.RESULT_OK);
}
startCameraActivityForResult();
};
/**
* Functions handling Android Gallery to select any picture
*/
private void startGalleryActivityForResult() {
Intent selectPhotoIntent = new Intent(Intent.ACTION_PICK);
selectPhotoIntent.setType(Const.imageIntentDataType);
try {
startActivityForResult(selectPhotoIntent, Const.RESULT_LOAD_IMG);
} catch (ActivityNotFoundException e) {
Log.e(loggerTag, "Error! Activity not found!" + e.toString());
}
}
/**
* Handles permissions and starts Gallery Activity
*/
final View.OnClickListener loadPhotoButtonOnClickListener = v -> {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Log.w(loggerTag, "Permission not granted!");
requestPermissions(new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE }, Const.RESULT_OK);
}
startGalleryActivityForResult();
};
/**
* Handles actions on Camera Activity result
*
* @param data Camera Intent with captured photo as extras
*/
final void onCameraResult(Intent data) {
Bitmap photo = (Bitmap) data.getExtras().get(Const.intentExtrasDataKey);
inputImageView.setImageBitmap(photo);
}
/**
* Handles actions on Gallery Activity result
*
* @param data Gallery Intent with chosen photo as extras
*/
final void onGalleryResult(Intent data) {
Uri imageUri = data.getData();
InputStream imageStream = null;
try { // try load image from stream
imageStream = getContentResolver().openInputStream(imageUri);
} catch (FileNotFoundException e) {
Log.e(loggerTag, e.toString());
}
Bitmap photo = BitmapFactory.decodeStream(imageStream);
inputImageView.setImageBitmap(photo);
}
/**
* Handles actions on activity result
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Const.REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
onCameraResult(data);
}
if (requestCode == Const.RESULT_LOAD_IMG && resultCode == Activity.RESULT_OK) {
onGalleryResult(data);
}
}
/**
* Function starts NeuralStylerActivity
*/
final View.OnClickListener stylizePhotoButtonOnClickListener = v -> {
Intent neuralStylerIntent = new Intent(this, NeuralStylerActivity.class);
if (inputImageView.getDrawable() != null) {
Bitmap photo = Utils.getBitmapFromImageView(inputImageView);
String fileName = Utils.savePhotoToFile(photo, context);
neuralStylerIntent.putExtra(Const.imageIntentExtraLabel, fileName);
startActivity(neuralStylerIntent);
} else {
Toast.makeText(context, "Load Image First!", Toast.LENGTH_LONG).show();
}
};
}
| 34.7343
| 134
| 0.687065
|
a23c529be0a0a47ed66d245e106e2886493a66de
| 17,953
|
/* ***** BEGIN LICENSE BLOCK *****
Version: Apache 2.0/GPL 3.0/LGPL 3.0
CCT - Computational Chemistry Tools
Jamberoo - Java Molecules Editor
Copyright 2008-2015 Dr. Vladislav Vasilyev
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.
Contributor(s):
Dr. Vladislav Vasilyev <vvv900@gmail.com> (original author)
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the Apache 2.0, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the Apache 2.0, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package cct.vasp;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import cct.interfaces.AtomInterface;
import cct.interfaces.MoleculeInterface;
import cct.modelling.ChemicalElements;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: ANU</p>
*
* @author Dr. V. Vasilyev
* @version 1.0
*/
public class Vasp {
static final int CARTESIAN_COORDINATES = 0;
static final int DIRECT_COORDINATES = 1;
static int colorMap[][] = {
{
227, 38, 54}, { // 0.8900 0.1500 0.2100 alizarin_crimson
240, 248, 255}, { // 0.9412 0.9725 1.0000 alice_blue
127, 255, 0}, { // 0.4980 1.0000 0.0000 chartreuse
127, 255, 212}, { // 0.4980 1.0000 0.8314 aquamarine
255, 97, 3}, // 1.0000 0.3800 0.0100 cadmium_orange
{
156, 102, 31}, { // 0.6100 0.4000 0.1200 brick
0, 0, 255}, { // 0.0000 0.0000 1.0000 blue
102, 128, 20}, { // 0.4000 0.5000 0.0800 chromeoxidegreen
102, 205, 170}, { // 0.4000 0.8039 0.6667 aquamarinemedium
255, 3, 13}, // 1.0000 0.0100 0.0500 cadmium_red_light
{
227, 23, 13}, { // 0.8900 0.0900 0.0500 cadmium_red_deep
173, 216, 230}, { // 0.6784 0.8471 0.9020 blue_light
97, 179, 41}, { // 0.3800 0.7000 0.1600 cinnabar_green
0, 255, 255}, { // 0.0000 1.0000 1.0000 cyan
237, 145, 33} // 0.9300 0.5700 0.1300 carrot
};
String Comment = "";
float latticeConstant = 1.0f;
float latticeVectors[][] = new float[3][3];
int[] atomicSpecies = null;
int numberOfAtoms = 0;
boolean selectiveDynamicsSwitch = false;
String selectiveDynamicsKey = "";
String coordinatesKey = "";
VaspAtom[] Atoms = null;
int atomicPositionsType = CARTESIAN_COORDINATES;
List<String> potcarAtomSymbols = null;
List<Integer> potcarAtomNumbers = null;
static final Logger logger = Logger.getLogger(Vasp.class.getCanonicalName());
public Vasp() {
}
public int getNumberOfAtoms() {
return this.numberOfAtoms;
}
public float[][] getLatticeVectors() {
return latticeVectors;
}
public void parsePoscar(String filename, int fileType) throws Exception {
String line;
StringTokenizer st;
BufferedReader in = null;
if (fileType == 0) { // Read from file
try {
in = new BufferedReader(new FileReader(filename));
}
catch (java.io.FileNotFoundException e) {
throw new Exception("Error opening file " + filename + ": " + e.getMessage());
}
}
else if (fileType == 1) { // Read from String
in = new BufferedReader(new StringReader(filename));
}
else {
throw new Exception("Implementation error: unknown file type");
}
try {
// --- 1st line
if ( (line = in.readLine()) == null) {
throw new Exception("Error reading file " + filename + ": unexpected end of file while reading comment");
}
Comment = line.trim();
// --- 2nd line - lattice constant
// If this value is negative it is interpreted as the total volume of the cell
if ( (line = in.readLine()) == null) {
throw new Exception("Error reading file " + filename + ": unexpected end of file while reading lattice constant");
}
st = new StringTokenizer(line, " \t");
if (st.countTokens() < 1) {
throw new Exception("Error reading file " + filename + ": expecting lattice constant, got blank line");
}
try {
latticeConstant = Float.parseFloat(st.nextToken());
}
catch (Exception ex) {
throw new Exception("Error reading file " + filename + ": error parsing lattice constant: " + ex.getMessage());
}
// --- 3-5 lines - lattice vectors
// On the following three lines the three lattice vectors defining
// the unit cell of the system are given (first line corresponding to
// the first lattice vector, second to the second, and third to the third).
for (int i = 0; i < 3; i++) {
if ( (line = in.readLine()) == null) {
throw new Exception("Error reading file " + filename + ": unexpected end of file while reading lattice vectors");
}
st = new StringTokenizer(line, " \t");
if (st.countTokens() < 3) {
throw new Exception("Error reading file " + filename + ": expecting at least three numbers for lattice vector, got " +
st.countTokens() + " numbers");
}
for (int j = 0; j < 3; j++) {
try {
latticeVectors[i][j] = Float.parseFloat(st.nextToken()) * latticeConstant;
}
catch (Exception ex) {
throw new Exception("Error reading file " + filename + ": error parsing lattice vector value: " + ex.getMessage());
}
}
}
// --- 6th line
// The sixth line supplies the number of atoms per atomic species
// (one number for each atomic species). The ordering must be consistent with the POTCAR and the INCAR file.
if ( (line = in.readLine()) == null) {
throw new Exception("Error reading file " + filename +
": unexpected end of file while reading the number of atoms per atomic species");
}
st = new StringTokenizer(line, " \t");
if (st.countTokens() < 1) {
throw new Exception("Error reading file " + filename +
": expecting the number of atoms per atomic species, got blank line");
}
atomicSpecies = new int[st.countTokens()];
numberOfAtoms = 0;
for (int i = 0; i < atomicSpecies.length; i++) {
try {
atomicSpecies[i] = Integer.parseInt(st.nextToken());
numberOfAtoms += atomicSpecies[i];
}
catch (Exception ex) {
throw new Exception("Error reading file " + filename + ": error parsing the number of atoms per atomic species: " +
ex.getMessage());
}
}
// --- 7st line
if ( (line = in.readLine()) == null) {
throw new Exception("Error reading file " + filename + ": unexpected end of file while reading 7th line");
}
selectiveDynamicsKey = line.trim();
if (selectiveDynamicsKey.startsWith("S") || selectiveDynamicsKey.startsWith("s")) {
selectiveDynamicsSwitch = true;
if ( (line = in.readLine()) == null) {
throw new Exception("Error reading file " + filename + ": unexpected end of file while reading 8th line");
}
coordinatesKey = line.trim();
}
else {
selectiveDynamicsSwitch = false;
coordinatesKey = selectiveDynamicsKey;
selectiveDynamicsKey = "";
}
if (coordinatesKey.startsWith("C") || coordinatesKey.startsWith("c") || coordinatesKey.startsWith("K") ||
coordinatesKey.startsWith("k")) {
atomicPositionsType = CARTESIAN_COORDINATES;
}
else if (coordinatesKey.startsWith("D") || coordinatesKey.startsWith("d")) {
atomicPositionsType = DIRECT_COORDINATES;
}
else {
throw new Exception("Error reading file " + filename + ": unknown type of atom input coordinates" + coordinatesKey);
}
if (atomicPositionsType == CARTESIAN_COORDINATES) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
latticeVectors[i][j] *= latticeConstant;
}
}
}
// --- Start to read atomic coordinates
float x, y, z;
boolean[] lf = new boolean[3];
Atoms = new VaspAtom[numberOfAtoms];
int nat = 0;
for (int k = 0; k < atomicSpecies.length; k++) {
for (int i = 0; i < atomicSpecies[k]; i++, nat++) {
if ( (line = in.readLine()) == null) {
throw new Exception("Error reading file " + filename + ": unexpected end of file while reading " + (i + 1) +
" atom");
}
st = new StringTokenizer(line, " \t");
if (st.countTokens() < 3) {
throw new Exception("Error reading file " + filename +
": should be at least 3 numbers for atomic coordinates for " +
(i + 1) + " atom");
}
try {
x = Float.parseFloat(st.nextToken());
y = Float.parseFloat(st.nextToken());
z = Float.parseFloat(st.nextToken());
}
catch (Exception ex) {
throw new Exception("Error reading file " + filename + ": wrong number for atomic coordinate for " +
(i + 1) + " atom");
}
if (atomicPositionsType == CARTESIAN_COORDINATES) {
x *= latticeConstant;
y *= latticeConstant;
z *= latticeConstant;
}
else if (atomicPositionsType == DIRECT_COORDINATES) {
float x2 = 0, y2 = 0, z2 = 0;
x2 = x * latticeVectors[0][0] + y * latticeVectors[1][0] + z * latticeVectors[2][0];
y2 = x * latticeVectors[0][1] + y * latticeVectors[1][1] + z * latticeVectors[2][1];
z2 = x * latticeVectors[0][2] + y * latticeVectors[1][2] + z * latticeVectors[2][2];
x = x2;
y = y2;
z = z2;
}
if (st.countTokens() > 0 && st.countTokens() < 3) {
throw new Exception("Error reading file " + filename + ": should be at least 3 letters for logical flags for " +
(i + 1) + " atom");
}
lf[0] = lf[1] = lf[2] = false;
if (st.countTokens() > 0) {
for (int j = 0; j < 3; j++) {
String flag = st.nextToken();
if (flag.equalsIgnoreCase("T")) {
lf[j] = true;
}
else if (flag.equalsIgnoreCase("F")) {
lf[j] = false;
}
else {
throw new Exception("Error reading file " + filename + ": unknown logical flag for " +
(i + 1) + " atom");
}
}
}
Atoms[nat] = new VaspAtom(x, y, z, lf[0], lf[1], lf[2]);
Atoms[nat].species = k;
}
}
}
catch (IOException e) {
throw new Exception("Error reading file " + filename + ": " + e.getMessage());
}
}
public void parsePotcar(String filename, int fileType) throws Exception {
String line;
StringTokenizer st;
BufferedReader in = null;
if (fileType == 0) { // Read from file
try {
in = new BufferedReader(new FileReader(filename));
}
catch (java.io.FileNotFoundException e) {
throw new Exception("Error opening file " + filename + ": " + e.getMessage());
}
}
else if (fileType == 1) { // Read from String
in = new BufferedReader(new StringReader(filename));
}
else {
throw new Exception("Implementation error: unknown file type");
}
try {
while ( (line = in.readLine()) != null) {
// --- 1st line; header
boolean elementResoved = false;
st = new StringTokenizer(line, " \t");
// assume, that the first token is a type of a potential, and the second is element symbol
String element = null, potential = null;
if (st.countTokens() < 2 && st.countTokens() > 0) {
element = st.nextToken();
}
else {
potential = st.nextToken();
element = st.nextToken();
}
if (element != null && element.contains("_")) {
element = element.substring(0, element.indexOf("_"));
}
if (element != null) {
elementResoved = true;
}
// --- Read potential information
while ( (line = in.readLine()) != null) {
line = line.trim().toUpperCase();
if (line.equalsIgnoreCase("End of Dataset")) {
break;
}
if (line.startsWith("VRHFIN")) {
st = new StringTokenizer(line, " =:\t");
if (st.countTokens() > 1) {
st.nextToken();
String el = st.nextToken();
if (el.contains("_")) {
el = el.substring(0, el.indexOf("_"));
}
if (elementResoved) { // Check
if (!el.equalsIgnoreCase(element)) {
element = el;
logger.info("parsePotcar: Warning: element in VRHFIN " + el + " does not match element " +
element + " in header");
}
}
else {
element = el;
}
}
}
}
if (element != null) {
Integer atomNumber = ChemicalElements.getAtomicNumber(element);
if (potcarAtomSymbols == null) {
potcarAtomSymbols = new ArrayList<String> ();
potcarAtomNumbers = new ArrayList<Integer> ();
}
potcarAtomSymbols.add(element);
potcarAtomNumbers.add(atomNumber);
}
else {
System.err.println("parsePotcar: Warning: cannot resolve element after reading potential information...");
}
}
}
catch (IOException e) {
throw new Exception("Error reading file " + filename + ": " + e.getMessage());
}
}
public static void main(String[] args) {
Vasp vasp = new Vasp();
}
public void resolveAtomTypes() throws Exception {
if (atomicSpecies == null) {
throw new Exception("resolveAtomTypes: atomicSpecies == null");
}
else if (potcarAtomSymbols == null) {
throw new Exception("resolveAtomTypes: potcarAtomSymbols == null");
}
else if (atomicSpecies.length != potcarAtomSymbols.size()) {
throw new Exception("resolveAtomTypes: amount of atomic species is different in POSCAR and POTCAR files");
}
int nat = 0;
for (int i = 0; i < atomicSpecies.length; i++) {
String symbol = potcarAtomSymbols.get(i);
int element = potcarAtomNumbers.get(i);
for (int j = 0; j < atomicSpecies[i]; j++, nat++) {
Atoms[nat].element = element;
}
}
}
public void getMolecularInterface(MoleculeInterface molec) throws
Exception {
if (molec == null) {
throw new Exception(this.getClass().getCanonicalName() + " : molec == null");
}
if (Atoms == null || Atoms.length < 1) {
throw new Exception(this.getClass().getCanonicalName() + " : no VASP atoms");
}
molec.addMonomer("VASP");
boolean typesNotSet = false;
for (int i = 0; i < Atoms.length; i++) {
AtomInterface atom = molec.getNewAtomInstance();
atom.setName(Atoms[i].getName());
atom.setAtomicNumber(Atoms[i].element);
atom.setXYZ(Atoms[i].xyz[0], Atoms[i].xyz[1], Atoms[i].xyz[2]);
molec.addAtom(atom);
if (Atoms[i].element > 0) {
continue;
}
typesNotSet = true;
int index = Atoms[i].species;
if (index >= colorMap.length) {
index = index % colorMap.length;
}
Integer[] rgbColor = new Integer[3];
rgbColor[0] = colorMap[index][0];
rgbColor[1] = colorMap[index][1];
rgbColor[2] = colorMap[index][2];
atom.setProperty(AtomInterface.RGB_COLOR, rgbColor);
float radius = ChemicalElements.getCovalentRadius(14);
radius *= AtomInterface.COVALENT_TO_GRADIUS_FACTOR;
atom.setProperty(AtomInterface.GR_RADIUS, new Float(radius)); // GR_RADIUS "gradius" is a "graphics radius"
}
if (typesNotSet) {
for (int i = 0; i < molec.getNumberOfAtoms(); i++) {
AtomInterface atom = molec.getAtomInterface(i);
atom.setAtomicNumber(4);
}
for (int i = 0; i < molec.getNumberOfAtoms(); i++) {
AtomInterface atom = molec.getAtomInterface(i);
atom.setAtomicNumber(0);
}
}
molec.addProperty(MoleculeInterface.LATTICE_VECTORS, latticeVectors);
}
}
| 34.001894
| 128
| 0.572551
|
a9097ee644b78d19ebea455b3b46f139c728c8f1
| 1,499
|
package org.codehaus.plexus.configuration.xml;
import org.codehaus.plexus.configuration.DefaultPlexusConfiguration;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.util.xml.Xpp3Dom;
public final class XmlPlexusConfiguration
extends DefaultPlexusConfiguration
{
public XmlPlexusConfiguration(String name)
{
super(name);
}
public XmlPlexusConfiguration(Xpp3Dom dom)
{
super(dom.getName(), dom.getValue());
for (String attribute : dom.getAttributeNames())
{
setAttribute(attribute, dom.getAttribute(attribute));
}
for (Xpp3Dom child : dom.getChildren())
{
addChild(new XmlPlexusConfiguration(child));
}
}
public String toString()
{
StringBuilder buf = new StringBuilder().append('<').append(getName());
for (String a : getAttributeNames())
{
buf.append(' ').append(a).append("=\"").append(getAttribute(a)).append('"');
}
if (getChildCount() > 0)
{
buf.append('>');
for (PlexusConfiguration c : getChildren())
{
buf.append(c);
}
buf.append("</").append(getName()).append('>');
}
else if (null != getValue())
{
buf.append('>').append(getValue()).append("</").append(getName()).append('>');
}
else
{
buf.append("/>");
}
return '\n';
}
protected PlexusConfiguration createChild(String name)
{
return new XmlPlexusConfiguration(name);
}
}
| 18.280488
| 84
| 0.625751
|
64706cd981cec316aba5e2733441177ad2a0d0a8
| 70,329
|
package jp.gr.java_conf.abagames.bulletml;
import org.w3c.dom.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* URelaxer2
* This class can be executed on the DOM2 parser.
*
* @since Sep. 3, 2000
* @version Jan. 18, 2001
* @author ASAMI, Tomoharu (asami@zeomtech.com)
*/
public final class URelaxer2
{
// String type
public static String getElementPropertyAsString(Element element)
{
return (element2Text(element));
}
public static String getElementPropertyAsString(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Text(property);
return (text);
}
public static List getElementPropertyAsStringList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(element2Text(nodes[i]));
}
return (list);
}
public static String getElementPropertyAsStringByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (element2Text(property));
}
public static List getElementPropertyAsStringListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(element2Text(property));
}
return (list);
}
public static String getAttributePropertyAsString(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (value);
}
}
public static List getAttributePropertyAsStringList(Element element, String namespaceURI, String localName)
{
List list = new ArrayList();
String value = getAttribute(element, namespaceURI, localName);
if (value != null)
{
StringTokenizer st = new StringTokenizer(value);
while (st.hasMoreTokens())
{
list.add(st.nextToken());
}
}
return (list);
}
public static void setElementPropertyByString(Element element, String namespaceURI, String localName, String value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value);
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByString(Element element, String value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(value);
element.appendChild(text);
}
public static void setElementPropertyByStringList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setAttributePropertyByString(Element element, String namespaceURI, String localName, String value, RNSContext nsContext)
{
if ((value == null) || "".equals(value))
{ // by horst.fiedler@tifff.com
if (getAttribute(element, namespaceURI, localName) != null)
{
element.removeAttributeNS(namespaceURI, localName);
}
}
else
{
element.setAttributeNS(namespaceURI, localName, value);
}
}
public static void setAttributePropertyByStringList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
StringBuffer buffer = new StringBuffer();
int size = values.size();
if (size > 0)
{
buffer.append(values.get(0).toString());
for (int i = 1; i < size; i++)
{
buffer.append(" ");
buffer.append(values.get(i).toString());
}
}
element.setAttributeNS(namespaceURI, localName, new String(buffer));
}
// boolean type
public static boolean getElementPropertyAsBoolean(Element element)
{
String text = element2Data(element);
if ("true".equals(text))
{
return (true);
}
else if ("false".equals(text))
{
return (false);
}
else if ("1".equals(text))
{
return (true);
}
else if ("0".equals(text))
{
return (false);
}
else
{
throw (new IllegalArgumentException());
}
}
public static boolean getElementPropertyAsBoolean(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
return (getElementPropertyAsBoolean(property));
}
public static List getElementPropertyAsBooleanList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new Boolean(element2Data(nodes[i])));
}
return (list);
}
public static Boolean getElementPropertyAsBooleanByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (new Boolean(element2Data(property)));
}
public static List getElementPropertyAsBooleanListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new Boolean(element2Text(property)));
}
return (list);
}
public static boolean getAttributePropertyAsBoolean(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if ("true".equals(value))
{
return (true);
}
else if ("false".equals(value))
{
return (false);
}
else
{
return (false);
}
}
public static Boolean getAttributePropertyAsBooleanObject(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if ("true".equals(value))
{
return (Boolean.TRUE);
}
else if ("false".equals(value))
{
return (Boolean.FALSE);
}
else
{
return (null);
}
}
public static void setElementPropertyByBoolean(Element element, String namespaceURI, String localName, boolean value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(new Boolean(value).toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByBoolean(Element element, String namespaceURI, String localName, Boolean value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByBooleanList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByBoolean(Element element, boolean value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(new Boolean(value).toString());
element.appendChild(text);
}
public static void setAttributePropertyByBoolean(Element element, String namespaceURI, String localName, boolean value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, new Boolean(value).toString());
}
public static void setAttributePropertyByBoolean(Element element, String namespaceURI, String localName, Boolean value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
// byte type
public static byte getElementPropertyAsByte(Element element)
{
String text = element2Data(element);
return (Byte.parseByte(text));
}
public static byte getElementPropertyAsByte(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (Byte.parseByte(text));
}
public static List getElementPropertyAsByteList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new Byte(element2Data(nodes[i])));
}
return (list);
}
public static Byte getElementPropertyAsByteByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (new Byte(element2Data(property)));
}
public static List getElementPropertyAsByteListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new Byte(element2Text(property)));
}
return (list);
}
public static byte getAttributePropertyAsByte(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (0);
}
else
{
return (Byte.parseByte(value));
}
}
public static Byte getAttributePropertyAsByteObject(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new Byte(value));
}
}
public static void setElementPropertyByByte(Element element, String namespaceURI, String localName, byte value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(Byte.toString(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByByte(Element element, String namespaceURI, String localName, Byte value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByByteList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByByte(Element element, byte value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(Byte.toString(value));
element.appendChild(text);
}
public static void setAttributePropertyByByte(Element element, String namespaceURI, String localName, byte value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, Byte.toString(value));
}
public static void setAttributePropertyByByte(Element element, String namespaceURI, String localName, Byte value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
// short type
public static short getElementPropertyAsShort(Element element)
{
String text = element2Data(element);
return (Short.parseShort(text));
}
public static short getElementPropertyAsShort(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (Short.parseShort(text));
}
public static List getElementPropertyAsShortList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new Short(element2Data(nodes[i])));
}
return (list);
}
public static Short getElementPropertyAsShortByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (new Short(element2Data(property)));
}
public static List getElementPropertyAsShortListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new Short(element2Text(property)));
}
return (list);
}
public static short getAttributePropertyAsShort(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (0);
}
else
{
return (Short.parseShort(value));
}
}
public static Short getAttributePropertyAsShortObject(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new Short(value));
}
}
public static void setElementPropertyByShort(Element element, String namespaceURI, String localName, short value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(Short.toString(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByShort(Element element, String namespaceURI, String localName, Short value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByShortList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByShort(Element element, short value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(Short.toString(value));
element.appendChild(text);
}
public static void setAttributePropertyByShort(Element element, String namespaceURI, String localName, short value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, Short.toString(value));
}
public static void setAttributePropertyByShort(Element element, String namespaceURI, String localName, Short value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
// int type
public static int getElementPropertyAsInt(Element element)
{
String text = element2Data(element);
return (Integer.parseInt(text));
}
public static int getElementPropertyAsInt(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (Integer.parseInt(text));
}
public static List getElementPropertyAsIntList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new Integer(element2Data(nodes[i])));
}
return (list);
}
public static Integer getElementPropertyAsIntByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (new Integer(element2Data(property)));
}
public static List getElementPropertyAsIntListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new Integer(element2Text(property)));
}
return (list);
}
public static int getAttributePropertyAsInt(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (0);
}
else
{
return (Integer.parseInt(value));
}
}
public static Integer getAttributePropertyAsIntObject(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new Integer(value));
}
}
public static void setElementPropertyByInt(Element element, String namespaceURI, String localName, int value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(Integer.toString(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByInt(Element element, String namespaceURI, String localName, Integer value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByIntList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByInt(Element element, int value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(Integer.toString(value));
element.appendChild(text);
}
public static void setAttributePropertyByInt(Element element, String namespaceURI, String localName, int value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, Integer.toString(value));
}
public static void setAttributePropertyByInt(Element element, String namespaceURI, String localName, Integer value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
// long type
public static long getElementPropertyAsLong(Element element)
{
String text = element2Data(element);
return (Long.parseLong(text));
}
public static long getElementPropertyAsLong(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (Long.parseLong(text));
}
public static List getElementPropertyAsLongList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new Long(element2Data(nodes[i])));
}
return (list);
}
public static Long getElementPropertyAsLongByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (new Long(element2Data(property)));
}
public static List getElementPropertyAsLongListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new Long(element2Text(property)));
}
return (list);
}
public static long getAttributePropertyAsLong(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (0);
}
else
{
return (Long.parseLong(value));
}
}
public static Long getAttributePropertyAsLongObject(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new Long(value));
}
}
public static void setElementPropertyByLong(Element element, String namespaceURI, String localName, long value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(Long.toString(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByLong(Element element, String namespaceURI, String localName, Long value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByLongList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByLong(Element element, long value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(Long.toString(value));
element.appendChild(text);
}
public static void setAttributePropertyByLong(Element element, String namespaceURI, String localName, long value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, Long.toString(value));
}
public static void setAttributePropertyByLong(Element element, String namespaceURI, String localName, Long value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
// float type
public static float getElementPropertyAsFloat(Element element)
{
String text = element2Data(element);
return (Float.parseFloat(text));
}
public static float getElementPropertyAsFloat(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (Float.parseFloat(text));
}
public static List getElementPropertyAsFloatList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new Float(element2Data(nodes[i])));
}
return (list);
}
public static Float getElementPropertyAsFloatByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (new Float(element2Data(property)));
}
public static List getElementPropertyAsFloatListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new Float(element2Text(property)));
}
return (list);
}
public static float getAttributePropertyAsFloat(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (0);
}
else
{
return (Float.parseFloat(value));
}
}
public static Float getAttributePropertyAsFloatObject(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new Float(value));
}
}
public static void setElementPropertyByFloat(Element element, String namespaceURI, String localName, float value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(Float.toString(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByFloat(Element element, String namespaceURI, String localName, Float value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByFloatList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByFloat(Element element, float value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(Float.toString(value));
element.appendChild(text);
}
public static void setAttributePropertyByFloat(Element element, String namespaceURI, String localName, float value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, Float.toString(value));
}
public static void setAttributePropertyByFloat(Element element, String namespaceURI, String localName, Float value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
// double type
public static double getElementPropertyAsDouble(Element element)
{
String text = element2Data(element);
return (Double.parseDouble(text));
}
public static double getElementPropertyAsDouble(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (Double.parseDouble(text));
}
public static List getElementPropertyAsDoubleList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new Double(element2Data(nodes[i])));
}
return (list);
}
public static Double getElementPropertyAsDoubleByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (new Double(element2Data(property)));
}
public static List getElementPropertyAsDoubleListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new Double(element2Text(property)));
}
return (list);
}
public static double getAttributePropertyAsDouble(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (0);
}
else
{
return (Double.parseDouble(value));
}
}
public static Double getAttributePropertyAsDoubleObject(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new Double(value));
}
}
public static void setElementPropertyByDouble(Element element, String namespaceURI, String localName, double value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(Double.toString(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByDouble(Element element, String namespaceURI, String localName, Double value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByDoubleList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByDouble(Element element, double value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(Double.toString(value));
element.appendChild(text);
}
public static void setAttributePropertyByDouble(Element element, String namespaceURI, String localName, double value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, Double.toString(value));
}
public static void setAttributePropertyByDouble(Element element, String namespaceURI, String localName, Double value, RNSContext nsContext)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
// BigDecimal type
public static BigDecimal getElementPropertyAsBigDecimal(Element element)
{
String text = element2Data(element);
return (new BigDecimal(text));
}
public static BigDecimal getElementPropertyAsBigDecimal(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (new BigDecimal(text));
}
public static List getElementPropertyAsBigDecimalList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new BigDecimal(element2Data(nodes[i])));
}
return (list);
}
public static BigDecimal getElementPropertyAsBigDecimalByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (getElementPropertyAsBigDecimal(property));
}
public static List getElementPropertyAsBigDecimalListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new BigDecimal(element2Text(property)));
}
return (list);
}
public static BigDecimal getAttributePropertyAsBigDecimal(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new BigDecimal(value));
}
}
public static void setElementPropertyByBigDecimal(Element element, String namespaceURI, String localName, BigDecimal value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByBigDecimalList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByBigDecimal(Element element, BigDecimal value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(value.toString());
element.appendChild(text);
}
public static void setAttributePropertyByBigDecimal(Element element, String namespaceURI, String localName, BigDecimal value, RNSContext nsContext)
{
if (value != null)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
}
// BigInteger type
public static BigInteger getElementPropertyAsBigInteger(Element element)
{
String text = element2Data(element);
return (new BigInteger(text));
}
public static BigInteger getElementPropertyAsBigInteger(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (new BigInteger(text));
}
public static List getElementPropertyAsBigIntegerList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(new BigInteger(element2Data(nodes[i])));
}
return (list);
}
public static BigInteger getElementPropertyAsBigIntegerByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (getElementPropertyAsBigInteger(property));
}
public static List getElementPropertyAsBigIntegerListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(new BigInteger(element2Text(property)));
}
return (list);
}
public static BigInteger getAttributePropertyAsBigInteger(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (new BigInteger(value));
}
}
public static void setElementPropertyByBigInteger(Element element, String namespaceURI, String localName, BigInteger value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByBigIntegerList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByBigInteger(Element element, BigInteger value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(value.toString());
element.appendChild(text);
}
public static void setAttributePropertyByBigInteger(Element element, String namespaceURI, String localName, BigInteger value, RNSContext nsContext)
{
if (value != null)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
}
// Date type
public static Date getElementPropertyAsDate(Element element)
{
try
{
String text = element2Data(element);
DateFormat df = DateFormat.getDateInstance();
return (df.parse(text));
}
catch (ParseException e)
{
throw (new IllegalArgumentException(e.getMessage()));
}
}
public static Date getElementPropertyAsDate(Element element, String namespaceURI, String localName)
{
try
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
DateFormat df = DateFormat.getDateInstance();
return (df.parse(text));
}
catch (ParseException e)
{
throw (new IllegalArgumentException(e.getMessage()));
}
}
public static List getElementPropertyAsDateList(Element element, String namespaceURI, String localName)
{
try
{
Element[] nodes = getElements(element, namespaceURI, localName);
DateFormat df = DateFormat.getDateInstance();
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(df.parse(element2Data(nodes[i])));
}
return (list);
}
catch (ParseException e)
{
throw (new IllegalArgumentException(e.getMessage()));
}
}
public static Date getElementPropertyAsDateByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (getElementPropertyAsDate(property));
}
public static List getElementPropertyAsDateListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
String value = element2Text(property);
try
{
DateFormat df = DateFormat.getDateInstance();
list.add(df.parse(value));
}
catch (ParseException e)
{
throw (new IllegalArgumentException(e.getMessage()));
}
}
return (list);
}
public static Date getAttributePropertyAsDate(Element element, String namespaceURI, String localName)
{
try
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
DateFormat df = DateFormat.getDateInstance();
return (df.parse(value));
}
}
catch (ParseException e)
{
throw (new IllegalArgumentException(e.getMessage()));
}
}
public static void setElementPropertyByDate(Element element, String namespaceURI, String localName, Date value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
DateFormat df = DateFormat.getDateInstance();
Text text = doc.createTextNode(df.format(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByDateList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByDate(Element element, Date value)
{
Document doc = element.getOwnerDocument();
DateFormat df = DateFormat.getDateInstance();
Text text = doc.createTextNode(df.format(value));
element.appendChild(text);
}
public static void setAttributePropertyByDate(Element element, String namespaceURI, String localName, Date value, RNSContext nsContext)
{
if (value != null)
{
DateFormat df = DateFormat.getDateInstance();
element.setAttributeNS(namespaceURI, localName, df.format(value));
}
}
// Locale type
public static Locale getElementPropertyAsLocale(Element element)
{
String text = element2Data(element);
return (makeLocale(text));
}
public static Locale getElementPropertyAsLocale(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (makeLocale(text));
}
public static List getElementPropertyAsLocaleList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(makeLocale(element2Data(nodes[i])));
}
return (list);
}
public static Locale getElementPropertyAsLocaleByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (getElementPropertyAsLocale(property));
}
public static List getElementPropertyAsLocaleListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(makeLocale(element2Text(property)));
}
return (list);
}
public static Locale getAttributePropertyAsLocale(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (makeLocale(value));
}
}
public static void setElementPropertyByLocale(Element element, String namespaceURI, String localName, Locale value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByLocaleList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByLocale(Element element, Locale value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(value.toString());
element.appendChild(text);
}
public static void setAttributePropertyByLocale(Element element, String namespaceURI, String localName, Locale value, RNSContext nsContext)
{
if (value != null)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
}
// URL type
public static URL getElementPropertyAsURL(Element element)
{
String text = element2Data(element);
return (makeURL(text));
}
public static URL getElementPropertyAsURL(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (makeURL(text));
}
public static List getElementPropertyAsURLList(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(makeURL(element2Data(nodes[i])));
}
return (list);
}
public static URL getElementPropertyAsURLByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (getElementPropertyAsURL(property));
}
public static List getElementPropertyAsURLListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(makeURL(element2Text(property)));
}
return (list);
}
public static URL getAttributePropertyAsURL(Element element, String namespaceURI, String localName)
{
String value = getAttribute(element, namespaceURI, localName);
if (value == null)
{
return (null);
}
else
{
return (makeURL(value));
}
}
public static void setElementPropertyByURL(Element element, String namespaceURI, String localName, URL value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(value.toString());
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByURLList(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
String prefix = nsContext.getPrefixByUri(namespaceURI);
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(prefix);
Text text = doc.createTextNode(values.get(i).toString());
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByURL(Element element, URL value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(value.toString());
element.appendChild(text);
}
public static void setAttributePropertyByURL(Element element, String namespaceURI, String localName, URL value, RNSContext nsContext)
{
if (value != null)
{
element.setAttributeNS(namespaceURI, localName, value.toString());
}
}
// binary type
public static byte[] getElementPropertyAsBinaryBASE64(Element element)
{
String text = element2Data(element);
return (makeBytesByBASE64(text));
}
public static byte[] getElementPropertyAsBinaryBASE64(Element element, String namespaceURI, String localName)
{
Element property = getOnlyElement(element, namespaceURI, localName);
String text = element2Data(property);
return (makeBytesByBASE64(text));
}
public static List getElementPropertyAsBinaryListBASE64(Element element, String namespaceURI, String localName)
{
Element[] nodes = getElements(element, namespaceURI, localName);
List list = new ArrayList();
for (int i = 0; i < nodes.length; i++)
{
list.add(makeBytesByBASE64(element2Data(nodes[i])));
}
return (list);
}
public static byte[] getElementPropertyAsBinaryBASE64ByStack(RStack stack, String namespaceURI, String localName)
{
if (stack.isEmptyElement())
{
return (null);
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
return (null);
}
stack.popElement();
return (getElementPropertyAsBinaryBASE64(property));
}
public static List getElementPropertyAsBinaryBASE64ListByStack(RStack stack, String namespaceURI, String localName)
{
List list = new ArrayList();
for (;;)
{
if (stack.isEmptyElement())
{
break;
}
Element property = stack.peekElement();
if (!isTargetElement(property, namespaceURI, localName))
{
break;
}
stack.popElement();
list.add(getElementPropertyAsBinaryBASE64(property));
}
return (list);
}
public static void setElementPropertyByBinaryBASE64(Element element, String namespaceURI, String localName, byte[] value, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(makeStringAsBASE64(value));
property.appendChild(text);
element.appendChild(property);
}
public static void setElementPropertyByBinaryListBASE64(Element element, String namespaceURI, String localName, List values, RNSContext nsContext)
{
Document doc = element.getOwnerDocument();
int size = values.size();
for (int i = 0; i < size; i++)
{
Element property = doc.createElementNS(namespaceURI, localName);
property.setPrefix(nsContext.getPrefixByUri(namespaceURI));
Text text = doc.createTextNode(makeStringAsBASE64((byte[]) values.get(i)));
property.appendChild(text);
element.appendChild(property);
}
}
public static void setElementPropertyByBinaryBASE64(Element element, byte[] value)
{
Document doc = element.getOwnerDocument();
Text text = doc.createTextNode(makeStringAsBASE64(value));
element.appendChild(text);
}
//
// matchers
//
public static boolean isTargetElement(Element element, String namespaceURI, String localName)
{
String elementURI = element.getNamespaceURI();
if (elementURI != null)
{
return (namespaceURI.equals(elementURI) && localName.equals(element.getLocalName()));
}
else
{
return (localName.equals(element.getTagName()));
}
}
public static boolean hasAttribute(Element element, String namespaceURI, String attrName)
{
return (getAttribute(element, namespaceURI, attrName) != null);
}
public static String getAttribute(Element element, String namespaceURI, String attrName)
{
Attr attr = element.getAttributeNodeNS(namespaceURI, attrName);
if (attr == null)
{
return (null);
}
return (attr.getValue());
}
public static boolean isSequence(RStack stack, String namespaceURI, String localName)
{
Element[] elements = stack.peekElements();
if (elements == null)
{
return (false);
}
if (elements.length != 1)
{
return (false);
}
return (isTargetElement(elements[0], namespaceURI, localName));
}
public static boolean isSequence(RStack stack, String namespaceURI, String[] names)
{
Element[] elements = stack.peekElements();
if (elements == null)
{
return (false);
}
if (elements.length != names.length)
{
return (false);
}
for (int i = 0; i < names.length; i++)
{
if (!isTargetElement(elements[i], namespaceURI, names[i]))
{
return (false);
}
}
return (true);
}
public static Element getOnlyElement(Element element, String namespaceURI, String localName)
throws IllegalArgumentException
{
Element[] nodes = getElements(element, namespaceURI, localName);
switch (nodes.length)
{
case 0:
return (null);
case 1:
break;
default:
throw (new IllegalArgumentException());
}
return (nodes[0]);
}
public static Element[] getElements(Element element, String namespaceURI, String localName)
{
NodeList children = element.getChildNodes();
List list = new ArrayList();
int size = children.getLength();
for (int i = 0; i < size; i++)
{
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE)
{
Element childElement = (Element) child;
if (isTargetElement(childElement, namespaceURI, localName))
{
list.add(childElement);
}
}
}
Element[] array = new Element[list.size()];
return ((Element[]) list.toArray(array));
}
public static String element2Data(Element element)
{
return (URelaxer.element2Data(element));
}
public static String element2Text(Element element)
{
return (URelaxer.element2Text(element));
}
public static Locale makeLocale(String name)
{
return (URelaxer.makeLocale(name));
}
public static URL makeURL(String name)
{
return (URelaxer.makeURL(name));
}
public static byte[] makeBytesByBASE64(String data)
{
return (URelaxer.makeBytesByBASE64(data));
}
public static String makeStringAsBASE64(byte[] data)
{
return (URelaxer.makeStringAsBASE64(data));
}
}
| 30.792032
| 152
| 0.597847
|
e198e83349090f4b8227b5af03b1239930bbe397
| 4,921
|
/*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* Copyright 2013 - 2021 Aurelian Tutuianu
*
* 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 rapaio.ml.classifier.bayes.nb;
import rapaio.core.distributions.Distribution;
import rapaio.core.distributions.Normal;
import rapaio.core.stat.OnlineStat;
import rapaio.data.Frame;
import rapaio.data.Var;
import rapaio.data.VarRange;
import rapaio.data.VarType;
import java.io.Serial;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Naive Bayes Gaussian estimator uses the Normal distribution to model
* a numerical feature. The used Gaussian distribution is fitted on test variable
* conditioned by target label. Thus, this event model assumes each conditional
* distribution is Gaussian and they are fitted separately.
* <p>
* Created by <a href="mailto:padreati@yahoo.com">Aurelian Tutuianu</a> on 5/18/15.
*/
public class GaussianEstimator extends AbstractEstimator {
public static GaussianEstimator forName(String testName) {
return new GaussianEstimator(testName);
}
public static List<GaussianEstimator> forRange(Frame df, VarRange varRange) {
return varRange.parseVarNames(df).stream().map(GaussianEstimator::new).collect(Collectors.toList());
}
public static List<GaussianEstimator> forType(Frame df, VarType type) {
return forRange(df, VarRange.onlyTypes(type));
}
public static List<GaussianEstimator> forNames(String... names) {
return Arrays.stream(names).map(GaussianEstimator::new).collect(Collectors.toList());
}
@Serial
private static final long serialVersionUID = -5974296887792054267L;
private final Map<String, Normal> normals = new HashMap<>();
private final String testName;
private GaussianEstimator(String testName) {
super(Collections.singletonList(testName));
this.testName = testName;
}
@Override
public Estimator newInstance() {
return new GaussianEstimator(testName);
}
@Override
public String name() {
return "Gaussian{test=" + testName + "}";
}
@Override
public String fittedName() {
return "Gaussian{test=" + testName + ", " +
"values=[" + normals.entrySet().stream().map(e -> e.getKey() + ":" + e.getValue().name()).collect(Collectors.joining(", ")) + "]}";
}
public List<String> getTargetLevels() {
return new ArrayList<>(normals.keySet());
}
public Normal getFittedNormal(String targetValue) {
return normals.get(targetValue);
}
@Override
public boolean fit(Frame df, Var weights, String targetName) {
String[] varNames = df.varNames();
boolean foundTest = false;
boolean foundTarget = false;
for (String varName : varNames) {
if (varName.equals(testName)) {
foundTest = true;
}
if (varName.equals(targetName)) {
foundTarget = true;
}
}
if (!(foundTest && foundTarget)) {
return false;
}
normals.clear();
Map<String, OnlineStat> stats = new HashMap<>();
for (int i = 0; i < df.rowCount(); i++) {
if (df.isMissing(i, targetName)) {
continue;
}
String label = df.getLabel(i, targetName);
stats.computeIfAbsent(label, key -> OnlineStat.empty())
.update(df.getDouble(i, testName));
}
for (String label : df.levels(targetName)) {
if ("?".equals(label)) {
continue;
}
double mu = stats.get(label).mean();
double sd = stats.get(label).sd();
normals.put(label, Normal.of(mu, sd));
}
hasLearned = true;
return true;
}
@Override
public double predict(Frame df, int row, String targetLevel) {
Distribution normal = normals.get(targetLevel);
double testValue = df.getDouble(row, getTestNames().get(0));
if (Math.abs(normal.var()) < 1e-20) {
return (Math.abs(normal.mean() - testValue) < 1e-20) ? 1.0 : 0.0;
}
return normals.get(targetLevel).pdf(testValue);
}
}
| 32.163399
| 147
| 0.642146
|
84b4c530bc03a0bd14d5e293d585b6d98799fb28
| 5,893
|
package com.nankung.common.module.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import androidx.annotation.AnimRes;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.nankung.common.R;
public class AnimatedRecyclerView extends RecyclerView {
private int orientation = LinearLayoutManager.VERTICAL;
private boolean reverse = false;
private int animationDuration = 250;
private int layoutManagerType = LayoutManagerType.LINEAR;
private int columns = 1;
@AnimRes
private int animation = R.anim.layout_animation_slide_to_left;
private LayoutAnimationController animationController;
public AnimatedRecyclerView(Context context, int orientation, boolean reverse,
int animationDuration, int layoutManagerType, int columns,
int animation, LayoutAnimationController animationController) {
super(context);
this.orientation = orientation;
this.reverse = reverse;
this.animationDuration = animationDuration;
this.layoutManagerType = layoutManagerType;
this.columns = columns;
this.animation = animation;
this.animationController = animationController;
init(context, null);
}
public AnimatedRecyclerView(Context context) {
super(context);
init(context, null);
}
public AnimatedRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public AnimatedRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
@SuppressLint({"Recycle", "WrongConstant"})
private void init(Context context, @Nullable AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AnimatedRecyclerView, 0, 0);
orientation = typedArray.getInt(R.styleable.AnimatedRecyclerView_layoutManagerOrientation, orientation);
reverse = typedArray.getBoolean(R.styleable.AnimatedRecyclerView_layoutManagerReverse, reverse);
animationDuration = typedArray.getInt(R.styleable.AnimatedRecyclerView_animationDuration, animationDuration);
layoutManagerType = typedArray.getInt(R.styleable.AnimatedRecyclerView_layoutManagerType, layoutManagerType);
columns = typedArray.getInt(R.styleable.AnimatedRecyclerView_gridLayoutManagerColumns, columns);
animation = typedArray.getResourceId(R.styleable.AnimatedRecyclerView_layoutAnimation, -1);
if (animationController == null)
animationController = animation != -1
? AnimationUtils.loadLayoutAnimation(getContext(), animation)
: AnimationUtils.loadLayoutAnimation(getContext(), R.anim.layout_animation_slide_to_left);
animationController.getAnimation().setDuration(animationDuration);
setLayoutAnimation(animationController);
if (layoutManagerType == LayoutManagerType.LINEAR)
setLayoutManager(new LinearLayoutManager(context, orientation, reverse));
else if (layoutManagerType == LayoutManagerType.GRID)
setLayoutManager(new GridLayoutManager(context, columns, orientation, reverse));
}
public static class Builder {
private int orientation = LinearLayoutManager.VERTICAL;
private boolean reverse = false;
private int animationDuration = 600;
private int layoutManagerType = LayoutManagerType.LINEAR;
private int columns = 1;
@AnimRes
private int animation = R.anim.layout_animation_from_bottom_scale;
private LayoutAnimationController animationController;
private Context context;
public Builder(Context context) {
this.context = context;
}
public Builder orientation(int orientation) {
this.orientation = orientation;
return this;
}
public Builder reverse(boolean reverse) {
this.reverse = reverse;
return this;
}
public Builder animationDuration(int animationDuration) {
this.animationDuration = animationDuration;
return this;
}
public Builder layoutManagerType(@LayoutManagerType int layoutManagerType) {
this.layoutManagerType = layoutManagerType;
return this;
}
public Builder columns(int columns) {
this.columns = columns;
return this;
}
public Builder animation(@AnimRes int animation) {
this.animation = animation;
return this;
}
public Builder animationController(LayoutAnimationController animationController) {
this.animationController = animationController;
return this;
}
public AnimatedRecyclerView build() {
return new AnimatedRecyclerView(
context, orientation, reverse, animationDuration, layoutManagerType, columns,
animation, animationController
);
}
}
public void notifyDataSetChanged() throws Exception {
if (getAdapter() != null) {
getAdapter().notifyDataSetChanged();
scheduleLayoutAnimation();
} else {
throw new Exception("The adapter must be set");
}
}
public @interface LayoutManagerType {
int LINEAR = 0;
int GRID = 1;
}
}
| 38.019355
| 117
| 0.687256
|
6ac59a7ee9d4f249da827fe8f745b58eda1d6692
| 1,701
|
package com.braintreepayments.api.models;
import android.os.Parcel;
import org.json.JSONException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import static com.braintreepayments.testutils.FixturesHelper.stringFromFixture;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
@RunWith(RobolectricGradleTestRunner.class)
public class CardNonceTest {
@Test
public void canCreateCardFromJson() throws JSONException {
CardNonce cardNonce = CardNonce.fromJson(stringFromFixture("payment_methods/visa_credit_card_response.json"));
assertEquals("Visa", cardNonce.getTypeLabel());
assertEquals("Visa", cardNonce.getCardType());
assertEquals("123456-12345-12345-a-adfa", cardNonce.getNonce());
assertEquals("ending in ••11", cardNonce.getDescription());
assertEquals("11", cardNonce.getLastTwo());
}
@Test
public void parcelsCorrectly() throws JSONException {
CardNonce cardNonce = CardNonce.fromJson(stringFromFixture("payment_methods/visa_credit_card_response.json"));
Parcel parcel = Parcel.obtain();
cardNonce.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
CardNonce parceled = CardNonce.CREATOR.createFromParcel(parcel);
assertEquals("Visa", parceled.getTypeLabel());
assertEquals("Visa", parceled.getCardType());
assertEquals("123456-12345-12345-a-adfa", parceled.getNonce());
assertEquals("ending in ••11", parceled.getDescription());
assertEquals("11", parceled.getLastTwo());
assertFalse(parceled.isDefault());
}
}
| 38.659091
| 118
| 0.733098
|
353280eb21806f7ee2d3750a584124c136197cdc
| 1,448
|
package com.lolzdev.fabriccomputers.items;
import com.lolzdev.fabriccomputers.FabricComputers;
import com.lolzdev.fabriccomputers.blocks.Blocks;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemGroup;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class Items {
public static void init() {
Registry.register(Registry.ITEM, new Identifier("fabriccomputers", "computer"), new BlockItem(Blocks.COMPUTER_BLOCK, new FabricItemSettings().group(FabricComputers.ITEM_GROUP)));
Registry.register(Registry.ITEM, new Identifier("fabriccomputers", "disk_drive"), new BlockItem(Blocks.DISK_DRIVE_BLOCK, new FabricItemSettings().group(FabricComputers.ITEM_GROUP)));
Registry.register(Registry.ITEM, new Identifier("fabriccomputers", "redstone_component"), new BlockItem(Blocks.REDSTONE_COMPONENT_BLOCK, new FabricItemSettings().group(FabricComputers.ITEM_GROUP)));
Registry.register(Registry.ITEM, new Identifier("fabriccomputers", "screen_component"), new BlockItem(Blocks.SCREEN_COMPONENT_BLOCK, new FabricItemSettings().group(FabricComputers.ITEM_GROUP)));
Registry.register(Registry.ITEM, new Identifier("fabriccomputers", "floppy_disk"), new FloppyDiskItem());
Registry.register(Registry.ITEM, new Identifier("fabriccomputers", "fos_disk"), new FixedFloppyDiskItem("fos"));
}
}
| 65.818182
| 206
| 0.790746
|
4de83afd8da00ced1108b1f0a6cab752c411d811
| 17,211
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.util.raytrace;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.util.blockray.RayTrace;
import org.spongepowered.api.util.blockray.RayTraceResult;
import org.spongepowered.api.world.Locatable;
import org.spongepowered.api.world.LocatableBlock;
import org.spongepowered.api.world.server.ServerLocation;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.common.util.VecHelper;
import org.spongepowered.math.vector.Vector3d;
import org.spongepowered.math.vector.Vector3i;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.AABB;
public abstract class AbstractSpongeRayTrace<T extends Locatable> implements RayTrace<@NonNull T> {
private final Predicate<T> defaultFilter;
int limit = 30;
@Nullable Vector3d start;
@Nullable Vector3d direction;
@Nullable Vector3d end;
@Nullable ResourceKey world;
@Nullable Predicate<T> select;
@Nullable Predicate<LocatableBlock> continueWhileBlock = null;
@Nullable Predicate<Entity> continueWhileEntity = null;
@Nullable Predicate<ServerLocation> continueWhileLocation = null;
AbstractSpongeRayTrace(final Predicate<T> defaultFilter) {
this.defaultFilter = defaultFilter;
this.select = defaultFilter;
}
@Override
@NonNull
public final RayTrace<@NonNull T> world(@NonNull final ServerWorld serverWorld) {
this.world = serverWorld.key();
return this;
}
@Override
@NonNull
public RayTrace<@NonNull T> sourceEyePosition(@NonNull final Living entity) {
this.sourcePosition(entity.get(Keys.EYE_POSITION)
.orElseThrow(() -> new IllegalArgumentException("Entity does not have an eye position key")));
return this.world(entity.serverLocation().world());
}
@Override
@NonNull
public final RayTrace<@NonNull T> sourcePosition(@NonNull final Vector3d sourcePosition) {
this.start = sourcePosition;
return this;
}
@Override
public RayTrace<@NonNull T> direction(@NonNull final Vector3d direction) {
this.end = null;
this.direction = direction.normalize();
return this;
}
@Override
public RayTrace<@NonNull T> limit(final int distance) {
if (distance < 1) {
throw new IllegalArgumentException("distance limit must be positive");
}
this.limit = distance;
return this;
}
@Override
@NonNull
public final RayTrace<@NonNull T> continueUntil(@NonNull final Vector3d endPosition) {
this.end = endPosition;
this.direction = null;
return this;
}
@Override
@NonNull
public RayTrace<@NonNull T> continueWhileLocation(@NonNull final Predicate<ServerLocation> continueWhileLocation) {
if (this.continueWhileLocation == null) {
this.continueWhileLocation = continueWhileLocation;
} else {
this.continueWhileLocation = this.continueWhileLocation.and(continueWhileLocation);
}
return this;
}
@Override
@NonNull
public RayTrace<@NonNull T> continueWhileBlock(@NonNull final Predicate<LocatableBlock> continueWhileBlock) {
if (this.continueWhileBlock == null) {
this.continueWhileBlock = continueWhileBlock;
} else {
this.continueWhileBlock = this.continueWhileBlock.and(continueWhileBlock);
}
return this;
}
@Override
@NonNull
public RayTrace<@NonNull T> continueWhileEntity(@NonNull final Predicate<Entity> continueWhileEntity) {
if (this.continueWhileEntity == null) {
this.continueWhileEntity = continueWhileEntity;
} else {
this.continueWhileEntity = this.continueWhileEntity.and(continueWhileEntity);
}
return this;
}
@Override
@NonNull
public final RayTrace<@NonNull T> select(@NonNull final Predicate<T> filter) {
if (this.select == this.defaultFilter) {
this.select = filter;
} else {
this.select = this.select.or(filter);
}
return this;
}
@Override
public Optional<RayTraceResult<@NonNull T>> execute() {
this.setupEnd();
// get the direction
final Vector3d directionWithLength = this.end.sub(this.start);
final double length = directionWithLength.length();
final Vector3d direction = directionWithLength.normalize();
if (direction.lengthSquared() == 0) {
throw new IllegalStateException("The start and end must be two different vectors");
}
final ServerWorld serverWorld = Sponge.server().worldManager().world(this.world)
.orElseThrow(() -> new IllegalStateException("World with key " + this.world.formatted() + " is not loaded!"));
Vector3i currentBlock = this.initialBlock(direction);
final Vector3i steps = this.createSteps(direction);
// The ray equation is, vec(u) + t vec(d). From a point (x, y), there is a t
// that we need to traverse to get to a boundary. We work that out now...
TData tData = this.createInitialTData(direction);
Vector3d currentLocation = new Vector3d(this.start.getX(), this.start.getY(), this.start.getZ());
final boolean requiresEntityTracking = this.requiresEntityTracking();
boolean requireAdvancement = true;
while (requireAdvancement) {
final net.minecraft.world.phys.Vec3 vec3dstart = VecHelper.toVanillaVector3d(currentLocation);
// As this iteration is for the CURRENT block location, we need to check where we are with the filter.
if (this.continueWhileLocation != null && !this.continueWhileLocation.test(ServerLocation.of(serverWorld, currentBlock))) {
return Optional.empty();
}
final Vector3d nextLocation;
final net.minecraft.world.phys.Vec3 vec3dend;
if (tData.getTotalTWithNextStep() > length) {
// This is the last step, we break out of the loop after this set of checks.
requireAdvancement = false;
nextLocation = this.end;
vec3dend = VecHelper.toVanillaVector3d(this.end);
} else {
nextLocation = currentLocation.add(
direction.getX() * tData.getNextStep(),
direction.getY() * tData.getNextStep(),
direction.getZ() * tData.getNextStep()
);
vec3dend = VecHelper.toVanillaVector3d(nextLocation);
}
// Get the selection result.
final Optional<RayTraceResult<@NonNull T>> result = this.testSelectLocation(serverWorld, vec3dstart, vec3dend);
if (result.isPresent() && !this.shouldCheckFailures()) {
// either this is a block ray, so no failures need to be checked, else
// we return the entity later if there isn't an entity in front of it
// that's blocking the view.
return result;
}
// Ensure that the block can be travelled through.
if (!this.shouldAdvanceThroughBlock(serverWorld, vec3dstart, vec3dend)) {
return Optional.empty();
}
// Ensure that the entities in the block can be travelled through.
if (requiresEntityTracking && this.continueWhileEntity != null) {
final double resultDistance;
if (result.isPresent()) {
resultDistance = result.get().hitPosition().distanceSquared(currentLocation);
} else {
resultDistance = Double.MAX_VALUE;
}
final AABB targetAABB = this.getBlockAABB(currentBlock);
for (final net.minecraft.world.entity.Entity entity : this.getFailingEntities(serverWorld, targetAABB)) {
final Optional<net.minecraft.world.phys.Vec3> vec3d = entity.getBoundingBox().clip(vec3dstart, vec3dend);
if (vec3d.isPresent()) {
final net.minecraft.world.phys.Vec3 hitPosition = vec3d.get();
final double sqdist = hitPosition.distanceToSqr(vec3dstart);
if (sqdist < resultDistance) {
// We have a failure, so at this point we just bail out and end the trace.
return Optional.empty();
}
}
}
}
// If we still have a result at this point, return it.
if (result.isPresent()) {
return result;
}
if (requireAdvancement) {
currentLocation = nextLocation;
currentBlock = this.getNextBlock(currentBlock, tData, steps);
tData = this.advance(tData, steps, direction);
}
}
return Optional.empty();
}
@Override
@NonNull
public RayTrace<@NonNull T> reset() {
this.select = this.defaultFilter;
this.world = null;
this.start = null;
this.end = null;
this.continueWhileBlock = null;
this.continueWhileEntity = null;
this.continueWhileLocation = null;
return this;
}
final Vector3i getNextBlock(final Vector3i current, final TData data, final Vector3i steps) {
return current.add(
data.nextStepWillAdvanceX() ? steps.getX() : 0,
data.nextStepWillAdvanceY() ? steps.getY() : 0,
data.nextStepWillAdvanceZ() ? steps.getX() : 0
);
}
final Vector3i createSteps(final Vector3d direction) {
return new Vector3i(
Math.signum(direction.getX()),
Math.signum(direction.getY()),
Math.signum(direction.getZ())
);
}
final AABB getBlockAABB(final Vector3i currentBlock) {
return new AABB(currentBlock.getX(),
currentBlock.getY(), currentBlock.getZ(), currentBlock.getX() + 1, currentBlock.getY() + 1, currentBlock.getZ() + 1);
}
private List<net.minecraft.world.entity.Entity> getFailingEntities(final ServerWorld serverWorld, final AABB targetAABB) {
return ((Level) serverWorld).getEntities((net.minecraft.world.entity.Entity) null, targetAABB, (Predicate) this.continueWhileEntity.negate());
}
boolean requiresEntityTracking() {
return this.continueWhileEntity != null;
}
List<net.minecraft.world.entity.Entity> selectEntities(final ServerWorld serverWorld, final AABB targetAABB) {
return Collections.emptyList();
}
abstract Optional<RayTraceResult<@NonNull T>> testSelectLocation(final ServerWorld serverWorld,
final net.minecraft.world.phys.Vec3 location,
final net.minecraft.world.phys.Vec3 exitLocation);
final LocatableBlock getBlock(final ServerWorld world, final net.minecraft.world.phys.Vec3 in, final net.minecraft.world.phys.Vec3 out) {
final Vector3i coord = new Vector3i(
Math.min(in.x, out.x),
Math.min(in.y, out.y),
Math.min(in.z, out.z)
);
return world.locatableBlock(coord);
}
private boolean shouldAdvanceThroughBlock(final ServerWorld serverWorld,
final net.minecraft.world.phys.Vec3 location,
final net.minecraft.world.phys.Vec3 exitLocation) {
if (this.continueWhileBlock == null) {
return true;
}
return this.continueWhileBlock.test(this.getBlock(serverWorld, location, exitLocation));
}
boolean shouldCheckFailures() {
return false;
}
final void setupEnd() {
if (this.start == null) {
throw new IllegalStateException("start cannot be null");
}
if (this.end == null && this.direction == null) {
throw new IllegalStateException("end cannot be null");
}
if (this.world == null) {
throw new IllegalStateException("world cannot be null");
}
if (this.select == null) {
throw new IllegalStateException("select filter cannot be null");
}
if (this.direction != null) {
this.continueUntil(this.start.add(this.direction.mul(this.limit)));
}
}
final Vector3i initialBlock(final Vector3d direction) {
return new Vector3i(
this.start.getX() - (direction.getX() < 0 && this.start.getX() == 0 ? 1 : 0),
this.start.getY() - (direction.getY() < 0 && this.start.getY() == 0 ? 1 : 0),
this.start.getZ() - (direction.getZ() < 0 && this.start.getZ() == 0 ? 1 : 0)
);
}
final TData createInitialTData(final Vector3d direction) {
return new TData(
0,
this.getT(this.start.getX(), direction.getX(), this.end.getX()),
this.getT(this.start.getY(), direction.getY(), this.end.getY()),
this.getT(this.start.getZ(), direction.getZ(), this.end.getZ())
);
}
final TData advance(final TData data, final Vector3i steps, final Vector3d direction) {
final double nextStep = data.getNextStep();
return new TData(
data.getTotalTWithNextStep(),
data.nextStepWillAdvanceX() ? steps.getX() / direction.getX() : data.gettToX() - nextStep,
data.nextStepWillAdvanceY() ? steps.getY() / direction.getY() : data.gettToY() - nextStep,
data.nextStepWillAdvanceZ() ? steps.getZ() / direction.getZ() : data.gettToZ() - nextStep
);
}
private double getT(final double start, final double direction, final double end) {
if (direction > 0) {
return (Math.min(end, Math.ceil(start)) - start) / direction;
} else if (direction < 0) {
return (Math.max(end, Math.floor(start)) - start) / direction;
} else {
// Infinity - indicates we never reach a boundary.
return Double.POSITIVE_INFINITY;
}
}
static final class TData {
private final double totalT;
private final double tToX;
private final double tToY;
private final double tToZ;
private final double nextStep;
TData(final double totalT, final double tToX, final double tToY, final double tToZ) {
this.totalT = totalT;
this.tToX = tToX;
this.tToY = tToY;
this.tToZ = tToZ;
this.nextStep = Math.min(tToX, Math.min(tToY, tToZ));
}
public double getTotalT() {
return this.totalT;
}
public double gettToX() {
return this.tToX;
}
public double gettToY() {
return this.tToY;
}
public double gettToZ() {
return this.tToZ;
}
public boolean nextStepWillAdvanceX() {
return this.tToX <= this.nextStep;
}
public boolean nextStepWillAdvanceY() {
return this.tToY <= this.nextStep;
}
public boolean nextStepWillAdvanceZ() {
return this.tToZ <= this.nextStep;
}
public double getNextStep() {
return this.nextStep;
}
public double getTotalTWithNextStep() {
return this.nextStep + this.totalT;
}
}
}
| 38.938914
| 150
| 0.627215
|
db55c09d69df95c1e3bfe3189e7af8174eb0c40b
| 5,643
|
package com.yunzhu.module.common.utils;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import androidx.core.app.ActivityCompat;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
public class AntiEmulator {
private static String[] known_pipes = {
"/dev/socket/qemud",
"/dev/qemu_pipe"
};
private static String[] known_qemu_drivers = {
"goldfish"
};
private static String[] known_files = {
"/system/lib/libc_malloc_debug_qemu.so",
"/sys/qemu_trace",
// "/system/bin/qemu-props"
};
public static boolean isEmulator(Context context) {
try {
if (checkByRuleOfGoogleAD()
|| checkID(context)
|| checkPipes()
|| checkQEmuDriverFile()
|| CheckEmulatorBuild(context)
|| CheckEmulatorFiles()
|| CheckOperatorNameAndroid(context)) {
return true;
}
} catch (Exception ioe) {
//捕获异常 则说明是虚拟机
return true;
}
return false;
}
protected static boolean checkID(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
String imei = tm.getDeviceId();
String phoneNum = tm.getLine1Number();
if (imei != null && imei.equals("000000000000000")) {
return true;
}
if (phoneNum != null && phoneNum.equals("15555215554")){
return true;
}
}
return false;
}
//检测“/dev/socket/qemud”,“/dev/qemu_pipe”这两个通道
protected static boolean checkPipes(){
for(int i = 0; i < known_pipes.length; i++){
String pipes = known_pipes[i];
File qemu_socket = new File(pipes);
if(qemu_socket.exists()){
Log.v("Result:", "Find pipes!");
return true;
}
}
Log.i("Result:", "Not Find pipes!");
return false;
}
// 检测驱动文件内容
// 读取文件内容,然后检查已知QEmu的驱动程序的列表
protected static Boolean checkQEmuDriverFile(){
File driver_file = new File("/proc/tty/drivers");
if(driver_file.exists() && driver_file.canRead()){
byte[] data = new byte[1024]; //(int)driver_file.length()
try {
InputStream inStream = new FileInputStream(driver_file);
inStream.read(data);
inStream.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
String driver_data = new String(data);
for(String known_qemu_driver : AntiEmulator.known_qemu_drivers){
if(driver_data.indexOf(known_qemu_driver) != -1){
Log.i("Result:", "Find know_qemu_drivers!");
return true;
}
}
}
Log.i("Result:", "Not Find known_qemu_drivers!");
return false;
}
//检测模拟器上特有的几个文件
protected static Boolean CheckEmulatorFiles(){
for(int i = 0; i < known_files.length; i++){
String file_name = known_files[i];
File qemu_file = new File(file_name);
if(qemu_file.exists()){
Log.v("Result:", "Find Emulator Files!::" + file_name);
return true;
}
}
Log.v("Result:", "Not Find Emulator Files!");
return false;
}
//检测手机上的一些硬件信息
protected static Boolean CheckEmulatorBuild(Context context){
String BOARD = android.os.Build.BOARD;
String BOOTLOADER = android.os.Build.BOOTLOADER;
String BRAND = android.os.Build.BRAND;
String DEVICE = android.os.Build.DEVICE;
String HARDWARE = android.os.Build.HARDWARE;
String MODEL = android.os.Build.MODEL;
String PRODUCT = android.os.Build.PRODUCT;
if (BOARD == "unknown" || BOOTLOADER == "unknown"
|| BRAND == "generic" || DEVICE == "generic"
|| MODEL.contains("sdk") ||MODEL.contains("vbox") ||PRODUCT == "sdk"
|| HARDWARE == "goldfish")
{
Log.v("Result:", "Find Emulator by EmulatorBuild!");
return true;
}
Log.v("Result:", "Not Find Emulator by EmulatorBuild!");
return false;
}
//检测手机运营商家
protected static boolean CheckOperatorNameAndroid(Context context) {
String szOperatorName = ((TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName();
if (szOperatorName.toLowerCase().equals("android") == true) {
Log.v("Result:", "Find Emulator by OperatorName!");
return true;
}
Log.v("Result:", "Not Find Emulator by OperatorName!");
return false;
}
/**
* 通过谷歌ad的方法进行检测
*/
protected static boolean checkByRuleOfGoogleAD() {
try {
Method localMethod = Class.forName("android.os.SystemProperties").getDeclaredMethod("get", new Class[]{String.class});
localMethod.setAccessible(true);
boolean bool = "1".equals(localMethod.invoke(null, new Object[]{"ro.kernel.qemu"}));
return bool;
} catch (Exception e) {}
return false;
}
}
| 33.589286
| 133
| 0.575049
|
f6731da15529f1785c06f3f006af73280a4346c7
| 768
|
/*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.task.api;
/**
* Created with IntelliJ IDEA.
* User: mederly
* Date: 27.4.2012
* Time: 20:59
* To change this template use File | Settings | File Templates.
*/
public class TaskManagerException extends Exception {
public TaskManagerException() {
super();
}
public TaskManagerException(Throwable cause) {
super(cause);
}
public TaskManagerException(String message) {
super(message);
}
public TaskManagerException(String message, Throwable cause) {
super(message, cause);
}
}
| 22.588235
| 67
| 0.679688
|
30177e360153c5439e97b5d5b412feb4ec9b11e2
| 11,558
|
package com.platon.contracts.ppos;
import com.platon.abi.solidity.datatypes.BytesType;
import com.platon.abi.solidity.datatypes.generated.Uint16;
import com.platon.abi.solidity.datatypes.generated.Uint256;
import com.platon.abi.solidity.datatypes.generated.Uint64;
import com.platon.bech32.Bech32;
import com.platon.contracts.ppos.abi.Function;
import com.platon.contracts.ppos.dto.CallResponse;
import com.platon.contracts.ppos.dto.TransactionResponse;
import com.platon.contracts.ppos.dto.common.ErrorCode;
import com.platon.contracts.ppos.dto.common.FunctionType;
import com.platon.contracts.ppos.dto.enums.StakingAmountType;
import com.platon.contracts.ppos.dto.resp.Delegation;
import com.platon.contracts.ppos.dto.resp.DelegationIdInfo;
import com.platon.contracts.ppos.exception.EstimateGasException;
import com.platon.contracts.ppos.exception.NoSupportFunctionType;
import com.platon.crypto.Credentials;
import com.platon.parameters.NetworkParameters;
import com.platon.protocol.Web3j;
import com.platon.protocol.core.RemoteCall;
import com.platon.protocol.core.methods.response.Log;
import com.platon.protocol.core.methods.response.PlatonSendTransaction;
import com.platon.protocol.core.methods.response.TransactionReceipt;
import com.platon.protocol.exceptions.TransactionException;
import com.platon.rlp.solidity.RlpDecoder;
import com.platon.rlp.solidity.RlpList;
import com.platon.rlp.solidity.RlpString;
import com.platon.rlp.solidity.RlpType;
import com.platon.tx.TransactionManager;
import com.platon.tx.gas.GasProvider;
import com.platon.utils.Numeric;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
public class DelegateContract extends BaseContract {
/**
* 加载合约, 默认ReadonlyTransactionManager事务管理
*
* @param web3j
* @return
*/
public static DelegateContract load(Web3j web3j) {
return new DelegateContract(NetworkParameters.getPposContractAddressOfStaking(), web3j);
}
/**
* 加载合约
*
* @param web3j
* @param transactionManager
* @return
*/
public static DelegateContract load(Web3j web3j, TransactionManager transactionManager) {
return new DelegateContract(NetworkParameters.getPposContractAddressOfStaking(), web3j, transactionManager);
}
/**
* 加载合约, 默认RawTransactionManager事务管理
*
* @param web3j
* @param credentials
* @return
*/
public static DelegateContract load(Web3j web3j, Credentials credentials) {
return new DelegateContract(NetworkParameters.getPposContractAddressOfStaking(), web3j, credentials);
}
private DelegateContract(String contractAddress, Web3j web3j) {
super(contractAddress, web3j);
}
private DelegateContract(String contractAddress, Web3j web3j, Credentials credentials) {
super(contractAddress, web3j, credentials);
}
private DelegateContract(String contractAddress, Web3j web3j, TransactionManager transactionManager) {
super(contractAddress, web3j, transactionManager);
}
/**
* 发起委托
*
* @param nodeId 被质押的节点的NodeId
* @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做委托,0: 自由金额; 1: 锁仓金额
* @param amount 委托的金额(按照最小单位算,1LAT = 10**18 von)
* @return
*/
public RemoteCall<TransactionResponse> delegate(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) {
Function function = createDelegateFunction(nodeId, stakingAmountType, amount);
return executeRemoteCallTransaction(function);
}
/**
* 发起委托
*
* @param nodeId 被质押的节点的NodeId
* @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做委托,0: 自由金额; 1: 锁仓金额
* @param amount 委托的金额(按照最小单位算,1LAT = 10**18 von)
* @param gasProvider 用户指定的gasProvider
* @return
*/
public RemoteCall<TransactionResponse> delegate(String nodeId, StakingAmountType stakingAmountType, BigInteger amount, GasProvider gasProvider) {
Function function = createDelegateFunction(nodeId, stakingAmountType, amount);
return executeRemoteCallTransaction(function,gasProvider);
}
/**
* 发起委托的gasProvider
*
* @param nodeId
* @param stakingAmountType
* @param amount
* @return
*/
public GasProvider getDelegateGasProvider(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) throws IOException, EstimateGasException, NoSupportFunctionType {
Function function = createDelegateFunction(nodeId, stakingAmountType, amount);
return getDefaultGasProvider(function);
}
/**
* 发起委托
*
* @param nodeId 被质押的节点的NodeId
* @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做委托,0: 自由金额; 1: 锁仓金额
* @param amount 委托的金额(按照最小单位算,1LAT = 10**18 von)
* @return
*/
public RemoteCall<PlatonSendTransaction> delegateReturnTransaction(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) {
Function function = createDelegateFunction(nodeId, stakingAmountType, amount);
return executeRemoteCallTransactionStep1(function);
}
/**
* 发起委托
*
* @param nodeId 被质押的节点的NodeId
* @param stakingAmountType 表示使用账户自由金额还是账户的锁仓金额做委托,0: 自由金额; 1: 锁仓金额
* @param amount 委托的金额(按照最小单位算,1LAT = 10**18 von)
* @param gasProvider 用户指定的gasProvider
* @return
*/
public RemoteCall<PlatonSendTransaction> delegateReturnTransaction(String nodeId, StakingAmountType stakingAmountType, BigInteger amount, GasProvider gasProvider) {
Function function = createDelegateFunction(nodeId, stakingAmountType, amount );
return executeRemoteCallTransactionStep1(function, gasProvider);
}
private Function createDelegateFunction(String nodeId, StakingAmountType stakingAmountType, BigInteger amount) {
Function function = new Function(FunctionType.DELEGATE_FUNC_TYPE,
Arrays.asList(new Uint16(stakingAmountType.getValue())
, new BytesType(Numeric.hexStringToByteArray(nodeId))
, new Uint256(amount)));
return function;
}
/**
* 减持/撤销委托(全部减持就是撤销)
*
* @param nodeId 被质押的节点的NodeId
* @param stakingBlockNum 代表着某个node的某次质押的唯一标示
* @param amount 减持委托的金额(按照最小单位算,1LAT = 10**18 von)
* @return
*/
public RemoteCall<TransactionResponse> unDelegate(String nodeId, BigInteger stakingBlockNum, BigInteger amount) {
Function function = createUnDelegateFunction(nodeId, stakingBlockNum, amount);
return executeRemoteCallTransaction(function);
}
/**
* 减持/撤销委托(全部减持就是撤销)
*
* @param nodeId 被质押的节点的NodeId
* @param stakingBlockNum 代表着某个node的某次质押的唯一标示
* @param amount 减持委托的金额(按照最小单位算,1LAT = 10**18 von)
* @param gasProvider 用户指定的gasProvider
* @return
*/
public RemoteCall<TransactionResponse> unDelegate(String nodeId, BigInteger stakingBlockNum, BigInteger amount, GasProvider gasProvider) {
Function function = createUnDelegateFunction(nodeId, stakingBlockNum, amount);
return executeRemoteCallTransaction(function,gasProvider);
}
/**
* 减持/撤销委托(全部减持就是撤销)的gasProvider
*
* @param nodeId
* @param stakingBlockNum
* @param amount
* @return
*/
public GasProvider getUnDelegateGasProvider(String nodeId, BigInteger stakingBlockNum, BigInteger amount) throws IOException, EstimateGasException, NoSupportFunctionType {
Function function = createUnDelegateFunction(nodeId, stakingBlockNum, amount);
return getDefaultGasProvider(function);
}
/**
* 减持/撤销委托(全部减持就是撤销)
*
* @param nodeId 被质押的节点的NodeId
* @param stakingBlockNum 代表着某个node的某次质押的唯一标示
* @param amount 减持委托的金额(按照最小单位算,1LAT = 10**18 von)
* @return
*/
public RemoteCall<PlatonSendTransaction> unDelegateReturnTransaction(String nodeId, BigInteger stakingBlockNum, BigInteger amount) {
Function function = createUnDelegateFunction(nodeId, stakingBlockNum, amount);
return executeRemoteCallTransactionStep1(function);
}
/**
* 减持/撤销委托(全部减持就是撤销)
*
* @param nodeId 被质押的节点的NodeId
* @param stakingBlockNum 代表着某个node的某次质押的唯一标示
* @param amount 减持委托的金额(按照最小单位算,1LAT = 10**18 von)
* @return
*/
public RemoteCall<PlatonSendTransaction> unDelegateReturnTransaction(String nodeId, BigInteger stakingBlockNum, BigInteger amount, GasProvider gasProvider) {
Function function = createUnDelegateFunction(nodeId, stakingBlockNum, amount);
return executeRemoteCallTransactionStep1(function, gasProvider);
}
private Function createUnDelegateFunction(String nodeId, BigInteger stakingBlockNum, BigInteger amount) {
Function function = new Function(FunctionType.WITHDREW_DELEGATE_FUNC_TYPE,
Arrays.asList(new Uint64(stakingBlockNum)
, new BytesType(Numeric.hexStringToByteArray(nodeId))
, new Uint256(amount)));
return function;
}
/**
* 获得解除委托时所提取的委托收益(当减持/撤销委托成功时调用)
*
* @param transactionReceipt
* @return
* @throws TransactionException
*/
public BigInteger decodeUnDelegateLog(TransactionReceipt transactionReceipt) throws TransactionException {
List<Log> logs = transactionReceipt.getLogs();
if(logs==null||logs.isEmpty()){
throw new TransactionException("TransactionReceipt logs is empty");
}
String logData = logs.get(0).getData();
if(null == logData || "".equals(logData) ){
throw new TransactionException("TransactionReceipt logs[0].data is empty");
}
RlpList rlp = RlpDecoder.decode(Numeric.hexStringToByteArray(logData));
List<RlpType> rlpList = ((RlpList)(rlp.getValues().get(0))).getValues();
String decodedStatus = new String(((RlpString)rlpList.get(0)).getBytes());
int statusCode = Integer.parseInt(decodedStatus);
if(statusCode != ErrorCode.SUCCESS){
throw new TransactionException("TransactionResponse code is 0");
}
return ((RlpString)((RlpList)RlpDecoder.decode(((RlpString)rlpList.get(1)).getBytes())).getValues().get(0)).asPositiveBigInteger();
}
/**
* 查询当前单个委托信息
*
* @param nodeId 验证人的节点Id
* @param delAddr 委托人账户地址
* @param stakingBlockNum 发起质押时的区块高度
* @return
*/
public RemoteCall<CallResponse<Delegation>> getDelegateInfo(String nodeId, String delAddr, BigInteger stakingBlockNum) {
Function function = new Function(FunctionType.GET_DELEGATEINFO_FUNC_TYPE,
Arrays.asList(new Uint64(stakingBlockNum)
, new BytesType(Bech32.addressDecode(delAddr))
, new BytesType(Numeric.hexStringToByteArray(nodeId))));
return executeRemoteCallObjectValueReturn(function, Delegation.class);
}
/**
* 查询当前账户地址所委托的节点的NodeID和质押Id
*
* @param address
* @return
*/
public RemoteCall<CallResponse<List<DelegationIdInfo>>> getRelatedListByDelAddr(String address) {
Function function = new Function(FunctionType.GET_DELEGATELIST_BYADDR_FUNC_TYPE,
Arrays.asList(new BytesType(Bech32.addressDecode(address))));
return executeRemoteCallListValueReturn(function, DelegationIdInfo.class);
}
}
| 39.179661
| 182
| 0.701938
|
816fc05c834213983660d836a7e6f2b7da5aaef3
| 608
|
package ferixx.test.mod;
import ferixx.test.mod.block.ModBlocks;
import ferixx.test.mod.item.ModItems;
import ferixx.test.mod.util.ModLootTableModifiers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.fabricmc.api.ModInitializer;
public class TestMod implements ModInitializer {
public static final String MOD_ID = "testmod";
public static final Logger LOGGER = LogManager.getLogger(MOD_ID);
@Override
public void onInitialize() {
ModItems.registerModItems();
ModBlocks.registerModBlocks();
// ModLootTableModifiers.modifyLootTables();
}
}// pp
| 27.636364
| 66
| 0.794408
|
8878704d09b61be108cf6bc58c1c836d80eb6086
| 2,730
|
package com.kong.alex.sharkfeed.di;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import com.kong.alex.sharkfeed.SharkFeedApp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import dagger.android.AndroidInjection;
import dagger.android.support.AndroidSupportInjection;
import dagger.android.support.HasSupportFragmentInjector;
/**
* Helper class to automatically inject fragments if they implement {@link Injectable}.
*/
public class AppInjector {
private AppInjector() {
}
public static void init(SharkFeedApp sharkFeedApp) {
sharkFeedApp.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
handleActivity(activity);
}
@Override
public void onActivityStarted(Activity activity) {
//do nothing
}
@Override
public void onActivityResumed(Activity activity) {
//do nothing
}
@Override
public void onActivityPaused(Activity activity) {
//do nothing
}
@Override
public void onActivityStopped(Activity activity) {
//do nothing
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//do nothing
}
@Override
public void onActivityDestroyed(Activity activity) {
//do nothing
}
});
}
private static void handleActivity(Activity activity) {
if(activity instanceof HasSupportFragmentInjector) {
AndroidInjection.inject(activity);
}
if(activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {
@Override
public void onFragmentCreated(@NonNull FragmentManager fm, @NonNull Fragment f, @Nullable Bundle savedInstanceState) {
super.onFragmentCreated(fm, f, savedInstanceState);
if(f instanceof Injectable) {
AndroidSupportInjection.inject(f);
}
}
}, true);
}
}
}
| 32.891566
| 142
| 0.610623
|
2ea5bdba7a108c5257ac1413603d1297045b57df
| 1,813
|
package com.meteo.coolweather;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.meteo.coolweather.db.County;
import java.util.List;
/**
* Created by meteo on 2017/3/15.
*/
public class CountyAdapter extends RecyclerView.Adapter<CountyAdapter.ViewHolder> {
List<County> countyList;
OnListFragmentInteractionListener listener;
public CountyAdapter(List<County> countyList, OnListFragmentInteractionListener listener) {
this.countyList = countyList;
this.listener = listener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView areaName;
public ViewHolder(View itemView) {
super(itemView);
areaName = (TextView) itemView.findViewById(R.id.area_name);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.area_item, parent, false);
final ViewHolder vh = new ViewHolder(view);
if (listener != null) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
County county = countyList.get(vh.getAdapterPosition());
listener.onListFragmentInteraction(county);
}
});
}
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
County county = countyList.get(position);
holder.areaName.setText(county.getCountyName());
}
@Override
public int getItemCount() {
return countyList.size();
}
}
| 28.777778
| 104
| 0.661335
|
5c2cd960de05570e79aeef182f693ec5b235ea1e
| 8,490
|
package eu.domaindriven.ddq.hal;
import org.jboss.resteasy.core.ResteasyContext;
import javax.json.bind.annotation.JsonbTransient;
import javax.json.bind.serializer.JsonbSerializer;
import javax.json.bind.serializer.SerializationContext;
import javax.json.stream.JsonGenerator;
import javax.ws.rs.core.Link;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
public abstract class HalSerializer<T extends HalObject> implements JsonbSerializer<T> {
@Override
public void serialize(T obj, JsonGenerator generator, SerializationContext ctx) {
generator.writeStartObject();
Map<FieldType, List<Field>> fields = Arrays.stream(obj.getClass().getDeclaredFields())
.filter(Field::trySetAccessible)
.collect(Collectors.groupingBy(HalSerializer::classifyField));
Map<String, Object> regularFields = extract(fields.getOrDefault(FieldType.REGULAR, List.of()), obj);
regularFields.putAll(supplyRegularFields(obj));
Map<String, Object> embeddedFields = extract(fields.getOrDefault(FieldType.EMBEDDED, List.of()), obj);
embeddedFields.putAll(supplyEmbeddedFields(obj));
Map<String, Object> transientFields = extract(fields.getOrDefault(FieldType.TRANSIENT, List.of()), obj);
Map<String, Object> linkTemplateValues = new HashMap<>(regularFields);
linkTemplateValues.putAll(transientFields);
Map<String, String> linkFields = extractLinks(fields.getOrDefault(FieldType.LINK, List.of()), linkTemplateValues, obj);
linkFields.putAll(supplyLinks(obj));
serializeRegularFields(regularFields, generator, ctx);
serializeLinks(linkFields, generator);
serializeEmbeddedFields(embeddedFields, generator, ctx);
generator.writeEnd();
}
protected Map<String, Object> supplyRegularFields(T obj) {
return Map.of();
}
protected Map<String, Object> supplyEmbeddedFields(T obj) {
return Map.of();
}
protected Map<String, String> supplyLinks(T obj) {
return Map.of();
}
protected static UriInfo uriInfo() {
return ResteasyContext.getContextData(UriInfo.class);
}
private static void serializeLinks(Map<String, String> links, JsonGenerator generator) {
generator.writeStartObject("_links");
if (!links.containsKey("self")) {
serializeLink("self", uriInfo().getRequestUri().toString(), generator);
}
links.forEach((key, value) -> serializeLink(key, value, generator));
generator.writeEnd();
}
private static Map<String, String> extractLinks(Collection<Field> fields, Map<String, Object> templateValues, Object obj) {
return fields.stream()
.filter(field -> isLinkActive(field, obj))
.collect(Collectors.toMap(HalSerializer::createRel, field -> createHref(field, obj, templateValues), (href1, href2) -> href1, HashMap::new));
}
private static String createRel(Field field) {
String rel = field.getName();
if (field.isAnnotationPresent(BaseLink.class)) {
String annotationRel = field.getAnnotation(BaseLink.class).rel();
if (!annotationRel.isBlank()) {
rel = annotationRel;
}
} else if (field.isAnnotationPresent(RequestLink.class)) {
String annotationRel = field.getAnnotation(RequestLink.class).rel();
if (!annotationRel.isBlank()) {
rel = annotationRel;
}
}
return rel;
}
private static boolean isLinkActive(Field field, Object obj) {
try {
if (isLinkAnnotationPresent(field)) {
String condition = field.isAnnotationPresent(BaseLink.class)
? field.getAnnotation(BaseLink.class).condition()
: field.getAnnotation(RequestLink.class).condition();
return condition.isBlank() || evaluateCondition(condition, obj);
} else {
return field.get(obj) != null;
}
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private static boolean evaluateCondition(String condition, Object obj) {
try {
Method method = obj.getClass().getMethod(condition);
method.trySetAccessible();
return (boolean) method.invoke(obj);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
private static String createHref(Field field, Object obj, Map<String, Object> templateValues) {
try {
String href;
Link link = (Link) field.get(obj);
if (link != null) {
href = link.getUri().toString();
} else if (isLinkAnnotationPresent(field)) {
href = createUriBuilder(field, obj).resolveTemplates(templateValues).build().toString();
} else {
throw new IllegalStateException("No href present");
}
return href;
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private static boolean isLinkAnnotationPresent(Field field) {
return field.isAnnotationPresent(BaseLink.class) || field.isAnnotationPresent(RequestLink.class);
}
private static UriBuilder createUriBuilder(Field field, Object obj) {
UriBuilder uriBuilder;
QueryParam[] queryParams;
if (field.isAnnotationPresent(BaseLink.class)) {
uriBuilder = uriInfo().getBaseUriBuilder();
BaseLink baseLink = field.getAnnotation(BaseLink.class);
queryParams = baseLink.queryParams();
if (obj.getClass().isAnnotationPresent(BasePath.class) && baseLink.useBasePath()) {
uriBuilder.path(obj.getClass().getAnnotation(BasePath.class).value());
}
uriBuilder.path(baseLink.path());
} else if (field.isAnnotationPresent(RequestLink.class)) {
RequestLink requestLink = field.getAnnotation(RequestLink.class);
queryParams = requestLink.queryParams();
uriBuilder = uriInfo().getRequestUriBuilder().path(requestLink.path());
} else {
throw new IllegalArgumentException("No annotation present.");
}
for (QueryParam queryParam : queryParams) {
uriBuilder.queryParam(queryParam.name(), (Object[]) queryParam.values());
}
return uriBuilder;
}
private static void serializeLink(String rel, String href, JsonGenerator generator) {
generator.writeStartObject(rel);
generator.write("href", href);
generator.writeEnd();
}
private static void serializeEmbeddedFields(Map<String, Object> fields, JsonGenerator generator, SerializationContext ctx) {
generator.writeStartObject("_embedded");
serializeRegularFields(fields, generator, ctx);
generator.writeEnd();
}
private static void serializeRegularFields(Map<String, Object> fields, JsonGenerator generator, SerializationContext ctx) {
fields.forEach((key, value) -> ctx.serialize(key, value, generator));
}
private static Map<String, Object> extract(Collection<Field> fields, Object obj) {
return fields.stream().collect(Collectors.toMap(Field::getName, field -> extractValue(field, obj), (value1, value2) -> value1, HashMap::new));
}
private static Object extractValue(Field field, Object obj) {
try {
return field.get(obj);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private static FieldType classifyField(Field field) {
if (field.isAnnotationPresent(JsonbTransient.class)) {
return FieldType.TRANSIENT;
} else if (field.getType().equals(Link.class)) {
return FieldType.LINK;
} else if (field.isAnnotationPresent(Embedded.class)) {
return FieldType.EMBEDDED;
} else {
return FieldType.REGULAR;
}
}
private enum FieldType {
LINK,
EMBEDDED,
REGULAR,
TRANSIENT
}
}
| 40.04717
| 157
| 0.648645
|
61af43b1661145c1d3fa780694c5dc29380fcf7d
| 2,822
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.isopropylcyanide.jdbiunitofwork.core;
import org.skife.jdbi.v2.Handle;
import java.util.concurrent.ThreadFactory;
/**
* A {@link JdbiHandleManager} is used to provide the lifecycle of a {@link Handle} with respect
* to a given scope. A scope may be session based, request based or may be invoked on every run.
*/
public interface JdbiHandleManager {
/**
* Provide a way to get a Jdbi handle, a wrapped connection to the underlying database
*
* @return a valid handle tied with a specific scope
*/
Handle get();
/**
* Provide a way to clear the handle rendering it useless for the other methods
*/
void clear();
/**
* Provide a thread factory for the caller with some identity represented by the
* {@link #getConversationId()}. This can be used by the caller to create multiple threads,
* say, using {@link java.util.concurrent.ExecutorService}. The {@link JdbiHandleManager} can
* then use the thread factory to identify and manage handle use across multiple threads.
*
* @return a thread factory used to safely create multiple threads
* @throws UnsupportedOperationException by default. Implementations overriding this method
* must ensure that the conversation id is unique
*/
default ThreadFactory createThreadFactory() {
throw new UnsupportedOperationException("Thread factory creation is not supported");
}
/**
* Provide a unique identifier for the conversation with a handle. No two identifiers
* should co exist at once during the application lifecycle or else handle corruption
* or misuse might occur.
* <br><br>
* This can be relied upon by the {@link #createThreadFactory()} to reuse handles across
* multiple threads spawned off a request thread.
*
* @return a unique identifier applicable to a scope
* @implNote hashcode can not be relied upon for providing a unique identifier due to the
* possibility of collision. Instead opt for a monotonically increasing counter, such as
* the thread id.
*/
default String getConversationId() {
return String.valueOf(Thread.currentThread().getId());
}
}
| 40.898551
| 97
| 0.704819
|
b8546cd0bbffb8a1fda2b97d8c30bb488e83ce39
| 10,030
|
package seedu.eylah.expensesplitter.logic.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.eylah.expensesplitter.testutil.TypicalPersons.getTypicalPersonAmountBook;
import static seedu.eylah.testutil.Assert.assertThrows;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import seedu.eylah.commons.core.index.Index;
import seedu.eylah.commons.logic.command.CommandResult;
import seedu.eylah.commons.logic.command.exception.CommandException;
import seedu.eylah.commons.logic.parser.exception.ParseException;
import seedu.eylah.expensesplitter.logic.parser.ParserUtil;
import seedu.eylah.expensesplitter.model.ModelStub;
import seedu.eylah.expensesplitter.model.PersonAmountBook;
import seedu.eylah.expensesplitter.model.ReadOnlyPersonAmountBook;
import seedu.eylah.expensesplitter.model.ReceiptStub;
import seedu.eylah.expensesplitter.model.person.Amount;
import seedu.eylah.expensesplitter.model.person.Name;
import seedu.eylah.expensesplitter.model.person.Person;
import seedu.eylah.expensesplitter.model.receipt.Receipt;
import seedu.eylah.expensesplitter.testutil.TypicalPersons;
public class PaidCommandTest {
@Test
public void constructor_nullPaidCommand_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new PaidCommand(null, null));
}
/**
* For this test case I am testing if the PaidCommand is working as expected with a
* pre creatied personamount book, with TYPICALPERSON.ALICE as index 1 and deducting $1 from ALICE.
* The expected output should be ALICE's Amount dropping from $3.50
* to $2.50.
* @throws Exception
*/
@Test
public void execute_paidCommandAcceptedByModel_paidSuccessful() throws Exception {
ModelStubPaidCommand modelStub = new ModelStubPaidCommand();
// Ensuring that the receipt is done before I can use PaidCommand.
modelStub.receipt.makeDone();
CommandResult commandResult = new PaidCommand(ParserUtil.parseIndex("1"), "1")
.execute(modelStub);
assertEquals(String.format(PaidCommand.MESSAGE_SUCCESS + TypicalPersons.ALICE.getName()
+ ". Amount owed decreased from " + "$3.50 to $2.50."), commandResult.getFeedbackToUser());
}
/**
* For this test case I am testing if the PaidCommand is working as expected by throwing an exception when
* the current receipt is still in process.
* `donereceipt` command must be execute before PaidCommand can be executed
* @throws Exception
*/
@Test
public void execute_paidCommandAcceptedByModel_paidUnsuccessful() throws ParseException, CommandException {
ModelStubPaidCommand modelStub = new ModelStubPaidCommand();
// Ensuring that the receipt is NOT done so I cannot use PaidCommand.
CommandResult commandResult = new PaidCommand(ParserUtil.parseIndex("1"), "1")
.execute(modelStub);
assertEquals(String.format(PaidCommand.MESSAGE_RECEIPT_UNDONE), commandResult.getFeedbackToUser());
}
/**
* For this test case I am testing if the PaidCommand is working as expected by
* inputting a wrong amount value. Such as -1.
* @throws Exception
*/
@Test
public void execute_paidCommandFailureDueToIncorrectAmount() throws ParseException, CommandException {
ModelStubPaidCommand modelStub = new ModelStubPaidCommand();
// Ensuring that the receipt is done so I can use PaidCommand.
modelStub.receipt.makeDone();
String test;
try {
CommandResult commandResult = new PaidCommand(ParserUtil.parseIndex("1"), "-1")
.execute(modelStub);
test = "pass";
} catch (IllegalArgumentException ex) {
// working as expected. Because amount paid cannot be negative
test = "fail";
}
assertTrue(test.equals("fail"));
}
/**
* For this test case I am testing if the PaidCommand is working as expected with a
* pre creatied personamount book, with TYPICALPERSON.ALICE as index 1 and deducting fully from ALICE.
* The expected output should be ALICE's Amount dropping from $3.50
* to $0.00.
* @throws Exception
*/
@Test
public void execute_paidCommandAcceptedByModel_paidFullySuccessful() throws Exception {
ModelStubPaidCommand modelStub = new ModelStubPaidCommand();
// Ensuring that the receipt is done before I can use PaidCommand.
modelStub.receipt.makeDone();
CommandResult commandResult = new PaidCommand(ParserUtil.parseIndex("1"), "3.50")
.execute(modelStub);
//System.out.println(modelStub.personAmountBook.getPersonList().size());
assertEquals(String.format(PaidCommand.MESSAGE_SUCCESS + TypicalPersons.ALICE.getName()
+ ". Amount owed decreased from " + "$3.50 to $0.00."), commandResult.getFeedbackToUser());
}
/**
* For this test case I am testing if the PaidCommand is working as expected with a
* pre creatied personamount book, with TYPICALPERSON.ALICE as index 1 and deducting fully from ALICE.
* ALICE should be deleted from the list since she owes $0.00.
* Ensuring that the person at INDEX 0 is different.
* Previously it was ALICE, after command its BOB.
* @throws Exception
*/
@Test
public void execute_paidCommandAcceptedByModel_deleteOfPersonSuccessful() throws Exception {
ModelStubPaidCommand modelStub = new ModelStubPaidCommand();
// Ensuring that the receipt is done before I can use PaidCommand.
int initialNumberOfPersons = modelStub.personAmountBook.getPersonList().size();
Name initialPersonAtIndexZero = modelStub.personAmountBook.getPersonByIndex(0).getName();
modelStub.receipt.makeDone();
CommandResult commandResult = new PaidCommand(ParserUtil.parseIndex("1"), "3.50")
.execute(modelStub);
int finalNumberOfPersons = modelStub.personAmountBook.getPersonList().size();
Name finalPersonAtIndexZero = modelStub.personAmountBook.getPersonByIndex(0).getName();
//Since I am comparing both int primitives I can use ==
assertTrue(initialNumberOfPersons - 1 == finalNumberOfPersons);
assertFalse(initialPersonAtIndexZero.equals(finalPersonAtIndexZero));
}
/**
* For this test case I am testing if the PaidCommand is working as expected by
* inputting a wrong amount value. Such as passing in an amount that
* is more than what the ALICE owes.
* @throws Exception
*/
@Test
public void execute_paidCommandFailureDueToTooMuchAmount() throws ParseException, CommandException {
ModelStubPaidCommand modelStub = new ModelStubPaidCommand();
// Ensuring that the receipt is done so I can use PaidCommand.
modelStub.receipt.makeDone();
String test;
try {
CommandResult commandResult = new PaidCommand(ParserUtil.parseIndex("1"), "5.00")
.execute(modelStub);
test = "pass";
} catch (CommandException ex) {
// working as expected. Because amount paid cannot be more than what the person owes.
test = "fail";
}
assertTrue(test.equals("fail"));
}
@Test
public void equals() {
PaidCommand paidCommand = new PaidCommand(Index.fromOneBased(1), "1.00");
// same object -> returns true
assertTrue(paidCommand.equals(paidCommand));
// different types -> returns false
assertFalse(paidCommand.equals(1));
//null -> returns false
assertFalse(paidCommand.equals(null));
}
/**
* This tests ensures that if all fields are null then it is not a valid command.
* And that a NullPointerException.class is thrown
*/
@Test
public void constructor_allNull_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new PaidCommand(null, null));
}
/**
* This tests ensures that if Index field is negative then it is not a valid command.
* And that a NullPointerException.class is thrown
*/
@Test
public void constructor_invalidIndex_throwsParseException() {
assertThrows(ParseException.class, () -> new PaidCommand(ParserUtil.parseIndex("-1"),
"1"));
}
/**
* This tests ensures that if all fields are invalid then it is not a valid command.
* And that a NullPointerException.class is thrown
*/
@Test
public void constructor_nullIndex_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new PaidCommand(null, "1"));
}
private class ModelStubPaidCommand extends ModelStub {
private final PersonAmountBook personAmountBook;
private final Receipt receipt;
ModelStubPaidCommand() {
personAmountBook = getTypicalPersonAmountBook();
receipt = new ReceiptStub();
}
/**
* In order to use PaidCommand, I need to ensure the receipt is done.
* Hence for this simple stub, I checking if receipt is done.
* @return
*/
@Override
public boolean isReceiptDone() {
return receipt.isDone();
}
@Override
public ReadOnlyPersonAmountBook getPersonAmountBook() {
return this.personAmountBook;
}
/**
* For this particular test case I am deducting ALICE's Amount by $1
* @param person TypicalPerson.ALice
* @param amountPaid
*/
@Override
public void paidPerson(Person person, String amountPaid) {
Amount amount = new Amount(new BigDecimal(amountPaid));
personAmountBook.removeAmount(person, amount);
}
}
}
| 35.192982
| 111
| 0.688534
|
7c5bbaca361a6baa7ad5c9dd95688d3b277c9751
| 616
|
package org.apache.spark.sql.catalyst.expressions.aggregate;
public class Percentile$ extends scala.runtime.AbstractFunction5<org.apache.spark.sql.catalyst.expressions.Expression, org.apache.spark.sql.catalyst.expressions.Expression, org.apache.spark.sql.catalyst.expressions.Expression, java.lang.Object, java.lang.Object, org.apache.spark.sql.catalyst.expressions.aggregate.Percentile> implements scala.Serializable {
/**
* Static reference to the singleton instance of this Scala object.
*/
public static final Percentile$ MODULE$ = null;
public Percentile$ () { throw new RuntimeException(); }
}
| 68.444444
| 359
| 0.792208
|
b4636ce471dd5fd277e8f4ce9196cf1879ef64a6
| 493
|
package ru.job4j.array;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Тест сортировки пузырьком.
*
* @author Andrey Sumin
* @since 18.02.2018
*/
public class BubbleSortTest {
@Test
public void testSort() {
BubbleSort sort = new BubbleSort();
int[] result = new int[]{8, 9, 5, 3, 1, 14, 96, 5, -3};
sort.sort(result);
int[] expected = new int[]{-3, 1, 3, 5, 5, 8, 9, 14, 96};
assertArrayEquals(expected, result);
}
}
| 21.434783
| 65
| 0.586207
|
fc085f8c6a7839ceaf5b54d4b5e822d52de82cdf
| 90
|
package com.coder163.service;
public interface IUserService {
void showMessage();
}
| 12.857143
| 31
| 0.744444
|
47d4a0cb9dd238130473472056e146dbc86164b8
| 644
|
package com.saucelabs.simplesauce;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
public class SauceDriverImpl implements SauceRemoteDriver {
private RemoteWebDriver remoteDriver;
public RemoteWebDriver createRemoteWebDriver(String seleniumServer, MutableCapabilities capabilities)
throws MalformedURLException
{
remoteDriver = new RemoteWebDriver(new URL(seleniumServer), capabilities);
return remoteDriver;
}
@Override
public void quit() {
remoteDriver.quit();
}
}
| 26.833333
| 105
| 0.762422
|
3d45c48b9b9c1a4a5672871bd790e6cba9f03418
| 2,937
|
package com.car.controller;
import com.alibaba.fastjson.JSONArray;
import com.car.domain.Car;
import com.car.mysql.impl.CarManagementImpl;
import com.car.service.UserService;
import com.car.service.VehicleService;
import com.car.utils.RootVoUtils;
import com.car.vo.RootVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @Author : mmy
* @Creat Time : 2020/5/7 22:58
* @Description
*/
@RestController
@RequestMapping("/api")
public class VehicleController {
@Autowired
private CarManagementImpl carManagement;
@Autowired
private VehicleService vehicleService;
@Autowired
UserService userService;
/**
* 增加车辆
* api/Vehicle/Add
*/
@PostMapping("/Vehicle/Add")
public RootVo Add(@RequestBody Map<String, Object> map, HttpServletRequest request) {
System.out.println("Vehicle/Search: " + map);
map = userService.getUserIdByRequest(request, map);
carManagement.insertCar(map);
return RootVoUtils.success(true);
}
/**
* 更新车辆
* api/Vehicle/Update
*/
@PostMapping("/Vehicle/Update")
public RootVo Update(@RequestBody Map<String, Object> map, HttpServletRequest request) {
System.out.println("Vehicle/Search: " + map);
carManagement.update(map);
return RootVoUtils.success(true);
}
/**
* 车辆管理
* Key: "14566"
* OrgId: "01a6eb66-a045-4869-92d0-ab4500f4ed9a"
* WithChildren: "true"
* 默认
* limit: 15
* page: 1
* start: 0
*/
@PostMapping("/Vehicle/Search")
public RootVo Search(@RequestBody Map<String, Object> map, HttpServletRequest request) {
System.out.println("Vehicle/Search: " + map.toString());
map = userService.getUserIdByRequest(request, map);
// map.put("OrgId", map.get("userId"));
return RootVoUtils.success(carManagement.getCarsListFromMap(map));
}
/**
* 删除车辆
* api/Vehicle/Remove
* 0: "3"
*/
@PostMapping("/Vehicle/Remove")
public RootVo Remove(@RequestBody JSONArray jsonArray, HttpServletRequest request) {
System.out.println("Vehicle/Remove: " + jsonArray);
carManagement.Remove(jsonArray);
return RootVoUtils.success(true);
}
/**
* api/Vehicle/CheckPlateNoOnly
*/
@PostMapping("/Vehicle/CheckPlateNoOnly")
public RootVo CheckPlateNoOnly(@RequestBody Map<String, Object> map, HttpServletRequest request) {
System.out.println("Vehicle/CheckPlateNoOnly: " + map.toString());
return RootVoUtils.success(vehicleService.CheckPlateNoOnly(map));
}
}
| 28.794118
| 102
| 0.683691
|
18833fcc82eb3bd24293c498c7014ee226207628
| 166
|
class SearchResult{
String[] words; // strings matched for this url
String url; // url matching search query
long frequency; //number of hits for page
}
| 33.2
| 51
| 0.692771
|
8f97d1a7cc1ef8debca649e10c8fe94ff47419fb
| 3,403
|
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Copyright (c) 2019, Eldar Timraleev (aka CRaFT4ik).
+
+ 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 ru.er_log.components;
import ru.er_log.utils.Utils;
import java.io.Serializable;
/*
* Describes each field of packet model and a whole packet.
*/
public class eConfig implements IConfig, Serializable
{
public enum fourthLevelPackages implements Serializable
{ TCP, UDP, ICMP }
private eEthernetConfig ethernetConfig;
private eIPv4Config ipv4Config;
private eTCPConfig tcpConfig;
private eUDPConfig udpConfig;
private eICMPConfig icmpConfig;
private fourthLevelPackages selectedType;
private final String createTime;
public eConfig()
{
this.createTime = Utils.getTime("dd.MM.YY HH:mm:ss");
}
@Override
public String toString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(createTime).append(": ");
if (ethernetConfig != null) stringBuilder.append("Eth ");
if (ipv4Config != null) stringBuilder.append("IPv4 ");
if (tcpConfig != null && selectedType == fourthLevelPackages.TCP) stringBuilder.append("TCP ");
else if (udpConfig != null && selectedType == fourthLevelPackages.UDP) stringBuilder.append("UDP ");
else if (icmpConfig != null && selectedType == fourthLevelPackages.ICMP) stringBuilder.append("ICMP ");
return stringBuilder.toString();
}
public fourthLevelPackages getSelectedType()
{
return selectedType;
}
public eConfig setSelectedType(fourthLevelPackages selectedTabId)
{
this.selectedType = selectedTabId;
return this;
}
public eEthernetConfig getEthernetConfig()
{
return ethernetConfig;
}
public eConfig setEthernetConfig(eEthernetConfig ethernetConfig)
{
this.ethernetConfig = ethernetConfig;
return this;
}
public eIPv4Config getIpv4Config()
{
return ipv4Config;
}
public eConfig setIpv4Config(eIPv4Config ipv4Config)
{
this.ipv4Config = ipv4Config;
return this;
}
public eTCPConfig getTcpConfig()
{
return tcpConfig;
}
public eConfig setTcpConfig(eTCPConfig tcpConfig)
{
this.tcpConfig = tcpConfig;
return this;
}
public eUDPConfig getUdpConfig()
{
return udpConfig;
}
public eConfig setUdpConfig(eUDPConfig udpConfig)
{
this.udpConfig = udpConfig;
return this;
}
public eICMPConfig getIcmpConfig()
{
return icmpConfig;
}
public eConfig setIcmpConfig(eICMPConfig icmpConfig)
{
this.icmpConfig = icmpConfig;
return this;
}
}
| 26.795276
| 111
| 0.642962
|
5027e372fd9b2e53729f888abbec45a8bf35bcfe
| 1,080
|
/* DungeonDiver4: A Dungeon-Solving Game
Copyright (C) 2008-2010 Eric Ahnell
Any questions should be directed to the author via email at: DungeonDiver4@worldwizard.net
*/
package com.puttysoftware.dungeondiver4.dungeon.objects;
import com.puttysoftware.dungeondiver4.dungeon.abc.AbstractBow;
import com.puttysoftware.dungeondiver4.dungeon.utilities.ArrowTypeConstants;
import com.puttysoftware.dungeondiver4.dungeon.utilities.ColorConstants;
public class FireBow extends AbstractBow {
// Constants
private static final int BOW_USES = 30;
// Constructors
public FireBow() {
super(FireBow.BOW_USES, ArrowTypeConstants.ARROW_TYPE_FIRE,
ColorConstants.COLOR_LIGHT_RED);
}
@Override
public String getName() {
return "Fire Bow";
}
@Override
public String getPluralName() {
return "Fire Bows";
}
@Override
public String getDescription() {
return "Fire Bows allow shooting of Fire Arrows, which burn Barrier Generators upon contact, and do everything normal arrows do.";
}
}
| 29.189189
| 138
| 0.726852
|
7e5c14671b2622230d8e479b91b55aa61f23936c
| 4,597
|
/*
* Open Advancement Question Answering (OAQA) Project Copyright 2016 Carnegie Mellon University
*
* 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 edu.cmu.lti.oaqa.baseqa.passage;
import com.aliasi.chunk.Chunking;
import com.aliasi.sentences.SentenceChunker;
import edu.cmu.lti.oaqa.type.retrieval.Document;
import edu.cmu.lti.oaqa.type.retrieval.Passage;
import edu.cmu.lti.oaqa.util.TypeFactory;
import edu.cmu.lti.oaqa.util.TypeUtil;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.uima.jcas.JCas;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
/**
* A utility class for retrieval related operations.
*
* @author <a href="mailto:ziy@cs.cmu.edu">Zi Yang</a> created on 10/19/14
*/
public class RetrievalUtil {
public static List<Passage> extractSections(JCas jcas, Document doc) {
String uri = doc.getUri();
String docId = doc.getDocId();
String[] sections = doc.getSections().toArray();
String[] sectionLabels = doc.getSectionLabels().toArray();
assert sections.length == sectionLabels.length;
return IntStream.range(0, sections.length).mapToObj(i -> {
String t = sections[i];
String label = sectionLabels[i];
return TypeFactory.createPassage(jcas, uri, t, docId, 0, t.length(), label, label);
} ).collect(toList());
}
public static List<Passage> extractSentences(JCas jcas, Passage passage,
SentenceChunker chunker) {
String text = passage.getText();
String uri = passage.getUri();
String docId = passage.getDocId();
String beginSection = passage.getBeginSection();
String endSection = passage.getEndSection();
Chunking chunking = chunker.chunk(text.toCharArray(), 0, text.length());
return chunking.chunkSet().stream().map(chunk -> {
int begin = chunk.start();
int end = chunk.end();
String t = text.substring(begin, end);
return TypeFactory.createPassage(jcas, uri, t, docId, begin, end, beginSection, endSection);
} ).collect(toList());
}
public static List<Passage> extractAbstractSection(JCas jcas, Document doc) {
String uri = doc.getUri();
String docId = doc.getDocId();
String[] sections = doc.getSections().toArray();
String[] sectionLabels = doc.getSectionLabels().toArray();
assert sections.length == sectionLabels.length;
return IntStream.range(0, 1).mapToObj(i -> {
String t = sections[i];
String label = sectionLabels[i];
return TypeFactory.createPassage(jcas, uri, t, docId, 0, t.length(), label, label);
} ).collect(toList());
}
public static org.apache.lucene.document.Document createLuceneDocument(Passage passage) {
org.apache.lucene.document.Document entry = new org.apache.lucene.document.Document();
entry.add(new StoredField("hash", TypeUtil.hash(passage)));
entry.add(new TextField("text", passage.getText(), Field.Store.NO));
return entry;
}
public static org.apache.lucene.document.Document createLuceneSectionDocument(Passage passage) {
org.apache.lucene.document.Document entry = new org.apache.lucene.document.Document();
entry.add(new StoredField("hash", TypeUtil.hash(passage)));
entry.add(new TextField(passage.getBeginSection(), passage.getText(), Field.Store.NO));
return entry;
}
public static List<Passage> extractTitleAbstract(JCas jcas, Document doc) {
String uri = doc.getUri();
String docId = doc.getDocId();
String title = doc.getTitle();
String text = doc.getText();
return extractTitleAbstract(jcas, doc,uri,docId,title,text);
}
public static List<Passage> extractTitleAbstract(JCas jcas, Document doc,String uri,String docId,String title,String text)
{
List<Passage> passages = new ArrayList<>();
if (title != null) {
passages.add(TypeFactory.createPassage(jcas, uri, title, docId, 0, title.length(), "title",
"title"));
}
if (text != null) {
passages.add(TypeFactory.createPassage(jcas, uri, text, docId, 0, text.length(), "abstract",
"abstract"));
}
return passages;
}
}
| 37.373984
| 124
| 0.731782
|
e4e625180f9c933879e07f6ec63de6525f13afbc
| 1,315
|
package com.example.p2pen;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class KeySettingActivity extends AppCompatActivity {
private Button keySetting;
private TextView pubKey;
private Button chatStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_key_setting);
chatStart = (Button) findViewById(R.id.chat_start);
keySetting = (Button) findViewById(R.id.key_set);
pubKey = (TextView) findViewById(R.id.public_key);
keySetting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpRequest.initKeys();
pubKey.setText(HttpRequest.getPublicKey());
}
});
chatStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
startActivity(intent);
}
});
}
}
| 31.309524
| 89
| 0.636502
|
37f9ff95a614e898f35663d0c3f05b7e1f0df894
| 1,697
|
package com.liquidlabs.vso.container;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.liquidlabs.vso.work.InvokableUI;
public interface Consumer {
Metric[] collectMetrics();
int getUsedResourceCount();
/**
* SLA driven release (called from Remove event)
* @param template TODO
*/
List<String> getResourceIdsToRelease(String template, Integer resourcesToFree);
/**
* Called when you are being told either by VScape to release a resource
*/
void take(String requestId, List<String> resourceIds);
/**
* Request for Resources to be released
* Choose (requiredCount) any resourceIds from the given list. The pending
* list is held and once actually released the same resourceIds
* should be returned through getReleasedResources;
* @param requestId TODO
*/
List<String> release(String requestId, List<String> resourceIds, int requiredCount);
/**
* Once the resource is actually free to be removed it is added to this list.
* Each call should clear the consumers free list.
*/
List<String> getReleasedResources();
/**
* Consumer MUST callback onto the addListener.success/fail
*/
void add(String requestId, List<String> resourceIds, AddListener addListener);
void setVariables(Map<String,String> propertyMap);
Set<String> collectResourceIdsForSync();
InvokableUI getUI();
void setInfo(String consumerId, String workIntent, String fullBundleName);
/**
* called every 60 seconds to alloc the consumer to correct its expectations against its vscape allocations (i.e. engines versus resources).
* @param set
*/
void synchronizeResources(Set<String> expectedResourceIds);
int getRunInterval();
}
| 26.107692
| 141
| 0.74779
|
28ac5f8dbf30eeaff92133f463c98f41e43a64fc
| 2,933
|
package org.firstinspires.ftc.teamcode;
//import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.hardware.DcMotor;
@Autonomous(name = "CraterPark", group = "Exercises")
/**
* Created by singh on 10/17/2018.
*/
public class AutoCraterPark extends LinearOpMode{
HardWareInit hardware = new HardWareInit();
@Override
public void runOpMode(){
hardware.initHardware(this);
hardware.leftMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
hardware.rightMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
telemetry.addData("Mode", "waiting");
telemetry.update();
waitForStart();
hardware.EncooderReseeter(this);
//lift goes down
/*hardware.LeftSlideMotor.setPower(.5);
sleep(3000);
hardware.LeftSlideMotor.setPower(0);
1
//robot strafes to get hook off
sleep(500);
hardware.strafeMotor.setPower(0.5);
sleep(2500);
hardware.strafeMotor.setPower(0);
//the lift goes back to its original position
hardware.LeftSlideMotor.setPower(-.5);
sleep(3000);
hardware.LeftSlideMotor.setPower(0);
hardware.GoStraight(3000, 1.0);
hardware.waitBlock(this);
hardware.MotorStop(this);
hardware.EncooderReseeter(this);
//Deploy the color servo. Below is the following mock code required for it to work.
/*
* while(ColorSensor1 = silver && ColorSensor2 = silver){
* robot should raise one arm and turn so that the middle is knocked off
* idle();
*}
*while(ColorSensor1 = Gold){
* robot should turn in that direction to knock it off, opposite if other colorsensor reads gold
*}
* */
/* hardware.Turn(400, .5);
hardware.waitBlock(this);
hardware.MotorStop(this);
hardware.EncooderReseeter(this);
hardware.GoStraight(1000, 1.0);
hardware.waitBlock(this);
hardware.MotorStop(this);
hardware.EncooderReseeter(this);*/
/* hardware.strafeMotor.setPower(-1.0);
sleep(4500);
hardware.strafeMotor.setPower(0);
sleep(50);*/
/* hardware.GoStraight(5000, 1.0);
hardware.waitBlock(this);
hardware.MotorStop(this);
hardware.EncooderReseeter(this);*/
hardware.strafeMotor.setPower(-1.0);
sleep(1000);
hardware.strafeMotor.setPower(0);
sleep(50);
hardware.EncooderReseeter(this);
hardware.Turn(300, 0.5);
hardware.waitBlock(this);
hardware.MotorStop(this);
hardware.GoStraight(-3000, -1.0);
hardware.waitBlock(this);
hardware.MotorStop(this);
hardware.EncooderReseeter(this);
}
}
| 24.441667
| 103
| 0.63314
|
fbc99887f1044ad738cb84e7fddd5c4344f509fc
| 261
|
public class SquareApplication {
public static void main(String[] args) {
double root;
double myroot;
root = 1048576;
myroot = SquareRoot.sqrtRoot(root);
System.out.println("The root is: " + myroot);
}
}
| 26.1
| 54
| 0.574713
|
73b08c5e69c6a482a045e8a6b29db469906ed800
| 2,305
|
package com.bolyartech.forge.server.response.forge;
import java.util.HashMap;
import java.util.Map;
/**
* Class containing basic response codes for Forge endpoints
*/
public class BasicResponseCodes {
/**
* Codes for OK
*/
@SuppressWarnings("SameParameterValue")
public enum Oks implements ForgeResponseCode {
OK(1); // used as general code that indicates success
private final int code;
Oks(int code) {
if (code > 0) {
this.code = code;
} else {
throw new IllegalArgumentException("Code must be positive");
}
}
@Override
public int getCode() {
return code;
}
}
/**
* Codes for errors
*/
public enum Errors implements ForgeResponseCode {
ERROR(-1), // used as general error when we cant/don't want to specify more details
MISSING_PARAMETERS(-2), // missing required parameters
REQUIRES_HTTPS(-3), // HTTPS protocol must be used
INVALID_PARAMETER_VALUE(-4), // parameter value is invalid. For example: string is passed where int is expected
INTERNAL_SERVER_ERROR(-5), // some serious problem occurred on the server
UPGRADE_NEEDED(-6); // client version is too old and unsupported
private static final Map<Integer, Errors> mTypesByValue = new HashMap<>();
static {
for (Errors type : Errors.values()) {
mTypesByValue.put(type.getCode(), type);
}
}
private final int mCode;
Errors(int code) {
if (code < 0) {
this.mCode = code;
} else {
throw new IllegalArgumentException("Code must be negative");
}
}
/**
* Resolves enum value from int value
*
* @param code Integer value of the code
* @return Enum value of the code
*/
public static Errors fromInt(int code) {
Errors ret = mTypesByValue.get(code);
if (ret != null) {
return ret;
} else {
return null;
}
}
@Override
public int getCode() {
return mCode;
}
}
}
| 24.521277
| 119
| 0.545336
|
831c38f7d9386fb3b5d7669883d587d1486c11f1
| 2,251
|
package gov.va.med.imaging.access;
public interface TransactionLogEntry
{
public abstract Long getStartTime();
public abstract Long getElapsedTime();
public abstract String getPatientIcn();
public abstract String getQueryType();
public abstract String getQueryFilter();
public abstract String getCommandClassName();
public abstract Integer getItemCount();
public abstract Long getFacadeBytesSent();
public abstract Long getFacadeBytesReceived();
public abstract Long getDataSourceBytesSent();
public abstract Long getDataSourceBytesReceived();
public abstract String getQuality();
public abstract String getMachineName();
public abstract String getRequestingSite();
public abstract String getOriginatingHost();
public abstract String getUser();
public abstract String getTransactionId();
public abstract String getUrn();
public abstract String getErrorMessage();
public abstract String getModality();
public abstract String getPurposeOfUse();
public abstract String getDatasourceProtocol();
public abstract Boolean isCacheHit();
public abstract String getResponseCode();
public abstract String getExceptionClassName();
public abstract String getRealmSiteNumber();
public abstract Long getTimeToFirstByte();
public abstract String getVixSoftwareVersion();
public abstract String getRespondingSite();
public abstract Integer getDataSourceItemsReceived();
public abstract Boolean isAsynchronousCommand();
public abstract String getCommandId();
public abstract String getParentCommandId();
public abstract String getRemoteLoginMethod();
public abstract String getFacadeImageFormatSent();
public abstract String getFacadeImageQualitySent();
public abstract String getDataSourceImageFormatReceived();
public abstract String getDataSourceImageQualityReceived();
public abstract String getClientVersion();
public abstract String getDataSourceMethod();
public abstract String getDataSourceVersion();
public abstract String getDebugInformation();
public abstract String getDataSourceResponseServer();
public abstract String getThreadId();
public abstract String getVixSiteNumber();
public abstract String getRequestingVixSiteNumber();
}
| 22.969388
| 60
| 0.795646
|
942726c9e804bfa42d18b92faf613216435684f3
| 3,964
|
package edu.perphy.enger;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.tubb.smrv.SwipeMenuRecyclerView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import edu.perphy.enger.adapter.RvAdapterNoteList;
import edu.perphy.enger.thread.ExportNoteTask;
import edu.perphy.enger.thread.ImportNoteTask;
public class NoteListActivity extends AppCompatActivity {
private Context mContext;
public TextView emptyList;
public SwipeMenuRecyclerView rvNoteList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_list);
mContext = this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if (fab != null)
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(mContext, NoteDetailActivity.class));
}
});
emptyList = (TextView) findViewById(R.id.emptyList);
rvNoteList = (SwipeMenuRecyclerView) findViewById(R.id.rvNoteList);
rvNoteList.addItemDecoration(new HorizontalDividerItemDecoration
.Builder(mContext).showLastDivider().build());
rvNoteList.setHasFixedSize(true);
rvNoteList.setLayoutManager(new LinearLayoutManager(mContext));
rvNoteList.setAdapter(new RvAdapterNoteList(mContext));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_note, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_import:
new AlertDialog.Builder(mContext)
.setTitle("Import notes")
.setMessage("This action will discard the note entries in json file " +
"which has identical title with current list. Continue?")
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new ImportNoteTask(mContext).execute();
}
}).setNegativeButton("Cancel", null).show();
return true;
case R.id.action_export:
new ExportNoteTask(mContext).execute();
return true;
case R.id.action_stars:
startActivity(new Intent(mContext, StarActivity.class));
return true;
case R.id.action_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onResume() {
super.onResume();
rvNoteList.setAdapter(new RvAdapterNoteList(mContext));
}
@Override
public void onBackPressed() {
if (!onSupportNavigateUp()) {
super.onBackPressed();
}
}
}
| 37.046729
| 95
| 0.64329
|
9d1b251288e7fe1dbeb9f41033226c5f5e3e91e5
| 2,459
|
package io.reactivex.internal.operators.flowable;
import io.reactivex.Flowable;
import io.reactivex.MaybeObserver;
import io.reactivex.MaybeSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.subscribers.SinglePostCompleteSubscriber;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.Subscriber;
public final class FlowableConcatWithMaybe<T> extends AbstractFlowableWithUpstream<T, T> {
final MaybeSource<? extends T> other;
public FlowableConcatWithMaybe(Flowable<T> flowable, MaybeSource<? extends T> maybeSource) {
super(flowable);
this.other = maybeSource;
}
/* access modifiers changed from: protected */
public void subscribeActual(Subscriber<? super T> subscriber) {
this.source.subscribe(new ConcatWithSubscriber(subscriber, this.other));
}
static final class ConcatWithSubscriber<T> extends SinglePostCompleteSubscriber<T, T> implements MaybeObserver<T> {
private static final long serialVersionUID = -7346385463600070225L;
boolean inMaybe;
MaybeSource<? extends T> other;
final AtomicReference<Disposable> otherDisposable = new AtomicReference<>();
ConcatWithSubscriber(Subscriber<? super T> subscriber, MaybeSource<? extends T> maybeSource) {
super(subscriber);
this.other = maybeSource;
}
public void onSubscribe(Disposable disposable) {
DisposableHelper.setOnce(this.otherDisposable, disposable);
}
public void onNext(T t) {
this.produced++;
this.downstream.onNext(t);
}
public void onError(Throwable th) {
this.downstream.onError(th);
}
public void onSuccess(T t) {
complete(t);
}
public void onComplete() {
if (this.inMaybe) {
this.downstream.onComplete();
return;
}
this.inMaybe = true;
this.upstream = SubscriptionHelper.CANCELLED;
MaybeSource<? extends T> maybeSource = this.other;
this.other = null;
maybeSource.subscribe(this);
}
public void cancel() {
super.cancel();
DisposableHelper.dispose(this.otherDisposable);
}
}
}
| 34.152778
| 119
| 0.663684
|
dd8577584a6aa90f407b5b32cba92c2faa82ed1e
| 2,598
|
package com.xieh.security;
import com.xieh.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.Filter;
/**
* @program security-oauth2
* @description: 资源服务器
* @author: Horng
* @create: 2018/11/24 21:31
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "my_rest_api";
@Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Autowired
private MyAuthenticationFailHandler myAuthenticationFailHandler;
@Autowired
private MyLogoutSuccessHandler myLogoutSuccessHandler;
@Autowired
private CustomAccessDeniedHandler customAccessDeniedHandler;
@Autowired
private Filter permitAuthenticationFilter;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
resources.authenticationEntryPoint(new AuthExceptionEntryPoint())//自定义授权失败处理器
.accessDeniedHandler(customAccessDeniedHandler);//自定义的什么处理器 好像无效
}
@Override
public void configure(HttpSecurity http) throws Exception {
//http.exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint());
http.formLogin()
.loginProcessingUrl("/login/token")
.successHandler(myAuthenticationSuccessHandler)
.failureHandler(myAuthenticationFailHandler)
.and().logout().logoutUrl("/login/out")
.logoutSuccessHandler(myLogoutSuccessHandler)
.and().anonymous().disable()
.requestMatchers().antMatchers("/**")
.and().authorizeRequests()
.antMatchers("/user*/**","/login/out").permitAll()
// configure 上面也有一个 customAccessDeniedHandler 暂时这样把
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler())
.authenticationEntryPoint(new AuthExceptionEntryPoint()) //给上面一样
.and().addFilterBefore(permitAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);
}
}
| 41.238095
| 111
| 0.827175
|
acb06070ffa173a5136d5e1f44eec346f0cbfa0e
| 1,418
|
package org.bouncycastle.tls.crypto.impl.jcajce;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import org.bouncycastle.tls.crypto.TlsAgreement;
import org.bouncycastle.tls.crypto.TlsSecret;
/**
* Support class for ephemeral Diffie-Hellman using the JCE.
*/
public class JceTlsDH
implements TlsAgreement
{
protected JceTlsDHDomain domain;
protected KeyPair localKeyPair;
protected DHPublicKey peerPublicKey;
public JceTlsDH(JceTlsDHDomain domain)
{
this.domain = domain;
}
public byte[] generateEphemeral() throws IOException
{
this.localKeyPair = domain.generateKeyPair();
return domain.encodePublicKey((DHPublicKey)localKeyPair.getPublic());
}
public void receivePeerValue(byte[] peerValue) throws IOException
{
this.peerPublicKey = domain.decodePublicKey(peerValue);
}
public TlsSecret calculateSecret() throws IOException
{
try
{
byte[] data = domain.calculateDHAgreement(peerPublicKey, (DHPrivateKey)localKeyPair.getPrivate());
return domain.getCrypto().adoptLocalSecret(data);
}
catch (GeneralSecurityException e)
{
throw new IOException("cannot calculate secret", e);
}
}
}
| 27.269231
| 110
| 0.708039
|
3021d47892acaec7674c9a1c429a7ea4e95a910e
| 5,355
|
package jfluentvalidation.validators.rulefor.bigdecimals;
import jfluentvalidation.ValidationResult;
import jfluentvalidation.validators.DefaultValidator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.math.BigDecimal;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.TEN;
import static java.math.BigDecimal.ZERO;
import static jfluentvalidation.validators.rulefor.bigdecimals.Constants.FIVE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class IsNotCloseToTest {
@ParameterizedTest
@CsvSource({
"1, 3, 1",
"-1, -3, 1",
"1, -2, 2",
"-1, 2, 2"
})
void shouldNotReturnFailureWhenDifferenceIsGreaterThanOffset(BigDecimal actual, BigDecimal expected, BigDecimal offset) {
Target t = new Target(actual);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(expected, offset, false);
ValidationResult validationResult = validator.validate(t);
assertTrue(validationResult.isValid());
}
@ParameterizedTest
@CsvSource({
"1.0, 0.0, 1.0",
"-1.0, 0.0, 1.0",
"-1.0, 1.0, 2.0"
})
void shouldNotReturnFailureWhenDifferenceIsEqualToStrictOffset(BigDecimal actual, BigDecimal expected, BigDecimal offsetValue) {
Target t = new Target(actual);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(expected, offsetValue, true);
ValidationResult validationResult = validator.validate(t);
assertTrue(validationResult.isValid());
}
@Test
void shouldReturnFailureWhenDifferenceIsLessThanOffset() {
Target t = new Target(FIVE);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(ONE, TEN, false);
ValidationResult validationResult = validator.validate(t);
assertFalse(validationResult.isValid());
}
@Test
void shouldReturnFailureWhenDifferenceIsLessThanStrictOffset() {
Target t = new Target(FIVE);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(ONE, TEN, true);
ValidationResult validationResult = validator.validate(t);
assertFalse(validationResult.isValid());
}
@ParameterizedTest
@CsvSource({
"1.0, 1.0, 0.0",
"1.0, 0.0, 1.0",
"-1.0, 0.0, 1.0",
"-1.0, -1.0, 0.0",
"-1.0, 1.0, 2.0"
})
void shouldReturnFailureWhenDifferenceIsEqualToOffset(BigDecimal actual, BigDecimal expected, BigDecimal offsetValue) {
Target t = new Target(actual);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(expected, offsetValue, false);
ValidationResult validationResult = validator.validate(t);
assertFalse(validationResult.isValid());
}
@Test
void shouldNotThrowWhenActualIsNull() {
Target t = new Target(null);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(ZERO, ONE, false);
ValidationResult validationResult = validator.validate(t);
assertTrue(validationResult.isValid());
}
@Test
void shouldThrowWhenExpectedIsNull() {
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
assertThrows(NullPointerException.class, () -> validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(null, ONE, false));
}
@Test
void shouldThrowWhenOffsetIsNull() {
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
assertThrows(NullPointerException.class, () -> validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(ZERO, null, false));
}
@Test
void shouldHaveAppropriateErrorMessage() {
Target t = new Target(ONE);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(ZERO, ONE, false);
ValidationResult validationResult = validator.validate(t);
assertEquals("number must not be close to 0 by less than 1.", validationResult.getViolations().get(0).getErrorMessage());
}
@Test
void shouldHaveAppropriateErrorMessageForStrictOffset() {
Target t = new Target(ONE);
DefaultValidator<Target> validator = new DefaultValidator<>(Target.class);
validator.ruleForBigDecimal(Target::getNumber).isNotCloseTo(FIVE, TEN, true);
ValidationResult validationResult = validator.validate(t);
assertEquals("number must not be close to 5 by strictly less than 10.", validationResult.getViolations().get(0).getErrorMessage());
}
}
| 35.939597
| 139
| 0.70887
|
4ecc1f8cbf0ed7f9110000252ce9333c9c68bcec
| 977
|
package com.g_node.gca.abstracts.pojo;
public class AbstractAffiliationIdPosition {
private String Abstract_UUID;
private String Affiliation_UUID;
private int Affiliation_position;
public AbstractAffiliationIdPosition(String abstract_UUID,
String affiliation_UUID, int affiliation_position) {
super();
Abstract_UUID = abstract_UUID;
Affiliation_UUID = affiliation_UUID;
Affiliation_position = affiliation_position;
}
public String getAbstract_UUID() {
return Abstract_UUID;
}
public void setAbstract_UUID(String abstract_UUID) {
Abstract_UUID = abstract_UUID;
}
public String getAffiliation_UUID() {
return Affiliation_UUID;
}
public void setAffiliation_UUID(String affiliation_UUID) {
Affiliation_UUID = affiliation_UUID;
}
public int getAffiliation_position() {
return Affiliation_position;
}
public void setAffiliation_position(int affiliation_position) {
Affiliation_position = affiliation_position;
}
}
| 17.140351
| 64
| 0.785056
|
82b99abc129c10f6e2e6c5dcb65fc8e9e60ef3b5
| 4,075
|
/*
Copyright (c) 2000-2018, Board of Trustees of Leland Stanford Jr. University,
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. 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 org.lockss.tdb;
import java.io.Serializable;
import java.util.*;
/**
* <p>
* A utility class holding the results of parsing TDB files.
* </p>
* <p>
* Currently this class implements the same rudimentary behavior that was
* standard in the Python tools -- publishers, titles and AUs are listed in the
* order added (which is also the order parsed), doing no useful processing for
* duplicates if any.
* </p>
*
* @author Thib Guicherd-Callin
* @since 1.67
*/
public class Tdb implements Serializable {
/**
* <p>
* The list of {@link Publisher} instances.
* </p>
*
* @since 1.67
*/
protected List<Publisher> publishers;
/**
* <p>
* The list of {@link Title} instances.
* </p>
*
* @since 1.67
*/
protected List<Title> titles;
/**
* <p>
* The list of {@link Au} instances.
* </p>
*
* @since 1.67
*/
protected List<Au> aus;
/**
* <p>
* Makes a new TDB structure.
* </p>
*
* @since 1.67
*/
public Tdb() {
this.publishers = new ArrayList<Publisher>();
this.titles = new ArrayList<Title>();
this.aus = new ArrayList<Au>();
}
/**
* <p>
* Appends a publisher to the list of publishers.
* </p>
*
* @param publisher
* A publisher.
* @since 1.67
*/
public void addPublisher(Publisher publisher) {
publishers.add(publisher);
}
/**
* <p>
* Appends a title to the list of title.
* </p>
*
* @param title
* A title.
* @since 1.67
*/
public void addTitle(Title title) {
titles.add(title);
}
/**
* <p>
* Appends an AU to the list of AUs.
* </p>
*
* @param au
* An AU.
* @since 1.67
*/
public void addAu(Au au) {
aus.add(au);
}
/**
* <p>
* Gives an unmodifiable view of the list of publishers.
* </p>
*
* @return The list of publishers (unmodifiable).
* @since 1.67
*/
public List<Publisher> getPublishers() {
return Collections.unmodifiableList(publishers);
}
/**
* <p>
* Gives an unmodifiable view of the list of titles.
* </p>
*
* @return The list of titles (unmodifiable).
* @since 1.67
*/
public List<Title> getTitles() {
return Collections.unmodifiableList(titles);
}
/**
* <p>
* Gives an unmodifiable view of the list of AUs.
* </p>
*
* @return The list of AUs (unmodifiable).
* @since 1.67
*/
public List<Au> getAus() {
return Collections.unmodifiableList(aus);
}
}
| 23.970588
| 80
| 0.656933
|
1297fbeb6274253ac62ce7fb895b870f2a055564
| 6,808
|
// Copyright 2020 The Whiley Project Developers
//
// 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 wy2boogie.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import wy2boogie.core.BoogieFile;
import wybs.lang.SyntacticException;
import wyfs.util.ArrayUtils;
/**
* A wrapper for the "boogie" verifier.
*
* @author David J. Pearce
*
*/
public class Boogie {
private static final String BOOGIE_COMMAND = "boogie";
private final String boogieCmd;
/**
* Record command-line options.
*/
public final Map<String,String> options;
public Boogie() {
this(BOOGIE_COMMAND);
}
public Boogie(String command) {
this.boogieCmd = command;
this.options = new HashMap<>();
// Note: we use Z3 array theory, because it handles large arrays much better (like Byte_Valid*.whiley)
this.options.put("useArrayTheory", null);
}
/**
* Control printing of enhanced error messages. If enabled then print Z3 error
* model enhanced error messages.
*
* @param flag
*/
public void setEnhancedErrorMessages(boolean flag) {
options.put("enhancedErrorMessages", flag ? "1":"0");
}
/**
* Limit the number of seconds spent trying to verify each procedure
*
* @param seconds
*/
public void setTimeLimit(int seconds) {
options.put("timeLimit", Integer.toString(seconds));
}
/**
* Check a given filename
*
* @param timeout (in milli seconds)
* @param boogie Boogie contents (as a string)
* @return
*/
public Error[] check(int timeout, BoogieFile boogie) {
String filename = null;
try {
// Determine id for the temporary file. This will help to identified should
// there be a need during debugging.
String id = boogie.getEntry().id().toString();
// Create the temporary file.
filename = createTemporaryFile(id, ".bpl", boogie.getBytes());
// ===================================================
// Construct command
// ===================================================
ArrayList<String> command = new ArrayList<>();
command.add(boogieCmd);
command.add("/nologo");
// Add any registered command-line options
for(Map.Entry<String,String> e : options.entrySet()) {
String opt = e.getKey();
String val = e.getValue();
if(val == null) {
command.add("/" + opt);
} else {
command.add("/" + opt + ":" + val);
}
}
command.add(filename);
// ===================================================
// Construct the process
// ===================================================
ProcessBuilder builder = new ProcessBuilder(command);
Process child = builder.start();
try {
// second, read the result whilst checking for a timeout
InputStream input = child.getInputStream();
InputStream error = child.getErrorStream();
boolean success = child.waitFor(timeout, TimeUnit.MILLISECONDS);
byte[] stdout = readInputStream(input);
byte[] stderr = readInputStream(error);
System.out.println("STDOUT: " + new String(stdout));
System.out.println("STDERR: " + new String(stdout));
if(success && child.exitValue() == 0) {
return parseErrors(new String(stdout));
}
} finally {
// make sure child process is destroyed.
child.destroy();
}
} catch(IOException e) {
throw new RuntimeException(e.getMessage(), e);
} catch(InterruptedException e) {
throw new RuntimeException(e.getMessage(),e);
} finally {
if(filename != null) {
// delete the temporary file
new File(filename).delete();
}
}
return null;
}
public static class Error {
private int line;
private int column;
private String message;
public Error(int line, int col, String message) {
this.line = line;
this.column = col;
this.message = message;
}
/**
* Get the line number of this error.
*
* @return
*/
public int getLine() {
return line;
}
/**
* Get the column number within the given line where this error occurs.
*
* @return
*/
public int getColumn() {
return column;
}
/**
* Get the error message.
* @return
*/
public String getMessage() {
return message;
}
@Override
public String toString() {
return Integer.toString(line) + ":" + column + ":" + message;
}
}
/**
* Parse Standard Output from Boogie into a useful form.
*
* @param output
* @return
*/
private static Error[] parseErrors(String output) {
String[] lines = output.split("\n");
Error[] errors = new Error[lines.length];
for (int i = 0; i != lines.length; ++i) {
// Decode boogie error line
String ith = lines[i];
if(ith.startsWith("Fatal Error:")) {
errors[i] = new Error(0,0,ith);
break;
} else {
int a = ith.indexOf('(');
int b = ith.indexOf(',');
int c = ith.indexOf(')');
int d = ith.indexOf(':');
if (a >= 0 && b >= 0 && c >= 0 && d >= 0) {
int line = Integer.parseInt(ith.substring(a + 1, b));
int col = Integer.parseInt(ith.substring(b + 1, c));
String message = ith.substring(d + 1);
errors[i] = new Error(line, col, message);
}
}
}
return ArrayUtils.removeAll(errors,null);
}
/**
* Write a given string into a temporary file which can then be checked by
* boogie.
*
* @param contents
* @return
*/
private static String createTemporaryFile(String prefix, String suffix, byte[] contents)
throws IOException, InterruptedException {
// Create new file
File f = File.createTempFile(prefix, suffix);
// Open for writing
FileOutputStream fout = new FileOutputStream(f);
// Write contents to file
fout.write(contents);
// Done creating file
fout.close();
//
return f.getAbsolutePath();
}
/**
* Read an input stream entirely into a byte array.
*
* @param input
* @return
* @throws IOException
*/
private static byte[] readInputStream(InputStream input) throws IOException {
byte[] buffer = new byte[1024];
ByteArrayOutputStream output = new ByteArrayOutputStream();
while (input.available() > 0) {
int count = input.read(buffer);
output.write(buffer, 0, count);
}
return output.toByteArray();
}
}
| 26.698039
| 104
| 0.641745
|
21e9afd30e5eb839f78d70c7f4dc5345beea893c
| 2,082
|
package com.implisense.ecep.api.sandbox;
import com.google.common.base.Charsets;
import com.google.common.collect.Multiset;
import com.google.common.collect.TreeMultiset;
import com.implisense.ecep.api.data.CompaniesHouseFormatParser;
import com.implisense.ecep.api.data.Sic03ToSic07Converter;
import com.implisense.ecep.index.model.Company;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Set;
import static java.util.stream.Collectors.summingInt;
import static java.util.stream.Collectors.toSet;
public class SicCodeLengthDistributionTester {
public static void main(String[] args) throws IOException {
File dir = new File("/home/hkorte/Projects/ECEP");
Sic03ToSic07Converter sic03ToSic07Converter = new Sic03ToSic07Converter();
CompaniesHouseFormatParser parser = new CompaniesHouseFormatParser(sic03ToSic07Converter);
Multiset<Integer> lengthDistribution = TreeMultiset.create();
for (int i = 1; i <= 5; i++) {
File file = new File(dir, "BasicCompanyData-2016-06-01-part" + i + "_5.csv");
System.out.println("File: " + file.getName());
for (Company company : parser.iterateCompanies(Files.readAllBytes(file.toPath()), Charsets.US_ASCII)) {
Set<Integer> lengths = company.getSicCodes().stream().map(String::length).collect(toSet());
// if (lengths.size() > 1) {
// System.out.println("different sic versions for the same company: " + company.getId()
// + " -> " + lengths);
// }
if (lengths.isEmpty()) {
lengthDistribution.add(-1);
} else {
lengthDistribution.add(lengths.stream().collect(summingInt(v -> v.intValue())));
}
}
}
System.out.println("Lengths:");
for (Multiset.Entry<Integer> entry : lengthDistribution.entrySet()) {
System.out.printf("%3d %10d\n", entry.getElement(), entry.getCount());
}
}
}
| 43.375
| 115
| 0.642651
|
830dde42b1020e180788abe98c648bc925e73972
| 6,492
|
package com.monnet.versionnumber;
import org.testng.Assert;
import org.testng.annotations.Test;
public class VersionNumberTest {
@Test
public void testVersionNumber_compareTo_lessThan_equalVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.1");
final VersionNumber targetVersionNumber = new VersionNumber("2.2");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, -1);
}
@Test
public void testVersionNumber_compareTo_greaterThan_equalVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2");
final VersionNumber targetVersionNumber = new VersionNumber("2.1");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 1);
}
@Test
public void testVersionNumber_compareTo_equalTo_equalVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2");
final VersionNumber targetVersionNumber = new VersionNumber("2.2");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 0);
}
@Test
public void testVersionNumber_compareTo_lessThan_moreSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.1.1");
final VersionNumber targetVersionNumber = new VersionNumber("2.2");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, -1);
}
@Test
public void testVersionNumber_compareTo_greaterThan_moreSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2.2");
final VersionNumber targetVersionNumber = new VersionNumber("2.1");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 1);
}
@Test
public void testVersionNumber_compareTo_equalTo_moreSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2.0");
final VersionNumber targetVersionNumber = new VersionNumber("2.2");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 0);
}
@Test
public void testVersionNumber_compareTo_lessThan_lessSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.1");
final VersionNumber targetVersionNumber = new VersionNumber("2.2.2");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, -1);
}
@Test
public void testVersionNumber_compareTo_greaterThan_lessSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2");
final VersionNumber targetVersionNumber = new VersionNumber("2.1.1");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 1);
}
@Test
public void testVersionNumber_compareTo_equalTo_lessSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2");
final VersionNumber targetVersionNumber = new VersionNumber("2.2.0");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 0);
}
@Test
public void testVersionNumber_compareTo_lessThan_extraIntermediateSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.0001.0");
final VersionNumber targetVersionNumber = new VersionNumber("2.2.2");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, -1);
}
@Test
public void testVersionNumber_compareTo_greaterThan_extraIntermediateSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2.000000.2");
final VersionNumber targetVersionNumber = new VersionNumber("2.2.0.1");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 1);
}
@Test
public void testVersionNumber_compareTo_equalTo_extraIntermediateSourceVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.0002.00000000");
final VersionNumber targetVersionNumber = new VersionNumber("2.2.0");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 0);
}
@Test
public void testVersionNumber_compareTo_lessThan_extraIntermediateTargetVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.1.0");
final VersionNumber targetVersionNumber = new VersionNumber("2.0001.0000.2");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, -1);
}
@Test
public void testVersionNumber_compareTo_greaterThan_extraIntermediateTargetVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2.0.2");
final VersionNumber targetVersionNumber = new VersionNumber("2.0002.00000.1");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 1);
}
@Test
public void testVersionNumber_compareTo_equalTo_extraIntermediateTargetVersionIdentifierFields() {
final VersionNumber sourceVersionNumber = new VersionNumber("2.2.0");
final VersionNumber targetVersionNumber = new VersionNumber("2.0002.000000000");
final int versionNumberComparison = sourceVersionNumber.compareTo(targetVersionNumber);
Assert.assertEquals(versionNumberComparison, 0);
}
}
| 51.52381
| 106
| 0.763401
|
d867e1221b11dfdfe74f988c91643b83707cc4d1
| 2,267
|
package cl.tavor.bancointeligente.activities;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import cl.tavor.bancointeligente.R;
public class DepositsActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deposits);
ImageView imgCash = (ImageView) findViewById(R.id.imageView_cashDeposit);
ImageLoader.getInstance().displayImage("drawable://" + R.drawable.deposit_cash, imgCash);
ImageView imgDocument = (ImageView) findViewById(R.id.imageView_documentDeposit);
ImageLoader.getInstance().displayImage("drawable://" + R.drawable.document_deposit, imgDocument);
CardView buttonCashdeposit = (CardView) findViewById(R.id.cardview_cashDeposit);
buttonCashdeposit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
CardView buttonDocument = (CardView) findViewById(R.id.cardview_documentDeposit);
buttonDocument.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_deposits, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 33.835821
| 105
| 0.696074
|
b3d5fd9cdeaa8cd24f53b8d4a9c61d03afc27d69
| 144
|
package org.zstack.header.image;
/**
* Created by GuoYi on 8/16/18.
*/
public enum ImageBootMode {
Legacy,
UEFI,
UEFI_WITH_CSM
}
| 13.090909
| 32
| 0.652778
|
e3d747be0cf75ad804cf3288cc1b99f604ead99d
| 3,562
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.db.mysql.nodes;
import org.netbeans.modules.db.mysql.*;
import org.netbeans.modules.db.mysql.actions.ConnectAction;
import org.netbeans.modules.db.mysql.DatabaseServer;
import javax.swing.Action;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.actions.DeleteAction;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.openide.util.actions.SystemAction;
/**
* Represents a database.
*
* @author David Van Couvering
*/
class DatabaseNode extends AbstractNode implements Comparable {
// I'd like a less generic icon, but this is what we have for now...
private static final String ICON_BASE = "org/netbeans/modules/db/mysql/resources/database.gif";
private final Database model;
public DatabaseNode(Database model) {
super(Children.LEAF);
this.model = model;
setDisplayName(model.getDisplayName());
setShortDescription(model.getShortDescription());
setIconBaseWithExtension(ICON_BASE);
}
@Override
public Action[] getActions(boolean context) {
if ( context ) {
return super.getActions(context);
} else {
return new SystemAction[] {
SystemAction.get(ConnectAction.class),
SystemAction.get(DeleteAction.class)
};
}
}
@Override
public boolean canDestroy() {
return true;
}
@NbBundle.Messages({
"# {0} - Database name",
"MSG_Confirm_DB_Delete=Really delete database {0}?",
"MSG_Confirm_DB_Delete_Title=Delete Database"})
@Override
public void destroy() {
NotifyDescriptor d =
new NotifyDescriptor.Confirmation(
Bundle.MSG_Confirm_DB_Delete(model.getDbName()),
Bundle.MSG_Confirm_DB_Delete_Title(),
NotifyDescriptor.YES_NO_OPTION);
Object result = DialogDisplayer.getDefault().notify(d);
if (!NotifyDescriptor.OK_OPTION.equals(result)) {
return;
}
DatabaseServer server = model.getServer();
String dbname = model.getDbName();
server.dropDatabase(dbname);
}
@Override
@SuppressWarnings("unchecked")
public Node.Cookie getCookie(Class cls) {
if ( cls == Database.class ) {
return model;
} else {
return super.getCookie(cls);
}
}
public int compareTo(Object other) {
Node othernode = (Node)other;
return this.getDisplayName().compareTo(othernode.getDisplayName());
}
}
| 31.803571
| 99
| 0.664234
|
001336edf7e5358be8ec0ffede8069e47757cd80
| 288
|
package com.piekoszek.nowaksharedrent.jwt.exceptions;
public class InvalidTokenException extends RuntimeException {
public InvalidTokenException() {
super("Provided token is invalid");
}
public InvalidTokenException(String message) {
super(message);
}
}
| 24
| 61
| 0.722222
|
e712f20b948f4d9a6032d9bc77103dc2803940f7
| 229
|
package perobobbot.lang;
public interface GatewayChannels {
String PLATFORM_MESSAGES = "chatChannel";
String EVENT_MESSAGES = "eventChannel";
String PLATFORM_NOTIFICATION_MESSAGES = "platformNotificationChannel";
}
| 25.444444
| 74
| 0.786026
|
bd11ae0d3561800f7747b6e181a3fbf54a7a1378
| 1,487
|
package com.example.caikeplan.activity;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.base.AndroidBug5497Workaround;
import com.example.caikeplan.R;
import com.example.util.Util;
import com.readystatesoftware.systembartint.SystemBarTintManager;
/**
* Created by dell on 2017/6/6.
*/
public class BaseActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
public void setView(int layoutID) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().getDecorView().setFitsSystemWindows(true);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
/*getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
setContentView(layoutID);
}
}
| 33.044444
| 93
| 0.756557
|
0c78d24be87f43770f14e2e25199324e680a6130
| 2,801
|
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.adempiere.apps.graph;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.compiere.Adempiere;
import org.compiere.apps.AEnv;
import org.compiere.apps.ConfirmPanel;
import org.compiere.model.MGoal;
import org.compiere.swing.CFrame;
/**
* Performance Detail Frame.
* BarPanel for Drill-Down
*
* @author Jorg Janke
* @version $Id: PerformanceDetail.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $
*/
public class PerformanceDetail extends CFrame
implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = -5994488373513922522L;
/**
* Constructor.
* Called from PAPanel, ViewPI (Performance Indicator)
* @param goal goal
*/
public PerformanceDetail (MGoal goal)
{
super (goal.getName());
setIconImage(Adempiere.getProductIconSmall());
barPanel = new Graph(goal, true);
init();
AEnv.addToWindowManager(this);
AEnv.showCenterScreen(this);
} // PerformanceDetail
Graph barPanel = null;
ConfirmPanel confirmPanel = ConfirmPanel.newWithOK();
/**
* Static init
*/
private void init()
{
getContentPane().add(barPanel, BorderLayout.CENTER);
getContentPane().add(confirmPanel, BorderLayout.SOUTH);
confirmPanel.setActionListener(this);
} // init
/**
* Action Listener
* @param e event
*/
@Override
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
dispose();
} // actionPerformed
} // PerformanceDetail
| 32.952941
| 79
| 0.656551
|
4f96074130bb02ba9dbbf79cefeb30c98d12f453
| 352
|
/*
* 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 brightstar;
public class loginRecord {
public String userName;
public String time;
public String date;
public String status;
}
| 20.705882
| 79
| 0.698864
|
e5b03bb7ac0ee95f43e84b1cd3ad1454603922df
| 716
|
package ggc.app.lookups;
/**
* Messages.
*/
interface Message {
/** @return string prompting for product identifier */
static String requestProductKey() {
return "Identificador do produto: ";
}
/** @return string prompting for a partner identifier. */
static String requestPartnerKey() {
return "Identificador do parceiro: ";
}
/** @return string prompting for identifier */
static String requestTransactionKey() {
return "Identificador da transacção: ";
}
/** @return string prompting for a price. */
static String requestPriceLimit() {
return "Preço: ";
}
/** @return string prompting for a delay. */
static String requestDelay() {
return "Atraso: ";
}
}
| 21.058824
| 59
| 0.664804
|
13722f5f9dcfb9ed6a40c2c97dd23e4f30aa7604
| 735
|
package com.abubusoft.kripton.processor.bind.transform.util;
import com.abubusoft.kripton.common.Pair;
import com.abubusoft.kripton.processor.bind.transform.BindTransform;
import com.google.common.collect.Lists;
import java.util.*;
import static com.abubusoft.kripton.common.Pair.of;
public abstract class UtilsTransformations {
public static final List<Pair<Class<?>, Class<? extends BindTransform>>> transformations = Lists.newArrayList(
of(Date.class, DateBindTransform.class),
of(Locale.class, LocaleBindTransform.class),
of(Currency.class, CurrencyBindTransform.class),
of(Calendar.class, CalendarBindTransform.class),
of(TimeZone.class, TimeZoneBindTransform.class)
);
}
| 36.75
| 112
| 0.756463
|
bec2581a77cb85040d3be12f84f5a98f74d81411
| 179
|
package potato.skyus.dotcontacts;
import java.util.ArrayList;
public class Contact
{
String displayName;
ArrayList<String> phoneNumbers;
ArrayList<String> emails;
}
| 16.272727
| 35
| 0.75419
|
a3d4678d01c7a685e42a08650880f8ab1e5bc4ed
| 2,338
|
package com.ailiwean.core.view.style1;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.ailiwean.core.view.ScanLightViewCallBack;
import com.google.android.cameraview.R;
/***
* Created by SWY
* DATE 2019/6/23
*
*/
public class ScanLightView extends FrameLayout implements ScanLightViewCallBack {
private TextView tv;
private ImageView iv;
private boolean isOpen;
Runnable open;
Runnable close;
public ScanLightView(Context context) {
super(context);
initView();
}
public ScanLightView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public ScanLightView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
View v = LayoutInflater.from(getContext()).inflate(R.layout.light_layout, null);
iv = v.findViewById(R.id.light_img);
tv = v.findViewById(R.id.light_text);
addView(v);
setOnClickListener(v1 -> toggle());
setVisibility(View.GONE);
}
public void toggle() {
if (tv.getText().equals("轻触照亮"))
open();
else close();
}
private void open() {
if (open != null)
open.run();
isOpen = true;
tv.setText("轻触关闭");
iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.light_open));
}
private void close() {
if (close != null)
close.run();
isOpen = false;
tv.setText("轻触照亮");
iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.light_close));
}
@Override
public void lightBrighter() {
setVisibility(View.VISIBLE);
}
@Override
public void lightDark() {
if (!isOpen)
setVisibility(View.GONE);
}
@Override
public void regLightOperator(Runnable open, Runnable close) {
this.open = open;
this.close = close;
}
@Override
public void cameraStartLaterInit() {
close();
setVisibility(View.GONE);
}
}
| 23.38
| 93
| 0.627459
|
c1ab9a154e46e9ee132d53a5433ea870abbdb176
| 660
|
package net.codejava.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.codejava.Model.Today;
import net.codejava.View.TodayRepository;
@Service
public class TodayService {
@Autowired
private TodayRepository repo;
public List<Today> listAll()
{
return repo.findAll();
}
public void save(Today t)
{
repo.save(t);
}
public Today get(Long id)
{
return repo.findById(id).get();
}
public void delete(Long id)
{
repo. deleteById(id);
}
public List<Today> search(String keyword)
{
return repo.search(keyword);
}
}
| 15
| 62
| 0.721212
|
18a2247cf737cb44dbf278d3d1e3d58f62c297c6
| 199
|
package dataProcess.model.modelMapper;
import dataProcess.model.OriginAdult;
public interface OriginAdultMapper {
int insert(OriginAdult record);
int insertSelective(OriginAdult record);
}
| 22.111111
| 44
| 0.80402
|
262477f1f501b8c86d8322ce28159b3cab3edc92
| 1,687
|
package org.minimalj.frontend.impl.vaadin.toolkit;
import java.util.ArrayList;
import java.util.List;
import org.minimalj.frontend.Frontend.Input;
import org.minimalj.frontend.Frontend.InputComponentListener;
import org.minimalj.model.Rendering;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.ItemCaptionGenerator;
public class VaadinComboBox<T> extends ComboBox<T> implements Input<T> {
private static final long serialVersionUID = 1L;
private final List<T> objects;
private T setObject;
public VaadinComboBox(List<T> objects, InputComponentListener listener) {
// setNullSelectionAllowed(true);
this.objects = objects;
updateChoice();
addValueChangeListener(event -> listener.changed(VaadinComboBox.this));
setItemCaptionGenerator(new RenderingItemCaptionGenerator());
}
private void updateChoice() {
if (setObject != null && !objects.contains(setObject)) {
List<T> objects2 = new ArrayList<T>(objects.size() + 1);
objects2.addAll(objects);
objects.add(setObject);
setItems(objects2);
} else {
setItems(objects);
}
}
// Tooltip not yet supported. Maybe easy with ItemDescriptionGenerator
private class RenderingItemCaptionGenerator implements ItemCaptionGenerator<T> {
private static final long serialVersionUID = 1L;
@Override
public String apply(T item) {
return Rendering.toString(item);
}
}
@Override
public void setValue(T object) {
if (setObject != null && !setObject.equals(object) || setObject == null && object != null) {
this.setObject = (T) object;
updateChoice();
}
super.setValue(object);
}
@Override
public void setEditable(boolean editable) {
super.setEnabled(editable);
}
}
| 26.359375
| 94
| 0.744517
|
7273bc721fad421c30ead4ae49c165e7e49c8b6d
| 2,670
|
/**
*/
package CIM.IEC61970.SCADA;
import CIM.IEC61970.Core.IdentifiedObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Remote Point</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link CIM.IEC61970.SCADA.RemotePoint#getRemoteUnit <em>Remote Unit</em>}</li>
* </ul>
*
* @see CIM.IEC61970.SCADA.SCADAPackage#getRemotePoint()
* @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='For a RTU remote points correspond to telemetered values or control outputs. Other units (e.g. control centers) usually also contain calculated values.'"
* annotation="http://langdale.com.au/2005/UML Profile\040documentation='For a RTU remote points correspond to telemetered values or control outputs. Other units (e.g. control centers) usually also contain calculated values.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='For a RTU remote points correspond to telemetered values or control outputs. Other units (e.g. control centers) usually also contain calculated values.' Profile\040documentation='For a RTU remote points correspond to telemetered values or control outputs. Other units (e.g. control centers) usually also contain calculated values.'"
* @generated
*/
public interface RemotePoint extends IdentifiedObject {
/**
* Returns the value of the '<em><b>Remote Unit</b></em>' reference.
* It is bidirectional and its opposite is '{@link CIM.IEC61970.SCADA.RemoteUnit#getRemotePoints <em>Remote Points</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Remote Unit</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Remote Unit</em>' reference.
* @see #setRemoteUnit(RemoteUnit)
* @see CIM.IEC61970.SCADA.SCADAPackage#getRemotePoint_RemoteUnit()
* @see CIM.IEC61970.SCADA.RemoteUnit#getRemotePoints
* @model opposite="RemotePoints"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Remote unit this point belongs to.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Remote unit this point belongs to.'"
* @generated
*/
RemoteUnit getRemoteUnit();
/**
* Sets the value of the '{@link CIM.IEC61970.SCADA.RemotePoint#getRemoteUnit <em>Remote Unit</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Remote Unit</em>' reference.
* @see #getRemoteUnit()
* @generated
*/
void setRemoteUnit(RemoteUnit value);
} // RemotePoint
| 46.842105
| 410
| 0.707491
|
68238e03c26295ba001a5e729c5dc41ba51563ea
| 3,743
|
/*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.dbvisitor.transaction;
import net.hasor.dbvisitor.transaction.support.SavepointManager;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
/**
* Connection 引用计数器
* @version : 2014-3-29
* @author 赵永春 (zyc@hasor.net)
*/
class ConnectionHolderImpl implements ConnectionHolder, SavepointManager {
private int referenceCount;
private final DataSource dataSource;
private Connection connection;
ConnectionHolderImpl(final DataSource dataSource) {
this.dataSource = dataSource;
}
/** 增加引用计数,一个因为持有人已被请求 */
public synchronized void requested() {
this.referenceCount++;
}
/** 减少引用计数,一个因为持有人已被释放 */
public synchronized void released() throws SQLException {
this.referenceCount--;
if (!this.isOpen() && this.connection != null) {
try {
this.savepointCounter = 0;
this.connection.close();
} finally {
this.connection = null;
}
}
}
@Override
public int getRefCount() {
return this.referenceCount;
}
/** 获取数据库连接 */
public synchronized Connection getConnection() throws SQLException {
if (!this.isOpen()) {
return null;
}
if (this.connection == null) {
this.connection = this.dataSource.getConnection();
}
return this.connection;
}
/** 则表示当前数据库连接是否被打开,被打开的连接一定有引用 */
public boolean isOpen() {
return this.referenceCount != 0;
}
/** 则表示当前数据库连接是否有被引用 */
public DataSource getDataSource() {
return dataSource;
}
//---------------------------------------------------------------------------Savepoint
private Connection checkConn(final Connection conn) throws SQLException {
if (conn == null) {
throw new SQLException("Connection is null.");
}
return conn;
}
private static final String SAVEPOINT_NAME_PREFIX = "SAVEPOINT_";
private int savepointCounter = 0;
/** 则表示当前数据库连接是否被打开(被打开的连接一定有引用) */
public boolean supportSavepoint() throws SQLException {
Connection conn = this.getConnection();
if (conn == null) {
throw new IllegalStateException("connection is close.");
}
return conn.getMetaData().supportsSavepoints();
}
/** 使用一个全新的名称创建一个保存点 */
public Savepoint createSavepoint() throws SQLException {
Connection conn = this.checkConn(this.getConnection());
this.savepointCounter++;
return conn.setSavepoint(SAVEPOINT_NAME_PREFIX + this.savepointCounter);
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
Connection conn = this.checkConn(this.getConnection());
conn.releaseSavepoint(savepoint);
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
Connection conn = this.checkConn(this.getConnection());
conn.rollback(savepoint);
}
}
| 30.185484
| 90
| 0.636388
|
064633551f75345a25d5a102d0cfe648974b8907
| 2,482
|
//==============================================================================
// WIT-J Java Source File AttBldrCOR.java.
//==============================================================================
package com.ibm.witj;
import static com.ibm.witj.Utility.*;
//==============================================================================
// Class AttBldrCOR
//
// "AttBldr C++ Object Representation"
// A Java representation of a C++ AttBldr.
//
// Class Hierarchy:
//
// PreservedInternal
// JavaAccObjCOR
// AttBldrCOR
//==============================================================================
final class AttBldrCOR extends JavaAccObjCOR
{
//==============================================================================
// Package-Internal Constructor
//==============================================================================
AttBldrCOR (CoordinatorCOR theCoordCOR)
{
createAndStoreCppAttBldr (theCoordCOR);
}
//==============================================================================
// Package-Internal Methods
//==============================================================================
//------------------------------------------------------------------------------
// hasAttFor (scopedAttName)
//
// Returns true, iff the C++ AttBldr that belongs to this AttBldrCOR currently
// owns a C++ Att whose scoped name matches scopedAttName.
//------------------------------------------------------------------------------
native boolean hasAttFor (String scopedAttName);
//------------------------------------------------------------------------------
// getAllAttNames
//
// Returns a String listing the names of all C++ Atts owned by the C++ AttBldr.
//------------------------------------------------------------------------------
native String getAllAttNames ();
//==============================================================================
// Private Methods
//==============================================================================
//------------------------------------------------------------------------------
// createAndStoreCppAttBldr (theCoordCOR).
//
// Creates a new C++ AttBldr and stores its pointer in this AttBldrCOR.
//------------------------------------------------------------------------------
private native void createAndStoreCppAttBldr (CoordinatorCOR theCoordCOR);
//==============================================================================
}
| 35.971014
| 80
| 0.321112
|
05ef038321691adbab36b1765e04c3ec8e9b0ed8
| 16,233
|
package br.com.basis.madre.web.rest;
import br.com.basis.madre.InternacaoApp;
import br.com.basis.madre.domain.TipoDoEventoLeito;
import br.com.basis.madre.repository.TipoDoEventoLeitoRepository;
import br.com.basis.madre.repository.search.TipoDoEventoLeitoSearchRepository;
import br.com.basis.madre.service.TipoDoEventoLeitoService;
import br.com.basis.madre.service.dto.TipoDoEventoLeitoDTO;
import br.com.basis.madre.service.mapper.TipoDoEventoLeitoMapper;
import br.gov.nuvem.comum.microsservico.web.rest.errors.ExceptionTranslator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.List;
import static br.com.basis.madre.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration tests for the {@link TipoDoEventoLeitoResource} REST controller.
*/
@SpringBootTest(classes = InternacaoApp.class)
public class TipoDoEventoLeitoResourceIT {
private static final String DEFAULT_NOME = "AAAAAAAAAA";
private static final String UPDATED_NOME = "BBBBBBBBBB";
@Autowired
private TipoDoEventoLeitoRepository tipoDoEventoLeitoRepository;
@Autowired
private TipoDoEventoLeitoMapper tipoDoEventoLeitoMapper;
@Autowired
private TipoDoEventoLeitoService tipoDoEventoLeitoService;
/**
* This repository is mocked in the br.com.basis.madre.repository.search test package.
*
* @see br.com.basis.madre.repository.search.TipoDoEventoLeitoSearchRepositoryMockConfiguration
*/
@Autowired
private TipoDoEventoLeitoSearchRepository mockTipoDoEventoLeitoSearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restTipoDoEventoLeitoMockMvc;
private TipoDoEventoLeito tipoDoEventoLeito;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final TipoDoEventoLeitoResource tipoDoEventoLeitoResource = new TipoDoEventoLeitoResource(tipoDoEventoLeitoService);
this.restTipoDoEventoLeitoMockMvc = MockMvcBuilders.standaloneSetup(tipoDoEventoLeitoResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static TipoDoEventoLeito createEntity(EntityManager em) {
TipoDoEventoLeito tipoDoEventoLeito = new TipoDoEventoLeito()
.nome(DEFAULT_NOME);
return tipoDoEventoLeito;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static TipoDoEventoLeito createUpdatedEntity(EntityManager em) {
TipoDoEventoLeito tipoDoEventoLeito = new TipoDoEventoLeito()
.nome(UPDATED_NOME);
return tipoDoEventoLeito;
}
@BeforeEach
public void initTest() {
tipoDoEventoLeito = createEntity(em);
}
@Test
@Transactional
public void createTipoDoEventoLeito() throws Exception {
int databaseSizeBeforeCreate = tipoDoEventoLeitoRepository.findAll().size();
// Create the TipoDoEventoLeito
TipoDoEventoLeitoDTO tipoDoEventoLeitoDTO = tipoDoEventoLeitoMapper.toDto(tipoDoEventoLeito);
restTipoDoEventoLeitoMockMvc.perform(post("/api/tipo-do-evento-leitos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipoDoEventoLeitoDTO)))
.andExpect(status().isCreated());
// Validate the TipoDoEventoLeito in the database
List<TipoDoEventoLeito> tipoDoEventoLeitoList = tipoDoEventoLeitoRepository.findAll();
assertThat(tipoDoEventoLeitoList).hasSize(databaseSizeBeforeCreate + 1);
TipoDoEventoLeito testTipoDoEventoLeito = tipoDoEventoLeitoList.get(tipoDoEventoLeitoList.size() - 1);
assertThat(testTipoDoEventoLeito.getNome()).isEqualTo(DEFAULT_NOME);
// Validate the TipoDoEventoLeito in Elasticsearch
verify(mockTipoDoEventoLeitoSearchRepository, times(1)).save(testTipoDoEventoLeito);
}
@Test
@Transactional
public void createTipoDoEventoLeitoWithExistingId() throws Exception {
int databaseSizeBeforeCreate = tipoDoEventoLeitoRepository.findAll().size();
// Create the TipoDoEventoLeito with an existing ID
tipoDoEventoLeito.setId(1L);
TipoDoEventoLeitoDTO tipoDoEventoLeitoDTO = tipoDoEventoLeitoMapper.toDto(tipoDoEventoLeito);
// An entity with an existing ID cannot be created, so this API call must fail
restTipoDoEventoLeitoMockMvc.perform(post("/api/tipo-do-evento-leitos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipoDoEventoLeitoDTO)))
.andExpect(status().isBadRequest());
// Validate the TipoDoEventoLeito in the database
List<TipoDoEventoLeito> tipoDoEventoLeitoList = tipoDoEventoLeitoRepository.findAll();
assertThat(tipoDoEventoLeitoList).hasSize(databaseSizeBeforeCreate);
// Validate the TipoDoEventoLeito in Elasticsearch
verify(mockTipoDoEventoLeitoSearchRepository, times(0)).save(tipoDoEventoLeito);
}
@Test
@Transactional
public void checkNomeIsRequired() throws Exception {
int databaseSizeBeforeTest = tipoDoEventoLeitoRepository.findAll().size();
// set the field null
tipoDoEventoLeito.setNome(null);
// Create the TipoDoEventoLeito, which fails.
TipoDoEventoLeitoDTO tipoDoEventoLeitoDTO = tipoDoEventoLeitoMapper.toDto(tipoDoEventoLeito);
restTipoDoEventoLeitoMockMvc.perform(post("/api/tipo-do-evento-leitos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipoDoEventoLeitoDTO)))
.andExpect(status().isBadRequest());
List<TipoDoEventoLeito> tipoDoEventoLeitoList = tipoDoEventoLeitoRepository.findAll();
assertThat(tipoDoEventoLeitoList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllTipoDoEventoLeitos() throws Exception {
// Initialize the database
tipoDoEventoLeitoRepository.saveAndFlush(tipoDoEventoLeito);
// Get all the tipoDoEventoLeitoList
restTipoDoEventoLeitoMockMvc.perform(get("/api/tipo-do-evento-leitos?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(tipoDoEventoLeito.getId().intValue())))
.andExpect(jsonPath("$.[*].nome").value(hasItem(DEFAULT_NOME)));
}
@Test
@Transactional
public void getTipoDoEventoLeito() throws Exception {
// Initialize the database
tipoDoEventoLeitoRepository.saveAndFlush(tipoDoEventoLeito);
// Get the tipoDoEventoLeito
restTipoDoEventoLeitoMockMvc.perform(get("/api/tipo-do-evento-leitos/{id}", tipoDoEventoLeito.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(tipoDoEventoLeito.getId().intValue()))
.andExpect(jsonPath("$.nome").value(DEFAULT_NOME));
}
@Test
@Transactional
public void getNonExistingTipoDoEventoLeito() throws Exception {
// Get the tipoDoEventoLeito
restTipoDoEventoLeitoMockMvc.perform(get("/api/tipo-do-evento-leitos/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTipoDoEventoLeito() throws Exception {
// Initialize the database
tipoDoEventoLeitoRepository.saveAndFlush(tipoDoEventoLeito);
int databaseSizeBeforeUpdate = tipoDoEventoLeitoRepository.findAll().size();
// Update the tipoDoEventoLeito
TipoDoEventoLeito updatedTipoDoEventoLeito = tipoDoEventoLeitoRepository.findById(tipoDoEventoLeito.getId()).get();
// Disconnect from session so that the updates on updatedTipoDoEventoLeito are not directly saved in db
em.detach(updatedTipoDoEventoLeito);
updatedTipoDoEventoLeito
.nome(UPDATED_NOME);
TipoDoEventoLeitoDTO tipoDoEventoLeitoDTO = tipoDoEventoLeitoMapper.toDto(updatedTipoDoEventoLeito);
restTipoDoEventoLeitoMockMvc.perform(put("/api/tipo-do-evento-leitos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipoDoEventoLeitoDTO)))
.andExpect(status().isOk());
// Validate the TipoDoEventoLeito in the database
List<TipoDoEventoLeito> tipoDoEventoLeitoList = tipoDoEventoLeitoRepository.findAll();
assertThat(tipoDoEventoLeitoList).hasSize(databaseSizeBeforeUpdate);
TipoDoEventoLeito testTipoDoEventoLeito = tipoDoEventoLeitoList.get(tipoDoEventoLeitoList.size() - 1);
assertThat(testTipoDoEventoLeito.getNome()).isEqualTo(UPDATED_NOME);
// Validate the TipoDoEventoLeito in Elasticsearch
verify(mockTipoDoEventoLeitoSearchRepository, times(1)).save(testTipoDoEventoLeito);
}
@Test
@Transactional
public void updateNonExistingTipoDoEventoLeito() throws Exception {
int databaseSizeBeforeUpdate = tipoDoEventoLeitoRepository.findAll().size();
// Create the TipoDoEventoLeito
TipoDoEventoLeitoDTO tipoDoEventoLeitoDTO = tipoDoEventoLeitoMapper.toDto(tipoDoEventoLeito);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restTipoDoEventoLeitoMockMvc.perform(put("/api/tipo-do-evento-leitos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipoDoEventoLeitoDTO)))
.andExpect(status().isBadRequest());
// Validate the TipoDoEventoLeito in the database
List<TipoDoEventoLeito> tipoDoEventoLeitoList = tipoDoEventoLeitoRepository.findAll();
assertThat(tipoDoEventoLeitoList).hasSize(databaseSizeBeforeUpdate);
// Validate the TipoDoEventoLeito in Elasticsearch
verify(mockTipoDoEventoLeitoSearchRepository, times(0)).save(tipoDoEventoLeito);
}
@Test
@Transactional
public void deleteTipoDoEventoLeito() throws Exception {
// Initialize the database
tipoDoEventoLeitoRepository.saveAndFlush(tipoDoEventoLeito);
int databaseSizeBeforeDelete = tipoDoEventoLeitoRepository.findAll().size();
// Delete the tipoDoEventoLeito
restTipoDoEventoLeitoMockMvc.perform(delete("/api/tipo-do-evento-leitos/{id}", tipoDoEventoLeito.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<TipoDoEventoLeito> tipoDoEventoLeitoList = tipoDoEventoLeitoRepository.findAll();
assertThat(tipoDoEventoLeitoList).hasSize(databaseSizeBeforeDelete - 1);
// Validate the TipoDoEventoLeito in Elasticsearch
verify(mockTipoDoEventoLeitoSearchRepository, times(1)).deleteById(tipoDoEventoLeito.getId());
}
@Test
@Transactional
public void searchTipoDoEventoLeito() throws Exception {
// Initialize the database
tipoDoEventoLeitoRepository.saveAndFlush(tipoDoEventoLeito);
when(mockTipoDoEventoLeitoSearchRepository.search(queryStringQuery("id:" + tipoDoEventoLeito.getId()), PageRequest.of(0, 20)))
.thenReturn(new PageImpl<>(Collections.singletonList(tipoDoEventoLeito), PageRequest.of(0, 1), 1));
// Search the tipoDoEventoLeito
restTipoDoEventoLeitoMockMvc.perform(get("/api/_search/tipo-do-evento-leitos?query=id:" + tipoDoEventoLeito.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(tipoDoEventoLeito.getId().intValue())))
.andExpect(jsonPath("$.[*].nome").value(hasItem(DEFAULT_NOME)));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(TipoDoEventoLeito.class);
TipoDoEventoLeito tipoDoEventoLeito1 = new TipoDoEventoLeito();
tipoDoEventoLeito1.setId(1L);
TipoDoEventoLeito tipoDoEventoLeito2 = new TipoDoEventoLeito();
tipoDoEventoLeito2.setId(tipoDoEventoLeito1.getId());
assertThat(tipoDoEventoLeito1).isEqualTo(tipoDoEventoLeito2);
tipoDoEventoLeito2.setId(2L);
assertThat(tipoDoEventoLeito1).isNotEqualTo(tipoDoEventoLeito2);
tipoDoEventoLeito1.setId(null);
assertThat(tipoDoEventoLeito1).isNotEqualTo(tipoDoEventoLeito2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(TipoDoEventoLeitoDTO.class);
TipoDoEventoLeitoDTO tipoDoEventoLeitoDTO1 = new TipoDoEventoLeitoDTO();
tipoDoEventoLeitoDTO1.setId(1L);
TipoDoEventoLeitoDTO tipoDoEventoLeitoDTO2 = new TipoDoEventoLeitoDTO();
assertThat(tipoDoEventoLeitoDTO1).isNotEqualTo(tipoDoEventoLeitoDTO2);
tipoDoEventoLeitoDTO2.setId(tipoDoEventoLeitoDTO1.getId());
assertThat(tipoDoEventoLeitoDTO1).isEqualTo(tipoDoEventoLeitoDTO2);
tipoDoEventoLeitoDTO2.setId(2L);
assertThat(tipoDoEventoLeitoDTO1).isNotEqualTo(tipoDoEventoLeitoDTO2);
tipoDoEventoLeitoDTO1.setId(null);
assertThat(tipoDoEventoLeitoDTO1).isNotEqualTo(tipoDoEventoLeitoDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(tipoDoEventoLeitoMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(tipoDoEventoLeitoMapper.fromId(null)).isNull();
}
}
| 45.343575
| 134
| 0.747798
|
858e29057d4303d6d381588e73c8e33a8f3cbc12
| 9,533
|
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.rocketmq.store;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.message.MessageDecoder;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.store.config.BrokerRole;
import org.apache.rocketmq.store.config.FlushDiskType;
import org.apache.rocketmq.store.config.MessageStoreConfig;
import org.apache.rocketmq.store.stats.BrokerStatsManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
/**
* HATest
*
*/
public class HATest {
private final String StoreMessage = "Once, there was a chance for me!";
private int QUEUE_TOTAL = 100;
private AtomicInteger QueueId = new AtomicInteger(0);
private SocketAddress BornHost;
private SocketAddress StoreHost;
private byte[] MessageBody;
private MessageStore messageStore;
private MessageStore slaveMessageStore;
private MessageStoreConfig masterMessageStoreConfig;
private MessageStoreConfig slaveStoreConfig;
private BrokerStatsManager brokerStatsManager = new BrokerStatsManager("simpleTest");
private String storePathRootParentDir = System.getProperty("user.home") + File.separator +
UUID.randomUUID().toString().replace("-", "");
private String storePathRootDir = storePathRootParentDir + File.separator + "store";
@Before
public void init() throws Exception {
StoreHost = new InetSocketAddress(InetAddress.getLocalHost(), 8123);
BornHost = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0);
masterMessageStoreConfig = new MessageStoreConfig();
masterMessageStoreConfig.setBrokerRole(BrokerRole.SYNC_MASTER);
masterMessageStoreConfig.setStorePathRootDir(storePathRootDir + File.separator + "master");
masterMessageStoreConfig.setStorePathCommitLog(storePathRootDir + File.separator + "master" + File.separator + "commitlog");
buildMessageStoreConfig(masterMessageStoreConfig);
slaveStoreConfig = new MessageStoreConfig();
slaveStoreConfig.setBrokerRole(BrokerRole.SLAVE);
slaveStoreConfig.setStorePathRootDir(storePathRootDir + File.separator + "slave");
slaveStoreConfig.setStorePathCommitLog(storePathRootDir + File.separator + "slave" + File.separator + "commitlog");
slaveStoreConfig.setHaListenPort(10943);
buildMessageStoreConfig(slaveStoreConfig);
messageStore = buildMessageStore(masterMessageStoreConfig, 0L);
slaveMessageStore = buildMessageStore(slaveStoreConfig, 1L);
boolean load = messageStore.load();
boolean slaveLoad = slaveMessageStore.load();
slaveMessageStore.updateHaMasterAddress("127.0.0.1:10912");
assertTrue(load);
assertTrue(slaveLoad);
messageStore.start();
slaveMessageStore.start();
Thread.sleep(6000L);//because the haClient will wait 5s after the first connectMaster failed,sleep 6s
}
@Test
public void testHandleHA() {
long totalMsgs = 10;
QUEUE_TOTAL = 1;
MessageBody = StoreMessage.getBytes();
for (long i = 0; i < totalMsgs; i++) {
messageStore.putMessage(buildMessage());
}
for (int i = 0; i < 100 && isCommitLogAvailable((DefaultMessageStore) messageStore); i++) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
for (int i = 0; i < 100 && isCommitLogAvailable((DefaultMessageStore) slaveMessageStore); i++) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
for (long i = 0; i < totalMsgs; i++) {
GetMessageResult result = slaveMessageStore.getMessage("GROUP_A", "FooBar", 0, i, 1024 * 1024, null);
assertThat(result).isNotNull();
assertTrue(GetMessageStatus.FOUND.equals(result.getStatus()));
result.release();
}
}
@Test
public void testSemiSyncReplica() throws Exception {
long totalMsgs = 5;
QUEUE_TOTAL = 1;
MessageBody = StoreMessage.getBytes();
for (long i = 0; i < totalMsgs; i++) {
MessageExtBrokerInner msg = buildMessage();
CompletableFuture<PutMessageResult> putResultFuture = messageStore.asyncPutMessage(msg);
PutMessageResult result = putResultFuture.get();
assertEquals(PutMessageStatus.PUT_OK, result.getPutMessageStatus());
//message has been replicated to slave's commitLog, but maybe not dispatch to ConsumeQueue yet
//so direct read from commitLog by physical offset
MessageExt slaveMsg = slaveMessageStore.lookMessageByOffset(result.getAppendMessageResult().getWroteOffset());
assertNotNull(slaveMsg);
assertTrue(Arrays.equals(msg.getBody(), slaveMsg.getBody()));
assertEquals(msg.getTopic(), slaveMsg.getTopic());
assertEquals(msg.getTags(), slaveMsg.getTags());
assertEquals(msg.getKeys(), slaveMsg.getKeys());
}
//shutdown slave, putMessage should return FLUSH_SLAVE_TIMEOUT
slaveMessageStore.shutdown();
//wait to let master clean the slave's connection
Thread.sleep(masterMessageStoreConfig.getHaHousekeepingInterval() + 500);
for (long i = 0; i < totalMsgs; i++) {
CompletableFuture<PutMessageResult> putResultFuture = messageStore.asyncPutMessage(buildMessage());
PutMessageResult result = putResultFuture.get();
assertEquals(PutMessageStatus.SLAVE_NOT_AVAILABLE, result.getPutMessageStatus());
}
}
@After
public void destroy() throws Exception {
Thread.sleep(5000L);
slaveMessageStore.shutdown();
slaveMessageStore.destroy();
messageStore.shutdown();
messageStore.destroy();
File file = new File(storePathRootParentDir);
UtilAll.deleteFile(file);
}
private MessageStore buildMessageStore(MessageStoreConfig messageStoreConfig, long brokerId) throws Exception {
BrokerConfig brokerConfig = new BrokerConfig();
brokerConfig.setBrokerId(brokerId);
return new DefaultMessageStore(messageStoreConfig, brokerStatsManager, null, brokerConfig);
}
private void buildMessageStoreConfig(MessageStoreConfig messageStoreConfig) {
messageStoreConfig.setMappedFileSizeCommitLog(1024 * 1024 * 10);
messageStoreConfig.setMappedFileSizeConsumeQueue(1024 * 1024 * 10);
messageStoreConfig.setMaxHashSlotNum(10000);
messageStoreConfig.setMaxIndexNum(100 * 100);
messageStoreConfig.setFlushDiskType(FlushDiskType.SYNC_FLUSH);
messageStoreConfig.setFlushIntervalConsumeQueue(1);
}
private MessageExtBrokerInner buildMessage() {
MessageExtBrokerInner msg = new MessageExtBrokerInner();
msg.setTopic("FooBar");
msg.setTags("TAG1");
msg.setBody(MessageBody);
msg.setKeys(String.valueOf(System.currentTimeMillis()));
msg.setQueueId(Math.abs(QueueId.getAndIncrement()) % QUEUE_TOTAL);
msg.setSysFlag(0);
msg.setBornTimestamp(System.currentTimeMillis());
msg.setStoreHost(StoreHost);
msg.setBornHost(BornHost);
msg.setPropertiesString(MessageDecoder.messageProperties2String(msg.getProperties()));
return msg;
}
private boolean isCommitLogAvailable(DefaultMessageStore store) {
try {
Field serviceField = store.getClass().getDeclaredField("reputMessageService");
serviceField.setAccessible(true);
DefaultMessageStore.ReputMessageService reputService =
(DefaultMessageStore.ReputMessageService) serviceField.get(store);
Method method = DefaultMessageStore.ReputMessageService.class.getDeclaredMethod("isCommitLogAvailable");
method.setAccessible(true);
return (boolean) method.invoke(reputService);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
}
| 44.339535
| 132
| 0.703661
|
79ed373ad00865c6d7b1edea514b1cea0ea49090
| 3,625
|
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Live-Video
* 直播管理API
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.live.model;
import java.util.List;
import java.util.ArrayList;
import com.jdcloud.sdk.service.live.model.PublishDomain;
import com.jdcloud.sdk.service.live.model.PlayDomain;
import com.jdcloud.sdk.service.JdcloudResult;
/**
* 查询指定域名相关信息
*/
public class DescribeLiveDomainDetailResult extends JdcloudResult implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* SourceID
*/
private Long sourceId;
/**
* publishDomains
*/
private List<PublishDomain> publishDomains;
/**
* playDomains
*/
private List<PlayDomain> playDomains;
/**
* get SourceID
*
* @return
*/
public Long getSourceId() {
return sourceId;
}
/**
* set SourceID
*
* @param sourceId
*/
public void setSourceId(Long sourceId) {
this.sourceId = sourceId;
}
/**
* get publishDomains
*
* @return
*/
public List<PublishDomain> getPublishDomains() {
return publishDomains;
}
/**
* set publishDomains
*
* @param publishDomains
*/
public void setPublishDomains(List<PublishDomain> publishDomains) {
this.publishDomains = publishDomains;
}
/**
* get playDomains
*
* @return
*/
public List<PlayDomain> getPlayDomains() {
return playDomains;
}
/**
* set playDomains
*
* @param playDomains
*/
public void setPlayDomains(List<PlayDomain> playDomains) {
this.playDomains = playDomains;
}
/**
* set SourceID
*
* @param sourceId
*/
public DescribeLiveDomainDetailResult sourceId(Long sourceId) {
this.sourceId = sourceId;
return this;
}
/**
* set publishDomains
*
* @param publishDomains
*/
public DescribeLiveDomainDetailResult publishDomains(List<PublishDomain> publishDomains) {
this.publishDomains = publishDomains;
return this;
}
/**
* set playDomains
*
* @param playDomains
*/
public DescribeLiveDomainDetailResult playDomains(List<PlayDomain> playDomains) {
this.playDomains = playDomains;
return this;
}
/**
* add item to publishDomains
*
* @param publishDomain
*/
public void addPublishDomain(PublishDomain publishDomain) {
if (this.publishDomains == null) {
this.publishDomains = new ArrayList<>();
}
this.publishDomains.add(publishDomain);
}
/**
* add item to playDomains
*
* @param playDomain
*/
public void addPlayDomain(PlayDomain playDomain) {
if (this.playDomains == null) {
this.playDomains = new ArrayList<>();
}
this.playDomains.add(playDomain);
}
}
| 21.837349
| 99
| 0.625655
|
c03ac617a431b35154d7da4499b4b26ee077206c
| 197
|
/*
*
*/
package edu.cpp.cs445;
public class Vector3Float {
public float x, y, z;
public Vector3Float(int x, int y, int z){
this.x=x;
this.y=y;
this.z=z;
}
}
| 13.133333
| 45
| 0.522843
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.