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
5e80ed6b4b5345f8416ed9ae7609e386c4c489a6
1,072
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.internal.metadata.core; import java.lang.reflect.Member; /** * An {@code AnnotationProcessingOptions} instance keeps track of annotations which should be ignored as configuration source. * The main validation source for Bean Validation is annotation and alternate configuration sources use this class * to override/ignore existing annotations. * * @author Hardy Ferentschik */ public interface AnnotationProcessingOptions { boolean areClassLevelConstraintsIgnoredFor(Class<?> clazz); boolean areMemberConstraintsIgnoredFor(Member member); boolean areReturnValueConstraintsIgnoredFor(Member member); boolean areCrossParameterConstraintsIgnoredFor(Member member); boolean areParameterConstraintsIgnoredFor(Member member, int index); void merge(AnnotationProcessingOptions annotationProcessingOptions); }
34.580645
127
0.810634
3d3b9b99fd657a706e1561ca8c33a5a80d71b99b
6,648
/** * Copyright Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.azure.storage.file; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Stack; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.microsoft.azure.storage.Constants; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.core.ListResponse; import com.microsoft.azure.storage.core.SR; import com.microsoft.azure.storage.core.Utility; /** * RESERVED FOR INTERNAL USE. A class used to deserialize a list of shares. */ final class ShareListHandler extends DefaultHandler { private final Stack<String> elementStack = new Stack<String>(); private StringBuilder bld = new StringBuilder(); private final CloudFileClient serviceClient; private final ListResponse<CloudFileShare> response = new ListResponse<CloudFileShare>(); private FileShareAttributes attributes; private String shareName; private String snapshotID; private ShareListHandler(CloudFileClient serviceClient) { this.serviceClient = serviceClient; } /** * Parses a {@link ShareListResponse} form the given XML stream. * * @param serviceClient * a reference to the client object associated with this object. * @param stream * the stream from which to parse the share list * @throws SAXException * @throws ParserConfigurationException * @throws IOException */ protected static ListResponse<CloudFileShare> getShareList(final InputStream stream, final CloudFileClient serviceClient) throws ParserConfigurationException, SAXException, IOException { SAXParser saxParser = Utility.getSAXParser(); ShareListHandler handler = new ShareListHandler(serviceClient); saxParser.parse(stream, handler); return handler.response; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.elementStack.push(localName); if (FileConstants.SHARE_ELEMENT.equals(localName)) { this.shareName = Constants.EMPTY_STRING; this.snapshotID = null; this.attributes = new FileShareAttributes(); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String currentNode = this.elementStack.pop(); // if the node popped from the stack and the localName don't match, the xml document is improperly formatted if (!localName.equals(currentNode)) { throw new SAXException(SR.INVALID_RESPONSE_RECEIVED); } String parentNode = null; if (!this.elementStack.isEmpty()) { parentNode = this.elementStack.peek(); } String value = this.bld.toString(); if (value.isEmpty()) { value = null; } if (FileConstants.SHARE_ELEMENT.equals(currentNode)) { try { CloudFileShare retShare = this.serviceClient.getShareReference(this.shareName); retShare.setMetadata(this.attributes.getMetadata()); retShare.setProperties(this.attributes.getProperties()); retShare.snapshotID = this.snapshotID; this.response.getResults().add(retShare); } catch (URISyntaxException e) { throw new SAXException(e); } catch (StorageException e) { throw new SAXException(e); } } else if (ListResponse.ENUMERATION_RESULTS.equals(parentNode)) { if (Constants.PREFIX_ELEMENT.equals(currentNode)) { this.response.setPrefix(value); } else if (Constants.MARKER_ELEMENT.equals(currentNode)) { this.response.setMarker(value); } else if (Constants.NEXT_MARKER_ELEMENT.equals(currentNode)) { this.response.setNextMarker(value); } else if (Constants.MAX_RESULTS_ELEMENT.equals(currentNode)) { this.response.setMaxResults(Integer.parseInt(value)); } } else if (FileConstants.SHARE_ELEMENT.equals(parentNode)) { if (Constants.NAME_ELEMENT.equals(currentNode)) { this.shareName = value; } else if (Constants.QueryConstants.SNAPSHOT.equals(currentNode.toLowerCase())) { this.snapshotID = value; } } else if (Constants.PROPERTIES.equals(parentNode)) { try { getProperties(currentNode, value); } catch (ParseException e) { throw new SAXException(e); } } else if (Constants.METADATA_ELEMENT.equals(parentNode)) { if (value == null) { value = ""; } this.attributes.getMetadata().put(currentNode, value); } this.bld = new StringBuilder(); } @Override public void characters(char ch[], int start, int length) throws SAXException { this.bld.append(ch, start, length); } private void getProperties(String currentNode, String value) throws ParseException { if (currentNode.equals(Constants.LAST_MODIFIED_ELEMENT)) { this.attributes.getProperties().setLastModified(Utility.parseRFC1123DateFromStringInGMT(value)); } else if (currentNode.equals(Constants.ETAG_ELEMENT)) { this.attributes.getProperties().setEtag(Utility.formatETag(value)); } else if (currentNode.equals(FileConstants.SHARE_QUOTA_ELEMENT)) { this.attributes.getProperties().setShareQuota(Utility.isNullOrEmpty(value) ? null : Integer.parseInt(value)); } } }
37.348315
121
0.656588
78d24c16a42a8ad01fde8f73bb6835b435dd1be0
6,181
/** * CS180 - Lab 07 * * This class contains a list of some of the on-campus and off-campus restaurants and cafes. * You should complete it to fulfill the requirements of lab07 * */ import java.util.*; import java.lang.*; public class Restaurants { // On campus public static final String ON_CAMPUS_VEGAN = "Purdue Dining Courts\nFlatbreads"; public static final String ON_CAMPUS_VEGETARIAN = ON_CAMPUS_VEGAN + "\nOasis Cafe\nAh*Z\nFreshens"; public static final String ON_CAMPUS_GLUTEN_FREE = "Purdue Dining Courts\nFlatbreads\nOasis Cafe\nPappy's " + "Sweet Shop"; public static final String ON_CAMPUS_BURGERS = "Pappy's Sweet Shop\nCary Knight Spot"; public static final String ON_CAMPUS_SANDWICHES = "Flatbreads\nOasis Cafe\nErbert & Gerbert's"; public static final String ON_CAMPUS_OTHERS = "Purdue Dining Courts\nAh*Z\nFreshens\nLemongrass"; public static final String ON_CAMPUS_ALL = ON_CAMPUS_BURGERS + "\n" + ON_CAMPUS_SANDWICHES + "\n" + ON_CAMPUS_OTHERS; // Off campus public static final String OFF_CAMPUS_VEGAN = "Chipotle\nQdoba\nNine Irish Brothers\nFive Guys\n Puccini's " + "Smiling Teeth\nPanera Bread"; public static final String OFF_CAMPUS_VEGETARIAN = OFF_CAMPUS_VEGAN + "\nWendy's\nBruno's Pizza\nJimmy " + "John's\nPotbelly Sandwich Shop\nBasil Thai\nIndia Mahal"; public static final String OFF_CAMPUS_GLUTEN_FREE = "Chipotle\nQdoba\nNine Irish Brothers\nPuccini's Smiling " + "Teeth\nWendy's\nScotty's Brewhouse\nPanera Bread\nBasil Thai"; public static final String OFF_CAMPUS_BURGERS = "Five Guys\nWendy's\nTriple XXX\nScotty's Brewhouse"; public static final String OFF_CAMPUS_SANDWICHES = "Panera Bread\nJimmy John's\nPotbelly Sandwich Shop"; public static final String OFF_CAMPUS_PIZZAS = "Puccini's Smiling Teeth\nMad Mushroom Pizza\nBruno's Pizza\n"; public static final String OFF_CAMPUS_OTHERS = "Chipotle\nQdoba\nNine Irish Brothers\nFamous Frank's\n Von's " + "Dough Shack\nBuffalo Wild Wings\nBasil Thai\nMaru Sushi\nIndia Mahal\nHappy China\nYori"; public static final String offCampusAll = OFF_CAMPUS_BURGERS + "\n" + OFF_CAMPUS_SANDWICHES + "\n" + OFF_CAMPUS_PIZZAS + OFF_CAMPUS_OTHERS; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Where do you want to eat? " + "\n" + "On campus" + "\n" + "Off campus"); String first = scanner.nextLine(); System.out.println(first); if (first.equalsIgnoreCase("Off campus")) { System.out.println("Dietary restrictions? " + "y/n"); String firsty = scanner.nextLine(); if (firsty.equalsIgnoreCase("y")) { System.out.println("1 - Vegan" + "\n" + "2 - Vegetarian" + "\n" + "3 - Gluten-free"); int dietaryrestriction = scanner.nextInt(); if (dietaryrestriction == 1) { System.out.println(OFF_CAMPUS_VEGAN); } else if (dietaryrestriction == 2) { System.out.println(OFF_CAMPUS_VEGETARIAN); } else if (dietaryrestriction == 3) { System.out.println(OFF_CAMPUS_GLUTEN_FREE); } else System.out.println("Error"); } { if (firsty.equalsIgnoreCase("n")) { System.out.println("Food preference? " + "y/n"); String secondy = scanner.nextLine(); if (secondy.equalsIgnoreCase("y")) { System.out.println("1 - Burgers" + "\n" + "2 - Sandwiches" + "\n" + "3 - Pizzas" + "\n" + "4 - Others"); int foodpreference = scanner.nextInt(); if (foodpreference == 1) ; System.out.println(OFF_CAMPUS_BURGERS); if (foodpreference == 2) ; System.out.println(OFF_CAMPUS_SANDWICHES); if (foodpreference == 3) ; System.out.println(OFF_CAMPUS_PIZZAS); if (foodpreference == 4) ; System.out.println(OFF_CAMPUS_OTHERS); } else if (secondy.equalsIgnoreCase("n")) { System.out.println(offCampusAll); } } } } else if (first.equalsIgnoreCase("On campus")) { System.out.println("Dietary restrictions? " + "y/n"); String first1y = scanner.nextLine(); if (first1y.equalsIgnoreCase("y")) { System.out.println("1 - Vegan" + "\n" + "2 - Vegetarian" + "\n" + "3 - Gluten-free"); int dietaryrestriction_l = scanner.nextInt(); if (dietaryrestriction_l == 1) { System.out.println(ON_CAMPUS_VEGAN); } else if (dietaryrestriction_l == 2) { System.out.println(ON_CAMPUS_VEGETARIAN); } else if (dietaryrestriction_l == 3) { System.out.println(ON_CAMPUS_GLUTEN_FREE); } else System.out.println("Error"); } else if (first1y.equalsIgnoreCase("n")) { System.out.println("Food preference? " + "y/n"); String secondyl = scanner.nextLine(); if (secondyl.equalsIgnoreCase("y")) { System.out.println("1 - Burgers" + "\n" + "2 - Sandwiches" + "\n" + "3 - Others"); int foodpreferencel = scanner.nextInt(); if (foodpreferencel == 1) { System.out.println(ON_CAMPUS_BURGERS); } else if (foodpreferencel == 2) { System.out.println(ON_CAMPUS_SANDWICHES); } else if (foodpreferencel == 3) { System.out.println(ON_CAMPUS_OTHERS); } } else if (secondyl.equalsIgnoreCase("n")) { System.out.println(ON_CAMPUS_ALL); } } else System.out.println("Error"); } } }
50.252033
128
0.577738
dcd92f3987ed90ff12c52486be61c4e338579b18
138
package enums; public enum NbrTeam { TWO(2), THREE(3), FOUR(4); NbrTeam(int i) { // TODO Auto-generated constructor stub } }
9.857143
41
0.630435
24f984c2ccc4c65634c8abb8836b802f1c85374b
6,150
/*- * * * Copyright 2015 Skymind,Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package org.deeplearning4j.text.corpora.treeparser; import org.apache.uima.fit.util.FSCollectionFactory; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.tcas.Annotation; import org.cleartk.syntax.constituent.type.TreebankNode; import org.cleartk.syntax.constituent.type.TreebankNodeUtil; import org.cleartk.token.type.Token; import org.deeplearning4j.nn.layers.feedforward.autoencoder.recursive.Tree; import org.nd4j.linalg.collection.MultiDimensionalMap; import org.nd4j.linalg.primitives.Pair; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * * Static movingwindow class handling the conversion of * treebank nodes to Trees useful * for recursive neural tensor networks * * @author Adam Gibson */ public class TreeFactory { private TreeFactory() {} /** * Builds a tree recursively * adding the children as necessary * @param node the node to build the tree based on * @param labels the labels to assign for each span * @return the compiled tree with all of its children * and childrens' children recursively * @throws Exception */ public static Tree buildTree(TreebankNode node, Pair<String, MultiDimensionalMap<Integer, Integer, String>> labels, List<String> possibleLabels) throws Exception { if (node.getLeaf()) return toTree(node); else { List<TreebankNode> preChildren = children(node); List<Tree> children = new ArrayList<>(); Tree t = toTree(node); for (Pair<Integer, Integer> interval : labels.getSecond().keySet()) { if (inRange(interval.getFirst(), interval.getSecond(), t)) { t.setGoldLabel(possibleLabels .indexOf(labels.getSecond().get(interval.getFirst(), interval.getSecond()))); break; } } for (TreebankNode preChild : preChildren) { children.add(buildTree(preChild)); } t.connect(children); return t; } } /** * Converts a treebank node to a tree * @param node the node to convert * @param labels the labels to assign for each span * @return the tree with the same tokens and type as * the given tree bank node * @throws Exception */ public static Tree toTree(TreebankNode node, Pair<String, MultiDimensionalMap<Integer, Integer, String>> labels) throws Exception { List<String> tokens = tokens(node); Tree ret = new Tree(tokens); ret.setValue(node.getNodeValue()); ret.setLabel(node.getNodeType()); ret.setType(node.getNodeType()); ret.setBegin(node.getBegin()); ret.setEnd(node.getEnd()); ret.setParse(TreebankNodeUtil.toTreebankString(node)); if (node.getNodeTags() != null) ret.setTags(tags(node)); else ret.setTags(Arrays.asList(node.getNodeType())); return ret; } /** * Builds a tree recursively * adding the children as necessary * @param node the node to build the tree based on * @return the compiled tree with all of its children * and childrens' children recursively * @throws Exception */ public static Tree buildTree(TreebankNode node) throws Exception { if (node.getLeaf()) return toTree(node); else { List<TreebankNode> preChildren = children(node); List<Tree> children = new ArrayList<>(); Tree t = toTree(node); for (TreebankNode preChild : preChildren) { children.add(buildTree(preChild)); } t.connect(children); return t; } } /** * Converts a treebank node to a tree * @param node the node to convert * @return the tree with the same tokens and type as * the given tree bank node * @throws Exception */ public static Tree toTree(TreebankNode node) throws Exception { List<String> tokens = tokens(node); Tree ret = new Tree(tokens); ret.setValue(node.getNodeValue()); ret.setLabel(node.getNodeType()); ret.setType(node.getNodeType()); ret.setBegin(node.getBegin()); ret.setEnd(node.getEnd()); ret.setParse(TreebankNodeUtil.toTreebankString(node)); if (node.getNodeTags() != null) ret.setTags(tags(node)); else ret.setTags(Arrays.asList(node.getNodeType())); return ret; } private static List<String> tags(TreebankNode node) { List<String> ret = new ArrayList<>(); for (int i = 0; i < node.getNodeTags().size(); i++) ret.add(node.getNodeTags(i)); return ret; } private static List<TreebankNode> children(TreebankNode node) { return new ArrayList<>(FSCollectionFactory.create(node.getChildren(), TreebankNode.class)); } private static List<String> tokens(Annotation ann) throws Exception { List<String> ret = new ArrayList<>(); for (Token t : JCasUtil.select(ann.getCAS().getJCas(), Token.class)) { ret.add(t.getCoveredText()); } return ret; } private static boolean inRange(int begin, int end, Tree tree) { return tree.getBegin() >= begin && tree.getEnd() <= end; } }
32.712766
119
0.621301
7039a0772f9a7c04996377eefd31f8306c09b6bb
2,552
/** * Copyright 2015 SPeCS. * * 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. under the License. */ package org.specs.matisselib.ssa.instructions; import java.util.Arrays; import java.util.List; import java.util.Map; import org.specs.matisselib.ssa.InstructionType; /** * If the "matrix" variable is a scalar, then this instruction is the identity function. Otherwise, this instruction * behaves like simple_get. * * @see SimpleGetInstruction * @see CombineSizeInstruction * @author Luís Reis */ public final class GetOrFirstInstruction extends IndexedInstruction { private String output; private String matrix; private String index; public GetOrFirstInstruction(String output, String matrix, String index) { this.output = output; this.matrix = matrix; this.index = index; } @Override public GetOrFirstInstruction copy() { return new GetOrFirstInstruction(this.output, this.matrix, this.index); } @Override public List<String> getInputVariables() { return Arrays.asList(this.matrix, this.index); } @Override public List<String> getOutputs() { return Arrays.asList(this.output); } public String getInputMatrix() { return this.matrix; } public String getIndex() { return this.index; } @Override public List<String> getIndices() { return Arrays.asList(index); } public String getOutput() { return this.output; } @Override public InstructionType getInstructionType() { return InstructionType.NO_SIDE_EFFECT; } @Override public void renameVariables(Map<String, String> newNames) { this.output = newNames.getOrDefault(this.output, this.output); this.matrix = newNames.getOrDefault(this.matrix, this.matrix); this.index = newNames.getOrDefault(this.index, this.index); } @Override public String toString() { return this.output + " = get_or_first " + this.matrix + ", " + this.index; } }
28.043956
118
0.688088
c9456278ab59ded5738b075b848f214e9d3b941b
1,216
package com.cipher.tradisional.library; import java.util.Random; /** * @author : hafiq on 20/04/2017. */ public class KamasutraCipher { public static String MakeKSutra(String text,String key){ int keyLen = key.length()/2; // arrange random key char[][] keyRow = new char[2][keyLen]; int count=0; for(int x=0;x<2;x++){ for(int y=0;y<keyLen;y++){ keyRow[x][y] = key.charAt(count); System.out.print(keyRow[x][y]+" "); count++; } System.out.println(); } String sb = ""; for(int x=0;x<text.length();x++){ for(int y=0;y<2;y++){ for(int z=0;z<keyLen;z++){ if(y == 0){ if(text.charAt(x) == keyRow[y][z]) sb += keyRow[y+1][z]; } else if (y == 1){ if(text.charAt(x) == keyRow[y][z]) sb += keyRow[y-1][z]; } } } if(text.charAt(x) == ' ') sb += text.charAt(x); } return sb; } }
25.333333
60
0.38898
6d3075734eecd9c63ba7e436e3dd524ded039c80
608
package com.youhualife.modules.topprod.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; /** * 客户信息表 * @author ZQ */ @Data @TableName("occ_file") public class OCCEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 客户编号 */ @TableField("OCC01") private String OCC01; /** * 简称 */ @TableField("OCC02") private String OCC02; /** * 全称 */ @TableField("OCC18") private String OCC18; }
16.888889
54
0.654605
33de10d4c56b5fd40df7136226c28d3aafb30776
2,229
package com.tianci.weather.ui.citysetting; import java.util.ArrayList; import java.util.List; import com.tianci.weather.Debugger; import com.tianci.weather.data.DataUtils; import com.tianci.weather.data.ShareDataManager; import android.R.integer; import android.text.TextUtils; /** @Date : 2016年4月26日 @Author : Zhan Yu @Description : 城市数据管理 */ public class CitySettingManager { private static CitySettingManager instance = new CitySettingManager(); private List<String> cityList; private String currentCity; private static final String KEY_CURRENT_CITY = "default_city"; private static final String KEY_SAVED_CITY_LIST = "saved_city_list"; @SuppressWarnings("unchecked") private CitySettingManager() { initCurrentCity(); cityList = (List<String>) DataUtils.openObject("saved_city_list"); if(cityList == null) cityList = new ArrayList<String>(); if(!cityList.contains(currentCity)) cityList.add(currentCity); } public static CitySettingManager getInstance() { return instance; } private void initCurrentCity() { String savedCity = ShareDataManager.getSharedValue(KEY_CURRENT_CITY, ""); Debugger.d("savedCity=" + savedCity); if(TextUtils.isEmpty(savedCity)) { savedCity = "深圳" ; saveCurrentCity(savedCity); } currentCity = savedCity; } /**改变list中的数据 * @param city * @param index */ public void setIndexCity(String city, int index){ if(cityList != null){ cityList.set(index, city); saveCityList(); } } /** * 获取当前城市 * @param listener */ public String getCurrentCity() { return currentCity; } public void setCurrentCity(String curCity) { this.currentCity = curCity; saveCurrentCity(curCity); } private void saveCurrentCity(String curCity) { ShareDataManager.setSharedValue(KEY_CURRENT_CITY, curCity); } public List<String> getSavedCityList() { return cityList; } public void addCity(String city) { if(!cityList.contains(city)) { cityList.add(city); saveCityList(); } } public void deleteCity(String city) { if(cityList.contains(city)) { cityList.remove(city); saveCityList(); } } private void saveCityList() { DataUtils.saveObject(KEY_SAVED_CITY_LIST, cityList); } }
18.889831
75
0.719605
75eb91448d61773fc2774351d9ee7a942da574e9
2,709
package com.amazonaws.xray.agent.dispatcher; import software.amazon.disco.agent.event.ServiceActivityRequestEvent; import software.amazon.disco.agent.event.ServiceActivityResponseEvent; import software.amazon.disco.agent.event.ServiceRequestEvent; import com.amazonaws.xray.agent.handlers.XRayHandlerInterface; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @RunWith(PowerMockRunner.class) public class EventDispatcherTest { private final String ORIGIN = "testOrigin"; private final String SERVICE = "testService"; private final String OPERATION = "testOperation"; @Mock private XRayHandlerInterface mockHandler; private EventDispatcher eventDispatcher; @Before public void setup() { eventDispatcher = new EventDispatcher(); eventDispatcher.addHandler(ORIGIN, mockHandler); } @Test public void testAddHandler() { String testOrigin = "SOMEORIGIN"; ServiceRequestEvent serviceRequestEvent = new ServiceActivityRequestEvent(testOrigin, SERVICE, OPERATION); eventDispatcher.dispatchRequestEvent(serviceRequestEvent); verify(mockHandler, times(0)).handleRequest(serviceRequestEvent); eventDispatcher.addHandler(testOrigin, mockHandler); eventDispatcher.dispatchRequestEvent(serviceRequestEvent); verify(mockHandler, times(1)).handleRequest(serviceRequestEvent); } @Test public void testDispatchRequest() { ServiceActivityRequestEvent serviceRequestEvent = new ServiceActivityRequestEvent(ORIGIN, SERVICE, OPERATION); eventDispatcher.dispatchRequestEvent(serviceRequestEvent); verify(mockHandler, times(1)).handleRequest(serviceRequestEvent); } @Test public void testDispatchResponse() { ServiceActivityRequestEvent serviceRequestEvent = mock(ServiceActivityRequestEvent.class); ServiceActivityResponseEvent serviceResponseEvent = new ServiceActivityResponseEvent(ORIGIN, SERVICE, OPERATION, serviceRequestEvent); eventDispatcher.dispatchResponseEvent(serviceResponseEvent); verify(mockHandler, times(1)).handleResponse(serviceResponseEvent); } @Test public void testDispatchNoHandler() { ServiceActivityRequestEvent serviceRequestEvent = new ServiceActivityRequestEvent("NotUsedOrigin", null, null); eventDispatcher.dispatchRequestEvent(serviceRequestEvent); verify(mockHandler, times(0)).handleRequest(serviceRequestEvent); } }
38.15493
142
0.771133
0264fde70a44b7d1db6a0786a76ceab67cb7f509
1,026
package com.quarantyne.classifiers.impl; import com.quarantyne.classifiers.HttpRequestClassifier; import com.quarantyne.classifiers.Label; import com.quarantyne.lib.HttpRequest; import com.quarantyne.lib.HttpRequestBody; import javax.annotation.Nullable; import lombok.extern.slf4j.Slf4j; @Slf4j public class LargeBodySizeClassifier implements HttpRequestClassifier { protected static int MAX_SIZE_BYTES = 1_024; @Override public Label classify(final HttpRequest httpRequest, final HttpRequestBody body) { if (body == null) { return Label.NONE; } if (body.getBody().length > MAX_SIZE_BYTES) { if (log.isDebugEnabled()) { log.debug("{} is sending a large ({} bytes) body size", httpRequest.getFingerprint(), body.getBody().length); } return Label.LARGE_BODY; } return Label.NONE; } @Override public boolean test(HttpRequest httpRequest, @Nullable HttpRequestBody body) { return isWriteRequest(httpRequest) && hasBody(body); } }
28.5
84
0.721248
e96f43bf878ed7311ad4a519c856f52aff019f8a
1,024
package slimeknights.tconstruct.tools; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import slimeknights.tconstruct.library.tinkering.Category; import slimeknights.tconstruct.library.tinkering.PartMaterialRequirement; import slimeknights.tconstruct.library.tools.ToolDefinition; import slimeknights.tconstruct.tools.stats.ExtraMaterialStats; import slimeknights.tconstruct.tools.stats.HandleMaterialStats; import slimeknights.tconstruct.tools.stats.HeadMaterialStats; public final class ToolDefinitions { public static final ToolDefinition PICKAXE = new ToolDefinition( ToolBaseStatDefinitions.PICKAXE, ImmutableList.of( new PartMaterialRequirement(TinkerToolParts.pickaxeHead, HeadMaterialStats.ID), new PartMaterialRequirement(TinkerToolParts.toolRod, HandleMaterialStats.ID), new PartMaterialRequirement(TinkerToolParts.smallBinding, ExtraMaterialStats.ID) ), ImmutableSet.of(Category.HARVEST)); private ToolDefinitions() { } }
39.384615
86
0.831055
7f2a06d1be4856a2807ac43bb2cf2be908c55ce0
136
package com.titizz.shorturl.repository; public interface InitialCodeDao { Long AUTO_INCREMENT_STEP = 1000L; Long insert(); }
15.111111
39
0.742647
a4fd29a959ea93daf7a1fb62571c387b259927ba
4,850
package com.lambdaschool.foundation.models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.persistence.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @ApiModel(value = "Potluck", description = "A potluck event record") @Entity @Table(name="potlucks") public class Potluck extends Auditable { @ApiModelProperty(name = "potluck id", value = "primary key for potluck", required = true, example = "1") @Id @GeneratedValue(strategy = GenerationType.AUTO) private long potluckid; @ApiModelProperty(name = "potluck name", value = "name of potluck event", required = true, example = "Game Day Tailgate") @Column(nullable = false) private String name; @ApiModelProperty(name = "potluck location", value = "location of potluck event", required = true, example = "Commonwealth Stadium") @Column(nullable = false) private String location; // Update this data type later, use as string temporarily @ApiModelProperty(name = "potluck date", value = "date of potluck event", required = true, example = "March 7th") @Column(nullable = false) private String date; // Update this data type later, use as string temporarily @ApiModelProperty(name = "potluck time", value = "time of potluck event", required = true, example = "2 PM") @Column(nullable = false) private String time; @ApiModelProperty(name = "potluck organizer", value = "organizer of potluck event", required = true, example = "BarnBarn") @Column(nullable = false) private String organizer; @OneToMany(mappedBy = "potluck", cascade = CascadeType.ALL, orphanRemoval = true) @JsonIgnoreProperties(value = "potluck", allowSetters = true) private List <Item> items = new ArrayList<>(); /** * Part of the join relationship between potluck and users * connects potluck to a potluck user combination */ @OneToMany(mappedBy = "potluck", cascade = CascadeType.ALL, orphanRemoval = true) @JsonIgnoreProperties(value = "potluck", allowSetters = true) private Set<UserPotlucks> users = new HashSet<>(); public Potluck() { } public Potluck( long potluckid, String name, String location, String date, String time, String organizer, List<Item> items, Set<UserPotlucks> users) { this.potluckid = potluckid; this.name = name; this.location = location; this.date = date; this.time = time; this.organizer = organizer; this.items = items; this.users = users; } public Potluck( String name, String location, String date, String time, String organizer, List<Item> items, Set<UserPotlucks> users) { this.name = name; this.location = location; this.date = date; this.time = time; this.organizer = organizer; this.items = items; this.users = users; } public Potluck( String name, String location, String date, String time, String organizer) { this.name = name; this.location = location; this.date = date; this.time = time; this.organizer = organizer; } public long getPotluckid() { return potluckid; } public void setPotluckid(long potluckid) { this.potluckid = potluckid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getOrganizer() { return organizer; } public void setOrganizer(String organizer) { this.organizer = organizer; } public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public Set<UserPotlucks> getUsers() { return users; } public void setUsers(Set<UserPotlucks> users) { this.users = users; } }
22.146119
65
0.594227
743e437688715669c63bc8cb45c8e2414e0bf279
3,043
package life.qbic.view.panels; import com.vaadin.ui.*; import life.qbic.model.Globals; import life.qbic.model.beans.AlignmentFileBean; import life.qbic.model.beans.ProjectBean; import life.qbic.presenter.Presenter; import life.qbic.testing.TestData; import life.qbic.view.InfoBar; import life.qbic.view.MyGrid; /** * This component has a panel where the user chooses a nameField for his project, selects the type of study, * and uploads an alignment file (if he selected "Strain or species") * * @author jmueller */ public class GeneralConfigPanel extends CustomComponent{ private Presenter presenter; private Panel generalConfigPanel; private Layout contentLayout; private Grid<ProjectBean> projectGrid; private Grid<AlignmentFileBean> alignmentFileGrid; RadioButtonGroup<String> projectTypeButtonGroup; public GeneralConfigPanel(Presenter presenter) { generalConfigPanel = designPanel(); setCompositionRoot(generalConfigPanel); this.presenter = presenter; } private Panel designPanel() { Panel panel = new Panel(); contentLayout = new FormLayout(); projectGrid = new MyGrid<>("Select your project"); projectGrid.addColumn(ProjectBean::getName).setCaption("Project Name"); projectGrid.addColumn(ProjectBean::getRegistrationDate).setCaption("Registration Date"); projectGrid.addStyleName("my-file-grid"); projectTypeButtonGroup = new RadioButtonGroup<>("Select type of study"); String strainOrSpecies = Globals.COMPARE_GENOMES; String conditions = Globals.COMPARE_CONDITIONS; projectTypeButtonGroup.setItems(strainOrSpecies, conditions); projectTypeButtonGroup.setSelectedItem(strainOrSpecies); alignmentFileGrid = new MyGrid<>("Select alignment file"); alignmentFileGrid.addColumn(AlignmentFileBean::getName).setCaption("File name"); alignmentFileGrid.addColumn(AlignmentFileBean::getCreationDate).setCaption("Creation Date"); alignmentFileGrid.addColumn(AlignmentFileBean::getSizeInKB).setCaption("Size (kB)"); alignmentFileGrid.addStyleName("my-file-grid"); //The alignment file selection should only be visible if strains/species are to be compared alignmentFileGrid.setVisible(!Globals.IS_CONDITIONS_INIT); contentLayout.addComponents(projectTypeButtonGroup, projectGrid, alignmentFileGrid); panel.setContent(new VerticalLayout(new InfoBar(Globals.GENERAL_CONFIG_INFO), contentLayout)); //<-- TESTING projectGrid.setItems(TestData.createProjectBeanList()); alignmentFileGrid.setItems(TestData.createAlignmentFileBeanList()); //TESTING --> return panel; } public Grid<ProjectBean> getProjectGrid() { return projectGrid; } public Grid<AlignmentFileBean> getAlignmentFileGrid() { return alignmentFileGrid; } public RadioButtonGroup<String> getProjectTypeButtonGroup() { return projectTypeButtonGroup; } }
36.22619
108
0.733158
0eae1f54d4b3a863205eb1f4f358c15e57e41193
887
package deposit; import rate.Rate; public abstract class Deposit implements DepositInterfaceAdvanced{ protected String name; protected double sum; protected Rate rate; protected double term; protected Deposit(String name, double sum, Rate rate, double term){ this.name = name; this.sum = sum; this.rate = rate; this.term = term; } public String getName(){ return name; } public double getSum(){ return sum; } public Rate getRate(){ return rate; } public double getTerm(){ return term; } public void setName(String name){ this.name = name; } public void setSum(double sum){ this.sum = sum; } public void setRate(Rate rate){ this.rate = rate; } public void setTerm(double term){ this.term = term; } }
20.627907
71
0.588501
42861e97f33ff1e388727ca7f945ab0302b5d4b7
1,593
package ro.pub.cs.systems.pdsd.lab05.sample03gridview; import android.app.Activity; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract.Contacts; import android.view.Menu; import android.widget.GridView; import android.widget.SimpleCursorAdapter; public class MainActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> { SimpleCursorAdapter adapter; GridView gridview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridview = (GridView)findViewById(R.id.gridview); String[] columns = new String[] {Contacts.DISPLAY_NAME}; int[] views = new int[] {android.R.id.text1}; adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, columns, views, 0); gridview.setAdapter(adapter); getLoaderManager().initLoader(0, null, this); } public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(this, Contacts.CONTENT_URI, null, null, null, Contacts.DISPLAY_NAME); } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); } public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
30.634615
104
0.775267
6a68411fc3bb5c884420819dc95433440e62dfd6
966
package ru.otus.core.model; import javax.persistence.*; @Entity(name = "Phone") @Table(name = "phones") public class Phone { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @Column(name = "phone_id") private long id; @Column(name = "number", nullable = false) private String number; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private User user; public Phone() { } public Phone(final String number, final User user) { this.number = number; this.user = user; } public User getUser() { return user; } public void setUser(final User user) { this.user = user; } public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getNumber() { return number; } public void setNumber(final String number) { this.number = number; } @Override public String toString() { return "Phone{" + "id=" + id + ", number='" + number + '\'' + '}'; } }
16.1
53
0.645963
42aee9647ff6668c8b65f3bf1d6c7c7d1b879b6e
769
package abused_master.refinedmachinery.blocks.tanks; import abused_master.refinedmachinery.RefinedMachinery; public enum EnumTankTypes { COPPER_TANK(RefinedMachinery.config.getInt("copperTankStorage")), SILVER_TANK(RefinedMachinery.config.getInt("silverTankStorage")), STEEL_TANK(RefinedMachinery.config.getInt("steelTankStorage")); private int storageCapacity; private BlockTank tank; EnumTankTypes(int storageCapacity) { this.tank = new BlockTank(this); this.storageCapacity = storageCapacity; } public String getName() { return this.toString().toLowerCase(); } public BlockTank getTank() { return tank; } public int getStorageCapacity() { return storageCapacity; } }
25.633333
69
0.713914
01b84ccea62e034639208acfd2a78cc3431c5c71
744
package com.jzd.jzshop.entity; import java.io.File; import java.util.List; /** * @author LWH * @description: * @date :2020/1/7 17:46 */ public class EventFile { private List<FileBean> file; public List<FileBean> getFile() { return file; } public void setFile(List<FileBean> file) { this.file = file; } public static class FileBean{ private String key; private File file; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } } }
16.533333
46
0.534946
d80ca0e1609325f68d8ca88d07d1c56bf8f2a52e
1,625
package life.genny.test; import java.lang.invoke.MethodHandles; import java.util.UUID; import org.apache.logging.log4j.Logger; import org.javamoney.moneta.Money; import org.junit.Test; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import life.genny.qwanda.MoneyDeserializer; import life.genny.qwanda.message.QBulkPullMessage; import life.genny.qwanda.message.QEventDropdownMessage; public class QBulkPullMessageTest { /** * Stores logger object. */ protected static final Logger log = org.apache.logging.log4j.LogManager .getLogger(MethodHandles.lookup().lookupClass().getCanonicalName()); @Test public void ddEventTest() { QEventDropdownMessage msg = new QEventDropdownMessage("LNK_HOST_COMPANY"); msg.getData().setTargetCode("PER_YTRYTRYTRYTRYTR"); msg.setSourceCode("PER_757657657657657"); msg.setPageIndex(0); msg.setPageSize(20); GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Money.class, new MoneyDeserializer()); Gson gson = gsonBuilder.create(); String moneyJson2 = gson.toJson(msg); System.out.println(moneyJson2); msg.data.setValue("GAD"); moneyJson2 = gson.toJson(msg); System.out.println(moneyJson2); } @Test public void jsonTest() { UUID uuid = UUID.randomUUID(); QBulkPullMessage msg = new QBulkPullMessage(uuid.toString()); msg.setPullUrl("https://pontoon.channel40.com.au/pull/"+uuid.toString()); GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Money.class, new MoneyDeserializer()); Gson gson = gsonBuilder.create(); String moneyJson2 = gson.toJson(msg); log.info(moneyJson2); } }
24.621212
104
0.759385
32b71f2384059f058125881fc7517a7530635150
438
package jToolkit4FixedPipeline.physics; /** * Created with IntelliJ IDEA. * User: Astemir Eleev * Date: 24.02.13 * Time: 19:53 * To change this template use File | Settings | File Templates. */ public interface BoundingRoundedVolume<T, V> extends BoundingVolume <T>{ public void setPosition(final V vec); public V getPosition(); public void setRadius(final float radius); public float getRadius(); }
27.375
73
0.694064
4fa7890d3ddb412f29a9b41d99c147245dc23f19
658
package com.rolfje.anonimatron.file; import junit.framework.TestCase; import java.io.*; public class CsvFileReaderTest extends TestCase { public void testHappy() throws IOException { File tempFile = File.createTempFile(CsvFileReaderTest.class.getSimpleName(), ".csv"); Writer writer = new BufferedWriter(new FileWriter(tempFile)); writer.write("\"Testfield1\";\"Testfield2\""); writer.close(); CsvFileReader csvFileReader = new CsvFileReader(tempFile); assertTrue(csvFileReader.hasRecords()); Record read = csvFileReader.read(); assertEquals("Testfield1", read.getValues()[0]); assertEquals("Testfield2", read.getValues()[1]); } }
27.416667
87
0.74772
dd525f5c563aff4a10e66d2dc309f5e7e12ca0ea
951
package com.tuixin11sms.tx.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Window; import com.tuixin11sms.tx.R; public class WarnDialogAcitvity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.warndialog); Intent intent = getIntent(); String stringExtra = intent.getStringExtra("rs"); new AlertDialog.Builder(WarnDialogAcitvity.this) .setTitle("警告") .setCancelable(false) .setMessage("你由于“" + stringExtra + "”被警告了,请自觉遵守神聊管理规范并保护聊天室秩序。") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { dialog.cancel(); finish(); } }).show();// 显示对话框 } }
27.970588
68
0.746583
a5b35560596991c118c73c5d98486f6099a70f29
2,725
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.service.protocol.event; import java.util.*; /** * Notifies interested parties in sound level changes of the main audio stream * coming from a given <tt>CallPeer</tt>. * <p> * What does this mean in the different cases: * 1) In the case of a <tt>CallPeer</tt>, which is not a conference focus and * has no <tt>ConferenceMember</tt>s we would be notified of any change in the * sound level of the stream coming from this peer. * 2) In the case of a <tt>CallPeer</tt>, which is also a conference focus and * is participating in the conference as a <tt>ConferenceMember</tt> the level * would be the aggregated level of all <tt>ConferenceMember</tt>s levels * including the one corresponding to the peer itself. * 3) In the case of a <tt>CallPeer</tt>, which is also a conference focus, but * is NOT participating in the conference as a <tt>ConferenceMember</tt> * (server) the level would be the aggregated level of all * <tt>ConferenceMember</tt>s. * * @author Yana Stamcheva * @author Lyubomir Marinov */ public interface SoundLevelListener extends EventListener { /** * Indicates that a change has occurred in the audio stream level coming * from a given <tt>CallPeer</tt>. In the case of conference focus the audio * stream level would be the total level including all * <tt>ConferenceMember</tt>s levels. * <p> * In contrast to the conventions of Java and Jitsi, * <tt>SoundLevelListener</tt> does not fire an <tt>EventObject</tt> (i.e. * <tt>SoundLevelChangeEvent</tt>) in order to try to reduce the number of * allocations related to sound level changes since their number is expected * to be very large. * </p> * * @param source the <tt>Object</tt> which is the source of the sound level * change event being fired to this <tt>SoundLevelListener</tt> * @param level the sound level to notify this <tt>SoundLevelListener</tt> * about */ public void soundLevelChanged(Object source, int level); }
41.287879
80
0.714128
833d0cafa2bf24babfc72c62e7c3571ed5c0940c
638
package com.github.chen0040.gp.treegp.program.operators; import org.testng.annotations.Test; import java.util.Arrays; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /** * Created by xschen on 11/5/2017. */ public class PlusUnitTest { @Test public void test_makeCopy(){ Plus op = new Plus(); assertThat(op.arity()).isEqualTo(2); assertThat(op.makeCopy()).isEqualTo(op); } @Test public void test_execute(){ Plus op = new Plus(); op.beforeExecute(Arrays.asList(2.0, 2.0), null); op.execute(null); assertThat(op.getValue()).isEqualTo(4.0); } }
20.580645
74
0.669279
d044eaf93a8ce78532cc93b82f593f32dddd784b
232
package com.coolweather.app.util; /** * Author:DJ * Time:2015/12/20 0020 20:42 * Name:CoolWeather * Description: */ public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
15.466667
37
0.706897
b1e43f186d3e818c3769ea40d04b5fc76d4c5ff4
2,468
/* * Copyright (c) 2010 eXtensible Catalog Organization. * * This program is free software; you can redistribute it and/or modify it * under the terms of the MIT/X11 license. The text of the license can be * found at http://www.opensource.org/licenses/mit-license.php. */ package org.oclc.circill.toolkit.service.ncip; import java.math.BigDecimal; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; /** * Provides structured information that describes the hierarchical relationship of the specific part * held by an Agency to a whole Item, expressed in chronological terms. */ public class ChronologyLevelInstance { protected String chronologyCaption; protected BigDecimal chronologyLevel; protected String chronologyValue; public String getChronologyCaption() { return chronologyCaption; } public void setChronologyCaption(final String chronologyCaption) { this.chronologyCaption = chronologyCaption; } public BigDecimal getChronologyLevel() { return chronologyLevel; } public void setChronologyLevel(final BigDecimal chronologyLevel) { this.chronologyLevel = chronologyLevel; } public String getChronologyValue() { return chronologyValue; } public void setChronologyValue(final String chronologyValue) { this.chronologyValue = chronologyValue; } /** * Generic toString() implementation. * * @return String */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } final ChronologyLevelInstance rhs = (ChronologyLevelInstance) obj; return new EqualsBuilder().append(chronologyCaption, rhs.chronologyCaption).append(chronologyLevel, rhs.chronologyLevel).append(chronologyValue, rhs.chronologyValue) .isEquals(); } @Override public int hashCode() { final int result = new HashCodeBuilder(391297093, 1175582677).append(chronologyCaption).append(chronologyLevel).append(chronologyValue).toHashCode(); return result; } }
30.097561
173
0.694895
7fcbe2f8356046496fc5a8a279e29fc5d59abaf1
4,257
/* * Copyright 2015-2021 Alexandr Evstigneev * * 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.perl5.lang.perl.idea.hierarchy.namespace; import com.intellij.ide.hierarchy.*; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.psi.PsiElement; import com.perl5.lang.perl.idea.hierarchy.namespace.treestructures.PerlSubTypesHierarchyTreeStructure; import com.perl5.lang.perl.idea.hierarchy.namespace.treestructures.PerlSuperTypesHierarchyTreeStructure; import com.perl5.lang.perl.psi.PerlNamespaceDefinitionElement; import com.perl5.lang.perl.psi.properties.PerlIdentifierOwner; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Comparator; import java.util.Map; public class PerlHierarchyBrowser extends TypeHierarchyBrowserBase { public PerlHierarchyBrowser(PsiElement element) { super(element.getProject(), element); } @Override protected boolean isInterface(@NotNull PsiElement psiElement) { return false; } @Override protected boolean canBeDeleted(PsiElement psiElement) { return false; } @Override protected String getQualifiedName(PsiElement psiElement) { if (psiElement instanceof PerlIdentifierOwner) { return ((PerlIdentifierOwner)psiElement).getPresentableName(); } return null; } @Override protected @Nullable String getContentDisplayName(@NotNull String typeName, @NotNull PsiElement element) { return super.getContentDisplayName(typeName, element); } @Override protected @Nullable PsiElement getElementFromDescriptor(@NotNull HierarchyNodeDescriptor descriptor) { if (!(descriptor instanceof PerlHierarchyNodeDescriptor)) { return null; } return ((PerlHierarchyNodeDescriptor)descriptor).getPerlElement(); } @Override protected void createTrees(@NotNull Map<? super String, ? super JTree> trees) { trees.put(getSupertypesHierarchyType(), createTree(true)); trees.put(getSubtypesHierarchyType(), createTree(true)); trees.put(getTypeHierarchyType(), createTree(true)); } @Override protected void prependActions(final @NotNull DefaultActionGroup actionGroup) { actionGroup.add(new ViewSupertypesHierarchyAction()); actionGroup.add(new ViewSubtypesHierarchyAction()); actionGroup.add(new AlphaSortAction()); } @Override protected @Nullable JPanel createLegendPanel() { return null; } @Override protected boolean isApplicableElement(@NotNull PsiElement element) { return element instanceof PerlNamespaceDefinitionElement; } @Override protected @Nullable HierarchyTreeStructure createHierarchyTreeStructure(@NotNull String typeName, @NotNull PsiElement psiElement) { if (getSupertypesHierarchyType().equals(typeName)) { return getSuperTypesHierarchyStructure(psiElement); } else if (getSubtypesHierarchyType().equals(typeName)) { return getSubTypesHierarchyStructure(psiElement); } else if (getTypeHierarchyType().equals(typeName)) { return getTypesHierarchyStructure(psiElement); } return null; } @Override protected @Nullable Comparator<NodeDescriptor<?>> getComparator() { return null; } protected @Nullable HierarchyTreeStructure getSuperTypesHierarchyStructure(PsiElement psiElement) { return new PerlSuperTypesHierarchyTreeStructure(psiElement); } protected @Nullable HierarchyTreeStructure getSubTypesHierarchyStructure(PsiElement psiElement) { return new PerlSubTypesHierarchyTreeStructure(psiElement); } protected @Nullable HierarchyTreeStructure getTypesHierarchyStructure(PsiElement psiElement) { return null; } }
33.257813
133
0.775664
6d67a017743e2bf8d636c4d8e0669452b117599f
632
package com.qmdj.service.teacher; import com.github.pagehelper.PageInfo; import com.qmdj.biz.pogo.qo.TeacherQO; import com.qmdj.service.bo.TeacherBO; import com.qmdj.service.common.Result; public interface TeacherService { /** * 添加 * @return */ Result<Integer> addTeacher(TeacherBO teacherBO); Result<Integer> updateTeacher(TeacherBO teacherBO); Result<Integer> delTeacher(long teacherBOId); Result<PageInfo<TeacherBO>> selectTeacherList(TeacherQO teacherBOId); /** * 查询 * @return */ Result<TeacherBO> selectTeacherById(long teacherId); Result<TeacherBO> selectTeacherByUserId(long teacherId); }
19.75
70
0.754747
bc794662715a2df8c55b4d01aaad1fc87a2326ff
412
package io.leego.office4j.excel; import org.apache.poi.xssf.streaming.SXSSFSheet; /** * @author Yihleego */ public interface ExcelFooter { /** * Returns the height occupied by the footer. * @param sheet {@link SXSSFSheet} sheet * @param rowNumber the number of current rows. * @return the height occupied by the footer. */ int apply(SXSSFSheet sheet, int rowNumber); }
21.684211
51
0.67233
81ebede3e55bac008c5fb3cf9e98cf73a79d6a82
1,564
package br.com.ecarrara.neom.nearearthobjects.data.entity.json; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class CloseApproachDataJsonEntity { @Expose private MissDistanceJsonEntity missDistance; @SerializedName("orbiting_body") @Expose private String orbitingBody; /** * * @return * The missDistance */ public MissDistanceJsonEntity getMissDistance() { return missDistance; } /** * * @param missDistance * The miss_distance */ public void setMissDistance(MissDistanceJsonEntity missDistance) { this.missDistance = missDistance; } /** * * @return * The orbitingBody */ public String getOrbitingBody() { return orbitingBody; } /** * * @param orbitingBody * The orbiting_body */ public void setOrbitingBody(String orbitingBody) { this.orbitingBody = orbitingBody; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CloseApproachDataJsonEntity that = (CloseApproachDataJsonEntity) o; if (!missDistance.equals(that.missDistance)) return false; return orbitingBody.equals(that.orbitingBody); } @Override public int hashCode() { int result = missDistance.hashCode(); result = 31 * result + orbitingBody.hashCode(); return result; } }
22.666667
75
0.627238
ff576ebfaaacb502475950095d0910248ec7d056
4,664
/* * 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.geode; /** * Indicates that serious error has occurred within the GemFire system. * * This is similar to {@link AssertionError}, but these errors are always enabled in a GemFire * system. * * @since GemFire 5.5 * @see AssertionError */ public class InternalGemFireError extends Error { private static final long serialVersionUID = 6390043490679349593L; public InternalGemFireError() { // TODO Auto-generated constructor stub } public InternalGemFireError(String message) { super(message); } public InternalGemFireError(Throwable cause) { super(cause); } public InternalGemFireError(String message, Throwable cause) { super(message, cause); } /** * Constructs an AssertionError with its detail message derived from the specified object, which * is converted to a string as defined in <i>The Java Language Specification, Second Edition</i>, * Section 15.18.1.1. * <p> * If the specified object is an instance of <tt>Throwable</tt>, it becomes the <i>cause</i> of * the newly constructed assertion error. * * @param detailMessage value to be used in constructing detail message * @see Throwable#getCause() */ public InternalGemFireError(Object detailMessage) { this("" + detailMessage); if (detailMessage instanceof Throwable) { initCause((Throwable) detailMessage); } } /** * Constructs an AssertionError with its detail message derived from the specified * <code>boolean</code>, which is converted to a string as defined in <i>The Java Language * Specification, Second Edition</i>, Section 15.18.1.1. * * @param detailMessage value to be used in constructing detail message */ public InternalGemFireError(boolean detailMessage) { this("" + detailMessage); } /** * Constructs an AssertionError with its detail message derived from the specified * <code>char</code>, which is converted to a string as defined in <i>The Java Language * Specification, Second Edition</i>, Section 15.18.1.1. * * @param detailMessage value to be used in constructing detail message */ public InternalGemFireError(char detailMessage) { this("" + detailMessage); } /** * Constructs an AssertionError with its detail message derived from the specified * <code>int</code>, which is converted to a string as defined in <i>The Java Language * Specification, Second Edition</i>, Section 15.18.1.1. * * @param detailMessage value to be used in constructing detail message */ public InternalGemFireError(int detailMessage) { this("" + detailMessage); } /** * Constructs an AssertionError with its detail message derived from the specified * <code>long</code>, which is converted to a string as defined in <i>The Java Language * Specification, Second Edition</i>, Section 15.18.1.1. * * @param detailMessage value to be used in constructing detail message */ public InternalGemFireError(long detailMessage) { this("" + detailMessage); } /** * Constructs an AssertionError with its detail message derived from the specified * <code>float</code>, which is converted to a string as defined in <i>The Java Language * Specification, Second Edition</i>, Section 15.18.1.1. * * @param detailMessage value to be used in constructing detail message */ public InternalGemFireError(float detailMessage) { this("" + detailMessage); } /** * Constructs an AssertionError with its detail message derived from the specified * <code>double</code>, which is converted to a string as defined in <i>The Java Language * Specification, Second Edition</i>, Section 15.18.1.1. * * @param detailMessage value to be used in constructing detail message */ public InternalGemFireError(double detailMessage) { this("" + detailMessage); } }
35.876923
100
0.719554
e82050d25ffeb41521d2f990a2f3e82dc3dc6526
2,087
/* * Copyright 2015-2018 The OpenZipkin 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 zipkin2.storage.mysql.v1; import java.util.Date; import java.util.List; import java.util.function.Function; import org.jooq.DSLContext; import org.jooq.Record; import zipkin2.DependencyLink; import zipkin2.internal.DependencyLinker; import static zipkin2.storage.mysql.v1.Schema.maybeGet; import static zipkin2.storage.mysql.v1.internal.generated.tables.ZipkinDependencies.ZIPKIN_DEPENDENCIES; final class SelectDependencies implements Function<DSLContext, List<DependencyLink>> { final Schema schema; final List<Date> days; SelectDependencies(Schema schema, List<Date> days) { this.schema = schema; this.days = days; } @Override public List<DependencyLink> apply(DSLContext context) { List<DependencyLink> unmerged = context .select(schema.dependencyLinkFields) .from(ZIPKIN_DEPENDENCIES) .where(ZIPKIN_DEPENDENCIES.DAY.in(days)) .fetch( (Record l) -> DependencyLink.newBuilder() .parent(l.get(ZIPKIN_DEPENDENCIES.PARENT)) .child(l.get(ZIPKIN_DEPENDENCIES.CHILD)) .callCount(l.get(ZIPKIN_DEPENDENCIES.CALL_COUNT)) .errorCount(maybeGet(l, ZIPKIN_DEPENDENCIES.ERROR_COUNT, 0L)) .build()); return DependencyLinker.merge(unmerged); } @Override public String toString() { return "SelectDependencies{days=" + days + "}"; } }
35.372881
104
0.691423
0187b79a488b753fd6c8e520045cadaa45097dac
255
package org.robotninjas.barge; public class NotLeaderException extends RaftException { private final Replica leader; public NotLeaderException(Replica leader) { this.leader = leader; } public Replica getLeader() { return leader; } }
17
55
0.733333
e1ecd2d8c48ddcfece84dc2340186f013deff498
34,906
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * org.lwjgl.opengl.GL11 */ package me.wintware.client.utils.visual; import java.awt.Color; import me.wintware.client.utils.font.FontRenderer; import me.wintware.client.utils.other.MinecraftHelper; import me.wintware.client.utils.visual.ColorUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import org.lwjgl.opengl.GL11; public class RenderUtil implements MinecraftHelper { private static final Frustum frustrum = new Frustum(); private static final double DOUBLE_PI = Math.PI * 2; public static double interpolate(double current, double old, double scale) { return old + (current - old) * scale; } public static void renderItem(ItemStack itemStack, int x, int y) { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.enableDepth(); RenderHelper.enableGUIStandardItemLighting(); mc.getRenderItem().renderItemAndEffectIntoGUI(itemStack, x, y); mc.getRenderItem().renderItemOverlays(RenderUtil.mc.fontRendererObj, itemStack, x, y); RenderHelper.disableStandardItemLighting(); GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); GlStateManager.disableDepth(); } public static void drawRectWithEdge(double x, double y, double width, double height, Color color, Color color2) { RenderUtil.drawRect(x, y, x + width, y + height, color.getRGB()); int c = color2.getRGB(); RenderUtil.drawRect(x - 1.0, y, x, y + height, c); RenderUtil.drawRect(x + width, y, x + width + 1.0, y + height, c); RenderUtil.drawRect(x - 1.0, y - 1.0, x + width + 1.0, y, c); RenderUtil.drawRect(x - 1.0, y + height, x + width + 1.0, y + height + 1.0, c); } public static void drawRoundedRect(double x, double y, double x1, double y1, int borderC, int insideC) { RenderUtil.drawRect(x + 0.5, y, x1 - 0.5, y + 0.5, insideC); RenderUtil.drawRect(x + 0.5, y1 - 0.5, x1 - 0.5, y1, insideC); RenderUtil.drawRect(x, y + 0.5, x1, y1 - 0.5, insideC); } public static void drawRoundedRect(int xCoord, int yCoord, int xSize, int ySize, int colour) { int width = xCoord + xSize; int height = yCoord + ySize; RenderUtil.drawRect(xCoord + 1, yCoord, width - 1, height, colour); RenderUtil.drawRect(xCoord, yCoord + 1, width, height - 1, colour); } public static void drawBoundingBox(AxisAlignedBB axisalignedbb) { GL11.glBegin(7); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ); GL11.glVertex3d(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ); GL11.glEnd(); } public static void drawFilledCircle(int xx, int yy, float radius, Color color) { int sections = 6; double dAngle = Math.PI * 2 / (double)sections; GL11.glPushAttrib(8192); GL11.glEnable(3042); GL11.glDisable(3553); GL11.glBlendFunc(770, 771); GL11.glEnable(2848); GL11.glBegin(6); for (int i = 0; i < sections; ++i) { float x = (float)((double)radius * Math.sin((double)i * dAngle)); float y = (float)((double)radius * Math.cos((double)i * dAngle)); GL11.glColor4f((float)color.getRed() / 255.0f, (float)color.getGreen() / 255.0f, (float)color.getBlue() / 255.0f, (float)color.getAlpha() / 255.0f); GL11.glVertex2f((float)xx + x, (float)yy + y); } GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glEnd(); GL11.glPopAttrib(); } public static final void drawSmoothRect(float left, float top, float right, float bottom, int color) { GL11.glEnable(3042); GL11.glEnable(2848); RenderUtil.drawRect(left, top, right, bottom, color); GL11.glScalef(0.5f, 0.5f, 0.5f); RenderUtil.drawRect(left * 2.0f - 1.0f, top * 2.0f, left * 2.0f, bottom * 2.0f - 1.0f, color); RenderUtil.drawRect(left * 2.0f, top * 2.0f - 1.0f, right * 2.0f, top * 2.0f, color); RenderUtil.drawRect(right * 2.0f, top * 2.0f, right * 2.0f + 1.0f, bottom * 2.0f - 1.0f, color); RenderUtil.drawRect(left * 2.0f, bottom * 2.0f - 1.0f, right * 2.0f, bottom * 2.0f, color); GL11.glDisable(3042); GL11.glScalef(2.0f, 2.0f, 2.0f); } public static void drawImage(ResourceLocation image, int x, int y, int width, int height) { GL11.glEnable(2848); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glPushMatrix(); Minecraft.getMinecraft().getTextureManager().bindTexture(image); Gui.drawModalRectWithCustomSizedTexture(x, y, 0.0f, 0.0f, width, height, width, height); RenderUtil.disableGL2D(); GL11.glPopMatrix(); } public static void drawCircle(float cx, double cy, float r, int num_segments, int c) { GL11.glPushMatrix(); cx *= 2.0f; cy *= 2.0; float f = (float)(c >> 24 & 0xFF) / 255.0f; float f1 = (float)(c >> 16 & 0xFF) / 255.0f; float f2 = (float)(c >> 8 & 0xFF) / 255.0f; float f3 = (float)(c & 0xFF) / 255.0f; float theta = (float)(6.2831852 / (double)num_segments); float p = (float)Math.cos(theta); float s = (float)Math.sin(theta); float x = r *= 2.0f; float y = 0.0f; GL11.glEnable(2848); RenderUtil.enableGL2D(); GL11.glScalef(0.5f, 0.5f, 0.5f); GL11.glColor4f(f1, f2, f3, f); GL11.glBegin(2); for (int ii = 0; ii < num_segments; ++ii) { GL11.glVertex2f(x + cx, (float)((double)y + cy)); float t = x; x = p * x - s * y; y = s * t + p * y; } GL11.glEnd(); GL11.glScalef(2.0f, 2.0f, 2.0f); RenderUtil.disableGL2D(); GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); GL11.glPopMatrix(); } public static void prepareScissorBox(float x, float y, float x2, float y2) { ScaledResolution scale = new ScaledResolution(Minecraft.getMinecraft()); int factor = ScaledResolution.getScaleFactor(); GL11.glScissor((int)(x * (float)factor), (int)(((float)scale.getScaledHeight() - y2) * (float)factor), (int)((x2 - x) * (float)factor), (int)((y2 - y) * (float)factor)); } public static void drawGradientSideways(double left, double top, double right, double bottom, int col1, int col2) { float f = (float)(col1 >> 24 & 0xFF) / 255.0f; float f1 = (float)(col1 >> 16 & 0xFF) / 255.0f; float f2 = (float)(col1 >> 8 & 0xFF) / 255.0f; float f3 = (float)(col1 & 0xFF) / 255.0f; float f4 = (float)(col2 >> 24 & 0xFF) / 255.0f; float f5 = (float)(col2 >> 16 & 0xFF) / 255.0f; float f6 = (float)(col2 >> 8 & 0xFF) / 255.0f; float f7 = (float)(col2 & 0xFF) / 255.0f; GL11.glEnable(3042); GL11.glDisable(3553); GL11.glBlendFunc(770, 771); GL11.glEnable(2848); GL11.glShadeModel(7425); GL11.glPushMatrix(); GL11.glBegin(7); GL11.glColor4f(f1, f2, f3, f); GL11.glVertex2d(left, top); GL11.glVertex2d(left, bottom); GL11.glColor4f(f5, f6, f7, f4); GL11.glVertex2d(right, bottom); GL11.glVertex2d(right, top); GL11.glEnd(); GL11.glPopMatrix(); GL11.glEnable(3553); GL11.glDisable(3042); } public static void enableGL2D() { GL11.glDisable(2929); GL11.glEnable(3042); GL11.glDisable(3553); GL11.glBlendFunc(770, 771); GL11.glDepthMask(true); GL11.glEnable(2848); GL11.glHint(3154, 4354); GL11.glHint(3155, 4354); } public static void disableGL2D() { GL11.glEnable(3553); GL11.glDisable(3042); GL11.glEnable(2929); GL11.glDisable(2848); GL11.glHint(3154, 4352); GL11.glHint(3155, 4352); } public static void relativeRect(float left, float top, float right, float bottom, int color) { if (left < right) { float i = left; left = right; right = i; } if (top < bottom) { float j = top; top = bottom; bottom = j; } float f3 = (float)(color >> 24 & 0xFF) / 255.0f; float f = (float)(color >> 16 & 0xFF) / 255.0f; float f1 = (float)(color >> 8 & 0xFF) / 255.0f; float f2 = (float)(color & 0xFF) / 255.0f; Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferBuilder = tessellator.getBuffer(); GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(f, f1, f2, f3); bufferBuilder.begin(7, DefaultVertexFormats.POSITION); bufferBuilder.pos(left, bottom, 0.0).endVertex(); bufferBuilder.pos(right, bottom, 0.0).endVertex(); bufferBuilder.pos(right, top, 0.0).endVertex(); bufferBuilder.pos(left, top, 0.0).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } public static void drawBorderedRect(double left, double top, double right, double bottom, double borderWidth, int insideColor, int borderColor, boolean borderIncludedInBounds) { RenderUtil.drawRect(left - (!borderIncludedInBounds ? borderWidth : 0.0), top - (!borderIncludedInBounds ? borderWidth : 0.0), right + (!borderIncludedInBounds ? borderWidth : 0.0), bottom + (!borderIncludedInBounds ? borderWidth : 0.0), borderColor); RenderUtil.drawRect(left + (borderIncludedInBounds ? borderWidth : 0.0), top + (borderIncludedInBounds ? borderWidth : 0.0), right - (borderIncludedInBounds ? borderWidth : 0.0), bottom - (borderIncludedInBounds ? borderWidth : 0.0), insideColor); } public static void drawRect(double left, double top, double right, double bottom, int color) { if (left < right) { double i = left; left = right; right = i; } if (top < bottom) { double j = top; top = bottom; bottom = j; } float f3 = (float)(color >> 24 & 0xFF) / 255.0f; float f = (float)(color >> 16 & 0xFF) / 255.0f; float f1 = (float)(color >> 8 & 0xFF) / 255.0f; float f2 = (float)(color & 0xFF) / 255.0f; Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferBuilder = tessellator.getBuffer(); GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(f, f1, f2, f3); bufferBuilder.begin(7, DefaultVertexFormats.POSITION); bufferBuilder.pos(left, bottom, 0.0).endVertex(); bufferBuilder.pos(right, bottom, 0.0).endVertex(); bufferBuilder.pos(right, top, 0.0).endVertex(); bufferBuilder.pos(left, top, 0.0).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } public static void drawRectOpacity(double left, double top, double right, double bottom, float opacity) { if (left < right) { double i = left; left = right; right = i; } if (top < bottom) { double j = top; top = bottom; bottom = j; } Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferBuilder = tessellator.getBuffer(); GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(0.1f, 0.1f, 0.1f, opacity); bufferBuilder.begin(7, DefaultVertexFormats.POSITION); bufferBuilder.pos(left, bottom, 0.0).endVertex(); bufferBuilder.pos(right, bottom, 0.0).endVertex(); bufferBuilder.pos(right, top, 0.0).endVertex(); bufferBuilder.pos(left, top, 0.0).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } public static void drawNewRect(double left, double top, double right, double bottom, int color) { if (left < right) { double i = left; left = right; right = i; } if (top < bottom) { double j = top; top = bottom; bottom = j; } float f3 = (float)(color >> 24 & 0xFF) / 255.0f; float f = (float)(color >> 16 & 0xFF) / 255.0f; float f1 = (float)(color >> 8 & 0xFF) / 255.0f; float f2 = (float)(color & 0xFF) / 255.0f; Tessellator tessellator = Tessellator.getInstance(); BufferBuilder vertexbuffer = tessellator.getBuffer(); GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.color(f, f1, f2, f3); vertexbuffer.begin(7, DefaultVertexFormats.POSITION); vertexbuffer.pos(left, bottom, 0.0).endVertex(); vertexbuffer.pos(right, bottom, 0.0).endVertex(); vertexbuffer.pos(right, top, 0.0).endVertex(); vertexbuffer.pos(left, top, 0.0).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } public static boolean isInViewFrustrum(Entity entity) { return RenderUtil.isInViewFrustrum(entity.getEntityBoundingBox()) || entity.ignoreFrustumCheck; } public static void drawLinesAroundPlayer(Entity entity, double radius, float partialTicks, int points, float width, int color) { GL11.glPushMatrix(); RenderUtil.enableGL2D3(); GL11.glDisable(3553); GL11.glEnable(2848); GL11.glHint(3154, 4354); GL11.glDisable(2929); GL11.glLineWidth(width); GL11.glEnable(3042); GL11.glBlendFunc(770, 771); GL11.glDisable(2929); GL11.glBegin(3); RenderManager renderManager = Minecraft.getMinecraft().getRenderManager(); double x = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double)partialTicks - renderManager.viewerPosX; double y = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double)partialTicks - renderManager.viewerPosY; double z = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double)partialTicks - renderManager.viewerPosZ; RenderUtil.color228(color); for (int i = 0; i <= points; ++i) { GL11.glVertex3d(x + radius * Math.cos((double)i * (Math.PI * 2) / (double)points), y, z + radius * Math.sin((double)i * (Math.PI * 2) / (double)points)); } GL11.glEnd(); GL11.glDepthMask(true); GL11.glDisable(3042); GL11.glEnable(2929); GL11.glDisable(2848); GL11.glEnable(2929); GL11.glEnable(3553); RenderUtil.disableGL2D3(); GL11.glPopMatrix(); } public static void enableGL2D3() { GL11.glDisable(2929); GL11.glEnable(3042); GL11.glDisable(3553); GL11.glBlendFunc(770, 771); GL11.glDepthMask(true); GL11.glEnable(2848); GL11.glHint(3154, 4354); GL11.glHint(3155, 4354); } public static void disableGL2D3() { GL11.glEnable(3553); GL11.glDisable(3042); GL11.glEnable(2929); GL11.glDisable(2848); GL11.glHint(3154, 4352); GL11.glHint(3155, 4352); } public static void color228(int color) { GL11.glColor4ub((byte)(color >> 16 & 0xFF), (byte)(color >> 8 & 0xFF), (byte)(color & 0xFF), (byte)(color >> 24 & 0xFF)); } private static boolean isInViewFrustrum(AxisAlignedBB bb) { Entity current = mc.getRenderViewEntity(); frustrum.setPosition(current.posX, current.posY, current.posZ); return frustrum.isBoundingBoxInFrustum(bb); } public static void glColor(int hex) { float alpha = (float)(hex >> 24 & 0xFF) / 255.0f; float red = (float)(hex >> 16 & 0xFF) / 255.0f; float green = (float)(hex >> 8 & 0xFF) / 255.0f; float blue = (float)(hex & 0xFF) / 255.0f; GL11.glColor4f(red, green, blue, alpha); } public static void blockEsp(BlockPos blockPos, Color c, double length, double length2) { double d = blockPos.getX(); Minecraft.getMinecraft().getRenderManager(); double x = d - RenderManager.renderPosX; double d2 = blockPos.getY(); Minecraft.getMinecraft().getRenderManager(); double y = d2 - RenderManager.renderPosY; double d3 = blockPos.getZ(); Minecraft.getMinecraft().getRenderManager(); double z = d3 - RenderManager.renderPosZ; GL11.glPushMatrix(); GL11.glBlendFunc(770, 771); GL11.glEnable(3042); GL11.glLineWidth(2.0f); GL11.glDisable(3553); GL11.glDisable(2929); GL11.glDepthMask(false); GL11.glColor4d((float)c.getRed() / 255.0f, (float)c.getGreen() / 255.0f, (float)c.getBlue() / 255.0f, 0.15); RenderUtil.drawColorBox(new AxisAlignedBB(x, y, z, x + length2, y + 1.0, z + length), 0.0f, 0.0f, 0.0f, 0.0f); GL11.glColor4d(0.0, 0.0, 0.0, 0.5); RenderUtil.drawSelectionBoundingBox(new AxisAlignedBB(x, y, z, x + length2, y + 1.0, z + length)); GL11.glLineWidth(2.0f); GL11.glEnable(3553); GL11.glEnable(2929); GL11.glDepthMask(true); GL11.glDisable(3042); GL11.glPopMatrix(); } public static void blockEspFrame(BlockPos blockPos, double red, double green, double blue) { double d = blockPos.getX(); Minecraft.getMinecraft().getRenderManager(); double x = d - RenderManager.renderPosX; double d2 = blockPos.getY(); Minecraft.getMinecraft().getRenderManager(); double y = d2 - RenderManager.renderPosY; double d3 = blockPos.getZ(); Minecraft.getMinecraft().getRenderManager(); double z = d3 - RenderManager.renderPosZ; GL11.glBlendFunc(770, 771); GL11.glEnable(3042); GL11.glLineWidth(1.0f); GL11.glDisable(3553); GL11.glDisable(2929); GL11.glDepthMask(false); GL11.glColor4d(red, green, blue, 0.5); RenderUtil.drawSelectionBoundingBox(new AxisAlignedBB(x, y, z, x + 1.0, y + 1.0, z + 1.0)); GL11.glEnable(3553); GL11.glEnable(2929); GL11.glDepthMask(true); GL11.glDisable(3042); } public static void drawOutlinedString(String str, FontRenderer font, float x, float y, int color) { Minecraft mc = Minecraft.getMinecraft(); font.drawString(str, x - 0.3f, y, ColorUtils.getColor(0)); font.drawString(str, x + 0.3f, y, ColorUtils.getColor(0)); font.drawString(str, x, y + 0.3f, ColorUtils.getColor(0)); font.drawString(str, x, y - 0.3f, ColorUtils.getColor(0)); font.drawString(str, x, y, color); } public static void drawSelectionBoundingBox(AxisAlignedBB boundingBox) { Tessellator tessellator = Tessellator.getInstance(); BufferBuilder vertexbuffer = tessellator.getBuffer(); vertexbuffer.begin(3, DefaultVertexFormats.POSITION); vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex(); tessellator.draw(); vertexbuffer.begin(3, DefaultVertexFormats.POSITION); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex(); tessellator.draw(); vertexbuffer.begin(1, DefaultVertexFormats.POSITION); vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex(); tessellator.draw(); } public static void drawColorBox(AxisAlignedBB axisalignedbb, float red, float green, float blue, float alpha) { Tessellator ts = Tessellator.getInstance(); BufferBuilder vb = ts.getBuffer(); vb.begin(7, DefaultVertexFormats.POSITION_TEX); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); ts.draw(); vb.begin(7, DefaultVertexFormats.POSITION_TEX); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); ts.draw(); vb.begin(7, DefaultVertexFormats.POSITION_TEX); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); ts.draw(); vb.begin(7, DefaultVertexFormats.POSITION_TEX); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); ts.draw(); vb.begin(7, DefaultVertexFormats.POSITION_TEX); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); ts.draw(); vb.begin(7, DefaultVertexFormats.POSITION_TEX); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); vb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex(); ts.draw(); } public static void drawEntityESP(Entity entity, Color c) { GL11.glPushMatrix(); GL11.glBlendFunc(770, 771); GL11.glEnable(3042); GL11.glLineWidth(1.0f); GL11.glDisable(3553); GL11.glDisable(2929); GL11.glDepthMask(false); GL11.glColor4d((float)c.getRed() / 255.0f, (float)c.getGreen() / 255.0f, (float)c.getBlue() / 255.0f, 0.15f); RenderManager renderManager = Minecraft.getMinecraft().getRenderManager(); RenderUtil.drawColorBox(new AxisAlignedBB(entity.boundingBox.minX - 0.05 - entity.posX + (entity.posX - RenderManager.renderPosX), entity.boundingBox.minY - entity.posY + (entity.posY - RenderManager.renderPosY), entity.boundingBox.minZ - 0.05 - entity.posZ + (entity.posZ - RenderManager.renderPosZ), entity.boundingBox.maxX + 0.05 - entity.posX + (entity.posX - RenderManager.renderPosX), entity.boundingBox.maxY + 0.1 - entity.posY + (entity.posY - RenderManager.renderPosY), entity.boundingBox.maxZ + 0.05 - entity.posZ + (entity.posZ - RenderManager.renderPosZ)), 0.0f, 0.0f, 0.0f, 0.0f); GL11.glColor4d(0.0, 0.0, 0.0, 0.5); RenderUtil.drawSelectionBoundingBox(new AxisAlignedBB(entity.boundingBox.minX - 0.05 - entity.posX + (entity.posX - RenderManager.renderPosX), entity.boundingBox.minY - entity.posY + (entity.posY - RenderManager.renderPosY), entity.boundingBox.minZ - 0.05 - entity.posZ + (entity.posZ - RenderManager.renderPosZ), entity.boundingBox.maxX + 0.05 - entity.posX + (entity.posX - RenderManager.renderPosX), entity.boundingBox.maxY + 0.1 - entity.posY + (entity.posY - RenderManager.renderPosY), entity.boundingBox.maxZ + 0.05 - entity.posZ + (entity.posZ - RenderManager.renderPosZ))); GL11.glLineWidth(2.0f); GL11.glEnable(3553); GL11.glEnable(2929); GL11.glDepthMask(true); GL11.glDisable(3042); GL11.glPopMatrix(); } public static void rectangleBordered(double x, double y, double x1, double y1, double width, int internalColor, int borderColor) { RenderUtil.drawRect(x + width, y + width, x1 - width, y1 - width, internalColor); RenderUtil.drawRect(x + width, y, x1 - width, y + width, borderColor); RenderUtil.drawRect(x, y, x + width, y1, borderColor); RenderUtil.drawRect(x1 - width, y, x1, y1, borderColor); RenderUtil.drawRect(x + width, y1 - width, x1 - width, y1, borderColor); } }
54.711599
601
0.663783
b6eef5b70c1d22902f38c5a430ac547cb449af2d
1,607
/* * Copyright (C) 2005-2020 Gregory Hedlund & Yvan Rose * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.phon.ui; import java.awt.*; import java.text.*; import ca.phon.formatter.*; /** * Formatter for {@link Font}s */ @FormatterType(value=Font.class) public class FontFormatter implements Formatter<Font> { @Override public String format(Font obj) { return fontToString(obj); } @Override public Font parse(String text) throws ParseException { return Font.decode(text); } /** * Converts the specified font into a string that can be used by * Font.decode. * @param font the Font to convert to a String * @return a String */ private String fontToString(Font font) { StringBuilder ret = new StringBuilder(); ret.append(font.getFamily()); ret.append("-"); if(font.isBold()) { if(font.isItalic()) ret.append("BOLDITALIC"); else ret.append("BOLD"); } else if(font.isItalic()) { ret.append("ITALIC"); } else { ret.append("PLAIN"); } ret.append("-"); ret.append(font.getSize()); return ret.toString(); } }
23.632353
75
0.686372
2043c8cab92a59d52fba5ecd3ce4a7623255993c
199
package com.smlnskgmail.jaman.hashchecker.features.hashcalculator.input; import androidx.annotation.NonNull; public interface TextValueTarget { void textValueEntered(@NonNull String text); }
19.9
72
0.81407
0bd5f99c575a1a20e73d8a92405bea7abffb810f
282
package Integracion.Avion; import Negocio.Avion.imp.TransferAvion; public interface DaoAvion { public boolean add(TransferAvion t); public TransferAvion search(String matricula); public TransferAvion searchId(int id); public boolean update(TransferAvion t); }
21.692308
48
0.762411
8c491ee21a9aa4fd5ef8c524d311ee159d8bd1cd
2,617
package org.qcri.rheem.core.optimizer.costs; import org.qcri.rheem.core.optimizer.ProbabilisticIntervalEstimate; import org.qcri.rheem.core.util.Formats; import java.util.Comparator; /** * An estimate of time (in <b>milliseconds</b>) expressed as a {@link ProbabilisticIntervalEstimate}. */ public class TimeEstimate extends ProbabilisticIntervalEstimate { public static final TimeEstimate ZERO = new TimeEstimate(0); public static final TimeEstimate MINIMUM = new TimeEstimate(1); public TimeEstimate(long estimate) { super(estimate, estimate, 1d); } public TimeEstimate(long lowerEstimate, long upperEstimate, double correctnessProb) { super(lowerEstimate, upperEstimate, correctnessProb); } public TimeEstimate plus(TimeEstimate that) { return new TimeEstimate( this.getLowerEstimate() + that.getLowerEstimate(), this.getUpperEstimate() + that.getUpperEstimate(), Math.min(this.getCorrectnessProbability(), that.getCorrectnessProbability()) ); } /** * Provides a {@link Comparator} for {@link TimeEstimate}s. For two {@link TimeEstimate}s {@code t1} and {@code t2}, * it works as follows: * <ol> * <li>If a either of the {@link TimeEstimate}s has a correctness probability of 0, we consider it to be greater.</li> * <li>Otherwise, we compare the two {@link TimeEstimate}s by their average estimation value.</li> * </ol> * @return */ public static Comparator<TimeEstimate> expectationValueComparator() { return (t1, t2) -> { if (t1.getCorrectnessProbability() == 0d) { if (t2.getCorrectnessProbability() != 0d) { return 1; } } else if (t2.getCorrectnessProbability() == 0d) { return -1; } return Long.compare(t1.getAverageEstimate(), t2.getAverageEstimate()); }; } @Override public String toString() { return String.format("%s[%s .. %s, conf=%s]", this.getClass().getSimpleName(), Formats.formatDuration(this.getLowerEstimate()), Formats.formatDuration(this.getUpperEstimate()), Formats.formatPercentage(this.getCorrectnessProbability())); } public TimeEstimate times(double scalar) { return new TimeEstimate( Math.round(this.getLowerEstimate() * scalar), Math.round(this.getUpperEstimate() * scalar), this.getCorrectnessProbability() ); } }
36.347222
126
0.627054
ce47cebd86dd05f7fc3ea71f2d61171eecd8ec67
511
package jetbrains.buildServer.clouds.kubernetes.podSpec; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; /** * Created by ekoshkin (koshkinev@gmail.com) on 15.06.17. */ public interface BuildAgentPodTemplateProviders { @NotNull Collection<BuildAgentPodTemplateProvider> getAll(); @Nullable BuildAgentPodTemplateProvider find(@Nullable String id); @NotNull BuildAgentPodTemplateProvider get(@Nullable String id); }
24.333333
60
0.778865
4c8f180440df4ea6735259827cf60d76e0019262
20,917
package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.util.io.DataExternalizer; import gnu.trove.TIntHashSet; import gnu.trove.TIntProcedure; import org.jetbrains.asm4.Type; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.PrintStream; import java.util.*; /** * @author: db * Date: 14.02.11 */ class UsageRepr { private static final byte FIELD_USAGE = 0x0; private static final byte FIELD_ASSIGN_USAGE = 0x1; private static final byte METHOD_USAGE = 0x2; private static final byte CLASS_USAGE = 0x3; private static final byte CLASS_EXTENDS_USAGE = 0x4; private static final byte CLASS_NEW_USAGE = 0x5; private static final byte ANNOTATION_USAGE = 0x6; private static final byte METAMETHOD_USAGE = 0x7; private static final byte CLASS_AS_GENERIC_BOUND_USAGE = 0x8; private static final int DEFAULT_SET_CAPACITY = 32; private static final float DEFAULT_SET_LOAD_FACTOR = 0.98f; private UsageRepr() { } public static abstract class Usage implements RW.Savable, Streamable { public abstract int getOwner(); } public static abstract class FMUsage extends Usage { public final int myName; public final int myOwner; abstract void kindToStream (PrintStream stream); @Override public void toStream(final DependencyContext context, final PrintStream stream) { kindToStream(stream); stream.println(" Name : " + context.getValue(myName)); stream.println(" Owner: " + context.getValue(myOwner)); } @Override public int getOwner() { return myOwner; } private FMUsage(final int name, final int owner) { this.myName = name; this.myOwner = owner; } private FMUsage(final DataInput in) { try { myName = in.readInt(); myOwner = in.readInt(); } catch (IOException e) { throw new RuntimeException(e); } } protected final void save(final byte tag, final DataOutput out) { try { out.writeByte(tag); out.writeInt(myName); out.writeInt(myOwner); } catch (IOException e) { throw new RuntimeException(e); } } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FMUsage fmUsage = (FMUsage)o; if (myName != fmUsage.myName) return false; if (myOwner != fmUsage.myOwner) return false; return true; } @Override public int hashCode() { return 31 * myName + myOwner; } } public static class FieldUsage extends FMUsage { public final TypeRepr.AbstractType myType; private FieldUsage(final DependencyContext context, final int name, final int owner, final int descriptor) { super(name, owner); myType = TypeRepr.getType(context, descriptor); } private FieldUsage(final DependencyContext context, final DataInput in) { super(in); try { myType = TypeRepr.externalizer(context).read(in); } catch (IOException e) { throw new RuntimeException(e); } } protected void kindToStream(final PrintStream stream) { stream.println("FieldUsage:"); } @Override public void toStream(final DependencyContext context, final PrintStream stream) { super.toStream(context, stream); stream.println(" Type: " + myType.getDescr(context)); } @Override public void save(final DataOutput out) { save(FIELD_USAGE, out); myType.save(out); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final FieldUsage that = (FieldUsage)o; return myType.equals(that.myType) && myName == that.myName && myOwner == that.myOwner; } @Override public int hashCode() { return 31 * (31 * myType.hashCode() + myName) + myOwner; } } public static class FieldAssignUsage extends FieldUsage { private FieldAssignUsage(final DependencyContext context, final int n, final int o, final int d) { super(context, n, o, d); } private FieldAssignUsage(final DependencyContext context, final DataInput in) { super(context, in); } @Override protected void kindToStream(final PrintStream stream) { stream.println("FieldAssignUsage:"); } @Override public void save(final DataOutput out) { save(FIELD_ASSIGN_USAGE, out); myType.save(out); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final FieldAssignUsage that = (FieldAssignUsage)o; return myType.equals(that.myType) && myName == that.myName && myOwner == that.myOwner; } @Override public int hashCode() { return super.hashCode() + 1; } } public static class MethodUsage extends FMUsage { public final TypeRepr.AbstractType[] myArgumentTypes; public final TypeRepr.AbstractType myReturnType; private MethodUsage(final DependencyContext context, final int name, final int owner, final String descriptor) { super(name, owner); myArgumentTypes = TypeRepr.getType(context, Type.getArgumentTypes(descriptor)); myReturnType = TypeRepr.getType(context, Type.getReturnType(descriptor)); } private MethodUsage(final DependencyContext context, final DataInput in) { super(in); try { final DataExternalizer<TypeRepr.AbstractType> externalizer = TypeRepr.externalizer(context); myArgumentTypes = RW.read(externalizer, in, new TypeRepr.AbstractType[in.readInt()]); myReturnType = externalizer.read(in); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void save(final DataOutput out) { save(METHOD_USAGE, out); RW.save(myArgumentTypes, out); myReturnType.save(out); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final MethodUsage that = (MethodUsage)o; if (!Arrays.equals(myArgumentTypes, that.myArgumentTypes)) return false; if (myReturnType != null ? !myReturnType.equals(that.myReturnType) : that.myReturnType != null) return false; if (myName != that.myName) return false; if (myOwner != that.myOwner) return false; return Arrays.equals(myArgumentTypes, that.myArgumentTypes) && myReturnType.equals(that.myReturnType) && myName == that.myName && myOwner == that.myOwner; } @Override public int hashCode() { return ((31 * Arrays.hashCode(myArgumentTypes) + (myReturnType.hashCode())) * 31 + (myName)) * 31 + (myOwner); } @Override void kindToStream(final PrintStream stream) { stream.println("MethodUsage:"); } @Override public void toStream(DependencyContext context, PrintStream stream) { super.toStream(context, stream); stream.println(" Arguments:"); for (final TypeRepr.AbstractType at : myArgumentTypes) { stream.println(" " + at.getDescr(context)); } stream.println(" Return type:"); stream.println(" " + myReturnType.getDescr(context)); } } public static class MetaMethodUsage extends FMUsage { private int myArity; public MetaMethodUsage(final DependencyContext context, final int n, final int o, final String descr) { super(n, o); myArity = TypeRepr.getType(context, Type.getArgumentTypes(descr)).length; } public MetaMethodUsage(final DataInput in) { super(in); try { myArity = in.readInt(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void save(final DataOutput out) { save(METAMETHOD_USAGE, out); try { out.writeInt(myArity); } catch (IOException e) { throw new RuntimeException(e); } } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MetaMethodUsage that = (MetaMethodUsage)o; if (myArity != that.myArity) return false; return super.equals(o); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + myArity; return result; } @Override void kindToStream(final PrintStream stream) { stream.println("MetaMethodUsage:"); } @Override public void toStream(DependencyContext context, PrintStream stream) { super.toStream(context, stream); stream.println(" Arity: " + Integer.toString(myArity)); } } public static class ClassUsage extends Usage { final int myClassName; @Override public int getOwner() { return myClassName; } private ClassUsage(final int className) { this.myClassName = className; } private ClassUsage(final DataInput in) { try { myClassName = in.readInt(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void save(final DataOutput out) { try { out.writeByte(CLASS_USAGE); out.writeInt(myClassName); } catch (IOException e) { throw new RuntimeException(e); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ClassUsage that = (ClassUsage)o; return myClassName == that.myClassName; } @Override public int hashCode() { return myClassName; } @Override public void toStream(final DependencyContext context, final PrintStream stream) { stream.println("ClassUsage: " + context.getValue(myClassName)); } } public static class ClassAsGenericBoundUsage extends ClassUsage { public ClassAsGenericBoundUsage(int className) { super(className); } public ClassAsGenericBoundUsage(DataInput in) { super(in); } @Override public int hashCode() { return super.hashCode() + 3; } @Override public void save(final DataOutput out) { try { out.writeByte(CLASS_AS_GENERIC_BOUND_USAGE); out.writeInt(myClassName); } catch (IOException e) { throw new RuntimeException(e); } } } public static class ClassExtendsUsage extends Usage { protected final int myClassName; @Override public int getOwner() { return myClassName; } private ClassExtendsUsage(final int className) { this.myClassName = className; } private ClassExtendsUsage(final DataInput in) { try { myClassName = in.readInt(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void save(final DataOutput out) { try { out.writeByte(CLASS_EXTENDS_USAGE); out.writeInt(myClassName); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int hashCode() { return myClassName + 1; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassExtendsUsage that = (ClassExtendsUsage)o; if (myClassName != that.myClassName) return false; return true; } @Override public void toStream(final DependencyContext context, final PrintStream stream) { stream.println("ClassExtendsUsage: " + context.getValue(myClassName)); } } public static class ClassNewUsage extends ClassExtendsUsage { public ClassNewUsage(int className) { super(className); } private ClassNewUsage(final DataInput in) { super(in); } @Override public void save(final DataOutput out) { try { out.writeByte(CLASS_NEW_USAGE); out.writeInt(myClassName); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int hashCode() { return myClassName + 2; } @Override public void toStream(final DependencyContext context, final PrintStream stream) { stream.println("ClassNewUsage: " + context.getValue(myClassName)); } } public static class AnnotationUsage extends Usage { public static final DataExternalizer<ElemType> elementTypeExternalizer = new DataExternalizer<ElemType>() { @Override public void save(final DataOutput out, final ElemType value) throws IOException { out.writeInt(value.ordinal()); } @Override public ElemType read(final DataInput in) throws IOException { final int ordinal = in.readInt(); for (ElemType value : ElemType.values()) { if (value.ordinal() == ordinal) { return value; } } throw new IOException("Error reading ElementType enum value; unknown ordinal: " + ordinal); } }; final TypeRepr.ClassType myType; final TIntHashSet myUsedArguments; final Set<ElemType> myUsedTargets; public boolean satisfies(final Usage usage) { if (usage instanceof AnnotationUsage) { final AnnotationUsage annotationUsage = (AnnotationUsage)usage; if (!myType.equals(annotationUsage.myType)) { return false; } boolean argumentsSatisfy = false; if (myUsedArguments != null) { final TIntHashSet arguments = new TIntHashSet(myUsedArguments.toArray()); arguments.removeAll(annotationUsage.myUsedArguments.toArray()); argumentsSatisfy = !arguments.isEmpty(); } boolean targetsSatisfy = false; if (myUsedTargets != null) { final Collection<ElemType> targets = EnumSet.copyOf(myUsedTargets); targets.retainAll(annotationUsage.myUsedTargets); targetsSatisfy = !targets.isEmpty(); } return argumentsSatisfy || targetsSatisfy; } return false; } private AnnotationUsage(final TypeRepr.ClassType type, final TIntHashSet usedArguments, final Set<ElemType> targets) { this.myType = type; this.myUsedArguments = usedArguments; this.myUsedTargets = targets; } private AnnotationUsage(final DependencyContext context, final DataInput in) { final DataExternalizer<TypeRepr.AbstractType> externalizer = TypeRepr.externalizer(context); try { myType = (TypeRepr.ClassType)externalizer.read(in); myUsedArguments = RW.read(new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR), in); myUsedTargets = (EnumSet<ElemType>)RW.read(elementTypeExternalizer, EnumSet.noneOf(ElemType.class), in); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void save(final DataOutput out) { try { out.writeByte(ANNOTATION_USAGE); myType.save(out); RW.save(myUsedArguments, out); RW.save(myUsedTargets, elementTypeExternalizer, out); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int getOwner() { return myType.className; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnnotationUsage that = (AnnotationUsage)o; if (myUsedArguments != null ? !myUsedArguments.equals(that.myUsedArguments) : that.myUsedArguments != null) return false; if (myUsedTargets != null ? !myUsedTargets.equals(that.myUsedTargets) : that.myUsedTargets != null) return false; if (myType != null ? !myType.equals(that.myType) : that.myType != null) return false; return true; } @Override public int hashCode() { int result = myType != null ? myType.hashCode() : 0; result = 31 * result + (myUsedArguments != null ? myUsedArguments.hashCode() : 0); result = 31 * result + (myUsedTargets != null ? myUsedTargets.hashCode() : 0); return result; } @Override public void toStream(final DependencyContext context, final PrintStream stream) { stream.println(" AnnotationUsage:"); stream.println(" Type : " + myType.getDescr(context)); final List<String> arguments = new LinkedList<String>(); if (myUsedArguments != null) { myUsedArguments.forEach(new TIntProcedure() { @Override public boolean execute(final int value) { arguments.add(context.getValue(value)); return true; } }); } Collections.sort(arguments); final List<String> targets = new LinkedList<String>(); if (myUsedTargets != null) { for (final ElemType e : myUsedTargets) { targets.add(e.toString()); } } Collections.sort(targets); stream.println(" Arguments:"); for (final String s : arguments) { stream.println(" " + s); } stream.println(" Targets :"); for (final String s : targets) { stream.println(" " + s); } } } public static Usage createFieldUsage(final DependencyContext context, final int name, final int owner, final int descr) { return context.getUsage(new FieldUsage(context, name, owner, descr)); } public static Usage createFieldAssignUsage(final DependencyContext context, final int name, final int owner, final int descr) { return context.getUsage(new FieldAssignUsage(context, name, owner, descr)); } public static Usage createMethodUsage(final DependencyContext context, final int name, final int owner, final String descr) { return context.getUsage(new MethodUsage(context, name, owner, descr)); } public static Usage createMetaMethodUsage(final DependencyContext context, final int name, final int owner, final String descr) { return context.getUsage(new MetaMethodUsage(context, name, owner, descr)); } public static Usage createClassUsage(final DependencyContext context, final int name) { return context.getUsage(new ClassUsage(name)); } public static Usage createClassAsGenericBoundUsage(final DependencyContext context, final int name) { return context.getUsage(new ClassAsGenericBoundUsage(name)); } public static Usage createClassExtendsUsage(final DependencyContext context, final int name) { return context.getUsage(new ClassExtendsUsage(name)); } public static Usage createClassNewUsage(final DependencyContext context, final int name) { return context.getUsage(new ClassNewUsage(name)); } public static Usage createAnnotationUsage(final DependencyContext context, final TypeRepr.ClassType type, final TIntHashSet usedArguments, final Set<ElemType> targets) { return context.getUsage(new AnnotationUsage(type, usedArguments, targets)); } public static DataExternalizer<Usage> externalizer(final DependencyContext context) { return new DataExternalizer<Usage>() { @Override public void save(final DataOutput out, final Usage value) throws IOException { value.save(out); } @Override public Usage read(DataInput in) throws IOException { final byte tag = in.readByte(); switch (tag) { case CLASS_USAGE: return context.getUsage(new ClassUsage(in)); case CLASS_AS_GENERIC_BOUND_USAGE: return context.getUsage(new ClassAsGenericBoundUsage(in)); case CLASS_EXTENDS_USAGE: return context.getUsage(new ClassExtendsUsage(in)); case CLASS_NEW_USAGE: return context.getUsage(new ClassNewUsage(in)); case FIELD_USAGE: return context.getUsage(new FieldUsage(context, in)); case FIELD_ASSIGN_USAGE: return context.getUsage(new FieldAssignUsage(context, in)); case METHOD_USAGE: return context.getUsage(new MethodUsage(context, in)); case ANNOTATION_USAGE: return context.getUsage(new AnnotationUsage(context, in)); case METAMETHOD_USAGE: return context.getUsage(new MetaMethodUsage(in)); } assert (false); return null; } }; } }
28.575137
131
0.641488
0935fe1ad9e289f113296816b5e1e135caf23698
1,084
package com.liuyiyang.code.client; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; /** * Description: * <br/>��վ: <a href="http://www.crazyit.org">���Java����</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class MyClient { public static void main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1", 30000); // �ͻ�������ClientThread�̲߳��϶�ȡ���Է����������� new Thread(new ClientThread(s)).start(); // �� // ��ȡ��Socket��Ӧ������� PrintStream ps = new PrintStream(s.getOutputStream()); String line = null; // ���϶�ȡ�������� BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); while ((line = br.readLine()) != null) { // ���û��ļ�����������д��Socket��Ӧ������� ps.println(line); } } }
30.111111
62
0.555351
e1b0469479fa74977c1de6a69cf34db49320cac8
457
package com.alexrnl.jseries.request.parameters; /** * Parameter which allow to set the episode number.<br /> * @author Alex */ public class Episode extends Parameter<Integer> { /** Name of the episode parameter */ public static final String PARAMETER_EPISODE = "episode"; /** * Constructor #1.<br /> * @param episode * the number of the episode. */ public Episode (final Integer episode) { super(PARAMETER_EPISODE, episode); } }
22.85
58
0.68709
1e01365accf8a3b3e79c3778a484980c47500d86
1,777
package org.dbpedia.dbtax.utils; import java.awt.Point; import java.util.ArrayList; import java.util.List; import org.dbpedia.dbtax.database.CategoryDB; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * * This class has all functions related to threshold calculations. * We calculated threshold to avoid any administrative categories during the leaf extraction. * */ public class ThresholdCalculations { private static final Logger logger = LoggerFactory.getLogger(ThresholdCalculations.class); private ThresholdCalculations() { } //Gets the list of categories along with their slopes. private static List<Point> calculuateNoOfCategories(){ ArrayList<Point> points = new ArrayList(); for(int i=0;i<1000;i++){ Point p = new Point(i,CategoryDB.getCategoryPageCount(i)); points.add(p); System.out.println(p.getX()+","+p.getY()); } return points; } //This function calculates and returns the Threshold. public static int findThreshold(){ List<Point> points = calculuateNoOfCategories(); int count =0; int i=0; while(count<5){ double slope = caluculateSlope(points.get(i), points.get(i+1)); System.out.println("heree"+ i+" "+slope); if(slope<10) count++; i++; } return i; } //Helper Function: Calculates the slope, given two points private static double caluculateSlope(Point p1, Point p2){ double deltaX = p2.getX()-p1.getX(); double deltaY = p2.getY()-p1.getY(); return deltaY/deltaX; } public static void main(String[] argv){ org.slf4j.Logger logger = LoggerFactory.getLogger(ThresholdCalculations.class); int threshold =ThresholdCalculations.findThreshold(); System.out.println(threshold); } }
29.131148
93
0.693303
5c0728fc742ef3d0de1f78bcf56eba24a7bc269e
4,976
// Copyright (c) 2010 Rob Eden. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Intrepid 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 <COPYRIGHT HOLDER> 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.starlight.intrepid; import com.starlight.intrepid.exception.ObjectNotBoundException; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * */ public class LocalRegistry implements Registry { private final VMID vmid; private final Lock map_lock = new ReentrantLock(); private final Map<String,Proxy> proxy_map = new HashMap<String, Proxy>(); private final TIntObjectMap<String> id_to_name_map = new TIntObjectHashMap<String>(); private final Condition new_object_condition = map_lock.newCondition(); private Intrepid instance; LocalRegistry( VMID vmid ) { this.vmid = vmid; } @Override public Object lookup( String name ) throws ObjectNotBoundException { map_lock.lock(); try { Object obj = proxy_map.get( name ); if ( obj == null ) { throw new ObjectNotBoundException( "Object not bound: " + name ); } else return obj; } finally { map_lock.unlock(); } } @Override public Object tryLookup( String name, long timeout, TimeUnit timeout_unit ) throws InterruptedException { map_lock.lock(); try { Object obj = proxy_map.get( name ); if ( obj != null ) return obj; long remaining = timeout_unit.toNanos( timeout ); while( remaining > 0 ) { long start = System.nanoTime(); new_object_condition.await( remaining, TimeUnit.NANOSECONDS ); obj = proxy_map.get( name ); if ( obj != null ) return obj; remaining -= ( System.nanoTime() - start ); } return null; } finally { map_lock.unlock(); } } /** * Bind an object in the registry. */ public void bind( String name, Object object ) { Objects.requireNonNull( name ); Objects.requireNonNull( object ); final Object original_object = object; // Make sure it's a proxy if ( !ProxyKit.isProxy( object ) ) { object = instance.createProxy( object ); assert object != null : "Null object returned from Intrepid.createProxy() for object: " + original_object; } else if ( !ProxyKit.isProxyLocal( object, vmid ) ) { throw new IllegalArgumentException( "Proxy must be local" ); } Proxy proxy = ( Proxy ) object; map_lock.lock(); try { proxy_map.put( name, proxy ); id_to_name_map.put( proxy.__intrepid__getObjectID(), name ); proxy.__intrepid__setPersistentName( name ); new_object_condition.signalAll(); } finally { map_lock.unlock(); } instance.getLocalCallHandler().markBound( proxy.__intrepid__getObjectID(), true ); } /** * Remove an object from the registry. */ @SuppressWarnings( "WeakerAccess" ) public void unbind( String name ) { Proxy proxy; map_lock.lock(); try { proxy = proxy_map.remove( name ); if ( proxy != null ) { id_to_name_map.remove( proxy.__intrepid__getObjectID() ); } } finally { map_lock.unlock(); } if ( proxy != null ) { proxy.__intrepid__setPersistentName( null ); instance.getLocalCallHandler().markBound( proxy.__intrepid__getObjectID(), false ); } } void setInstance( Intrepid instance ) { assert vmid.equals( instance.getLocalVMID() ) : vmid + " != " + instance.getLocalVMID(); this.instance = instance; } }
28.434286
86
0.711817
b9efbb47cbf09e2bf746ed2d3f7865d215d43750
2,680
package com.safie.rtsp; // import org.slf4j.Logger; // import org.slf4j.LoggerFactory; import com.safie.rtsp.core.*; import com.safie.rtsp.util.GeneralUtil; import com.safie.rtp.server.*; import com.safie.rtp.session.*; import com.safie.rtp.media.*; import com.safie.rtp.packet.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Set; import java.util.HashSet; import java.io.File; import java.io.IOException; import javax.sound.sampled.UnsupportedAudioFileException; public class Main { private static Logger logger = LogManager.getLogger(Main.class); private static final String DEFAULT_IP = "localhost"; private static final Integer DEFAULT_PORT = 8070; public static void main(String[] args) { // ipとportの初期化 String ip = DEFAULT_IP; Integer port = DEFAULT_PORT; switch(args.length){ case 1: ip = args[0]; break; case 2: ip = args[0]; port = GeneralUtil.stringToIntegerWithDafault(args[1], DEFAULT_PORT); break; } Set<Integer> payloadTypes = new HashSet(1); payloadTypes.add(96); payloadTypes.add(0); RtpServer rtpServer = new SimpleRtpServer(); rtpServer.ssrc = 1024; final RtpSession rtpSession = new RtpSession(rtpServer, payloadTypes); RtcpSession rtcpSession = new RtcpSession(rtpServer); RtspServer server = new RtspServer(ip, port, rtpSession, rtcpSession); //RtspController rtspController = new RtspController(ip, port, session); try { //rtspController.start(); server.run(); Thread.sleep(1000*20); String filepath = "/Users/atsuki/Downloads/jazz_02.wav"; File aFile = new File(filepath); int counter = 0; while(counter < 100){ Audio audio = new Audio(aFile); logger.debug("audio stream frame size : "+ String.valueOf(audio.stream.available())); PacketGenerator generator = new AudioFilePacketGenerator(rtpServer.ssrc, audio); generator.setGeneratedListener(new MediaGeneratedListener(){ @Override public void whenGenerated(DataPacket packet){ rtpSession.sendPacket(packet); } }); generator.start(); counter += 1; Thread.sleep(1); } }catch(IOException e){ logger.error(e); return; }catch(UnsupportedAudioFileException e){ logger.error(e); return; }catch(java.lang.InterruptedException e){ logger.error(e); return; } catch (Exception e) { // logger.error(e.getMessage(), e); } } }
30.11236
97
0.644776
ff56b2a4e5c671e35540fa8464b49618a1f1c6ae
457
package coronavaitus.coronavairus.Services; import coronavaitus.coronavairus.Model.CoronaModel; import java.util.List; public interface CoronaServiceInterface { public CoronaModel save(CoronaModel cModel); public CoronaModel update(CoronaModel cModel, Integer id_corona_virus); public Integer delete(Integer id_corona_virus); public List<CoronaModel> getAllPersons(); public CoronaModel getPersonByIdPer(Integer id_corona_virus); }
28.5625
75
0.809628
a634b7cf6c55ace7f5f62ed3dea645f520b80a30
7,028
package net.poringsoft.imascggallery; import android.content.Context; import android.graphics.Point; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import net.poringsoft.imascggallery.data.EnvOption; import net.poringsoft.imascggallery.data.EnvPath; import net.poringsoft.imascggallery.data.IdleCardInfo; import net.poringsoft.imascggallery.data.SqlAccessManager; import net.poringsoft.imascggallery.utils.KanamojiCharUtils; import net.poringsoft.imascggallery.utils.PSDebug; /** * カード詳細を表示するフラグメント * Created by mry on 15/01/25. */ public class CardDetailFragment extends Fragment { //定数 //--------------------------------------------------------------------- private static final String ARG_SELECT_ALBUM_ID = "album_id"; private static final DisplayImageOptions IMAGE_OPTIONS_CLICKVIEW = new DisplayImageOptions.Builder() //画像表示の際にフェードを使用しない .cacheInMemory(true) .cacheOnDisk(true) .build(); //フィールド //--------------------------------------------------------------------- private int m_selectAlbumId= 0; private boolean m_showCardStatus = false; private boolean m_showCardFrame = true; private Point m_dispSize = new Point(); //初期化メソッド //--------------------------------------------------------------------- /** * インスタンスを生成する * @param albumId アルバムID * @return インスタンス */ public static CardDetailFragment newInstance(int albumId) { CardDetailFragment fragment = new CardDetailFragment(); Bundle args = new Bundle(); args.putInt(ARG_SELECT_ALBUM_ID, albumId); fragment.setArguments(args); return fragment; } /** * コンストラクタ * 基本的には呼び出さない。 * newInstanceを使用すること */ public CardDetailFragment() { } /** * Fragmentが生成された時 * Fragment操作データの構築を行う * @param savedInstanceState セーブデータ */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PSDebug.d("savedInstanceState=" + savedInstanceState); } /** * ビューの生成 */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { PSDebug.d("container=" + container); return inflater.inflate(R.layout.fragment_carddetail, container, false); } /** * Activity生成完了 * @param savedInstanceState セーブデータ */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); PSDebug.d("savedInstanceState=" + savedInstanceState); if (savedInstanceState != null) { //型番の復元 m_selectAlbumId = savedInstanceState.getInt(ARG_SELECT_ALBUM_ID); } else { //親画面からの型番の取得 Bundle argment = this.getArguments(); if (argment != null) { m_selectAlbumId = argment.getInt(ARG_SELECT_ALBUM_ID); } } //フィールド初期化 WindowManager wm = (WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getSize(m_dispSize); SqlAccessManager sqlManager = new SqlAccessManager(getActivity()); m_showCardStatus = EnvOption.getViewShowCardParam(getActivity()); m_showCardFrame = EnvOption.getViewShowCardFrame(getActivity()); //型番からカードデータを取得し表示にセットする IdleCardInfo cardInfo = sqlManager.selectIdleCardInfoFromAlbumId(m_selectAlbumId); if (cardInfo != null) { setCardInfo(getView(), cardInfo); } } /** * データの保存 * @param outState 保存先データ */ @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); PSDebug.d("call"); outState.putInt(ARG_SELECT_ALBUM_ID, m_selectAlbumId); } /** * カード情報を設定する * @param parentView レイアウトビュー * @param cardInfo カード情報 */ private void setCardInfo(View parentView, final IdleCardInfo cardInfo) { //カードタイトル TextView titleTextView = (TextView)parentView.findViewById(R.id.titleTextView); titleTextView.setText(cardInfo.getNamePrefix() + cardInfo.getName() + cardInfo.getNamePost()); //カード画像 final ImageView imageView = (ImageView)parentView.findViewById(R.id.cardImageView); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); double xyPercentage = (double) EnvOption.CARD_IMAGE_SIZE.y / (double)EnvOption.CARD_IMAGE_SIZE.x; double viewWidth = m_dispSize.x; imageView.setLayoutParams(new LinearLayout.LayoutParams((int)viewWidth, (int)(viewWidth * xyPercentage))); if (!cardInfo.getImageHash().equals("")) { ImageLoader.getInstance().displayImage(EnvPath.getIdleCardImageUrl(cardInfo, m_showCardFrame), imageView); } imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //画像をクリックすると枠の表示・非表示を反転させる m_showCardFrame = !m_showCardFrame; ImageLoader.getInstance().displayImage(EnvPath.getIdleCardImageUrl(cardInfo, m_showCardFrame), imageView, IMAGE_OPTIONS_CLICKVIEW); } }); LinearLayout statusLayout = (LinearLayout)parentView.findViewById(R.id.statusLayout); if (m_showCardStatus) { statusLayout.setVisibility(View.VISIBLE); TextView headTextView = (TextView)parentView.findViewById(R.id.headTextView); String headText = "属性\nレアリティ\nコスト\nアルバム攻\nアルバム守\n特技名\n備考"; headTextView.setText(headText); TextView detailTextView = (TextView)parentView.findViewById(R.id.detailTextView); String detailText = cardInfo.getAttribute() + "\n" + cardInfo.getRarity() + "\n" + cardInfo.getCost() + "\n" + cardInfo.getAttack() + "\n" + cardInfo.getDefense() + "\n" + toDetailStringData(cardInfo.getSkillName()) + "\n" + toDetailStringData(cardInfo.getRemarks()); detailTextView.setText(detailText); } else { statusLayout.setVisibility(View.GONE); } } /** * パラメーター詳細の文字列データを表示用に変換して返す * @param text パラメーターデータ文字列 * @return 変換後のデータ */ private String toDetailStringData(String text) { if (text.equals("")) { return " "; } return KanamojiCharUtils.hankakuKatakanaToZenkakuKatakana(text); } }
34.965174
147
0.641007
06febbaf771f3de78f6941e1fc89c8901d9392e0
4,277
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.usage_stats; import android.app.Activity; import android.content.res.Resources; import org.chromium.base.Callback; import org.chromium.chrome.R; import org.chromium.components.browser_ui.modaldialog.AppModalPresenter; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogType; import org.chromium.ui.modaldialog.ModalDialogProperties; import org.chromium.ui.modelutil.PropertyModel; /** * Dialog prompting a user to either enable integration with Digital Wellbeing or to revoke * permission for that integration. * TODO(pnoland): Revisit the style of this dialog and where it's used(i.e. whether it's used from * PrivacySettings or not) to ensure that the visual style is consistent. */ public class UsageStatsConsentDialog { private Activity mActivity; private ModalDialogManager mManager; private PropertyModel mDialogModel; private boolean mIsRevocation; private Callback<Boolean> mDidConfirmCallback; public static UsageStatsConsentDialog create( Activity activity, boolean isRevocation, Callback<Boolean> didConfirmCallback) { return new UsageStatsConsentDialog(activity, isRevocation, didConfirmCallback); } /** Show this dialog in the context of its enclosing activity. */ public void show() { Resources resources = mActivity.getResources(); PropertyModel.Builder builder = new PropertyModel.Builder(ModalDialogProperties.ALL_KEYS) .with(ModalDialogProperties.CONTROLLER, makeController()) .with(ModalDialogProperties.NEGATIVE_BUTTON_TEXT, resources, R.string.cancel); if (mIsRevocation) { builder.with(ModalDialogProperties.TITLE, resources, R.string.usage_stats_revocation_prompt) .with(ModalDialogProperties.MESSAGE, resources, R.string.usage_stats_revocation_explanation) .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, resources, R.string.remove); } else { builder.with(ModalDialogProperties.TITLE, resources, R.string.usage_stats_consent_title) .with(ModalDialogProperties.MESSAGE, resources, R.string.usage_stats_consent_prompt) .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, resources, R.string.show); } mDialogModel = builder.build(); mManager = new ModalDialogManager(new AppModalPresenter(mActivity), ModalDialogType.APP); mManager.showDialog(mDialogModel, ModalDialogType.APP); } private UsageStatsConsentDialog( Activity activity, boolean isRevocation, Callback<Boolean> didConfirmCallback) { mActivity = activity; mIsRevocation = isRevocation; mDidConfirmCallback = didConfirmCallback; } private ModalDialogProperties.Controller makeController() { return new ModalDialogProperties.Controller() { @Override public void onClick(PropertyModel model, int buttonType) { UsageStatsService service = UsageStatsService.getInstance(); boolean didConfirm = false; switch (buttonType) { case ModalDialogProperties.ButtonType.POSITIVE: didConfirm = true; break; case ModalDialogProperties.ButtonType.NEGATIVE: break; } if (didConfirm) { service.setOptInState(!mIsRevocation); } mDidConfirmCallback.onResult(didConfirm); dismiss(); } @Override public void onDismiss(PropertyModel model, int dismissalCause) { mDidConfirmCallback.onResult(false); mManager.destroy(); } }; } private void dismiss() { mManager.destroy(); } }
41.125
100
0.658172
6f864ed230a60a9eb0b4c2d9157bd8e85bb1a474
889
package entities; import javax.persistence.Entity; import javax.persistence.Table; /** * Created by POF4CLJ on 29.07.2016. */ @Entity public class Config extends BaseEntity { String line; String factory; String machine_id; protected Config() { } public Config(String line, String factory, String machine_id) { this.line = line; this.factory = factory; this.machine_id = machine_id; } public String getLine() { return line; } public void setLine(String line) { this.line = line; } public String getFactory() { return factory; } public void setFactory(String factory) { this.factory = factory; } public String getMachine_id() { return machine_id; } public void setMachine_id(String machine_id) { this.machine_id = machine_id; } }
18.142857
67
0.622047
36a9e80bf6b9d9ecf9e98bc3dc30396e892029ff
350
package com.cleeng.api.domain; import java.io.Serializable; public class UpdateCustomerSubscriptionOfferData implements Serializable { public String status; public String expiresAt; public UpdateCustomerSubscriptionOfferData(String status, String expiresAt) { this.status = status; this.expiresAt = expiresAt; } }
23.333333
81
0.748571
129bb702b3caab9e57c3065fa7d15ecf17e5209b
1,110
package no.nav.vedtak.isso.ressurs; import no.nav.vedtak.feil.Feil; import no.nav.vedtak.feil.FeilFactory; import no.nav.vedtak.feil.LogLevel; import no.nav.vedtak.feil.deklarasjon.DeklarerteFeil; import no.nav.vedtak.feil.deklarasjon.TekniskFeil; import java.io.UnsupportedEncodingException; interface RelyingPartyCallbackFeil extends DeklarerteFeil { RelyingPartyCallbackFeil FACTORY = FeilFactory.create(RelyingPartyCallbackFeil.class); @TekniskFeil(feilkode = "F-963044", feilmelding = "Mangler parameter 'code' i URL", logLevel = LogLevel.WARN) Feil manglerCodeParameter(); @TekniskFeil(feilkode = "F-731807", feilmelding = "Mangler parameter 'state' i URL", logLevel = LogLevel.WARN) Feil manglerStateParameter(); @TekniskFeil(feilkode = "F-755892", feilmelding = "Cookie for redirect URL mangler eller er tom", logLevel = LogLevel.WARN) Feil manglerCookieForRedirectionURL(); @TekniskFeil(feilkode = "F-448219", feilmelding = "Kunne ikke URL decode '%s'", logLevel = LogLevel.WARN) Feil kunneIkkeUrlDecode(String urlEncoded, UnsupportedEncodingException e); }
42.692308
127
0.772973
273d2a281f82302592475596f9be1c9d1167a22e
1,112
package org.hy.common.xml.junit.xjavacloud; import org.hy.common.net.data.LoginRequest; import org.hy.common.net.netty.rpc.ClientRPC; import org.hy.common.xml.log.Logger; /** * 测试单元:XJavaCloud的客户端 * * @author ZhengWei(HY) * @createDate 2021-09-29 * @version v1.0 */ public class JU_XJavaCloudClient { private static final Logger $Logger = new Logger(JU_XJavaCloudClient.class ,true); public static void main(String [] args) { ClientRPC v_Client = new ClientRPC().setPort(3021).setHost("127.0.0.1"); v_Client.start(); // 登录 LoginRequest v_LoginRequest = new LoginRequest(); v_LoginRequest.setUserName ("用户1"); v_LoginRequest.setSystemName("系统1"); v_Client.operation().login(v_LoginRequest); // 通讯 $Logger.info("获取服务端的对象:时间1:" + v_Client.operation().getObject("TEST-Date-1")); $Logger.info("获取服务端的对象:时间2:" + v_Client.operation().getObject("TEST-Date-2")); $Logger.info("获取服务端的对象:多个对象:" + v_Client.operation().getObjects("TEST-Date")); } }
25.860465
86
0.630396
5853139b83df6882673d61274151ba0f9beecbb1
4,350
/* * Copyright (c) 2016 Zhang Hai <Dreaming.in.Code.ZH@Gmail.com> * All Rights Reserved. */ package me.zhanghai.android.douya.network.api.info.frodo; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import com.google.gson.annotations.SerializedName; // TODO: Extend from BaseItem. public class Diary implements Parcelable { public enum Visibility { PRIVATE("X"), PROTECTED("S"), PUBLIC("P"); private String apiString; Visibility(String apiString) { this.apiString = apiString; } public static Visibility ofString(String apiString, Visibility defaultValue) { for (Visibility visibility : Visibility.values()) { if (TextUtils.equals(visibility.apiString, apiString)) { return visibility; } } return defaultValue; } public static Visibility ofString(String apiString) { return ofString(apiString, PUBLIC); } } @SerializedName("abstract") public String abstract_; @SerializedName("allow_comment") public boolean allowComment; @SerializedName("allow_donate") public boolean allowDonate; public SimpleUser author; @SerializedName("comments_count") public int commentCount; @SerializedName("cover_url") public String cover; @SerializedName("create_time") public String creationTime; /** * @deprecated Use {@link #getVisibility()} instead. */ @SerializedName("domain") public String visibility; @SerializedName("donate_count") public int donationCount; public long id; @SerializedName("is_donated") public boolean isDonated; @SerializedName("is_original") public boolean isOriginal; @SerializedName("likers_count") public int likerCount; @SerializedName("sharing_url") public String shareUrl; public String title; public String type; @SerializedName("update_time") public String updateTime; public String uri; public String url; public Visibility getVisibility() { //noinspection deprecation return Visibility.ofString(visibility); } public static final Creator<Diary> CREATOR = new Creator<Diary>() { @Override public Diary createFromParcel(Parcel source) { return new Diary(source); } @Override public Diary[] newArray(int size) { return new Diary[size]; } }; public Diary() {} protected Diary(Parcel in) { abstract_ = in.readString(); allowComment = in.readByte() != 0; allowDonate = in.readByte() != 0; author = in.readParcelable(SimpleUser.class.getClassLoader()); commentCount = in.readInt(); cover = in.readString(); creationTime = in.readString(); //noinspection deprecation visibility = in.readString(); donationCount = in.readInt(); id = in.readLong(); isDonated = in.readByte() != 0; isOriginal = in.readByte() != 0; likerCount = in.readInt(); shareUrl = in.readString(); title = in.readString(); type = in.readString(); updateTime = in.readString(); uri = in.readString(); url = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(abstract_); dest.writeByte(allowComment ? (byte) 1 : (byte) 0); dest.writeByte(allowDonate ? (byte) 1 : (byte) 0); dest.writeParcelable(author, flags); dest.writeInt(commentCount); dest.writeString(cover); dest.writeString(creationTime); //noinspection deprecation dest.writeString(visibility); dest.writeInt(donationCount); dest.writeLong(id); dest.writeByte(isDonated ? (byte) 1 : (byte) 0); dest.writeByte(isOriginal ? (byte) 1 : (byte) 0); dest.writeInt(likerCount); dest.writeString(shareUrl); dest.writeString(title); dest.writeString(type); dest.writeString(updateTime); dest.writeString(uri); dest.writeString(url); } }
25.892857
86
0.618161
9e70115fd36343dceb87307d1e994ef83147d98e
8,205
package cn.leancloud.sample.testcase; import android.app.AlertDialog; import android.content.DialogInterface; import android.view.LayoutInflater; import android.widget.EditText; import android.widget.LinearLayout; import java.util.HashMap; import java.util.Map; import cn.leancloud.LCException; import cn.leancloud.LCUser; import cn.leancloud.sample.DemoBaseActivity; import cn.leancloud.sample.R; import cn.leancloud.callback.LogInCallback; import cn.leancloud.callback.SaveCallback; import cn.leancloud.callback.SignUpCallback; import cn.leancloud.convertor.ObserverBuilder; /** * Created by fengjunwen on 2018/5/10. */ public class UserAuthDataDemoActivity extends DemoBaseActivity { public interface InputDialogListener { void onAction(final String username, final String password); } protected void showInputDialog(final String title, final InputDialogListener listener) { runOnUiThread(new Runnable() { @Override public void run() { final AlertDialog.Builder builder = new AlertDialog.Builder(demoRunActivity); LayoutInflater inflater = LayoutInflater.from(demoRunActivity); final LinearLayout layout = (LinearLayout) inflater.inflate(cn.leancloud.sample.R.layout.login_dialog, null); final EditText userNameET = (EditText) layout.findViewById(R.id.usernameInput); final EditText passwordET = (EditText) layout.findViewById(R.id.passwordInput); builder.setView(layout); builder.setTitle(title).setPositiveButton(title, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String username = userNameET.getText().toString(); String password = passwordET.getText().toString(); if (listener != null && username.length() > 0 && password.length() > 0) { listener.onAction(username, password); } } }); AlertDialog ad = builder.create(); ad.show(); } }); } public void testLoginWithAuthData() { Map<String, Object> authData = new HashMap<String, Object>(); authData.put("expires_at", "2019-01-07T02:41:13.580Z"); authData.put("openid", "6A83158"); authData.put("access_token", "DCIF"); authData.put("platform", "weixin"); LCUser.loginWithAuthData(authData, "weixin_darenbangbang").subscribe(ObserverBuilder.buildSingleObserver(new LogInCallback() { @Override public void done(LCUser LCUser, LCException e) { if (null != e) { log("尝试使用第三方账号登录,发生错误。cause:" + e.getMessage()); } else { log("成功登录,当前用户:" + LCUser); } } })); } public void testLoginWithAuthDataEx() { final Map<String, Object> authData = new HashMap<String, Object>(); authData.put("expires_at", "2019-01-07T02:41:13.580Z"); authData.put("openid", "6A83158"); authData.put("access_token", "DCIF"); authData.put("platform", "weixin"); LCUser.loginWithAuthData(authData, "weixin_darenbangbang") .subscribe(ObserverBuilder.buildSingleObserver(new LogInCallback() { @Override public void done(final LCUser LCUser, LCException e) { if (null != e) { log("尝试使用第三方账号登录,发生错误。cause:" + e.getMessage()); } else { log("第一次成功登录,当前用户:" + LCUser.getObjectId()); Map<String, Object> authData2 = new HashMap<String, Object>(); authData2.put("expires_at", "2019-11-07T02:41:13.580Z"); authData2.put("openid", "6A8315fwirw328"); authData2.put("access_token", "Dfaef21CIF"); authData2.put("platform", "weixin"); LCUser.loginWithAuthData(authData2, "weixin_darenxiu") .subscribe(ObserverBuilder.buildSingleObserver(new LogInCallback() { @Override public void done(LCUser LCUser2, LCException ex) { if (null != ex) { log("尝试使用第三方账号登录,发生错误。cause:" + ex.getMessage()); } else { log("第二次成功登录,当前用户:" + LCUser2.getObjectId()); LCUser.loginWithAuthData(authData, "weixin_darenbangbang", "ThisisaunionId", "weixin", true) .subscribe(ObserverBuilder.buildSingleObserver(new LogInCallback() { @Override public void done(LCUser au, LCException e2) { if (null != e2) { log("尝试使用第三方账号登录,发生错误。cause:" + e2.getMessage()); } else { log("第三次成功登录,当前用户:" + au.getObjectId()); if (au.getObjectId().equals(LCUser.getObjectId())) { log("expected: bind to correct user with unionId"); } else { log("not expected: cannot bind to correct user with unionId"); } } } })); } } })); } } })); } public void testAssociateWithAuthData() { showInputDialog("Sign Up", new InputDialogListener(){ public void onAction(final String username, final String password) { final LCUser user = new LCUser(); user.setUsername(username); user.setPassword(password); user.signUpInBackground().subscribe(ObserverBuilder.buildSingleObserver(new SignUpCallback() { @Override public void done(LCException e) { if (null != e) { log("用户注册失败。 cause:" + e.getMessage()); } else { log("注册成功 uesr: " + user.getObjectId()); final Map<String, Object> authData = new HashMap<String, Object>(); authData.put("expires_at", "2019-01-07T02:41:13.580Z"); authData.put("openid", "6A83faefewfew158"); authData.put("access_token", "DCfafewerEWDWIF"); authData.put("platform", "weixin"); user.associateWithAuthData(authData, "weixin_darenbangbang") .subscribe(ObserverBuilder.buildSingleObserver(new SaveCallback() { @Override public void done(LCException ex) { if (null != ex) { log("第三方信息关联失败。 cause:" + ex.getMessage()); } else { log("第三方信息关联成功"); } } })); } } })); } }); } public void testAssociateWithAuthDataEx() { showInputDialog("Sign Up", new InputDialogListener(){ public void onAction(final String username, final String password) { final LCUser user = new LCUser(); user.setUsername(username); user.setPassword(password); user.signUpInBackground().subscribe(ObserverBuilder.buildSingleObserver(new SignUpCallback() { @Override public void done(LCException e) { if (null != e) { log("用户注册失败。 cause:" + e.getMessage()); } else { log("注册成功 uesr: " + user.getObjectId()); final Map<String, Object> authData = new HashMap<String, Object>(); authData.put("expires_at", "2019-01-07T02:41:13.580Z"); authData.put("openid", "6A83faefewfew158"); authData.put("access_token", "DCfafewerEWDWIF"); authData.put("platform", "weixin"); user.associateWithAuthData(authData, "weixin_darenbangbang", "ThisisAUnionIDXXX", "weixin", false) .subscribe(ObserverBuilder.buildSingleObserver(new SaveCallback() { @Override public void done(LCException ex) { if (null != ex) { log("第三方信息关联失败。 cause:" + ex.getMessage()); } else { log("第三方信息关联成功"); } } })); } } })); ; } }); } }
42.076923
130
0.567824
048190292526d5eea7f2af31a4570c3fc57e95bf
595
package fr.romainmoreau.gsmmodem.web; import javax.validation.constraints.NotNull; import org.springframework.util.StringUtils; public class SmsRoute { @NotNull private String prefix; @NotNull private String endpointUrl; public boolean matches(String sms) { return StringUtils.startsWithIgnoreCase(sms, prefix); } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getEndpointUrl() { return endpointUrl; } public void setEndpointUrl(String endpointUrl) { this.endpointUrl = endpointUrl; } }
17.5
55
0.757983
82401a1289227e1c7336c4a5e09e641dab9291e0
3,128
package helloworld.hmrc.camel; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.ValidationException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.dataformat.JsonLibrary; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.concurrent.atomic.AtomicLong; import static java.lang.String.format; /** * Backend route service, for ease, this is simply another set of routes within the same application as * frontend service. */ @Component public class BackEndRoute extends RouteBuilder { @Override public void configure() throws Exception { // handle validation errors, result in headers being set to indicate error onException(ValidationException.class) .log("validation failed") .log("${exception.message}") .setHeader("SERVER_ERROR", constant(500)) .setHeader("ERROR_TYPE", constant("validation error")) .handled(true) .setBody(); from("direct:remoteService") .routeId("direct-route") .tracing() .log("direct:remoteService") .log("in >>> ${body}") .log("validating input") .to("direct:jsonValidateBack") .log("validation ok") .unmarshal().json(JsonLibrary.Jackson) .log("out <<< ${body}") .to("direct:createResponse") .endRest(); // validate received json from("direct:jsonValidateBack") // expects inputstream not json object .marshal().json(JsonLibrary.Jackson, true) .to("json-validator:back-end-schema.json"); // route to unmarshal string to json object, expected type by rest binding mode json from("direct:inJsonString2").unmarshal().json(JsonLibrary.Jackson); // process json input and return response as json string since this would normally be done as a back end service from("direct:createResponse") .process(new Processor() { final AtomicLong counter = new AtomicLong(); @Override public void process(Exchange exchange) throws Exception { HashMap<String, Object> body = (HashMap<String, Object>) exchange.getIn().getBody(); String forename = (String) body.get("forename"); String surname = (String) body.get("surname"); HelloWorldResponse response = HelloWorldResponse.builder() .greeting(format("Hello %s, how are you today", forename)) .fullname(format("%s %s", forename, surname)) .responseCount(counter.incrementAndGet()) .build(); exchange.getIn().setBody(response); } }) .marshal().json(JsonLibrary.Jackson); } }
40.102564
120
0.576087
16f8c392032dfffe397893caa60b46fd755bee45
1,114
/* * Copyright 2009 Denys Pavlov, Igor Azarnyi * * 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.yes.cart.bulkcommon.service; import org.yes.cart.service.async.model.JobContext; /** * User: Igor Azarny iazarny@yahoo.com * Date: 12/12/11 * Time: 2:34 PM */ public interface ImportService { enum BulkImportResult { OK, ERROR } /** * Perform bulk import. * * @param context job context of this import. * * @return {@link BulkImportResult} */ BulkImportResult doImport(JobContext context); }
25.906977
78
0.672352
2a214423f46900ffbfcb48498a1785d4140ce92d
3,980
package lm44_xw47.chatRoom.controller; import java.rmi.RemoteException; import common.DataPacketCR; import common.ICRCmd2ModelAdapter; import common.ICRMessageType; import common.IChatRoom; import common.IComponentFactory; import common.IReceiver; import common.IUser; import lm44_xw47.chatRoom.model.ChatRoomModel; import lm44_xw47.chatRoom.model.IChatRoomModel2ViewAdapter; import lm44_xw47.chatRoom.model.ILocalCRCmd2ModelAdapter; import lm44_xw47.chatRoom.view.ChatRoomView; import lm44_xw47.chatRoom.view.IChatRoomView2ModelAdapter; import lm44_xw47.model.Receiver; import lm44_xw47.view.MainViewFrame; import provided.mixedData.MixedDataDictionary; import provided.mixedData.MixedDataKey; /** * Following defines the class the chat room controller. * * @author Xiaojun Wu * @author Lu Ma */ public class ChatRoomController { /** * The view of the chat room. */ private ChatRoomView chatRoomView; /** * The model of the chatroom. */ private ChatRoomModel chatRoomModel; /** * Constructor. * * @param chatRoom The chat room of this chat room MVC. * @param receiver The local user's receiver stub. * @param mainView The main view of the local system. * @param receiverHost The local user's receiver server object. */ public ChatRoomController(IChatRoom chatRoom, IReceiver receiver, MainViewFrame<IUser> mainView, Receiver receiverHost) { chatRoomModel = new ChatRoomModel(chatRoom, new IChatRoomModel2ViewAdapter() { @Override public void appendMsg(String msg) { chatRoomView.appendMsg(msg); } @Override public ICRCmd2ModelAdapter createCRCmd2ModelAdapter() { return new ILocalCRCmd2ModelAdapter() { private MixedDataDictionary dict = new MixedDataDictionary(); @Override public String getName() { // TODO Auto-generated method stub return null; } @Override public void appendMsg(String text, String name) { chatRoomView.appendMsg(name + text); } @Override public void buildScrollableComponent(IComponentFactory fac, String label) { // TODO Auto-generated method stub chatRoomView.getPanelOther().add(fac.makeComponent()); } @Override public void buildNonScrollableComponent(IComponentFactory fac, String label) { // TODO Auto-generated method stub chatRoomView.getPanelOther().add(fac.makeComponent()); } @Override public <T> T put(MixedDataKey<T> key, T value) { // TODO Auto-generated method stub return dict.put(key, value); } @Override public <T> T get(MixedDataKey<T> key) { // TODO Auto-generated method stub return dict.get(key); } @Override public <T extends ICRMessageType> void sendTo(IReceiver target, Class<T> id, T data) { try { target.receive(new DataPacketCR<T>(id, data, receiver)); } catch (RemoteException e) { e.printStackTrace(); } } @Override public <T extends ICRMessageType> void sendToChatRoom(Class<T> id, T data) { chatRoom.sendPacket(new DataPacketCR<T>(id, data, receiver)); } @Override public void addReceiver(IReceiver receiver) { chatRoomModel.addReceiver(receiver); } @Override public void removeReceiver(IReceiver receiver) { chatRoomModel.removeReceiver(receiver); } }; } }, receiver, receiverHost); chatRoomView = new ChatRoomView(new IChatRoomView2ModelAdapter() { @Override public void start() { } @Override public void sendMsg(String msg) { chatRoomModel.sendMsg(msg); } @Override public void leave() { chatRoomModel.leave(); // lobbyView.removeTeamView(chatRoomView.getContentPnl()); } }); mainView.addMiniView(chatRoomView.getContentPnl(), chatRoom.getName()); // lobbyView.addTeamView(chatRoomView.getContentPnl()); } /** * Start the chat room MVC. */ public void start() { chatRoomView.start(); } }
26.357616
122
0.702261
fcd44b194e5e94efd440b942c4de7772d719b22a
6,929
package com.catherine.classloader; import android.app.Application; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.util.Log; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Stack; /** * Created by Catherine on 2017/2/13. * yacatherine19@gmail.com */ public class MyApplication extends Application { private static final String TAG = "MyApplication"; private Context cc; private Object j; private Stack<ClassLoader> CLs; private static Stack<Object> parents; private Smith<Object> sm; private Resources mResources; private String dexPath; private Resources.Theme mTheme; private AssetManager mAssetManager; private static boolean isopen = true; @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); cc = base; } @Override public String getPackageName() { if (!isopen) { return ""; } else { return getBaseContext().getPackageName(); } } @Override public synchronized void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); this.isopen = true; CLs = new Stack<>(); parents = new Stack<>(); createPath(); } @Override public void onConfigurationChanged(Configuration paramConfiguration) { super.onConfigurationChanged(paramConfiguration); if (this.j != null) { try { this.j.getClass().getDeclaredMethod("onConfigurationChanged", new Class[]{Configuration.class}) .invoke(this.j, new Object[]{paramConfiguration}); return; } catch (Exception localException) { Log.e(TAG, "onLowMemory()" + localException); } } } @Override public void onLowMemory() { super.onLowMemory(); if (this.j == null) { try { this.j.getClass().getDeclaredMethod("onLowMemory", new Class[0]).invoke(this.j, new Object[0]); return; } catch (Exception localException) { Log.w(TAG, "onLowMemory()" + localException); } } } @Override public void onTerminate() { super.onTerminate(); if (this.j != null) { try { this.j.getClass().getDeclaredMethod("onTerminate", new Class[0]).invoke(this.j, new Object[0]); return; } catch (Exception localException) { Log.e(TAG, "onTerminate()" + localException); } } } // Dynamically load apk public void LoadApk(String fileName) { Log.d(TAG, "LoadApk()"); Log.d(TAG, "CLs:" + CLs.size()); Log.d(TAG, "parents:" + parents.size()); if (getExternalFilesDir(null) != null) { dexPath = new File(getExternalFilesDir(null), fileName).getAbsolutePath(); } else if (getFilesDir() != null) { dexPath = new File(getFilesDir(), fileName).getAbsolutePath(); } ClassLoader defaultCL = getClass().getClassLoader(); Log.d(TAG, "defaultCL:" + defaultCL.toString()); Log.d(TAG, "parent:" + defaultCL.getParent().toString()); sm = new Smith<>(defaultCL); if (CLs.size() == 0) CLs.push(defaultCL); try { Object defaultP = sm.get(); if (parents.size() == 0) parents.push(defaultP); Object layerP = new MyDexClassLoader(this, dexPath, cc.getFilesDir().getAbsolutePath(), (ClassLoader) sm.get()); //4:the parent class loader if (!parents.peek().equals(layerP)) { parents.push(layerP); CLs.push((ClassLoader) layerP); } sm.set(parents.peek()); loadResources(); } catch (Exception e) { Log.e(TAG, "onCreate catch " + e.toString()); } } // Remove classLoader from loaded apk and recovery public void RemoveApk() { Log.d(TAG, "RemoveApk()"); try { if (CLs.size() > 1) { CLs.pop(); parents.pop(); } Smith<Object> sm = new Smith<>(CLs.peek()); sm.set(parents.peek()); } catch (Exception e) { Log.e(TAG, "RemoveApk : " + e.toString()); if (e instanceof IllegalArgumentException) return; } mTheme = null; mResources = null; mAssetManager = null; } // Load resources from apks protected void loadResources() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException { Log.d(TAG, "MyApplication : loadResources()"); AssetManager am = (AssetManager) AssetManager.class.newInstance(); am.getClass().getMethod("addAssetPath", String.class).invoke(am, dexPath); mAssetManager = am; Constructor<?> constructor_Resources = Resources.class.getConstructor(AssetManager.class, cc.getResources() .getDisplayMetrics().getClass(), cc.getResources().getConfiguration().getClass()); mResources = (Resources) constructor_Resources.newInstance(am, cc.getResources().getDisplayMetrics(), cc.getResources().getConfiguration()); mTheme = mResources.newTheme(); mTheme.applyStyle(android.R.style.Theme_Light_NoTitleBar_Fullscreen, true); } public void createPath() { File file; if (getExternalFilesDir(null) != null) { file = getExternalFilesDir(null); } else { file = getFilesDir(); } if (!file.exists()) { file.mkdir(); } } @Override public ClassLoader getClassLoader() { if (CLs == null || CLs.size() == 0) { Log.d(TAG, "super.getClassLoader()"); return super.getClassLoader(); } Log.d(TAG, "It's in the " + CLs.size() + " layer"); return CLs.peek(); } @Override public AssetManager getAssets() { Log.e(TAG, mAssetManager == null ? "super.getAssets()" : "mAssetManager"); return mAssetManager == null ? super.getAssets() : mAssetManager; } @Override public Resources getResources() { Log.e(TAG, mResources == null ? "super.getResources()" : "mResources"); return mResources == null ? super.getResources() : mResources; } @Override public Resources.Theme getTheme() { Log.e(TAG, mTheme == null ? "super.getTheme()" : "mTheme"); return mTheme == null ? super.getTheme() : mTheme; } }
32.530516
148
0.580603
db866f61c8366905fdb05d7cd82e6c81eb29a8dc
1,255
package jdo.ecommerce.model.webvisit; import javax.persistence.Entity; import javax.persistence.ManyToOne; import jdo.model.BasePersistentModel; @Entity public class UserAgent extends BasePersistentModel { /** * */ private static final long serialVersionUID = 1L; @ManyToOne private BrowserType browser; @ManyToOne private UserAgentMethodType methodType; @ManyToOne private PlatformType platform; @ManyToOne private ProtocolType protocolType; @ManyToOne private UserAgentType type; public BrowserType getBrowser() { return browser; } public UserAgentMethodType getMethodType() { return methodType; } public PlatformType getPlatform() { return platform; } public ProtocolType getProtocolType() { return protocolType; } public UserAgentType getType() { return type; } public void setBrowser(BrowserType browser) { this.browser = browser; } public void setMethodType(UserAgentMethodType methodType) { this.methodType = methodType; } public void setPlatform(PlatformType platform) { this.platform = platform; } public void setProtocolType(ProtocolType protocolType) { this.protocolType = protocolType; } public void setType(UserAgentType type) { this.type = type; } }
17.430556
60
0.752191
af287e3256297a436ed85da5d3f5cb474801be78
653
package ru.kershov.blogapp.model.dto.auth; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import ru.kershov.blogapp.config.Config; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; @Data @AllArgsConstructor @NoArgsConstructor @ToString public class EmailDTO { /** * DTO for restoring user's password */ @JsonProperty(value = "email") @NotBlank(message = Config.STRING_FIELD_CANT_BE_BLANK) @Email(message = Config.STRING_AUTH_INVALID_EMAIL) private String email; }
29.681818
58
0.784074
a45bba57b45516363e8dedeb09fc954eb67980a5
4,449
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.s3a.auth.delegation; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.net.URI; import org.apache.hadoop.fs.s3a.auth.MarshalledCredentials; import org.apache.hadoop.io.Text; import static org.apache.hadoop.fs.s3a.auth.delegation.DelegationConstants.SESSION_TOKEN_KIND; /** * A token identifier which contains a set of AWS session credentials, * credentials which will be valid until they expire. * * <b>Note 1:</b> * There's a risk here that the reference to {@link MarshalledCredentials} * may trigger a transitive load of AWS classes, a load which will * fail if the aws SDK isn't on the classpath. * * <b>Note 2:</b> * This class does support subclassing, but every subclass MUST declare itself * to be of a different token kind. * Otherwise the process for decoding tokens breaks. */ public class SessionTokenIdentifier extends AbstractS3ATokenIdentifier { /** * Session credentials: initially empty but non-null. */ private MarshalledCredentials marshalledCredentials = new MarshalledCredentials(); /** * Constructor for service loader use. * Created with the kind {@link DelegationConstants#SESSION_TOKEN_KIND}. * Subclasses MUST NOT subclass this; they must provide their own * token kind. */ public SessionTokenIdentifier() { super(SESSION_TOKEN_KIND); } /** * Constructor for subclasses. * @param kind kind of token identifier, for storage in the * token kind to implementation map. */ protected SessionTokenIdentifier(final Text kind) { super(kind); } /** * Constructor. * @param kind token kind. * @param owner token owner * @param uri filesystem URI. * @param marshalledCredentials credentials to marshall * @param encryptionSecrets encryption secrets * @param origin origin text for diagnostics. */ public SessionTokenIdentifier( final Text kind, final Text owner, final URI uri, final MarshalledCredentials marshalledCredentials, final EncryptionSecrets encryptionSecrets, final String origin) { super(kind, uri, owner, origin, encryptionSecrets); this.marshalledCredentials = marshalledCredentials; } /** * Constructor. * @param kind token kind. * @param owner token owner * @param renewer token renewer * @param realUser real user running over proxy user * @param uri filesystem URI. */ public SessionTokenIdentifier(final Text kind, final Text owner, final Text renewer, final Text realUser, final URI uri) { super(kind, owner, renewer, realUser, uri); } @Override public void write(final DataOutput out) throws IOException { super.write(out); marshalledCredentials.write(out); } @Override public void readFields(final DataInput in) throws IOException { super.readFields(in); marshalledCredentials.readFields(in); } /** * Return the expiry time in seconds since 1970-01-01. * @return the time when the AWS credentials expire. */ @Override public long getExpiryTime() { return marshalledCredentials.getExpiration(); } /** * Get the marshalled credentials. * @return marshalled AWS credentials. */ public MarshalledCredentials getMarshalledCredentials() { return marshalledCredentials; } /** * Add the (sanitized) marshalled credentials to the string value. * @return a string value for test assertions and debugging. */ @Override public String toString() { return super.toString() + "; " + marshalledCredentials.toString(); } }
29.85906
94
0.717689
d3b4fbc242f643fd9c42bd4d68d6e88b015d8835
11,366
package com.techexe.androidroom.Common; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.support.annotation.CheckResult; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.techexe.androidroom.R; /** * This file is part of Toaster. * * Toaster is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Toaster 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 Toaster. If not, see <http://www.gnu.org/licenses/>. */ @SuppressLint("InflateParams") public class Toaster { @ColorInt private static int DEFAULT_TEXT_COLOR = Color.parseColor("#FFFFFF"); @ColorInt private static int ERROR_COLOR = Color.parseColor("#D50000"); @ColorInt private static int INFO_COLOR = Color.parseColor("#3F51B5"); @ColorInt private static int SUCCESS_COLOR = Color.parseColor("#388E3C"); @ColorInt private static int WARNING_COLOR = Color.parseColor("#FFA900"); @ColorInt private static int NORMAL_COLOR = Color.parseColor("#353A3E"); private static final Typeface LOADED_TOAST_TYPEFACE = Typeface.create("sans-serif-condensed", Typeface.NORMAL); private static Typeface currentTypeface = LOADED_TOAST_TYPEFACE; private static int textSize = 16; // in SP private static boolean tintIcon = true; private Toaster() { // avoiding instantiation } @CheckResult public static Toast normal(@NonNull Context context, @NonNull CharSequence message) { return normal(context, message, Toast.LENGTH_SHORT, null, false); } @CheckResult public static Toast normal(@NonNull Context context, @NonNull CharSequence message, Drawable icon) { return normal(context, message, Toast.LENGTH_SHORT, icon, true); } @CheckResult public static Toast normal(@NonNull Context context, @NonNull CharSequence message, int duration) { return normal(context, message, duration, null, false); } @CheckResult public static Toast normal(@NonNull Context context, @NonNull CharSequence message, int duration, Drawable icon) { return normal(context, message, duration, icon, true); } @CheckResult public static Toast normal(@NonNull Context context, @NonNull CharSequence message, int duration, Drawable icon, boolean withIcon) { return custom(context, message, icon, NORMAL_COLOR, duration, withIcon, true); } @CheckResult public static Toast warning(@NonNull Context context, @NonNull CharSequence message) { return warning(context, message, Toast.LENGTH_SHORT, true); } @CheckResult public static Toast warning(@NonNull Context context, @NonNull CharSequence message, int duration) { return warning(context, message, duration, true); } @CheckResult public static Toast warning(@NonNull Context context, @NonNull CharSequence message, int duration, boolean withIcon) { return custom(context, message, ToastUtils.getDrawable(context, R.drawable.ic_error_outline_white_48dp), WARNING_COLOR, duration, withIcon, true); } @CheckResult public static Toast info(@NonNull Context context, @NonNull CharSequence message) { return info(context, message, Toast.LENGTH_SHORT, true); } @CheckResult public static Toast info(@NonNull Context context, @NonNull CharSequence message, int duration) { return info(context, message, duration, true); } @CheckResult public static Toast info(@NonNull Context context, @NonNull CharSequence message, int duration, boolean withIcon) { return custom(context, message, ToastUtils.getDrawable(context, R.drawable.ic_info_outline_white_48dp), INFO_COLOR, duration, withIcon, true); } @CheckResult public static Toast success(@NonNull Context context, @NonNull CharSequence message) { return success(context, message, Toast.LENGTH_SHORT, true); } @CheckResult public static Toast success(@NonNull Context context, @NonNull CharSequence message, int duration) { return success(context, message, duration, true); } @CheckResult public static Toast success(@NonNull Context context, @NonNull CharSequence message, int duration, boolean withIcon) { return custom(context, message, ToastUtils.getDrawable(context, R.drawable.ic_check_white_48dp), SUCCESS_COLOR, duration, withIcon, true); } @CheckResult public static Toast error(@NonNull Context context, @NonNull CharSequence message) { return error(context, message, Toast.LENGTH_SHORT, true); } @CheckResult public static Toast error(@NonNull Context context, @NonNull CharSequence message, int duration) { return error(context, message, duration, true); } @CheckResult public static Toast error(@NonNull Context context, @NonNull CharSequence message, int duration, boolean withIcon) { return custom(context, message, ToastUtils.getDrawable(context, R.drawable.ic_clear_white_48dp), ERROR_COLOR, duration, withIcon, true); } @CheckResult public static Toast custom(@NonNull Context context, @NonNull CharSequence message, Drawable icon, int duration, boolean withIcon) { return custom(context, message, icon, -1, duration, withIcon, false); } @CheckResult public static Toast custom(@NonNull Context context, @NonNull CharSequence message, @DrawableRes int iconRes, @ColorInt int tintColor, int duration, boolean withIcon, boolean shouldTint) { return custom(context, message, ToastUtils.getDrawable(context, iconRes), tintColor, duration, withIcon, shouldTint); } @CheckResult public static Toast custom(@NonNull Context context, @NonNull CharSequence message, Drawable icon, @ColorInt int tintColor, int duration, boolean withIcon, boolean shouldTint) { final Toast currentToast = new Toast(context); final View toastLayout = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(R.layout.layout_toast, null); final ImageView toastIcon = (ImageView) toastLayout.findViewById(R.id.toast_icon); final TextView toastTextView = (TextView) toastLayout.findViewById(R.id.toast_text); Drawable drawableFrame; if (shouldTint) drawableFrame = ToastUtils.tint9PatchDrawableFrame(context, tintColor); else drawableFrame = ToastUtils.getDrawable(context, R.drawable.toast_frame); ToastUtils.setBackground(toastLayout, drawableFrame); if (withIcon) { if (icon == null) throw new IllegalArgumentException("Avoid passing 'icon' as null if 'withIcon' is set to true"); if (tintIcon) icon = ToastUtils.tintIcon(icon, DEFAULT_TEXT_COLOR); ToastUtils.setBackground(toastIcon, icon); } else { toastIcon.setVisibility(View.GONE); } toastTextView.setTextColor(DEFAULT_TEXT_COLOR); toastTextView.setText(message); toastTextView.setTypeface(currentTypeface); toastTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); currentToast.setView(toastLayout); currentToast.setDuration(duration); return currentToast; } public static class Config { @ColorInt private int DEFAULT_TEXT_COLOR = Toaster.DEFAULT_TEXT_COLOR; @ColorInt private int ERROR_COLOR = Toaster.ERROR_COLOR; @ColorInt private int INFO_COLOR = Toaster.INFO_COLOR; @ColorInt private int SUCCESS_COLOR = Toaster.SUCCESS_COLOR; @ColorInt private int WARNING_COLOR = Toaster.WARNING_COLOR; private Typeface typeface = Toaster.currentTypeface; private int textSize = Toaster.textSize; private boolean tintIcon = Toaster.tintIcon; private Config() { // avoiding instantiation } @CheckResult public static Config getInstance() { return new Config(); } public static void reset() { Toaster.DEFAULT_TEXT_COLOR = Color.parseColor("#FFFFFF"); Toaster.ERROR_COLOR = Color.parseColor("#D50000"); Toaster.INFO_COLOR = Color.parseColor("#3F51B5"); Toaster.SUCCESS_COLOR = Color.parseColor("#388E3C"); Toaster.WARNING_COLOR = Color.parseColor("#FFA900"); Toaster.currentTypeface = LOADED_TOAST_TYPEFACE; Toaster.textSize = 16; Toaster.tintIcon = true; } @CheckResult public Config setTextColor(@ColorInt int textColor) { DEFAULT_TEXT_COLOR = textColor; return this; } @CheckResult public Config setErrorColor(@ColorInt int errorColor) { ERROR_COLOR = errorColor; return this; } @CheckResult public Config setInfoColor(@ColorInt int infoColor) { INFO_COLOR = infoColor; return this; } @CheckResult public Config setSuccessColor(@ColorInt int successColor) { SUCCESS_COLOR = successColor; return this; } @CheckResult public Config setWarningColor(@ColorInt int warningColor) { WARNING_COLOR = warningColor; return this; } @CheckResult public Config setToastTypeface(@NonNull Typeface typeface) { this.typeface = typeface; return this; } @CheckResult public Config setTextSize(int sizeInSp) { this.textSize = sizeInSp; return this; } @CheckResult public Config tintIcon(boolean tintIcon) { this.tintIcon = tintIcon; return this; } public void apply() { Toaster.DEFAULT_TEXT_COLOR = DEFAULT_TEXT_COLOR; Toaster.ERROR_COLOR = ERROR_COLOR; Toaster.INFO_COLOR = INFO_COLOR; Toaster.SUCCESS_COLOR = SUCCESS_COLOR; Toaster.WARNING_COLOR = WARNING_COLOR; Toaster.currentTypeface = typeface; Toaster.textSize = textSize; Toaster.tintIcon = tintIcon; } } }
37.511551
122
0.670597
81cf97a33e84aced489a9d34f2c848cbf2f6ec68
5,962
package tools; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import javax.swing.JFileChooser; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * Easy configuration file managment * * @date 15 October 2013 * @author jordan */ public class ConfigFile { File configFile = null; Properties config = null; boolean created = false; String filePath = null; /** * Load the configuration file or create it if it does not exists * * @param filePath * @throws nxt.api.tools.ConfigFileException */ public ConfigFile(String filePath) throws ConfigFileException { this.filePath = filePath; openFile(); } public ConfigFile() { } public String askFilePathWithGui() throws ConfigFileException { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { } JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Select the file"); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { filePath = chooser.getSelectedFile().getAbsolutePath(); openFile(); return filePath; } else { filePath = null; return null; } } public void openFile() throws ConfigFileException { if(filePath == null) throw new ConfigFileException("File selection canceled"); configFile = new File(filePath); if (!configFile.exists()) { try { if (!configFile.createNewFile()) { throw new ConfigFileException("Failed to create the configuration file"); } created = true; } catch (IOException e) { throw new ConfigFileException("Failed to create the configuration file : " + e.getMessage()); } } config = new Properties(); try { try (FileInputStream file = new FileInputStream(configFile)) { config.load(file); file.close(); } } catch (IOException e) { config = null; throw new ConfigFileException("Failed to load the configuration file : " + e.getMessage()); } } /** * Get the string value of the given property * * @param property The property name * @param defaultValue The default value if the property is not found * @return The value of the given property or the default given or null if * it is not found */ public String getString(String property, String defaultValue) { return config.getProperty(property, defaultValue); } public String getString(String property) { return getString(property, null); } /** * Get the char value of the given property * * @param property The property name * @param defaultValue The default value if the property is not found * @return The value of the given property or the default given or null if * it is not found */ public Character getChar(String property, Character defaultValue) { String val = config.getProperty(property, defaultValue.toString()); return (val == null) ? null : val.charAt(0); } public Character getChar(String property) { return getChar(property, null); } /** * Get the Integer value of the given property * * @param property The property name * @param defaultValue The default value if the property is not found * @return The value of the given property or the default given or null if * it is not found * @throws nxt.api.tools.ConfigFileException */ public Integer getInt(String property, Integer defaultValue) throws ConfigFileException { String stringVal = config.getProperty(property, defaultValue.toString()); try { return (stringVal == null) ? null : Integer.parseInt(stringVal); } catch (NumberFormatException e) { throw new ConfigFileException("Property : \"" + property + "\" is not a valid integer"); } } public Integer getInt(String property) throws ConfigFileException { return getInt(property, null); } /** * Set the property with the given value in the configuration file. Theses * modifications are temporary, to save definitively in file use save() * method. If the property already exists it is replace. * * @param key * @param val * @throws nxt.api.tools.ConfigFileException */ public void set(String key, String val) throws ConfigFileException { config.setProperty(key, val); } /** * Save all changes in the configuration file * * @param fileComment The comment writen at the top of file * @throws ConfigFileException */ public void save(String fileComment) throws ConfigFileException { try { config.store(new FileOutputStream(configFile), fileComment); } catch (IOException e) { throw new ConfigFileException("Can't save the file. IOException : " + e.getMessage()); } } /** * Delete the given property Theses modifications are temporary, to save * definitively in file use save() method. * * @param key */ public void delete(String key) { config.remove(key); } }
31.378947
128
0.604663
04ce9251fd3d04d7861cfbc8fe1a38f470c5d78b
6,574
package com.example.amar.smartphoneinventory; import android.app.LoaderManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.example.amar.smartphoneinventory.data.SmartphoneContract; public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { private static final int SMARTPHONE_LOADER = 0; // Adapter for the ListView SmartphoneCursorAdapter mCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_catalog); // Setup FAB to open EditorActivity FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(CatalogActivity.this, EditorActivity.class); startActivity(intent); } }); // Find the ListView which will be populated with the smartphone data ListView smartphoneListView = findViewById(R.id.smartphone_list); // Find and set empty view on the ListView, so that it only shows when the list has 0 items. View emptyView = findViewById(R.id.empty_view); smartphoneListView.setEmptyView(emptyView); // Setup an Adapter to create a list item for each row of smartphone data in the Cursor. // There is no smartphone data yet (until the loader finishes) so pass in null for the Cursor. mCursorAdapter = new SmartphoneCursorAdapter(this, null); smartphoneListView.setAdapter(mCursorAdapter); // Setup the item click listener smartphoneListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Intent intent = new Intent(CatalogActivity.this, SmartphoneDetailsActivity.class); // Form the content URI that represents the specific smartphone that was clicked on Uri currentSmartphoneUri = ContentUris.withAppendedId(SmartphoneContract.SmartphoneEntry.CONTENT_URI, id); intent.setData(currentSmartphoneUri); // Launch smartphone details activity startActivity(intent); Log.v("CatalogActivity", "item click"); } }); // Kick off the loader getLoaderManager().initLoader(SMARTPHONE_LOADER, null, this); } //Helper method to insert hardcoded smartphone data into the database. For debugging purposes only. private void insertSmartphone() { // dummy data ContentValues values = new ContentValues(); values.put(SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_NAME, "Redmi Note 5 pro"); values.put(SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_PRICE, 14999); values.put(SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_QUANTITY, 1); values.put(SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_SUPPLIER_NAME, "Redmi Hub"); values.put(SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_SUPPLIER_PHONE, "9417476801"); // Insert a new row for data into the provider using the ContentResolver. Uri newUri = getContentResolver().insert(SmartphoneContract.SmartphoneEntry.CONTENT_URI, values); } private void deleteAllSmartphones() { int rowsDeleted = getContentResolver().delete(SmartphoneContract.SmartphoneEntry.CONTENT_URI, null, null); Log.v("CatalogActivity", rowsDeleted + " rows deleted from smartphone database"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // This inflates menu items on the app bar. getMenuInflater().inflate(R.menu.menu_catalog, menu); Log.v("CatalogActivity", "menu inflated "); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { case R.id.action_insert_dummy_data: insertSmartphone(); return true; case R.id.action_delete_all_entries: deleteAllSmartphones(); Log.v("CatalogActivity", "option item selected "); return true; } return super.onOptionsItemSelected(item); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { // Define a projection that specifies the columns from the table we care about. String[] projection = { SmartphoneContract.SmartphoneEntry._ID, SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_NAME, SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_QUANTITY, SmartphoneContract.SmartphoneEntry.COLUMN_SMARTPHONE_PRICE,}; // This loader will execute the ContentProvider's query method on a background thread return new CursorLoader(this, // Parent activity context SmartphoneContract.SmartphoneEntry.CONTENT_URI, // Provider content URI to query projection, // Columns to include in the resulting Cursor null, // No selection clause null, // No selection arguments null); // Default sort order } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Update cursor adapter with this new cursor containing updated smartphone data mCursorAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { // Callback called when the data needs to be deleted mCursorAdapter.swapCursor(null); } @Override public void onBackPressed() { super.onBackPressed(); } }
41.345912
122
0.685123
d4e21354a1f7370dbb05cb658ab5671a2f5eac9e
766
package il.ac.technion.nlp.nli.core; import il.ac.technion.nlp.nli.core.state.NliEntity; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to add a description (a natural language phrase) to a NLI method, relation field or a class implementing * {@link NliEntity}. Note that the identifier of the method/field/class already provides one description. * * @author Ofer Givoli <ogivoli@cs.technion.ac.il> */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) public @interface NliDescriptions { /** * Order: from most to least important. */ String[] descriptions(); }
30.64
112
0.755875
9a243de5d154bbda69bdb567481fa44bbd467810
776
package com.baislsl.decompiler.structure.constantPool; import com.baislsl.decompiler.DecompileException; import com.baislsl.decompiler.Result; public class DoubleTag extends LongDoubleBasic { public DoubleTag(int tag){ super(tag); } @Override public String[] description(Result result) throws DecompileException { return new String[]{ "Double", Double.toString(getValue()) }; } public double getValue(){ return Double.longBitsToDouble(((long) highByte << 32) | Integer.toUnsignedLong(lowByte)); } @Override public String toString() { return Double.toString(getValue()) + "D"; } @Override public String name() throws DecompileException { return toString(); } }
24.25
98
0.662371
3b505a8ae0aa186c1a15790f007109f5146a736e
2,386
package com.services; import com.LongPolling.ServicePoll; import com.entity.Credentials; import com.entity.RegistrationModel; import com.entity.User; import com.dao.UserDaoInterface; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class UserServiceImpl extends ServicePoll implements UserServiceInterface { private final UserDaoInterface userDaoInterface; private final CredentialsServiceInterface credentialsService; @Autowired public UserServiceImpl(UserDaoInterface userDaoInterface, CredentialsServiceInterface credentialsService) { this.userDaoInterface = userDaoInterface; this.credentialsService = credentialsService; } @Override @Transactional public List<User> getAllUsers() { return userDaoInterface.getAllUsers(); } @Override @Transactional public int saveUser(RegistrationModel theUser) { String userKey = (theUser.getName().substring(0,3) + theUser.getSurname().substring(0,3)).toUpperCase(); User user = new User(); user.setName(Character.toUpperCase(theUser.getName().charAt(0)) + theUser.getName().substring(1).toLowerCase()); user.setSurname(Character.toUpperCase(theUser.getSurname().charAt(0)) + theUser.getSurname().substring(1).toLowerCase()); user.setKey(userKey); user.setTeamName("NEW EMPLOYEE"); user.setEmail(theUser.getEmail()); userDaoInterface.saveUser(user); Credentials credentials = new Credentials(); credentials.setKey(userKey); credentials.setEmail(theUser.getEmail()); credentials.setPassword(theUser.getPassword()); credentialsService.save(credentials); return user.getId(); } @Override @Transactional public User getUser(int theId) { return userDaoInterface.getUser(theId); } @Override @Transactional public void deleteUser(int theId) { userDaoInterface.deleteUser(theId); } @Override @Transactional public void updateUser(User user) { userDaoInterface.updateUser(user); } @Override @Transactional public User getUserByKey(String key) { return userDaoInterface.getUserByKey(key); } }
30.589744
129
0.718776
21c06cab6b25c1b106cddebeb231cb843156bc37
1,224
/* * 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 main; import java.io.File; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.ResourceFactory; /** * * @author Jan-Peter.Schmidt */ public class Test { public static void main(String args[]) { String path = "C:\\Users\\JP_Schmidt\\Desktop\\MaschineSmall.n3"; File file = new File(path); Model model = ModelFactory.createDefaultModel(); model.read(file.getAbsolutePath()); System.out.println("MS: " + model.getGraph().size()); Property prop = ResourceFactory.createProperty("https://w3id.org/saref", "Unit_of_measure"); model.listObjectsOfProperty(prop).toList().forEach((object) -> { Model model2 = ModelFactory.createDefaultModel(); model2.read(object.toString()); System.out.println(model2.getGraph().size()); }); } }
27.2
100
0.628268
9c07f3d6920b0933f06b76fba96865f9d733ef7d
1,444
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { static boolean doThrow = false; static long longValue; public static void assertEquals(float expected, float result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } public static void main(String[] args) { assertEquals(1.0F, $noinline$longToFloat()); } /// CHECK-START: float Main.$noinline$longToFloat() register (after) /// CHECK-DAG: <<Const1:j\d+>> LongConstant 1 /// CHECK-DAG: <<Convert:f\d+>> TypeConversion [<<Const1>>] /// CHECK-DAG: Return [<<Convert>>] static float $noinline$longToFloat() { if (doThrow) { throw new Error(); } longValue = $inline$returnConst(); return (float) longValue; } static long $inline$returnConst() { return 1L; } }
30.723404
75
0.664127
f1b02435cbe7520de46a1afa7d6381647d41b540
1,003
package com.gabor.hr.service.dto.validator; import com.gabor.hr.model.Status; import com.gabor.hr.service.dto.RequestDto; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.time.LocalDate; public class DateValidator implements ConstraintValidator<DateInFuture, RequestDto> { @Override public boolean isValid(RequestDto requestDto, ConstraintValidatorContext constraintValidatorContext) { //date must be in the future only for newly created requests if (requestDto.getStatus() == Status.OPEN) { LocalDate now = LocalDate.now(); if (requestDto.getEndDate() == null || requestDto.getStartDate() == null) { return false; } if (requestDto.getEndDate().isBefore(now)) { return false; } if (requestDto.getStartDate().isBefore(now)) { return false; } } return true; } }
30.393939
106
0.648056
aa91dd60ca55521aaa44279685c33e955909f524
3,773
package com.photatos.dalin.mlkit.ghost.auth; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import java.net.HttpURLConnection; import java.net.MalformedURLException; import io.reactivex.Observable; import io.reactivex.Single; import com.photatos.dalin.mlkit.ghost.error.UrlNotFoundException; import com.photatos.dalin.mlkit.ghost.util.NetworkUtils; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import static com.photatos.dalin.mlkit.ghost.util.NetworkUtils.networkCall; class NetworkBlogUrlValidator implements BlogUrlValidator { private static final String TAG = "BlogUrlValidator"; private final OkHttpClient mHttpClient; NetworkBlogUrlValidator(@NonNull OkHttpClient httpClient) { mHttpClient = httpClient; } /** * @param blogUrl - URL to validate, without http:// or https:// */ @Override public Observable<String> validate(@NonNull String blogUrl) { // try HTTPS and HTTP, in that order return Observable.create(source -> { checkGhostBlog("https://" + blogUrl, mHttpClient) .onErrorResumeNext(checkGhostBlog("http://" + blogUrl, mHttpClient)) .subscribe(source::onNext, e -> { source.onError(new UrlValidationException(e, "https://" + blogUrl)); }); }); } @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) static Single<String> checkGhostBlog(@NonNull String blogUrl, @NonNull OkHttpClient client) { final String adminPagePath = "/ghost/"; String adminPageUrl = NetworkUtils.makeAbsoluteUrl(blogUrl, adminPagePath); return checkUrl(adminPageUrl, client).flatMap(response -> { if (response.isSuccessful()) { // the request may have been redirected, most commonly from HTTP => HTTPS // so pick up the eventual URL of the blog and use that // (even if the user manually entered HTTP - it's certainly a mistake) // to get that, chop off the admin page path from the end String potentiallyRedirectedUrl = response.request().url().toString(); String finalBlogUrl = potentiallyRedirectedUrl.replaceFirst(adminPagePath + "?$", ""); return Single.just(finalBlogUrl); } else if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) { return Single.error(new UrlNotFoundException(blogUrl)); } else { return Single.error(new RuntimeException("Response code " + response.code() + " on requesting admin page at " + adminPageUrl)); } }); } private static Single<Response> checkUrl(@NonNull String url, @NonNull OkHttpClient client) { try { Request request = new Request.Builder() .url(url) .head() // make a HEAD request because we only want the response code .build(); return networkCall(client.newCall(request)); } catch (IllegalArgumentException e) { // invalid url (whitespace chars etc) return Single.error(new MalformedURLException("Invalid Ghost admin address: " + url)); } } public static class UrlValidationException extends RuntimeException { private final String url; public UrlValidationException(Throwable cause, String url) { super("Couldn't validate the url " + url, cause); this.url = url; } public String getUrl() { return url; } } }
40.569892
102
0.622847
7d5c4ea9acafe167ac5234fe258b4570ffc9a0f4
1,343
package co.team.security.service; import org.junit.Test; import co.team.food.service.FoodVO; public class PasswordEncoderTest { @Test public void passwordEncode() throws Exception{ //String str ="하하.png"; //String word = str.split("\\.")[str.split("\\.").length -1]; //System.out.println(word); //String list [] = str.split("."); /* * for(int i=0; i<list.length; i++) { System.out.println(list[i]); } */ // System.out.println(getRandomStr(8)); } public static String getRandomStr(int size) { if(size > 0) { char[] tmp = new char[size]; for(int i=0; i<tmp.length; i++) { int div = (int) Math.floor( Math.random() * 2 ); if(div == 0) { // 0이면 숫자로 tmp[i] = (char) (Math.random() * 10 + '0') ; }else { //1이면 알파벳 tmp[i] = (char) (Math.random() * 26 + 'A') ; } } return new String(tmp); } return "ERROR : Size is required."; } // @Test // public void passwordTest() throws Exception{ // PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // String encodePasswd = "$2a$10$lkaOPkitBlBtu7HPb6U3tuW4LP7VPv8eun1RzzHN3Oz6CkiJt9HGW"; // String password = "1234"; // boolean test = passwordEncoder.matches(password, encodePasswd); // System.out.println(test); // } }
24.87037
92
0.581534
992444ca5ae493c592d54102fa6961b464faec1c
1,649
package lk.axres.mobimart; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; public class EnginActivity extends AppCompatActivity { Button conti; String[] model = { "No Car", "BMW", "Toyota", "Hyundai", "Honda"}; String[] car = { "No Car", "X1", "Z4", "3", "X7"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_engin); conti = findViewById(R.id.conti); Spinner spin = (Spinner) findViewById(R.id.spinner); Spinner spin2 = (Spinner) findViewById(R.id.spinner2); //Creating the ArrayAdapter instance having the country list ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,car); aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); ArrayAdapter aaa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,model); aaa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //Setting the ArrayAdapter data on the Spinner spin.setAdapter(aa); spin2.setAdapter(aaa); conti.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(EnginActivity.this, MainActivity.class); startActivity(intent); } }); } }
34.354167
93
0.688296
9b4732d12c4badd729793bccd208178bc0439b39
482
package net.minidev.ovh.api.dbaas.queue; /** * AppConfiguration */ public class OvhAppConfiguration { /** * Application * * canBeNull && readOnly */ public OvhApp app; /** * List of created roles * * canBeNull && readOnly */ public OvhRole[] roles; /** * Metrics account * * canBeNull && readOnly */ public OvhMetricsAccount metricsAccount; /** * List of created users * * canBeNull && readOnly */ public OvhUserWithPassword[] users; }
13.771429
41
0.639004
1765e8b49a497085ef0c9e29738abc6d065c3d79
8,499
package com.xiaojukeji.kafka.manager.service.cache; import com.xiaojukeji.kafka.manager.common.entity.po.ClusterDO; import kafka.admin.AdminClient; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * Cache Kafka客户端 * @author zengqiao * @date 19/12/24 */ public class KafkaClientCache { private final static Logger logger = LoggerFactory.getLogger(KafkaClientCache.class); /** * AdminClient */ private static Map<Long, AdminClient> AdminClientMap = new ConcurrentHashMap<>(); /** * API侧接口使用的Client */ private static Map<Long, KafkaConsumer> ApiKafkaConsumerClientMap = new ConcurrentHashMap<>(); /** * Common使用的Client */ private static Map<Long, KafkaConsumer> CommonKafkaConsumerClientMap = new ConcurrentHashMap<>(); /** * 公共Producer, 一个集群至多一个 */ private static Map<Long, KafkaProducer<String, String>> KafkaProducerMap = new ConcurrentHashMap<>(); private static ReentrantLock lock = new ReentrantLock(); public static KafkaProducer<String, String> getKafkaProducerClient(Long clusterId) { KafkaProducer<String, String> kafkaProducer = KafkaProducerMap.get(clusterId); if (kafkaProducer != null) { return kafkaProducer; } ClusterDO clusterDO = ClusterMetadataManager.getClusterFromCache(clusterId); if (clusterDO == null) { return null; } Properties properties = createProperties(clusterDO, true); properties.setProperty(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4"); properties.setProperty(ProducerConfig.LINGER_MS_CONFIG, "10"); properties.setProperty(ProducerConfig.RETRIES_CONFIG, "3"); lock.lock(); try { kafkaProducer = KafkaProducerMap.get(clusterId); if (kafkaProducer != null) { return kafkaProducer; } KafkaProducerMap.put(clusterId, new KafkaProducer<String, String>(properties)); } catch (Exception e) { logger.error("create kafka producer client failed, clusterId:{}.", clusterId, e); } finally { lock.unlock(); } return KafkaProducerMap.get(clusterId); } public static KafkaConsumer getApiKafkaConsumerClient(ClusterDO clusterDO) { if (clusterDO == null) { return null; } KafkaConsumer kafkaConsumer = ApiKafkaConsumerClientMap.get(clusterDO.getId()); if (kafkaConsumer != null) { return kafkaConsumer; } Properties properties = createProperties(clusterDO, false); properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "10000"); properties.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, "20000"); properties.put("enable.auto.commit", "false"); lock.lock(); try { kafkaConsumer = ApiKafkaConsumerClientMap.get(clusterDO.getId()); if (kafkaConsumer != null) { return kafkaConsumer; } ApiKafkaConsumerClientMap.put(clusterDO.getId(), new KafkaConsumer(properties)); } catch (Exception e) { logger.error("create kafka consumer client failed, clusterId:{}.", clusterDO.getId(), e); } finally { lock.unlock(); } return ApiKafkaConsumerClientMap.get(clusterDO.getId()); } public static KafkaConsumer getCommonKafkaConsumerClient(Long clusterId) { KafkaConsumer kafkaConsumer = CommonKafkaConsumerClientMap.get(clusterId); if (kafkaConsumer != null) { return kafkaConsumer; } ClusterDO clusterDO = ClusterMetadataManager.getClusterFromCache(clusterId); if (clusterDO == null) { return null; } Properties properties = createProperties(clusterDO, false); properties.put("enable.auto.commit", "false"); lock.lock(); try { kafkaConsumer = CommonKafkaConsumerClientMap.get(clusterId); if (kafkaConsumer != null) { return kafkaConsumer; } CommonKafkaConsumerClientMap.put(clusterId, new KafkaConsumer(properties)); } catch (Exception e) { logger.error("create kafka consumer client failed, clusterId:{}.", clusterId, e); } finally { lock.unlock(); } return CommonKafkaConsumerClientMap.get(clusterId); } public static synchronized void closeApiKafkaConsumerClient(Long clusterId) { KafkaConsumer kafkaConsumer = ApiKafkaConsumerClientMap.remove(clusterId); if (kafkaConsumer == null) { return; } try { kafkaConsumer.close(); } catch (Exception e) { logger.error("close kafka consumer client error, clusterId:{}.", clusterId, e); } } public static synchronized void closeCommonKafkaConsumerClient(Long clusterId) { KafkaConsumer kafkaConsumer = CommonKafkaConsumerClientMap.remove(clusterId); if (kafkaConsumer == null) { return; } try { kafkaConsumer.close(); } catch (Exception e) { logger.error("close kafka consumer client error, clusterId:{}.", clusterId, e); } } public static AdminClient getAdminClient(Long clusterId) { AdminClient adminClient = AdminClientMap.get(clusterId); if (adminClient != null) { return adminClient; } ClusterDO clusterDO = ClusterMetadataManager.getClusterFromCache(clusterId); if (clusterDO == null) { return null; } Properties properties = createProperties(clusterDO, false); lock.lock(); try { adminClient = AdminClientMap.get(clusterId); if (adminClient != null) { return adminClient; } AdminClientMap.put(clusterId, AdminClient.create(properties)); } catch (Exception e) { logger.error("create kafka admin client failed, clusterId:{}.", clusterId, e); } finally { lock.unlock(); } return AdminClientMap.get(clusterId); } public static void closeAdminClient(ClusterDO cluster) { if (AdminClientMap.containsKey(cluster.getId())) { AdminClientMap.get(cluster.getId()).close(); } } public static Properties createProperties(ClusterDO clusterDO, Boolean serialize) { Properties properties = new Properties(); properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, clusterDO.getBootstrapServers()); if (serialize) { properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); } else { properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); } if (!StringUtils.isEmpty(clusterDO.getSecurityProtocol())) { properties.setProperty (CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, clusterDO.getSecurityProtocol()); } if (!StringUtils.isEmpty(clusterDO.getSaslMechanism())) { properties.setProperty ("sasl.mechanism", clusterDO.getSaslMechanism()); } if (!StringUtils.isEmpty(clusterDO.getSaslJaasConfig())) { properties.put("sasl.jaas.config", clusterDO.getSaslJaasConfig()); } return properties; } private static String key(Long clusterId, String topicName) { if (StringUtils.isEmpty(topicName)) { return String.valueOf(clusterId); } return String.valueOf(clusterId) + '_' + topicName; } }
39.901408
143
0.656783
e5a68f58793511a0c9126150b34f48b07886fa3e
796
package application.model.quantity; public class Charge extends UnitValue implements Cloneable { public static final String unit = "As"; public Charge(double value) { super(value, unit); } public Charge(Charge Q) { this(Q.getValue()); } public Charge(Current I, Time t) { this(I.mul(t).getValue()); } public Charge(Time t, Current I) { this(I.mul(t).getValue()); } public Charge(Work W, Voltage V) { this(W.div(V).getValue()); } public Charge(Energy E, Voltage V) { this(E.div(V).getValue()); } public Charge clone() { return new Charge(this); } @Override public String toString() { return getValue() + " C"; } }
20.410256
61
0.540201
59299a0d1c33431415a17d10e6a9ee3e5b270215
4,934
package com.airbnb.aerosolve.core.models; import com.airbnb.aerosolve.core.KDTreeNode; import com.airbnb.aerosolve.core.util.Util; import com.google.common.base.Optional; import lombok.Getter; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Stack; import static com.airbnb.aerosolve.core.KDTreeNodeType.LEAF; // A specialized 2D kd-tree that supports point and box queries. public class KDTreeModel implements Serializable { private static final long serialVersionUID = -2884260218927875695L; private static final Logger log = LoggerFactory.getLogger(KDTreeModel.class); @Getter private KDTreeNode[] nodes; public KDTreeModel(KDTreeNode[] nodes) { this.nodes = nodes; } public KDTreeModel(List<KDTreeNode> nodeList) { nodes = new KDTreeNode[nodeList.size()]; nodeList.toArray(nodes); } // Returns the indice of leaf containing the point. public int leaf(double x, double y) { if (nodes == null) return -1; int currIdx = 0; while (true) { int nextIdx = next(currIdx, x, y); if (nextIdx == -1) { return currIdx; } else { currIdx = nextIdx; } } } public KDTreeNode getNode(int id) { return nodes[id]; } // Returns the indices of nodes traversed to get to the leaf containing the point. public ArrayList<Integer> query(double x, double y) { ArrayList<Integer> idx = new ArrayList<>(); if (nodes == null) return idx; int currIdx = 0; while (true) { idx.add(currIdx); int nextIdx = next(currIdx, x, y); if (nextIdx == -1) { return idx; } else { currIdx = nextIdx; } } } private int next(int currIdx, double x, double y) { KDTreeNode node = nodes[currIdx]; int nextIndex = -1; switch(node.nodeType) { case X_SPLIT: { if (x < node.splitValue) { nextIndex = node.leftChild; } else { nextIndex = node.rightChild; } } break; case Y_SPLIT: { if (y < node.splitValue) { nextIndex = node.leftChild; } else { nextIndex = node.rightChild; } } break; default: assert (node.nodeType == LEAF); break; } return nextIndex; } // Returns the indices of all node overlapping the box public ArrayList<Integer> queryBox(double minX, double minY, double maxX, double maxY) { ArrayList<Integer> idx = new ArrayList<>(); if (nodes == null) return idx; Stack<Integer> stack = new Stack<Integer>(); stack.push(0); while (!stack.isEmpty()) { int currIdx = stack.pop(); idx.add(currIdx); KDTreeNode node = nodes[currIdx]; switch (node.nodeType) { case X_SPLIT: { if (minX < node.splitValue) { stack.push(node.leftChild); } if (maxX >= node.splitValue) { stack.push(node.rightChild); } } break; case Y_SPLIT: { if (minY < node.splitValue) { stack.push(node.leftChild); } if (maxY >= node.splitValue) { stack.push(node.rightChild); } } case LEAF: break; } } return idx; } public static Optional<KDTreeModel> readFromGzippedStream(InputStream inputStream) { List<KDTreeNode> nodes = Util.readFromGzippedStream(KDTreeNode.class, inputStream); if (!nodes.isEmpty()) { return Optional.of(new KDTreeModel(nodes)); } else { return Optional.absent(); } } public static Optional<KDTreeModel> readFromGzippedResource(String name) { InputStream inputStream = java.lang.ClassLoader.getSystemResourceAsStream(name); Optional<KDTreeModel> modelOptional = readFromGzippedStream(inputStream); if (!modelOptional.isPresent()) { log.error("Could not load resource named " + name); } return modelOptional; } public static Optional<KDTreeModel> readFromGzippedBase64String(String encoded) { byte[] decoded = Base64.decodeBase64(encoded); InputStream stream = new ByteArrayInputStream(decoded); return readFromGzippedStream(stream); } // Strips nodes for queries. To save space we just store the minimum amount of data. public static KDTreeNode stripNode(KDTreeNode node) { KDTreeNode newNode = new KDTreeNode(); if (node.isSetNodeType()) { newNode.setNodeType(node.nodeType); } if (node.isSetSplitValue()) { newNode.setSplitValue(node.splitValue); } if (node.isSetLeftChild()) { newNode.setLeftChild(node.leftChild); } if (node.isSetRightChild()) { newNode.setRightChild(node.rightChild); } return newNode; } }
27.10989
90
0.638022
6858aba99d318ecfbcee4a8a0b0ffcc9092c14ef
2,992
package com.telek.betterswing.components; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingFrame { private JFrame frame; //////////////////// /* CONSTRUCTORS */ //////////////////// public SwingFrame(JFrame frame){ this.frame = frame; } public SwingFrame(SwingFrame swingFrame){ this.frame = swingFrame.getFrame(); } public SwingFrame(){ this.frame = new JFrame(); } public SwingFrame(String title){ this.frame = new JFrame(title); } /////////////// /* METHODS */ /////////////// public SwingFrame setBounds(Rectangle bounds){ this.frame.setBounds(bounds); return this; } public SwingFrame setBackground(Color bgColor){ this.frame.setBackground(bgColor); return this; } public SwingFrame setForeground(Color fgColor){ this.frame.setForeground(fgColor); return this; } public SwingFrame setCursor(Cursor cursor){ this.frame.setCursor(cursor); return this; } public SwingFrame setEnabled(boolean isEnabled){ this.frame.setEnabled(isEnabled); return this; } public SwingFrame setFont(Font font){ this.frame.setFont(font); return this; } public SwingFrame setVisible(boolean isVisible){ this.frame.setVisible(isVisible); return this; } public SwingFrame setLayout(LayoutManager layout){ this.frame.setLayout(layout); return this; } public SwingFrame setIconImage(Image iconImage){ this.frame.setIconImage(iconImage); return this; } public SwingFrame setTitle(String title){ this.frame.setTitle(title); return this; } public SwingFrame setResizable(boolean isResizable){ this.frame.setResizable(isResizable); return this; } public SwingFrame setDefaultCloseOperation(int closeOperation){ this.frame.setDefaultCloseOperation(closeOperation); return this; } public SwingFrame setContentPane(Container contentPane){ this.frame.setContentPane(contentPane); return this; } public SwingFrame setOpacity(float opacity){ this.frame.setOpacity(opacity); return this; } public SwingFrame addMouseListener(MouseListener mouseListener){ this.frame.addMouseListener(mouseListener); return this; } public SwingFrame addMouseMotionListener(MouseMotionListener mouseMotionListener){ this.frame.addMouseMotionListener(mouseMotionListener); return this; } public SwingFrame addMouseWheelListener(MouseWheelListener mouseWheelListener){ this.frame.addMouseWheelListener(mouseWheelListener); return this; } /////////////////////////// /* GETTERS AND SETTERS */ /////////////////////////// public JFrame getFrame() { return frame; } }
26.245614
86
0.626003
0955137da844dd18831a1ca454d99bf2a8eb5e0e
2,296
package ooga.parser.components; import java.util.ResourceBundle; /** * Job of this class is to parse and extract display/launcher info. Uses the DOM Parser API. * @author Alex Xu */ public class DisplayInfoParser extends AbstractParser { public static final String RESOURCES_PATH = "ooga.parser.properties.displayInfoProperties"; public static final String XSD = "src/ooga/parser/validators/xsdSchema/displayinfo.xsd"; public static final String DISPLAY_CONFIG_SUFFIX = "info.xml"; public static final String COVER_IMAGE = "coverimage"; public static final String TITLE = "title"; public static final String DESCRIPTION = "description"; public static final String CONTROLS = "controls"; public static final String DESCRIPTION_IMAGE = "descriptionimage"; private String myCoverImage; private String myTitle; private String myDescription; private String myControls; private String myDescriptionImage; private ResourceBundle myResources; public DisplayInfoParser(String filepath){ super(filepath + DISPLAY_CONFIG_SUFFIX, XSD); myResources = ResourceBundle.getBundle(RESOURCES_PATH); extractCoverImage(); extractDescriptionImage(); extractTitle(); extractDescription(); extractControls(); } public String getCoverImage(){ return myCoverImage; } public String getDescriptionImage(){ return myDescriptionImage; } public String getTitle(){ return myTitle; } public String getDescription(){ return myDescription; } public String getControls(){ return myControls; } private void extractCoverImage(){ myCoverImage = extractElementValue(myResources.getString(COVER_IMAGE)); } private void extractTitle(){ myTitle = extractElementValue(myResources.getString(TITLE)); } private void extractControls() { myControls = extractElementValue(myResources.getString(CONTROLS)); } private void extractDescription() { myDescription = extractElementValue(myResources.getString(DESCRIPTION)); } private void extractDescriptionImage(){ myDescriptionImage = extractElementValue(myResources.getString(DESCRIPTION_IMAGE)); } }
29.818182
95
0.710366
16d6dcc6606a251ce171df87b56192a2ae6d82af
1,291
package com.example.demo.repository; import com.example.demo.entity.Menu; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @Log @Repository public class MenuRepository { @Autowired private JdbcTemplate jdbcTemplate; public List<Menu> list() throws Exception { List<Menu> results = jdbcTemplate.query( "select drinkName, drinkMemo, drinkPrice, drinkType from menuInfo", new RowMapper<Menu>() { @Override public Menu mapRow(ResultSet rs, int rowNum) throws SQLException { Menu menu = new Menu(); menu.setDrinkName(rs.getString("drinkName")); menu.setDrinkMemo(rs.getString("drinkMemo")); menu.setDrinkPrice(rs.getInt("drinkPrice")); menu.setDrinkType(rs.getString("drinkType")); return menu; } } ); return results; } }
30.738095
86
0.613478
c1a518b287e367f3f0b669e09282ff62c1e3f095
463
package app.retake.services.api; import app.retake.domain.dto.AnimalJSONImportDTO; import app.retake.domain.dto.AnimalsJSONExportDTO; import app.retake.domain.models.Animal; import java.text.ParseException; import java.util.List; public interface AnimalService { void create(AnimalJSONImportDTO dto) throws ParseException; List<AnimalsJSONExportDTO> findByOwnerPhoneNumber(String phoneNumber); Animal findByPassportSerialNumber(String passport); }
30.866667
74
0.825054
0b25236c5e4f15afeea7e2d258a1993ac99e88bc
12,401
package com.github.cuter44.wxpay.resps; import java.util.List; import java.util.ArrayList; import java.util.Properties; import java.util.Iterator; import java.util.Arrays; import java.util.Date; import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import com.github.cuter44.nyafx.crypto.*; import com.github.cuter44.nyafx.text.*; import com.github.cuter44.wxpay.WxpayException; import com.github.cuter44.wxpay.WxpayProtocolException; import com.github.cuter44.wxpay.util.*; /** General response passed by req.execute() or alipay callback/redirect gateways * Actually reqs/gateways passed excatly response type, i.e. sub-class of this. * I'm recommending you to see the sub-class javadoc... to help you write elegant code. * Notice that downloadbill's response does not inherit this class. That's ass hole. */ public class WxpayResponseBase { // CONSTANTS public static final String KEY_KEY = "KEY"; public static final String KEY_SIGN = "sign"; public static final String KEY_SKIP_VERIFY_SIGN = "SKIP_VERIFY_SIGN"; public static final String KEY_RETURN_CODE = "return_code"; public static final String KEY_RETURN_MSG = "return_msg"; public static final String KEY_RESULT_CODE = "result_code"; public static final String KEY_ERR_CODE = "err_code"; public static final String KEY_ERR_CODE_DES = "err_code_des"; public static final String VALUE_SUCCESS = "SUCCESS"; public static final String VALUE_FAIL = "FAIL"; protected static CryptoBase crypto = CryptoBase.getInstance(); protected Boolean validity = null; // STRING /** @deprecated since 0.4.5 WxpayResponse no longer preserve the origin response body */ protected String respString; /** * retrieve callback params or response content as String * @deprecated since 0.4.5 WxpayResponse no longer preserve the origin response body */ public String getString() { return(this.respString); } // PROPERTIES protected Properties respProp; /** * retrieve callback params or response content as Properties */ public final Properties getProperties() { return(this.respProp); } public final String getProperty(String key) { return(this.respProp.getProperty(key)); } public final Integer getIntProperty(String key) { String v = this.getProperty(key); return( (v!=null) ? Integer.valueOf(v) : null ); } public final Date getDateProperty(String key) { try { String v = this.getProperty(key); return( (v!=null) ? CSTConvert.parse(v) : null ); } catch (Exception ex) { // rarely occurs ex.printStackTrace(); return(null); } } // CONSTRUCT public WxpayResponseBase() { return; } /** * This construstor automatically parse input as xml, and output properties. Meanwhile, detect the fails. * Notice that Properties does not support hierachy, so it go down if tag names are non-unique. * It is raw in present. If it really happens, a new response type and parser should be defined to cope with that. */ public WxpayResponseBase(String xml) throws WxpayProtocolException, WxpayException { this.respString = xml; this.respProp = XMLParser.parseXML(xml); if (!this.isReturnCodeSuccess()) throw( new WxpayProtocolException( this.respProp.getProperty(KEY_RETURN_MSG) )); if (!this.isResultCodeSuccess()) throw( new WxpayException( this.respProp.getProperty(KEY_ERR_CODE) )); return; } /** * This construstor automatically parse input as xml, and output properties. Meanwhile, detect the fails. * Notice that Properties does not support hierachy, so it go down if tag names are non-unique. * It is raw in present. If it really happens, a new response type and parser should be defined to cope with that. */ public WxpayResponseBase(InputStream xml) throws IOException { this.respProp = XMLParser.parseXML(xml); if (!this.isReturnCodeSuccess()) throw( new WxpayProtocolException( this.respProp.getProperty(KEY_RETURN_MSG) )); if (!this.isResultCodeSuccess()) throw( new WxpayException( this.respProp.getProperty(KEY_ERR_CODE) )); xml.close(); return; } /** @deprecated due to it doesn't parse and detect fails. ONLY FOR DEBUGGING. */ public WxpayResponseBase(Properties aRespProp) { this(null, aRespProp); return; } /** @deprecated due to it doesn't parse and detect fails. ONLY FOR DEBUGGING. */ public WxpayResponseBase(String aRespString, Properties aRespProp) { this.respString = aRespString; this.respProp = aRespProp; return; } // EXCEPTION /** 此字段是通信标识,非交易标识,交易是否成功需要查看 result_code 来判断 */ public boolean isReturnCodeSuccess() { return( VALUE_SUCCESS.equals(this.getProperty(KEY_RETURN_CODE)) ); } public WxpayProtocolException getReturnMsg() { String returnMsg = this.getProperty(KEY_RETURN_MSG); if (returnMsg != null) return(new WxpayProtocolException(returnMsg)); // else return(null); } public boolean isResultCodeSuccess() { return( VALUE_SUCCESS.equals(this.getProperty(KEY_RESULT_CODE)) ); } public WxpayException getErrCode() { String errCode = this.getProperty(KEY_ERR_CODE); if (errCode != null) return(new WxpayException(errCode)); // else return(null); } public String getErrCodeDes() { return( this.getProperty(KEY_ERR_CODE_DES) ); } // VERIFY /** * verify response sign * @return true if passed (i.e. response content should be trusted), otherwise false */ public boolean verify(Properties conf) throws UnsupportedEncodingException { if (this.validity != null) return(this.validity); Boolean skipSign = Boolean.valueOf(conf.getProperty("SKIP_VERIFY_SIGN")); // else this.validity = true; if (!skipSign) this.validity = this.validity && this.verifySign(conf); return(this.validity); } /** 子类应该实现这个方法以验证签名 * SUB-CLASS MUST IMPLEMENT THIS METHOD TO BE CALLBACKED. Default behavior do no verification, i.e. always return true. * A typical implemention should be <code>return(super.verifySign(this.keysParamName, conf)</code> where * ); */ protected boolean verifySign(Properties conf) throws UnsupportedEncodingException, UnsupportedOperationException { // DEFAULT IMPLEMENT return(true); } protected boolean verifySign(List<String> paramNames, Properties conf) throws UnsupportedEncodingException { this.respProp = buildConf(this.respProp, conf); String stated = this.getProperty("sign"); String calculated = this.sign( paramNames ); return( stated!=null && stated.equals(calculated) ); } /** * @param paramNames key names to submit, in dictionary order */ protected String sign(List<String> paramNames) throws UnsupportedEncodingException, UnsupportedOperationException, IllegalStateException { String key = this.getProperty(KEY_KEY); String sign = this.signMD5(paramNames, key); return(sign); } /** * caculate sign according to wxp-spec * @exception UnsupportedEncodingException if your runtime does not support utf-8. */ protected String signMD5(List<String> paramNames, String key) throws UnsupportedEncodingException { if (key == null) throw(new IllegalArgumentException("KEY required to sign, but not found.")); StringBuilder sb = new StringBuilder() .append(this.toQueryString(paramNames)) .append("&key="+key); String sign = this.crypto.byteToHex( this.crypto.MD5Digest( sb.toString().getBytes("utf-8") )); sign = sign.toUpperCase(); return(sign); } /** Provide query string to sign(). * toURL() may not invoke this method. */ protected String toQueryString(List<String> paramNames) { URLBuilder ub = new URLBuilder(); for (String key:paramNames) { if (KEY_SIGN.equals(key)) continue; String value = this.getProperty(key); if (value == null || value.isEmpty()) continue; ub.appendParam(key, value); } return(ub.toString()); } // UTIL protected static Properties buildConf(Properties prop, Properties defaults) { Properties ret = new Properties(defaults); Iterator<String> iter = prop.stringPropertyNames().iterator(); while (iter.hasNext()) { String key = iter.next(); ret.setProperty(key, prop.getProperty(key)); } return(ret); } protected static String materializeParamName(String template, Integer ... params) { String s = template; for (int i=0; i<params.length; i++) s = s.replace("$"+i, Integer.toString(params[i])); return(s); } private static String[] internalMaterializeParamNames(String template, int level, Integer count0) { if (count0 == null || count0 == 0) return(new String[0]); if (!template.contains("$")) return(new String[]{template}); String placeholder = "$"+level; String[] m0 = new String[count0]; for (int i=0; i<count0; i++) m0[i] = template.replace(placeholder, Integer.toString(i)); Arrays.sort(m0); return(m0); } protected static List<String> materializeParamNames(String template, int level, Integer count0) { if (count0 == null || count0 == 0) return(new ArrayList<String>()); return( Arrays.asList( WxpayResponseBase.internalMaterializeParamNames(template, level, count0) ) ); } @SuppressWarnings("unchecked") protected static List<String> materializeParamNames(String template, int level, Integer count0, List ... counts) { if (count0 == null || count0 == 0) return(new ArrayList<String>()); String[] m0 = WxpayResponseBase.internalMaterializeParamNames(template, level, count0); List<String> mx; if (!m0[0].contains("$")) { mx = Arrays.asList(m0); } else { mx = new ArrayList<String>(); List<Integer> count1s = (List<Integer>)counts[0]; if (counts.length == 1) { for (int i=0; i<count0; i++) { Integer count1 = count1s.get(i); if (count1 == null) continue; mx.addAll( materializeParamNames(m0[i], level+1, count1) ); } } else { for (int i=0; i<count0; i++) { Integer count1 = count1s.get(i); if (count1 == null) continue; List[] countsDesc = new List[counts.length-1]; for (int j=1; j<counts.length; j++) countsDesc[j-1] = (List)counts[j].get(i); mx.addAll( materializeParamNames(m0[i], level+1, count1, countsDesc) ); } } } return(mx); } }
27.993228
123
0.587775
a15f97385f9efabb7ce3e14fa086bc34d3b45030
599
package com.young.simpledict.dict.model; import java.util.ArrayList; import java.util.List; /** * Author: landerlyoung * Date: 2014-10-22 * Time: 16:05 * Life with passion. Code with creativity! */ public class DictExplain { public String dictName; //词性 public List<String> trs = new ArrayList<String>(); //变换 public List<WF> wfs = new ArrayList<WF>(); public static class WF { public WF(String name, String value) { this.name = name; this.value = value; } public String name; public String value; } }
20.655172
54
0.609349
4f4062bdbcd75afdd16c5007f6be34e86abef9b8
369
package com.goat.chapter200.item03; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * Created by Administrator on 2021/6/16. * * @ Description: TODO * @ author 山羊来了 * @ date 2021/6/16---16:18 */ @Configuration @ComponentScan("com.goat.chapter200.item03") public class Config { }
18.45
60
0.745257
4f9a8e84d80adc225c7afaed39f921b8b0b3aca2
1,816
package org.algorithms.coding_patterns.educative.merge_intervals; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class EmployeeFreeTimeTest { @Test void findEmployeeFreeTime1() { List<List<Interval>> input = new ArrayList<>(); input.add(new ArrayList<>(Arrays.asList(new Interval(1, 3), new Interval(5, 6)))); input.add(new ArrayList<>(Arrays.asList(new Interval(2, 3), new Interval(6, 8)))); List<Interval> result = EmployeeFreeTime.findEmployeeFreeTime(input); assertEquals(1, result.size()); assertEquals(new Interval(3, 5), result.get(0)); } @Test void findEmployeeFreeTime2() { List<List<Interval>> input = new ArrayList<>(); input.add(new ArrayList<>(Arrays.asList(new Interval(1, 3), new Interval(9, 12)))); input.add(new ArrayList<>(Arrays.asList(new Interval(2, 4)))); input.add(new ArrayList<>(Arrays.asList(new Interval(6, 8)))); List<Interval> result = EmployeeFreeTime.findEmployeeFreeTime(input); assertEquals(2, result.size()); assertEquals(new Interval(4, 6), result.get(0)); assertEquals(new Interval(8, 9), result.get(1)); } @Test void findEmployeeFreeTime3() { List<List<Interval>> input = new ArrayList<>(); input.add(new ArrayList<>(Arrays.asList(new Interval(1, 3)))); input.add(new ArrayList<>(Arrays.asList(new Interval(2, 4)))); input.add(new ArrayList<>(Arrays.asList(new Interval(3, 5), new Interval(7, 9)))); List<Interval> result = EmployeeFreeTime.findEmployeeFreeTime(input); assertEquals(1, result.size()); assertEquals(new Interval(5, 7), result.get(0)); } }
40.355556
91
0.659692
8865e42b27160cb2440dc893f302b0ee2b112ee3
11,794
package com.chin.bbdb.activity; import java.util.HashMap; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.chin.bbdb.FamStore; import com.chin.bbdb.FamStore.TierCategory; import com.chin.bbdb.R; import com.chin.common.TabListener; import com.chin.common.Util; import com.nostra13.universalimageloader.core.ImageLoader; import android.app.ActionBar; import android.app.Activity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTabHost; import android.content.Intent; import android.graphics.Point; import android.os.AsyncTask; import android.os.Bundle; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TabWidget; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; /** * An activity that displays the PVP, Raid and Tower tier tables */ public class TierTableActivity extends BaseFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // add the tabs ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); Bundle bundlePVP = new Bundle(); bundlePVP.putSerializable("category", TierCategory.PVP); bar.addTab(bar.newTab().setText("PVP Tier") .setTabListener(new TabListener<TierFragment>(this, "pvp", TierFragment.class, bundlePVP, R.id.tab_viewgroup))); Bundle bundleRAID = new Bundle(); bundleRAID.putSerializable("category", TierCategory.RAID); bar.addTab(bar.newTab().setText("Raid Tier") .setTabListener(new TabListener<TierFragment>(this, "raid", TierFragment.class, bundleRAID, R.id.tab_viewgroup))); Bundle bundleTOWER = new Bundle(); bundleTOWER.putSerializable("category", TierCategory.TOWER); bar.addTab(bar.newTab().setText("Tower Tier") .setTabListener(new TabListener<TierFragment>(this, "tower", TierFragment.class, bundleTOWER, R.id.tab_viewgroup))); // if we're resuming the activity, re-select the tab that was selected before if (savedInstanceState != null) { // Select the tab that was selected before orientation change int index = savedInstanceState.getInt("TAB_INDEX"); bar.setSelectedNavigationItem(index); } } @Override public void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); // Save the index of the currently selected tab bundle.putInt("TAB_INDEX", getActionBar().getSelectedTab().getPosition()); } /** * A fragment for a tier category (PVP, raid or tower) * There will be many TierTableFragment nested inside it */ public static class TierFragment extends Fragment { private FragmentTabHost mTabHost; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); TierCategory category = (TierCategory) args.getSerializable("category"); mTabHost = new FragmentTabHost(getActivity()); mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.tab_viewgroup); // make the X+, X, S+, etc. tabs String[] listOfTiers = FamStore.catTierList.get(category); for (int i = 0; i < listOfTiers.length; i++) { String tier = listOfTiers[i]; Bundle bundle = new Bundle(); bundle.putSerializable("category", category); bundle.putString("tier", tier); mTabHost.addTab(mTabHost.newTabSpec(tier).setIndicator("Tier " + tier), TierTableFragment.class, bundle); } // make the tabs scrollable TabWidget tw = (TabWidget) mTabHost.findViewById(android.R.id.tabs); LinearLayout ll = (LinearLayout) tw.getParent(); HorizontalScrollView hs = new HorizontalScrollView(getActivity()); hs.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); ll.addView(hs, 0); ll.removeView(tw); hs.addView(tw); hs.setHorizontalScrollBarEnabled(false); return mTabHost; } @Override public void onDestroyView() { super.onDestroyView(); mTabHost = null; } } /** * A fragment for a specific category-tier pair that displays all fams in that tier and category */ public static class TierTableFragment extends Fragment { @SuppressWarnings("rawtypes") AsyncTask myTask; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); TierCategory category = (TierCategory) args.getSerializable("category"); String tier = args.getString("tier"); // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_tier_list, container, false); LinearLayout layout = (LinearLayout) view.findViewById(R.id.tier_layout); try {//TODO: see if we can be more error-tolerance myTask = new PopulateTierTableAsyncTask(getActivity(), layout, category).execute(tier); } catch (Exception e) { e.printStackTrace(); } return view; } @Override public void onPause() { super.onPause(); if (myTask != null) { myTask.cancel(true); } myTask = null; } } /** * An AsyncTask that populates a TierTableFragment * @author Chin * */ public static class PopulateTierTableAsyncTask extends AsyncTask<String, Void, Void> { Activity activity; LinearLayout layout; String tier; Document pageDOM; TierCategory category; // map a tier string to an int (the table number) private static final HashMap<TierCategory, HashMap<String, Integer>> tierMap; static { // darn java, why do you make things so hard for me? tierMap = new HashMap<TierCategory, HashMap<String, Integer>>(); HashMap<String, Integer> pvp = new HashMap<String, Integer>(); HashMap<String, Integer> raid = new HashMap<String, Integer>(); HashMap<String, Integer> tower = new HashMap<String, Integer>(); pvp.put("X+", 0); pvp.put("X", 1); pvp.put("S+", 2); pvp.put("S", 3); pvp.put("A+", 4); pvp.put("A", 5); pvp.put("B", 6); pvp.put("C", 7); raid.put("X", 0); raid.put("S+", 1); raid.put("S", 2); raid.put("A+", 3); raid.put("A", 4); raid.put("B", 5); raid.put("C", 6); raid.put("D", 7); raid.put("E", 8); tower.put("X+", 0); tower.put("X", 1); tower.put("S+", 2); tower.put("S", 3); tower.put("A+", 4); tower.put("A", 5); tower.put("B", 6); tower.put("C", 7); tierMap.put(TierCategory.PVP, pvp); tierMap.put(TierCategory.RAID, raid); tierMap.put(TierCategory.TOWER, tower); } public PopulateTierTableAsyncTask(Activity activity, LinearLayout layout, TierCategory category) { this.activity = activity; this.layout = layout; this.category = category; } @Override protected Void doInBackground(String... params) { String mainHTML = null; try { mainHTML = FamStore.getInstance(activity).getTierHTML(category); if (isCancelled()) { return null; // try to return early if possible } tier = params[0]; pageDOM = Jsoup.parse(mainHTML); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void param) { if (pageDOM == null) { return; // instead of try-catch } Elements tierTables = pageDOM.getElementsByClass("wikitable"); // calculate the width of the images to be displayed later on Display display = activity.getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screenWidth = size.x; int scaleWidth = screenWidth / 10; // set it to be 1/10 of the screen width int tableIndex = tierMap.get(category).get(tier); Element tierTable = tierTables.get(tableIndex); TableLayout table = new TableLayout(activity); Elements rows = tierTable.getElementsByTag("tbody").first().getElementsByTag("tr"); // get all rows in each table int countRow = 0; for (Element row : rows) { countRow++; if (countRow == 1) { // row 1 is the column headers. This may be different in the DOM in browser continue; } else { Elements cells = row.getElementsByTag("td"); TableRow tr = new TableRow(activity); ImageView imgView = new ImageView(activity); tr.addView(imgView); // get the thubnail image src Element link = row.getElementsByTag("a").first(); String imgSrc = link.getElementsByTag("img").first().attr("data-src"); if (imgSrc == null || imgSrc.equals("")) imgSrc = link.getElementsByTag("img").first().attr("src"); imgView.setLayoutParams(new TableRow.LayoutParams(scaleWidth, (int) (scaleWidth*1.5))); // the height's not exact imgView.setScaleType(ImageView.ScaleType.FIT_CENTER); // get the scaled image link and display it String newScaledLink = Util.getScaledWikiaImageLink(imgSrc, scaleWidth); ImageLoader.getInstance().displayImage(newScaledLink, imgView); String famName = cells.get(2).text(); TextView tv = new TextView(activity); tv.setText(famName); tr.addView(tv); tr.setGravity(0x10); //center vertical table.addView(tr); tr.setTag(famName); tr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, FamDetailActivity.class); intent.putExtra(MainActivity.FAM_NAME, (String) v.getTag()); activity.startActivity(intent); } }); } } layout.addView(table); //TODO: center the spinner horizontally //remove the spinner ProgressBar progressBar = (ProgressBar) activity.findViewById(R.id.progressBar_tierTable); layout.removeView(progressBar); } } }
39.444816
133
0.596744
194d19113d09a59b7bc744ac613e58cc067ddbdf
159
package com.camnter.hook.ams.f.activity.plugin.host; import android.app.Activity; /** * @author CaMnter */ public class StubActivity extends Activity { }
14.454545
52
0.742138
79e6d9e2db3eb30477f4486edd2813147c4ad3b2
8,061
/* * 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. */ // Generated by http://code.google.com/p/protostuff/ ... DO NOT EDIT! // Generated from protobuf package org.apache.drill.exec.proto.beans; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import com.dyuproject.protostuff.GraphIOUtil; import com.dyuproject.protostuff.Input; import com.dyuproject.protostuff.Message; import com.dyuproject.protostuff.Output; import com.dyuproject.protostuff.Schema; public final class RpcEndpointInfos implements Externalizable, Message<RpcEndpointInfos>, Schema<RpcEndpointInfos> { public static Schema<RpcEndpointInfos> getSchema() { return DEFAULT_INSTANCE; } public static RpcEndpointInfos getDefaultInstance() { return DEFAULT_INSTANCE; } static final RpcEndpointInfos DEFAULT_INSTANCE = new RpcEndpointInfos(); private String name; private String version; private int majorVersion; private int minorVersion; private int patchVersion; private String application; private int buildNumber; private String versionQualifier; public RpcEndpointInfos() { } // getters and setters // name public String getName() { return name; } public RpcEndpointInfos setName(String name) { this.name = name; return this; } // version public String getVersion() { return version; } public RpcEndpointInfos setVersion(String version) { this.version = version; return this; } // majorVersion public int getMajorVersion() { return majorVersion; } public RpcEndpointInfos setMajorVersion(int majorVersion) { this.majorVersion = majorVersion; return this; } // minorVersion public int getMinorVersion() { return minorVersion; } public RpcEndpointInfos setMinorVersion(int minorVersion) { this.minorVersion = minorVersion; return this; } // patchVersion public int getPatchVersion() { return patchVersion; } public RpcEndpointInfos setPatchVersion(int patchVersion) { this.patchVersion = patchVersion; return this; } // application public String getApplication() { return application; } public RpcEndpointInfos setApplication(String application) { this.application = application; return this; } // buildNumber public int getBuildNumber() { return buildNumber; } public RpcEndpointInfos setBuildNumber(int buildNumber) { this.buildNumber = buildNumber; return this; } // versionQualifier public String getVersionQualifier() { return versionQualifier; } public RpcEndpointInfos setVersionQualifier(String versionQualifier) { this.versionQualifier = versionQualifier; return this; } // java serialization public void readExternal(ObjectInput in) throws IOException { GraphIOUtil.mergeDelimitedFrom(in, this, this); } public void writeExternal(ObjectOutput out) throws IOException { GraphIOUtil.writeDelimitedTo(out, this, this); } // message method public Schema<RpcEndpointInfos> cachedSchema() { return DEFAULT_INSTANCE; } // schema methods public RpcEndpointInfos newMessage() { return new RpcEndpointInfos(); } public Class<RpcEndpointInfos> typeClass() { return RpcEndpointInfos.class; } public String messageName() { return RpcEndpointInfos.class.getSimpleName(); } public String messageFullName() { return RpcEndpointInfos.class.getName(); } public boolean isInitialized(RpcEndpointInfos message) { return true; } public void mergeFrom(Input input, RpcEndpointInfos message) throws IOException { for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this)) { switch(number) { case 0: return; case 1: message.name = input.readString(); break; case 2: message.version = input.readString(); break; case 3: message.majorVersion = input.readUInt32(); break; case 4: message.minorVersion = input.readUInt32(); break; case 5: message.patchVersion = input.readUInt32(); break; case 6: message.application = input.readString(); break; case 7: message.buildNumber = input.readUInt32(); break; case 8: message.versionQualifier = input.readString(); break; default: input.handleUnknownField(number, this); } } } public void writeTo(Output output, RpcEndpointInfos message) throws IOException { if(message.name != null) output.writeString(1, message.name, false); if(message.version != null) output.writeString(2, message.version, false); if(message.majorVersion != 0) output.writeUInt32(3, message.majorVersion, false); if(message.minorVersion != 0) output.writeUInt32(4, message.minorVersion, false); if(message.patchVersion != 0) output.writeUInt32(5, message.patchVersion, false); if(message.application != null) output.writeString(6, message.application, false); if(message.buildNumber != 0) output.writeUInt32(7, message.buildNumber, false); if(message.versionQualifier != null) output.writeString(8, message.versionQualifier, false); } public String getFieldName(int number) { switch(number) { case 1: return "name"; case 2: return "version"; case 3: return "majorVersion"; case 4: return "minorVersion"; case 5: return "patchVersion"; case 6: return "application"; case 7: return "buildNumber"; case 8: return "versionQualifier"; default: return null; } } public int getFieldNumber(String name) { final Integer number = __fieldMap.get(name); return number == null ? 0 : number.intValue(); } private static final java.util.HashMap<String,Integer> __fieldMap = new java.util.HashMap<String,Integer>(); static { __fieldMap.put("name", 1); __fieldMap.put("version", 2); __fieldMap.put("majorVersion", 3); __fieldMap.put("minorVersion", 4); __fieldMap.put("patchVersion", 5); __fieldMap.put("application", 6); __fieldMap.put("buildNumber", 7); __fieldMap.put("versionQualifier", 8); } }
25.349057
114
0.610842
a4b2bd341fe8b71bed051ff7c2399f8bc4b50bcc
315
package com.doublechain.flowable.district; import com.doublechain.flowable.EntityNotFoundException; public class DistrictVersionChangedException extends DistrictManagerException { private static final long serialVersionUID = 1L; public DistrictVersionChangedException(String string) { super(string); } }
21
79
0.828571
a0fec5dcb659ac7e3b8cfb64ad103f37c773db45
1,242
package com.andcreations.ae.lua.parser; /** * Represents a Lua element. * * @author Mikolaj Gucki */ public abstract class LuaElement { /** The begin line. */ private int beginLine; /** The end line. */ private int endLine; /** */ protected LuaElement(int beginLine,int endLine) { this.beginLine = beginLine; this.endLine = endLine; } /** * Gets the number of the line at which the function begins. * * @return The begin line number. */ public int getBeginLine() { return beginLine; } /** * Gets the numbe rof line line at which the function ends. * * @return The end line number. */ public int getEndLine() { return endLine; } /** */ @Override public String toString() { return String.format("%d-%d",beginLine,endLine); } /** */ @Override public boolean equals(Object obj) { if ((obj instanceof LuaElement) == false) { return false; } LuaElement that = (LuaElement)obj; return beginLine == that.beginLine && endLine == that.endLine; } }
22.581818
71
0.530596
9a7cc05bf97a1e636f8dcc8f99f775ab48fa4b55
482
/* * Copyright (c) 2019 - 2020. * Author: Arnold Chow * Project name: Java_Optional * Filename: Teacher.java * Date: 21/10/2020, 21:18 */ package test.chapter6.t4; public class Teacher extends Person{ public int b; public static void main(String[] args) { Person p = new Person(); Teacher t = new Teacher(); int i; i = p.change(30); } } class Person { private int a; public int change(int m) { return m; } }
17.214286
44
0.582988
4d5a8f2f10b734f91af4396149f67b03bba4170a
2,322
package br.com.fernando.myExamCloud.implementBusinessLogicUsingEJBs; import java.util.concurrent.TimeUnit; import javax.ejb.Schedule; import javax.ejb.Singleton; import javax.ejb.Stateful; import javax.ejb.StatefulTimeout; import javax.ejb.Stateless; public class Question02 { // What is true about TimerService infertace? // // A - The TimerService interface is unavailable to stateless session beans. // // B - The TimerService interface is unavailable to steful session beans. // // C - The TimerService interface is unavailable to singleton session beans. // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // Choice B is correct: // // A stateless session bean or singleton session bean can be registered with the EJB Timer Service for time-based event notifications. // The container invokes the appropriate bean instance timeout callback method when a timer for the bean has expired. @Stateless public static class MyTimer01 { @Schedule(year = "*", month = "*", hour = "*", minute = "*", second = "*/10", persistent = false) // Timers are persistent by default. public void printTime() { System.out.println("MyTimer.printTime!"); } } @Singleton public static class MyTimer04 { @Schedule(year = "*", month = "*", hour = "*", minute = "*", second = "*/10", persistent = false) // Timers are persistent by default. public void printTime() { System.out.println("MyTimer.printTime!"); } } @Stateful // error public static class MyTimer02 { @Schedule(year = "*", month = "*", hour = "*", minute = "*", second = "*/10", persistent = false) // public void printTime() { System.out.println("MyTimer.printTime!"); } } @StatefulTimeout(unit = TimeUnit.MINUTES, value = 0) // error public static class MyTimer03 { @Schedule(year = "*", month = "*", hour = "*", minute = "*", second = "*/10", persistent = false) // Timers are persistent by default. public void printTime() { System.out.println("MyTimer.printTime!"); } } }
21.90566
138
0.577089
f41cb3b3032fd1a31aa7c738ef06120d43ae26cf
4,568
/******************************************************************************* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tudarmstadt.ukp.lexcompare.core.db; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import de.tudarmstadt.ukp.lexcompare.core.db.Table.FieldDefinition; import de.tudarmstadt.ukp.lexcompare.core.db.Table.FieldIndex; import de.tudarmstadt.ukp.lexcompare.core.util.configuration.IProperties; public class MySQLAdapter extends JDBCDatabaseAdapter { public MySQLAdapter(final IProperties properties) throws SQLException { super(properties); } public MySQLAdapter(final String hostName, final String dbName, final String userName, final String password) throws SQLException { super(hostName, dbName, userName, password); } @Override protected String makeConnectionString(final String hostName, final String dbName, final String userName, final String password) throws ClassNotFoundException, SQLException { Class.forName("org.gjt.mm.mysql.Driver"); return "jdbc:mysql://" + hostName + "/" + dbName + "?user=" + userName + "&password=" + password + "&characterEncoding=utf-8"; } private static final String CREATION_CHARSET = " DEFAULT CHARSET=utf8 COLLATE=utf8_bin"; @Override protected String makeCreateTableSQL(final Table table) { StringBuilder result = new StringBuilder(); result.append("CREATE TABLE ").append(table.getTableName()).append(" (") .append("id INT NOT NULL PRIMARY KEY AUTO_INCREMENT"); for (FieldDefinition field : table.getFields()) result.append(", ").append(fieldAsSQL(field)); result.append(")").append(CREATION_CHARSET); return result.toString(); } @Override public void dropTable(final Table table) throws SQLException { executeStatement("DROP TABLE IF EXISTS " + table.getTableName()); } @Override public boolean tableExists(final Table table) throws SQLException { try (PreparedStatement stmt = connection.prepareStatement( "SHOW TABLES LIKE ?")) { stmt.setString(1, table.getTableName()); try (ResultSet tblResSet = stmt.executeQuery()) { return tblResSet.next(); } } } @Override public boolean fieldExists(final Table table, final FieldDefinition field) throws SQLException { boolean result = false; try (PreparedStatement stmt = connection.prepareStatement( "SHOW COLUMNS FROM " + table.getTableName() + " WHERE field LIKE ?")) { stmt.setString(1, field.getFieldName()); try (ResultSet resSet = stmt.executeQuery()) { if (resSet.next()) result = true; } } return result; } @Override protected String fieldAsSQL(final FieldDefinition field) { StringBuilder result = new StringBuilder(field.getFieldName()).append(" "); Class<?> dataType = field.getDataType(); if (dataType.equals(String.class)) { if (field.hasParam("long")) result.append("LONGTEXT"); else { int length = field.getLength(); if (length > 0) result.append("VARCHAR(").append(length).append(")"); else result.append("TEXT"); } } else if (dataType.equals(boolean.class)) result.append("CHAR(1)"); else if (dataType.equals(int.class)) result.append("INT"); else if (dataType.equals(double.class)) result.append("DOUBLE"); else if (dataType.equals(Date.class)) result.append("DATETIME"); if (field.isNotNull()) result.append(" NOT NULL"); return result.toString(); } @Override public boolean indexExists(final Table table, final FieldIndex index) throws SQLException { try (PreparedStatement stmt = connection.prepareStatement( "SHOW INDEX FROM " + table.getTableName() + " WHERE key_name = ?")) { stmt.setString(1, index.makeIndexName(table.getTableName())); try (ResultSet tblResSet = stmt.executeQuery()) { return tblResSet.next(); } } } }
32.397163
97
0.696804
10e1f104696c08273f7649edb10dedf5a7e2e3b0
202
package cn.ism.fw.simba.jsr.validation.groups; import javax.validation.groups.Default; /** * 创建校验组 * @since 2017年9月25日 * @author Administrator */ public interface CreateGroup extends Default { }
15.538462
46
0.747525
42d53cee6bcb5926c7fc24e95c3b01346eb9d684
3,914
package com.calliemao.gasmeter.clients.mapsresponse; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @Generated("org.jsonschema2pojo") public class Step { @SerializedName("distance") @Expose private Distance_ distance; @SerializedName("duration") @Expose private Duration_ duration; @SerializedName("end_location") @Expose private EndLocation_ endLocation; @SerializedName("html_instructions") @Expose private String htmlInstructions; @SerializedName("polyline") @Expose private Polyline polyline; @SerializedName("start_location") @Expose private StartLocation_ startLocation; @SerializedName("steps") @Expose private List<Step_> steps = new ArrayList<Step_>(); @SerializedName("travel_mode") @Expose private String travelMode; @SerializedName("transit_details") @Expose private TransitDetails transitDetails; /** * * @return * The distance */ public Distance_ getDistance() { return distance; } /** * * @param distance * The distance */ public void setDistance(Distance_ distance) { this.distance = distance; } /** * * @return * The duration */ public Duration_ getDuration() { return duration; } /** * * @param duration * The duration */ public void setDuration(Duration_ duration) { this.duration = duration; } /** * * @return * The endLocation */ public EndLocation_ getEndLocation() { return endLocation; } /** * * @param endLocation * The end_location */ public void setEndLocation(EndLocation_ endLocation) { this.endLocation = endLocation; } /** * * @return * The htmlInstructions */ public String getHtmlInstructions() { return htmlInstructions; } /** * * @param htmlInstructions * The html_instructions */ public void setHtmlInstructions(String htmlInstructions) { this.htmlInstructions = htmlInstructions; } /** * * @return * The polyline */ public Polyline getPolyline() { return polyline; } /** * * @param polyline * The polyline */ public void setPolyline(Polyline polyline) { this.polyline = polyline; } /** * * @return * The startLocation */ public StartLocation_ getStartLocation() { return startLocation; } /** * * @param startLocation * The start_location */ public void setStartLocation(StartLocation_ startLocation) { this.startLocation = startLocation; } /** * * @return * The steps */ public List<Step_> getSteps() { return steps; } /** * * @param steps * The steps */ public void setSteps(List<Step_> steps) { this.steps = steps; } /** * * @return * The travelMode */ public String getTravelMode() { return travelMode; } /** * * @param travelMode * The travel_mode */ public void setTravelMode(String travelMode) { this.travelMode = travelMode; } /** * * @return * The transitDetails */ public TransitDetails getTransitDetails() { return transitDetails; } /** * * @param transitDetails * The transit_details */ public void setTransitDetails(TransitDetails transitDetails) { this.transitDetails = transitDetails; } }
19.186275
66
0.570772
2414d075bd268a193f5773b0abd72e29e5ee0f8e
157
package com.github.prbpedro.sortingalgorithms.algorithms.interfaces; public interface ISortAlgorithmExecutioner<T> { void sort(T[] unsortedArr); }
22.428571
68
0.77707
6c7b4d3569eeaf028c8d38c559ef5d80c533d80b
1,280
package com.github.east196.core.api; import cn.hutool.core.builder.EqualsBuilder; import cn.hutool.core.builder.HashCodeBuilder; public class DataTableResult<T> { private int draw; private long recordsTotal; private long recordsFiltered; private T data; public DataTableResult() { } public DataTableResult(int draw, long recordsTotal, int recordsFiltered, T data) { this.draw = draw; this.recordsTotal = recordsTotal; this.recordsFiltered = recordsFiltered; this.data = data; } public int getDraw() { return draw; } public void setDraw(int draw) { this.draw = draw; } public long getRecordsTotal() { return recordsTotal; } public void setRecordsTotal(long recordsTotal) { this.recordsTotal = recordsTotal; } public long getRecordsFiltered() { return recordsFiltered; } public void setRecordsFiltered(long recordsFiltered) { this.recordsFiltered = recordsFiltered; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object other) { return EqualsBuilder.reflectionEquals(this, other); } }
19.393939
84
0.7