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
9d69dd2efdde9350bd16db1dc1ee6df973a3fa86
1,138
package at.roteskreuz.covidapp.convert; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import org.apache.commons.lang3.StringUtils; /** * Converter class for converting list of String into String and the other way around * * @author Zoltán Puskai */ @Converter public class ListToStringConverter implements AttributeConverter<List<String>, String> { /** * Converts list of Strings to database column * @param list the list to be converted * @return value to be stored in database */ @Override public String convertToDatabaseColumn(List<String> list) { if (list == null) { return null; } return String.join(",", list); } /** * Splits the String into a list * @param joined The String to be split * @return a list from the database field value */ @Override public List<String> convertToEntityAttribute(String joined) { if (StringUtils.isBlank(joined)) { return Collections.EMPTY_LIST; } return new ArrayList<>(Arrays.asList(joined.split(","))); } }
25.288889
88
0.73638
cbd0960d42c161fa8cbd5031a8c056ec46c3e098
907
package pl.automatedplayground.myloader.example; /* Created by Adrian Skupień (automatedplayground@gmail.com) on 20.07.15. Copyright (c) 2015 Automated Playground under Apache 2.0 License */ import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import pl.automatedplayground.myloader.R; import pl.automatedplayground.statefragment.DataFragment; public class SimpleDataFragment extends DataFragment<SimpleDataModel> { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_example_data, null); TextView tv = (TextView) view.findViewById(R.id.textView); tv.setText(getData().data); return view; } }
33.592593
103
0.771775
6c47e975c4ba9955d5f1ec17bf4ff495474361f9
243
package no.ssb.useraccess.autocreate.model; public class Domain { private final String domain; public Domain(String domain) { this.domain = domain; } public String getDomain() { return this.domain; } }
15.1875
43
0.63786
c6920abe4f6d6794d04606fcc38751eab9ba639c
442
package com.css.memento.atricle; import java.util.Stack; /** * 备忘录管理类 * * 中国软件与技术服务股份有限公司-设计模式培训(Java版) * * CSS. WangWeidong */ public class ArticleMementoManager { private final Stack<ArticleMemento> ARTICLE_MEMENTO_STACK = new Stack<>(); public ArticleMemento getMemento() { return ARTICLE_MEMENTO_STACK.pop(); } public void addMemento(ArticleMemento articleMemento) { ARTICLE_MEMENTO_STACK.push(articleMemento); } }
17.68
75
0.748869
b6e5f0060203bc09b5018b7dde23ba3a8ee71889
1,723
package com.github.wxiaoqi.security.admin.biz; import com.github.wxiaoqi.security.admin.mapper.GrowthRecordMapper; import com.github.wxiaoqi.security.api.entity.Course; import com.github.wxiaoqi.security.api.entity.GrowthRecord; import com.github.wxiaoqi.security.api.entity.MLesson; import com.github.wxiaoqi.security.common.biz.BaseBiz; import com.github.wxiaoqi.security.common.util.DateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * <pre> * author : lpf * time : 2017/11/2116:44 * desc : 输入描述 * </pre> */ @Service public class GrowthRecordBiz extends BaseBiz<GrowthRecordMapper, GrowthRecord> { @Autowired private CourseBiz courseBiz; @Autowired private MLessonBiz mLessonBiz; public void createRecord(Long childId, MLesson mLesson,String lable, String redirectUrl) { GrowthRecord growthRecord = new GrowthRecord(); growthRecord.setChildId(childId); if(mLesson.getCourseId()!=null){ Course c = courseBiz.selectById(mLesson.getCourseId()); growthRecord.setLabel(c.getCourseLable()[0]); }else{ growthRecord.setLabel(lable); } growthRecord.setCourseId(mLesson.getCourseId()); growthRecord.setCourseName(mLesson.getCourseName()); growthRecord.setCreateTime(mLesson.getEndTime()); growthRecord.setMarkerTitle(mLesson.getCourseName()); growthRecord.setMlessonId(mLesson.getId()); growthRecord.setMlessonName(mLesson.getLessonName()); growthRecord.setRedirectUrl(redirectUrl); growthRecord.setPointType(0); growthRecord.setStudayHours((double) DateUtil.getDateSpace(mLesson.getStartTime(), mLesson.getEndTime()) / 3600); insert(growthRecord); } }
35.163265
115
0.766106
2be9f8e304a418ea840bc48e117725860cf41a17
2,925
/* * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.spring.cloud; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.assertj.core.api.BDDAssertions; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.RabbitMQContainer; import org.springframework.boot.SpringApplication; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.cloud.stream.messaging.Sink; import org.springframework.cloud.task.batch.listener.support.JobExecutionEvent; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import static org.assertj.core.api.Assertions.assertThat; public class BatchEventsApplicationTests { static { GenericContainer rabbitmq = new RabbitMQContainer("rabbitmq:3.7") .withExposedPorts(5672); rabbitmq.start(); final Integer mappedPort = rabbitmq.getMappedPort(5672); System.setProperty("spring.rabbitmq.test.port", mappedPort.toString()); rabbitPort = mappedPort.toString(); } // Count for two job execution events per task static CountDownLatch jobExecutionLatch = new CountDownLatch(2); private static String rabbitPort; @Test public void testExecution() throws Exception { SpringApplication .run(JobExecutionListenerBinding.class, "--spring.main.web-environment=false"); SpringApplication.run(BatchEventsApplication.class, "--server.port=0", "--spring.cloud.stream.bindings.output.producer.requiredGroups=testgroup", "--spring.jmx.default-domain=fakedomain", "--spring.main.webEnvironment=false", "--spring.rabbitmq.port=" + rabbitPort); assertThat(jobExecutionLatch.await(60, TimeUnit.SECONDS)) .as("The latch did not count down to zero before timeout").isTrue(); } @EnableBinding(Sink.class) @PropertySource("classpath:io/spring/task/listener/job-listener-sink-channel.properties") @Configuration public static class JobExecutionListenerBinding { @StreamListener(Sink.INPUT) public void receive(JobExecutionEvent execution) { BDDAssertions.then(execution.getJobInstance().getJobName()) .isEqualTo("job").as("Job name should be job"); jobExecutionLatch.countDown(); } } }
36.5625
90
0.783932
4b57e70552add31cca60a2019a98220cc0edcbfd
983
package com.performance.jvm.outofmemoryerror; import java.util.ArrayList; import java.util.List; /** * -verbose:gc -Xmn10M -Xms20M -Xmx20M -XX:+PrintGC * * [GC (Allocation Failure) 2208K->736K(19456K), 0.0181611 secs] [GC (Allocation Failure) 736K->712K(19456K), 0.0215309 secs] [Full GC (Allocation Failure) 712K->637K(19456K), 0.0166645 secs] [GC (Allocation Failure) 637K->637K(19456K), 0.0009471 secs] [Full GC (Allocation Failure) 637K->619K(19456K), 0.0348298 secs] Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at NotEnoughMemoryJavaHeapSpace.main(NotEnoughMemoryJavaHeapSpace.java:15) 对象大于新生代剩余内存的时候,将直接放入老年代,当老 年代剩余内存还是无法放下的时候,触发垃圾收集,收集后还是不能放下就会抛出内存溢出异常了 如果出现了内存溢出问题,这往往是程序本生需要的内存大于了我们给虚拟机配置的内存,这种情况下,我 们可以采用调大-Xmx来解决这种问题。 * */ public class NotEnoughMemoryJavaHeapSpace { public static void main(String[] args){ List<byte[]> buffer = new ArrayList<byte[]>(); buffer.add(new byte[10*1024*1024]); } }
30.71875
75
0.74059
e3902e540c5fc47871ddeef80487a05c24a59b46
1,629
/* 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.camunda.bpm.engine.impl.json; import org.camunda.bpm.engine.impl.QueryOperator; import org.camunda.bpm.engine.impl.TaskQueryVariableValue; import org.camunda.bpm.engine.impl.util.json.JSONObject; /** * @author Sebastian Menski */ public class JsonTaskQueryVariableValueConverter extends JsonObjectConverter<TaskQueryVariableValue> { public JSONObject toJsonObject(TaskQueryVariableValue variable) { JSONObject json = new JSONObject(); json.put("name", variable.getName()); json.put("value", variable.getValue()); json.put("operator", variable.getOperator()); return json; } public TaskQueryVariableValue toObject(JSONObject json) { String name = json.getString("name"); Object value = json.get("value"); QueryOperator operator = QueryOperator.valueOf(json.getString("operator")); boolean isTaskVariable = json.getBoolean("taskVariable"); boolean isProcessVariable = json.getBoolean("processVariable"); return new TaskQueryVariableValue(name, value, operator, isTaskVariable, isProcessVariable); } }
38.785714
102
0.754451
619e8e5205c637c207a2abae57d57e11cfc60656
3,722
/* * Copyright 2010 Last.fm * * 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 fm.last.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Unit test case for the StringUtils class. */ public class StringUtilsTest { @Test public void testTruncate() { String input = "abcdefghij"; assertEquals("abc", StringUtils.truncate(input, 3)); assertEquals(input, StringUtils.truncate(input, input.length())); assertEquals(input, StringUtils.truncate(input, input.length() + 10)); } @Test public void testTruncate_Null() { assertEquals(null, StringUtils.truncate(null, 3)); } @Test public void testMatchingStartSubstring() { assertEquals("abc", StringUtils.matchingStartSubstring("abc", "abc")); assertEquals("abc", StringUtils.matchingStartSubstring("abc", "abcdef")); assertEquals("abc", StringUtils.matchingStartSubstring("abcdef", "abc")); assertEquals("", StringUtils.matchingStartSubstring("abcdef", "xyz")); assertEquals("", StringUtils.matchingStartSubstring("abcdef", "xbcdef")); assertEquals("", StringUtils.matchingStartSubstring("abcdef", "xabc")); assertEquals("", StringUtils.matchingStartSubstring("", "")); assertEquals("", StringUtils.matchingStartSubstring("a", "")); assertEquals("", StringUtils.matchingStartSubstring("", "a")); // and what we really wanted this method for assertEquals( "/stats/label_reporting/xml/incoming/umg/", StringUtils .matchingStartSubstring( "/stats/label_reporting/xml/incoming/umg/", "/stats/label_reporting/xml/incoming/umg/00602517655362_1000000178594/UMG_metdat_LastFM_US_New_00602517655362_2008-04-23_15-36-01.xml")); } @Test public void testExtractStackTraceString_Throwable() { Throwable t = new Throwable("test"); String stack = StringUtils.extractStackTraceString(t); // don't check entire string, just check a bit of it assertTrue(stack.startsWith("java.lang.Throwable: test")); assertTrue(stack.contains("at fm.last.util.StringUtilsTest.testExtractStackTraceString")); } @Test public void testExtractStackTraceString_Exception() { Exception e = new Exception("test"); String stack = StringUtils.extractStackTraceString(e); // don't check entire string, just check a bit of it assertTrue(stack.startsWith("java.lang.Exception: test")); assertTrue(stack.contains("at fm.last.util.StringUtilsTest.testExtractStackTraceString")); } @Test public void testRemoveNonPrintableWhitespace() { assertEquals(null, StringUtils.removeNonPrintableWhitespace(null)); assertEquals("Herbie Hancock", StringUtils.removeNonPrintableWhitespace("Herbie Hancock")); assertEquals("Herbie Hancock", StringUtils.removeNonPrintableWhitespace("Herbie\t Hancock")); assertEquals("Herbie Hancock", StringUtils.removeNonPrintableWhitespace("Herbie\t Hancock\r\f")); assertEquals("Herbie Hancock", StringUtils.removeNonPrintableWhitespace("Herbie\t Hancock\r\n")); assertEquals("Herbie Hancock", StringUtils.removeNonPrintableWhitespace("Her\tbie\t\t Hancock\n\n")); } }
41.355556
153
0.729715
06b76e1fb8b6ba1617c4f51a9034bbb488f5e742
3,803
/* Copyright 2011 Bojan Savric Revised version of April 6, 2010. 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.jhlabs.map.proj; import java.awt.geom.Point2D; /** * The Natural Earth projection was designed by Tom Patterson, US National Park * Service, in 2007, using Flex Projector. The shape of the original projection * was defined at every 5 degrees and piece-wise cubic spline interpolation was * used to compute the complete graticule. * The code here uses polynomial functions instead of cubic splines and * is therefore much simpler to program. The polynomial approximation was * developed by Bojan Savric, in collaboration with Tom Patterson and Bernhard * Jenny, Institute of Cartography, ETH Zurich. It slightly deviates from * Patterson's original projection by adding additional curvature to meridians * where they meet the horizontal pole line. This improvement is by intention * and designed in collaboration with Tom Patterson. * * @author Bojan Savric */ public class NaturalEarthProjection extends PseudoCylindricalProjection { private static final double A0 = 0.8707; private static final double A1 = -0.131979; private static final double A2 = -0.013791; private static final double A3 = 0.003971; private static final double A4 = -0.001529; private static final double B0 = 1.007226; private static final double B1 = 0.015085; private static final double B2 = -0.044475; private static final double B3 = 0.028874; private static final double B4 = -0.005916; private static final double C0 = B0; private static final double C1 = 3 * B1; private static final double C2 = 7 * B2; private static final double C3 = 9 * B3; private static final double C4 = 11 * B4; private static final double EPS = 1e-11; private static final double MAX_Y = 0.8707 * 0.52 * Math.PI; @Override public Point2D.Double project(double lplam, double lpphi, Point2D.Double out) { double phi2 = lpphi * lpphi; double phi4 = phi2 * phi2; out.x = lplam * (A0 + phi2 * (A1 + phi2 * (A2 + phi4 * phi2 * (A3 + phi2 * A4)))); out.y = lpphi * (B0 + phi2 * (B1 + phi4 * (B2 + B3 * phi2 + B4 * phi4))); return out; } @Override public boolean hasInverse() { return true; } @Override public Point2D.Double projectInverse(double x, double y, Point2D.Double lp) { // make sure y is inside valid range if (y > MAX_Y) { y = MAX_Y; } else if (y < -MAX_Y) { y = -MAX_Y; } // latitude double yc = y; double tol; for (;;) { // Newton-Raphson double y2 = yc * yc; double y4 = y2 * y2; double f = (yc * (B0 + y2 * (B1 + y4 * (B2 + B3 * y2 + B4 * y4)))) - y; double fder = C0 + y2 * (C1 + y4 * (C2 + C3 * y2 + C4 * y4)); yc -= tol = f / fder; if (Math.abs(tol) < EPS) { break; } } lp.y = yc; // longitude double y2 = yc * yc; double phi = A0 + y2 * (A1 + y2 * (A2 + y2 * y2 * y2 * (A3 + y2 * A4))); lp.x = x / phi; return lp; } @Override public String toString() { return "Natural Earth"; } }
33.955357
90
0.63371
e39992d4bf74e133bae7cc50dbb4616480cc0e9f
1,398
package org.jeecg.modules.wxChatMsg.entity; import java.io.Serializable; import java.util.Date; import java.math.BigDecimal; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import org.jeecgframework.poi.excel.annotation.Excel; import org.jeecg.common.aspect.annotation.Dict; /** * @Description: 皖新学生管理 * @Author: jeecg-boot * @Date: 2019-10-23 * @Version: V1.0 */ @Data @TableName("wx_studyNew") public class WxChatDto implements Serializable { private static final long serialVersionUID = 1L; /**学生姓名*/ @Excel(name = "学生姓名", width = 15) private java.lang.String studyName; /**学籍号*/ @Excel(name = "学籍号", width = 15) private java.lang.String xuejiHao; /**登录名*/ @Excel(name = "登录名", width = 15) private java.lang.String userName; /**性别*/ @Excel(name = "性别", width = 15) @Dict(dicCode = "sex") private java.lang.Integer sex; @Excel(name = "用户表id", width = 15) private java.lang.String userId; @Excel(name = "班级id", width = 15) @Dict(dicCode = "id",dictTable = "wx_banji",dicText = "banji_name") private java.lang.String banjiId; @Excel(name = "所在年级", width = 15) /** * 是否有未读信息 */ private java.lang.String isRead; }
26.884615
68
0.723891
bfe0248b5c438c2a6df6bcd67372ea780fa7610a
107
package org.lkpnotice.infra.architecture; /** * Created by jpliu on 2020/5/22. */ public class Main { }
13.375
41
0.691589
f509e525578fd8eb64023996952dd04144566713
788
package com.krishagni.catissueplus.core.exporter.services; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import com.krishagni.catissueplus.core.common.events.RequestEvent; import com.krishagni.catissueplus.core.common.events.ResponseEvent; import com.krishagni.catissueplus.core.exporter.domain.ExportJob; import com.krishagni.catissueplus.core.exporter.events.ExportDetail; import com.krishagni.catissueplus.core.exporter.events.ExportJobDetail; public interface ExportService { ResponseEvent<ExportJobDetail> exportObjects(RequestEvent<ExportDetail> req); ResponseEvent<String> getExportFile(RequestEvent<Long> req); void registerObjectsGenerator(String type, Supplier<Function<ExportJob, List<? extends Object>>> genFactory); }
39.4
110
0.841371
0494c9198f39f8aa16ae576b9ce35630abaf2e00
1,056
package org.jenkinsci.plugins.workflow.flow; import hudson.ExtensionList; import hudson.ExtensionPoint; import hudson.model.Item; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; /** * Provides a way to indirectly register durability settings to apply to pipelines. */ public interface DurabilityHintProvider extends ExtensionPoint { int ordinal(); @CheckForNull FlowDurabilityHint suggestFor(@NonNull Item x); static @NonNull FlowDurabilityHint suggestedFor(@NonNull Item x) { int ordinal = Integer.MAX_VALUE; FlowDurabilityHint hint = GlobalDefaultFlowDurabilityLevel.getDefaultDurabilityHint(); for (DurabilityHintProvider p : ExtensionList.lookup(DurabilityHintProvider.class)) { FlowDurabilityHint h = p.suggestFor(x); if (h != null) { if (p.ordinal() < ordinal) { hint = h; ordinal = p.ordinal(); } } } return hint; } }
28.540541
94
0.661932
e3b4c00737dd2fd3d79d085e78205184f1abf24b
1,541
package algorithms; import java.util.ArrayList; /** * Determines which number is missing from an unsorted array of values 1-100. * Iterate through the array and compute the sum of all numbers. * Now, sum of natural numbers from 1 to N, can be expressed as N(N+1)/2. In your case N=100. * Subtract the sum of the array from N(N+1)/2, where N=100. * * Complexity: O(n) * * @author joeytawadrous */ public class UnsortedArray { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < 101; i++) // leave 100 out { if(i != 77) { list.add(i); } } getMissingNumber(list); getMissingNumber2(); } /** * Prints the missing number in a list of numbers. * @param list */ public static void getMissingNumber(ArrayList<Integer> list) { int sum = 0; for (int i = 0; i < list.size(); i++) { sum += list.get(i); } // the total sum of numbers between 1 and arr.length. int total = (list.size() + 1) * list.size() / 2; System.out.println("Missing number is: " + (total - sum)); } /** * Prints the missing number in an array of numbers. */ public static void getMissingNumber2() { int[] arr = {1,2,3,5}; int indexes = 5; int values = 0; for (int i = 0; i < arr.length; i++) { indexes += i + 1; values += arr[i]; } int result = indexes - values; System.out.println("Missing number is: " + result); } }
20.824324
93
0.580792
699f68d34fabc88aa5c468f0079bc5ccc7703b23
235
package ac.hs.se.model; public enum ToDoStatus { TODO("TODO"), DOING("DOING"), DONE("DONE"); private final String status; ToDoStatus(String status) { this.status = status; } public String getStatus() { return status; } }
14.6875
44
0.676596
bf9cf809f6192927f324e87cc4465980406a94ec
1,746
/** * Copyright 2017 FIX Protocol Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package io.fixprotocol.orchestra.dsl.antlr; /** * An Exception that occurs in the evaluation of a Score DSL expression * * @author Don Mendelson * */ public class ScoreException extends Exception { private static final long serialVersionUID = 6950517934100277304L; /** * */ public ScoreException() { } /** * @param message error text */ public ScoreException(String message) { super(message); } /** * @param cause nested exception */ public ScoreException(Throwable cause) { super(cause); } /** * @param message error text * @param cause nested exception */ public ScoreException(String message, Throwable cause) { super(message, cause); } /** * @param message error text * @param cause nested exception * @param enableSuppression whether or not suppression is enabled or disabled * @param writableStackTrace whether or not the stack trace should be writable */ public ScoreException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
26.059701
100
0.710767
417fb804c7bf0a6d23f3cc426148257dc76cb4f8
2,678
package com.qianmi.elasticsearch.index.analysis.tokenizer; import com.qianmi.elasticsearch.index.analysis.common.Position; import com.qianmi.elasticsearch.index.analysis.common.SubParseResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import java.io.IOException; import java.util.List; /** * @author hourui 2020/4/30 4:03 PM */ public class QianmiSubTokenizer extends Tokenizer { private static final Logger LOG = LogManager.getLogger(); private static final int IO_BUFFER_SIZE = 4096; private final List<Position> positions; private int sectionOffset = 0; private char[] charArray; private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class); public QianmiSubTokenizer(List<Position> positions) { LOG.debug("Init class QianmiSubTokenizer"); this.positions = positions; } @Override public boolean incrementToken() throws IOException { clearAttributes(); if (null == positions || positions.size() == 0 || sectionOffset >= positions.size()) { return false; } if (sectionOffset == 0) { char[] chars = new char[IO_BUFFER_SIZE]; StringBuilder sb = new StringBuilder(); while (true) { int size = input.read(chars); if (size == -1) { break; } char[] result = new char[size]; System.arraycopy(chars, 0, result, 0, size); sb.append(result); } charArray = sb.toString().toCharArray(); if (charArray.length == 0) { return false; } LOG.debug("Read input: {}", sb); } Position position = positions.get(sectionOffset); SubParseResult subParseResult = position.parse(charArray); char[] result = subParseResult.getChars(); LOG.debug("Sub tokenizer: {}, offset: {}, position: {}", new String(result), sectionOffset, position); termAtt.copyBuffer(result, 0, result.length); termAtt.setLength(result.length); offsetAtt.setOffset(sectionOffset, sectionOffset + 1); sectionOffset++; return true; } @Override public void reset() throws IOException { super.reset(); charArray = null; sectionOffset = 0; } }
31.505882
110
0.637043
589916da7ac4ce21c87c8ce90a32d982660ffe02
733
package org.baswell.sessioncookie; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * A {@link SessionCookieRequestChain} for {@link javax.servlet.Filter}. */ public class SessionCookieFilterRequestChain implements SessionCookieRequestChain { private final FilterChain filterChain; public SessionCookieFilterRequestChain(FilterChain filterChain) { this.filterChain = filterChain; } @Override public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { filterChain.doFilter(request, response); } }
27.148148
116
0.80764
18f928862cda272e9b7e83de87e3ca00c43a9111
1,008
package mvc.view.components.shapes; import java.awt.*; public class LabelShape implements Shape{ private int x, y; private Label label; public LabelShape(int x, int y, Label label) { this.x = x; this.y = y; this.label = label; } public void draw(Graphics g) { // Draw label g.setColor(label.getColor()); g.setFont(label.getFont()); g.drawString(label.getText(), x, y); } @Override public boolean containsPoint(Point point) { return false; } @Override public Shape getShapeWithPoint(Point point) { return this; } public int getLabelHeight(){ return label.getHeight(); } public int getLabelWidth(){ return label.getWidth(); } public void setX(int x){ this.x = x; } public void setY(int y){ this.y = y; } public Label getLabel(){ return label; } public int getX(){ return x; } }
16.8
50
0.555556
5699390871c50cd7a49f6eb8c66a6cac44ef9566
1,045
package ge.geometry; import ge.utils.GEBoundingBox; import ge.utils.GERegularBoundingBox; public class GELine extends GEGeometry { private static double[] getLinePoints(GEBoundingBox boundingBox){ double[] buffVertices = new double[4]; // [x, y] 4 times buffVertices[0] = boundingBox.getPoint1().x; buffVertices[1] = boundingBox.getPoint1().y; buffVertices[2] = boundingBox.getPoint2().x; buffVertices[3] = boundingBox.getPoint2().y; return buffVertices; } public GELine(GEBoundingBox boundingBox){ super(getLinePoints(boundingBox)); } public GELine(GERegularBoundingBox boundingBox){ super(getLinePoints(boundingBox)); } } //public class GELine extends GEGeometry { // // public GELine(int X1, int Y1, int X2, int Y2){ // super(new Line(X1,Y1,X2,Y2)); // } // // public GELine(GERegularBoundingBox boundingBox){ // super(new Line(-boundingBox.size/2,-boundingBox.size/2,boundingBox.size/2,boundingBox.size/2)); // } //}
26.125
105
0.667943
866f4fcd8f9f9ab9915f0778fac6b727b4ab23ec
3,633
package org.spleen.example; import org.spleen.Spleen; import org.spleen.config.SpleenConfigurator; import org.spleen.tool.SizeConverter; import org.spleen.type.CacheObject; import org.spleen.type.SimpleCacheObject; public class SpleenExample { public static void main(String[] args) { //define new spleen Spleen mainSpleen = new Spleen(); //create a simple namespace indexed under "simpleNamespace" key mainSpleen.createNamespace("simpleNamespace", configExample()); /* * create a multi-threaded namespace indexed under "multiThreadNamespace" key * * A multi-threaded namespace will create some subnamespace with associated * remover thread. * * This namespace type allow superior memory suppression. This is more * usable for very large instance storage, but need more time for access * and adding. */ mainSpleen.createNamespace(10, "multiThreadNamespace",configExample()); //Create cachable objects SimpleCacheObject integer12 = new SimpleCacheObject(new Integer(12)); SimpleCacheObject double24 = new SimpleCacheObject(new Double(24)); SimpleCacheObject integer05 = new SimpleCacheObject(new Integer(5)); SimpleCacheObject double12 = new SimpleCacheObject(new Double(12)); //register objects mainSpleen.put("simpleNamespace", "integer12", integer12); mainSpleen.put("simpleNamespace", "double24", double24); mainSpleen.put("multiThreadNamespace", "integer05", integer05); mainSpleen.put("multiThreadNamespace", "double12", double12); //get objects CacheObject integer12Rec = mainSpleen.get("simpleNamespace", "integer12"); CacheObject double24Rec = mainSpleen.get("simpleNamespace", "double24"); CacheObject integer05Rec = mainSpleen.get("multiThreadNamespace", "integer05"); CacheObject double12Rec = mainSpleen.get("multiThreadNamespace", "double12"); //Get stored objects System.out.println("integer12Rec : "+integer12Rec.getCacheObject()); System.out.println("double24Rec : "+double24Rec.getCacheObject()); System.out.println("integer05Rec : "+integer05Rec.getCacheObject()); System.out.println("double12Rec : "+double12Rec.getCacheObject()); //wait for remover thread completely clear the namespaces System.out.println("Start to wait elements deletion. (Configured to be removed after 10 seconds (+/- 500 for the scheduler))"); long start = System.currentTimeMillis(); while(!mainSpleen.get("simpleNamespace").isEmpty() && !mainSpleen.get("simpleNamespace").isEmpty()); System.out.println("Each elements deleted into "+((System.currentTimeMillis()-start) / (double)1000)+" seconds."); } public static SpleenConfigurator configExample(){ /* * Define base configuration. * * Spleen configurator set automatically undefined * parameters to the following : * - Remover schedule : 5 milliseconds * - Cache timeout : 1 second * - Maximum memory size : 1 megabit * - Maximum entry count : 100 instances */ SpleenConfigurator baseConfig = new SpleenConfigurator(); //Set up remover schedule to 500 milliseconds : baseConfig.setRemoverSheduleTime(500); //Set up timeout to 10 seconds : baseConfig.setCacheTimeout(10_000); //Set up memory size to 5 kilobit : baseConfig.setMaxSize(5120); //or with SizeConverter : baseConfig.setMaxSize(SizeConverter.convert(5, SizeConverter.K)); //Set up maximum entry count to 10 instances : baseConfig.setMaxCount(10); baseConfig = null; /* * Define the same configuration with constructor : */ baseConfig = new SpleenConfigurator(500, 10_000, 5120, 10); return baseConfig; } }
35.617647
129
0.737958
626e8642414da3d64e48e02c37737cf94b5be769
6,230
/* * LuceneField.java * * This source file is part of the FoundationDB open source project * * Copyright 2015-2021 Apple Inc. and the FoundationDB project 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 com.apple.foundationdb.record.lucene; import com.apple.foundationdb.record.RecordCoreArgumentException; import com.apple.foundationdb.record.logging.LogMessageKeys; import com.apple.foundationdb.record.metadata.MetaDataException; import com.apple.foundationdb.record.metadata.expressions.FieldKeyExpression; import com.apple.foundationdb.record.metadata.expressions.GroupingKeyExpression; import com.apple.foundationdb.record.metadata.expressions.KeyExpression; import com.apple.foundationdb.record.metadata.expressions.NestingKeyExpression; import com.apple.foundationdb.record.metadata.expressions.ThenKeyExpression; import com.google.common.collect.Lists; import org.apache.commons.lang3.tuple.ImmutablePair; import javax.annotation.Nullable; import java.util.List; import java.util.stream.Collectors; public interface LuceneKeyExpression extends KeyExpression { /** * Types allowed for lucene Indexing. StringKeyMap is not explicitly specifying the values because we expect the * child expressions to be lucene expressions and specify it from the below choices. */ enum FieldType { STRING, INT, LONG, INT_LIST, STRING_KEY_MAP } /** * For nested fields and possibly in the future more validation on fields + types and possibly field names. * Other possible things to check would be complexity and number of levels. * * @param expression the expression to validate * * @return if the entire expression is validated as lucene compatible */ static boolean validateLucene(KeyExpression expression) { if (expression instanceof LuceneKeyExpression) { return true; } if (expression instanceof GroupingKeyExpression) { return validateLucene(((GroupingKeyExpression)expression).getWholeKey()); } if (expression instanceof NestingKeyExpression) { boolean valid = true; for (KeyExpression keyExpression : ((NestingKeyExpression)expression).getChildren()) { valid = valid && validateLucene(keyExpression); } return valid; } throw new MetaDataException("Unsupported field type, please check allowed lucene field types under LuceneField class", LogMessageKeys.KEY_EXPRESSION, expression); } // Todo: limit depth of recursion static List<ImmutablePair<String, LuceneKeyExpression>> normalize(KeyExpression expression, @Nullable String givenPrefix) { if (expression instanceof LuceneFieldKeyExpression) { return Lists.newArrayList(new ImmutablePair<>(givenPrefix, (LuceneFieldKeyExpression)expression)); } else if (expression instanceof LuceneThenKeyExpression) { if (((LuceneThenKeyExpression)expression).fan()) { return Lists.newArrayList(new ImmutablePair<>(givenPrefix, (LuceneKeyExpression)expression)); } else { return ((LuceneThenKeyExpression)expression).getChildren().stream().flatMap( e -> normalize(e, givenPrefix).stream()).collect(Collectors.toList()); } } else if (expression instanceof GroupingKeyExpression) { return normalize(((GroupingKeyExpression)expression).getWholeKey(), givenPrefix); } else if (expression instanceof NestingKeyExpression) { String newPrefix = givenPrefix; if (((NestingKeyExpression)expression).getParent().getFanType() == FanType.None) { newPrefix = givenPrefix == null ? "" : givenPrefix.concat("_"); newPrefix = newPrefix.concat(((NestingKeyExpression)expression).getParent().getFieldName()); } return Lists.newArrayList(normalize(((NestingKeyExpression)expression).getChild(), newPrefix)); } else if (expression instanceof ThenKeyExpression) { return ((ThenKeyExpression)expression).getChildren().stream().flatMap(e -> normalize(e, givenPrefix).stream()).collect(Collectors.toList()); } throw new RecordCoreArgumentException("tried to normalize a non-lucene, non-grouping expression. These are currently unsupported.", LogMessageKeys.KEY_EXPRESSION, expression); } static List<String> listIndexFieldNames(KeyExpression expression) { List<ImmutablePair<String, LuceneKeyExpression>> pairs = normalize(expression, null); List<String> indexFields = Lists.newArrayList(); for (ImmutablePair<String, LuceneKeyExpression> pair : pairs) { if (pair.right instanceof LuceneFieldKeyExpression) { indexFields.add(pair.left != null ? pair.left.concat("_").concat(((LuceneFieldKeyExpression)pair.right).getFieldName()) : ((LuceneFieldKeyExpression)pair.right).getFieldName()); } else if (pair.right instanceof LuceneThenKeyExpression) { if (pair.left != null) { indexFields.add(pair.left); } KeyExpression primaryKey = ((LuceneThenKeyExpression)pair.right).getPrimaryKey(); if (primaryKey instanceof FieldKeyExpression) { indexFields.add(((FieldKeyExpression)primaryKey).getFieldName()); } } else { if (pair.left != null) { indexFields.add(pair.left); } } } return indexFields; } }
48.294574
183
0.683788
afba50296680b942f1d1edb82437f1c7049ee469
326
package de.digitalcollections.iiif.demo.config; import de.digitalcollections.iiif.hymir.config.SpringConfigSecurity; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import(SpringConfigSecurity.class) public class SpringConfigSecurityDemo {}
32.6
68
0.865031
e9772723861503896c3d1bf61ca0637e2e0c808b
22,565
package com.dream.common.utils.elasticsearch; import com.alibaba.fastjson.JSON; import com.dream.common.utils.reflect.ReflectUtils; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * @author Tan */ public class EsUtils{ private static Logger log = LoggerFactory.getLogger(ReflectUtils.class); /** * 获取客户端 * @return */ public static RestHighLevelClient getRestHighLevelClient() throws Exception { return EsClientPool.getClient(); } /** * 关闭客户端 */ public static void closeClient(RestHighLevelClient client) { EsClientPool.returnClient(client); } /** * 创建索引 分片和副本采用默认值 * @param esIndex * @return false索引创建失败,true索引创建成功 */ public static boolean createIndex(String esIndex) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); boolean result = false; if (!isIndexExist(esIndex)) { //1.创建索引请求 CreateIndexRequest request = new CreateIndexRequest(esIndex); try { //2.客户端执行请求,请求之后得到相应 CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); result = response.isAcknowledged(); if (result) { log.info(String.format("索引%s已创建", esIndex)); } else { log.info(String.format("索引%s创建失败", esIndex)); } } catch (Exception e) { log.error("ex",e); }finally { closeClient(client); } }else { log.info(String.format("索引%s已存在", esIndex)); } return result; } /** * 新建索引 * @param esIndex * @param shards 分片数 * @param replications 副本数 * @param fields 字段名->类型 */ public static void createIndex(String esIndex, int shards, int replications, Map<String, String> fields) throws Exception { if (!isIndexExist(esIndex)) { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); try { XContentBuilder builder = XContentFactory.jsonBuilder() .startObject() .field("properties") .startObject(); for (String s : fields.keySet()) { builder.field(s).startObject().field("index", "true").field("type", fields.get(s)).endObject(); } builder.endObject().endObject(); CreateIndexRequest request = new CreateIndexRequest(esIndex); request.settings(Settings.builder() .put("index.number_of_shards", shards) .put("index.number_of_replicas", replications) ).mapping(builder); CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); boolean acknowledged = createIndexResponse.isAcknowledged(); if (acknowledged) { log.info(String.format("索引%s创建成功", esIndex)); } else { log.info(String.format("索引%s创建失败", esIndex)); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } } else { log.info(String.format("索引%s已存在", esIndex)); } } /** * 删除索引 * @param esIndex * @return false索引删除失败,true索引删除成功 */ public static boolean deleteIndex(String esIndex) throws Exception { boolean result = false; //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); DeleteIndexRequest request = new DeleteIndexRequest(esIndex); try { AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT); result = deleteIndexResponse.isAcknowledged(); if (result) { log.info(String.format("索引%s已删除", esIndex)); } else { log.info(String.format("索引%s删除失败", esIndex)); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } return result; } /** * 判断索引是否存在 * @param esIndex * @return */ public static boolean isIndexExist(String esIndex) throws Exception { boolean result = false; //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); GetIndexRequest request = new GetIndexRequest(esIndex); try { result = client.indices().exists(request, RequestOptions.DEFAULT); if (result) { log.info(String.format("索引%s已存在", esIndex)); } else { log.info(String.format("索引%s不存在", esIndex)); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } return result; } /** * 插入一条数据 * @param o * @param esIndex */ public static void addDocument(Object o,String esIndex) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); IndexRequest request = new IndexRequest(esIndex); //不设置id,es会自动分配id //request.id("1"); //设置超时时间 //request.timeout("1s"); request.source(JSON.toJSONString(o), XContentType.JSON); try { IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); RestStatus status = indexResponse.status(); System.out.println(status); } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } } /** * 根据id获取数据,返回map(字段名,字段值) * @param esIndex * @param id * @return */ public static Map<String, Object> getDocumentById(String esIndex, String id) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); GetRequest request = new GetRequest(esIndex, id); Map<String, Object> source = null; try { GetResponse response = client.get(request, RequestOptions.DEFAULT); if (response.isExists()) { source = response.getSource(); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } return source; } /** * 更新文档 采用map传递数据方式 * @param esIndex * @param id * @param updateFields 更新的字段名->字段值 */ public static void updateDocumentById(String esIndex, String id, Map<String, Object> updateFields) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); UpdateRequest request = new UpdateRequest(esIndex, id).doc(updateFields); try { UpdateResponse response = client.update(request, RequestOptions.DEFAULT); if (response.status() == RestStatus.OK) { log.info(String.format("更新索引为%s,id为%s的文档成功", response.getIndex(), response.getId())); } else { log.info(String.format("更新索引为%s,id为%s的文档失败", response.getIndex(), response.getId())); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } } /** * 更新文档 采用对象传递数据方式 * @param esIndex * @param id * @param o 更新的值放入对象中 */ public static void updateDocumentById(String esIndex, String id, Object o) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); UpdateRequest request = new UpdateRequest(esIndex, id).doc(JSON.toJSONString(o), XContentType.JSON); try { UpdateResponse response = client.update(request, RequestOptions.DEFAULT); if (response.status() == RestStatus.OK) { log.info(String.format("更新索引为%s,id为%s的文档成功", response.getIndex(), response.getId())); } else { log.info(String.format("更新索引为%s,id为%s的文档失败", response.getIndex(), response.getId())); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } } /** * 删除指定id的文档 * @param esIndex * @param id */ public static boolean deleteDocumentById(String esIndex, String id) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); boolean result = false; DeleteRequest request = new DeleteRequest(esIndex, id); try { DeleteResponse response = client.delete(request, RequestOptions.DEFAULT); if (response.getResult() == DocWriteResponse.Result.DELETED) { result = true; log.info(String.format("id为%s的文档删除成功", id)); } else { log.info(String.format("id为%s的文档删除失败", id)); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } return result; } /** * 批量插入 * @param esIndex * @param datalist 数据集,数据格式为map<字段名,字段值> */ public static boolean bulkLoadMap(String esIndex, List<Map<String, Object>> datalist) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); boolean result = false; BulkRequest bulkRequest = new BulkRequest(); for (Map<String, Object> data : datalist) { Object id = data.get("id"); //如果数据包含id字段,使用数据id作为文档id if (id != null) { data.remove("id"); bulkRequest.add(new IndexRequest(esIndex).id(id.toString()).source(data)); } else {//让es自动生成id bulkRequest.add(new IndexRequest(esIndex).source(data)); } } try { BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT); System.out.println(response.hasFailures()); if (!response.hasFailures()) { result = true; log.info(String.format("索引%s批量插入成功,共插入%d条", esIndex, datalist.size())); } else { log.info(String.format("索引%s批量插入失败", esIndex)); } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } return result; } /** * 批量插入 * @param esIndex * @param list 直接插入对象集合 * @return */ public static boolean bulkLoadObject(String esIndex,List<Object> list) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); boolean result = false; BulkRequest bulkRequest = new BulkRequest(); //等待时间 //bulkRequest.timeout("10s"); try { for(int i=0;i<list.size();i++){ //如果数据中不包含id,自己生成id,当然如果自己不给id的话,es会自动生成id if (!list.contains("id")) { bulkRequest.add(new IndexRequest(esIndex).id(""+(i+1)).source(JSON.toJSONString(list.get(i)),XContentType.JSON)); } else {//让es自动生成id bulkRequest.add(new IndexRequest(esIndex).source(JSON.toJSONString(list.get(i)),XContentType.JSON)); } } BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT); if(!responses.hasFailures()){ result = true; } } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } return result; } /** * 全文检索 * @param query * @return */ public static Map<String,Object> search(SearchRequestQuery query) throws Exception { //获取客户端 RestHighLevelClient client = getRestHighLevelClient(); Map<String,Object> result = new HashMap<>(); List<Map<String,Object>> list = new ArrayList<>(); // 1、创建查询索引 SearchRequest searchRequest = new SearchRequest(query.getEsIndex()); // 2、条件查询 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //3.构建分页 int pageNo = 1,pageSize =10; if(query.getPageNo() != null){ pageNo = query.getPageNo(); } if(query.getPageSize() != null){ pageSize = query.getPageSize(); } //3.1 es默认从第0页开始 sourceBuilder.from((pageNo - 1) * pageSize); sourceBuilder.size(pageSize); //4.构建基础查询(包含基础查询和过滤条件)【过滤关系,key为(and或者or或者not),value为过滤字段和值】 QueryBuilder queryBuilder =buildBasicQueryWithFilter(query); sourceBuilder.query(queryBuilder); //4.2 设置最长等待时间1分钟 sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); // 5、高亮设置(替换返回结果文本中目标值的文本内容) HighlightBuilder highlightBuilder = new HighlightBuilder(); for (int i = 0; i < query.getKeywordFields().length; i++) { highlightBuilder.field(query.getKeywordFields()[i]); } //5.1允许同一个检索词多次高亮,false则表示,同意字段中同一个检索词第一个位置的高亮,其他不高亮 highlightBuilder.requireFieldMatch(true); highlightBuilder.preTags("<span style='color:red'>"); highlightBuilder.postTags("</span>"); sourceBuilder.highlighter(highlightBuilder); //6.构建排序 String sortBy = query.getSortBy(); Boolean desc = query.getIsDesc(); if (StringUtils.isNotBlank(sortBy)) { sourceBuilder.sort(new FieldSortBuilder(sortBy).order(desc ? SortOrder.DESC : SortOrder.ASC)); } //7.聚合(分组) Map<String, String> aggs = query.getAggMap(); if(aggs != null){ for (Map.Entry<String, String> entry : aggs.entrySet()) { //聚合名称(分组) String aggName = entry.getKey(); //聚合字段 String aggFiled = entry.getValue(); if(aggName != null || aggFiled != null) { sourceBuilder.aggregation(AggregationBuilders.terms(aggName).field(aggFiled+".keyword")); } } } //8、通过sourceFilter设置返回的结果字段,第一个参数是现实的字段,第二各个参数是不显示的字段,默认设置为null sourceBuilder.fetchSource(query.getSourceFilter(),null); //9、执行搜索 searchRequest.source(sourceBuilder); try { SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); for (SearchHit doc : searchResponse.getHits().getHits()) { // 解析高亮字段 Map<String, HighlightField> highlightFields = doc.getHighlightFields(); for (int i = 0; i < query.getKeywordFields().length; i++) { HighlightField fieldTitle = highlightFields.get(query.getKeywordFields()[i]); // 获取原来的结果集 Map<String, Object> sourceAsMap = doc.getSourceAsMap(); if (fieldTitle != null) { // 获取内容中匹配的片段 Text[] fragments = fieldTitle.fragments(); // 设置当前的目标字段为空 String new_fieldTitle = ""; for (Text res : fragments) { new_fieldTitle += res; } // 将原来的结果替换为新结果 sourceAsMap.put(query.getKeywordFields()[i], new_fieldTitle); } list.add(sourceAsMap); } } // List 数组去重, 多字段查询高亮解析的时候存在数组重复的情况(优化方法未知!) list = list.stream().distinct().collect(Collectors.toList()); int total = (int) searchResponse.getHits().getTotalHits().value; result.put("data",list); result.put("total",total); result.put("totalPage",total== 0 ? 0: (total%pageSize == 0 ? total / pageSize : (total / pageSize) + 1)); result.put("pageSize",pageSize); result.put("pageNo",pageNo); //聚和结果处理 Aggregations aggregations = searchResponse.getAggregations(); List<Object> aggData = new ArrayList<>(); if(aggregations != null){ aggData = getAggData(aggregations,query); } result.put("aggData",aggData); } catch (IOException e) { log.error("ex",e); }finally { closeClient(client); } return result; } /** * 聚合数据处理(分组) * @param aggregations * @param query * @return */ private static List<Object> getAggData( Aggregations aggregations ,SearchRequestQuery query) { List<Object> result = new ArrayList<>(); for (Map.Entry<String, String> entry : query.getAggMap().entrySet()) { LinkedHashMap<String,Object> map = new LinkedHashMap<>(); //聚合名称(分组) String aggName = entry.getKey(); //聚合字段 String aggFiled = entry.getValue(); if(aggName != null) { LinkedHashMap<String,Object> groupItem=new LinkedHashMap<>(); Terms aggregation = aggregations.get(aggName); for (Terms.Bucket bucket : aggregation.getBuckets()) { map.put(bucket.getKey().toString(),bucket.getDocCount()); } groupItem.put("aggregationName",aggName); groupItem.put("aggregationField",aggFiled); groupItem.put("aggregationData",map); result.add(groupItem); } } return result; } private static QueryBuilder buildBasicQueryWithFilter( SearchRequestQuery query ) { String flag = ""; BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery(); //过滤条件(and,or,not关系) Map<String, Object> filter = query.getFilter(); if(filter != null) { for (Map.Entry<String, Object> entry : filter.entrySet()) { String key = entry.getKey(); flag = key; Map<String, String> value = (Map<String, String>) entry.getValue(); for (Map.Entry<String, String> map : value.entrySet()) { String filterKey = map.getKey(); String filterValue = map.getValue(); if(key == "and") { queryBuilder.filter(QueryBuilders.termQuery(filterKey, filterValue)); } if(key == "or") { shouldQuery.should(QueryBuilders.termQuery(filterKey, filterValue)); } if(key == "not") { queryBuilder.mustNot(QueryBuilders.termQuery(filterKey, filterValue)); } } } } //过滤日期期间的值,比如2019-07-01到2019-07-17 if(StringUtils.isNotBlank(query.getDateField()) || StringUtils.isNotBlank(query.getStartDate()) || StringUtils.isNotBlank(query.getEndDate())) { queryBuilder.must(QueryBuilders.rangeQuery(query.getDateField()).from(query.getStartDate()).to(query.getEndDate())); } //如果输入的查询条件为空,则查询所有数据 if(query.getKeyword() == null || "".equals(query.getKeyword())) { queryBuilder.must(QueryBuilders.matchAllQuery()); return queryBuilder; } if("or".equals(flag) ) { //配置中文分词器并指定并分词的搜索方式operator queryBuilder.must(QueryBuilders.multiMatchQuery(query.getKeyword(), query.getKeywordFields())) //解决should和must共用不生效问题 .must(shouldQuery); }else { //多字段查询,字段直接是or的关系 queryBuilder.must(QueryBuilders.multiMatchQuery(query.getKeyword(),query.getKeywordFields())); /*queryBuilder.must(QueryBuilders.multiMatchQuery(query.getKeyword(),query.getKeywordFields()) .analyzer("ik_smart").operator(Operator.OR));*/ } return queryBuilder; } }
38.638699
152
0.588123
830611fe8a352ecbda3de96533489ef19dbbf75c
1,861
package ahc; import java.io.File; import java.io.InputStream; import com.ning.http.client.Realm; import com.ning.http.client.RequestBuilder; import com.ning.http.client.PerRequestConfig; import com.ning.http.client.ProxyServer; import com.ning.http.client.Cookie; import com.ning.http.client.generators.InputStreamBodyGenerator; public class RequestBuilderWrapper { private RequestBuilder rb; public RequestBuilderWrapper(RequestBuilder rb) { this.rb = rb; } public RequestBuilderWrapper addHeader(String k, String v) { rb.addHeader(k, v); return this;} public RequestBuilderWrapper setHeader(String k, String v) { rb.setHeader(k, v); return this;} public RequestBuilderWrapper addParameter(String k, String v) { rb.addParameter(k, v); return this;} public RequestBuilderWrapper addQueryParameter(String k, String v) { rb.addQueryParameter(k,v); return this;} public RequestBuilderWrapper setBody(byte[] data) { rb.setBody(data); return this;} public RequestBuilderWrapper setBody(InputStream stream) { rb.setBody(new InputStreamBodyGenerator(stream)); return this;} public RequestBuilderWrapper setBody(File f) { rb.setBody(f); return this;} public RequestBuilderWrapper setProxyServer(ProxyServer proxy) { rb.setProxyServer(proxy); return this;} public RequestBuilderWrapper addCookie(Cookie cookie) { rb.addCookie(cookie); return this;} public RequestBuilderWrapper setRealm(Realm realm) { rb.setRealm(realm); return this;} public RequestBuilderWrapper setPerRequestConfig(PerRequestConfig perRequestConfig) { rb.setPerRequestConfig(perRequestConfig); return this;} public RequestBuilder getRequestBuilder() { return rb; }}
37.979592
89
0.710908
679df2393d10c7ac92dbf3cc76f50952bd357a20
67
package compiler.generator; public abstract class Generator { }
9.571429
33
0.776119
0a84057a71fa90a113a5d594f50ddcf388293f4b
469
package org.continuity.idpa.application.config; import static org.assertj.core.api.Assertions.assertThat; import org.continuity.api.amqp.AmqpApi; import org.junit.Test; public class QueueDeclarationTest { @Test public void test() { assertThat(RabbitMqConfig.WORKLOAD_MODEL_CREATED_QUEUE_NAME).as("The defined queue name sould be equal to the derived one.") .isEqualTo(AmqpApi.WorkloadModel.EVENT_CREATED.deriveQueueName(RabbitMqConfig.SERVICE_NAME)); } }
27.588235
126
0.80597
d21ab5e122cad8cd6c6cc032afff98e54cac28c0
756
package ninja.leaping.configurate.objectmapping.serialize; import com.google.common.reflect.TypeToken; import net.X7; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers$1; class TypeSerializers$StringSerializer implements TypeSerializer { private TypeSerializers$StringSerializer() { } public String deserialize(TypeToken var1, ConfigurationNode var2) throws X7 { return var2.getString(); } public void serialize(TypeToken var1, String var2, ConfigurationNode var3) { var3.setValue(var2); } TypeSerializers$StringSerializer(TypeSerializers$1 var1) { this(); } }
30.24
80
0.785714
299aa3bd59f2ea2dff5cfae2ea98411164595f17
5,923
/* * 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.uima.ruta.explain.element; import java.util.HashMap; import java.util.Map; import org.apache.uima.caseditor.editor.AnnotationEditor; import org.apache.uima.caseditor.editor.ICasDocument; import org.apache.uima.ruta.addons.RutaAddonsPlugin; import org.apache.uima.ruta.explain.ExplainConstants; import org.apache.uima.ruta.explain.failed.FailedView; import org.apache.uima.ruta.explain.matched.MatchedView; import org.apache.uima.ruta.explain.tree.RuleElementRootNode; import org.apache.uima.ruta.explain.tree.RuleMatchNode; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.part.Page; public class ElementViewPage extends Page implements ISelectionListener { private TreeViewer treeView; private Map<String, Image> images; private AnnotationEditor editor; private ICasDocument document; public ElementViewPage(AnnotationEditor editor) { super(); this.editor = editor; this.document = editor.getDocument(); } @Override public void dispose() { super.dispose(); getSite().getPage().removeSelectionListener(this); if (images != null) { for (Image each : images.values()) { each.dispose(); } } } private void initImages() { images = new HashMap<String, Image>(); ImageDescriptor desc; Image image; String name; desc = RutaAddonsPlugin.getImageDescriptor("/icons/chart_organisation_add.png"); image = desc.createImage(); name = ExplainConstants.RULE_ELEMENT_MATCHES_TYPE + "true"; images.put(name, image); desc = RutaAddonsPlugin.getImageDescriptor("/icons/chart_organisation_delete.png"); image = desc.createImage(); name = ExplainConstants.RULE_ELEMENT_MATCHES_TYPE + "false"; images.put(name, image); desc = RutaAddonsPlugin.getImageDescriptor("/icons/chart_organisation_delete.png"); image = desc.createImage(); name = "element"; images.put(name, image); desc = RutaAddonsPlugin.getImageDescriptor("/icons/font_add.png"); image = desc.createImage(); name = ExplainConstants.RULE_ELEMENT_MATCH_TYPE + "true"; images.put(name, image); desc = RutaAddonsPlugin.getImageDescriptor("/icons/font_delete.png"); image = desc.createImage(); name = ExplainConstants.RULE_ELEMENT_MATCH_TYPE + "false"; images.put(name, image); desc = RutaAddonsPlugin.getImageDescriptor("/icons/accept.png"); image = desc.createImage(); name = ExplainConstants.EVAL_CONDITION_TYPE + "true"; images.put(name, image); desc = RutaAddonsPlugin.getImageDescriptor("/icons/cancel.png"); image = desc.createImage(); name = ExplainConstants.EVAL_CONDITION_TYPE + "false"; images.put(name, image); } public Image getImage(String name) { if (images == null) { initImages(); } return images.get(name); } @Override public void createControl(Composite parent) { // treeView = new CheckboxTreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL // | SWT.V_SCROLL); treeView = new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL); treeView.setContentProvider(new ElementTreeContentProvider()); treeView.setLabelProvider(new ElementTreeLabelProvider(this)); treeView.setInput(null); // treeView.addCheckStateListener(getCurrentCEVData()); getSite().setSelectionProvider(treeView); getSite().getPage().addSelectionListener(this); } @Override public Control getControl() { return treeView.getControl(); } @Override public void setFocus() { treeView.getControl().setFocus(); } public void inputChange(Object newInput) { if (treeView == null) { return; } Object oldInput = treeView.getInput(); if ((oldInput == null && newInput == null) || (oldInput != null && oldInput.equals(newInput))) return; if (newInput != null && newInput instanceof RuleElementRootNode) { treeView.setInput(newInput); treeView.expandAll(); treeView.refresh(); } else { treeView.setInput(null); } } public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (selection instanceof TreeSelection && (part instanceof MatchedView || part instanceof FailedView)) { TreeSelection ts = (TreeSelection) selection; Object firstElement = ts.getFirstElement(); if (firstElement instanceof RuleMatchNode) { RuleMatchNode match = (RuleMatchNode) firstElement; if (match.hasChildren()) { inputChange(match.getChildren().get(0)); } } } } }
33.089385
99
0.696775
62717e5b5125224c9f2de63d45fea5b6cb261676
1,515
package universalelectricity.api.energy; import net.minecraftforge.common.ForgeDirection; import universalelectricity.api.net.IConnectable; /** * Applied to all TileEntities that can interact with energy. * * @author Calclavia, Inspired by Thermal Expansion */ public interface IEnergyInterface extends IConnectable { /** * Adds energy to a block. Returns the quantity of energy that was accepted. This should always * return 0 if the block cannot be externally charged. * * @param from Orientation the energy is sent in from. * @param receive Maximum amount of energy (joules) to be sent into the block. * @param doReceive If false, the charge will only be simulated. * @return Amount of energy that was accepted by the block. */ public long onReceiveEnergy(ForgeDirection from, long receive, boolean doReceive); /** * Removes energy from a block. Returns the quantity of energy that was extracted. This should * always return 0 if the block cannot be externally discharged. * * @param from Orientation the energy is requested from. This direction MAY be passed as * "Unknown" if it is wrapped from another energy system that has no clear way to find * direction. (e.g BuildCraft 4) * @param energy Maximum amount of energy to be sent into the block. * @param doExtract If false, the charge will only be simulated. * @return Amount of energy that was given out by the block. */ public long onExtractEnergy(ForgeDirection from, long extract, boolean doExtract); }
39.868421
96
0.755116
2180fff3e27788af67672a09c23f924e15d14a6a
807
package com.suheng.structure.net.request.normal; import android.util.Log; import com.suheng.structure.net.request.basic.OkHttpTask; import org.jetbrains.annotations.NotNull; import okhttp3.ResponseBody; public abstract class StringTask<T> extends OkHttpTask<T> { protected static final String JSON = "{" + "\"code\":0" + ",\"msg\":密码错误" + ",data:{" + "\"member_id\":17" + ",\"age\":18" + ",\"email_address\":\"Wbj@qq.com\"" + "}" + "}"; protected abstract T parseResult(String result); @Override protected void parseResponseBody(@NotNull ResponseBody responseBody) throws Exception { String result = responseBody.string(); //result = JSON; Log.d(getLogTag(), "string result: " + result); setFinishCallback(this.parseResult(result)); } }
33.625
99
0.664188
ea05453368b22ccaa59bec1c038a8c1c101fdebf
1,110
/* * Copyright (C) 2016 PGS Software SA * Copyright (C) 2007 The Guava Authors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * */ package com.pgssoft.gimbus; import android.support.annotation.NonNull; /** * Wraps an event that was posted, but which had no subscribers and thus could not be delivered. * <p/> * <p>Registering a DeadEvent subscriber is useful for debugging or logging, as it can detect * misconfigurations in a system's event distribution. * * @author Lukasz Plominski (Android EventBus code) * @author Cliff Biffle (Guava inherited code) */ public class DeadEvent { @NonNull public final EventBus eventBus; @NonNull public final Object event; /** * Creates a new DeadEvent. * * @param eventBus the event bus broadcasting the original event. * @param event the event that could not be delivered. */ /*package*/ DeadEvent(@NonNull EventBus eventBus, @NonNull Object event) { this.eventBus = eventBus; this.event = event; } }
25.813953
96
0.69009
593a227a6ad23c7d447a51f571baf6e880884a64
5,372
/* * Copyright (c) 2010-2020. Axon Framework * * 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.axonframework.axonserver.connector.heartbeat; import org.axonframework.axonserver.connector.AxonServerConnectionManager; import org.axonframework.axonserver.connector.heartbeat.connection.checker.HeartbeatConnectionChecker; import org.axonframework.axonserver.connector.util.Scheduler; import org.axonframework.lifecycle.Phase; import org.axonframework.lifecycle.ShutdownHandler; import org.axonframework.lifecycle.StartHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Verifies if the connection is still alive, and react if it is not. * * @author Sara Pellegrini * @since 4.2.1 */ public class HeartbeatMonitor { private static final long DEFAULT_INITIAL_DELAY = 10_000; private static final long DEFAULT_DELAY = 1_000; private final Scheduler scheduler; private static final Logger logger = LoggerFactory.getLogger(HeartbeatMonitor.class); private final Runnable onInvalidConnection; private final ConnectionSanityChecker connectionSanityCheck; private final long initialDelay; private final long delay; /** * Constructs an instance of {@link HeartbeatMonitor} that forces a disconnection * when the AxonServer connection is no longer alive. * * @param connectionManager connectionManager to AxonServer * @param context the (Bounded) Context for which the heartbeat activity is monitored */ public HeartbeatMonitor(AxonServerConnectionManager connectionManager, String context) { this(() -> connectionManager.disconnectExceptionally(context, new RuntimeException("Inactivity timeout.")), new HeartbeatConnectionChecker(connectionManager, context), new DefaultScheduler(), DEFAULT_INITIAL_DELAY, DEFAULT_DELAY); } /** * Primary constructor of {@link HeartbeatMonitor}. * * @param onInvalidConnection callback to be call when the connection is no longer alive * @param connectionSanityCheck sanity check which allows to verify if the connection is alive * @param scheduler the {@link Scheduler} to use for scheduling the task * @param initialDelay the initial delay, in milliseconds * @param delay the scheduling period, in milliseconds */ public HeartbeatMonitor(Runnable onInvalidConnection, ConnectionSanityChecker connectionSanityCheck, Scheduler scheduler, long initialDelay, long delay) { this.onInvalidConnection = onInvalidConnection; this.connectionSanityCheck = connectionSanityCheck; this.scheduler = scheduler; this.initialDelay = initialDelay; this.delay = delay; } /** * Verify if the connection with AxonServer is still alive. * If it is not, invoke a callback in order to react to the disconnection. */ private void run() { try { boolean valid = connectionSanityCheck.isValid(); if (!valid) { onInvalidConnection.run(); } } catch (Exception e) { logger.warn("Impossible to correctly monitor the Axon Server connection state.", e); } } /** * Schedule a task that verifies that the connection is still alive and, if it is not, invoke a callback in order to * react to the disconnection. Started in phase {@link Phase#INSTRUCTION_COMPONENTS}, as this means all inbound and * outbound connections have been started. */ @StartHandler(phase = Phase.INSTRUCTION_COMPONENTS) public void start() { this.scheduler.scheduleWithFixedDelay(this::run, initialDelay, delay, TimeUnit.MILLISECONDS); } /** * Stops the scheduled task and shutdown the monitor, that cannot be restarted again. Shuts down in phase {@link * Phase#INSTRUCTION_COMPONENTS}. */ @ShutdownHandler(phase = Phase.INSTRUCTION_COMPONENTS) public void shutdown() { this.scheduler.shutdownNow(); } private static final class DefaultScheduler implements Scheduler { private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); @Override public ScheduledTask scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { ScheduledFuture<?> scheduled = executor.scheduleWithFixedDelay(command, initialDelay, delay, unit); return scheduled::cancel; } @Override public void shutdownNow() { executor.shutdown(); } } }
38.927536
120
0.711467
5d1dd728d6c175291baea2f111aa4a21aef868fb
502
public class EndDelCommand extends ModifierCommand{ private Document document; private String str; private int n; public EndDelCommand(Document document,int n){ this.n = n; this.document = document; this.str = null; } @Override public void excute() { str = document.endDel(n); } @Override public void unexcute() { document.endAdd(str); } @Override public String toString() { return "D "+n; } }
18.592593
51
0.583665
4cbe295cd26ab7a42e2773c2dd74fe5ac1c77653
3,426
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class HtmlDemo extends JPanel { JLabel theLabel; JTextArea htmlTextArea; public HtmlDemo() { String initialText = "<html>\n" + "Color and font test:\n" + "<ul>\n" + "<li><font color=red>red</font>\n" + "<li><font color=blue>blue</font>\n" + "<li><font color=green>green</font>\n" + "<li><font size=-2>small</font>\n" + "<li><font size=+2>large</font>\n" + "<li><i>italic</i>\n" + "<li><b>bold</b>\n" + "</ul>\n"; htmlTextArea = new JTextArea(10, 20); htmlTextArea.setText(initialText); JScrollPane scrollPane = new JScrollPane(htmlTextArea); JButton changeTheLabel = new JButton("Change the label"); changeTheLabel.setMnemonic(KeyEvent.VK_C); changeTheLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { theLabel.setText(htmlTextArea.getText()); } catch (Throwable exc) { JOptionPane.showMessageDialog( HtmlDemo.this, "The HTML you specified was invalid."); } } }); changeTheLabel.setAlignmentX(Component.CENTER_ALIGNMENT); theLabel = new JLabel(initialText) { public Dimension getPreferredSize() { return new Dimension(200, 200); } public Dimension getMinimumSize() { return new Dimension(200, 200); } public Dimension getMaximumSize() { return new Dimension(200, 200); } }; theLabel.setVerticalAlignment(SwingConstants.CENTER); theLabel.setHorizontalAlignment(SwingConstants.CENTER); JPanel leftPanel = new JPanel(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); leftPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder( "Edit the HTML, then click the button"), BorderFactory.createEmptyBorder(10,10,10,10))); leftPanel.add(scrollPane); leftPanel.add(Box.createRigidArea(new Dimension(0,10))); leftPanel.add(changeTheLabel); JPanel rightPanel = new JPanel(); rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS)); rightPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("A label with HTML"), BorderFactory.createEmptyBorder(10,10,10,10))); rightPanel.add(theLabel); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); add(leftPanel); add(Box.createRigidArea(new Dimension(10,0))); add(rightPanel); } public static void main(String args[]) { JFrame f = new JFrame("HtmlDemo"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); f.getContentPane().add(new HtmlDemo()); f.pack(); f.setVisible(true); } }
36.446809
78
0.563047
b698d973dc48944588eec83058ca3b9d1af57dcd
738
import com.github.wxiaoqi.security.movie.MovieBootstrap; import com.github.wxiaoqi.security.movie.entity.User; import com.github.wxiaoqi.security.movie.service.IUserService; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * @description * @author: lxr * @create: 2019-06-14 16:14 **/ @RunWith(SpringRunner.class) @SpringBootTest(classes = MovieBootstrap.class) public class Test { @Autowired IUserService iUserService; @org.junit.Test public void test(){ User user = new User(); iUserService.verifyUser(user); } }
21.705882
62
0.749322
56ce6cc884d9f8f7336c5334af23ddb2cee0a60e
5,185
/* * The MIT License (MIT) * Copyright (c) 2019 Hyperwallet Systems Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.hyperwallet.android.ui.common.util; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Common HW-SDK UI Date Utility class, that will assist on safe presentation of date whatever the mobile device setting * is set Locale, Timezone and etc... that dictates how that dates are being presented * * Moreover all date string to {@link Date} object conversion is automatically converted from * GMT date string from API to locale Date set by the phone */ public final class DateUtils { private static final String DATE_FORMAT = "yyyy-MM-dd"; private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; private static final String DATE_TIME_FORMAT_MILLISECONDS = "yyyy-MM-dd'T'HH:mm:ss.SSS"; private static final TimeZone API_TIMEZONE = TimeZone.getTimeZone("GMT"); private DateUtils() { } /** * Creates a string date format: <code>yyyy-MM-dd</code> * * @param date Date object * @return string date in <code>yyyy-MM-dd</code> format */ public static String toDateFormat(@NonNull final Date date) { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault()); dateFormat.setTimeZone(TimeZone.getDefault()); return dateFormat.format(date); } /** * Creates a string date in specified format * * @param date Date object * @param format specify desired format of date * @return formatted date string based on format specified */ public static String toDateFormat(@NonNull final Date date, @NonNull final String format) { SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault()); dateFormat.setTimeZone(TimeZone.getDefault()); return dateFormat.format(date); } /** * Creates a string date format * * @param date Date object * @return formatted string in <code>yyyy-MM-dd'T'HH:mm:ss</code> format */ public static String toDateTimeFormat(@NonNull final Date date) { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault()); dateFormat.setTimeZone(TimeZone.getDefault()); return dateFormat.format(date); } /** * Creates a string date format * * @param date Date object * @return formatted string in <code>yyyy-MM-dd'T'HH:mm:ss.SSS</code> format */ public static String toDateTimeMillisFormat(@NonNull final Date date) { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT_MILLISECONDS, Locale.getDefault()); dateFormat.setTimeZone(TimeZone.getDefault()); return dateFormat.format(date); } /** * Creates a Date object from string date using API Timezone * * @param dateString String date from API with GMT timezone * @return date Date object converted to local timezone * @throws IllegalArgumentException when string is un-parsable */ public static Date fromDateTimeString(@NonNull final String dateString) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault()); dateFormat.setTimeZone(API_TIMEZONE); return dateFormat.parse(dateString); } catch (ParseException e) { throw new IllegalArgumentException("An exception occurred when attempting to parse " + "the date " + dateString, e); } } @VisibleForTesting static Date fromDateTimeString(@NonNull final String dateString, @NonNull final String format) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault()); dateFormat.setTimeZone(API_TIMEZONE); return dateFormat.parse(dateString); } catch (ParseException e) { throw new IllegalArgumentException("An exception occurred when attempting to parse " + "the date " + dateString, e); } } }
41.814516
120
0.701254
617a49966d88436702dcbd1783f39e6d0db6e5b0
3,594
/* * Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package io.hops.hopsworks.common.dao.user.security; import java.io.Serializable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import io.hops.hopsworks.common.dao.user.Users; @Entity @Table(name = "hopsworks.user_group") @XmlRootElement @NamedQueries({ @NamedQuery(name = "UserGroup.findAll", query = "SELECT p FROM UserGroup p"), @NamedQuery(name = "UserGroup.findByUid", query = "SELECT p FROM UserGroup p WHERE p.userGroupPK.uid = :uid"), @NamedQuery(name = "UserGroup.findByGid", query = "SELECT p FROM UserGroup p WHERE p.userGroupPK.gid = :gid")}) public class UserGroup implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected UserGroupPK userGroupPK; @JoinColumn(name = "uid", referencedColumnName = "uid", insertable = false, updatable = false) @ManyToOne(optional = false) private Users user; public UserGroup() { } public UserGroup(UserGroupPK userGroupPK) { this.userGroupPK = userGroupPK; } public UserGroup(int uid, int gid) { this.userGroupPK = new UserGroupPK(uid, gid); } public UserGroupPK getUserGroupPK() { return userGroupPK; } public void setUserGroupPK(UserGroupPK userGroupPK) { this.userGroupPK = userGroupPK; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } @Override public int hashCode() { int hash = 0; hash += (userGroupPK != null ? userGroupPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof UserGroup)) { return false; } UserGroup other = (UserGroup) object; if ((this.userGroupPK == null && other.userGroupPK != null) || (this.userGroupPK != null && !this.userGroupPK.equals( other.userGroupPK))) { return false; } return true; } @Override public String toString() { return "se.kth.bbc.security.ua.model.UserGroup[ userGroupPK=" + userGroupPK + " ]"; } }
32.089286
98
0.706455
64d9ca81a7e9a1c30cffea5ebc8656eaa5c9ae1f
2,843
package api; import dynamics.Compiler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import codeGenerator.ModelJsonParser; import codeGenerator.RuleParser; import judge.Processor; import languageParser.BaseParser; import reqParser.EntityParser; import util.ModeEnum; import util.PathConsts; import util.TypeEnum; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Map; import java.util.Objects; /** * @author Guo Weize * @date 2021/2/22 */ public class Main { private static final Map<ModeEnum, JsonDeserializer<?>> PARSERS = Map.ofEntries( Map.entry(ModeEnum.MODEL, new ModelJsonParser()), Map.entry(ModeEnum.RULE, new RuleParser()), Map.entry(ModeEnum.REQUIREMENT, new EntityParser()) ); public static void run(final String model, final String rule, final String requirement) { PathConsts.initialization(model, rule, requirement); definitions2json(); json2java(); judge(); } public static void definitions2json() { Processor.initialization(); BaseParser.run(); } public static void json2java() { clearJavaFiles(); parseJsonFile(ModeEnum.MODEL); parseJsonFile(ModeEnum.RULE); } public static void judge() { Compiler.run(); parseJsonFile(ModeEnum.REQUIREMENT); Processor.run(); } private static void clearJavaFiles() { File file = new File(PathConsts.DYNAMICS_JAVA_CODE_DIR); for (File f: Objects.requireNonNull(file.listFiles())) { if (f.isFile()) { f.delete(); } } } private static void parseJsonFile(final ModeEnum mode) { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addDeserializer(Object.class, PARSERS.get(mode)); mapper.registerModule(module); try { mapper.readValue(readFile(PathConsts.file(mode, TypeEnum.JSON)), Object.class); } catch (JsonProcessingException e) { e.printStackTrace(); } } private static String readFile(final String filePath) { File file = new File(filePath); long length = file.length(); byte[] content = new byte[(int) length]; try { FileInputStream in = new FileInputStream(file); in.read(content); in.close(); } catch (IOException e) { e.printStackTrace(); } return new String(content); } public static void main(String[] args) { run("model", "GANNT_entities", "rule"); } }
29.010204
93
0.650369
3af5445c5349cd7f97f492e2d3222d8575a93be3
3,032
package io.opensphere.core.hud.awt; import io.opensphere.core.model.GeographicBoxAnchor; /** Internal frame to be displayed as a HUD window. */ public class HUDJInternalFrame implements HUDFrame { /** * The geographic position to which the frame is attached. This may be null * when the frame is not attached to a geographic position. */ private final GeographicBoxAnchor myGeoAnchor; /** The Internal frame which is to be displayed. */ private final AbstractInternalFrame myInternalFrame; /** * Constructor. * * @param builder Builder which contains my settings. */ public HUDJInternalFrame(Builder builder) { myInternalFrame = builder.getInternalFrame(); myGeoAnchor = builder.getGeographicAnchor(); } /** * Get the geographicAnchor. * * @return the geographicAnchor */ public GeographicBoxAnchor getGeographicAnchor() { return myGeoAnchor; } /** * Get the internalFrame. * * @return the internalFrame */ public AbstractInternalFrame getInternalFrame() { return myInternalFrame; } @Override public String getTitle() { return myInternalFrame.getTitle(); } @Override public boolean isVisible() { return myInternalFrame.isVisible(); } @Override public void setVisible(boolean visible) { myInternalFrame.setVisible(visible); } /** Builder for the internal frame. */ public static class Builder { /** * The geographic position to which the frame is attached. This may be * null when the frame is not attached to a geographic position. */ private GeographicBoxAnchor myGeographicAnchor; /** The Internal frame which is to be displayed. */ private AbstractInternalFrame myInternalFrame; /** * Get the geographicAnchor. * * @return the geographicAnchor */ public GeographicBoxAnchor getGeographicAnchor() { return myGeographicAnchor; } /** * Get the internalFrame. * * @return the internalFrame */ public AbstractInternalFrame getInternalFrame() { return myInternalFrame; } /** * Set the geographicAnchor. * * @param geographicAnchor the geographicAnchor to set * @return the builder */ public Builder setGeographicAnchor(GeographicBoxAnchor geographicAnchor) { myGeographicAnchor = geographicAnchor; return this; } /** * Set the internalFrame. * * @param internalFrame the internalFrame to set * @return the builder */ public Builder setInternalFrame(AbstractInternalFrame internalFrame) { myInternalFrame = internalFrame; return this; } } }
24.650407
80
0.602243
429949ad7f26e63d41f4abec8a552209a03ecb72
4,467
/* * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package dom.ls; import java.io.StringBufferInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSParser; import org.w3c.dom.ls.LSSerializer; import org.w3c.dom.ls.LSSerializerFilter; import org.w3c.dom.traversal.NodeFilter; /* * @test * @bug 6376823 * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest * @run testng/othervm -DrunSecMngr=true -Djava.security.manager=allow dom.ls.Bug6376823 * @run testng/othervm dom.ls.Bug6376823 * @summary Test LSSerializer works. */ @Listeners({jaxp.library.BasePolicy.class}) public class Bug6376823 { private static String XML_STRING = "<?xml version=\"1.0\"?><ROOT><ELEMENT1><CHILD1/><CHILD1><COC1/></CHILD1></ELEMENT1><ELEMENT2>test1<CHILD2/></ELEMENT2></ROOT>"; private static DOMImplementationLS implLS; @Test public void testStringSourceWithXmlDecl() { String result = prepare(XML_STRING, true); System.out.println("testStringSource: output: " + result); Assert.assertTrue(result.indexOf("<?xml", 5) < 0, "XML Declaration expected in output"); } private String prepare(String source, boolean xmlDeclFlag) { Document startDoc = null; DocumentBuilder domParser = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); domParser = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } final StringBufferInputStream is = new StringBufferInputStream(XML_STRING); try { startDoc = domParser.parse(is); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } DOMImplementation impl = startDoc.getImplementation(); implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0"); LSParser parser = implLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, "http://www.w3.org/2001/XMLSchema"); LSInput src = getXmlSource(source); LSSerializer writer = implLS.createLSSerializer(); DOMConfiguration conf = writer.getDomConfig(); conf.setParameter("xml-declaration", Boolean.valueOf(xmlDeclFlag)); // set filter writer.setFilter(new LSSerializerFilter() { public short acceptNode(Node enode) { return FILTER_ACCEPT; } public int getWhatToShow() { return NodeFilter.SHOW_ALL; } }); Document doc = parser.parse(src); return writer.writeToString(doc); } private LSInput getXmlSource(String xml1) { LSInput src = implLS.createLSInput(); try { src.setStringData(xml1); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } return src; } }
36.024194
167
0.686367
01884f7781334a3e6b20e88d2d1b8a22ed57da1d
137
public class MetadataPlayerDeath { // Failed to decompile, took too long to decompile: net/minecraft/client/stream/MetadataPlayerDeath }
45.666667
100
0.817518
e5bb941eb6718806fb4740809958ef1188775b61
598
package top.yzhelp.campus.shiro.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.io.Serializable; import java.util.List; /** * @author <a href="https://github.com/gongsir0630">码之泪殇</a> * @date 2021/3/29 12:52 * 你的指尖,拥有改变世界的力量 * @description shiro 校验信息 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString public class ShiroAccount implements Serializable { /** * 用户名 */ private String authName; /** * 校验密码 */ private String authSecret; /** * 角色 */ private List<String> role; }
17.085714
60
0.704013
532bf749b2ff5e65381004683f1a2449f6c17b7e
518
package org.ekstep.genieservices.commons.bean.enums; /** * Created by swayangjit on 22/5/17. */ public enum JWTokenType { HS256("HS256", "HmacSHA256"); private String algorithmName; private String tokenType; JWTokenType(String tokenType, String algorithmName) { this.algorithmName = algorithmName; this.tokenType = tokenType; } public String getAlgorithmName() { return algorithmName; } public String getTokenType() { return tokenType; } }
18.5
57
0.662162
4474d69a38f91cedb7895afe679e50ca3eaa16f6
1,682
package com.ggp.players.continual_resolving.cfrd; import com.ggp.*; import java.util.List; import java.util.Objects; public class OpponentsTerminalState implements ICompleteInformationState { private static final long serialVersionUID = 1L; private double opponentPayoff; private int opponentId; public OpponentsTerminalState(double opponentPayoff, int opponentId) { this.opponentPayoff = opponentPayoff; this.opponentId = opponentId; } @Override public boolean isTerminal() { return true; } @Override public int getActingPlayerId() { return 0; } @Override public double getPayoff(int player) { return opponentPayoff * (player == opponentId ? 1 : -1); } @Override public List<IAction> getLegalActions() { return null; } @Override public IInformationSet getInfoSetForPlayer(int player) { return null; } @Override public ICompleteInformationState next(IAction a) { return null; } @Override public Iterable<IPercept> getPercepts(IAction a) { return null; } @Override public IRandomNode getRandomNode() { return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OpponentsTerminalState that = (OpponentsTerminalState) o; return Double.compare(that.opponentPayoff, opponentPayoff) == 0 && opponentId == that.opponentId; } @Override public int hashCode() { return Objects.hash(opponentPayoff, opponentId); } }
23.361111
74
0.64566
9300ab40fe3e5b6fbc4b63b20ffa897c0d1ee9e2
2,590
import java.util.ArrayList; import java.util.List; /** * Models the layout of places in vehicle. It can represent multi-floor place layout. */ public class PlaceLayout { // level, posInRow, posInColumn private List<Place[][]> m_places = new ArrayList<>(); private int m_floors = 0; /** * Default constructor. */ public PlaceLayout() { } /** * Add floor to the layout. * @param rows number of rows * @param cols number of places in each row */ public void addFloor(int rows, int cols) { m_places.add(new Place[rows][cols]); ++m_floors; } /** * Add place to the specific position in layout. * @param place place to be added * @param floor floor on which place will be added * @param row row in which place will be added * @param col position in row in which place will be added * @throws IndexOutOfBoundsException */ public void addPlace(Place place, int floor, int row, int col) throws IndexOutOfBoundsException { (m_places.get(floor))[row][col] = place; } /** * Return the number of rows on specific floor. * @param floor number of floor * @return number of rows on floor */ public int getRowsOnFloor(int floor) { return m_places.get(floor).length; } /** * Return the number of places in row on specific floor. * @param floor number of floor * @return number of places in row on floor. */ public int getColsOnFloor(int floor) { return m_places.get(floor)[0].length; } /** * Return place at specific position. * @param nr place number * @return selected place if success, false otherwise */ public Place getPlaceAtNumber(int nr) { Place p; for(int i = 0; i < m_floors; ++i) { for(int j = 0; j < m_places.get(i).length; ++j) for(int k = 0; k < m_places.get(i)[0].length; ++k) if(( p = m_places.get(i)[j][k]).getID() == nr) return p; } return null; } /** * Return total number of places in layout. * @return total number of places */ public int getTotalPlacesNumber() { int res = 0; for(Place[][] p : m_places) res += p.length * p[0].length; return res; } /** * Return number of floors in the layout. * @return number of floors in layout */ public int getFloorsNumber() { return m_floors; } }
25.145631
99
0.569884
34365d7f896352c64e4fbea8cff4ddfe039f75b3
1,930
package uk.nhs.adaptors.pss.translator.service; import static uk.nhs.adaptors.pss.translator.util.DateFormatUtil.toHl7Format; import static uk.nhs.adaptors.pss.translator.util.template.TemplateUtil.fillTemplate; import static uk.nhs.adaptors.pss.translator.util.template.TemplateUtil.loadTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.github.mustachejava.Mustache; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import uk.nhs.adaptors.common.model.TransferRequestMessage; import uk.nhs.adaptors.common.util.DateUtils; import uk.nhs.adaptors.pss.translator.util.template.parameter.SendEhrExtractRequestParams; @Service @Slf4j @AllArgsConstructor(onConstructor = @__(@Autowired)) public class EhrExtractRequestService { private static final Mustache SEND_EHR_EXTRACT_REQUEST_TEMPLATE = loadTemplate("sendEhrExtractRequest.mustache"); private final DateUtils dateUtils; private final IdGeneratorService idGeneratorService; public String buildEhrExtractRequest(TransferRequestMessage transferRequestMessage) { LOGGER.debug("Building EHRExtractRequest with nhsNumber=[{}]", transferRequestMessage.getPatientNhsNumber()); SendEhrExtractRequestParams params = SendEhrExtractRequestParams.builder() .messageId(idGeneratorService.generateUuid()) .timestamp(toHl7Format(dateUtils.getCurrentInstant())) .toAsid(transferRequestMessage.getToAsid()) .fromAsid(transferRequestMessage.getFromAsid()) .nhsNumber(transferRequestMessage.getPatientNhsNumber()) .ehrRequestId(idGeneratorService.generateUuid()) .fromOds(transferRequestMessage.getFromOds()) .toOds(transferRequestMessage.getToOds()) .build(); return fillTemplate(SEND_EHR_EXTRACT_REQUEST_TEMPLATE, params); } }
42.888889
117
0.780829
cb7730e7946cb70bd01d7652b0054e51ae934888
370
package sorcerer.client.data; import com.google.gwt.core.client.JavaScriptObject; /** * @author Kohsuke Kawaguchi */ public final class LocalVariableEntry extends JavaScriptObject { protected LocalVariableEntry() {} public native String name() /*-{ return this[0]; }-*/; public native String id() /*-{ return this[1]; }-*/; }
17.619048
64
0.645946
b6f7d8d834deea971b7efc6ce8f1056b862090b4
1,985
package compiling; import java.util.ArrayList; import java.util.Hashtable; public class CompilerLogs { //Changelog messages are stored here public static ArrayList<String> changeLogMessagesOutdated= new ArrayList<String>(); public static ArrayList<String> changeLogMessagesDuplicate = new ArrayList<String>(); public static ArrayList<String> changeLogMessagesNoAnswers = new ArrayList<String>(); public static ArrayList<String> changeLogMessagesOther = new ArrayList<String>(); public static ArrayList<String> changeLogMessagesRemoved = new ArrayList<String>(); public static ArrayList<String> errorLogMessages = new ArrayList<String>(); public static ArrayList<String> TypesofExceptions = new ArrayList<String>(); public static ArrayList<String> UnresolvedPrefixedNameExceptions = new ArrayList<String>(); public static ArrayList<String> LexicalErrorExceptions = new ArrayList<String>(); public static ArrayList<String> UnexpectedEncounterExceptions = new ArrayList<String>(); public static ArrayList<String> EncounteredPname = new ArrayList<String>(); public static ArrayList<String> OtherExceptions = new ArrayList<String>(); public static Hashtable<Integer, Integer> tripleCounter = new Hashtable<Integer, Integer>(); public static Hashtable<String, Integer> operatorDistribution = new Hashtable<String, Integer>(); public static Hashtable<String, Integer> subqueryDistribution = new Hashtable<String, Integer>(); public static Hashtable<String, Integer> keywordCount = new Hashtable<String, Integer>(); public static Hashtable<String, Integer> fileQuestionCount = new Hashtable<String, Integer>(); public static Hashtable<Integer, Integer> tripleCounterFull = new Hashtable<Integer, Integer>(); public static Hashtable<String, Integer> operatorDistributionFull = new Hashtable<String, Integer>(); public static Hashtable<String, Integer> subqueryDistributionFull = new Hashtable<String, Integer>(); }
52.236842
103
0.779849
02a0896d71571a74cc97e1a1390301164e34dcaa
4,654
package nl.mwensveen.adventofcode.year_2017.day_18; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.primitives.Longs; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ForkJoinPool; import java.util.stream.Collectors; public class Duet { private Map<String, Long> registers = new HashMap<>(); private List<Instruction> instructions; private Long lastFrequency; public Duet(String input) { instructions = toInstructionList(input); } public Integer calculateSendReceive() { ForkJoinPool commonPool = ForkJoinPool.commonPool(); DuetSendReceive duetSendReceive = new DuetSendReceive(instructions); return commonPool.invoke(duetSendReceive); } public Long calculate() { int i = 0; while (true) { System.out.println(i); Instruction instruction = instructions.get(i); System.out.println(instruction); Long value = null; Long instructionValue = null; switch (instruction.getCommand()) { case SND: value = getValueOrUseLong(instruction.getRegister()); lastFrequency = value; break; case SET: instructionValue = getValueOrUseLong(instruction.getValue()); setValueOfRegister(instruction.getRegister(), instructionValue); break; case INCREASE: value = getValueFromRegister(instruction.getRegister()); instructionValue = getValueOrUseLong(instruction.getValue()); setValueOfRegister(instruction.getRegister(), value.longValue() + instructionValue.longValue()); break; case MULTIPLY: value = getValueFromRegister(instruction.getRegister()); instructionValue = getValueOrUseLong(instruction.getValue()); setValueOfRegister(instruction.getRegister(), value.longValue() * instructionValue.longValue()); break; case REMAINDER: value = getValueFromRegister(instruction.getRegister()); instructionValue = getValueOrUseLong(instruction.getValue()); setValueOfRegister(instruction.getRegister(), value % instructionValue.longValue()); break; case RCV: value = getValueOrUseLong(instruction.getRegister()); if (value != Long.valueOf(0)) { return lastFrequency; } break; case JUMP: value = getValueOrUseLong(instruction.getRegister()); if (value > Long.valueOf(0)) { instructionValue = getValueOrUseLong(instruction.getValue()); i = i + instructionValue.intValue() - 1; } break; default: throw new RuntimeException("Instruction not implemented " + instruction); } i++; } } private Long getValueOrUseLong(String value) { Long Long = Longs.tryParse(value); if (Long != null) { return Long; } return getValueFromRegister(value); } private void setValueOfRegister(String register, Long value) { registers.put(register, value); } private Long getValueFromRegister(String register) { Long i = registers.get(register); if (i == null) { return Long.valueOf(0); } return i; } private Instruction toInstruction(String input) { Iterable<String> split = Splitter.on(" ") .trimResults() .omitEmptyStrings() .split(input); ArrayList<String> newArrayList = Lists.newArrayList(split); System.out.println(input); return new Instruction(InstructionCommand.find(newArrayList.get(0)), newArrayList.get(1), newArrayList.size() > 2 ? newArrayList.get(2) : null); } private List<Instruction> toInstructionList(String in) { Iterable<String> split = Splitter.on("\n") .trimResults() .omitEmptyStrings() .split(in); ArrayList<String> newArrayList = Lists.newArrayList(split); return newArrayList.stream().map(s -> toInstruction(s)).collect(Collectors.toList()); } }
38.783333
152
0.58208
b0bdb1db3db3c0b6c36d1b2ebdd322ba5314af57
627
package com.partysys.partymanage.deus.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.partysys.core.service.impl.BaseServiceImpl; import com.partysys.partymanage.deus.dao.DeusDao; import com.partysys.partymanage.deus.entity.Deus; import com.partysys.partymanage.deus.service.DeusService; @Service("deusService") public class DeusServiceImpl extends BaseServiceImpl<Deus> implements DeusService{ private DeusDao deusDao; @Autowired public void setDeusDao(DeusDao deusDao) { super.setBaseDao(deusDao); this.deusDao = deusDao; } }
31.35
82
0.822967
c8c4b7afa3bedb39b535d9c0b4c4b82f475d3fce
4,759
package com.ep.eventparticipant.adapter; import android.app.Activity; import android.app.ActivityOptions; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.ep.eventparticipant.Item.All_item; import com.ep.eventparticipant.Item.Informention_item; import com.ep.eventparticipant.R; import com.ep.eventparticipant.activity.AllActivity; import com.ep.eventparticipant.activity.FindThing; import com.ep.eventparticipant.activity.OtherActivity; import java.util.List; import static com.ep.eventparticipant.activity.ExchangeInformation.informention_itemList; public class AllAdapter extends RecyclerView.Adapter<AllAdapter.ViewHolder> { public static List<All_item> mall_items; private Context context; static class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; TextView textView; TextView xiangqin; public ViewHolder(View view) { super(view); imageView = (ImageView) view.findViewById(R.id.all_imageview); textView = (TextView) view.findViewById(R.id.all_text_view); xiangqin = (TextView) view.findViewById(R.id.xiangqin); } } public AllAdapter(List<All_item> all_items) { mall_items = all_items; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_item, parent, false); final ViewHolder holder = new ViewHolder(view); if (context == null) { context = parent.getContext(); } holder.imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { int position = holder.getAdapterPosition(); All_item all_item = mall_items.get(position); if (context.getClass().equals(FindThing.class)) { Intent intent = new Intent("tuao"); intent.putExtra("tupian2", position); v.getContext().sendBroadcast(intent); } else { Intent intent = new Intent(context, FindThing.class); intent.putExtra("key", all_item.getName()); Toast.makeText(context, "您需要搜索的是 " + all_item.getName(), Toast.LENGTH_LONG).show(); context.startActivity(intent); // informention_itemList.add(new Informention_item(all_item.getName(),all_item.getId(),"","","",100)); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(context, "出现未知错误! ", Toast.LENGTH_LONG).show(); } } }); return holder; } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { final All_item all_item = mall_items.get(position); holder.textView.setText(all_item.getName()); int id = all_item.getId(); if (id > 10000) Glide.with(context).load(all_item.getId()).into(holder.imageView); else Glide.with(context).load(all_item.getImageurl()).into(holder.imageView); final String name = all_item.getName(); holder.xiangqin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), OtherActivity.class); intent.putExtra("b", position); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { v.getContext().startActivity(intent, ActivityOptions.makeSceneTransitionAnimation((Activity) v.getContext(), v, "sharedView").toBundle()); } } }); // holder.imageView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { //informention_itemList.add(new Informention_item(all_item.getName(),all_item.getId(),"","","",100)); // } // }); } @Override public int getItemCount() { return mall_items.size(); } }
37.179688
129
0.626812
62a0784d2d594faf8e43f789b4035777383e8765
17,221
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.camel.component.lumberjack.io package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|charset operator|. name|StandardCharsets import|; end_import begin_import import|import name|java operator|. name|util operator|. name|LinkedHashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|zip operator|. name|Inflater import|; end_import begin_import import|import name|com operator|. name|fasterxml operator|. name|jackson operator|. name|databind operator|. name|ObjectMapper import|; end_import begin_import import|import name|io operator|. name|netty operator|. name|buffer operator|. name|ByteBuf import|; end_import begin_import import|import name|io operator|. name|netty operator|. name|channel operator|. name|ChannelHandlerContext import|; end_import begin_import import|import name|io operator|. name|netty operator|. name|handler operator|. name|codec operator|. name|ByteToMessageDecoder import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|FRAME_COMPRESS_HEADER_LENGTH import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|FRAME_DATA_HEADER_LENGTH import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|FRAME_HEADER_LENGTH import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|FRAME_JSON_HEADER_LENGTH import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|FRAME_WINDOW_HEADER_LENGTH import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|INT_LENGTH import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|TYPE_COMPRESS import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|TYPE_DATA import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|TYPE_JSON import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|lumberjack operator|. name|io operator|. name|LumberjackConstants operator|. name|TYPE_WINDOW import|; end_import begin_comment comment|/** * Decode lumberjack protocol frames. Support protocol V1 and V2 and frame types D, J, W and C.<br/> *<p> * For more info, see: *<ul> *<li><a href="https://github.com/elastic/beats">https://github.com/elastic/beats</a></li> *<li><a href="https://github.com/logstash-plugins/logstash-input-beats/blob/master/PROTOCOL.md">https://github.com/logstash-plugins/logstash-input-beats/blob/master/PROTOCOL.md</a></li> *<li><a href="https://github.com/elastic/logstash-forwarder/blob/master/PROTOCOL.md">https://github.com/elastic/logstash-forwarder/blob/master/PROTOCOL.md</a></li> *<li><a href="https://github.com/elastic/libbeat/issues/279">https://github.com/elastic/libbeat/issues/279</a></li> *</ul> */ end_comment begin_class DECL|class|LumberjackFrameDecoder specifier|final class|class name|LumberjackFrameDecoder extends|extends name|ByteToMessageDecoder block|{ DECL|field|LOG specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|LumberjackFrameDecoder operator|. name|class argument_list|) decl_stmt|; DECL|field|sessionHandler specifier|private specifier|final name|LumberjackSessionHandler name|sessionHandler decl_stmt|; DECL|field|jackson specifier|private specifier|final name|ObjectMapper name|jackson init|= operator|new name|ObjectMapper argument_list|() decl_stmt|; DECL|method|LumberjackFrameDecoder (LumberjackSessionHandler sessionHandler) name|LumberjackFrameDecoder parameter_list|( name|LumberjackSessionHandler name|sessionHandler parameter_list|) block|{ name|this operator|. name|sessionHandler operator|= name|sessionHandler expr_stmt|; block|} annotation|@ name|Override DECL|method|decode (ChannelHandlerContext ctx, ByteBuf in, List<Object> out) specifier|protected name|void name|decode parameter_list|( name|ChannelHandlerContext name|ctx parameter_list|, name|ByteBuf name|in parameter_list|, name|List argument_list|< name|Object argument_list|> name|out parameter_list|) throws|throws name|Exception block|{ comment|// mark the reader index to be able to start decoding from the same position if there is not enough data to finish the frame decoding name|in operator|. name|markReaderIndex argument_list|() expr_stmt|; name|boolean name|frameDecoded init|= literal|false decl_stmt|; try|try block|{ if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|FRAME_HEADER_LENGTH argument_list|) condition|) block|{ return|return; block|} name|int name|frameVersion init|= name|in operator|. name|readUnsignedByte argument_list|() decl_stmt|; name|sessionHandler operator|. name|versionRead argument_list|( name|frameVersion argument_list|) expr_stmt|; name|int name|frameType init|= name|in operator|. name|readUnsignedByte argument_list|() decl_stmt|; name|LOG operator|. name|debug argument_list|( literal|"Received a lumberjack frame of type {}" argument_list|, operator|( name|char operator|) name|frameType argument_list|) expr_stmt|; switch|switch condition|( name|frameType condition|) block|{ case|case name|TYPE_JSON case|: name|frameDecoded operator|= name|handleJsonFrame argument_list|( name|in argument_list|, name|out argument_list|) expr_stmt|; break|break; case|case name|TYPE_DATA case|: name|frameDecoded operator|= name|handleDataFrame argument_list|( name|in argument_list|, name|out argument_list|) expr_stmt|; break|break; case|case name|TYPE_WINDOW case|: name|frameDecoded operator|= name|handleWindowFrame argument_list|( name|in argument_list|) expr_stmt|; break|break; case|case name|TYPE_COMPRESS case|: name|frameDecoded operator|= name|handleCompressedFrame argument_list|( name|ctx argument_list|, name|in argument_list|, name|out argument_list|) expr_stmt|; break|break; default|default: throw|throw operator|new name|RuntimeException argument_list|( literal|"Unsupported frame type=" operator|+ name|frameType argument_list|) throw|; block|} block|} finally|finally block|{ if|if condition|( operator|! name|frameDecoded condition|) block|{ name|LOG operator|. name|debug argument_list|( literal|"Not enough data to decode a complete frame, retry when more data is available. Reader index was {}" argument_list|, name|in operator|. name|readerIndex argument_list|() argument_list|) expr_stmt|; name|in operator|. name|resetReaderIndex argument_list|() expr_stmt|; block|} block|} block|} DECL|method|handleJsonFrame (ByteBuf in, List<Object> out) specifier|private name|boolean name|handleJsonFrame parameter_list|( name|ByteBuf name|in parameter_list|, name|List argument_list|< name|Object argument_list|> name|out parameter_list|) throws|throws name|IOException block|{ if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|FRAME_JSON_HEADER_LENGTH argument_list|) condition|) block|{ return|return literal|false return|; block|} name|int name|sequenceNumber init|= name|in operator|. name|readInt argument_list|() decl_stmt|; comment|// read message string and then decode it as JSON name|String name|jsonStr init|= name|readLengthPrefixedString argument_list|( name|in argument_list|) decl_stmt|; if|if condition|( name|jsonStr operator|== literal|null condition|) block|{ return|return literal|false return|; block|} name|Object name|jsonMessage init|= name|jackson operator|. name|readValue argument_list|( name|jsonStr argument_list|, name|Object operator|. name|class argument_list|) decl_stmt|; comment|// put message in the pipeline name|out operator|. name|add argument_list|( operator|new name|LumberjackMessage argument_list|( name|sequenceNumber argument_list|, name|jsonMessage argument_list|) argument_list|) expr_stmt|; return|return literal|true return|; block|} DECL|method|handleDataFrame (ByteBuf in, List<Object> out) specifier|private name|boolean name|handleDataFrame parameter_list|( name|ByteBuf name|in parameter_list|, name|List argument_list|< name|Object argument_list|> name|out parameter_list|) block|{ if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|FRAME_DATA_HEADER_LENGTH argument_list|) condition|) block|{ return|return literal|false return|; block|} name|int name|sequenceNumber init|= name|in operator|. name|readInt argument_list|() decl_stmt|; name|int name|entriesCount init|= name|in operator|. name|readInt argument_list|() decl_stmt|; name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|dataMessage init|= operator|new name|LinkedHashMap argument_list|<> argument_list|() decl_stmt|; while|while condition|( name|entriesCount operator|-- operator|> literal|0 condition|) block|{ name|String name|key init|= name|readLengthPrefixedString argument_list|( name|in argument_list|) decl_stmt|; if|if condition|( name|key operator|== literal|null condition|) block|{ return|return literal|false return|; block|} name|String name|value init|= name|readLengthPrefixedString argument_list|( name|in argument_list|) decl_stmt|; if|if condition|( name|value operator|== literal|null condition|) block|{ return|return literal|false return|; block|} name|dataMessage operator|. name|put argument_list|( name|key argument_list|, name|value argument_list|) expr_stmt|; block|} name|out operator|. name|add argument_list|( operator|new name|LumberjackMessage argument_list|( name|sequenceNumber argument_list|, name|dataMessage argument_list|) argument_list|) expr_stmt|; return|return literal|true return|; block|} DECL|method|handleWindowFrame (ByteBuf in) specifier|private name|boolean name|handleWindowFrame parameter_list|( name|ByteBuf name|in parameter_list|) block|{ if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|FRAME_WINDOW_HEADER_LENGTH argument_list|) condition|) block|{ return|return literal|false return|; block|} comment|// update window size name|sessionHandler operator|. name|windowSizeRead argument_list|( name|in operator|. name|readInt argument_list|() argument_list|) expr_stmt|; return|return literal|true return|; block|} DECL|method|handleCompressedFrame (ChannelHandlerContext ctx, ByteBuf in, List<Object> out) specifier|private name|boolean name|handleCompressedFrame parameter_list|( name|ChannelHandlerContext name|ctx parameter_list|, name|ByteBuf name|in parameter_list|, name|List argument_list|< name|Object argument_list|> name|out parameter_list|) throws|throws name|Exception block|{ if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|FRAME_COMPRESS_HEADER_LENGTH argument_list|) condition|) block|{ return|return literal|false return|; block|} name|int name|compressedPayloadLength init|= name|in operator|. name|readInt argument_list|() decl_stmt|; if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|compressedPayloadLength argument_list|) condition|) block|{ return|return literal|false return|; block|} comment|// decompress payload name|Inflater name|inflater init|= operator|new name|Inflater argument_list|() decl_stmt|; if|if condition|( name|in operator|. name|hasArray argument_list|() condition|) block|{ name|inflater operator|. name|setInput argument_list|( name|in operator|. name|array argument_list|() argument_list|, name|in operator|. name|arrayOffset argument_list|() operator|+ name|in operator|. name|readerIndex argument_list|() argument_list|, name|compressedPayloadLength argument_list|) expr_stmt|; name|in operator|. name|skipBytes argument_list|( name|compressedPayloadLength argument_list|) expr_stmt|; block|} else|else block|{ name|byte index|[] name|array init|= operator|new name|byte index|[ name|compressedPayloadLength index|] decl_stmt|; name|in operator|. name|readBytes argument_list|( name|array argument_list|) expr_stmt|; name|inflater operator|. name|setInput argument_list|( name|array argument_list|) expr_stmt|; block|} while|while condition|( operator|! name|inflater operator|. name|finished argument_list|() condition|) block|{ name|ByteBuf name|decompressed init|= name|ctx operator|. name|alloc argument_list|() operator|. name|heapBuffer argument_list|( literal|1024 argument_list|, literal|1024 argument_list|) decl_stmt|; name|byte index|[] name|outArray init|= name|decompressed operator|. name|array argument_list|() decl_stmt|; name|int name|count init|= name|inflater operator|. name|inflate argument_list|( name|outArray argument_list|, name|decompressed operator|. name|arrayOffset argument_list|() argument_list|, name|decompressed operator|. name|writableBytes argument_list|() argument_list|) decl_stmt|; name|decompressed operator|. name|writerIndex argument_list|( name|count argument_list|) expr_stmt|; comment|// put data in the pipeline name|out operator|. name|add argument_list|( name|decompressed argument_list|) expr_stmt|; block|} return|return literal|true return|; block|} comment|/** * Read a string that is prefixed by its length encoded by a 4 bytes integer. * * @param in the buffer to consume * @return the read string or {@code null} if not enough data available to read the whole string */ DECL|method|readLengthPrefixedString (ByteBuf in) specifier|private name|String name|readLengthPrefixedString parameter_list|( name|ByteBuf name|in parameter_list|) block|{ if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|INT_LENGTH argument_list|) condition|) block|{ return|return literal|null return|; block|} name|int name|length init|= name|in operator|. name|readInt argument_list|() decl_stmt|; if|if condition|( operator|! name|in operator|. name|isReadable argument_list|( name|length argument_list|) condition|) block|{ return|return literal|null return|; block|} name|String name|str init|= name|in operator|. name|toString argument_list|( name|in operator|. name|readerIndex argument_list|() argument_list|, name|length argument_list|, name|StandardCharsets operator|. name|UTF_8 argument_list|) decl_stmt|; name|in operator|. name|skipBytes argument_list|( name|length argument_list|) expr_stmt|; return|return name|str return|; block|} block|} end_class end_unit
15.013949
810
0.799779
d186af134a6f6c9bd3ac1664009058e34cc582c0
20,417
package com.flat502.rox.client; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URL; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.flat502.rox.log.Log; import com.flat502.rox.log.LogFactory; import com.flat502.rox.utils.CaptureTimeoutException; import com.flat502.rox.utils.MinHeap; import com.flat502.rox.utils.Profiler; import com.flat502.rox.utils.ThreadQueue; class SharedSocketChannelPool { private static Log log = LogFactory.getLog(SharedSocketChannelPool.class); // These map HttpRpcClient instances to pooled and active connections // respectively. Destinations in the following are (protocol, host, port) // tuples. // pooledConnStacks maps Destinations -> List<PooledSocketChannel> // These lists are treated as stacks so we always reuse the MRU connection // activeConnSets maps Destinations -> Set<PooledSocketChannel> // These sets allow us to recover active channels when a client // detaches. private Map<Object, ArrayList<PooledSocketChannel>> pooledConnStacks = new HashMap<>(); private Map<Object, Set<PooledSocketChannel>> activeConnSets = new HashMap<>(); // Maps Destinations -> Set<HttpRpcClient> so we can track all // known clients for a given key (see createClientKey()). private Map<Object, Set<HttpRpcClient>> knownClients = new HashMap<>(); // A binary heap holding PooledSocketChannel instances that aren't // checked out. This is ordered by the last access time of said // channels. This allows us to efficiently check for channels that // should be expired after some amount of inactivity, and to // efficiently locate the least recently used channel // (globally) when we need to evict a channel to satisfy // a client request. private MinHeap channelHeap = new MinHeap(); // Tracks the total number of connections in existence // that are still in the pool. This provides // an easy check for availability. private int availableConnections; // Maps physical channels to their pooled wrapper // so we can find the pooled wrapper when a channel // is returned. private Map<SocketChannel, PooledSocketChannel> channelMap = new HashMap<>(); // We use this to capture threads when the pool reaches it's // limit. This ensures that threads are serviced in FIFO order // which is a reasonably simple approach to fairness. private ThreadQueue threadQueue; private Object mutex; private int maxConnections; private int activeConnections; private long maxWait; private Profiler profiler; public SharedSocketChannelPool(Object mutex, int maxConnections, long maxWait, Profiler profiler) { this.mutex = mutex; this.maxConnections = maxConnections; this.maxWait = maxWait; this.threadQueue = new ThreadQueue(this.mutex); this.profiler = profiler; if (log.logTrace()) { log.trace("Socket channel pool initialized: limit=" + maxConnections + ", timeout=" + maxWait); } } public SocketChannel getChannel(HttpRpcClient client) throws IOException { long pid = client.hashCode() ^ System.nanoTime(); this.profiler.begin(pid, this.getClass().getName() + ".getChannel"); try { synchronized (this.mutex) { SocketChannel channel; dbgLog("GET starts", client, null); // Ensure this client is always recorded Object key = this.createClientKey(client); Set<HttpRpcClient> clientSet = this.knownClients.get(key); if (clientSet == null) { clientSet = new HashSet<>(); this.knownClients.put(key, clientSet); } clientSet.add(client); // Now try to satisfy the connection request if (this.maxConnections == 0) { // No limit is defined. If we can't check a pooled connection out // then just create a new one. channel = this.checkOut(client); if (channel == null) { channel = this.getNewChannel(client); } } else { // A limit is defined if (this.activeConnections + this.availableConnections == this.maxConnections) { // And we've hit it. We loop here because capture()/release() below has similar semantics // to wait()/notify(). while (this.activeConnections == this.maxConnections) { // Nothing is pooled (they're all active connections). Wait until something frees up. if (log.logTrace()) { log.trace("Connection pool limit reached, waiting for return"); } try { dbgLog("CAPTURE", client, null); this.threadQueue.capture(this.maxWait); dbgLog("RELEASE", client, null); } catch (CaptureTimeoutException e) { throw new ConnectionPoolTimeoutException(e); } } // There's capacity but it may not be appropriate for our use. // Try to check out a pooled connection. If we can't then create a new one // (which may require us to evict an existing connection). channel = this.checkOut(client); if (channel == null) { if (this.availableConnections > 0) { if (log.logTrace()) { log.trace("Replacing pooled socket channel for [" + client.getURL() + "]"); } // Select LRU SocketChannel and close it this.removeLeastRecentlyUsedChannel(); } channel = this.getNewChannel(client); } } else { // But we haven't hit it yet. Try to check out a pooled connection, // but if we can't then just create a new one. channel = this.checkOut(client); if (channel == null) { channel = this.getNewChannel(client); } } } dbgLog("GET returns", client, channel); return channel; } } finally { this.profiler.end(pid, this.getClass().getName() + ".getChannel"); } } private static long classInit = System.currentTimeMillis(); private void dbgLog(String id, HttpRpcClient client, SocketChannel channel) { if (!log.logTrace()) { return; } long time = System.currentTimeMillis()-classInit; Object key = client == null ? null : createClientKey(client); log.trace(time+": "+id+": client="+System.identityHashCode(client)+" ["+key+"]: ch="+System.identityHashCode(channel)+": "+this); } public void returnChannel(HttpRpcClient client, SocketChannel channel) { boolean bailing = false; synchronized (this.mutex) { try { dbgLog("RETURN starts", client, channel); if (log.logTrace()) { log.trace("Returning socket channel to pool for [" + client.getURL() + "]"); } if (this.availableConnections > 0) { this.removeExpiredChannels(); } // Look up the pooled channel for this channel PooledSocketChannel pooledChannel = this.channelMap.get(channel); if (pooledChannel == null) { // This has been cleaned up by a call to detach() (via HttpRpcClient.stop()) // Counts should all be correct. Just bail. dbgLog("RETURN bails", client, channel); bailing = true; return; } if (pooledChannel.getOwner() != client) { throw new IllegalArgumentException("Channel not returned by owner"); } // Indicate it's been returned (so we can update its accessTime) pooledChannel.notifyReturned(); // And check this connection back in this.checkIn(client, pooledChannel); dbgLog("RETURN returns", client, channel); } finally { if (!bailing) { dbgLog("RETURN releases", client, channel); this.threadQueue.release(); } } } } public void removeChannel(HttpRpcClient client, SocketChannel channel) { synchronized (this.mutex) { try { dbgLog("REMOVE starts", client, channel); Object key = createClientKey(client); if (log.logTrace()) { log.trace("Closing pooled socket channel for [" + key + "]"); } PooledSocketChannel pooledChannel = this.channelMap.remove(channel); if (pooledChannel != null) { if (pooledChannel.getOwner() != client) { throw new IllegalArgumentException("Channel not removed by owner"); } Set<PooledSocketChannel> activeSet = this.activeConnSets.get(key); // This might be null if a timeout occurs, calls into this method // and the client has already detached. if (activeSet != null) { activeSet.remove(pooledChannel); this.activeConnections--; } } client.cancel(channel); dbgLog("REMOVE returns", client, channel); } finally { dbgLog("REMOVE releases", client, channel); this.threadQueue.release(); } } } void removeClosedChannel(SocketChannel channel) { synchronized (this.mutex) { dbgLog("REMOVE_CLOSED starts", null, channel); if (log.logTrace()) { log.trace("Removing closed pooled socket channel"); } PooledSocketChannel pooledChannel = this.channelMap.remove(channel); if (pooledChannel != null) { if (pooledChannel.getOwner() != null) { throw new IllegalArgumentException("Channel has an owner"); } // Remove the pooled connection if it hasn't been done already (because // we closed this connection as part of detaching() and this is the channel selector // calling through after being woken up subsequently). List<PooledSocketChannel> connStack = this.pooledConnStacks.get(pooledChannel.getPoolingKey()); if (connStack != null) { Set<HttpRpcClient> clientSet = this.knownClients.get(pooledChannel.getPoolingKey()); if (clientSet == null) { if (connStack.remove(pooledChannel)) { this.availableConnections--; } } } } dbgLog("REMOVE_CLOSED returns", null, channel); } } // TODO: This won't close in-use connections. Should it? public void close() { synchronized (this.mutex) { Iterator<Entry<Object, ArrayList<PooledSocketChannel>>> stacks = this.pooledConnStacks.entrySet().iterator(); while(stacks.hasNext()) { Entry<Object, ArrayList<PooledSocketChannel>> entry = stacks.next(); String key = (String) entry.getKey(); List<PooledSocketChannel> stack = entry.getValue(); ListIterator<PooledSocketChannel> pooledChannels = stack.listIterator(stack.size()); while(pooledChannels.hasPrevious()) { PooledSocketChannel pooledChannel = pooledChannels.previous(); this.closePooledChannel(pooledChannel); pooledChannels.remove(); } Set<HttpRpcClient> clientSet = this.knownClients.get(key); if (clientSet != null && clientSet.isEmpty()) { // Only remove this stack if we know of no other clients using this key (URL) stacks.remove(); } } } } @Override public String toString() { int total = this.channelMap.size(); return "Pool[size=" + total + ", active=" + this.activeConnections + ", pooled=" + this.availableConnections + ", max=" + this.maxConnections + "]"; } public void detach(HttpRpcClient client) { synchronized(this.mutex) { try { // String hc = ""+System.identityHashCode(client); Object key = createClientKey(client); dbgLog("DETACH starts", client, null); // By definition, pooled connections are not "owned" by this client. // However, if no other clients we know of share their key then // we need to clean up those pooled connections. Set<HttpRpcClient> clientSet = this.knownClients.get(key); // We may never have seen connections on this URL if (clientSet != null) { clientSet.remove(client); if (clientSet.isEmpty()) { this.knownClients.remove(key); // Clean up all pooled connections for this key ArrayList<PooledSocketChannel> connStack = this.pooledConnStacks.remove(key); if (connStack != null) { Iterator<PooledSocketChannel> pooledChannels = connStack.iterator(); while(pooledChannels.hasNext()) { PooledSocketChannel pooledChannel = pooledChannels.next(); this.channelHeap.removeValue(pooledChannel); // This cleans up channelMap too this.closePooledChannel(pooledChannel); } } } } dbgLog("DETACH pooled done", client, null); // Reclaim any active connections owned by this client Set<PooledSocketChannel> activeSet = this.activeConnSets.get(key); if (activeSet != null) { Iterator<PooledSocketChannel> pooledChannels = activeSet.iterator(); while(pooledChannels.hasNext()) { PooledSocketChannel pooledChannel = pooledChannels.next(); if (pooledChannel.getOwner() == client) { this.channelHeap.removeValue(pooledChannel); // This cleans up channelMap too this.closeActiveChannel(pooledChannel); // Remove this active channel pooledChannels.remove(); } } // If there are no other clients using this key (URL) then we can clean up // entirely. // Note: clientSet can't be null here since we must have returned one channel // to have set activeConnSets up. if (clientSet.isEmpty()) { this.activeConnSets.remove(key); } } dbgLog("DETACH returns", client, null); } finally { dbgLog("DETACH releases", client, null); this.threadQueue.release(); } } } protected Object createClientKey(HttpRpcClient client) { // It might make sense to put this method onto the client so // this value can be constructed once. URL url = client.getURL(); int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } return url.getProtocol() + "://" + url.getHost() + ":" + port; } /** * Invoked when the pool is empty and a new connection * is required. This method will block (if the * pool's limit is non-zero and has been reached) until a new connection * can be created. * @throws IOException */ private SocketChannel getNewChannel(HttpRpcClient client) throws IOException { Object key = createClientKey(client); if (log.logTrace()) { log.trace("Creating new socket channel for [" + key + "]"); } SocketChannel channel = this.newChannel(client); PooledSocketChannel pooledChannel = new PooledSocketChannel(client, channel, key); this.channelMap.put(channel, pooledChannel); Set<PooledSocketChannel> activeSet = this.activeConnSets.get(key); if (activeSet == null) { activeSet = new HashSet<>(); this.activeConnSets.put(key, activeSet); } activeSet.add(pooledChannel); this.activeConnections++; if (!this.pooledConnStacks.containsKey(key)) { this.pooledConnStacks.put(key, new ArrayList<PooledSocketChannel>()); } return channel; } private SocketChannel newChannel(HttpRpcClient client) throws IOException { // Create a non-blocking socket channel SocketChannel clientChannel = SocketChannel.open(); clientChannel.configureBlocking(false); // Send a connection request to the server; this method is non-blocking int port = client.getURL().getPort(); if (port == -1) { port = client.getURL().getDefaultPort(); } clientChannel.connect(new InetSocketAddress(client.getURL().getHost(), port)); // Register the new channel with our selector client.register(clientChannel); return clientChannel; } private void removeExpiredChannels() { while(true) { if (this.channelHeap.isEmpty()) { break; } PooledSocketChannel pooledChannel = (PooledSocketChannel) this.channelHeap.getSmallest(); // Because this is an ordered heap, we're done as soon as we encounter // the first entry that is younger than our expiration age. if (pooledChannel.getAge() < 5000) { break; } // Everything else is too old and must be expired. But first, remove // it from our heap. this.channelHeap.removeSmallest(); // Fetch the related connection stack and remove this channel ArrayList<PooledSocketChannel> connStack = this.pooledConnStacks.get(pooledChannel.getPoolingKey()); connStack.remove(pooledChannel); if (log.logTrace()) { log.trace("Closing expired pooled socket channel (age=" + pooledChannel.getAge() + "ms)"); } this.closePooledChannel(pooledChannel); } } // Pull out the LRU pooled channel private void removeLeastRecentlyUsedChannel() { PooledSocketChannel pooledChannel = (PooledSocketChannel) this.channelHeap.removeSmallest(); // Fetch the related connection stack and remove this channel ArrayList<PooledSocketChannel> connStack = this.pooledConnStacks.get(pooledChannel.getPoolingKey()); connStack.remove(pooledChannel); // And finally, actually close the connection. This also // removes the physical->pooled channel mapping. this.closePooledChannel(pooledChannel); } private SocketChannel checkOut(HttpRpcClient client) { if (this.availableConnections > 0) { this.removeExpiredChannels(); } Object key = createClientKey(client); if (log.logTrace()) { log.trace("Checking out pooled socket channel for [" + key + "]"); } ArrayList<PooledSocketChannel> pooledStack = this.pooledConnStacks.get(key); if (pooledStack == null || pooledStack.isEmpty()) { // No pooled channel available return null; } int lastIdx = pooledStack.size() - 1; PooledSocketChannel pooledChannel = pooledStack.remove(lastIdx); this.availableConnections--; // Update our record of ownership and register this channel // so Selector operations are routed to the new owner. pooledChannel.setOwner(client); client.registerChannel(pooledChannel.getPhysicalConnection()); Set<PooledSocketChannel> activeSet = this.activeConnSets.get(key); activeSet.add(pooledChannel); this.activeConnections++; this.channelHeap.removeValue(pooledChannel); SocketChannel channel = pooledChannel.getPhysicalConnection(); // Vet the channel: if it's been closed then it's no use to us // TODO: We could be a little more efficient and try other pooled // connections here before giving up. if (!channel.isOpen()) { this.closePooledChannel(pooledChannel); return null; } return pooledChannel.getPhysicalConnection(); } private void checkIn(HttpRpcClient client, PooledSocketChannel pooledChannel) { Object key = pooledChannel.getPoolingKey(); if (log.logTrace()) { log.trace("Checking in pooled socket channel for [" + key + "]"); } // Deregister this channel so Selector operations are not routed to the // previous owner. pooledChannel.getOwner().deregisterChannel(pooledChannel.getPhysicalConnection()); pooledChannel.setOwner(null); List<PooledSocketChannel> pooledStack = this.pooledConnStacks.get(key); pooledStack.add(pooledChannel); this.availableConnections++; Set<PooledSocketChannel> activeSet = this.activeConnSets.get(key); activeSet.remove(pooledChannel); this.activeConnections--; this.channelHeap.insertUnordered(pooledChannel.getAccessTime(), pooledChannel); } private void closePooledChannel(PooledSocketChannel pooledChannel) { this.channelMap.remove(pooledChannel.getPhysicalConnection()); try { HttpRpcClient owner = pooledChannel.getOwner(); if (owner != null) { owner.cancel(pooledChannel.getPhysicalConnection()); } pooledChannel.getPhysicalConnection().close(); } catch (IOException e) { log.warn("Exception closing pooled connection", e); } finally { this.availableConnections--; } } private void closeActiveChannel(PooledSocketChannel pooledChannel) { this.channelMap.remove(pooledChannel.getPhysicalConnection()); try { HttpRpcClient owner = pooledChannel.getOwner(); if (owner != null) { owner.cancel(pooledChannel.getPhysicalConnection()); } pooledChannel.getPhysicalConnection().close(); } catch (IOException e) { log.warn("Exception closing active connection", e); } finally { this.activeConnections--; } } }
34.841297
151
0.675516
2faed00e75a345da692c3cab3d898cba7301b9c5
565
package io.walkers.planes.fundhelper.listener; import io.walkers.planes.fundhelper.entity.model.FundModel; import org.springframework.context.ApplicationEvent; /** * 补偿计算日增长率事件 * 计算为 null 的基金净值 * * @author planeswalker23 */ public class RecalculateNullIncreaseRateEvent extends ApplicationEvent { /** * 目标基金信息 */ private final FundModel fund; public RecalculateNullIncreaseRateEvent(Object source, FundModel fund) { super(source); this.fund = fund; } public FundModel getFund() { return fund; } }
20.178571
76
0.699115
5474858dddeead266ce06a1a97aedf48d9892f3f
28,651
class QbkZ1 { } class kfP { public int Ir8IgozDOrk4 () throws iv0Uurp77 { void[][] yACu = new MyUAcfw2eGp()[ null.bpwjFe6Ws8BE1] = !--!!null[ new SzOV8AfTgozX().qA9H9ADLMa]; boolean[] T6iR0 = null.Ar7; bkLwaqmtDKIhzw[][][][] klj8D; f[][] IiWrD0tbyCp; U.iNJkq1TJ5PX(); this.NQDC6xJyJmXCx(); { ; void _VZpzbM_jhvHu; int[][] YHzqg5m7; int B; boolean[][][][] zz; int[] GL80BTKfM; boolean[] fPoC; return; boolean[] E5WnPtDLqdTvuk; void PRbRVy; { while ( null[ -2[ this[ 83933.hfp()]]]) return; } return; int[][] msDSvrCtsIv75; UKSPDWXEj3gvle[][][][][] UY67l6q7; int RMHuBMpAlWj6hH; } while ( this.HOO()) ; int[] zPjFOwO3DN; } public void FSvgGiQVj; public mhJCzfzz Qyda_4HWw (void[] y, boolean[][] Q_WVSktKS9kQ, boolean EYG, Ech[] fd47bfV) { { int[] Q7gaUv95L; 42838.nLM2I51zUJH; } BnH[] mq = !-!this[ new Ye5y6KqaCJ().AYWnoYNn]; } public static void n7wBqNfq (String[] mkeO0OtWBG4) { if ( ( true.c6())[ new void[ -!false.KlyzspKzqhS2W()][ !--!!!this.kB4C8qpF]]) if ( !!jWV6gPc0.MTnlQwah()) !null[ E0ytpA.BAw4Ht()];else if ( --( 054032.K6).vS()) ; while ( ( null.kheD9sdU()).Be_4()) if ( !!--new ZT().F1_ougeJK4) -new n().wPXF8jTT6Kt(); boolean DB0W0x = ( ---null.Sm()).r7k(); return; ; int[] b; { if ( -teR()[ false.TgXU44iGxIYW_()]) ( new yy()[ false.czO8qY]).tV3b; int YUJSv; null[ -Zh5VFwFK().pfLI77p3LN9Qe()]; int eckUO8mMbW5I; void[][][] aOgDSjfe; while ( this.qYWfnnf53wut()) if ( new int[ new nuYZ1GFk8jc()[ omAc.T3()]][ this[ !!mhZJjNOSflIpy().jGyg2LncJ]]) if ( -!!!!gVof3mq_.SXlSoNYNO()) return; !null[ !--!34555138.UKvUiFvt0PA4()]; void bTwQxiS; ; { void[] rsS_Z3FJsu8; } if ( -!false.V) return; } void[] lWuz = -!( -81[ iZz()[ false.xL1okKl]])[ ( qd0Gqiqw().eOif3hfz).fiB7o()] = !!new int[ this.Li65Exk3MwKp()][ this[ false.lh3C()]]; void puKqjM; return; while ( this[ !this.hjR9yeFcqFs()]) if ( !!!null[ this.H1FSSwe]) if ( 06113632.Sb2yiM()) return; UV3VV[] oAq7y; } public PgP4[] JL (boolean thhAc2, boolean[] L, boolean[][] z9gz49_zZ8uzf) throws mlyPs { { boolean MVcWfwObSClWvJ; int[] x5TMOt9E; boolean YzhTZXlgq; { int[][][] FJYeIjoWpMa; } true[ -2[ -LmW()[ -false.BmyOZyXrO()]]]; { boolean[] smzb4amDnu; } { 78325479.sYwyGcjxm; } ----this.WTzk(); while ( new tmOtjnO().X0omE) while ( !-!( new boolean[ -null[ false[ 6208.j()]]].ev9)[ 1[ !!new boolean[ !8.lyxx90l()][ gDQjv26oWCHi.U2r8Q0C6uCHclc()]]]) { return; } null[ !new boolean[ new M5DJn().WFoxGiF2UO].qS7RKcZ1a9HXg]; int O; hQ().RrU3(); int[][] wbNb7Hzo; void DBWAZHCO; } return; return; knEA[][] Ve = dRJ().v5dQ = false.ory(); if ( !new void[ -!!false[ !this[ 8555901.bK3MnOZTSj()]]][ ---!!-8.uf()]) while ( !yJDNyIme()[ !( true[ null[ !--this.r]]).bHmqWZQ]) { void[] t42AA65hI; } void[] kUx; while ( !true.S()) ; void hmAOwZe6YF9LZx; } public static void jwzeSXKsT6I (String[] FIUjC6un5L) { void nG8ktkQPucr; cu JZ5OCSYxQJkxD; oIFPZZ4zNth e9QCQR; ; NgG[][][][][] VO = -true.hvKC_r0ZGzGR6() = this[ wTQvETDib[ this[ false.lKDb]]]; return; new int[ !this.ftw7o2sMjUg][ !( ( -!this.N91u).zwDEH9)[ true[ ( new boolean[ tut60lq.i7UVWz4].xH0t_Sbau).g13tAtXLJe()]]]; ; int[][][] lMhMlha7iSz = g().z0tlc; ; int[] MpD6Gt5ZnK8 = ---!this.Fj = !!K3Dx6Aer()[ true.q08pHvO]; } } class MKT19cbKxG5 { } class gKCXHX43pkwTk { public cUeuonD osimZWoz; public static void b_AV8 (String[] UOnaF) { { { while ( !-!-this.C6irX()) ; } int d; int[] Nr; if ( ( false.DVQW7b).UG4zxI8RBrj) return; { if ( DhSTr_UzLj.de) ; } n Sh; { { if ( !-d[ lp6X().rGK]) { boolean[][] odN1DbtjWOVk1; } } } void HtzDxkQBLtJK; while ( ( -true.sEsmTl7).FpakGSu9N()) ; void do; void cSdyGs5; while ( false.E58lBDoxp()) while ( new SJqcD1QdrUm().Pf()) if ( -new Plg()[ Z[ new int[ P6z().j2xf66_x6k][ null.W4jUDGR]]]) ; MWdMrtKddv1z L; boolean yeW8qSxI0f5S; while ( !false.vlig()) while ( ( true.NrCNBasfOf)[ this.bxyD8uHqi]) if ( !!45936024.YGO()) { void ULdTz1DySaHLfG; } { if ( 590.MxZLs_I()) this[ --!false.xUWMrzmX2()]; } { i89xwIYlYGPI7W[][][] fV; } int sHvh; { int eFycrAmYF3L9E0; } boolean pJYYptc; } boolean[] sSAKqd = new zvew4JV()[ !null.WnkcA7w3gIzm5f]; X6qz4zLiPXB Aw59DzVEv; } public A1hY[] INf () { void Di = new boolean[ false.Qtsp3d2()].uKEjd34o = -null.S_(); if ( null.mej7QZCcOe_Li2) if ( pMeE0qPAvjCRW2.VFQJ4) !-this.Gb0CsWK0lHJLU();else new int[ !q().Ax].amoAIeUCr; int[][][] qi6_x0c3KE = !-!false.d796p6uPIW(); int[][][][][][] Dcqd; int Eilx9; int[] WjPV6X6VP6; hr lAW9X9DFcHiKQG = 30.ymW7rs(); ; return -true.iV1; return; boolean[] io; { int Dx42Idsqa8; ; null[ null.K0]; } _ oK; while ( hVLQL2tme2ng().Ne2ritpIhit) return; void[][] w289QhviHMCj = -!!kGIcKjpQNwm()._mrcO5IU(); g[][][] c4viAUp_Aq_RT = --Cm2qaUIVt2GcB0()[ !!true[ !57629139.rB1ZVexY8Hirz]]; } public static void rl (String[] btYFd7L) throws GItBOH4jC { !-true.baHPFBWTz; void jRFlaGc8btEv = new CzJduoYEDgRY()[ -MdrWqqAFZu0()[ new oKCAZGhYw()[ null.CuKA]]]; return; return; iql1Hcff[] D88; boolean[][] JvEROTiZUxvv; { ; { while ( new E3RILBa7v()[ new boolean[ new iaYJl().YF6quBm6apWiE()].FFmQyfUwC()]) return; } !-new bIuKp7()[ i561iD().TVbSl6sWE2]; NHHLg14Oly[][][][] t; int A; int[][] c; while ( -new boolean[ TCcCG5q8P().p5VHL()].HiAT) ; ; int HR6kFT05QafaS; boolean[] qh; { true.ntnDb4; } } void[][][][] GZ = new HmIxKDtmHWQ().JkP2NbdAb1qVhR() = !true[ !false[ 99906304.Jzl2dGANB_l()]]; if ( b.QMV5I) if ( c6tc.kSwt2qWd()) if ( -Xzbp1Fifpfd.yK8q()) return; boolean Baeg; boolean gcJOkX = new k[ false[ new Lw[ false[ !-VNI()[ -!-!14[ new I8owhv[ -ImGNtSZUWep()[ !-!-31078[ iJS.Da05S4LZDoH2YF]]][ -!nSAYg().ajR()]]]]][ !8577622[ null[ -( this.hj81ASdgG()).ARFTCXYid]]]]][ new void[ new SEPmSvr097Q89s()[ 58125291.KfHwJVXlDs]].nGKK75] = new NH2B().d12O7gXSy_f(); { null.Gd3aA; { if ( qRLDYki.hymGKfZ5ZCa) --( dDlo8Ro().q9Ac9f61ADf())[ 7989[ -!!!null.Z7t()]]; } if ( !!!VA8u.Y6q3Ob7) { int oGP7_qNa1Lw; } boolean J8kyO; void[][] _XdFHnu1OC; boolean ofsDl5; void[] nAY5t74WWFr; } while ( eTiUhunh()[ new l5wUIGGwAYQru().Etk2tqR09aiL0r()]) { void[] xNQ7fUGnlOAnZA; } int[][] QdgRfILQCb0Tet = -!new XJHOJ_eULXpCqO().mDSsNl3LksZ_tP; { y dgrvF2p8; -false[ this.BmYU83hY]; { void pB68v0n_Q; } { !!-!--Uq91J2()[ new int[ 85724225.vwlYM()][ PZ0lfD().eEE]]; } while ( !( -4.aBO6Qgy_B)[ !!!( new jNBx10MBAEA3().KdV1rFm3Fpgho())[ ( -!!( !fupLqK.N()).XQL5eb7BV()).TAeBwnd7v9L07()]]) ; return; boolean[] A0leF; if ( null.JeJjLFonF()) ; while ( -!zFsu.ObxNyJ43A) while ( -!!!( -null.medp9).b77GcX()) return; boolean yv; { boolean[][][] Gy2HSB; } return; bRpi4pdAF1tEWJ Bz3sKh; boolean[] U1; ; if ( -this.eJHlJRkuqkq0Mi()) while ( new void[ -!-!( !-false.jtw1uTRv).hPepWHQU8zI_jv].Egc2PbUOexG) ; TH[][][] waoYXXpMK9c; boolean cxeDeRFRsHrL; while ( !true.EgEnqa) ; P585o8Jl4[][][] cqN; } return -( this[ false[ !true.NHw9y50sC_]])[ !new rl7lxZpJj[ ( !2733322.v()).Mgk()].xraaukARz9()]; } public void[][] R (Lc3wks mmglqhz_n3, kbfbMUKbQ4qz6 jMW2) throws w { !y().bij0qaGCKuG; return; if ( olTSZxJ()[ S5brEw2ki4a5Ea().eClmUYRltGg()]) B()[ !new boolean[ true.Q()].ePId5()]; } public static void dMD_lsQDh (String[] NW2z8R2hS) { ; if ( UdIDpf().HNePMEQeU156) -new boolean[ false.b5jRJiGM6tzLtd].Bk; boolean[][] qlB921v0UA_ = !( null.gF).Six0YEj2sT(); DaONObMvNN58[] wAJmY; while ( -!!new XtbTDl[ -!!---!-!!678[ ( new kGF5mjSq[ new int[ 71447[ ---false[ 65903[ 67921.ipbdKz4AO()]]]][ --null.hmVUpgPFA9iS()]].c2SV())[ !--new N4Jyem3k[ new DZZPApMUiFDZ[ --OA.LaxIU()].F_ti_].SpKIjuB3tn0Hk]]].QeZL4RBa6e) { int kkG; } cCd aMCxST7CdjgmT; boolean EItgg; while ( false.U4CX1VQ()) if ( -!!!!-false.nz8sbzIiprLt5) ; ; if ( !09[ !!!-w8PrEXzMc9z3u6().k5ocCt()]) --false.Fd3g8oaNiVV();else ; void[] G7QSILff = qIYO()[ !!!!this.CvEc()] = -!--G().W1M7oSz9Eu; { --false.E3xmWFpjN(); { return; } boolean[] XtE8; ; ; WpUC[] Vb9ypf_n_; while ( !-this[ true[ ( new int[ true.o4K1hPuL].F())[ -( this.Q)[ !MaU1.V()]]]]) while ( -LWPcOiLr().iUDmvoaa7hXt()) ; HcuZ929xbg_[] AKTFF5Xz; void[] ZatJf0HXjWt; boolean[][] tr8AKPcaaa; if ( !-true.GF()) -!!!--!new t0vh().K6Pi; boolean[][][][][] N; if ( new h3lozV()[ !ptZU6C9BoZlMPs.HKVbBHm2p]) if ( ( -VRxB8X9qt5[ true.THO()])[ !!---!-VxcuU37_9Jsbdy.tedjV32YY]) ; return; int[] KfVvX8NQO_l; if ( true.Qp) return; if ( -!!!--!--true[ new boolean[ !-this.U6].hEb1UM6Z_UZ]) return; return; ; } if ( new fWTV_uqZoa7()[ true.qOF()]) !--!this.CSmaV();else { void[][] geFtNBb25Y4Mqk; } { while ( -this.o9N()) if ( s0iuD().tKsx()) if ( this[ ( !-!( -87556165.KvqwPkMUrB).Z).xJuAsXYdmG26]) if ( -!false[ new int[ false.zJE].Zdf4kLfJNz()]) ; void[] t9y; void Yx; X[][][] h5xw2; ; if ( !-new int[ !new x[ !-this.nIz5QMih()].YmEVE2J5MFv7TC][ ( --null[ new Dk9tXk0yPU[ null.JF74DipN()][ this[ --!---!_iN.O()]]]).u1lqGVZFj_Mnr6()]) !-!-( !508156887.mDZg())[ new boolean[ -this.Mn][ --new fyIfpNt().STVKOBMO1w9Q]]; !!yy2TcZDlB2JKFm.gBY_tZ(); void pV9XbSfSE; boolean[] EdE6qd; ; if ( !T.xjGNQD10QJk()) while ( m.QPUMYT()) { if ( new nKgJlocY5().Vz) while ( !-21[ null.u006akfrsuq4EG()]) { new bwreqSpH[ new xs().NXoWwn_BcQLKO()][ --!!true.uv1g1mI3Q]; } } VUD _r5NUUaJnS; boolean _FNh_Rkbv0D6vy; while ( !null[ new void[ !false.xiqw7iBvw()][ new ARitZYzob().yCBUrKQ]]) { void f25; } } int[] QAKTM6akx; void pgL = !MUPMc[ -true.BTILFZHK49c4bR] = false[ xMgZ6Ud.JZH()]; } public void CqiV9adWjHg; public T7yPSVYZU[] h92NSYC; public boolean[] f7dvfLiP (void[] znLg, void[][][][][] X, int[] aIXYGQ3fR7M, boolean[][][][] ZAnQG4, void keT) { while ( --( !!-!-( JOQTl1XY5[ ( new pNpsBzha().M_Xt7lB4pdm4C).CcAEMO()]).kdEXp()).KoUMJToDMPTBXo) if ( new void[ this.Yjd97vUSMuja()][ null.FvwvQbKomkAPd()]) while ( -new ti6bHH()[ -!new W_anzo().Ysh]) { boolean[] FmuGt0zo2; } int tfnwYrWiqP14a = -!!( -null._l70DZEM).yMUfpvd(); !!new JMHBTw[ true.AVEPL3()].igYRVgjO1CI0(); ; VKId[][][] o1uPD = new void[ -this.Uj0FetU7ND4()].sNQpiuNiemuF8() = null.J7bjkfG; while ( !true[ fUL_nLc7zmyZb.AUE0lafKYglj]) new boolean[ !new void[ new int[ new PJsOJnbsjw[ true.mxLvaY2sAMCDOU()].T1qUCoLXRhPeBy()][ -true.d()]][ new int[ -new boolean[ this.xP].o()].xokG0UBdSzcdH()]].JvrXcTz0iqOKOm; return !-!new KYZynwow().pW(); int[][] hKDTjJ7; while ( !-!-new L6HlPbFQ4nqz4b().jcE()) while ( !!GFtnSjR5ws4().sI3bdWY0FS()) if ( null[ ---eLEYjt.wKSkCxSsrXFjH()]) { -false.Z_bR2gzY; } { ; while ( null.dUmUkTqcCvBhaS) return; int Ki; int[] T4_NGE; qVx6T0E8B[][][][] IimDV0at3; if ( this[ new o().cGZVvmNJ6vA()]) if ( -!new boolean[ !true[ null[ null.ObNUsl()]]][ ---vL4iwjm3tr8D.HtZrT6()]) { if ( O.uj()) return; } int[][][] hUPDVXzt; ; Y5PTGFFSxs07[] PPizN1n; null.X9q; boolean[][][] wNFA3f4RWu; void[] BR; int[] EXeo7x; void rp0YB512f; boolean[][][][] u17d5UH4; } } public static void qfY (String[] df) throws ysWVyJ { while ( -!xw7i013oI0WU5u()[ --false[ -!true.BZpNetlhfjH2h()]]) { if ( -true.trxeGcNUVLAIw()) eyXG719i6rt().v_0U9Y7aC3(); } if ( !false.grQ()) !!pt.oo2EcO6QdpgR();else ; boolean[][][] RxqWtIS_aB; { void[] STK7nK; int YFLe7xkdDxQ; if ( -( new g[ false.Tl1JjOZ0IqQKy].wU8ZWo()).RfeJeTPx0wLpD) return; boolean wjrF25X5BdrK1; int ocf; return; R9IivNlNrZ8[][] qcxa93Abzx; return; void[] Kl7xDJilEWEf3; void QL6; int bGhEJYtsus3yU; 4[ new int[ -!tkCEW().UVUJi6].L()]; boolean eK3Cqmg; XEU6.e8TxllPfdSML; } if ( !this[ --!-!wxf5gYIO.gSj()]) if ( null.tuhsbDIP()) return; ybrQjfA4Sv5 mu0ku00gY = new Yod()[ -null.gESzIM9V3X6hl()]; void[][] cg9f7Q7 = ( DNPt3Zlmg6.b18tkqxMJ_).PPoJ4(); if ( !!false.QFp6LLOW8_VKgt()) { a[][][] XUH; }else return; return; boolean w1LL5fVvXbTDDj = !( -!!false.qZ19FEH)[ new void[ true.QR()].kv] = ONQbVKN.a0DTp_s4g1(); ; tQ2ZvnK6G7nf S; { -!!-!null[ new boolean[ -!false.TVFhsfJzN7()].Aw7]; void z1wDnkKYB3H; if ( !019941390.Vhb) if ( !new sYMRDIMGt().w20piUbFao()) this[ !-!( --!Jg8n8kfvOuM().jM).r2igINRQ]; boolean Go2oQ5; { if ( XAMutDp().ymMCw5lMfq1nU) { { void[][] aUiEk99; } } } while ( Bm.NNIVOPOblRa5_) if ( new boolean[ 095926612.KI6()][ !!!this.vTTye]) while ( -516595830.wgKdspLL3zzuYB()) if ( aqIxdtF.QJ8j) ; ; void JS; return; { while ( !!Bdf0kCes[ !-true.qk31_kPo4]) { !-this.OToynJK7_; } } int GZZX6Eew; while ( DqqedlymnwGA[ !-new int[ sxoTbBT.Dk6()].MWN3qtZ]) while ( --false.fzPJQ0K2) while ( 495988.O()) while ( ( !-!true.p()).HSR3LRWT17vKg()) !---!-!( new void[ -!-!!this.j2GUll].CQdEkQC6bk9Rs())[ IGE.a5mK3rR3zV]; { int _1; } } if ( !!---Lb2UmmsfBrm.TKFTSKGf4m8rk1()) return;else if ( new yQZN2Tu()[ -870373[ !----p[ -!!!!cFWeL4atlMp.oV5t61_IIq()]]]) false.VM; boolean VfMuv; boolean[] QHDwl; void[][][][] uF_nHrZyb; } public int[] yaNEGVKv4qrk (void eSPWxJp, void[] tzoOrElHX2bdG, int BvWR_1L4N8X, int[][] aawbu, void kwVUNJSrGT9B8y, boolean K) throws Z66f { boolean[][][][][][][] ygKO1PQf4k5BT; boolean E1ZJRkLq = ( --367.g6k9xcu0X4XmGx()).EMS7wsjsY() = null.JBxxZphu; int[][] ip; ; -11799.cdkC9Pn0X7fr(); boolean zSkmPnxwymk_Dk; return ( !new F4i67kQ().auqhwzBDTLv)[ ( !se0q15SALmG[ !( this.PNLPwdp)[ !!--!--!new oNWcwLV[ 11996783.D5wqwU94u8E()].c()]]).YOdRQRUZH7F()]; void[][] DtCaMQEL2VXRg; boolean[] ZIhuhQdh2nx = !!-IIs8K[ null.zv()]; } public void[][] WSA5xoFuR7OlX; public vN3M Sv53lf0 (boolean[][][] GPhm_b3d5e5, UsR8Zsz[][][] hBxWj1BqlMW, int t0dUpS8SN9E) { eeb xzm = false[ !!new eus()[ new int[ !new G[ !-false.BIw3WMBVD5u()][ ( --!new jbv().KnNTK).SOkVI9NN6UWuTW]].sn6oMoao()]] = 13400.wS3HI1dlFrTS; return ( !null[ -li31gL().GGIBiyTXo5bHe_()]).odeE2N2W7(); int[][][][][] qSNHgD; T SFCbGYybx16 = b8IWI().A6rMELevQUI(); { null.nV; if ( -jTr5rijr_H1dD.Z) { return; } --vWxB5t()[ -null[ null.oRY()]]; int[][][] r9A2mJ6jX; int[] ZiDL; if ( new boolean[ xvvyvaF8KxpEU()[ !true[ new G6WO().tiG94ji]]].T()) { ; } ; { boolean QX7F; } void[][] K; vINPmjxADv4[][][] jpceURcKH; { if ( ( -!-!!true.A44gSaZX).Vq6n()) ; } JnDklnsrZE0e bF9E; ; { { ( rSuKs5eybQOHz8.kQctx()).rYyzaGZdDqSY(); } } if ( !4543.rwgBl) while ( -!eYG3GF0hH().N7M6VL36fUWq()) new iFT[ !null[ true.IbpiqGl]].a4xCsOhZiImz(); int[][][] L; void a2TonG; { return; } eU[] ACMlSumMe; } boolean[] uQ8BMwX; return; boolean hbm3ouno = true[ -this[ -this[ Ya1Ei().eNpoqkIhK()]]] = 190769382.BLM89D_T5Iaps7(); ; while ( -new int[ 6761637.ZHRvb1Cz].nOdSDhW0) !!new int[ !-false[ -this[ false[ -zepl7mcF().Y2RmMsjUy0X()]]]].dgtqN; Fwr6yB tRJ0nRmX0N; if ( MazY6LZ3yonq[ true[ tKpp_0.o2qUSUyPeW()]]) return; void d2gj = !94.BHv9SSW23; int[][][][][] c7IMWjqxaPSC; } public static void Lpln2B (String[] LFXzp) { void[] F27Xot7kTdJKf = !76439037[ !!!!!null.FHRCQA1Mt()]; int[][][][] RloCP_0Sq6sLh0 = false.HeAUjK_R() = stdTThHjBSHu[ ( -!FLOpCtX8rT[ --new int[ false.WbGDVFJDO8ggP()][ --!4.lNXaMqsKr6TnCt()]]).HJv0]; int[] EC; wHuzj.bxApViBcn(); return; void[] N6eeYhKPA6aDv; int[][][] pRoY = new KLnv().x8(); int jdO = new void[ eVTggHhQ.Bmlq].LPiNrPD() = !--!!fII1cL4n1.LqBi; boolean[] QQb5m; -zf().fXIJ7; return; EfDxtG[] BsXlJ; new boolean[ this[ H5G1b_TBrRdMA[ true.EkJghGgTaFsHTx()]]][ false.sldL]; boolean[][][][][][][][][] hB2zM7ikiXag; } } class tDO6IUJXTv5 { public static void impmNSQ (String[] yY) throws d { !false.elw(); if ( new SYMbXRcQCW2A()[ new z().D6wCUayCTf()]) -this.wbQpLFDuP; d2FGIH F2R4 = new e2F4dkHbKW().ekWx7jVgNXBEI = !-( !--!true.Vrgc_Mqzm).aCXd(); void[][] gMxR2XG = new int[ true.MZ_EWluiYM_EHO()].Dy(); void cwa8MoC; ; while ( !720489688[ igvTUFLn[ ( !-!( !wPAPOt8().yeHzh())[ !( -this.IHW2ch8KlENs()).C3DlO3fdDQLpU])[ -nz()[ !this.H4ivRjN()]]]]) while ( null.mKF) false.GWVhcxRKj4x; return -!new int[ this[ !-null.OybmRdr()]].cimDklRK68Lx6(); int vzHtAhBH; h5lulIHClqrG[] S7GLrLMKvT_0F = !33486._nA7B_MVVo6gDg; while ( !new boolean[ ---true.cLe3sBo0p2].a()) if ( !-!false.PD6HQfxMJWF8Yo()) while ( Kbcrv1tjJZElXs().sYiH()) { ; } ok7J6sg8 A95Vge0r; int gmdqKV1YZDZzni = I().VmoKvyJpD(); { ; while ( !--!-AYz7LrPyJO[ PPpCM5wjR.hd3yepUgaA]) ; sVZwau[] _o7qSodBT20; int[][] jopj1b6T; } return; ; } public static void lY (String[] Rj8J_) throws ZGMG3 { boolean[][] WYaThwJfVmpTy = !false.hLib_vOA; 970083.liTHXVYbbr1(); boolean[] vHIMct2kV; if ( ( this[ this.Mtx()]).ddA76) -null[ --null.GuVC];else return; void DBK3A9Zmt5wR; jnjJe4v ZvbM = !--this.H; boolean H52zzGZPB2y3Xv = xPXKM.a8Z29AGC() = !!-true[ y5qbJd_aTgC1pf()[ false.AIJW3wpF()]]; while ( GEVT8O[ -!-A1KhjEF3u()[ T_h[ -true[ !-null[ new void[ null.w9BIfbM].kDeLr7nB]]]]]) -!qJz().Yv2dJ_unrzU7P7(); ; void bE; true.H548iRvWL1bf; boolean V6JZQiTGprpFs; while ( !( new w12Jbhetx41r2u().q())[ -!!-this[ !rcvfDxar6D6H.MrrxAC6()]]) while ( !( new boolean[ -( this.hs())[ -!false.yWA9qJpf()]].oEIHx09k).s2pOPAq_jReIs2()) while ( --BodacWLJ2()._v()) while ( !( null.rVnOXYnV1Z()).CxliC4Fq) if ( true.oPS9XfDjDmR2()) ; int[][] SSJ0gywwl; int[][] aTFViP9JB5ON; if ( !-this.j4kjEkZb) ;else while ( new _cEbu().XPFfLHCzLtJEvB()) return; } public static void rFuJiCLQBg4Cm (String[] Pt4BxUqN1) { return; return; boolean zMOR5vAHIkfBjB = !new s1RUqfv3k2B().JlXNScwyQj() = !-( ( JzCzGUHDgq()[ !-!null.XlcgijZq]).b388ZaME1g8C).lQnN0NMq2wcrtU; return -new A9XlQv3VcSUz[ ( -( -!this[ new YIfv3()[ pK0R4Az()[ -!( -new R8ZrK().uelS1RHymvfoAI)[ -74[ 101278.Tu8olx5PKaY_xy()]]]]]).YaXU)[ !-!QzMdIkd_x2s20U().K]].mu0f7BbAJ; if ( !-null[ -( null[ -this[ ( -( -46.sRz8ue9Ms_UBKD).eJqC1).ifRPBPOa7iOS]]).KQ()]) new int[ --!new int[ new boolean[ true.jC3oSQo8D()][ new H7ZKyFPpMd().dWEDNrt2]].zJWnpbdu][ !( HJ[ -!-!true.TEaZS])[ false[ new boolean[ new boolean[ null.hG][ !296923238[ -!this.tAyFu]]][ --this[ !false.NjN8zfo()]]]]];else { ; } WwDGIzKqJjo6[][][][] q76htNFeqLM = C().Cv = -!CSmc.aqxdN7q; { while ( ---!new UrofqnpvCZd7().St()) return; void ZdEBqh0k; boolean[][] xl; hbIs[] y; } int w1BG81hTeI; KNpZ().OvWgncHYcSE6rp; !-!( false.QNV2aS9F())._x7ePji; } public boolean[] N7SZbbSdj; public int[] h0NW; public static void yfM8PphU (String[] x5) { boolean[] Y_ = !!!!true.Z1WeyjHtBD() = -!_()[ KC()[ new int[ -this[ -Njnf5t60n.bCz9HzZ4SbOA]][ !!!this.BnYZa6XnmWd()]]]; return this.HS2; while ( ( null.cdk8XUz()).ti8j1) return; void Q99CM5x6OsPa; ; while ( hF()[ !( new boolean[ -new boolean[ true.lQyetFDu].Y8GbAzb].K).djlAaHvoQp9()]) while ( new WeCyz2[ true.K386()].GvRsdHYdJ) return; int[] pLeHuAsGX0nFn; void Yl5lKRHlKs; boolean pkVH7HIou = -886644[ PFKJ0st[ -GHG().DkC4h5iT9()]]; { if ( new int[ 14020[ new qQgyEa[ --bKtCum().ABVB7b7b7K()][ !false[ !this.w8DRbm6_z_kyd]]]][ false.ob]) ; if ( new iX().bUCCrO9PJ) while ( !true[ new Bvwg()[ Iqy.uu9lwQ1q()]]) return; } qmuC3h[] vVe9P5 = 9169.ae(); return; boolean[][] Jta5tzt; false.dM; null.fvDyJ; void VEZGqIYoZ; void CZFqS3JkMfb; if ( true.dIsduPo()) !Qywo9zpOyjMzY().VPD;else if ( true[ new s8WnJ5P2T9().S1IQpvrph6()]) return; void[] HCxX7Ag9PAWbtu = -new int[ this.uCyN69aIA].KA2jyD0wF0q1UJ() = this[ -this.o7hRE()]; } public boolean EeK0lR () throws Y8MF { while ( ( !null.Wi9q)[ dcbVRHj9DhH8Y().pUqb9XYki]) return; if ( CG0vZc16syz4().p0GAI1nma0hO()) if ( new p6AZjdHjZmStG()[ !BuBKR.l2xq]) return;else if ( -true[ ( !nhL2uzY2WcXh().s91())[ -915932.z]]) !!!-!( !( ----new IIB()[ -new O[ !!NX6LSp87KvC1wC().okadyxarYba()].kjFp]).EGmARiT()).nFkTdxhrl; int[][][] snNvJ8N6oQdfV = !!---( new void[ ( -!-!-new gxz().dF()).DOk()].yFl2HYEBBdv()).cev(); ; ; if ( -new gMpcvN().idR3xFCa) ;else if ( new dYH3u3V6be[ gUOEA.Za3qW()].TQlhok8UftBkE) while ( -false[ -null[ !--false.i85s]]) while ( !--!false[ mJGHekIS()._r()]) return; while ( !!( ( true[ -new boolean[ !this.qvwzPTCI7wwh()].sktk8()])[ -new int[ !gtdvnefT.y1dz2Vo90TTVU].gdrYBJGGg()]).s1Tq3AQ_dWlB()) return; return; int[][][] rcstp9AjEIL; boolean dkZZPYOyKJTHhA; } public static void bJowyqT0VmiO (String[] oTNzPZPXlH) { ; return; new void[ true._].Kn91iO8nkC(); while ( !135364669.SxTckixkh()) ; WvM CzJgq = !-( 9.rvws())[ true[ true.XAx0aH()]]; void[] S5o8DO4Fbjq = --null.VT8VcB9wYe3z = !!!!BN[ -true.pMz()]; !( !JScKRXO().IpPyJpzWZ).D(); Ud9 xwm9Ngf9c79i = true.IBMr; boolean[] VHTdVocNE = U74ARFWnmy7INS()[ !!!( !-!true.yRqC())[ !-new SRG0lS_T()[ !null[ Q().EZX3tU()]]]]; jmBqzwsVR[] Ahw; boolean[][] uG__; } public int[] TOtVU3o5lIE () { if ( -true.h__E44A2wmuB()) ; int[][] AG3_doyQ_CA8; { int p3uxqsTk; int IgIdXdH; boolean _lOiYI9q3; boolean rIUT; void AB7B; void[] E; while ( ( true[ -this.O]).wr7xHTMQi()) return; LW6Zg2uOw oMI; ; while ( ( ( this.DI7pZP)[ ---!true.lJwUpOXmESBP])[ !( null[ 014[ !oq4_x.pcP0()]]).Sli]) ; } void[][] ICAga = true[ !true[ -!--true[ new O2bqdBBLVrL().dp9I3cObJ7PY]]] = -new baJrqzvo().X(); ; while ( ---null.zgFS()) { void Z4uN; } boolean[] dWFp5o3bhCIq; boolean jSuDao7 = !-RvrZ().Ks9jpAtYZnU = g()[ -!new boolean[ !this.tKkhjrz].TXSk2]; TpO jB; int[] rXdLwGu = --!!!false.O2VrGTsBQ93Oj0 = new int[ new int[ this.F8i].PNcayZQbrlZ5].FX4WV3Fuis2bJb(); return -( -true.FfjM)[ !true.HF()]; void[][][][][][] mfho9Ql1; void[][] Gom5C68; void[] pMNkya = this[ null.w4stCbuNsEg()] = XaNHzw0lYK.jCG6; boolean XNTIdXqztQGXc = !-true._x7; if ( new z45WkollJ2KCa().gseWyqUHH()) while ( !new int[ this[ new gVkzDX6e0().klPTRbX1()]][ ----new xqUv().d53h2a]) return;else while ( !rEVZIs6RvUb().VhBGQX2pR()) true.SaNRShhLDN; ; while ( true.rsn()) while ( ( OAmkczm().qm8ZDnNIwpgomS()).VnwcdBHQ5tELsP) if ( --!K().zdYP1mK) if ( this.zs11()) if ( eann2V0T[ new nVlEyz()[ null.SLwpqtH]]) while ( !true.JMavcfKVMro()) ; XFkKo2ogaJ tJx11zUI16LNm6; } public boolean B6; public int[] qNbdNMyAp (g53fQf0RQP[] Rt6tJMiHyN, void[] ATtFZ0Um, LDm6C UqdPoNHsB) throws raYj5zmBqCoVav { while ( this[ !---OY0ENYe8i7nDo.cgkfbNNLW()]) while ( null[ -( !!!-bkDtL6.Q).Y0bhx()]) if ( 13.IyBR0ySKe()) while ( rqy()[ 056835._XMcQ1CM()]) while ( -509165[ 09435069[ --!this.ahb5Lx9COlQVUv()]]) new YYGm4Al87()[ !-82891228.fC3Cm_l3aF6A2F()]; if ( ----new bK5fWbf().NxiR_VhN5b) return;else while ( !( --this[ -!new gO_ioSilR()[ true[ ( 795046620.B).L5Sle()]]]).nkYMYB()) while ( this.hbxLN()) return; void[][] g1_; { boolean Gv; esWvfiKdBJi().SzyQQMZCgNor0q; while ( !new wSNJv().viMKFHIl03c22) while ( null[ -M1ZzVwC.YR]) true.MkHWwoEJ; void RMh; boolean IFz4L6ul5c7vH; int vB52; if ( !!!l5aLJ[ -this[ !fWBMjVLM()[ true.qZfoRtK()]]]) ( false.rUHxj1()).cg(); } ; boolean ehKJEBU; GRg[][][] Pht; } }
41.826277
319
0.493979
7c1c2ea946584464ef6c6d161491849c21d47ce5
2,621
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Creates an explosion by changing images when someone is hit with a bullet and plays a sound * * @author Barry Al-Jawari, Betim Goxhuli, Edi Imamovic, James Lay * */ public class Boom extends GifActor { int countingDown=0; int lagga=0; private SimpleTimer timer = new SimpleTimer(); SoundOn soundon = new SoundOn(); private GreenfootImage image1; private GreenfootImage image2; private GreenfootImage image3; private GreenfootImage image4; private GreenfootImage image5; private GreenfootImage image6; GreenfootSound booms = new GreenfootSound("boom.wav"); int p1 = 1; int p2 = 2; int p3 = 3; int p4 = 4; //private GifImage gif = new GifImage("explosionn.gif"); /** * Act - do whatever the Boom wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void Boom() { image1 = new GreenfootImage("Explosion1.png"); image2 = new GreenfootImage("Explosion2.png"); image3 = new GreenfootImage("Explosion3.png"); image4 = new GreenfootImage("Explosion4.png"); image5 = new GreenfootImage("Explosion5.png"); image6 = new GreenfootImage("Explosion6.png"); setImage(image1); } public void addedToWorld(World world) { setImage("ex.gif"); //You must use the setImage method and not just right click + setImage in the GUI. } public void soundStart() { if(soundon.Sound=true) { booms.setVolume(100); booms.play(); } if(soundon.Sound=false) { booms.setVolume(0); booms.play(); } } public void act() { soundStart(); DeletePic(); super.act(); } public void switchImage() { if(getImage() == image1){ setImage(image2); } if(getImage() == image2){ setImage(image3); } if(getImage() == image3){ setImage(image4); } if(getImage() == image4){ setImage(image5); } if(getImage() == image5){ setImage(image6); } } public void DeletePic() { if (timer.millisElapsed() > 500){ World world = getWorld(); world.removeObject(this); } } }
25.201923
111
0.542541
5e973c419b82898da55af50483d6fa2977089db3
2,453
package com.tramchester.domain.presentation.DTO; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.Nulls; import com.tramchester.domain.places.LocationType; import com.tramchester.domain.reference.TransportMode; import java.time.LocalTime; import java.util.Collections; import java.util.Set; @JsonTypeName("DeparturesQuery") public class DeparturesQueryDTO { @JsonSetter(nulls = Nulls.SKIP) @JsonProperty("time") private LocalTime time; @JsonProperty("locationType") private LocationType locationType; @JsonProperty("locationId") private String locationId; @JsonSetter(nulls = Nulls.SKIP) @JsonProperty("modes") private Set<TransportMode> modes; @JsonSetter(nulls = Nulls.SKIP) @JsonProperty("notes") private Boolean includeNotes; public DeparturesQueryDTO(LocationType locationType, String locationId, boolean includeNotes) { this.locationType = locationType; this.locationId = locationId; this.includeNotes = includeNotes; modes = Collections.emptySet(); // deserialisation } public DeparturesQueryDTO() { modes = Collections.emptySet(); includeNotes = false; time = LocalTime.MAX; // deserialisation } public LocalTime getTime() { return time; } public void setTime(LocalTime time) { this.time = time; } public LocationType getLocationType() { return locationType; } public String getLocationId() { return locationId; } public Set<TransportMode> getModes() { return modes; } public void setModes(Set<TransportMode> modes) { this.modes = modes; } public boolean getIncludeNotes() { return includeNotes; } public void setIncludeNotes(boolean includeNotes) { this.includeNotes = includeNotes; } @Override public String toString() { return "DeparturesQueryDTO{" + "time=" + time + ", locationType=" + locationType + ", locationId='" + locationId + '\'' + ", modes=" + modes + ", includeNotes=" + includeNotes + '}'; } public boolean hasValidTime() { return time != LocalTime.MAX; } }
25.28866
99
0.648594
1023fee069d73bf5aec9222bb77864b61083b25a
9,966
/* Copyright (C) 2013-2021 Expedia Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.hotels.styx.client; import com.hotels.styx.api.Buffer; import com.hotels.styx.api.ByteStream; import com.hotels.styx.api.HttpInterceptor; import com.hotels.styx.api.HttpInterceptor.Context; import com.hotels.styx.api.HttpRequest; import com.hotels.styx.api.HttpResponse; import com.hotels.styx.api.Id; import com.hotels.styx.api.LiveHttpRequest; import com.hotels.styx.api.LiveHttpResponse; import com.hotels.styx.api.extension.Origin; import com.hotels.styx.client.connectionpool.ConnectionPool; import com.hotels.styx.server.HttpInterceptorContext; import com.hotels.styx.support.Support; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; import reactor.core.publisher.BaseSubscriber; import reactor.core.publisher.EmitterProcessor; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import reactor.test.publisher.TestPublisher; import java.util.concurrent.atomic.AtomicReference; import static com.hotels.styx.api.HttpResponseStatus.OK; import static com.hotels.styx.client.StyxHostHttpClient.ORIGINID_CONTEXT_KEY; import static com.hotels.styx.support.Support.requestContext; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static reactor.core.publisher.Flux.just; public class StyxHostHttpClientTest { private LiveHttpRequest request; private LiveHttpResponse response; private EmitterProcessor<LiveHttpResponse> responseProvider; @BeforeEach public void setUp() { request = HttpRequest.get("/").build().stream(); response = HttpResponse.response(OK) .header("X-Id", "123") .body("xyz", UTF_8) .build() .stream(); responseProvider = EmitterProcessor.create(); } @Test public void returnsConnectionBackToPool() { Connection connection = mockConnection(just(response)); ConnectionPool pool = mockPool(connection); Context context = mockContext(); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); StepVerifier.create(hostClient.sendRequest(request, context)) .consumeNextWith(response -> response.consume()) .expectComplete() .verify(); verify(pool).borrowConnection(); verify(connection).write(any(LiveHttpRequest.class)); verify(pool).returnConnection(any(Connection.class)); verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin")); } @Test public void ignoresCancelledHeaders() { // Request observable unsubscribe/cancel has to be ignored after "onNext" event. // This is because Reactor Mono will automatically cancel after an event has // been published. Connection connection = mockConnection(just(response)); ConnectionPool pool = mockPool(connection); Context context = mockContext(); AtomicReference<LiveHttpResponse> transformedResponse = new AtomicReference<>(); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); // The StepVerifier consumes the response event and then unsubscribes // from the response observable. StepVerifier.create(hostClient.sendRequest(request, context)) .consumeNextWith(transformedResponse::set) .verifyComplete(); // The response is still alive... verify(pool, never()).returnConnection(any(Connection.class)); verify(pool, never()).closeConnection(any(Connection.class)); // ... until response body is consumed: transformedResponse.get().consume(); // Finally, the connection is returned after the response body is fully consumed: verify(pool).returnConnection(any(Connection.class)); verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin")); } @Test public void releasesIfRequestIsCancelledBeforeHeaders() { Connection connection = mockConnection(EmitterProcessor.create()); ConnectionPool pool = mockPool(connection); Context context = mockContext(); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); AtomicReference<Subscription> subscription = new AtomicReference<>(); Flux.from(hostClient.sendRequest(request, context)) .subscribe(new BaseSubscriber<LiveHttpResponse>() { @Override protected void hookOnSubscribe(Subscription s) { super.hookOnSubscribe(s); s.request(1); subscription.set(s); } }); subscription.get().cancel(); verify(pool).closeConnection(any(Connection.class)); verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin")); } @Test public void ignoresResponseObservableErrorsAfterHeaders() { Connection connection = mockConnection(responseProvider); ConnectionPool pool = mockPool(connection); Context context = mockContext(); AtomicReference<LiveHttpResponse> newResponse = new AtomicReference<>(); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); StepVerifier.create(hostClient.sendRequest(request, context)) .then(() -> { responseProvider.onNext(response); responseProvider.onError(new RuntimeException("oh dear ...")); }) .consumeNextWith(newResponse::set) .expectError() .verify(); newResponse.get().consume(); verify(pool).returnConnection(any(Connection.class)); verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin")); } @Test public void terminatesConnectionWhenResponseObservableCompletesWithoutHeaders() { // A connection that yields no response: Connection connection = mockConnection(Flux.empty()); ConnectionPool pool = mockPool(connection); Context context = mockContext(); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); StepVerifier.create(hostClient.sendRequest(request, context)) .expectNextCount(0) .expectComplete() .log() .verify(); verify(pool).closeConnection(any(Connection.class)); verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin")); } @Test public void releasesConnectionWhenResponseFailsBeforeHeaders() { Connection connection = mockConnection(Flux.error(new RuntimeException())); ConnectionPool pool = mockPool(connection); Context context = mockContext(); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); StepVerifier.create(hostClient.sendRequest(request, context)) .expectNextCount(0) .expectError() .verify(); verify(pool).closeConnection(any(Connection.class)); verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin")); } @Test public void terminatesConnectionDueToUnsubscribedBody() { TestPublisher<Buffer> testPublisher = TestPublisher.create(); Connection connection = mockConnection(just(LiveHttpResponse.response(OK).body(new ByteStream(testPublisher)).build())); ConnectionPool pool = mockPool(connection); Context context = mockContext(); AtomicReference<LiveHttpResponse> receivedResponse = new AtomicReference<>(); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); StepVerifier.create(hostClient.sendRequest(request, context)) .consumeNextWith(receivedResponse::set) .expectComplete() .verify(); StepVerifier.create(receivedResponse.get().body()) .thenCancel() .verify(); verify(pool).closeConnection(any(Connection.class)); verify(context).add(ORIGINID_CONTEXT_KEY, Id.id("mockorigin")); } @Test public void closesTheConnectionPool() { ConnectionPool pool = mock(ConnectionPool.class); StyxHostHttpClient hostClient = new StyxHostHttpClient(pool); hostClient.close(); verify(pool).close(); } Connection mockConnection(Flux<LiveHttpResponse> responseObservable) { Connection connection = mock(Connection.class); when(connection.write(any(LiveHttpRequest.class))).thenReturn(responseObservable); return connection; } ConnectionPool mockPool(Connection connection) { ConnectionPool pool = mock(ConnectionPool.class); when(pool.borrowConnection()).thenReturn(Flux.just(connection)); Origin origin = mockOrigin("mockorigin"); when(pool.getOrigin()).thenReturn(origin); return pool; } Origin mockOrigin(String id) { Origin origin = mock(Origin.class); when(origin.id()).thenReturn(Id.id(id)); return origin; } HttpInterceptor.Context mockContext() { return mock(HttpInterceptor.Context.class); } }
38.330769
128
0.681015
5c1cf23fae95053b3694583cc00e05d8c1685633
585
package com.gupao.proxy.dynamicproxy.gpproxy.client; /** * @ProjectName: DesignPattern * @ClassName: Test * @Description: TODO(一句话描述该类的功能) * @Author: tangqi * @Date: 2020/4/24 1:12 下午 * @Version v1.0 */ public class Test { public static void main(String[] args) { GPMeiProxy gpMeiProxy = new GPMeiProxy(); IPerson iPerson = gpMeiProxy.getInstance(new Zhangsan()); iPerson.findLove(26); iPerson.getHeight(); iPerson.getAge(14); // IPerson zhaoliu = jdkMeiPo.getInstance(new Zhaoliu()); // zhaoliu.findLove(); } }
23.4
65
0.641026
362f14f9608916550fdfcbcc260d5c54c662a235
237
package com.zjj.jrpc.proxy; import com.zjj.jrpc.clutter.Clutter; import com.zjj.jrpc.extension.SPI; import java.util.List; @SPI("cglib") public interface ProxyFactory { <T> T getProxy(Class<T> clazz, List<Clutter<T>> clutters); }
19.75
62
0.734177
e35152623ee2ab43a508dcb371c74eef17ab28aa
3,607
package com.benstatertots.brewerydb.beer.list; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v7.content.res.AppCompatResources; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.benstatertots.brewerydb.R; import com.benstatertots.brewerydb.beer.list.model.BeerItem; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; /** * {@link RecyclerView.Adapter} that can display a {@link BeerItem} and makes a call to the * specified {@link BeerListFragment.OnBeerListFragmentInteractionListener}. */ public class MyBeerListRecyclerViewAdapter extends RecyclerView.Adapter<MyBeerListRecyclerViewAdapter.ViewHolder> { private List<BeerItem> mBeers; private BeerListFragment.OnBeerListFragmentInteractionListener mListener; private final Context mContext; private final Drawable mPlaceholder; private final Picasso mPicasso; public MyBeerListRecyclerViewAdapter(Context context, Picasso picasso) { mBeers = new ArrayList<>(); mContext = context; mPlaceholder = AppCompatResources.getDrawable(mContext, R.drawable.ic_beers_black_100dp); mPicasso = picasso; } public void setBeers(List<BeerItem> items) { mBeers = items; this.notifyDataSetChanged(); //TODO: use diffutil to only notify about the changed items, e.g: // https://stackoverflow.com/questions/44489235/update-recyclerview-with-android-livedata } public void setmListener(BeerListFragment.OnBeerListFragmentInteractionListener mListener) { this.mListener = mListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_beerlist_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { BeerItem item = mBeers.get(position); holder.mItem = item; holder.mTitleTextView.setText(item.name); holder.mSubtitleTextView.setText("Description " + item.id); if (item.labels.large == null || item.labels.large.isEmpty()) { holder.mImageView.setImageDrawable(mPlaceholder); } else { Picasso.with(mContext) .load(item.labels.large) .placeholder(mPlaceholder) .into(holder.mImageView); } holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != mListener) { mListener.onBeerItemTap(holder.mItem); } } }); } @Override public int getItemCount() { return mBeers.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final ImageView mImageView; public final TextView mTitleTextView; public final TextView mSubtitleTextView; public BeerItem mItem; public ViewHolder(View view) { super(view); mView = view; mImageView = view.findViewById(R.id.image); mTitleTextView = view.findViewById(R.id.title); mSubtitleTextView = view.findViewById(R.id.subtitle); } } }
34.682692
115
0.680621
14d5cca5519d10e0352ab2824d60b212303c55b6
2,673
package com.newrelic.nrvideoproject; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.google.android.exoplayer2.MediaItem; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.ui.PlayerView; import com.newrelic.videoagent.core.NewRelicVideoAgent; import com.newrelic.videoagent.core.tracker.NRVideoTracker; import com.newrelic.videoagent.exoplayer.tracker.NRTrackerExoPlayer; import java.util.HashMap; import java.util.Map; public class VideoPlayer extends AppCompatActivity { private SimpleExoPlayer player; private Integer trackerId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_player); String video = getIntent().getStringExtra("video"); if (video.equals("Tears")) { Log.v("VideoPlayer", "Play Tears"); playVideo("http://www.bok.net/dash/tears_of_steel/cleartext/stream.mpd"); } else if (video.equals("Playhouse")) { Log.v("VideoPlayer", "Play Playhouse"); playVideo("https://bitmovin-a.akamaihd.net/content/playhouse-vr/mpds/105560.mpd"); } else if (video.equals("Kite")) { Log.v("VideoPlayer", "Play Kite"); playVideo("https://demos.transloadit.com/dashtest/my_playlist.mpd"); } else if (video.equals("Live")) { Log.v("VideoPlayer", "Play Live"); playVideo("https://livesim.dashif.org/livesim/testpic_2s/Manifest.mpd"); } else { Log.v("VideoPlayer","Unknown video"); } } @Override protected void onDestroy() { super.onDestroy(); ((NRVideoTracker)NewRelicVideoAgent.getInstance().getContentTracker(trackerId)).sendEnd(); NewRelicVideoAgent.getInstance().releaseTracker(trackerId); } private void playVideo(String videoUrl) { player = new SimpleExoPlayer.Builder(this).build(); NRTrackerExoPlayer tracker = new NRTrackerExoPlayer(); trackerId = NewRelicVideoAgent.getInstance().start(tracker); Map<String, Object> attr = new HashMap<>(); attr.put("myAttrStr", "Hello"); attr.put("myAttrInt", 101); tracker.sendEvent("CUSTOM_ACTION", attr); PlayerView playerView = findViewById(R.id.player); playerView.setPlayer(player); tracker.setPlayer(player); player.setMediaItem(MediaItem.fromUri(videoUrl)); // Prepare the player. player.setPlayWhenReady(true); player.prepare(); } }
34.269231
98
0.66966
52885b1268a8c53957127d883d94dff6e430fc90
410
package com.jjh.beans; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Component public class BookService { @PostConstruct public void setupBookService() { System.out.println("BookService.setupBookService()"); } @PreDestroy public void clearBookService() { System.out.println("BookService.clearBookService()"); } }
18.636364
55
0.77561
4543df599cf5353b0cbef6247d479a32dcbf9b05
15,594
package com.commitstrip.commitstripreader.data.source; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.commitstrip.commitstripreader.common.dto.DisplayStripDto; import com.commitstrip.commitstripreader.data.source.local.StripDaoEntity; import com.commitstrip.commitstripreader.dto.StripDto; import com.squareup.picasso.RequestCreator; import com.squareup.picasso.Target; import org.reactivestreams.Publisher; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.concurrent.CompletableFuture; import io.reactivex.Flowable; import io.reactivex.Maybe; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.SingleSource; import io.requery.util.function.Supplier; import okhttp3.Response; public interface StripDataSource { /** * Fetch all strips from backend * * @return all strips from the backend */ Flowable<List<StripDto>> fetchAllStrip(); /** * Fetch strip from local database or network. * * @param id strip id * @param forceNetwork true, fetch will prioritize the network. * @return */ Maybe<StripDto> fetchStrip(Long id, boolean forceNetwork); /** * Get a list of strip from the page to page + numberOfStripPerPage. * The chronological order must be respected when returning the data. * * @param numberOfStripPerPage Number of strip per page * @param page The wanted page number * @param forceNetwork prioritize network * @return list of strip */ Flowable<StripDto> fetchListStrip(Integer numberOfStripPerPage, int page, boolean forceNetwork); /** * Fetch image from memory, disk or network, whichever is available first. * * @return Request object, call method into as described in the picasso library fon binding the * image to an ImageView. */ RequestCreator fetchImageStrip(@NonNull Long id, @NonNull String url); /** * Fetch from disk, if the strip is in user favorite. * * @param id strip id * @return whenever the strip is in user favorite. */ boolean isFavorite(@NonNull Long id); /** * Add the strip pass in parameter in the favorite * * @param mCurrentStrip The strip to save in favorite. * @param byteArrayOutputStream an array of image representation * @return strip added as favorite */ Single<StripDto> addFavorite(@NonNull StripDto mCurrentStrip, @NonNull ByteArrayOutputStream byteArrayOutputStream); /** * Delete the favorite strip pass in parameter. * * @param id delete the strip as one of his user favorite * @return strip id */ Maybe<Integer> deleteFavorite(@NonNull Long id); /** * Fetch all favorite strip. * * @return strips */ Flowable<DisplayStripDto> fetchFavoriteStrip(); /** * Fetch next favorite strip in time according to the date pass in parameter. * * @param date * @return the most recent strip according to the date. */ Single<StripDto> fetchNextFavoriteStrip(Date date); /** * Fetch previous favorite strip in time according to the date pass in parameter. * * @param date * @return previous favorite strip in time */ Single<StripDto> fetchPreviousFavoriteStrip(Date date); /** * Save in cache the strip image pass in parameter. * @param id strip id * @param url image url*/ Flowable<Integer> saveImageStripInCache(Long id, String url); /** * Save strips in local database. * * @param strips insert or update strips * @return strips added or update */ Flowable<Iterable<StripDaoEntity>> upsertStrip(List<StripDto> strips); /** * @param id strip id * @param outputStream a strip image. * @return */ File saveImageStripInCache(@NonNull Long id, @NonNull ByteArrayOutputStream outputStream); /** * Fetch random list of strip. * * @param numberOfStripPerPage number of strip wanted * @param alreadySeenStrip strip already seen, that we must select. * @return strips */ Flowable<StripDto> fetchRandomListStrip(Integer numberOfStripPerPage, List<Long> alreadySeenStrip); /** * Fetch older strip synchronously. * * @return older strip */ Maybe<StripDto> fetchOlderStrip(); /** * Fetch number of strip between two date * @param from start date * @param to end date */ Flowable<StripDto> fetchNumberOfStrip(Date from, Date to); /** * Schedule strips for download. * * @param strips * @return strips scheduled strips to download */ Single<Integer> scheduleStripForDownload(List<StripDto> strips); Flowable<StripDto> fetchToDownloadImageStrip(); void clearCacheStripForDownload(); int fetchCompressionLevelImages(); void saveLastReadIdFromTheBeginningMode(Long id); void saveLastReadDateFromTheBeginningMode(Long date); long fetchLastReadDateFromTheBeginningMode(); /* (no-Javadoc) */ boolean fetchPriorityForUseVolumeKey(); Long fetchLastReadIdFromTheBeginningMode(); /* (no-Javadoc) */ void savePriorityForUseVolumeKey(boolean useVolumeKey); File saveSharedImageInSharedFolder(@NonNull Long id, @NonNull ByteArrayOutputStream outputStream); interface RemoteDataSource { /** * Fetch a strip with the id given in parameter. * * @param id strip id * @return strip corresponding to the id pass in parameter. */ Maybe<StripDto> fetchStrip(Long id); /** * Fetch an image strip. * * @param url url where the method can fetch the image. * @return an picasso instance */ RequestCreator fetchImageStrip(String url); /** * Fetch all strips in the remote database. * * @return all strips */ Flowable<List<StripDto>> fetchAllStrip(); /** * @param numberOfStripPerPage number of wanted strip * @param page page number * @return strips according to the two parameters */ Flowable<StripDto> fetchListStrip(Integer numberOfStripPerPage, int page); } interface LocalDataSource { /** * Fetch a strip with the id specified in parameter in local database. * * Throw a NotSynchronizedException, if the local database have not been synchronized with the * org.commitstrip.commistripreader.data.source.remote yet and can not be found in local * database. * * @param id null id will return the most recent strip */ Maybe<StripDto> fetchStrip(@Nullable Long id); /** * Fetch a list of strips. * * @param numberOfStripPerPage number of wanted strip * @param page page number * @return list strips */ Flowable<StripDto> fetchListStrip( @NonNull Integer numberOfStripPerPage, @NonNull Integer page); /** * @param listId Fetch a list of strip corresponding to ids passed in parameter. * @return strip */ Flowable<StripDto> fetchListStrip(@NonNull Iterable<Long> listId); /** * Fetch a random list of strips. * * @param numberOfStripPerPage number of wanted strip. * @param alreadySeenStrip list of strip that we should not select * @return strip list */ Flowable<StripDto> fetchRandomListStrip( @NonNull Integer numberOfStripPerPage, @NonNull List<Long> alreadySeenStrip); /** * Return method for existing strip. * * @param id strip id * @return */ Maybe<StripDaoEntity> existStrip(@NonNull Long id); boolean isFavorite(@NonNull Long id); /** * Add a strip as a favorite. * * @param mCurrentStrip the strip to add as favorite * @return the strip added as favorite */ Single<StripDto> addFavorite(@NonNull StripDto mCurrentStrip); /** * Delete strip as a favorite. * * @param id strip id * @return the strip which is not in favorite */ Maybe<Integer> deleteFavorite(@NonNull Long id); /** * Fetch all strips from the favorite list. * * @return all strips added as favorite */ Flowable<StripDto> fetchFavoriteStrip(); /** * Fetch the most previous strip in time. * * @param date * @return the most previous strip in time. */ Single<StripDto> fetchPreviousFavoriteStrip(@NonNull Date date); /** * Fetch the most recent strip in time. * * @param date * @return the most recent in time according to the date in parameter */ Single<StripDto> fetchNextFavoriteStrip(@NonNull Date date); /** * Insert or update strip according to the id. * * @param strips strip to insert or update. * @return added strip */ Flowable<Iterable<StripDaoEntity>> upsertStrip(@NonNull Iterable<StripDto> strips); /** * Fetch most recent strip in the local database. * * @return most recent strip */ Single<StripDto> fetchMostRecentStrip(); /** * Fetch older strip synchronously. * * @return older strip */ Maybe<StripDto> fetchOlderStrip(); /** * Fetch number of strip. * @param from start date * @param to end date*/ Flowable<StripDto> fetchNumberOfStrip(Date from, Date to); /** * Schedule strips for download. * * @param strips * @return strips scheduled strips to download */ Single<Integer> scheduleStripForDownload(List<StripDto> strips); /** * Fetch every strip that are flagged for downloading their image * * @return every strip flagged for download */ Flowable<StripDto> fetchToDownloadImageStrip(); /** * Flag a strip as be done downloading * * @param id */ Single<Integer> flagAsDownloadedImage(Long id); } interface StripImageCacheDataSource { /** * Get image from local disk. You should call {@code isImageCacheForStripExist} before using * this function. * * @param id strip id * @return an file instance where the supposed file is. If no file exist on network it will * return a File instance pointing to a non existing file */ File getImageCacheForStrip(@NonNull Long id); /** * Try to fetch image strip from local disk, it will not try to load with network and will * not save it. * * @param id strip id * @return Picasso instance call {@code into}, if you want to display the strip. */ RequestCreator fetchImageStrip(@NonNull Long id); /** * Return true if image strip is on local disk. * * @param id strip id * @return true if an image exist, false otherwise. */ boolean isImageCacheForStripExist(@NonNull Long id); /** * Delete strip image from local disk. * * @param id strip id * @return true, the file have been successfully deleted, false otherwise. */ boolean deleteImageStripInCache(@NonNull Long id); /** * @param id strip id * @param compression compression level of the image, between 1 and 100. * @param requestCreator picasso instance */ void saveImageStripInCache(@NonNull Long id, @NonNull RequestCreator requestCreator, int compression); /** * @param id strip id * @param url picasso instance * @param compression compression level of the image, between 1 and 100. */ Flowable<Long> saveImageStripInCache(@NonNull Long id, @NonNull String url, int compression); /** * @param id strip id * @param outputStream bytes image representation * @return path to saved file */ File saveImageStripInCache(@NonNull Long id, @NonNull ByteArrayOutputStream outputStream); /** * List all cached image on local disk * @return list of cached image id */ List<Long> getCachedImagesId(); /** * Use it for saving the image by using method {@code into} on an {@code picasso instance}. * @param id strip id * @param compression compression * @return target instance for saving the file */ Target getTarget(@NonNull Long id, int compression); /** * Clear cache, skips strips pass in parameter * * @param strips skip strip pass in parameter. * @return */ Flowable<File> clearCache(List<StripDto> strips); File saveSharedImageInSharedFolder(Long id, ByteArrayOutputStream outputStream); } interface StripSharedPreferencesDataSource { /** * Get compression level of images from the user shared preferences repository. * * @return compression level between 1 and 100 (top quality image) */ int fetchCompressionLevelImages (); /** * Get compression level of images from the user shared preferences repository. * * @param compression level between 1 and 100 (top quality image) */ void saveCompressionLevelImages (int compression); /** * Return last id read from the beginning mode. * * @return last id read by user */ long fetchLastReadIdFromTheBeginningMode(); /** * Set the last id read from the beginning mode. * * @return last id read by user */ void saveLastReadIdFromTheBeginningMode(Long lastId); /** * Return last date read from the beginning mode. * * @return last date read by user */ long fetchLastReadDateFromTheBeginningMode(); /* (no-Javadoc) */ boolean fetchPriorityForUseVolumeKey(); /** * Set the last date read from the beginning mode. * * @return last vate read by user */ void saveLastReadDateFromTheBeginningMode(Long date); /* (no-Javadoc) */ void savePriorityForUseVolumeKey(boolean useVolumeKey); } }
31.063745
111
0.593562
077bba808c8e4c86a488fea80817fa324ab6ae57
2,862
package com.yunussen.mobilappws; import java.util.Arrays; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.yunussen.mobilappws.io.entity.AuthorityEntity; import com.yunussen.mobilappws.io.entity.RoleEntity; import com.yunussen.mobilappws.io.entity.UserEntity; import com.yunussen.mobilappws.io.repository.AuthorityRepository; import com.yunussen.mobilappws.io.repository.RoleRepository; import com.yunussen.mobilappws.io.repository.UserRepository; import com.yunussen.mobilappws.shared.Roles; import com.yunussen.mobilappws.shared.Utils; @Component public class InitialUsersSetup { @Autowired private AuthorityRepository authorityRepository; @Autowired private RoleRepository roleRepository; @Autowired private UserRepository userRepository; @Autowired private Utils utils; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @EventListener @Transactional public void onApplicationEvent(ApplicationReadyEvent event) { AuthorityEntity readAuthority=createAuthority("READ_AUTHORITY"); AuthorityEntity writeAuthority=createAuthority("WRITE_AUTHORITY"); AuthorityEntity deleteAuthority=createAuthority("DELETE_AUTHORITY"); createRole(Roles.ROLE_USER.name(), Arrays.asList(readAuthority,writeAuthority)); RoleEntity roleAdmin=createRole(Roles.ROLE_ADMIN.name(), Arrays.asList(readAuthority,writeAuthority,deleteAuthority)); UserEntity user=userRepository.findByEmail("yunussen2727@gmail.com"); if(roleAdmin==null||user!=null)return; user=new UserEntity(); user.setFirstName("yunus"); user.setLastName("Şen"); user.setEmail("yunussen2727@gmail.com"); user.setEmailVerificationStatus(Boolean.TRUE); String publicUserId=utils.generateUserId(32); user.setUserId(publicUserId); user.setEncryptedPassword(bCryptPasswordEncoder.encode("1234")); user.setRoles(Arrays.asList(roleAdmin)); userRepository.save(user); } @Transactional public RoleEntity createRole(String name,Collection<AuthorityEntity>authorities) { RoleEntity role=roleRepository.findByName(name); if(role==null) { role=new RoleEntity(); role.setName(name); role.setAuthorities(authorities); roleRepository.save(role); } return role; } @Transactional public AuthorityEntity createAuthority(String name) { AuthorityEntity authority=authorityRepository.findByName(name); if(authority==null) { authority=new AuthorityEntity(); authority.setName(name); authorityRepository.save(authority); } return authority; } }
33.670588
120
0.809923
2b1a40057806b8d1cc96646864cd0b2d9a37c7a0
2,770
package com.google.android.gms.internal; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.maps.GoogleMap; public interface bu extends IInterface { /* renamed from: com.google.android.gms.internal.bu.a */ public static abstract class C1489a extends Binder implements bu { /* renamed from: com.google.android.gms.internal.bu.a.a */ private static class C1488a implements bu { private IBinder f3627a; C1488a(IBinder iBinder) { this.f3627a = iBinder; } public void m5419a(LocationSettingsResult locationSettingsResult) { Parcel obtain = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.location.internal.ISettingsCallbacks"); if (locationSettingsResult != null) { obtain.writeInt(1); locationSettingsResult.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.f3627a.transact(1, obtain, null, 1); } finally { obtain.recycle(); } } public IBinder asBinder() { return this.f3627a; } } public static bu m5420a(IBinder iBinder) { if (iBinder == null) { return null; } IInterface queryLocalInterface = iBinder.queryLocalInterface("com.google.android.gms.location.internal.ISettingsCallbacks"); return (queryLocalInterface == null || !(queryLocalInterface instanceof bu)) ? new C1488a(iBinder) : (bu) queryLocalInterface; } public IBinder asBinder() { return this; } public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) { switch (i) { case GoogleMap.MAP_TYPE_NORMAL /*1*/: parcel.enforceInterface("com.google.android.gms.location.internal.ISettingsCallbacks"); m5418a(parcel.readInt() != 0 ? (LocationSettingsResult) LocationSettingsResult.CREATOR.createFromParcel(parcel) : null); return true; case 1598968902: parcel2.writeString("com.google.android.gms.location.internal.ISettingsCallbacks"); return true; default: return super.onTransact(i, parcel, parcel2, i2); } } } void m5418a(LocationSettingsResult locationSettingsResult); }
37.945205
140
0.577256
ebc49b29063f1ced3338a466ec1ff995944d9e6f
1,881
package com.xuecheng.ucenter.service; import com.xuecheng.framework.domain.ucenter.XcCompanyUser; import com.xuecheng.framework.domain.ucenter.XcMenu; import com.xuecheng.framework.domain.ucenter.XcUser; import com.xuecheng.framework.domain.ucenter.ext.XcUserExt; import com.xuecheng.ucenter.dao.XcCompanyUserRepository; import com.xuecheng.ucenter.dao.XcMenuMapper; import com.xuecheng.ucenter.dao.XcUserRepository; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * User: 李锦卓 * Time: 2019/5/23 16:01 */ @Service @Transactional public class UserService { @Autowired XcUserRepository xcUserRepository; @Autowired XcCompanyUserRepository xcCompanyUserRepository; @Autowired XcMenuMapper xcMenuMapper; //根据用户账号查询用户信息 public XcUser findXcUsername(String username) { return xcUserRepository.findXcUserByUsername(username); } //根据账号查询用户信息,返回用户扩展信息 public XcUserExt getUserExt(String username) { XcUser xcUser = this.findXcUsername(username); if (xcUser == null) { return null; } //用户id String id = xcUser.getId(); //查询用户所有权限 List<XcMenu> xcMenuList = xcMenuMapper.selectPermissionByUserId(id); XcCompanyUser xcCompanyUser = xcCompanyUserRepository.findByUserId(id); //取到用户的公司id String companyId = null; if(xcCompanyUser!=null){ companyId = xcCompanyUser.getCompanyId(); } XcUserExt xcUserExt = new XcUserExt(); BeanUtils.copyProperties(xcUser, xcUserExt); xcUserExt.setCompanyId(companyId); //设置权限 xcUserExt.setPermissions(xcMenuList); return xcUserExt; } }
31.881356
79
0.724083
a34673dd2d5c2ae5b882dd9d74c83640788b0775
1,446
package com.austinlm.packetdump.util; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * Custom logging formatter to make things nicer * * @author Keenan Thompson */ public class CustomFormatter extends Formatter { private static final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL [%4$s] [%3$s] %5$s %6$s%n"; private final Date dat = new Date(); /** * Formats a log message (taken from SimpleFormatter, but better formatting). */ @Override public String format(LogRecord record) { dat.setTime(record.getMillis()); String source; if (record.getSourceClassName() != null) { source = record.getSourceClassName(); if (record.getSourceMethodName() != null) { source += " " + record.getSourceMethodName(); } } else { source = record.getLoggerName(); } String message = formatMessage(record); String throwable = ""; if (record.getThrown() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(); record.getThrown().printStackTrace(pw); pw.close(); throwable = sw.toString(); } return String.format(format, dat, source, record.getLoggerName(), record.getLevel().getLocalizedName(), message, throwable); } }
27.283019
109
0.639696
df9cd671589ec4c762b903c48264ec3ba3523299
340
package com.cay.rockstock.utils; import com.cay.rockstock.beans.enums.NumberEnum; import org.junit.jupiter.api.Test; public class NumberUtilTest { @Test public void NumberTest() { System.out.println(NumberUtil.formatNumber("1.3元")); System.out.println(NumberUtil.formatNumber("1.33万亿元", NumberEnum.WAN)); } }
24.285714
79
0.714706
4bed51816e4f6facc02cc3c752ad2ba56adb0246
12,380
package com.annimon.ownlang.parser; import com.annimon.ownlang.exceptions.LexerException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * * @author aNNiMON */ public final class Lexer { public static List<Token> tokenize(String input) { return new Lexer(input).tokenize(); } private static final String OPERATOR_CHARS = "+-*/%()[]{}=<>!&|.,^~?:"; private static final Map<String, TokenType> OPERATORS; static { OPERATORS = new HashMap<>(); OPERATORS.put("+", TokenType.PLUS); OPERATORS.put("-", TokenType.MINUS); OPERATORS.put("*", TokenType.STAR); OPERATORS.put("/", TokenType.SLASH); OPERATORS.put("%", TokenType.PERCENT); OPERATORS.put("(", TokenType.LPAREN); OPERATORS.put(")", TokenType.RPAREN); OPERATORS.put("[", TokenType.LBRACKET); OPERATORS.put("]", TokenType.RBRACKET); OPERATORS.put("{", TokenType.LBRACE); OPERATORS.put("}", TokenType.RBRACE); OPERATORS.put("=", TokenType.EQ); OPERATORS.put("<", TokenType.LT); OPERATORS.put(">", TokenType.GT); OPERATORS.put(".", TokenType.DOT); OPERATORS.put(",", TokenType.COMMA); OPERATORS.put("^", TokenType.CARET); OPERATORS.put("~", TokenType.TILDE); OPERATORS.put("?", TokenType.QUESTION); OPERATORS.put(":", TokenType.COLON); OPERATORS.put("!", TokenType.EXCL); OPERATORS.put("&", TokenType.AMP); OPERATORS.put("|", TokenType.BAR); OPERATORS.put("==", TokenType.EQEQ); OPERATORS.put("!=", TokenType.EXCLEQ); OPERATORS.put("<=", TokenType.LTEQ); OPERATORS.put(">=", TokenType.GTEQ); OPERATORS.put("+=", TokenType.PLUSEQ); OPERATORS.put("-=", TokenType.MINUSEQ); OPERATORS.put("*=", TokenType.STAREQ); OPERATORS.put("/=", TokenType.SLASHEQ); OPERATORS.put("%=", TokenType.PERCENTEQ); OPERATORS.put("&=", TokenType.AMPEQ); OPERATORS.put("^=", TokenType.CARETEQ); OPERATORS.put("|=", TokenType.BAREQ); OPERATORS.put("::=", TokenType.COLONCOLONEQ); OPERATORS.put("<<=", TokenType.LTLTEQ); OPERATORS.put(">>=", TokenType.GTGTEQ); OPERATORS.put(">>>=", TokenType.GTGTGTEQ); OPERATORS.put("++", TokenType.PLUSPLUS); OPERATORS.put("--", TokenType.MINUSMINUS); OPERATORS.put("::", TokenType.COLONCOLON); OPERATORS.put("&&", TokenType.AMPAMP); OPERATORS.put("||", TokenType.BARBAR); OPERATORS.put("<<", TokenType.LTLT); OPERATORS.put(">>", TokenType.GTGT); OPERATORS.put(">>>", TokenType.GTGTGT); OPERATORS.put("@", TokenType.AT); OPERATORS.put("@=", TokenType.ATEQ); OPERATORS.put("..", TokenType.DOTDOT); OPERATORS.put("**", TokenType.STARSTAR); OPERATORS.put("^^", TokenType.CARETCARET); OPERATORS.put("?:", TokenType.QUESTIONCOLON); OPERATORS.put("??", TokenType.QUESTIONQUESTION); } private static final Map<String, TokenType> KEYWORDS; static { KEYWORDS = new HashMap<>(); KEYWORDS.put("print", TokenType.PRINT); KEYWORDS.put("println", TokenType.PRINTLN); KEYWORDS.put("if", TokenType.IF); KEYWORDS.put("else", TokenType.ELSE); KEYWORDS.put("while", TokenType.WHILE); KEYWORDS.put("for", TokenType.FOR); KEYWORDS.put("do", TokenType.DO); KEYWORDS.put("break", TokenType.BREAK); KEYWORDS.put("continue", TokenType.CONTINUE); KEYWORDS.put("def", TokenType.DEF); KEYWORDS.put("return", TokenType.RETURN); KEYWORDS.put("use", TokenType.USE); KEYWORDS.put("match", TokenType.MATCH); KEYWORDS.put("case", TokenType.CASE); KEYWORDS.put("extract", TokenType.EXTRACT); KEYWORDS.put("include", TokenType.INCLUDE); KEYWORDS.put("class", TokenType.CLASS); KEYWORDS.put("new", TokenType.NEW); } public static Set<String> getKeywords() { return KEYWORDS.keySet(); } private final String input; private final int length; private final List<Token> tokens; private final StringBuilder buffer; private int pos; private int row, col; public Lexer(String input) { this.input = input; length = input.length(); tokens = new ArrayList<>(); buffer = new StringBuilder(); row = col = 1; } public List<Token> tokenize() { while (pos < length) { final char current = peek(0); if (Character.isDigit(current)) tokenizeNumber(); else if (isOwnLangIdentifierStart(current)) tokenizeWord(); else if (current == '`') tokenizeExtendedWord(); else if (current == '"') tokenizeText(); else if (current == '#') { next(); tokenizeHexNumber(1); } else if (OPERATOR_CHARS.indexOf(current) != -1) { tokenizeOperator(); } else { // whitespaces next(); } } return tokens; } private void tokenizeNumber() { clearBuffer(); char current = peek(0); if (current == '0' && (peek(1) == 'x' || (peek(1) == 'X'))) { next(); next(); tokenizeHexNumber(2); return; } while (true) { if (current == '.') { if (buffer.indexOf(".") != -1) throw error("Invalid float number"); } else if (!Character.isDigit(current)) { break; } buffer.append(current); current = next(); } addToken(TokenType.NUMBER, buffer.toString()); } private void tokenizeHexNumber(int skipped) { clearBuffer(); char current = peek(0); while (isHexNumber(current) || (current == '_')) { if (current != '_') { // allow _ symbol buffer.append(current); } current = next(); } final int length = buffer.length(); if (length > 0) { addToken(TokenType.HEX_NUMBER, buffer.toString()); } } private static boolean isHexNumber(char current) { return Character.isDigit(current) || ('a' <= current && current <= 'f') || ('A' <= current && current <= 'F'); } private void tokenizeOperator() { char current = peek(0); if (current == '/') { if (peek(1) == '/') { next(); next(); tokenizeComment(); return; } else if (peek(1) == '*') { next(); next(); tokenizeMultilineComment(); return; } } clearBuffer(); while (true) { final String text = buffer.toString(); if (!text.isEmpty() && !OPERATORS.containsKey(text + current)) { addToken(OPERATORS.get(text)); return; } buffer.append(current); current = next(); } } private void tokenizeWord() { clearBuffer(); buffer.append(peek(0)); char current = next(); while (true) { if (!isOwnLangIdentifierPart(current)) { break; } buffer.append(current); current = next(); } final String word = buffer.toString(); if (KEYWORDS.containsKey(word)) { addToken(KEYWORDS.get(word)); } else { addToken(TokenType.WORD, word); } } private void tokenizeExtendedWord() { next();// skip ` clearBuffer(); char current = peek(0); while (true) { if (current == '`') break; if (current == '\0') throw error("Reached end of file while parsing extended word."); if (current == '\n' || current == '\r') throw error("Reached end of line while parsing extended word."); buffer.append(current); current = next(); } next(); // skip closing ` addToken(TokenType.WORD, buffer.toString()); } private void tokenizeText() { next();// skip " clearBuffer(); char current = peek(0); while (true) { if (current == '\\') { current = next(); switch (current) { case '"': current = next(); buffer.append('"'); continue; case '0': current = next(); buffer.append('\0'); continue; case 'b': current = next(); buffer.append('\b'); continue; case 'f': current = next(); buffer.append('\f'); continue; case 'n': current = next(); buffer.append('\n'); continue; case 'r': current = next(); buffer.append('\r'); continue; case 't': current = next(); buffer.append('\t'); continue; case 'u': // http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.3 int rollbackPosition = pos; while (current == 'u') current = next(); int escapedValue = 0; for (int i = 12; i >= 0 && escapedValue != -1; i -= 4) { if (isHexNumber(current)) { escapedValue |= (Character.digit(current, 16) << i); } else { escapedValue = -1; } current = next(); } if (escapedValue >= 0) { buffer.append((char) escapedValue); } else { // rollback buffer.append("\\u"); pos = rollbackPosition; } continue; } buffer.append('\\'); continue; } if (current == '"') break; if (current == '\0') throw error("Reached end of file while parsing text string."); buffer.append(current); current = next(); } next(); // skip closing " addToken(TokenType.TEXT, buffer.toString()); } private void tokenizeComment() { char current = peek(0); while ("\r\n\0".indexOf(current) == -1) { current = next(); } } private void tokenizeMultilineComment() { char current = peek(0); while (true) { if (current == '*' && peek(1) == '/') break; if (current == '\0') throw error("Reached end of file while parsing multiline comment"); current = next(); } next(); // * next(); // / } private boolean isOwnLangIdentifierStart(char current) { return (Character.isLetter(current) || (current == '_') || (current == '$')); } private boolean isOwnLangIdentifierPart(char current) { return (Character.isLetterOrDigit(current) || (current == '_') || (current == '$')); } private void clearBuffer() { buffer.setLength(0); } private char next() { pos++; final char result = peek(0); if (result == '\n') { row++; col = 1; } else col++; return result; } private char peek(int relativePosition) { final int position = pos + relativePosition; if (position >= length) return '\0'; return input.charAt(position); } private void addToken(TokenType type) { addToken(type, ""); } private void addToken(TokenType type, String text) { tokens.add(new Token(type, text, row, col)); } private LexerException error(String text) { return new LexerException(row, col, text); } }
33.73297
116
0.498546
9e09a5db7979ee2a811852ce72eaa3c8a55bb9b3
12,931
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: SideeffectReportVO.java package report; import java.util.Date; public class SideeffectReportVO { public SideeffectReportVO() { } public String getExtra_info2() { return extra_info2; } public void setExtra_info2(String extra_info2) { this.extra_info2 = extra_info2; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getReporter_type() { return reporter_type; } public void setReporter_type(String reporter_type) { this.reporter_type = reporter_type; } public String getCompany_name() { return company_name; } public void setCompany_name(String company_name) { this.company_name = company_name; } public String getEntp_name() { return entp_name; } public void setEntp_name(String entp_name) { this.entp_name = entp_name; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getClass_kor_name() { return class_kor_name; } public void setClass_kor_name(String class_kor_name) { this.class_kor_name = class_kor_name; } public String getProduct_cob_code() { return product_cob_code; } public void setProduct_cob_code(String product_cob_code) { this.product_cob_code = product_cob_code; } public String getMedicalcode() { return medicalcode; } public void setMedicalcode(String medicalcode) { this.medicalcode = medicalcode; } public String getPatientcode() { return patientcode; } public void setPatientcode(String patientcode) { this.patientcode = patientcode; } public String getComponetcode() { return componetcode; } public void setComponetcode(String componetcode) { this.componetcode = componetcode; } public String getResult_value() { return result_value; } public void setResult_value(String result_value) { this.result_value = result_value; } public String getCause_value() { return cause_value; } public void setCause_value(String cause_value) { this.cause_value = cause_value; } public String getCausality() { return causality; } public void setCausality(String causality) { this.causality = causality; } public String getExta_info() { return exta_info; } public void setExta_info(String exta_info) { this.exta_info = exta_info; } public String getFollowup() { return followup; } public void setFollowup(String followup) { this.followup = followup; } public String getReport_year() { return report_year; } public void setReport_year(String report_year) { this.report_year = report_year; } public String getReport_month() { return report_month; } public void setReport_month(String report_month) { this.report_month = report_month; } public Date getFirst_modified() { return first_modified; } public void setFirst_modified(Date first_modified) { this.first_modified = first_modified; } public String getDocument_number() { return document_number; } public void setDocument_number(String document_number) { this.document_number = document_number; } public String getReport_type2() { return report_type2; } public void setReport_type2(String report_type2) { this.report_type2 = report_type2; } public String getReport_date() { return report_date; } public void setReport_date(String report_date) { this.report_date = report_date; } public String getMreport_date() { return mreport_date; } public void setMreport_date(String mreport_date) { this.mreport_date = mreport_date; } public String getRepresentatives() { return representatives; } public void setRepresentatives(String representatives) { this.representatives = representatives; } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager; } public String getReport_tel() { return report_tel; } public void setReport_tel(String report_tel) { this.report_tel = report_tel; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getReport_address() { return report_address; } public void setReport_address(String report_address) { this.report_address = report_address; } public String getMeddev_entp_no() { return meddev_entp_no; } public void setMeddev_entp_no(String meddev_entp_no) { this.meddev_entp_no = meddev_entp_no; } public String getMea_class_no() { return mea_class_no; } public void setMea_class_no(String mea_class_no) { this.mea_class_no = mea_class_no; } public String getCountry_manufactured() { return country_manufactured; } public void setCountry_manufactured(String country_manufactured) { this.country_manufactured = country_manufactured; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getMeb_type() { return meb_type; } public void setMeb_type(String meb_type) { this.meb_type = meb_type; } public String getSerial_number() { return serial_number; } public void setSerial_number(String serial_number) { this.serial_number = serial_number; } public String getPatient_name() { return patient_name; } public void setPatient_name(String patient_name) { this.patient_name = patient_name; } public String getPatient_gender() { return patient_gender; } public void setPatient_gender(String patient_gender) { this.patient_gender = patient_gender; } public String getPatient_age() { return patient_age; } public void setPatient_age(String patient_age) { this.patient_age = patient_age; } public String getPatient_extra_info() { return patient_extra_info; } public void setPatient_extra_info(String patient_extra_info) { this.patient_extra_info = patient_extra_info; } public String getSide_effect_first_date() { return side_effect_first_date; } public void setSide_effect_first_date(String side_effect_first_date) { this.side_effect_first_date = side_effect_first_date; } public String getSide_effect_generation_date() { return side_effect_generation_date; } public void setSide_effect_generation_date(String side_effect_generation_date) { this.side_effect_generation_date = side_effect_generation_date; } public String getSide_effect_last_date() { return side_effect_last_date; } public void setSide_effect_last_date(String side_effect_last_date) { this.side_effect_last_date = side_effect_last_date; } public String getReport_status() { return report_status; } public void setReport_status(String report_status) { this.report_status = report_status; } public String getFollow_up_action() { return follow_up_action; } public void setFollow_up_action(String follow_up_action) { this.follow_up_action = follow_up_action; } public String getOrganization1() { return organization1; } public void setOrganization1(String organization1) { this.organization1 = organization1; } public String getOrganization_tel() { return organization_tel; } public void setOrganization_tel(String organization_tel) { this.organization_tel = organization_tel; } public String getOrganization_address() { return organization_address; } public void setOrganization_address(String organization_address) { this.organization_address = organization_address; } public String getAttachment() { return attachment; } public void setAttachment(String attachment) { this.attachment = attachment; } public String getGubun() { return gubun; } public void setGubun(String gubun) { this.gubun = gubun; } public String getMeddev_item_no() { return meddev_item_no; } public void setMeddev_item_no(String meddev_item_no) { this.meddev_item_no = meddev_item_no; } public Integer getMeddev_item_no1() { return meddev_item_no1; } public void setMeddev_item_no1(Integer meddev_item_no1) { this.meddev_item_no1 = meddev_item_no1; } public Integer getMeddev_item_no2() { return meddev_item_no2; } public void setMeddev_item_no2(Integer meddev_item_no2) { this.meddev_item_no2 = meddev_item_no2; } public String getProduct_value() { return product_value; } public void setProduct_value(String product_value) { this.product_value = product_value; } public String getKfda_followup() { return Kfda_followup; } public void setKfda_followup(String kfda_followup) { Kfda_followup = kfda_followup; } private Integer id; private String document_number; private String reporter_type; private String company_name; private String entp_name; private String grade; private String class_kor_name; private String product_cob_code; private String medicalcode; private String patientcode; private String componetcode; private String result_value; private String cause_value; private String causality; private String exta_info; private String followup; private String report_year; private String report_month; private Date first_modified; private String report_type2; private String report_date; private String mreport_date; private String representatives; private String manager; private String report_tel; private String fax; private String email; private String report_address; private String meddev_entp_no; private String mea_class_no; private String country_manufactured; private String manufacturer; private String meb_type; private String serial_number; private String patient_name; private String patient_gender; private String patient_age; private String patient_extra_info; private String side_effect_first_date; private String side_effect_generation_date; private String side_effect_last_date; private String report_status; private String follow_up_action; private String organization1; private String organization_tel; private String organization_address; private String attachment; private String gubun; private String extra_info2; private String meddev_item_no; private Integer meddev_item_no1; private Integer meddev_item_no2; private String product_value; private String Kfda_followup; }
21.129085
83
0.62006
b613ac27745955e0781ba25e7ba91e26baf62aa9
1,329
package com.xgimi.dlna.upnp.xml; import com.xgimi.dlna.upnp.control.QueryListener; import com.xgimi.dlna.upnp.control.QueryResponse; /** * author : joker.peng * e-mail : joker.peng@xgimi.com * date : 2020/8/4 9:34 * desc : */ public class StateVariableData extends NodeData { public StateVariableData() { } //////////////////////////////////////////////// // value //////////////////////////////////////////////// private String value = ""; public String getValue() { return value; } public void setValue(String value) { this.value = value; } //////////////////////////////////////////////// // QueryListener //////////////////////////////////////////////// private QueryListener queryListener = null; public QueryListener getQueryListener() { return queryListener; } public void setQueryListener(QueryListener queryListener) { this.queryListener = queryListener; } //////////////////////////////////////////////// // QueryResponse //////////////////////////////////////////////// private QueryResponse queryRes = null; public QueryResponse getQueryResponse() { return queryRes; } public void setQueryResponse(QueryResponse res) { queryRes = res; } }
21.786885
63
0.496614
a35e0e5817f17b837e589e724697d940ad3e89c2
1,855
package com.maxheapsize.jpm; import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.MockMvc; import java.util.Date; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; public class SmartMeterControllerTest { private MockMvc mockMvc; private String expectedString; @Before public void setup() { SmartMeterController smartMeterController = new SmartMeterController(); smartMeterController.readingBuffer = new ReadingBuffer(); SmartMeterReading smartMeterReading = new SmartMeterReading(); smartMeterReading.date = new Date(); expectedString = "{\"date\":" + smartMeterReading.date.getTime() + ",\"meterTotal\":{\"value\":0,\"unit\":\"wh\"},\"meterOne\":{\"value\":0,\"unit\":\"wh\"},\"meterTwo\":{\"value\":0,\"unit\":\"wh\"},\"power\":{\"value\":0,\"unit\":\"wh\"},\"complete\":false}"; smartMeterController.readingBuffer.setSmartMeterReading("testdevice", smartMeterReading); this.mockMvc = standaloneSetup(smartMeterController).build(); } @Test public void testGetDevice() throws Exception { this.mockMvc.perform(get("/testdevice")) .andExpect(status().isOk()) .andExpect(content().string(expectedString)) .andExpect(content().contentType("application/json")); } @Test public void testGetDevices() throws Exception { this.mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(content().string("{\"devices\":[\"testdevice\"]}")) .andExpect(content().contentType("application/json")); } }
37.857143
265
0.720216
806e09a46d01dee1fbfb453c86f96c030e5c9547
656
package md.mgmt.common; import md.mgmt.base.md.ClusterNodeInfo; import java.util.List; /** * Created by Mr-yang on 16-1-11. */ public interface CommonModule { /** * 生成文件编码 */ public String genFileCode(); /** * 生成分布编码 */ public Long genDistrCode(); /** * 检验分布编码对应的节点能否继续保持新的元数据 */ public boolean checkDistrCodeFit(Long distrCode); /** * 获取分布编码对应的元数据节点信息 */ public ClusterNodeInfo getMdLocation(Long distrCode); /** * 生成分布编码对应的元数据节点信息 */ public ClusterNodeInfo genMdLocation(); public List<ClusterNodeInfo> getMdLocationList(List<Long> distrCodeList); }
17.263158
77
0.635671
3cdef9719f63d3a49277ceeaac4ddaf2696f6fa3
2,778
package net.keabotstudios.superin; import java.lang.reflect.Field; import java.util.Arrays; import net.java.games.input.Component; import net.java.games.input.Component.Identifier; public class InputAxis { public static final int EMPTY = -1; private final String name; private int keyCode = EMPTY, mouseCode = EMPTY; private Identifier[] identifiers = null; private float actZone = 0.0f; public InputAxis(String name, int keyCode, Identifier identifier, float actZone, int mouseCode) { this.name = name; this.keyCode = keyCode; this.identifiers = new Identifier[1]; if(identifier == null) throw new NullPointerException("Identifier array should not be null, empty, or contain a null identfier!"); this.identifiers[0] = identifier; this.actZone = actZone; this.mouseCode = mouseCode; } public InputAxis(String name, int keyCode, Identifier[] identifiers, float actZone, int mouseCode) { this.name = name; this.keyCode = keyCode; if(identifiers.equals(null) || identifiers.length == 0 || Arrays.asList(identifiers).contains(null)) throw new NullPointerException("Identifier array should not be null, empty, or contain a null identfier!"); this.identifiers = identifiers; this.actZone = actZone; this.mouseCode = mouseCode; } public InputAxis(String name, int keyCode, int mouseCode) { this.name = name; this.keyCode = keyCode; this.mouseCode = mouseCode; } public InputAxis(String name, int keyCode) { this.name = name; this.keyCode = keyCode; } public String getName() { return name; } public int getKeyCode() { return keyCode; } public Identifier[] getIdentifiers() { return identifiers; } public float getActZone() { return actZone; } public int getMouseCode() { return mouseCode; } public static Identifier getIdentifierFromName(String s) { if(s.equalsIgnoreCase("null")) return null; String[] split = s.split("\\."); try { if (split.length == 2) { String typeName = split[0]; String identifier = split[1]; Class<?>[] declaredClasses = Component.Identifier.class.getDeclaredClasses(); for (int i = 0; i < declaredClasses.length; i++) { if (declaredClasses[i].getName().contains(typeName)) { Field[] declaredFields = declaredClasses[i].getDeclaredFields(); for (int j = 0; j < declaredFields.length; j++) { if (declaredFields[j].getName().equals(identifier)) { if (declaredFields[j].get(null) instanceof Identifier) { return (Identifier) declaredFields[j].get(null); } } } } } } } catch (Exception e) {} System.err.println("Unable to get identifier from name: " + s); return null; } }
28.9375
211
0.670266
79315caa2d6cb946f3134b54ff284e943e16a5eb
6,619
package com.objectcomputing.checkins.services.memberprofile; import io.micronaut.core.annotation.Introspected; import io.swagger.v3.oas.annotations.media.Schema; import io.micronaut.core.annotation.Nullable; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.time.LocalDate; import java.util.Objects; import java.util.UUID; @Introspected public class MemberProfileCreateDTO { @NotBlank @Schema(description = "first name of the employee") private String firstName; @Nullable @Schema(description = "middle name of the employee") private String middleName; @NotBlank @Schema(description = "last name of the employee") private String lastName; @Nullable @Schema(description = "suffix of the employee") private String suffix; @NotBlank @Schema(description = "employee's title at the company", required = true) private String title ; @Nullable @Schema(description = "employee's professional development lead") private UUID pdlId; @NotBlank @Schema(description = "where the employee is geographically located", required = true) private String location; @NotBlank @Schema(description = "employee's OCI email. Typically last name + first initial @ObjectComputing.com", required = true) private String workEmail; @Nullable @Schema(description = "unique identifier for this employee") private String employeeId; @NotNull @Schema(description = "employee's date of hire", required = true) private LocalDate startDate; @Nullable @Schema(description = "employee's biography") private String bioText; @Nullable @Schema(description = "id of the supervisor this member is associated with", nullable = true) private UUID supervisorid; @Nullable @Schema(description = "employee's date of termination", nullable = true) private LocalDate terminationDate; @Nullable @Schema(description = "Birth date of employee", nullable = true) private LocalDate birthDay; @Nullable @Schema(description = "The employee termination was voluntary", nullable = true) private Boolean voluntary; @Nullable @Schema(description = "The employee is excluded from retention reports", nullable = true) private Boolean excluded; @NotBlank public String getFirstName() { return firstName; } public void setFirstName(@NotBlank String firstName) { this.firstName = firstName; } @Nullable public String getMiddleName() { return middleName; } public void setMiddleName(@Nullable String middleName) { this.middleName = middleName; } @NotBlank public String getLastName() { return lastName; } public void setLastName(@NotBlank String lastName) { this.lastName = lastName; } @Nullable public String getSuffix() { return suffix; } public void setSuffix(@Nullable String suffix) { this.suffix = suffix; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Nullable public UUID getPdlId() { return pdlId; } public void setPdlId(@Nullable UUID pdlId) { this.pdlId = pdlId; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getWorkEmail() { return workEmail; } public void setWorkEmail(String workEmail) { this.workEmail = workEmail; } @Nullable public String getEmployeeId() { return employeeId; } public void setEmployeeId(@Nullable String employeeId) { this.employeeId = employeeId; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } @Nullable public String getBioText() { return bioText; } public void setBioText(@Nullable String bioText) { this.bioText = bioText; } @Nullable public UUID getSupervisorid() { return supervisorid; } public void setSupervisorid(@Nullable UUID supervisorid) { this.supervisorid = supervisorid; } @Nullable public LocalDate getTerminationDate() { return terminationDate; } public void setTerminationDate(@Nullable LocalDate terminationDate) { this.terminationDate = terminationDate; } @Nullable public LocalDate getBirthDay() { return birthDay; } public void setBirthDay(@Nullable LocalDate birthDay) { this.birthDay = birthDay;} @Nullable public Boolean getVoluntary() { return voluntary; } public void setVoluntary(@Nullable Boolean voluntary) { this.voluntary = voluntary; } @Nullable public Boolean getExcluded() { return excluded; } public void setExcluded(@Nullable Boolean excluded) { this.excluded = excluded; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MemberProfileCreateDTO that = (MemberProfileCreateDTO) o; return Objects.equals(firstName, that.firstName) && Objects.equals(middleName, that.middleName) && Objects.equals(lastName, that.lastName) && Objects.equals(suffix, that.suffix) && Objects.equals(title, that.title) && Objects.equals(pdlId, that.pdlId) && Objects.equals(location, that.location) && Objects.equals(workEmail, that.workEmail) && Objects.equals(employeeId, that.employeeId) && Objects.equals(startDate, that.startDate) && Objects.equals(bioText, that.bioText) && Objects.equals(supervisorid, that.supervisorid) && Objects.equals(terminationDate, that.terminationDate) && Objects.equals(birthDay, that.birthDay) && Objects.equals(voluntary, that.voluntary) && Objects.equals(excluded, that.excluded); } @Override public int hashCode() { return Objects.hash(firstName, middleName, lastName, suffix, title, pdlId, location, workEmail, employeeId, startDate, bioText, supervisorid, terminationDate, birthDay, voluntary, excluded); } }
26.582329
124
0.651458
11356c8966fbb5fdf2ff540d81f0604f26782a83
7,603
// ======================================================================== // Copyright 2010-2012 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.tests.authentication; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.cipango.client.test.matcher.SipMatchers.*; import java.util.List; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import org.cipango.client.Authentication; import org.cipango.client.Authentication.Digest; import org.cipango.client.test.CredentialsImpl; import org.cipango.client.Call; import org.cipango.client.SipHeaders; import org.cipango.client.SipMethods; import org.cipango.tests.UaTestCase; import org.junit.Test; public class AuthenticationTest extends UaTestCase { class MutableDigest extends Digest { public MutableDigest(Digest digest) { _realm = digest.getRealm(); _qop = digest.getQop(); _nonce = digest.getNonce(); _opaque = digest.getOpaque(); _stale = String.valueOf(digest.isStale()); } public void setNonce(String nonce) { _nonce = nonce; } } /** * Check Digest authentication on a simple transaction. * * <pre> * Alice AS * | | * | MESSAGE | * |--------------------------->| * | 401 | * |<---------------------------| * | MESSAGE | * |--------------------------->| * | 200 | * |<---------------------------| * </pre> */ @Test public void testAuthSucceed() throws Exception { _ua.addCredentials(new CredentialsImpl("Test", "user", "password")); SipServletRequest request = _ua.createRequest(SipMethods.MESSAGE, getTo()); SipServletResponse response = _ua.sendSynchronous(request); assertThat(response, isSuccess()); assertThat(response, hasHeader("servlet")); @SuppressWarnings("unchecked") List<SipServletResponse> responses = (List<SipServletResponse>) response .getRequest().getAttribute(SipServletResponse.class.getName()); assertThat(responses.size(), is(2)); assertThat(responses.get(0), hasStatus(SipServletResponse.SC_UNAUTHORIZED)); assertThat(responses.get(1), is(sameInstance(response))); } /** * Check a forbidden method. * * <pre> * Alice AS * | | * | FORBIDDEN_METHOD | * |--------------------------->| * | 403 | * |<---------------------------| * </pre> */ @Test public void testAuthForbidden() throws Exception { SipServletRequest request = _ua.createRequest("FORBIDDEN_METHOD", getTo()); SipServletResponse response = _ua.sendSynchronous(request); assertThat(response, hasStatus(SipServletResponse.SC_FORBIDDEN)); } /** * Check Digest authentication with a wrong password. * * <pre> * Alice AS * | | * | MESSAGE | * |--------------------------->| * | 401 | * |<---------------------------| * | MESSAGE | * |--------------------------->| * | 403 | * |<---------------------------| * </pre> */ @Test public void testInvalidPassword() throws Exception { _ua.addCredentials(new CredentialsImpl("Test", "user", "invalidPassword")); SipServletRequest request = _ua.createRequest(SipMethods.MESSAGE, getTo()); SipServletResponse response = _ua.sendSynchronous(request); assertThat(response, hasStatus(SipServletResponse.SC_FORBIDDEN)); @SuppressWarnings("unchecked") List<SipServletResponse> responses = (List<SipServletResponse>) response .getRequest().getAttribute(SipServletResponse.class.getName()); assertThat(responses.size(), is(2)); assertThat(responses.get(0), hasStatus(SipServletResponse.SC_UNAUTHORIZED)); assertThat(responses.get(1), is(sameInstance(response))); } /** * Check Digest authentication using an invalid Nonce. * * <pre> * Alice AS * | | * | MESSAGE | * |--------------------------->| * | 401 | * |<---------------------------| * | MESSAGE | * |--------------------------->| * | 401 | * |<---------------------------| * </pre> */ @Test public void testInvalidNonce() throws Exception { SipServletRequest request = _ua.createRequest(SipMethods.MESSAGE, getTo()); request.getSession().setInvalidateWhenReady(false); SipServletResponse response = _ua.sendSynchronous(request); assertThat(response, hasStatus(SipServletResponse.SC_UNAUTHORIZED)); MutableDigest digest = new MutableDigest( Authentication.createDigest(response.getHeader(SipHeaders.WWW_AUTHENTICATE))); digest.setNonce(digest.getNonce().substring(4) + "AAAA"); Authentication auth = new Authentication(digest); request = _ua.customize(request.getSession().createRequest(SipMethods.MESSAGE)); request.addHeader(SipHeaders.AUTHORIZATION, auth.authorize( request.getMethod(), request.getRequestURI().toString(), new CredentialsImpl("", "user", "password"))); response = _ua.sendSynchronous(request); assertThat(response, hasStatus(SipServletResponse.SC_UNAUTHORIZED)); assertThat(Authentication.createDigest( response.getHeader(SipHeaders.WWW_AUTHENTICATE)).isStale(), is(true)); } /** * Check Digest authentication on a complete dialog. * * <pre> * Alice AS * | | * | INVITE | * |--------------------------->| * | 401 | * |<---------------------------| * | ACK | * |--------------------------->| * | INVITE | * |--------------------------->| * | 200 | * |<---------------------------| * | ACK | * |--------------------------->| * | BYE | * |--------------------------->| * | 401 | * |<---------------------------| * | BYE | * |--------------------------->| * | 200 | * |<---------------------------| * </pre> */ @Test public void testCall() throws Exception { _ua.addCredentials(new CredentialsImpl("Test", "user", "password")); Call call = _ua.createCall(_ua.getFactory().createURI(getTo())); assertThat(call.waitForFinalResponse(), isSuccess()); Thread.sleep(50); call.createAck().send(); call.createRequest(SipMethods.BYE).send(); assertThat(call.waitForResponse(), isSuccess()); } }
34.559091
82
0.527423
22f3159d8468b4da539cf36ddb4dd40bd6b6faaa
6,476
package io.elastest.eim.test.e2e; import java.io.IOException; import java.util.Collections; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import com.google.gson.JsonObject; public class CpuCommandsGKETest1 { private String sut_address = "35.240.45.54"; private String URL_API = "http://"+sut_address+":5000"; private String server = "http://nightly.elastest.io:37004/eim/api/agent/"; public RestTemplate restTemplate = new RestTemplate(); public HttpHeaders headers = new HttpHeaders(); public static Long latency; static String agentId="iagent3"; @Test public void a_Test() throws InterruptedException, IOException{ System.out.println("############ Running Test 1: Calculate Base SLO Latency: ############"); long start = System.nanoTime(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); int responseCode = -1; long elapesedTimeInMiliSeconds = 0; try { HttpEntity<String> request = new HttpEntity<String>("", headers); ResponseEntity<String> response = restTemplate.exchange(URL_API, HttpMethod.GET, request, String.class); System.out.println(response); long elapsedTime = System.nanoTime() - start ; elapesedTimeInMiliSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS); responseCode= response.getStatusCode().value(); }catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); System.out.println(e.getCause()); } latency = elapesedTimeInMiliSeconds; System.out.println("Base SLO Latency before injection packetloss commands is: "+latency); Assertions.assertEquals(200, responseCode); } @Test public void b_Test() throws InterruptedException { System.out.println("############ Running test 2: Cpu test stress with stressor=10 over 30 seconds : ############"); String uri_packetloss_action = "controllability/"+agentId+"/stress"; String URL = server + uri_packetloss_action; JsonObject obj = new JsonObject(); obj.addProperty("exec", "EXECBEAT"); obj.addProperty("component", "EIM"); obj.addProperty("packetLoss", ""); obj.addProperty("stressNg", "10"); obj.addProperty("dockerized", "yes"); obj.addProperty("cronExpression", "@every 60s"); System.out.println("Payload: "+obj.toString()); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); int responseCode = -1; try { HttpEntity<String> request = new HttpEntity<String>( obj.toString(), headers); ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.POST, request, String.class); System.out.println("############ Response for Test3: ############"); System.out.println(response); TimeUnit.SECONDS.sleep(60); responseCode = response.getStatusCode().value(); }catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); System.out.println(e.getCause()); } Assertions.assertEquals(200, responseCode); } @Test public void c_Test() throws InterruptedException, IOException{ System.out.println("############ Running Test 3: Calculate SLO Latency after CPU injection command: ############"); long start = System.nanoTime(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); int responseCode = -1; long elapesedTimeInMiliSeconds = 0; try { HttpEntity<String> request = new HttpEntity<String>("", headers); ResponseEntity<String> response = restTemplate.exchange(URL_API, HttpMethod.GET, request, String.class); System.out.println(response); long elapsedTime = System.nanoTime() - start ; elapesedTimeInMiliSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS); responseCode= response.getStatusCode().value(); }catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); System.out.println(e.getCause()); } latency = elapesedTimeInMiliSeconds; System.out.println("SLO Latency after packetloss injection command is: "+latency); Assertions.assertEquals(200, responseCode); } @Test public void d_Test() throws InterruptedException { System.out.println("############ Running test 4: SLO Max.timing is: "+latency+". ############"); long start = System.nanoTime(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); int responseCode = -1; long elapesedTimeInMiliSeconds = 0; try { HttpEntity<String> request = new HttpEntity<String>("", headers); ResponseEntity<String> response = restTemplate.exchange(URL_API, HttpMethod.GET, request, String.class); System.out.println(response); long elapsedTime = System.nanoTime() - start ; elapesedTimeInMiliSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS); responseCode= response.getStatusCode().value(); }catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); System.out.println(e.getCause()); } Assertions.assertTrue(latency <= elapesedTimeInMiliSeconds, "SLO latency is <= "+latency+". Actual latency is: "+elapesedTimeInMiliSeconds+" ms"); } @Test public void e_Test() throws InterruptedException { System.out.println("############ Running Test 5: unchecked agent ############"); String uri_unistall_agent = agentId+"/unchecked"; String URL = server + uri_unistall_agent; headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); HttpEntity<String> request = new HttpEntity<String>("", headers); ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.DELETE, request, String.class); System.out.println("############ Response for Test 5: unchecked agent ############"); System.out.println(response); Assertions.assertEquals(200, response.getStatusCode().value()); } }
34.817204
117
0.71958
655c6ee309b1965088bebbadb6ff8dd8fccc8050
1,234
package com.bigdatalighter.kafka.offset.monitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author: Leo Zhang(johnson5211.work@gmail.com) **/ public class LoggingOffsetStateObserver extends AbsConsumerOffsetStateObserver { private Logger logger = LoggerFactory.getLogger(LoggingOffsetStateObserver.class); @Override protected void doCaughtUp(ConsumerOffsetState offsetState, ConsumerOffsetState.StateInfo stateInfo) { logger.info("Consumer[{}:{}] has caught up to target offset;", offsetState.getGroup(), offsetState.getTopic()); } @Override protected void doDelay(ConsumerOffsetState offsetState, ConsumerOffsetState.StateInfo stateInfo) { logger.warn("Consumer[{}:{}] has fallen behind target offset.Difference:{}.", offsetState.getGroup(), offsetState.getTopic(), stateInfo.getTotalDifference()); logger.warn("Partition\tCurrent offset\tConsumer offset\tDifference"); for (ConsumerOffsetState.PartitionOffsetDifference difference : stateInfo.getDifferences()) { logger.warn("{} \t {} \t {} \t {}", difference.getPartitionId(), difference.getCurrentOffset(), difference.getTargetOffset(), difference.getDifference()); } } }
45.703704
166
0.742301
cdae8701c416e543ce63192a87d15e66cfdb7cc7
1,585
package de.jpaw.bonaparte.refsc; import java.util.List; import de.jpaw.bonaparte.core.BonaPortableRef; import de.jpaw.bonaparte.pojos.api.DataWithTracking; import de.jpaw.bonaparte.pojos.api.SearchFilter; import de.jpaw.bonaparte.pojos.api.SortColumn; import de.jpaw.bonaparte.pojos.api.TrackingBase; import de.jpaw.bonaparte.refs.BaseRefResolver; import de.jpaw.util.ApplicationException; /** API to noSQL backends (mini EntityManager) for types inheriting from their key superclass. */ public interface RefResolver<REF extends BonaPortableRef, KEY extends REF, DTO extends KEY, TRACKING extends TrackingBase> extends BaseRefResolver<REF, DTO, TRACKING> { /** * Returns the key for the provided unique index. Null-safe, returns 0 for a null parameter. Throws an exception if the reference does not exist. */ KEY getRef(REF refObject) throws ApplicationException; /** * Returns a frozen copy of the tracking columns (to avoid tampering with them) for a given primary key. */ TRACKING getTracking(KEY ref) throws ApplicationException; /** * Removes the record referenced by the key. Does nothing if key is null. Throws an exception if the key does not exist. */ void remove(KEY key) throws ApplicationException; /** Returns a number of records for a query. * Throws UnsupportedOperationException in case the persistence provider does not support searches. */ List<DataWithTracking<DTO,TRACKING>> query(int limit, int offset, SearchFilter filter, List<SortColumn> sortColumns) throws ApplicationException; }
44.027778
168
0.762776
bacfa7f01ae1213018ed7ff28434ae65e6729fea
540
package com.fghifarr.tarkamleague.models.requests; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.*; import java.util.Set; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class SeasonReq { @NotBlank(message = "Name cannot be blank!") private String name; @NotNull(message = "Clubs cannot be null!") @Size(min = 3, max = 25, message = "Total clubs must be between 3 and 25!") private Set<Long> clubs; }
23.478261
79
0.746296
6bf1ff899dad01b9b2f53bdc17428105498ad23a
2,905
/** * Copyright 2020 Skyscanner Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.skyscanner.opentsdb_rollups.parser; import net.opentsdb.core.Internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.nio.ByteBuffer; import java.util.*; import static org.apache.commons.codec.binary.Hex.encodeHexString; public class TsdbTableParser implements Serializable { private static final Logger log = LoggerFactory.getLogger(TsdbTableParser.class); // TODO: Refactor this to make it configurable. public static final byte SALT_LENGTH = 1; public static final byte METRIC_UID_LENGTH = 3; public static final byte TIMESTAMP_LENGTH = 4; private static final int TAGK_LENGTH = 3; private static final int TAGV_LENGTH = 4; /** * Parse the row key of the tsdb table * @param byteKey - row key in bytes * @return the parsed {@link TsdbRowKey} */ public static TsdbRowKey parseTsdbTableRow(byte[] byteKey) throws ParseException { HashMap<byte[], byte[]> tags = new LinkedHashMap<>(); int pos = 0; pos += SALT_LENGTH; // Don't care about the salt byte[] metricUid = Arrays.copyOfRange(byteKey, pos, pos+=METRIC_UID_LENGTH); int timestamp = ByteBuffer.wrap(Arrays.copyOfRange(byteKey, pos, pos+=TIMESTAMP_LENGTH)).getInt(); if ((byteKey.length - SALT_LENGTH - METRIC_UID_LENGTH - TIMESTAMP_LENGTH) % (TAGK_LENGTH + TAGV_LENGTH) != 0) { throw new ParseException("TSDB table row " + encodeHexString(byteKey) + " was an incorrect length"); } int keyLimit = byteKey.length - TAGK_LENGTH - TAGV_LENGTH + 1; Set<String> tagKeys = new HashSet<>(); for (int i = pos; i < keyLimit; i += TAGK_LENGTH + TAGV_LENGTH) { int tagPos = i; byte[] tagK = Arrays.copyOfRange(byteKey, tagPos, tagPos+=TAGK_LENGTH); byte[] tagV = Arrays.copyOfRange(byteKey, tagPos, tagPos + TAGV_LENGTH); if (tagKeys.contains(encodeHexString(tagK))) { throw new ParseException("TSDB table row had duplicate tag key " + encodeHexString(tagK)); } else { tagKeys.add(encodeHexString(tagK)); } tags.put(tagK, tagV); } return new TsdbRowKey(metricUid, timestamp, tags); } }
37.727273
112
0.676764
bbd6838309f74d43c8e118bea62d9c9f83c58009
3,168
package com.alfianwibowo.ballonpopper.mainmenu; import android.animation.ObjectAnimator; import android.content.Intent; import android.graphics.drawable.GradientDrawable; import android.media.MediaPlayer; import android.os.Handler; import androidx.core.content.res.ResourcesCompat; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.animation.BounceInterpolator; import android.widget.Button; import android.widget.LinearLayout; import com.alfianwibowo.ballonpopper.R; public class CaraBermain extends AppCompatActivity { private ViewGroup mContentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cara_bermain); mContentView = findViewById(R.id.CaraBermain); mContentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setToFullScreen(); } }); LinearLayout m3linlay = findViewById(R.id.m3linlay); GradientDrawable gd1 = (GradientDrawable) m3linlay.getBackground(); gd1.setColor(ResourcesCompat.getColor(getResources(), R.color.google_yellow_light, null)); Button m3bk = findViewById(R.id.m3bk); GradientDrawable gd2 = (GradientDrawable) m3bk.getBackground(); gd2.setColor(ResourcesCompat.getColor(getResources(), R.color.google_yellow_light, null)); } public void Kembali(View v){ Button b1 = findViewById(R.id.m3bk); final MediaPlayer mp = MediaPlayer.create(this, R.raw.button); mp.start(); mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); ObjectAnimator animY = ObjectAnimator.ofFloat(b1, "translationY", -10f, 0f); animY.setDuration(1000); animY.setInterpolator(new BounceInterpolator()); animY.start(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), MainMenu.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }, 500); } private void setToFullScreen() { mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } @Override protected void onResume() { super.onResume(); setToFullScreen(); } }
34.064516
98
0.643624
ad9f931b1bc2126d3a47b8878648bd03edd54692
158
package sec03.exam05; import java.util.*; public class HashsetDemo { public static void main(String[] args) { // TODO Auto-generated method stub } }
12.153846
41
0.702532
d2ac076ad4234695adeba8e17dbf2a8615fea1de
650
package ooga.utilities; public class Coordinate { private int x; private int y; /** * This class encapsulates the x, and y coordinates of an entity. * Can be extended to have three dimensional coordinate system * @param x the x location of an entity * @param y the y location of an entity */ public Coordinate(int x, int y) { this.x = x; this.y = y; } /** * * @return the x location of an entity */ public int getX() { return x; } /** * * @return the y location of an entity */ public int getY() { return y; } }
17.567568
69
0.541538
4e10373d655d78d1925b01ba11d0efa9c03545fb
2,021
/* * Copyright 2015 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.nbasearc.gcp; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; class SingleThreadEventLoopTrunk { private final SingleThreadEventLoop[] eventLoops; private final AtomicInteger roundrobin = new AtomicInteger(); SingleThreadEventLoopTrunk(int threadPoolSize) { eventLoops = new SingleThreadEventLoop[threadPoolSize]; for (int i = 0; i < threadPoolSize; i++) { eventLoops[i] = new SingleThreadEventLoop(); eventLoops[i].init(); } } ListenableFuture<?> close() { final SettableFuture<?> sf = SettableFuture.create(); final AtomicInteger counter = new AtomicInteger(eventLoops.length); for (final SingleThreadEventLoop eventLoop : eventLoops) { eventLoop.close().addListener(new Runnable() { @Override public void run() { if (counter.decrementAndGet() == 0) { sf.set(null); } } }, MoreExecutors.directExecutor()); } return sf; } SingleThreadEventLoop roundrobinEventLoop() { return eventLoops[Math.abs(roundrobin.incrementAndGet()) % eventLoops.length]; } }
34.254237
86
0.666007
bbd5ce5914a7abe7142942266475d7e663eaf515
4,735
package com.e.typt.core.config.mybatis; import com.baomidou.mybatisplus.MybatisConfiguration; import com.baomidou.mybatisplus.MybatisXMLLanguageDriver; import com.baomidou.mybatisplus.entity.GlobalConfiguration; import com.baomidou.mybatisplus.enums.DBType; import com.baomidou.mybatisplus.enums.IdType; import com.baomidou.mybatisplus.mapper.AutoSqlInjector; import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean; import org.apache.ibatis.mapping.DatabaseIdProvider; import org.apache.ibatis.plugin.Interceptor; import org.mybatis.spring.boot.autoconfigure.MybatisProperties; import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import javax.sql.DataSource; import java.io.IOException; /** * mybatis-plus配置 */ @Configuration @EnableConfigurationProperties(MybatisProperties.class) public class MybatisPlusConfig { @Autowired private Environment environment; //private RelaxedPropertyResolver propertyResolver; @Autowired private DataSource dataSource; @Autowired private MybatisProperties properties; @Autowired private ResourceLoader resourceLoader = new DefaultResourceLoader(); @Autowired(required = false) private Interceptor[] interceptors; @Autowired(required = false) private DatabaseIdProvider databaseIdProvider; /** * mybatis-plus分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType("mysql"); return page; } /** * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定 * 配置文件和mybatis-boot的配置文件同步 */ @Bean public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() throws IOException { MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean(); mybatisPlus.setDataSource(dataSource); mybatisPlus.setVfs(SpringBootVFS.class); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); mybatisPlus.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); if (StringUtils.hasText(this.properties.getConfigLocation())) { mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation())); } mybatisPlus.setConfiguration(properties.getConfiguration()); if (!ObjectUtils.isEmpty(this.interceptors)) { mybatisPlus.setPlugins(this.interceptors); } // MP 全局配置,更多内容进入类看注释 GlobalConfiguration globalConfig = new GlobalConfiguration(); globalConfig.setDbType(DBType.MYSQL.name());//数据库类型 // ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") //使用ID_WORKER_STR,因为前后端分离使用整形,前端JS会有精度丢失 globalConfig.setIdType(IdType.ID_WORKER_STR.getKey()); globalConfig.setSqlInjector(new AutoSqlInjector()); //MP 属性下划线 转 驼峰 , 如果原生配置 mc.setMapUnderscoreToCamelCase(true) 开启,该配置可以无。 //globalConfig.setDbColumnUnderline(true); mybatisPlus.setGlobalConfig(globalConfig); MybatisConfiguration mc = new MybatisConfiguration(); // 对于完全自定义的mapper需要加此项配置,才能实现下划线转驼峰 mc.setMapUnderscoreToCamelCase(true); mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); mybatisPlus.setConfiguration(mc); if (this.databaseIdProvider != null) { mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider); } if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) { mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage()); } if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) { mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage()); } if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) { mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations()); } return mybatisPlus; } }
40.470085
112
0.754593
b67915c6a0b5efd7bc8eb18a952bf47d7cf1a471
1,712
/******************************************************************************* * Copyright 2013 Geoscience Australia * * 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 au.gov.ga.earthsci.core.retrieve.retriever; import au.gov.ga.earthsci.core.retrieve.RetrievalProperties; /** * Basic implementation of {@link IHttpRetrievalProperties}. * * @author Michael de Hoog (michael.dehoog@ga.gov.au) */ public class HttpRetrievalProperties extends RetrievalProperties implements IHttpRetrievalProperties { private String requestMethod; private byte[] requestPayload; private String contentType; @Override public String getRequestMethod() { return requestMethod; } public void setRequestMethod(String requestMethod) { this.requestMethod = requestMethod; } @Override public byte[] getRequestPayload() { return requestPayload; } public void setRequestPayload(byte[] requestPayload) { this.requestPayload = requestPayload; } @Override public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } }
26.75
100
0.689252
1b66165630b9e6dc88ba7d9b71570e743c63fa97
219
package lego.ev3.core; /** * Created by Andrei Tanas on 14-11-28. */ public class ArgumentException extends Throwable { public ArgumentException(String message, String argument) { super(message); } }
19.909091
63
0.694064
595dd6354c48d017fb5419f9c694afb2607f47e1
4,906
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.dimm.vsm.fsengine; import de.dimm.vsm.LogicControl; import de.dimm.vsm.Main; import de.dimm.vsm.auth.User; import de.dimm.vsm.log.Log; import de.dimm.vsm.net.StoragePoolQry; import de.dimm.vsm.records.StoragePool; import java.io.IOException; import java.sql.SQLException; /** * * @author Administrator */ public class StoragePoolHandlerFactory { static boolean jpa = false; private static boolean persistRunnerEnabled = false; public static StoragePoolHandler createStoragePoolHandler(StoragePool pool, User user, boolean rdonly) throws IOException { return createStoragePoolHandler( LogicControl.getStorageNubHandler(), pool, user, rdonly); } public static StoragePoolHandler createStoragePoolHandler( IStoragePoolNubHandler nubHandler, StoragePool _pool, User user, boolean rdonly ) throws IOException { return createStoragePoolHandler(nubHandler, _pool, user, rdonly, /* * showDeleted */ false); } public static StoragePoolHandler createStoragePoolHandler( IStoragePoolNubHandler nubHandler, StoragePool _pool, User user, boolean rdonly, boolean showDeleted ) throws IOException { try { StoragePool pool; if ( Main.get_control() != null) { pool = Main.get_control().getStoragePool(_pool.getIdx()); Log.debug("Offene DB-Verbindungen", "" + LogicControl.getStorageNubHandler().getActiveConnections(pool) ); } else { pool = _pool; } // RELOAD FROM LIST JDBCConnectionFactory conn = nubHandler.getConnectionFactory(pool); JDBCEntityManager em = new JDBCEntityManager(pool.getIdx(), conn); StoragePoolQry qry; if (rdonly) qry = StoragePoolQry.createActualRdOnlyStoragePoolQry(user, showDeleted); else qry = StoragePoolQry.createActualRdWrStoragePoolQry(user, showDeleted); JDBCStoragePoolHandler sp_handler = createStoragePoolHandlerbyQry( em, pool, qry ); if (isPersistRunnerEnabled()) { HandlePersistRunner persistRunner = new HandlePersistRunner(); sp_handler.setPersistRunner(persistRunner); } return sp_handler; } catch (SQLException sQLException) { String msg = Main.Txt("Kann DB-Verbindung nicht öffnen"); Log.err(msg, _pool.toString(), sQLException); throw new IOException( msg, sQLException); } } public static void setPersistRunnerEnabled( boolean persistRunnerEnabled ) { StoragePoolHandlerFactory.persistRunnerEnabled = persistRunnerEnabled; } public static boolean isPersistRunnerEnabled() { return persistRunnerEnabled; } private static JDBCStoragePoolHandler createStoragePoolHandlerbyQry(JDBCEntityManager em, StoragePool pool, StoragePoolQry qry) throws SQLException { JDBCStoragePoolHandler sp_handler; if (qry.getUser() != null && !qry.getUser().isAdmin()) { sp_handler = new UserMappedStoragePoolHandler( em, pool, qry ); } else { sp_handler = new JDBCStoragePoolHandler( em, pool, qry ); } return sp_handler; } public static StoragePoolHandler createStoragePoolHandler(StoragePool pool, StoragePoolQry qry) throws IOException { return createStoragePoolHandler( LogicControl.getStorageNubHandler(), pool, qry); } public static StoragePoolHandler createStoragePoolHandler( IStoragePoolNubHandler nubHandler, StoragePool _pool, StoragePoolQry qry ) throws IOException { try { // RELOAD FROM LIST StoragePool pool = Main.get_control().getStoragePool(_pool.getIdx()); JDBCConnectionFactory conn = nubHandler.getConnectionFactory(pool); JDBCEntityManager em = new JDBCEntityManager(pool.getIdx(), conn); JDBCStoragePoolHandler sp_handler = createStoragePoolHandlerbyQry( em, pool, qry ); if (isPersistRunnerEnabled()) { HandlePersistRunner persistRunner = new HandlePersistRunner(); sp_handler.setPersistRunner(persistRunner); } return sp_handler; } catch (Exception sQLException) { Log.err("Kann DB-Verbindung nicht öffnen", _pool.toString(), sQLException); throw new IOException(Main.Txt("Kann DB-Verbindung nicht öffnen"), sQLException); } } }
36.61194
189
0.637383
b397ac75d8beacc86aa73c7ca9e8c843d6b5f7e4
4,376
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/retail/v2alpha/prediction_service.proto package com.google.cloud.retail.v2alpha; public interface PredictResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.retail.v2alpha.PredictResponse) com.google.protobuf.MessageOrBuilder { /** * <pre> * A list of recommended products. The order represents the ranking (from the * most relevant product to the least). * </pre> * * <code>repeated .google.cloud.retail.v2alpha.PredictResponse.PredictionResult results = 1;</code> */ java.util.List<com.google.cloud.retail.v2alpha.PredictResponse.PredictionResult> getResultsList(); /** * <pre> * A list of recommended products. The order represents the ranking (from the * most relevant product to the least). * </pre> * * <code>repeated .google.cloud.retail.v2alpha.PredictResponse.PredictionResult results = 1;</code> */ com.google.cloud.retail.v2alpha.PredictResponse.PredictionResult getResults(int index); /** * <pre> * A list of recommended products. The order represents the ranking (from the * most relevant product to the least). * </pre> * * <code>repeated .google.cloud.retail.v2alpha.PredictResponse.PredictionResult results = 1;</code> */ int getResultsCount(); /** * <pre> * A list of recommended products. The order represents the ranking (from the * most relevant product to the least). * </pre> * * <code>repeated .google.cloud.retail.v2alpha.PredictResponse.PredictionResult results = 1;</code> */ java.util.List<? extends com.google.cloud.retail.v2alpha.PredictResponse.PredictionResultOrBuilder> getResultsOrBuilderList(); /** * <pre> * A list of recommended products. The order represents the ranking (from the * most relevant product to the least). * </pre> * * <code>repeated .google.cloud.retail.v2alpha.PredictResponse.PredictionResult results = 1;</code> */ com.google.cloud.retail.v2alpha.PredictResponse.PredictionResultOrBuilder getResultsOrBuilder( int index); /** * <pre> * A unique attribution token. This should be included in the * [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs resulting from this * recommendation, which enables accurate attribution of recommendation model * performance. * </pre> * * <code>string attribution_token = 2;</code> * @return The attributionToken. */ java.lang.String getAttributionToken(); /** * <pre> * A unique attribution token. This should be included in the * [UserEvent][google.cloud.retail.v2alpha.UserEvent] logs resulting from this * recommendation, which enables accurate attribution of recommendation model * performance. * </pre> * * <code>string attribution_token = 2;</code> * @return The bytes for attributionToken. */ com.google.protobuf.ByteString getAttributionTokenBytes(); /** * <pre> * IDs of products in the request that were missing from the inventory. * </pre> * * <code>repeated string missing_ids = 3;</code> * @return A list containing the missingIds. */ java.util.List<java.lang.String> getMissingIdsList(); /** * <pre> * IDs of products in the request that were missing from the inventory. * </pre> * * <code>repeated string missing_ids = 3;</code> * @return The count of missingIds. */ int getMissingIdsCount(); /** * <pre> * IDs of products in the request that were missing from the inventory. * </pre> * * <code>repeated string missing_ids = 3;</code> * @param index The index of the element to return. * @return The missingIds at the given index. */ java.lang.String getMissingIds(int index); /** * <pre> * IDs of products in the request that were missing from the inventory. * </pre> * * <code>repeated string missing_ids = 3;</code> * @param index The index of the value to return. * @return The bytes of the missingIds at the given index. */ com.google.protobuf.ByteString getMissingIdsBytes(int index); /** * <pre> * True if the validateOnly property was set in the request. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ boolean getValidateOnly(); }
32.176471
102
0.687614
6f342d563554db22bbdd4a51958e715e748fdf4a
1,661
package com.example.phone_notes.activity; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.example.phone_notes.R; import com.example.phone_notes.base.BaseActivity; import com.example.phone_notes.constant.myConstant; import com.example.phone_notes.utils.ToastUtils; //登录界面 public class LoginActivity extends BaseActivity { private EditText input_password;// 密码框 private Button ensure;// 确定按钮 private String password;// 密码 @Override protected void initView() { setContentView(R.layout.activity_login); input_password = (EditText) findViewById(R.id.input_password); ensure = (Button) findViewById(R.id.ensure); } @Override protected void initData() { input_password.requestFocus(); } @Override protected void initListener() { // 确定按钮点击事件 ensure.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { password = mPreferences.getString(myConstant.PASS, ""); if (TextUtils.isEmpty(input_password.getText().toString())) { ToastUtils.show(mContext, "请输入密码"); } else if (input_password.getText().toString().equals(password)) { // 密码正确,进入主界面 MainActivity.enterMain(mContext, MainActivity.class); finish(); } else { ToastUtils.show(mContext, "密码错误,请重新输入"); input_password.setText(""); } } }); } // 进入登录界面方法封装 public static void enterLogin(Context con, Class<LoginActivity> class1) { Intent intent = new Intent(con, class1); con.startActivity(intent); } }
26.790323
74
0.74112
dbc5879a9572b7eaf5ebc435adf8bf8808ba824b
2,610
/* * Copyright 2016, Red Hat Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.infinispan.objectfilter.impl.ql; import org.antlr.runtime.tree.Tree; /** * Defines hooks for implementing custom logic when walking the parse tree of a JPQL query. * * @author Gunnar Morling * @author anistor@redhat.com * @since 9.0 */ public interface QueryResolverDelegate<TypeDescriptor> { void registerPersisterSpace(String entityName, Tree alias); void registerJoinAlias(Tree alias, PropertyPath<TypeDescriptor> path); boolean isUnqualifiedPropertyReference(); PropertyPath.PropertyReference<TypeDescriptor> normalizeUnqualifiedPropertyReference(Tree propertyNameTree); boolean isPersisterReferenceAlias(); PropertyPath.PropertyReference<TypeDescriptor> normalizeUnqualifiedRoot(Tree aliasTree); PropertyPath.PropertyReference<TypeDescriptor> normalizeQualifiedRoot(Tree root); PropertyPath.PropertyReference<TypeDescriptor> normalizePropertyPathIntermediary(PropertyPath<TypeDescriptor> path, Tree propertyNameTree); PropertyPath.PropertyReference<TypeDescriptor> normalizeIntermediateIndexOperation(PropertyPath.PropertyReference<TypeDescriptor> propertyReference, Tree collectionProperty, Tree selector); void normalizeTerminalIndexOperation(PropertyPath.PropertyReference<TypeDescriptor> propertyReference, Tree collectionProperty, Tree selector); PropertyPath.PropertyReference<TypeDescriptor> normalizeUnqualifiedPropertyReferenceSource(Tree identifier); PropertyPath.PropertyReference<TypeDescriptor> normalizePropertyPathTerminus(PropertyPath<TypeDescriptor> path, Tree propertyNameTree); void activateFromStrategy(JoinType joinType, Tree associationFetchTree, Tree propertyFetchTree, Tree alias); void activateSelectStrategy(); void deactivateStrategy(); /** * Notifies this delegate when parsing of a property path in the SELECT or WHERE is completed. * * @param path the completely parsed property path */ void propertyPathCompleted(PropertyPath<TypeDescriptor> path); }
39.545455
192
0.8
87fd83fdc33111a32b9b24b628d4cf983b05a910
3,999
/** * pims-web org.pimslims.data XmlExporter.java * * @author pajanne * @date Jan 12, 2009 * * Protein Information Management System * @version: 2.2 * * Copyright (c) 2009 pajanne The copyright holder has licenced the STFC to redistribute this * software */ package org.pimslims.xmlio; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.pimslims.properties.PropertyGetter; import org.xml.sax.SAXException; /** * XmlExporter * */ public class XmlConvertor { /** * Converts Java XML bean object to XML output string * * @param bean * @return xml string * @throws JAXBException */ public static String convertBeanToXml(final Object bean, final String schemaName) throws JAXBException { assert null != bean : "ERROR: Object must not be null."; try { final JAXBContext context = JAXBContext.newInstance(bean.getClass()); final Marshaller marshaller = context.createMarshaller(); if (null != schemaName) { final Schema schema = XmlConvertor.getSchema(schemaName); marshaller.setSchema(schema); } final StringWriter sw = new StringWriter(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(bean, sw); return sw.toString(); } catch (final SAXException e) { // bad schema throw new RuntimeException(e); } } /** * Converts XML input string into java XML bean * * @param xml * @param classContext * @param schemaName * @return Object * @throws JAXBException * @throws SAXException * @throws IOException */ public static <T> T convertXmlToBean(final String xml, final Class<T> classContext, final String schemaName) throws JAXBException, SAXException, IOException { // see http://www.java.net/forum/topic/glassfish/metro-and-jaxb/linkageerror-duplicate-class-definition-0 System.setProperty("com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize", "true"); final InputStream in = new ByteArrayInputStream(xml.getBytes()); final JAXBContext context = JAXBContext.newInstance(classContext); final Unmarshaller unmarshaller = context.createUnmarshaller(); final Schema schema = XmlConvertor.getSchema(schemaName); unmarshaller.setSchema(schema); final BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); return classContext.cast(unmarshaller.unmarshal(reader)); } private static Schema getSchema(final String schemaName) throws SAXException { final File schemaFile = PropertyGetter.getFileProperty("xsd schema", schemaName); final Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile); return schema; } /** * Converts InputStream to String * * @param in * @return * @throws IOException */ public static String convertStreamToString(final InputStream in) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } in.close(); return sb.toString(); } }
33.049587
113
0.668417
6f835ba293f15a061ee0900af9c63fa8a975729c
353
package com.xuxianda.thread; /** * Created by Xianda Xu on 2017/08/17 11:27. */ public class MyThread extends Thread { private String name; public MyThread(String name){ this.name = name; } @Override public void run() { for(int i = 0 ;i<10000;i++){ System.out.println(name+":"+i); } } }
16.809524
44
0.558074
2f85a986ac3ab2a1c278a320f3b175f8645ac45c
3,080
/** * Copyright (C) 2014 Xillio (support@xillio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.xillio.xill.plugins.mongodb.services; import com.google.inject.Inject; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import nl.xillio.xill.api.components.MetaExpression; import org.bson.Document; import java.util.Map; import java.util.concurrent.TimeUnit; /** * This class is responsible for wrapping the functionality of parsing and getting an FindIterable. * * @author Pieter Dirk Soels */ public class FindIterableBuilder extends MongoIterableFactory { private MongoConverter mongoConverter; @Inject void setMongoConverter(MongoConverter mongoConverter) { this.mongoConverter = mongoConverter; } /** * This function parses the given arguments to BSON-documents and runs the query on the collection. * * @param collection the collection of data to execute the query on * @param arguments the parts of the query in this particular order: filter, projection, sort * @return the iterable containing the result of the query */ public FindIterable<Document> getIterable(MongoCollection<Document> collection, MetaExpression[] arguments) { // Parse the arguments. Document filter = mongoConverter.parse(arguments[0]); Document projection = mongoConverter.parse(arguments[1]); Document sort = mongoConverter.parse(arguments[2]); Map<String, MetaExpression> options = arguments[3].getValue(); // Create the find iterable. FindIterable<Document> result = collection.find(filter).projection(projection).sort(sort); // Process all options. options.forEach((option, value) -> processOption(option, value, result)); return result; } private void processOption(String option, MetaExpression value, FindIterable<Document> iterable) { switch (option) { case "limit": iterable.limit(value.getNumberValue().intValue()); break; case "skip": iterable.skip(value.getNumberValue().intValue()); break; case "maxTime": iterable.maxTime(value.getNumberValue().longValue(), TimeUnit.MILLISECONDS); break; case "noCursorTimeout": iterable.noCursorTimeout(value.getBooleanValue()); break; default: super.processOption(option, value, iterable); } } }
37.108434
113
0.681494
178f549da5f25e768f04703b4ff1c2643ebac14c
8,140
// BlockLimiter // // Part of DAVE-ML utility suite, written by Bruce Jackson, NASA LaRC // <bruce.jackson@nasa.gov> // Visit <http://daveml.org> for more info. // Latest version can be downloaded from http://dscb.larc.nasa.gov/Products/SW/DAVEtools.html // Copyright (c) 2011 United States Government as represented by LAR-17460-1. No copyright is // claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved. package gov.nasa.daveml.dave; /** * * <p> Object representing a two-sided limiter block </p> * <p> 2010-12-15 Bruce Jackson, NASA Langley Research Center * <mailto:bruce.jackson@nasa.gov> </p> * @author Bruce Jackson * **/ import java.io.IOException; import java.io.Writer; /** * * <p> The Limiter Block provides upper and lower limits to an input signal. </p> * **/ public class BlockLimiter extends Block { /** * units of measure of downstream block */ String units; /** * lower limit, or -Inf */ Double lowerLim; /** * upper limit, or +Inf */ Double upperLim; /** * indicates presence of lower limit (not -Inf) */ boolean hasLowerLim; /** * indicates presence of valid upper limit (not +Inf) */ boolean hasUpperLim; /** * * <p> Constructor for output Block <p> * * @param sourceSignal Upstream <code>Signal</code> with which to connect * @param m <code>Model</code> we're part of * @param lowerLimit <code>String</code> representing the minimum value we can pass (-Infinity means no limit) * @param upperLimit <code>String</code> representing the maximum value we can pass (+Infinity means no limit) * **/ public BlockLimiter( Signal sourceSignal, Model m, double lowerLimit, double upperLimit ) { // Initialize superblock elements super(sourceSignal.getName()+ " limiter", "limiter", 1, m); // record our U of M this.units = sourceSignal.getUnits(); // record limits lowerLim = lowerLimit; upperLim = upperLimit; // ensure correct order if (lowerLim > upperLim) { Double temp = lowerLim; lowerLim = upperLim; upperLim = temp; } // set limiting flags hasLowerLim = !lowerLim.isInfinite(); hasUpperLim = !upperLim.isInfinite(); // hook up to upstream signal //System.out.println(" BlockOutput constructor: " + myName + " is hooking up to signal " + sourceSignal.getName()); sourceSignal.addSink( this, 1 ); //System.out.println(" BlockOutput constructor: " + myName + " as output " + seqNumber); } /** * <p> Returns the output value </p> * * <p> This method is distinguished from normal * <code>Block.getValue()</code> in that it is public</p> * **/ @Override public double getValue() { return this.value; } /** * <p> Returns the units of measure of the output signal </p> * **/ public String getUnits() { return this.units; } /** * <p> Generates C algorithm to limit input to output</p> */ @Override public CodeAndVarNames genCode() { CodeAndVarNames cvn = new CodeAndVarNames(); String rel; Signal input; Signal outputSig = this.getOutput(); // check to see if we're derived variable (code fragment) or a whole statement // if not derived, need preceding command and the LHS of the equation too if (outputSig != null) { if (!outputSig.isDerived()) { // cvn.code = "// Code for variable \"" + outVarID + "\":\n"; cvn.appendCode(indent() + outVarID + " = "); cvn.addVarName(outVarID); } } input = inputs.get(0); int dialect = ourModel.getCodeDialect(); cvn.append( input.genCode() ); if (this.hasLowerLimit()) { cvn.appendCode(endLine()); rel = " < "; // default is DT_ANSI_C if (dialect == Model.DT_FORTRAN) { rel = " .LT. "; } cvn.appendCode(beginIf( outVarID + rel + lowerLim.toString() )); cvn.appendCode(indent() + " " + outVarID + " = " + lowerLim.toString()); cvn.appendCode(endLine()); cvn.appendCode(endIf()); } if (this.hasUpperLimit()) { if (!this.hasLowerLimit()) { cvn.appendCode(endLine()); // don't issue blank line } rel = " > "; // default is DT_ANSI_C if (dialect == Model.DT_FORTRAN) { rel = " .GT. "; } cvn.appendCode(beginIf( outVarID + rel + upperLim.toString() )); cvn.appendCode(indent() + " " + outVarID + " = " + upperLim.toString()); cvn.appendCode(endLine()); cvn.appendCode(endIf()); } // if not derived, need trailing semicolon and new line if no limits if (outputSig != null) { if (!outputSig.isDerived()) { if (!this.hasLowerLimit() && !this.hasUpperLimit() ) { cvn.appendCode(endLine()); } } } return cvn; } /** * * <p> Generates description of self </p> * * @throws <code>IOException</code> **/ @Override public void describeSelf(Writer writer) throws IOException { super.describeSelf(writer); writer.write(" (" + units + ") and is a limiter block with " + "a lower limit of " + lowerLim + " and an upper limit of " + upperLim + "."); } /** * * <p> Implements update() method </p> * @throws DAVEException * **/ @Override public void update() throws DAVEException { if (isVerbose()) { System.out.println(); System.out.println("Method update() called for limiter block '" + this.getName() + "'"); } // Check to see if only one input if (this.inputs.size() < 1) { throw new DAVEException(" Limiter block " + this.myName + " has no input."); } if (this.inputs.size() > 1) { throw new DAVEException(" Limiter block " + this.myName + " has more than one input."); } // see if single input variable is ready Signal theInput = this.inputs.get(0); if (!theInput.sourceReady()) { if (this.isVerbose()) { System.out.println(" Upstream signal '" + theInput.getName() + "' is not ready."); } return; } // get single input variable value double inputValue = theInput.sourceValue(); if (this.isVerbose()) { System.out.println(" Input value is " + inputValue); } // show ourselves up-to-date this.resultsCycleCount = ourModel.getCycleCounter(); // save answer this.value = inputValue; if (hasLowerLim) { if( this.value < lowerLim ) { this.value = lowerLim; } } if (hasUpperLim) { if( this.value > upperLim ) { this.value = upperLim; } } } /** * Indicates a practical lower limit has been defined * @return true if lower limit exists */ public boolean hasLowerLimit() { return hasLowerLim; } /** * Indicates a practical upper limit has been defined * @return true if upper limit exists */ public boolean hasUpperLimit() { return hasUpperLim; } /** * Returns the value of the lower limit * @return lower limit as a double */ public double getLowerLimit() { return lowerLim.doubleValue(); } /** * Returns the value of the upper limit * @return upper limit as a double */ public double getUpperLimit() { return upperLim.doubleValue(); } }
28.661972
126
0.547052
17458e45853595d3a9609f6b9bb6ddcaa9cfd15d
4,145
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.msu.cme.pyro.cluster.io; import edu.msu.cme.pyro.cluster.io.RDPClustParser.Cutoff; import edu.msu.cme.pyro.cluster.utils.Cluster; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * * @author Jordan Fish <fishjord at msu.edu> */ public class ClusterToBiom { private static void writeHeader(PrintStream out) { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); out.println("\"id\":null,"); out.println("\"format\":\"Biological Observation Matrix 1.0.0\","); out.println("\"format_url\": \"http://biom-format.org\","); out.println("\"type\": \"OTU table\","); out.println("\"generated_by\": \"RDP mcClust\","); out.println("\"date\" : \"" + df.format(new Date()) + "\","); } private static void writeRowsHeader( Cutoff c, PrintStream out) { Map<String, List<Cluster>> clusters = c.getClusters(); out.println("\"rows\" : ["); HashSet<Integer> seenCluster = new HashSet<Integer>(); int index = 0; for( List<Cluster> clusterList: clusters.values()) { for ( Cluster clust: clusterList){ if ( !seenCluster.contains(clust.getId())) { // should print out the cluster id out.print("\t {\"id\" : \"cluster_" + clust.getId() +"\", \"metadata\" : null }"); if(index + 1 != c.getNumClusters()) { out.print(","); } out.println(); seenCluster.add(clust.getId()); index++; } } } out.println("],"); } private static void writeColsHeader(List<String> clusters, PrintStream out) { out.println("\"columns\" : ["); for(int index = 0;index < clusters.size();index++) { out.print("\t {\"id\" : \"" + clusters.get(index) +"\", \"metadata\" : null }"); if(index + 1 != clusters.size()) { out.print(","); } out.println(); } out.println("],"); } public static void writeCutoff(Cutoff c, PrintStream out) { Map<String, List<Cluster>> clusters = c.getClusters(); List<String> sampleNames = new ArrayList(clusters.keySet()); Collections.sort(sampleNames); out.println("{"); writeHeader(out); writeRowsHeader(c, out); writeColsHeader(sampleNames, out); out.println("\"matrix_type\": \"dense\","); out.println("\"matrix_element_type\": \"int\","); out.println("\"shape\": [" + c.getNumClusters() + ", " + sampleNames.size() + "],"); out.println("\"data\": ["); for(int row = 0;row < c.getNumClusters();row++) { out.print("\t["); for(int col = 0;col < sampleNames.size();col++) { out.print(clusters.get(sampleNames.get(col)).get(row).getNumberOfSeqs()); if(col + 1 != sampleNames.size()) { out.print(","); } } out.print("]"); if(row + 1 != c.getNumClusters()) { out.print(","); } out.println(); } out.println("]"); out.println("}"); } public static void main(String[] args) throws IOException { if( args.length != 3){ throw new IllegalArgumentException("Usage: clusterfile out.biom distance"); } RDPClustParser parser = new RDPClustParser(new File(args[0]), false); PrintStream out = new PrintStream(args[1]); writeCutoff(parser.getCutoff(args[2]), out); out.close(); } }
35.127119
102
0.541616