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
1e2e4b73164efd15c745ef64ee9a1270c164e6db
5,720
package org.dhis2.fhir.adapter.fhir.transform.dhis.impl.util.dstu3; /* * Copyright (c) 2004-2019, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.dhis2.fhir.adapter.dhis.converter.ValueConverter; import org.dhis2.fhir.adapter.fhir.script.ScriptExecutionContext; import org.dhis2.fhir.adapter.geo.Location; import org.dhis2.fhir.adapter.geo.StringToLocationConverter; import org.dhis2.fhir.adapter.spring.StaticObjectProvider; import org.hl7.fhir.dstu3.model.Address; import org.hl7.fhir.dstu3.model.DecimalType; import org.hl7.fhir.dstu3.model.Location.LocationPositionComponent; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.support.DefaultConversionService; import java.math.BigDecimal; import java.util.Collections; import java.util.Objects; /** * Unit tests for {@link Dstu3GeoDhisToFhirTransformerUtils}. * * @author volsch */ public class Dstu3GeoDhisToFhirTransformerUtilsTest { @Mock private ScriptExecutionContext scriptExecutionContext; private Dstu3GeoDhisToFhirTransformerUtils utils; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Before public void before() { final ConversionService conversionService = new DefaultConversionService(); final ValueConverter valueConverter = new ValueConverter( new StaticObjectProvider<>( Collections.singletonList( new StringToLocationConverter() ) ) ); utils = new Dstu3GeoDhisToFhirTransformerUtils( scriptExecutionContext, valueConverter ); } @Test public void createPositionNull() { Assert.assertNull( utils.createPosition( null ) ); } @Test public void createPosition() { final Location location = new Location( 47.1, -23.2 ); final LocationPositionComponent position = (LocationPositionComponent) utils.createPosition( location ); Assert.assertEquals( 47.1, Objects.requireNonNull( position ).getLongitude().doubleValue(), 0.0 ); Assert.assertEquals( -23.2, Objects.requireNonNull( position ).getLatitude().doubleValue(), 0.0 ); } @Test public void updateAddressLocationNull() { final Address address = new Address(); utils.updateAddressLocation( address, null ); Assert.assertEquals( 0, address.getExtensionsByUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ).size() ); } @Test public void updateAddressLocationRemoved() { final Address address = new Address(); address.addExtension().setUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ); utils.updateAddressLocation( address, null ); Assert.assertEquals( 0, address.getExtensionsByUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ).size() ); } @Test public void updateAddressLocationAddress() { final Address address = new Address(); final Location location = new Location( 47.1, -23.2 ); utils.updateAddressLocation( address, location ); Assert.assertEquals( 1, address.getExtensionsByUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ).size() ); Assert.assertEquals( 1, address.getExtensionsByUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ).get( 0 ) .getExtensionsByUrl( "longitude" ).size() ); Assert.assertEquals( BigDecimal.valueOf( 47.1 ), ( (DecimalType) address.getExtensionsByUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ).get( 0 ) .getExtensionsByUrl( "longitude" ).get( 0 ).getValue() ).getValueAsNumber() ); Assert.assertEquals( 1, address.getExtensionsByUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ).get( 0 ) .getExtensionsByUrl( "latitude" ).size() ); Assert.assertEquals( BigDecimal.valueOf( -23.2 ), ( (DecimalType) address.getExtensionsByUrl( "http://hl7.org/fhir/StructureDefinition/geolocation" ).get( 0 ) .getExtensionsByUrl( "latitude" ).get( 0 ).getValue() ).getValueAsNumber() ); } }
45.396825
166
0.738112
58875b72496ce2eb52c779bb4fb0aa73d155910c
638
package com.example.administrator.testone.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.AppCompatTextView; import android.widget.AutoCompleteTextView; import android.widget.EditText; import com.example.administrator.testone.R; public class MyLoginActivity extends AppCompatActivity { private AutoCompleteTextView tv_user_name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_login); tv_user_name=findViewById(R.id.tv_user_name); } }
27.73913
56
0.793103
a719a435834ba8dc656619f49184a3a969a3af90
374
package ppt; import java.awt.Dimension; import java.util.ArrayList; import java.util.List; public class Table extends Element { List<TableRow> tablerows = new ArrayList<>(); public Table(double pX, double pY, List<TableRow> tr, Dimension sz) { super(pX, pY, sz); tablerows = tr; } public Table(double pX, double pY, Dimension sz) { super(pX, pY, sz); } }
18.7
70
0.692513
c65554760add6ee3e631bfedec5dcb0d0fcafd04
4,682
/* * Copyright © 2020 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.delta.app; import com.google.gson.Gson; import io.cdap.cdap.api.common.Bytes; import io.cdap.delta.api.ReplicationError; import io.cdap.delta.proto.DBTable; import io.cdap.delta.proto.PipelineReplicationState; import io.cdap.delta.proto.PipelineState; import io.cdap.delta.proto.TableReplicationState; import io.cdap.delta.proto.TableState; import io.cdap.delta.store.StateStore; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.stream.Collectors; /** * Stores information about pipeline and table state. Stores state in memory, persisting it to the StateStore if * anything changes. Separate instances of this class should not be used to write state, as it will result in * inconsistent results due to the fact that it keeps state information in memory. */ public class PipelineStateService { private static final Gson GSON = new Gson(); private static final String STATE_KEY = "pipeline"; private final DeltaWorkerId id; private final StateStore stateStore; private final Map<DBTable, TableReplicationState> tables; private PipelineState sourceState; private ReplicationError sourceError; public PipelineStateService(DeltaWorkerId id, StateStore stateStore) { this.id = id; this.stateStore = stateStore; this.tables = new HashMap<>(); } /** * Load state from persistent storage into memory. */ public void load() throws IOException { byte[] bytes = stateStore.readState(id, STATE_KEY); if (bytes == null) { sourceState = PipelineState.OK; sourceError = null; tables.clear(); } else { PipelineReplicationState replState = GSON.fromJson(Bytes.toString(bytes), PipelineReplicationState.class); replState = replState == null ? PipelineReplicationState.EMPTY : replState; sourceState = replState.getSourceState(); sourceError = replState.getSourceError(); tables.putAll(replState.getTables().stream() .collect(Collectors.toMap(t -> new DBTable(t.getDatabase(), t.getTable()), t -> t))); } } public PipelineReplicationState getState() { return new PipelineReplicationState(sourceState, new HashSet<>(tables.values()), sourceError); } synchronized void setSourceError(ReplicationError error) throws IOException { setSourceState(PipelineState.FAILING, error); } synchronized void setSourceOK() throws IOException { setSourceState(PipelineState.OK, null); } synchronized void setTableSnapshotting(DBTable dbTable) throws IOException { setTableState(dbTable, new TableReplicationState(dbTable.getDatabase(), dbTable.getTable(), TableState.SNAPSHOTTING, null)); } synchronized void setTableReplicating(DBTable dbTable) throws IOException { setTableState(dbTable, new TableReplicationState(dbTable.getDatabase(), dbTable.getTable(), TableState.REPLICATING, null)); } synchronized void setTableError(DBTable dbTable, ReplicationError error) throws IOException { setTableState(dbTable, new TableReplicationState(dbTable.getDatabase(), dbTable.getTable(), TableState.FAILING, error)); } synchronized void dropTable(DBTable dbTable) throws IOException { if (tables.remove(dbTable) != null) { save(); } } private void setSourceState(PipelineState state, ReplicationError error) throws IOException { boolean shouldSave = sourceState != state; sourceState = state; sourceError = error; if (shouldSave) { save(); } } private void setTableState(DBTable dbTable, TableReplicationState newState) throws IOException { TableReplicationState oldState = tables.put(dbTable, newState); if (!newState.equals(oldState)) { save(); } } private void save() throws IOException { byte[] stateBytes = Bytes.toBytes(GSON.toJson(getState())); stateStore.writeState(id, STATE_KEY, stateBytes); } }
36.294574
112
0.715079
c8669f5c64bdcde393753c417c1caf5b1dde8712
3,961
package com.bitmovin.api.sdk.model; import java.util.Objects; import java.util.Arrays; import com.bitmovin.api.sdk.model.Message; import com.bitmovin.api.sdk.model.Status; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * CustomPlayerBuildStatus */ public class CustomPlayerBuildStatus { @JsonProperty("status") private Status status; @JsonProperty("eta") private Integer eta; @JsonProperty("progress") private Integer progress; @JsonProperty("messages") private Message messages; @JsonProperty("subtasks") private String subtasks; /** * Status of the player build (required) * @return status */ public Status getStatus() { return status; } /** * Status of the player build (required) * * @param status * Status of the player build (required) */ public void setStatus(Status status) { this.status = status; } /** * The estimated time span of the custom player build in seconds. * @return eta */ public Integer getEta() { return eta; } /** * The estimated time span of the custom player build in seconds. * * @param eta * The estimated time span of the custom player build in seconds. */ public void setEta(Integer eta) { this.eta = eta; } /** * The actual progress of the custom player build. (required) * @return progress */ public Integer getProgress() { return progress; } /** * The actual progress of the custom player build. (required) * * @param progress * The actual progress of the custom player build. (required) */ public void setProgress(Integer progress) { this.progress = progress; } /** * Get messages * @return messages */ public Message getMessages() { return messages; } /** * Set messages * * @param messages */ public void setMessages(Message messages) { this.messages = messages; } /** * Get subtasks * @return subtasks */ public String getSubtasks() { return subtasks; } /** * Set subtasks * * @param subtasks */ public void setSubtasks(String subtasks) { this.subtasks = subtasks; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomPlayerBuildStatus customPlayerBuildStatus = (CustomPlayerBuildStatus) o; return Objects.equals(this.status, customPlayerBuildStatus.status) && Objects.equals(this.eta, customPlayerBuildStatus.eta) && Objects.equals(this.progress, customPlayerBuildStatus.progress) && Objects.equals(this.messages, customPlayerBuildStatus.messages) && Objects.equals(this.subtasks, customPlayerBuildStatus.subtasks); } @Override public int hashCode() { return Objects.hash(status, eta, progress, messages, subtasks); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CustomPlayerBuildStatus {\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" eta: ").append(toIndentedString(eta)).append("\n"); sb.append(" progress: ").append(toIndentedString(progress)).append("\n"); sb.append(" messages: ").append(toIndentedString(messages)).append("\n"); sb.append(" subtasks: ").append(toIndentedString(subtasks)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
22.895954
82
0.654633
0721af2b1d164248e77e870bd767f1a6954592a3
5,384
/* * * * Copyright 2020 New Relic Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * */ package com.newrelic.agent.deadlock; import com.google.common.collect.Maps; import com.newrelic.agent.Agent; import com.newrelic.agent.HarvestServiceImpl; import com.newrelic.agent.attributes.AttributeNames; import com.newrelic.agent.config.ErrorCollectorConfig; import com.newrelic.agent.errors.DeadlockTraceError; import com.newrelic.agent.errors.ErrorService; import com.newrelic.agent.errors.TracedError; import com.newrelic.agent.service.ServiceFactory; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; public class DeadLockDetector { private static final int MAX_THREAD_DEPTH = 300; private final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); private final ErrorCollectorConfig errorCollectorConfig; public DeadLockDetector(ErrorCollectorConfig errorCollectorConfig) { this.errorCollectorConfig = errorCollectorConfig; } protected void detectDeadlockedThreads() { ThreadInfo[] threadInfos = getDeadlockedThreadInfos(); if (threadInfos.length > 0) { Agent.LOG.info(MessageFormat.format("Detected {0} deadlocked threads", threadInfos.length)); if (Agent.isDebugEnabled()) { boolean harvestThreadLocked = false; for (ThreadInfo threadInfo : threadInfos) { if (threadInfo.getThreadName().equals(HarvestServiceImpl.HARVEST_THREAD_NAME)) { harvestThreadLocked = true; } } if (harvestThreadLocked) { Agent.LOG.severe("A harvest thread deadlock condition was detected"); return; } } reportDeadlocks(Arrays.asList(threadInfos)); } } ThreadInfo[] getDeadlockedThreadInfos() { long[] deadlockedThreadIds = findDeadlockedThreads(); if (deadlockedThreadIds == null) { return new ThreadInfo[0]; } return threadMXBean.getThreadInfo(deadlockedThreadIds, MAX_THREAD_DEPTH); } protected ThreadMXBean getThreadMXBean() { return threadMXBean; } protected long[] findDeadlockedThreads() { try { return getThreadMXBean().findDeadlockedThreads(); } catch (UnsupportedOperationException e) { return getThreadMXBean().findMonitorDeadlockedThreads(); } } private void reportDeadlocks(List<ThreadInfo> deadThreads) { TracedError[] tracedErrors = getTracedErrors(deadThreads); getErrorService().reportErrors(tracedErrors); } private ErrorService getErrorService() { return ServiceFactory.getRPMService().getErrorService(); } /** * Returns a list of traced errors for the given deadlocked threads. This list should be smaller than the original * list of threads - one error is created for each pair of deadlocked threads, and the error contains a stack trace * for each thread. */ TracedError[] getTracedErrors(List<ThreadInfo> threadInfos) { Map<Long, ThreadInfo> idToThreads = new HashMap<>(); for (ThreadInfo thread : threadInfos) { idToThreads.put(thread.getThreadId(), thread); } List<TracedError> errors = new ArrayList<>(); Set<Long> skipIds = new HashSet<>(); StringBuffer deadlockMsg = new StringBuffer(); for (ThreadInfo thread : threadInfos) { if (!skipIds.contains(thread.getThreadId())) { long otherId = thread.getLockOwnerId(); skipIds.add(otherId); ThreadInfo otherThread = idToThreads.get(otherId); // four to preserve memory and not cause a new map to be created Map<String, String> parameters = Maps.newHashMapWithExpectedSize(4); parameters.put(AttributeNames.THREAD_NAME, thread.getThreadName()); Map<String, StackTraceElement[]> stackTraces = new HashMap<>(); stackTraces.put(thread.getThreadName(), thread.getStackTrace()); if (otherThread != null) { parameters.put(AttributeNames.LOCK_THREAD_NAME, otherThread.getThreadName()); stackTraces.put(otherThread.getThreadName(), otherThread.getStackTrace()); } if (!errors.isEmpty()) { deadlockMsg.append(", "); } deadlockMsg.append(thread.toString()); errors.add(DeadlockTraceError .builder(errorCollectorConfig, null, System.currentTimeMillis()) .threadInfoAndStackTrace(thread, stackTraces) .errorAttributes(parameters) .build()); } } Agent.LOG.log(Level.FINER, "There are {0} deadlocked thread(s): [{1}]", errors.size(), deadlockMsg); return errors.toArray(new TracedError[0]); } }
39.588235
119
0.647845
27215707142e3bf274d3a25c0ddac32ab06d561c
727
package com.jtmcn.archwiki.viewer; /** * Various constants used throughout the program. */ public class Constants { //format types public static final String TEXT_HTML_MIME = "text/html"; public static final String TEXT_PLAIN_MIME = "text/plain"; public static final String UTF_8 = "UTF-8"; //arch wiki urls public static final String ARCHWIKI_BASE = "https://wiki.archlinux.org/"; public static final String ARCHWIKI_MAIN = ARCHWIKI_BASE + "index.php/Main_page"; public static final String ARCHWIKI_SEARCH_URL = ARCHWIKI_BASE + "index.php?&search=%s"; //local file paths public static final String ASSETS_FOLDER = "file:///android_asset/"; public static final String LOCAL_CSS = ASSETS_FOLDER + "style.css"; }
34.619048
89
0.755158
5567935844a959348eea9c86f85526d74ce3eab6
1,364
/* Copyright 2016 Urban Airship and Contributors */ package com.urbanairship.preference; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import com.urbanairship.UAirship; /** * CheckboxPreference to enable/disable push notification vibration. */ public class VibrateEnablePreference extends UACheckBoxPreference { private static final String CONTENT_DESCRIPTION = "VIBRATE_ENABLED"; @TargetApi(Build.VERSION_CODES.LOLLIPOP) public VibrateEnablePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public VibrateEnablePreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public VibrateEnablePreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected boolean getInitialAirshipValue(UAirship airship) { return airship.getPushManager().isVibrateEnabled(); } @Override protected void onApplyAirshipPreference(UAirship airship, boolean enabled) { airship.getPushManager().setVibrateEnabled(enabled); } @Override protected String getContentDescription() { return CONTENT_DESCRIPTION; } }
29.021277
108
0.75
f05f39cbe050d4c47fd737dd7cd6e07649b6b447
2,088
/* * generated by Xtext 2.10.0 */ package com.beenleigh.dsl.web; import com.beenleigh.dsl.ide.contentassist.antlr.LemmaParser; import com.beenleigh.dsl.ide.contentassist.antlr.internal.InternalLemmaLexer; import com.google.inject.Binder; import com.google.inject.Provider; import com.google.inject.name.Names; import java.util.concurrent.ExecutorService; import org.eclipse.xtext.ide.LexerIdeBindings; import org.eclipse.xtext.ide.editor.contentassist.FQNPrefixMatcher; import org.eclipse.xtext.ide.editor.contentassist.IPrefixMatcher; import org.eclipse.xtext.ide.editor.contentassist.IProposalConflictHelper; import org.eclipse.xtext.ide.editor.contentassist.antlr.AntlrProposalConflictHelper; import org.eclipse.xtext.ide.editor.contentassist.antlr.IContentAssistParser; import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.Lexer; import org.eclipse.xtext.web.server.DefaultWebModule; /** * Manual modifications go to {@link LemmaWebModule}. */ @SuppressWarnings("all") public abstract class AbstractLemmaWebModule extends DefaultWebModule { public AbstractLemmaWebModule(Provider<ExecutorService> executorServiceProvider) { super(executorServiceProvider); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class<? extends IProposalConflictHelper> bindIProposalConflictHelper() { return AntlrProposalConflictHelper.class; } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public void configureContentAssistLexer(Binder binder) { binder.bind(Lexer.class) .annotatedWith(Names.named(LexerIdeBindings.CONTENT_ASSIST)) .to(InternalLemmaLexer.class); } // contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2 public Class<? extends IContentAssistParser> bindIContentAssistParser() { return LemmaParser.class; } // contributed by org.eclipse.xtext.xtext.generator.exporting.QualifiedNamesFragment2 public Class<? extends IPrefixMatcher> bindIPrefixMatcher() { return FQNPrefixMatcher.class; } }
38.666667
94
0.823755
d242d370804920446fc2ce2fbc2affc5c6d342bf
339
package com.dotterbear.schedule.a.tweet.db.repo; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.dotterbear.schedule.a.tweet.db.model.ScheduledTweet; @Repository public interface ScheduledTweetRepository extends MongoRepository<ScheduledTweet, String> { }
33.9
91
0.852507
09e0d906395e907e7f06c18f02f6d7547042f515
20,808
package com.u8.server.web.analytics; import com.u8.server.cache.CacheManager; import com.u8.server.common.Page; import com.u8.server.common.UActionSupport; import com.u8.server.data.analytics.GameChannelTSummaryData; import com.u8.server.data.analytics.TSummary; import com.u8.server.log.Log; import com.u8.server.service.analytics.AnalyticsManager; import com.u8.server.utils.DownloadUtil; import com.u8.server.utils.TimeUtils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.poi.xssf.usermodel.*; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 统计分析 * Created by ant on 2016/8/25. */ @Controller @Namespace("/analytics") public class AnalyticsAction extends UActionSupport { private int page; //当前请求的页码 private int rows; //当前每页显示的行数 private Integer appID; private Integer timeType; private Date beginTime; private Date endTime; @Autowired private AnalyticsManager summaryManager; @Action(value = "summary", results = {@Result(name = "success", location = "/WEB-INF/admin/t_summary.jsp")}) public String showSummary() { return "success"; } @Action(value = "newUsers", results = {@Result(name = "success", location = "/WEB-INF/admin/t_newuser.jsp")}) public String showNewUsers() { return "success"; } @Action(value = "dau", results = {@Result(name = "success", location = "/WEB-INF/admin/t_dau.jsp")}) public String showDAUData() { return "success"; } @Action(value = "retention", results = {@Result(name = "success", location = "/WEB-INF/admin/t_retention.jsp")}) public String showRetentionData() { return "success"; } @Action(value = "flow", results = {@Result(name = "success", location = "/WEB-INF/admin/t_flow.jsp")}) public String showFlowData() { return "success"; } @Action(value = "money", results = {@Result(name = "success", location = "/WEB-INF/admin/t_money.jsp")}) public String showMoneyData() { return "success"; } @Action(value = "pay", results = {@Result(name = "success", location = "/WEB-INF/admin/t_pay.jsp")}) public String showPayData() { return "success"; } @Action(value = "payratio", results = {@Result(name = "success", location = "/WEB-INF/admin/t_payratio.jsp")}) public String showPayRatioData() { return "success"; } @Action(value = "currTime", results = {@Result(name = "success", location = "/WEB-INF/admin/t_analytics.jsp")}) public String showCurrTimeData() { return "success"; } @Action(value = "gameSummaryData", results = {@Result(name = "success", location = "/WEB-INF/admin/t_gameData.jsp")}) public String showGameSummaryData(){ return "success"; } @Action("runTestData") public void runTestData() { renderState(true, "11"); } @Action("summaryData") public void getSummaryData() { try { Date from = null; Date to = new Date(); switch (timeType) { case 1: Date lastDay = TimeUtils.lastDay(); from = TimeUtils.dateBegin(lastDay); break; case 2: Date lastWeek = TimeUtils.dateSub(new Date(), 7); from = TimeUtils.dateBegin(lastWeek); break; case 3: Date lastMonth = TimeUtils.dateSub(new Date(), 30); from = TimeUtils.dateBegin(lastMonth); break; } String json = summaryManager.collectSummaryInfo(appID, from, to); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } @Action("newUserData") public void getNewUserData() { try { if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } String json = summaryManager.collectNewUserInfo(appID, this.beginTime, this.endTime); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } @Action("dauData") public void getDAUData() { try { if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } String json = summaryManager.collectDAUInfo(appID, this.beginTime, this.endTime); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } @Action("retentionData") public void getRetentionData() { try { if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } String json = summaryManager.collectRetentionInfo(appID, this.beginTime, this.endTime); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } @Action("flowData") public void getFlowData() { try { if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } String json = summaryManager.collectFlowInfo(appID, this.beginTime, this.endTime, this.timeType); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } @Action("moneyData") public void getMoneyData() { try { if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } String json = summaryManager.collectMoneyInfo(appID, this.beginTime, this.endTime); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } @Action("payData") public void getPayData() { try { if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } String json = summaryManager.collectPayInfo(appID, this.beginTime, this.endTime); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } @Action("payRatioData") public void getPayRatioData() { try { if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } String json = summaryManager.collectPayRatioInfo(appID, this.beginTime, this.endTime); Log.d("the json data is "); Log.d(json); renderState(true, json); } catch (Exception e) { e.printStackTrace(); } } //实时数据 @Action("currTimeData") public void getCurrTimeData(){ if (this.beginTime == null || this.endTime == null) { renderState(false, "请指定时间段"); return; } //Calendar calendar = Calendar.getInstance(); //calendar.setTime(endTime); //calendar.add(Calendar.HOUR,24); String game_datas = super.request.getParameter("game_datas"); String masterName = super.request.getParameter("masterName"); //收益 JSONArray profit_json = summaryManager.collectProfitInfo(appID, this.beginTime, this.endTime, game_datas, masterName); //新增 JSONArray newreg_json = summaryManager.collectNewRegInfo(appID, this.beginTime, this.endTime, game_datas, masterName); JSONArray jsonArray = new JSONArray(); List<Integer> appIDs = new ArrayList<>(); List<Integer> channelIDs = new ArrayList<>(); for(int i = 0;i < profit_json.size()-2;i++) { GameChannelTSummaryData gameChannelTSummaryData = new GameChannelTSummaryData(); JSONObject profitObject = (JSONObject)profit_json.get(i); gameChannelTSummaryData.setAppID(profitObject.getInt("appID")); gameChannelTSummaryData.setChannelID(profitObject.getInt("channelID")); gameChannelTSummaryData.setAppName(profitObject.getString("appName")); gameChannelTSummaryData.setChannelName(profitObject.getString("channelName")); gameChannelTSummaryData.setTotalMoney(profitObject.getString("totalMoney").substring(0,profitObject.getString("totalMoney").indexOf("."))); gameChannelTSummaryData.setTotalCostNum(profitObject.getString("totalCostNum")); Integer appID = profitObject.getInt("appID"); Integer channelID = profitObject.getInt("channelID"); boolean flag = true; for(int j = 0;j < newreg_json.size()-2;j++) { JSONObject newregObject = (JSONObject) newreg_json.get(j); Integer id = newregObject.getInt("appID"); Integer newregeChannelID = newregObject.getInt("channelID"); if (appID == id && channelID.intValue() == newregeChannelID.intValue()) { appIDs.add(id); channelIDs.add(channelID); gameChannelTSummaryData.setTotalNewreg(newregObject.getString("totalNewreg")); gameChannelTSummaryData.setTotalNewCostNum(newregObject.getString("totalNewCostNum")); gameChannelTSummaryData.setPayOfRegistRate(gameChannelTSummaryData.caculate(gameChannelTSummaryData.getTotalNewCostNum(),gameChannelTSummaryData.getTotalNewreg())); flag = false; break; } } if (flag) { gameChannelTSummaryData.setTotalNewreg("0"); gameChannelTSummaryData.setTotalNewCostNum("0"); gameChannelTSummaryData.setPayOfRegistRate("0.00%"); } jsonArray.add(gameChannelTSummaryData); } for(int j = 0;j < newreg_json.size()-2;j++) { JSONObject newregObject = (JSONObject) newreg_json.get(j); Integer id = newregObject.getInt("appID"); Integer channelID = newregObject.getInt("channelID"); boolean flag = true; for(int i = 0;i < channelIDs.size(); i++) { if((appIDs.get(i) == id && channelIDs.get(i).intValue() == channelID.intValue())) { //重复的数据 已经合并的 flag = false; break; } } if (flag) { //遍历所有的 都没有匹配的 需要添加 GameChannelTSummaryData gameChannelTSummaryData = new GameChannelTSummaryData(); gameChannelTSummaryData.setAppID(id); gameChannelTSummaryData.setAppName(newregObject.getString("appName")); gameChannelTSummaryData.setChannelID(newregObject.getInt("channelID")); gameChannelTSummaryData.setChannelName(newregObject.getString("channelName")); gameChannelTSummaryData.setTotalMoney("0"); gameChannelTSummaryData.setTotalCostNum("0"); gameChannelTSummaryData.setTotalNewreg(newregObject.getString("totalNewreg")); gameChannelTSummaryData.setTotalNewCostNum(newregObject.getString("totalNewCostNum")); gameChannelTSummaryData.setPayOfRegistRate(gameChannelTSummaryData.caculate(gameChannelTSummaryData.getTotalNewCostNum(),gameChannelTSummaryData.getTotalNewreg())); jsonArray.add(gameChannelTSummaryData); } } JSONObject json = new JSONObject(); //json.put("profit_json",profit_json); //json.put("newreg_json",newreg_json); json.put("profitAndNewReg",jsonArray.toString()); json.put("totalMoney",profit_json.get(profit_json.size()-2)); json.put("totalCostNum",profit_json.get(profit_json.size()-1)); json.put("totalNewreg",newreg_json.get(newreg_json.size()-2)); json.put("totalNewCostNum",newreg_json.get(newreg_json.size()-1)); Log.d("----profitAndNewReg:%s",jsonArray.toString()); renderState(true, json.toString()); } //统计数据Start @Action("getGameSummaryData") public void getGameSummaryData(){ try{ Page<TSummary> pages = summaryManager.getSummaryPage(page, rows, appID, beginTime, endTime); List<TSummary> list = pages.getResultList(); for (TSummary tSummary:list) { tSummary.setArppu(caculate(tSummary.getMoney(),tSummary.getPayUserNum())); tSummary.setArpu(caculate(tSummary.getMoney(),tSummary.getDau())); tSummary.setPayRate(caculatePay(tSummary.getPayUserNum(),tSummary.getDau())); } pages.setResultList(list); JSONObject json = new JSONObject(); JSONArray users = new JSONArray(); if(pages != null){ json.put("total", pages.getTotalCount()); for(TSummary m : pages.getResultList()){ users.add(m.toJSON()); } } json.put("rows", users); renderJson(json.toString()); }catch (Exception e){ e.printStackTrace(); } } //统计数据End @SuppressWarnings("all") @Action("/downloadSummary") public void downloadSummary() { OutputStream os = null; try{ os = this.response.getOutputStream(); InputStream is = this.getClass().getClassLoader().getResourceAsStream("统计数据模板.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(is); XSSFSheet sheet = workbook.getSheetAt(0); XSSFRow row = sheet.getRow(0); XSSFCell cell = row.getCell(0); String title = CacheManager.getInstance().getGame(appID).getName()+"最近一个月统计数据"; cell.setCellValue(title); cell.getCellStyle().setAlignment(XSSFCellStyle.ALIGN_CENTER_SELECTION); row = sheet.getRow(1); List<XSSFCellStyle> cellStyleList = new ArrayList<>(); for(int i = 0;i < 17;i++) { cell = row.getCell(i); XSSFCellStyle cellStyle = cell.getCellStyle(); cellStyleList.add(cellStyle); } is.close(); List<TSummary> list = summaryManager.getSummaryPageAll(appID, beginTime, endTime); for (TSummary tSummary:list) { tSummary.setArppu(caculate(tSummary.getMoney(),tSummary.getPayUserNum())); tSummary.setArpu(caculate(tSummary.getMoney(),tSummary.getDau())); tSummary.setPayRate(caculatePay(tSummary.getPayUserNum(),tSummary.getDau())); } Integer maxRow = 1048576; if(list.size() >= maxRow) { Log.d("----下载订单失败,数据量过大"); String content = "下载订单失败,数据量过大,请重新筛选"; os.write(content.getBytes("UTF-8")); return; } List<String> values = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for(int i = 2;i < list.size()+2;i++) { row = sheet.createRow(i); TSummary tSummary = list.get(i-2); values.add(sdf.format(tSummary.getCurrTime())); values.add(CacheManager.getInstance().getGame(tSummary.getAppID()).getName()); values.add(tSummary.getDeviceNum()+""); values.add(tSummary.getUserNum()+""); values.add(tSummary.getUniUserNum()+""); values.add(tSummary.getTotalUserNum()+""); values.add(tSummary.getDau()+""); values.add(tSummary.getNdau()+""); values.add(tSummary.getWau()+""); values.add(tSummary.getMau()+""); values.add(tSummary.getPayUserNum()+""); values.add(tSummary.getTotalPayUserNum()+""); values.add(tSummary.getNewPayUserNum()+""); values.add((tSummary.getMoney()/100)+".00"); values.add(tSummary.getArppu()+""); values.add(tSummary.getArpu()+""); values.add(tSummary.getPayRate()+""); for (int j = 0;j<17;j++) { cell = row.createCell(j); XSSFCellStyle style = cellStyleList.get(j); XSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setBorderBottom(style.getBorderBottom()); cellStyle.setBorderLeft(style.getBorderLeft()); cellStyle.setBorderTop(style.getBorderTop()); cellStyle.setBorderRight(style.getBorderRight()); cell.setCellStyle(cellStyle); cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); cell.setCellValue(values.get(j)); } values.clear(); } list.clear(); String fileName = "统计数据.xlsx"; DownloadUtil downloadUtil = new DownloadUtil(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); downloadUtil.download(outputStream,this.response,fileName); }catch(Exception e) { Log.e("-----下载订单失败:"+e.getMessage()); return ; } } //保留两位小数 private Double caculate(Long money,Integer number) { if (0 == number) { return 0D; } money = money/100; BigDecimal bigDecimal = new BigDecimal(money.doubleValue()); bigDecimal = bigDecimal.divide(new BigDecimal(number.doubleValue()),2,BigDecimal.ROUND_HALF_UP); return bigDecimal.doubleValue(); } private Double caculatePay(Integer pay,Integer Regist) { if (0 == Regist) { return 0D; } BigDecimal bigDecimal = new BigDecimal(pay.doubleValue()); bigDecimal = bigDecimal.divide(new BigDecimal(Regist.doubleValue()),2,BigDecimal.ROUND_HALF_UP); return bigDecimal.doubleValue(); } private void renderState(boolean suc, String data) { JSONObject json = new JSONObject(); json.put("state", suc ? 1 : 0); json.put("data", data); renderJson(json.toString()); } public Integer getAppID() { return appID; } public void setAppID(Integer appID) { this.appID = appID; } public Integer getTimeType() { return timeType; } public void setTimeType(Integer timeType) { this.timeType = timeType; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } }
38.040219
185
0.564398
c9672edc8613fefdadefa40e970c1a00963b9708
1,962
package org.firstinspires.ftc.teamcode.Robot.SubSystems; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.Servo; import org.firstinspires.ftc.teamcode.FTC_API.Robot.SubSystems.SubSystem; /** * Created by byron.nice on 9/26/2018. */ public class Arm extends SubSystem { private DcMotor liftMotor; private Servo hand; private Servo handLock; private String liftName; //private String handName; //private String handLockName; private final double LIFT_SPEED= 1; @Override public boolean init(HardwareMap hardwareDevices) { liftMotor = hardwareDevices.dcMotor.get(liftName); //hand = hardwareDevices.servo.get(handName); //handLock = hardwareDevices.servo.get(handLockName); liftMotor.setDirection(DcMotorSimple.Direction.REVERSE); return true; } public void liftUp() { liftMotor.setPower(LIFT_SPEED);} public void stopLift() { liftMotor.setPower(0);} public void liftDown() { liftMotor.setPower(-LIFT_SPEED);} /*public void autoUp() { liftMotor.setPower(LIFT_SPEED), wait(10000), liftMotor.setPower(0); ;} public void autoLiftDown() { liftMotor.setPower(-LIFT_SPEED), wait(10000), liftMotor.setPower(0), ;} */ public Arm setMotorNames(String lift) { liftName = lift; return this; } public DcMotor getMotor(){ return liftMotor; } //public Arm setServoNames(String hand, String handLock) { //handName = hand; //handLockName = handLock; //return this; //} }
27.633803
73
0.599388
224735b1e0c321a38475e43c25d240a2ac7de1ad
2,137
package com.client.core.soap.tools.property.getdtofields.impl; import org.springframework.stereotype.Service; import com.bullhorn.entity.candidate.SendoutDto; import com.client.core.soap.tools.property.getdtofields.DtoFieldGetService; @Service("sendoutGetService") public class SendoutDtoFieldGetService extends DtoFieldGetService<SendoutDto> { public SendoutDtoFieldGetService() { super(); } @Override public Object retrieveField(String field, SendoutDto sendout, Boolean isDotPrefixed) throws NoSuchMethodException { Object value = null; if(isDotPrefixed) { field = removeDotPrefix(field); } if (field.equalsIgnoreCase(CANDIDATEID)) { value = sendout.getCandidateID(); } else if (field.equalsIgnoreCase(CLIENTCONTACTID)) { value = sendout.getClientContactID(); } else if (field.equalsIgnoreCase(CLIENTCORPORATIONID)) { value = sendout.getClientCorporationID(); } else if (field.equalsIgnoreCase(DATEADDED)) { value = sendout.getDateAdded(); } else if (field.equalsIgnoreCase(EMAIL)) { value = sendout.getEmail(); } else if (field.equalsIgnoreCase(ISREAD)) { value = sendout.isIsRead(); } else if (field.equalsIgnoreCase(JOBORDERID)) { value = sendout.getJobOrderID(); } else if (field.equalsIgnoreCase(MIGRATEGUID)) { value = sendout.getMigrateGUID(); } else if (field.equalsIgnoreCase(SENDOUTID)) { value = sendout.getSendoutID(); } else if (field.equalsIgnoreCase(USERID)) { value = sendout.getUserID(); } else if (field.equalsIgnoreCase(USERMESSAGEID)) { value = sendout.getUserMessageID(); } else { throw new NoSuchMethodException(); } return value; } private String CANDIDATEID="candidateID"; private String CLIENTCONTACTID="clientContactID"; private String CLIENTCORPORATIONID="clientCorporationID"; private String DATEADDED="dateAdded"; private String EMAIL="email"; private String ISREAD="isRead"; private String JOBORDERID="jobOrderID"; private String MIGRATEGUID="migrateGUID"; private String SENDOUTID="sendoutID"; private String USERID="userID"; private String USERMESSAGEID="userMessageID"; }
28.118421
116
0.746841
7c1f69db84a4e3b643cb63698346b2c9a3d2924d
617
package org.glob3.mobile.generated; public class GenericQuadTree_Geodetic2DElement extends GenericQuadTree_Element { public final Geodetic2D _geodetic ; public GenericQuadTree_Geodetic2DElement(Geodetic2D geodetic, Object element) { super(element); _geodetic = new Geodetic2D(geodetic); } public final boolean isSectorElement() { return false; } public final Geodetic2D getCenter() { return _geodetic; } public final Sector getSector() { return new Sector(_geodetic, _geodetic); } public void dispose() { super.dispose(); } }
19.903226
80
0.685575
b393c7d0fd6f5571ac4a873123c96df8d9ae4e43
562
import Algorithms.BinarySearch.BinarySearch; import Algorithms.Hashmap.Entry; import Algorithms.Hashmap.OpenAddressing.RobinHood; import java.util.*; public class Main { public static void main(String[] args) { int[] a = new int[] {1,2,3,3,4,5,5,6,7,8,9,10,20,30,30,40,50}; Arrays.sort(a); int elem = 60; System.out.println(a[BinarySearch.upperBound(a,elem)]+" "+BinarySearch.upperBound(a,elem)); System.out.println(a[BinarySearch.lowerBound(a,elem)]+" "+BinarySearch.lowerBound(a,elem)); } }
31.222222
100
0.654804
3ace55507ecc34cd53c5a35ab985b0ce7e8b82a9
462
package org.wildfly.swarm.config.generator.generator; import org.jboss.dmr.Property; import org.wildfly.swarm.config.runtime.model.AddressTemplate; /** * Maps resources (through their address) to {@link ClassPlan}'s. * This way multiple resources can be represented by the same java class. * * @author Bob McWhirter */ public interface ClassIndex { ClassPlan lookup(AddressTemplate address); EnumPlan lookup(ClassPlan requester, Property attr); }
28.875
73
0.768398
1135deb8125e7dcbcbe7e46318f1346fae663476
220
package com.leaning.linnyk.cloud.limitsservice.bean; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public class LimitConfiguration { private int maximum; private int minimum; }
16.923077
52
0.818182
dff85df6dfdde29f74d863e3cb818a1eca46add5
2,929
package org.example.pool; import cn.hutool.core.util.RandomUtil; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.SneakyThrows; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.*; import java.util.stream.IntStream; @DisplayName("池化测试用例") public class CommonPoolTest { @Test @SneakyThrows @DisplayName("默认实现") public void defaultImplement() { GenericObjectPool<Mark> pool = new GenericObjectPool<>(new BasePooledObjectFactory<Mark>() { @Override public Mark create() throws Exception { return new Mark(RandomUtil.randomStringUpper(10)); } @Override public PooledObject<Mark> wrap(Mark mark) { return new DefaultPooledObject<>(mark); } }); pool.setMaxTotal(8); pool.setMaxIdle(4); pool.setMinIdle(2); print(pool); ExecutorService delegate = Executors.newFixedThreadPool(10); ListeningExecutorService executorService = MoreExecutors.listeningDecorator(delegate); List<ListenableFuture<String>> futures = new ArrayList<>(); IntStream.range(0, 20).forEach(i -> { futures.add(executorService.submit(() -> { Mark mark = null; try { mark = pool.borrowObject(); TimeUnit.SECONDS.sleep(RandomUtil.randomInt(3)); print(pool); return Thread.currentThread().getName() + ", " + mark.getName(); } catch (Exception e) { pool.invalidateObject(mark); } finally { if (Optional.ofNullable(mark).isPresent()) { pool.returnObject(mark); } } return ""; })); }); List<String> list = Futures.allAsList(futures).get(); list.stream().forEach(System.out::println); print(pool); } private void print(GenericObjectPool pool) { System.out.println(" [active: " + pool.getNumActive() + ", idle: " + pool.getNumIdle() + ", wait: " + pool.getNumWaiters() + "]"); } @Data @NoArgsConstructor @AllArgsConstructor private class Mark { private String name; } }
34.05814
138
0.625811
34695a469b310cc6541d5bcaf20fa86d0a1a325a
2,624
/* * 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.hive.common.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.apache.hadoop.hive.common.type.Date; import org.junit.Test; public class TestDateParser { private Date date = new Date(); void checkValidCase(String strValue, Date expected) { Date dateValue = DateParser.parseDate(strValue); assertEquals(expected, dateValue); assertTrue(DateParser.parseDate(strValue, date)); assertEquals(expected, date); } void checkInvalidCase(String strValue) { Date dateValue = DateParser.parseDate(strValue); assertNull(dateValue); assertFalse(DateParser.parseDate(strValue, date)); } @Test public void testValidCases() throws Exception { checkValidCase("1945-12-31", Date.valueOf("1945-12-31")); checkValidCase("1946-01-01", Date.valueOf("1946-01-01")); checkValidCase("2001-11-12", Date.valueOf("2001-11-12")); checkValidCase("0004-05-06", Date.valueOf("0004-05-06")); checkValidCase("1678-09-10", Date.valueOf("1678-09-10")); checkValidCase("9999-10-11", Date.valueOf("9999-10-11")); // Timestamp strings should parse ok checkValidCase("2001-11-12 01:02:03", Date.valueOf("2001-11-12")); // Leading spaces checkValidCase(" 1946-01-01", Date.valueOf("1946-01-01")); checkValidCase(" 2001-11-12 01:02:03", Date.valueOf("2001-11-12")); } @Test public void testInvalidCases() throws Exception { checkInvalidCase("2001"); checkInvalidCase("2001-01"); checkInvalidCase("abc"); checkInvalidCase(" 2001 "); checkInvalidCase("a2001-01-01"); checkInvalidCase("0000-00-00"); checkInvalidCase("2001-13-12"); checkInvalidCase("2001-11-31"); } }
34.986667
75
0.720274
834bda3e4f13ff54b758a41bb8938ee8967eefa1
557
package ai.hyacinth.core.service.gateway.server.security; import java.util.ArrayList; import java.util.Collection; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.security.core.Authentication; @Data @NoArgsConstructor public class DefaultAuthentication implements Authentication { private static final long serialVersionUID = 383300673565185225L; boolean authenticated; Object credentials; Object details; Object principal; String name; Collection<DefaultGrantedAuthority> authorities = new ArrayList<>(); }
26.52381
70
0.818671
68cd4d628b646c9b6095ffb54898bc6a456a0222
500
package com.luv2code.imusic.entity.customInterface; import com.luv2code.imusic.entity.Artist; import com.luv2code.imusic.entity.Category; import java.util.Date; import java.util.Set; public interface SongNotUrl { Integer getId(); String getName(); String getIntroduction(); Date getCreateTime(); Date getUpdateTime(); String getPhoto(); String getLyric(); boolean isEnabled(); Set<Artist> getArtists(); Set<Category> getCategories(); }
15.625
51
0.688
e6443476c308e6a9a122ef456f24012dbfafa3ca
3,492
package com.xinsite.core.model.user; import com.xinsite.common.uitls.mapper.JsonMapper; import java.io.Serializable; /** * 用户登录成功用户实例 * create by zhangxiaxin */ public class LoginUser implements Serializable { private int userId; //当前登录用户Id private String userName; private String loginName; private int orgId; // 当前登录用户所属机构(公司) private String organizeName; private int roleId; // 当前登录用户所属角色 private String roleName; private int deptId; // 当前登录用户所属部门 private String deptName; private int postId; private String postName; private int userState; private String headPhoto; private boolean superAdminer; //是否属于超级管理员 private String loginIp; // 当前登录用户Ip地址 /** * 用户信息更新标记 */ private String changeUserFlag; public LoginUser() { } public LoginUser(int userId, String loginName) { this.userId = userId; this.loginName = loginName; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public int getOrgId() { return orgId; } public void setOrgId(int orgId) { this.orgId = orgId; } public String getOrganizeName() { return organizeName; } public void setOrganizeName(String organizeName) { this.organizeName = organizeName; } public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public int getDeptId() { return deptId; } public void setDeptId(int deptId) { this.deptId = deptId; } public int getPostId() { return postId; } public void setPostId(int postId) { this.postId = postId; } public int getUserState() { return userState; } public void setUserState(int userState) { this.userState = userState; } public String getHeadPhoto() { return headPhoto; } public void setHeadPhoto(String headPhoto) { this.headPhoto = headPhoto; } public boolean isSuperAdminer() { return superAdminer; } public void setSuperAdminer(boolean superAdminer) { this.superAdminer = superAdminer; } public String getUserInfoJson() { return JsonMapper.toJson(this); } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getPostName() { return postName; } public void setPostName(String postName) { this.postName = postName; } public String getLoginIp() { return loginIp; } public void setLoginIp(String loginIp) { this.loginIp = loginIp; } public String getChangeUserFlag() { return changeUserFlag; } public void setChangeUserFlag(String changeUserFlag) { this.changeUserFlag = changeUserFlag; } }
19.954286
58
0.621707
e901d0a5f7670da72540310570ed3484fbf8bf91
252
package org.star.jaising.jarmony.ws; import org.star.jaising.jarmony.JArmonyApplicationTests; /** * @author zhengjiaxing * @description WebSocket服务端客户端消息收发测试类 * @date 2020/10/30 */ public class WebSocketTests extends JArmonyApplicationTests { }
19.384615
61
0.785714
b4ca20b2a22238da28cd086e6ff09fcb8fc41553
3,373
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * Rectangle2DReadHandler * ---------------------- * (C) Copyright 2003, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): -; * * $Id: Rectangle2DReadHandler.java,v 1.2 2005/10/18 13:33:32 mungady Exp $ * * Changes * ------- * */ package org.jfree.xml.parser.coretypes; import java.awt.geom.Rectangle2D; import org.jfree.xml.parser.AbstractXmlReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * A handler for reading a {@link Rectangle2D} object. */ public class Rectangle2DReadHandler extends AbstractXmlReadHandler { /** The rectangle being constructed. */ private Rectangle2D rectangle; /** * Default constructor. */ public Rectangle2DReadHandler() { super(); } /** * Begins parsing. * * @param attrs the attributes. * * @throws SAXException if there is a parsing error. */ protected void startParsing(final Attributes attrs) throws SAXException { final String type = attrs.getValue("type"); this.rectangle = createRect(type); final String x = attrs.getValue("x"); final String y = attrs.getValue("y"); final String w = attrs.getValue("width"); final String h = attrs.getValue("height"); this.rectangle.setRect( Double.parseDouble(x), Double.parseDouble(y), Double.parseDouble(w), Double.parseDouble(h) ); } /** * Creates a rectangle. * * @param type the type ('float' or 'double'). * * @return The rectangle. */ private Rectangle2D createRect(final String type) { if ("float".equals(type)) { return new Rectangle2D.Float(); } return new Rectangle2D.Double(); } /** * Returns the object under construction. * * @return The object. */ public Object getObject() { return this.rectangle; } }
30.944954
79
0.595316
938999ec23ec7d223f378c531d6d0f2a14a65eb8
2,504
package ruina.vfx; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.helpers.ImageMaster; import com.megacrit.cardcrawl.vfx.AbstractGameEffect; import ruina.monsters.AbstractRuinaMonster; import ruina.util.TexLoader; import static ruina.RuinaMod.makeVfxPath; public class BurrowingHeavenEffect extends AbstractGameEffect { private Texture img; private float animTimer; private float lastTimer; private Color[] color2 = new Color[5]; private int stage; private boolean playedFinishSound = false; public BurrowingHeavenEffect() { img = TexLoader.getTexture(makeVfxPath("BurrowingHeavenEffect.png")); for (int i = 0; i < 5; i++) { this.color2[i] = Color.WHITE.cpy(); (this.color2[i]).a = 0.0F; } this.animTimer = 0.1F; this.duration = 2.0F; this.startingDuration = 1.0F; this.lastTimer = 0.5F; this.stage = 1; } public void update() { this.startingDuration -= Gdx.graphics.getDeltaTime(); if (this.duration > 0.0F) { if (!playedFinishSound) { AbstractRuinaMonster.playSound("HeavenWakeStrong"); playedFinishSound = true; } this.duration -= Gdx.graphics.getDeltaTime(); if (this.stage > 1) { this.animTimer -= Gdx.graphics.getDeltaTime(); } if (this.stage <= 5) { (this.color2[this.stage - 1]).a += Gdx.graphics.getDeltaTime() * 2.5F; if ((this.color2[this.stage - 1]).a > 1.0F) { (this.color2[this.stage - 1]).a = 1.0F; this.stage++; } } } else { this.lastTimer -= Gdx.graphics.getDeltaTime(); if (this.lastTimer > 0.0F) { for (int i = 0; i < 5; i++) (this.color2[i]).a = this.lastTimer * 2.0F; } else { this.isDone = true; } } } public void render(SpriteBatch sb) { for (int i = 0; i < 5; i++) { sb.setColor(this.color2[i]); sb.draw(this.img, 0.0F, 0.0F, Settings.WIDTH, Settings.HEIGHT); } } public void dispose() {} }
31.3
86
0.572684
2723b96b1549562c14031b616a7d7f0c33814a47
13,950
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v6/common/bidding.proto package com.google.ads.googleads.v6.common; public final class BiddingProto { private BiddingProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_Commission_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_Commission_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_EnhancedCpc_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_EnhancedCpc_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_ManualCpc_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_ManualCpc_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_ManualCpm_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_ManualCpm_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_ManualCpv_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_ManualCpv_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_MaximizeConversions_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_MaximizeConversions_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_MaximizeConversionValue_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_MaximizeConversionValue_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_TargetCpa_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_TargetCpa_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_TargetCpm_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_TargetCpm_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_TargetImpressionShare_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_TargetImpressionShare_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_TargetRoas_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_TargetRoas_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_TargetSpend_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_TargetSpend_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v6_common_PercentCpc_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v6_common_PercentCpc_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n,google/ads/googleads/v6/common/bidding" + ".proto\022\036google.ads.googleads.v6.common\032D" + "google/ads/googleads/v6/enums/target_imp" + "ression_share_location.proto\032\034google/api" + "/annotations.proto\"L\n\nCommission\022#\n\026comm" + "ission_rate_micros\030\002 \001(\003H\000\210\001\001B\031\n\027_commis" + "sion_rate_micros\"\r\n\013EnhancedCpc\"G\n\tManua" + "lCpc\022!\n\024enhanced_cpc_enabled\030\002 \001(\010H\000\210\001\001B" + "\027\n\025_enhanced_cpc_enabled\"\013\n\tManualCpm\"\013\n" + "\tManualCpv\")\n\023MaximizeConversions\022\022\n\ntar" + "get_cpa\030\001 \001(\003\"C\n\027MaximizeConversionValue" + "\022\030\n\013target_roas\030\002 \001(\001H\000\210\001\001B\016\n\014_target_ro" + "as\"\275\001\n\tTargetCpa\022\036\n\021target_cpa_micros\030\004 " + "\001(\003H\000\210\001\001\022#\n\026cpc_bid_ceiling_micros\030\005 \001(\003" + "H\001\210\001\001\022!\n\024cpc_bid_floor_micros\030\006 \001(\003H\002\210\001\001" + "B\024\n\022_target_cpa_microsB\031\n\027_cpc_bid_ceili" + "ng_microsB\027\n\025_cpc_bid_floor_micros\"\013\n\tTa" + "rgetCpm\"\215\002\n\025TargetImpressionShare\022p\n\010loc" + "ation\030\001 \001(\0162^.google.ads.googleads.v6.en" + "ums.TargetImpressionShareLocationEnum.Ta" + "rgetImpressionShareLocation\022%\n\030location_" + "fraction_micros\030\004 \001(\003H\000\210\001\001\022#\n\026cpc_bid_ce" + "iling_micros\030\005 \001(\003H\001\210\001\001B\033\n\031_location_fra" + "ction_microsB\031\n\027_cpc_bid_ceiling_micros\"" + "\262\001\n\nTargetRoas\022\030\n\013target_roas\030\004 \001(\001H\000\210\001\001" + "\022#\n\026cpc_bid_ceiling_micros\030\005 \001(\003H\001\210\001\001\022!\n" + "\024cpc_bid_floor_micros\030\006 \001(\003H\002\210\001\001B\016\n\014_tar" + "get_roasB\031\n\027_cpc_bid_ceiling_microsB\027\n\025_" + "cpc_bid_floor_micros\"\213\001\n\013TargetSpend\022$\n\023" + "target_spend_micros\030\003 \001(\003B\002\030\001H\000\210\001\001\022#\n\026cp" + "c_bid_ceiling_micros\030\004 \001(\003H\001\210\001\001B\026\n\024_targ" + "et_spend_microsB\031\n\027_cpc_bid_ceiling_micr" + "os\"\210\001\n\nPercentCpc\022#\n\026cpc_bid_ceiling_mic" + "ros\030\003 \001(\003H\000\210\001\001\022!\n\024enhanced_cpc_enabled\030\004" + " \001(\010H\001\210\001\001B\031\n\027_cpc_bid_ceiling_microsB\027\n\025" + "_enhanced_cpc_enabledB\347\001\n\"com.google.ads" + ".googleads.v6.commonB\014BiddingProtoP\001ZDgo" + "ogle.golang.org/genproto/googleapis/ads/" + "googleads/v6/common;common\242\002\003GAA\252\002\036Googl" + "e.Ads.GoogleAds.V6.Common\312\002\036Google\\Ads\\G" + "oogleAds\\V6\\Common\352\002\"Google::Ads::Google" + "Ads::V6::Commonb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v6.enums.TargetImpressionShareLocationProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), }); internal_static_google_ads_googleads_v6_common_Commission_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v6_common_Commission_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_Commission_descriptor, new java.lang.String[] { "CommissionRateMicros", "CommissionRateMicros", }); internal_static_google_ads_googleads_v6_common_EnhancedCpc_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v6_common_EnhancedCpc_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_EnhancedCpc_descriptor, new java.lang.String[] { }); internal_static_google_ads_googleads_v6_common_ManualCpc_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v6_common_ManualCpc_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_ManualCpc_descriptor, new java.lang.String[] { "EnhancedCpcEnabled", "EnhancedCpcEnabled", }); internal_static_google_ads_googleads_v6_common_ManualCpm_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_ads_googleads_v6_common_ManualCpm_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_ManualCpm_descriptor, new java.lang.String[] { }); internal_static_google_ads_googleads_v6_common_ManualCpv_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_ads_googleads_v6_common_ManualCpv_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_ManualCpv_descriptor, new java.lang.String[] { }); internal_static_google_ads_googleads_v6_common_MaximizeConversions_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_ads_googleads_v6_common_MaximizeConversions_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_MaximizeConversions_descriptor, new java.lang.String[] { "TargetCpa", }); internal_static_google_ads_googleads_v6_common_MaximizeConversionValue_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_ads_googleads_v6_common_MaximizeConversionValue_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_MaximizeConversionValue_descriptor, new java.lang.String[] { "TargetRoas", "TargetRoas", }); internal_static_google_ads_googleads_v6_common_TargetCpa_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_ads_googleads_v6_common_TargetCpa_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_TargetCpa_descriptor, new java.lang.String[] { "TargetCpaMicros", "CpcBidCeilingMicros", "CpcBidFloorMicros", "TargetCpaMicros", "CpcBidCeilingMicros", "CpcBidFloorMicros", }); internal_static_google_ads_googleads_v6_common_TargetCpm_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_ads_googleads_v6_common_TargetCpm_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_TargetCpm_descriptor, new java.lang.String[] { }); internal_static_google_ads_googleads_v6_common_TargetImpressionShare_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_ads_googleads_v6_common_TargetImpressionShare_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_TargetImpressionShare_descriptor, new java.lang.String[] { "Location", "LocationFractionMicros", "CpcBidCeilingMicros", "LocationFractionMicros", "CpcBidCeilingMicros", }); internal_static_google_ads_googleads_v6_common_TargetRoas_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_ads_googleads_v6_common_TargetRoas_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_TargetRoas_descriptor, new java.lang.String[] { "TargetRoas", "CpcBidCeilingMicros", "CpcBidFloorMicros", "TargetRoas", "CpcBidCeilingMicros", "CpcBidFloorMicros", }); internal_static_google_ads_googleads_v6_common_TargetSpend_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_ads_googleads_v6_common_TargetSpend_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_TargetSpend_descriptor, new java.lang.String[] { "TargetSpendMicros", "CpcBidCeilingMicros", "TargetSpendMicros", "CpcBidCeilingMicros", }); internal_static_google_ads_googleads_v6_common_PercentCpc_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_ads_googleads_v6_common_PercentCpc_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v6_common_PercentCpc_descriptor, new java.lang.String[] { "CpcBidCeilingMicros", "EnhancedCpcEnabled", "CpcBidCeilingMicros", "EnhancedCpcEnabled", }); com.google.ads.googleads.v6.enums.TargetImpressionShareLocationProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
62.276786
162
0.800143
755fbeb6c4395183518b501fe56cd94ee0365196
557
package com.tudou.common.annotation; import java.lang.annotation.*; /** * 在不需要验证用户是否有权限的类或方法上标注即可(后台通常都是需要权限的)<br/> * 当某些 url 只需要用户登录后就可以访问时, 标注此注解<br/> * <span style="color:red">优先级低于 NotNeedLogin</span>, 也就是如果两个注解都有标注时, 对应类或方法的 url 就不需要登录 * <br><br> * * 在 Controller 类上标注后, 这个类下面的方法都不会再验证权限.<br> * 想要在某个方法上再次验证权限, 可以在这个方法上再标注一下这个注解并设置 flag = false * * @see NotNeedLogin */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface NotNeedPermission { boolean flag() default true; }
24.217391
88
0.745063
ecfac7220b95f8ebd31b6eff1edaf788675fb788
4,137
/* * YUI Test * Author: Nicholas C. Zakas <[email protected]> * Copyright (c) 2009, Yahoo! Inc. All rights reserved. * Code licensed under the BSD License: * http://developer.yahoo.net/yui/license.txt */ package com.yahoo.platform.yuitest.coverage.report; import com.yahoo.platform.yuitest.coverage.results.DirectoryCoverageReport; import com.yahoo.platform.yuitest.coverage.results.FileCoverageReport; import com.yahoo.platform.yuitest.coverage.results.SummaryCoverageReport; import com.yahoo.platform.yuitest.writers.ReportWriter; import com.yahoo.platform.yuitest.writers.ReportWriterFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Date; /** * * @author Nicholas C. Zakas */ public class GCOVReportGenerator implements CoverageReportGenerator { private File outputdir = null; private boolean verbose = false; /** * Creates a new GCOVReportGenerator * @param outputdir The output directory for the GCOV report. * @param verbose True to output additional information to the console. */ public GCOVReportGenerator(String outputdir, boolean verbose){ this.outputdir = new File(outputdir); this.verbose = verbose; } /** * Generates report files for the given coverage report. * @param report The report to generate files for. * @throws IOException When the files cannot be written. */ public void generate(SummaryCoverageReport report) throws IOException { generate(report, new Date()); } /** * Generates report files for the given coverage report. * @param report The report to generate files for. * @param timestamp The timestamp to apply to the files. * @throws IOException When the files cannot be written. */ public void generate(SummaryCoverageReport report, Date timestamp) throws IOException { //create the report directory now if (!outputdir.exists()){ outputdir.mkdirs(); if (verbose){ System.err.println("[INFO] Creating " + outputdir.getCanonicalPath()); } } DirectoryCoverageReport[] reports = report.getDirectoryReports(); for (int i=0; i < reports.length; i++){ generateDirectories(reports[i], timestamp); } } /** * Generates a report page for each file in the coverage information. * @param report The coverage information to generate reports for. * @param date The date associated with the report. * @throws IOException When a file cannot be written to. */ private void generateDirectories(DirectoryCoverageReport report, Date date) throws IOException { FileCoverageReport[] fileReports = report.getFileReports(); //make the directory to mimic the source file String parentDir = fileReports[0].getFile().getParent(); File parent = new File(outputdir.getAbsolutePath() + File.separator + parentDir); if (!parent.exists()){ parent.mkdirs(); } for (int i=0; i < fileReports.length; i++){ generateGCOVFile(fileReports[i], date, parent); } } /** * Generates a GCOV file for the file coverage information. * @param report The coverage information to generate files for. * @param date The date associated with the report. * @throws IOException When a file cannot be written to. */ private void generateGCOVFile(FileCoverageReport report, Date date, File parent) throws IOException { String outputFile = parent.getAbsolutePath() + File.separator + report.getFile().getName() + ".gcov"; if (verbose){ System.err.println("[INFO] Outputting " + outputFile); } Writer out = new OutputStreamWriter(new FileOutputStream(outputFile)); ReportWriter reportWriter = (new ReportWriterFactory<FileCoverageReport>()).getWriter(out, "GCOVFileReport"); reportWriter.write(report, date); out.close(); } }
36.610619
117
0.678994
bb1f7395d8fd5b62dfa7b56380650894ec552812
1,155
package com.example.demo.manager; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.manager.dao.EmployeeDao; import com.example.demo.model.Employee; @Service public class EmployeeManagerImpl implements EmployeeManager { private static final Logger logger = LogManager.getLogger(EmployeeManagerImpl.class.getName()); @Autowired private EmployeeDao dao; @Override public Employee findLogin(String email, String password) { logger.info("Accessing database"); Employee employee = dao.findLogin(email); if(employee != null && employee.getPassword().equals(password)) { logger.info("Returning employee information"); return employee; } return null; } @Override public Employee getAccount(int id) { logger.info("Accessing database"); Optional<Employee> employee = dao.findById(id); if(!employee.isPresent()) { return null; } else { logger.info("Returning employee information"); return employee.get(); } } }
25.108696
96
0.758442
2930ad4d41493c46d62d4e9283b6f868e2dab464
3,676
/** * Implementation of directed, weighed graph using a HashMap to represent adjacency list. * * @author marcinkossakowski on 9/24/14. */ import java.util.HashMap; import java.util.ArrayList; import java.util.HashSet; // For file reading import java.io.BufferedReader; import java.io.IOException; import java.io.FileReader; public class WeighedDigraph { private HashMap<Integer, ArrayList<WeighedDigraphEdge>> adj = new HashMap(); // adjacency-list public WeighedDigraph() {} /** * Instantiate graph from file with data * @param file * @throws IOException */ public WeighedDigraph(String file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; while ((line = reader.readLine()) != null) { String[] parts = line.split("\\s"); if (parts.length == 3) { int from = Integer.parseInt(parts[0]); int to = Integer.parseInt(parts[1]); double weight = Double.parseDouble(parts[2]); addEdge(new WeighedDigraphEdge(from, to, weight)); } } } /** * @param vertex * @return list of edges vertex is connected to. */ public ArrayList<WeighedDigraphEdge> edgesOf(int vertex) { return adj.get(vertex); } /** * @return list of all edges in the graph. */ public ArrayList<WeighedDigraphEdge> edges() { ArrayList list = new ArrayList<WeighedDigraphEdge>(); for (int from : adj.keySet()) { ArrayList<WeighedDigraphEdge> currentEdges = adj.get(from); for (WeighedDigraphEdge e : currentEdges) { list.add(e); } } return list; } /** * @return iterable of all vertices in the graph. */ public Iterable<Integer> vertices() { HashSet set = new HashSet(); for (WeighedDigraphEdge edge : edges()) { set.add(edge.from()); set.add(edge.to()); } return set; } /** * @return size of adjacency list */ public int size() { return adj.size(); } /** * @return string representation of digraph */ public String toString() { String out = ""; for (int from : adj.keySet()) { ArrayList<WeighedDigraphEdge> currentEdges = adj.get(from); out += from + " -> "; if (currentEdges.size() == 0) out += "-,"; for (WeighedDigraphEdge edge : currentEdges) out += edge.to() + " @ " + edge.weight() + ", "; out += "\n"; } return out; } /** * Add new edge to the system. * @param newEdge */ public void addEdge(WeighedDigraphEdge newEdge) { // create empty connection set if (!adj.containsKey(newEdge.from())) adj.put(newEdge.from(), new ArrayList<WeighedDigraphEdge>()); ArrayList<WeighedDigraphEdge> currentEdges = adj.get(newEdge.from()); /* Check if edge already exists, * if it is, replace it with new one assuming it needs to be updated */ //boolean edgeExists = false; /* for (int i = 0; i < currentEdges.size(); i++) { if (currentEdges.get(i).to() == newEdge.to()) { currentEdges.set(i, newEdge); edgeExists = true; break; } } */ //if (!edgeExists) currentEdges.add(newEdge); adj.put(newEdge.from(), currentEdges); } /** * Graph Tests * @param args */ }
26.070922
98
0.548966
343d8f4dd47753bd40cb3eec6ba05cb3e15049e2
165
class C { double test() { System.out.println("from test"); return 20.90; } } class D extends C { int test() { System.out.println("from D"); return 10; } }
9.705882
33
0.606061
8703c07049a8b561565ac7a405b0634c99f5beee
2,353
package com.omnicrola.pixelblaster.map.io; import com.omnicrola.pixelblaster.util.PointSet; public class TerrainShapes { public static final PointSet BASE = createRounded(); public static final PointSet CENTER = createSquare(); public static final PointSet ROUNDED = createRounded(); public static final PointSet CLIFF_LEFT = createSquare(); public static final PointSet CLIFF_RIGHT = createSquare(); public static final PointSet CLIFF_ALT_LEFT = createSquare(); public static final PointSet CLIFF_ALT_RIGHT = createSquare(); public static final PointSet CORNER_LEFT = createSquare(); public static final PointSet CORNER_RIGHT = createSquare(); public static final PointSet HALF = createSquare(); public static final PointSet HALF_LEFT = createSquare(); public static final PointSet HALF_MID = createSquare(); public static final PointSet HALF_RIGHT = createSquare(); public static final PointSet HILL_LEFT = createHillLeft(); public static final PointSet HILL_RIGHT = createHillRight(); public static final PointSet LEFT = createSquare(); public static final PointSet MID = createSquare(); public static final PointSet RIGHT = createSquare(); private static PointSet createSquare() { final PointSet polygon = new PointSet(); polygon.addPoint(-1.0f, -1.0f); polygon.addPoint(1.0f, -1.0f); polygon.addPoint(1.0f, 1.0f); polygon.addPoint(-1.0f, 1.0f); return polygon; } private static PointSet createRounded() { final PointSet polygon = new PointSet(); final float outerCorner = 0.75f; final float innerCorner = 0.9125f; final float edge = 1.0f; polygon.addPoint(-edge, -outerCorner); polygon.addPoint(-innerCorner, -innerCorner); polygon.addPoint(-outerCorner, -edge); polygon.addPoint(outerCorner, -edge); polygon.addPoint(innerCorner, -innerCorner); polygon.addPoint(edge, -outerCorner); polygon.addPoint(edge, edge); polygon.addPoint(-edge, edge); return polygon; } private static PointSet createHillRight() { final PointSet polygon = new PointSet(); polygon.addPoint(1.0f, -1.0f); polygon.addPoint(1.0f, 1.0f); polygon.addPoint(-1.0f, 1.0f); return polygon; } private static PointSet createHillLeft() { final PointSet polygon = new PointSet(); polygon.addPoint(-1.0f, -1.0f); polygon.addPoint(1.0f, 1.0f); polygon.addPoint(-1.0f, 1.0f); return polygon; } }
34.101449
63
0.747981
a3aa39a7f56385f4c6cd3c46e6d94a6d6a217b63
1,344
package org.juicecode.telehlam.ui.fingerprint; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import org.juicecode.telehlam.R; import org.juicecode.telehlam.utils.FingerPrintChecker; import org.juicecode.telehlam.utils.SharedPreferencesRepository; import org.juicecode.telehlam.utils.SnackbarShower; public class ConfirmScannerPrint extends Fragment { Button login; LinearLayout layout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_fingerprint_auth, container, false); layout = view.findViewById(R.id.layout); login = view.findViewById(R.id.login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FingerPrintChecker checker = new FingerPrintChecker(FingerPrintChecker.IDENTIFYING_WITH_FINGERPRINT, getContext(), new SnackbarShower(layout)); checker.checkAuth(new SharedPreferencesRepository(getContext())); } }); return view; } }
33.6
159
0.725446
8f7c870a2cc95f47fcf4f83bea6a98a35d0c1f7e
207
package org.vno.repository; import org.springframework.data.repository.CrudRepository; import org.vno.domain.Tag; /** * @author kk */ public interface TagRepository extends CrudRepository<Tag, Long> { }
18.818182
66
0.772947
715c42f99d50e81f807dd8df65b9a132625b20c7
1,726
package io.github.jsbd.common.serialization.bytebean.codec.primitive; import io.github.jsbd.common.serialization.bytebean.codec.ByteFieldCodec; import io.github.jsbd.common.serialization.bytebean.codec.NumberCodec; import io.github.jsbd.common.serialization.bytebean.context.DecContext; import io.github.jsbd.common.serialization.bytebean.context.DecResult; import io.github.jsbd.common.serialization.bytebean.context.EncContext; import org.apache.commons.lang.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LongCodec extends AbstractPrimitiveCodec implements ByteFieldCodec { private static final Logger logger = LoggerFactory.getLogger(LongCodec.class); @Override public Class<?>[] getFieldType() { return new Class<?>[] { long.class, Long.class }; } @Override public DecResult decode(DecContext ctx) { byte[] bytes = ctx.getDecBytes(); int byteLength = ctx.getByteSize(); NumberCodec numberCodec = ctx.getNumberCodec(); if (byteLength > bytes.length) { String errmsg = "LongCodec: not enough bytes for decode, need [" + byteLength + "], actually [" + bytes.length + "]."; if (null != ctx.getField()) { errmsg += "/ cause field is [" + ctx.getField() + "]"; } logger.error(errmsg); throw new RuntimeException(errmsg); } return new DecResult(numberCodec.bytes2Long(bytes, byteLength), ArrayUtils.subarray(bytes, byteLength, bytes.length)); } @Override public byte[] encode(EncContext ctx) { long enc = ((Long) ctx.getEncObject()).longValue(); int byteLength = ctx.getByteSize(); NumberCodec numberCodec = ctx.getNumberCodec(); return numberCodec.long2Bytes(enc, byteLength); } }
35.958333
124
0.727115
74945cb94f58d7a67b0b4dd0721bba4bd18ee705
2,266
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.sql.legacy.parser; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLTextLiteralExpr; import java.util.List; import org.opensearch.sql.legacy.domain.Where; import org.opensearch.sql.legacy.exception.SqlParseException; import org.opensearch.sql.legacy.utils.Util; /** * Created by Razma Tazz on 14/04/2016. */ public class ChildrenType { public String field; public String childType; public Where where; private boolean simple; public boolean tryFillFromExpr(SQLExpr expr) throws SqlParseException { if (!(expr instanceof SQLMethodInvokeExpr)) { return false; } SQLMethodInvokeExpr method = (SQLMethodInvokeExpr) expr; String methodName = method.getMethodName(); if (!methodName.toLowerCase().equals("children")) { return false; } List<SQLExpr> parameters = method.getParameters(); if (parameters.size() != 2) { throw new SqlParseException( "on children object only allowed 2 parameters (type, field)/(type, conditions...) "); } String type = Util.extendedToString(parameters.get(0)); this.childType = type; SQLExpr secondParameter = parameters.get(1); if (secondParameter instanceof SQLTextLiteralExpr || secondParameter instanceof SQLIdentifierExpr || secondParameter instanceof SQLPropertyExpr) { this.field = Util.extendedToString(secondParameter); this.simple = true; } else { Where where = Where.newInstance(); new WhereParser(new SqlParser()).parseWhere(secondParameter, where); if (where.getWheres().size() == 0) { throw new SqlParseException("Failed to parse filter condition"); } this.where = where; simple = false; } return true; } public boolean isSimple() { return simple; } }
31.472222
105
0.656222
bf2fa3995dbe514d0463795d01d5e78e197101c4
287
package com.biniam.designpatterns.abstractFactory.foobarmotorco; /** * @author Biniam Asnake */ public class CarVehicleFactory extends AbstractVehicleFactory { @Override Body getBody() { return new CarBody(); } @Override Chassis getChassis() { return new CarChassis(); } }
16.882353
64
0.738676
6afc643be3b8442d5c170a2a1967c2f5ba300624
517
package perfectNumber; import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.print("Enter number: "); Scanner input = new Scanner(System.in); int number = input.nextInt(); int total = 0; for (int i = 1; i < number; i++) { if (number % i == 0) { total = total + i ; } } if (total == number) { System.out.println(number + " is perfect number"); }else { System.out.println(number + " is NOT perfect number"); } } }
17.233333
57
0.584139
6c4b49b49b3b001f273c7940446736d32d809c0c
5,022
package com.mundane.androidtechniqueapply.ui.fragment; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import com.mundane.androidtechniqueapply.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ObjectAnimateSubJavaFragment extends Fragment { @BindView(R.id.btn_alpha) Button mBtnAlpha; @BindView(R.id.btn_translate) Button mBtnTranslate; @BindView(R.id.btn_color) Button mBtnScale; @BindView(R.id.btn_rotate) Button mBtnRotate; @BindView(R.id.btn_set) Button mBtnSet; @BindView(R.id.iv) ImageView mIv; private final String TAG = getClass().getSimpleName(); public ObjectAnimateSubJavaFragment() { // Required empty public constructor } public static ObjectAnimateSubJavaFragment newInstance() { ObjectAnimateSubJavaFragment fragment = new ObjectAnimateSubJavaFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_object_animate_sub_java, container, false); ButterKnife.bind(this, view); return view; } @OnClick({R.id.btn_alpha, R.id.btn_translate, R.id.btn_color, R.id.btn_rotate, R.id.btn_set}) public void onClick(View view) { switch (view.getId()) { case R.id.btn_alpha: alpha(); break; case R.id.btn_translate: translate(); break; case R.id.btn_color: scale(); break; case R.id.btn_rotate: rotation(); break; case R.id.btn_set: // set1(); set2(); break; } } private void set2() { AnimatorSet animatorSet = new AnimatorSet(); ObjectAnimator alpha = ObjectAnimator.ofFloat(mIv, "alpha", 1f, 0f, 1f); ObjectAnimator rotation = ObjectAnimator.ofFloat(mIv, "rotation", 0f, 360f); animatorSet.setDuration(2000); animatorSet.playTogether(alpha, rotation); animatorSet.start(); // animatorSet.play(alpha).after(rotation).before(alpha).with(rotation); // animatorSet.setStartDelay(1000); // alpha.setStartDelay(1000); // animatorSet.playSequentially(alpha, rotation); } private void set1() { PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1f, 0.5f); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0.5f); PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0.5f); ObjectAnimator.ofPropertyValuesHolder(mIv, alpha, scaleX, scaleY).setDuration(1000).start(); } private void rotation() { // 这里设置的是绝对坐标, 这两个一定要同时设置, 只设置一个是无效的 mIv.setPivotY(0.5f * mIv.getHeight()); mIv.setPivotX(0); ObjectAnimator.ofFloat(mIv, "rotation", 0f, 360f).setDuration(2000).start(); // ObjectAnimator.ofFloat(mIv, "rotationY", 0f, 180f).setDuration(1000).start();//绕着图片中心的Y轴旋转 } private void scale() { // ValueAnimator valueAnimator = ObjectAnimator.ofFloat(0, 0.5f, 1.0f); ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mIv, "scaleX", 1, 0.5f).setDuration(2000); objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float animatedValue = (float) animation.getAnimatedValue(); float animatedFraction = animation.getAnimatedFraction(); Log.d(TAG, "Fraction = " + animatedFraction); mIv.setScaleX(animatedValue); mIv.setScaleY(animatedValue); } }); objectAnimator.start(); } private void translate() { ObjectAnimator.ofFloat(mIv, "translationX", 0, 500, 0, 500, 0).setDuration(4000).start(); } private void alpha() { ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mIv, "alpha", 1, 0); objectAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); objectAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); } }); objectAnimator.setDuration(3000); // objectAnimator.setFloatValues(mIv.getAlpha(), 1); objectAnimator.setRepeatCount(ObjectAnimator.INFINITE); objectAnimator.setRepeatMode(ObjectAnimator.REVERSE); // objectAnimator.setStartDelay(1000);//延时开始 objectAnimator.start(); } }
29.368421
100
0.749303
57f57f8de4bc004540799bbb230577c76da568b2
715
package io.vertx.armysystem.microservice.dictionary.api; import io.vertx.armysystem.business.common.CRUDRestAPIVerticle; import io.vertx.armysystem.business.common.CRUDService; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.Router; import java.util.List; public class DictionaryRestAPIVerticle extends CRUDRestAPIVerticle { private static final Logger logger = LoggerFactory.getLogger(DictionaryRestAPIVerticle.class); private static final String SERVICE_NAME = "dictionary-rest-api"; public DictionaryRestAPIVerticle(List<CRUDService> services) { super(services, SERVICE_NAME); } @Override public void routeApi(Router router) { } }
29.791667
96
0.806993
a141b72f8d10d06eeb97fed39dc0b842a4b1f141
5,019
/******************************************************************************* * Copyright © 2019 by California Community Colleges Chancellor's Office * * 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.cccnext.tesuto.user.assembler; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.cccnext.tesuto.admin.dto.SecurityPermissionDto; import org.cccnext.tesuto.user.model.SecurityPermission; import org.cccnext.tesuto.user.repository.SecurityPermissionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * @author James T Stanley <[email protected]> */ @Slf4j @Component(value = "securityPermissionDtoAssembler") public class SecurityPermissionDtoAssemblerImpl implements SecurityPermissionDtoAssembler { @Autowired SecurityPermissionRepository securityPermissionRepository; @Override public SecurityPermissionDto create(SecurityPermissionDto securityPermissionDto) { SecurityPermission securityPermission = disassembleDto(securityPermissionDto); // Protect if there is no security permission returned, in which case it // would these would not be generated. if (securityPermission != null) { Date currentTimeStamp = new Date(System.currentTimeMillis()); securityPermission.setLastUpdatedDate(currentTimeStamp); securityPermission.setCreatedOnDate(currentTimeStamp); } securityPermission = securityPermissionRepository.save(securityPermission); return assembleDto(securityPermission); } @Override public SecurityPermissionDto update(SecurityPermissionDto securityPermissionDto) { SecurityPermission oldUser = securityPermissionRepository .findById(securityPermissionDto.getSecurityPermissionId()).get(); securityPermissionDto.setSecurityPermissionId(oldUser.getSecurityPermissionId()); SecurityPermission securityPermission = disassembleDto(securityPermissionDto); securityPermission = securityPermissionRepository.save(securityPermission); return assembleDto(securityPermission); } @Override public SecurityPermissionDto readById(String securityPermissionId) { SecurityPermission securityPermission = securityPermissionRepository.findById(securityPermissionId).get(); return assembleDto(securityPermission); } @Override public List<SecurityPermissionDto> readAll() { List<SecurityPermission> securityPermissionList = securityPermissionRepository.findAll(); List<SecurityPermissionDto> securityPermissions = new ArrayList<SecurityPermissionDto>(); for (SecurityPermission securityPermission : securityPermissionList) { securityPermissions.add(assembleDto(securityPermission)); } return securityPermissions; } @Override public SecurityPermissionDto assembleDto(SecurityPermission securityPermission) { // Drop out of here immediately if there is nothing to assemble. if (securityPermission == null) { return null; } SecurityPermissionDto securityPermissionDto = new SecurityPermissionDto(); securityPermissionDto.setCreatedOnDate(securityPermission.getCreatedOnDate()); securityPermissionDto.setLastUpdatedDate(securityPermission.getLastUpdatedDate()); securityPermissionDto.setSecurityPermissionId(securityPermission.getSecurityPermissionId()); securityPermissionDto.setDescription(securityPermission.getDescription()); return securityPermissionDto; } @Override public SecurityPermission disassembleDto(SecurityPermissionDto securityPermissionDto) { // If there is nothing to disassemble, just return null if (securityPermissionDto == null) { return null; } SecurityPermission securityPermission = new SecurityPermission(); securityPermission.setCreatedOnDate(securityPermissionDto.getCreatedOnDate()); securityPermission.setLastUpdatedDate(securityPermissionDto.getLastUpdatedDate()); securityPermission.setSecurityPermissionId(securityPermissionDto.getSecurityPermissionId()); securityPermission.setDescription(securityPermissionDto.getDescription()); return securityPermission; } }
43.267241
114
0.736202
037a3c37e5edd9679d87ac2be1759681cd08f1e7
7,912
/* * @copyright defined in LICENSE.txt */ package hera.api.model; import static hera.util.ValidationUtils.assertNotNull; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import hera.AbstractTestCase; import hera.api.model.Aer.Unit; import hera.key.AergoKey; import hera.key.AergoKeyGenerator; import java.io.IOException; import java.util.List; import org.junit.Test; public class RawTransactionTest extends AbstractTestCase { protected final ChainIdHash chainIdHash = ChainIdHash.of(BytesValue.EMPTY); protected final AccountAddress accountAddress = new AccountAddress("AmLo9CGR3xFZPVKZ5moSVRNW1kyscY9rVkCvgrpwNJjRUPUWadC5"); @Test public void testCalculateHashWithRawTx() { final RawTransaction rawTransaction = RawTransaction.newBuilder(chainIdHash) .from(accountAddress) .to(accountAddress) .amount("10000", Unit.AER) .nonce(1L) .fee(Fee.of(5)) .build(); assertNotNull(rawTransaction.calculateHash()); } @Test public void testCalculateHashWithRawTxAndSignature() throws IOException { final RawTransaction rawTransaction = RawTransaction.newBuilder(chainIdHash) .from(accountAddress) .to(accountAddress) .amount("10000", Unit.AER) .nonce(1L) .fee(Fee.of(5)) .build(); final TxHash hash = rawTransaction.calculateHash(Signature.EMPTY); assertNotNull(hash); } @Test public void testPlainTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final RawTransaction plainTransaction = RawTransaction.newBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .to(aergoKey.getAddress()) .amount(Aer.AERGO_ONE) .nonce(1L) .fee(Fee.ZERO) .payload(BytesValue.of("payload".getBytes())) .build(); assertNotNull(plainTransaction); } @Test public void testDeployContractTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final ContractDefinition deployTarget = ContractDefinition.newBuilder() .encodedContract( "FppTEQaroys1N4P8RcAYYiEhHaQaRE9fzANUx4q2RHDXaRo6TYiTa61n25JcV19grEhpg8qdCWVdsDE2yVfuTKxxcdsTQA2B5zTfxA4GqeRqYGYgWJpj1geuLJAn1RjotdRRxSS1BFA6CAftxjcgiP6WUHacmgtNzoWViYESykhjqVLdmTfV12d44wfh9YAgQ57aRkLNCPkujbnJhdhHEtY1hrJYLCxUDBveqVcDhrrvcHtjDAUcZ5UMzbg6qR1kthGB1Lua6ymw1BmfySNtqb1b6Hp92UPMa7gi5FpAXF5XgpQtEbYDXMbtgu5XtXNhNejrtArcekmjrmPXRoTnMDGUQFcALtnNCrgSv2z5PiXP1coGEbHLTTbxkmJmJz6arEfsb6J1Dv7wnvgysDFVApcpABfwMjHLmnEGvUCLthRfHNBDGydx9jvJQvismqdpDfcEaNBCo5SRMCqGS1FtKtpXjRaHGGFGcTfo9axnsJgAGxLk") .amount(Aer.ZERO) .constructorArgs(1, 2) .build(); final RawTransaction deployTransaction = RawTransaction.newDeployContractBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .definition(deployTarget) .nonce(1L) .fee(Fee.ZERO) .build(); assertNotNull(deployTransaction); } @Test public void testInvokeContractTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final ContractInterface contractInterface = dummyContractInterface(); final ContractInvocation execute = contractInterface.newInvocationBuilder() .function("set") .args("key", "123") .delegateFee(false) .build(); final RawTransaction executeTransaction = RawTransaction.newInvokeContractBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .invocation(execute) .nonce(1L) .fee(Fee.ZERO) .build(); assertNotNull(executeTransaction); } protected ContractInterface dummyContractInterface() { final ContractAddress address = ContractAddress.of("AmJaNDXoPbBRn9XHh9onKbDKuAzj88n5Bzt7KniYA78qUEc5EwBd"); final String version = "v1"; final String language = "lua"; final ContractFunction set = new ContractFunction("set", false, false, true); final ContractFunction get = new ContractFunction("get", false, true, false); final List<ContractFunction> functions = asList(set, get); final List<StateVariable> stateVariables = emptyList(); return ContractInterface .newBuilder() .address(address) .version(version) .language(language) .functions(functions) .stateVariables(stateVariables) .build(); } @Test public void testReDeployTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final ContractDefinition reDeployTarget = ContractDefinition.newBuilder() .encodedContract( "FppTEQaroys1N4P8RcAYYiEhHaQaRE9fzANUx4q2RHDXaRo6TYiTa61n25JcV19grEhpg8qdCWVdsDE2yVfuTKxxcdsTQA2B5zTfxA4GqeRqYGYgWJpj1geuLJAn1RjotdRRxSS1BFA6CAftxjcgiP6WUHacmgtNzoWViYESykhjqVLdmTfV12d44wfh9YAgQ57aRkLNCPkujbnJhdhHEtY1hrJYLCxUDBveqVcDhrrvcHtjDAUcZ5UMzbg6qR1kthGB1Lua6ymw1BmfySNtqb1b6Hp92UPMa7gi5FpAXF5XgpQtEbYDXMbtgu5XtXNhNejrtArcekmjrmPXRoTnMDGUQFcALtnNCrgSv2z5PiXP1coGEbHLTTbxkmJmJz6arEfsb6J1Dv7wnvgysDFVApcpABfwMjHLmnEGvUCLthRfHNBDGydx9jvJQvismqdpDfcEaNBCo5SRMCqGS1FtKtpXjRaHGGFGcTfo9axnsJgAGxLk") .amount(Aer.ZERO) .constructorArgs(1, 2) .build(); final RawTransaction reDeployTransaction = RawTransaction.newReDeployContractBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .creator(aergoKey.getAddress()) // must be creator .contractAddress(ContractAddress.of("AmJaNDXoPbBRn9XHh9onKbDKuAzj88n5Bzt7KniYA78qUEc5EwBd")) .definition(reDeployTarget) .nonce(1L) .fee(Fee.ZERO) .build(); assertNotNull(reDeployTransaction); } @Test public void testCreateNameTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final RawTransaction createNameTransaction = RawTransaction.newCreateNameTxBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .name("namenamename") .nonce(1L) .build(); assertNotNull(aergoKey); } @Test public void testUpdateNameTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final RawTransaction updateNameTransaction = RawTransaction.newUpdateNameTxBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .name("namenamename") .nextOwner(AccountAddress.of("AmgVbUZiReUVFXdYb4UVMru4ZqyicSsFPqumRx8LfwMKLFk66SNw")) .nonce(1L) .build(); assertNotNull(updateNameTransaction); } @Test public void testStakeTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final RawTransaction stakeTransaction = RawTransaction.newStakeTxBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .amount(Aer.of("10000", Unit.AERGO)) .nonce(1L) .build(); assertNotNull(stakeTransaction); } @Test public void testUnstakeTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final RawTransaction unstakeTransaction = RawTransaction.newUnstakeTxBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .amount(Aer.of("10000", Unit.AERGO)) .nonce(1L) .build(); assertNotNull(unstakeTransaction); } @Test public void testVoteTransaction() { final AergoKey aergoKey = new AergoKeyGenerator().create(); final RawTransaction voteTransaction = RawTransaction.newVoteTxBuilder() .chainIdHash(ChainIdHash.of(BytesValue.EMPTY)) .from(aergoKey.getAddress()) .voteId("voteBP") .candidates(asList("123", "456")) .nonce(1L) .build(); assertNotNull(voteTransaction); } }
38.407767
511
0.728387
d32faba95c69b7c6f3eb2160b257ab5b5a602628
7,341
/* * MergeValue.java * * This source file is part of the FoundationDB open source project * * Copyright 2015-2020 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.query.predicates; import com.apple.foundationdb.annotation.API; import com.apple.foundationdb.annotation.SpotBugsSuppressWarnings; import com.apple.foundationdb.record.EvaluationContext; import com.apple.foundationdb.record.ObjectPlanHash; import com.apple.foundationdb.record.PlanHashable; import com.apple.foundationdb.record.RecordCoreException; import com.apple.foundationdb.record.provider.foundationdb.FDBRecord; import com.apple.foundationdb.record.provider.foundationdb.FDBRecordStoreBase; import com.apple.foundationdb.record.query.plan.temp.AliasMap; import com.apple.foundationdb.record.query.plan.temp.Quantifier; import com.google.common.base.Preconditions; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.protobuf.Message; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * A value merges the input messages given to it into an output message. */ @API(API.Status.EXPERIMENTAL) public class MergeValue implements Value { private static final ObjectPlanHash BASE_HASH = new ObjectPlanHash("Merge-Value"); @Nonnull private final List<? extends QuantifiedColumnValue> children; public MergeValue(@Nonnull Iterable<? extends QuantifiedColumnValue> values) { this.children = ImmutableList.copyOf(values); Preconditions.checkArgument(!children.isEmpty()); } @Nonnull @Override public Iterable<? extends QuantifiedColumnValue> getChildren() { return children; } @Nonnull @Override public MergeValue withChildren(final Iterable<? extends Value> newChildren) { return new MergeValue(StreamSupport.stream(newChildren.spliterator(), false) .map(child -> { if (child instanceof QuantifiedColumnValue) { return (QuantifiedColumnValue)child; } throw new RecordCoreException("invalid call to withChildren; expected quantified value"); }) .collect(ImmutableList.toImmutableList())); } @Nullable @Override public <M extends Message> Object eval(@Nonnull final FDBRecordStoreBase<M> store, @Nonnull final EvaluationContext context, @Nullable final FDBRecord<M> record, @Nullable final M message) { if (message == null) { return null; } // TODO For now we'll just go through all the quantifiers and see if they have been bound by the caller. // If they are set, we happily use their value in the merge. If they are unset, we just skip that reference. // This can happen in the context of a set operation as the cursors over the e.g. union may only be // valid for one quantifier (or a subset). Us going through all possible references here will lead to // sub optimal performance as the caller already knows which quantifiers are bound and which ones are not. // Suggestion (although not implemented): We can allow the context to tell us which quantifiers are bound // and which ones are not. EvaluationContext#getBindings() almost does that job except that it also returns // all purely correlated bindings and not just bindings from the quantifiers this set expression ranges // over. final ImmutableList<Message> childrenResults = children.stream() .flatMap(child -> { final Object childResult = child.eval(store, context, record, message); if (!(childResult instanceof Message)) { return Stream.of(); } return Stream.of((Message)childResult); }).collect(ImmutableList.toImmutableList()); return merge(childrenResults); } @Nullable @SuppressWarnings("unused") private Message merge(@Nonnull final List<Message> childrenResults) { return null; // TODO do it } @Override public int semanticHashCode() { return PlanHashable.objectsPlanHash(PlanHashKind.FOR_CONTINUATION, BASE_HASH, children); } @Override public int planHash(@Nonnull final PlanHashKind hashKind) { return PlanHashable.objectsPlanHash(hashKind, BASE_HASH, children); } @Override public String toString() { return "merge(" + children.stream() .map(Value::toString) .collect(Collectors.joining(", ")) + ")"; } @Override public int hashCode() { return semanticHashCode(); } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @SpotBugsSuppressWarnings("EQ_UNUSUAL") @Override public boolean equals(final Object other) { return semanticEquals(other, AliasMap.identitiesFor(getCorrelatedTo())); } public static List<? extends MergeValue> pivotAndMergeValues(@Nonnull final List<? extends Quantifier> quantifiers) { Verify.verify(!quantifiers.isEmpty()); int numberOfFields = -1; final ImmutableList.Builder<List<? extends QuantifiedColumnValue>> allFlowedValuesBuilder = ImmutableList.builder(); for (final Quantifier quantifier : quantifiers) { final List<? extends QuantifiedColumnValue> flowedValues = quantifier.getFlowedValues(); allFlowedValuesBuilder.add(flowedValues); if (numberOfFields == -1 || numberOfFields > flowedValues.size()) { numberOfFields = flowedValues.size(); } } final ImmutableList<List<? extends QuantifiedColumnValue>> allFlowedValues = allFlowedValuesBuilder.build(); final ImmutableList.Builder<MergeValue> mergeValuesBuilder = ImmutableList.builder(); for (int i = 0; i < numberOfFields; i ++) { final ImmutableList.Builder<QuantifiedColumnValue> toBeMergedValuesBuilder = ImmutableList.builder(); for (final List<? extends QuantifiedColumnValue> allFlowedValuesFromQuantifier : allFlowedValues) { final QuantifiedColumnValue quantifiedColumnValue = allFlowedValuesFromQuantifier.get(i); toBeMergedValuesBuilder.add(quantifiedColumnValue); } mergeValuesBuilder.add(new MergeValue(toBeMergedValuesBuilder.build())); } return mergeValuesBuilder.build(); } }
43.182353
194
0.6871
b0d720b27c3e07a3dfcc5b8f1ee2cdc1b1432497
7,611
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2015-Present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo; import mock.*; import mock.muc.*; import mock.util.*; import org.jitsi.jicofo.conference.source.*; import org.jitsi.utils.*; import org.junit.*; import org.junit.runner.*; import org.junit.runners.*; import org.jxmpp.jid.*; import org.jxmpp.jid.impl.*; import static org.junit.Assert.*; @RunWith(JUnit4.class) public class AdvertiseSSRCsTest { private final JicofoHarness harness = new JicofoHarness(); @After public void tearDown() { harness.shutdown(); } @Test public void testOneToOneConference() throws Exception { //FIXME: test when there is participant without contents EntityBareJid roomName = JidCreate.entityBareFrom("[email protected]"); TestConference testConf = new TestConference(harness, roomName); MockChatRoom chatRoom = testConf.getChatRoom(); // Join with all users MockParticipant user1 = new MockParticipant("User1"); user1.join(chatRoom); MockParticipant user2 = new MockParticipant("User2"); user2.join(chatRoom); // Accept invite with all users assertNotNull(user1.acceptInvite(4000)); assertNotNull(user2.acceptInvite(4000)); user1.waitForAddSource(2000); user2.waitForAddSource(2000); ConferenceSourceMap user1RemoteSources = user1.getRemoteSources(); assertEquals(2, user1.numRemoteSourcesOfType(MediaType.AUDIO)); assertEquals(0, user1.numRemoteSourceGroupsOfType(MediaType.AUDIO)); // Verify SSRC owners and video types // From user 1 perspective EndpointSourceSet user1User2Sources = user1RemoteSources.get(user2.getMyJid()); Source user1User2AudioSource = ExtensionsKt.getFirstSourceOfType(user1User2Sources, MediaType.AUDIO); assertNotNull(user1User2AudioSource); Source user1User2VideoSource = ExtensionsKt.getFirstSourceOfType(user1User2Sources, MediaType.VIDEO); assertNotNull(user1User2VideoSource); // From user 2 perspective EndpointSourceSet user2User1Sources = user2.getRemoteSources().get(user1.getMyJid()); Source user2User1AudioSource = ExtensionsKt.getFirstSourceOfType(user2User1Sources, MediaType.AUDIO); assertNotNull(user2User1AudioSource); Source user2User1VideoSource = ExtensionsKt.getFirstSourceOfType(user2User1Sources, MediaType.VIDEO); assertNotNull(user2User1VideoSource); user2.leave(); // We no longer send source-remove when a member leaves, it is up to the participants to remove a member's // sources when it leaves. // assertNotNull(user1.waitForRemoveSource(500)); assertEquals(1, user1.numRemoteSourcesOfType(MediaType.AUDIO)); assertEquals(0, user1.numRemoteSourceGroupsOfType(MediaType.AUDIO)); MockParticipant user3 = new MockParticipant("User3"); user3.join(chatRoom); assertNotNull(user3.acceptInvite(4000)); user1.waitForAddSource(2000); assertEquals(2, user1.numRemoteSourcesOfType(MediaType.AUDIO)); assertEquals(0, user1.numRemoteSourceGroupsOfType(MediaType.AUDIO)); assertEquals(2, user3.numRemoteSourcesOfType(MediaType.AUDIO)); assertEquals(0, user3.numRemoteSourceGroupsOfType(MediaType.AUDIO)); user3.leave(); user1.leave(); testConf.stop(); } @Test public void testSourceRemoval() throws Exception { EntityBareJid roomName = JidCreate.entityBareFrom("[email protected]"); TestConference testConf = new TestConference(harness, roomName); MockChatRoom chat = testConf.getChatRoom(); // Join with all users MockParticipant user1 = new MockParticipant("User1"); user1.join(chat); MockParticipant user2 = new MockParticipant("User2"); user2.join(chat); // Accept invite with all users assertNotNull(user1.acceptInvite(4000)); assertNotNull(user2.acceptInvite(4000)); user1.waitForAddSource(2000); user2.waitForAddSource(2000); user2.audioSourceRemove(); assertNotNull(user1.waitForRemoveSource(500)); assertEquals(1, user1.numRemoteSourcesOfType(MediaType.AUDIO)); assertEquals(0, user1.numRemoteSourceGroupsOfType(MediaType.AUDIO)); MockParticipant user3 = new MockParticipant("User3"); user3.join(chat); assertNotNull(user3.acceptInvite(4000)); user1.waitForAddSource(2000); assertEquals(2, user1.numRemoteSourcesOfType(MediaType.AUDIO)); assertEquals(2, user3.numRemoteSourcesOfType(MediaType.AUDIO)); // No groups assertEquals(0, user1.numRemoteSourceGroupsOfType(MediaType.AUDIO)); assertEquals(0, user3.numRemoteSourceGroupsOfType(MediaType.AUDIO)); user3.leave(); user2.leave(); user1.leave(); testConf.stop(); } @Test public void testDuplicatedSSRCs() throws Exception { EntityBareJid roomName = JidCreate.entityBareFrom("[email protected]"); TestConference testConf = new TestConference(harness, roomName); MockChatRoom chatRoom = testConf.getChatRoom(); // Join with all users MockParticipant user1 = new MockParticipant("User1"); user1.join(chatRoom); MockParticipant user2 = new MockParticipant("User2"); user2.join(chatRoom); // Accept invite with all users long u1VideoSSRC = MockParticipant.nextSSRC(); user1.addLocalVideoSSRC(u1VideoSSRC); long u1VideoSSRC2 = MockParticipant.nextSSRC(); user1.addLocalVideoSSRC(u1VideoSSRC2); assertNotNull(user1.acceptInvite(4000)); assertNotNull(user2.acceptInvite(4000)); assertNotNull(user1.waitForAddSource(1000)); assertNotNull(user2.waitForAddSource(1000)); // There is 1 + 2 extra we've created here in the test assertEquals(1 /* jvb */ + 3, user2.numRemoteSourcesOfType(MediaType.VIDEO)); // No groups assertEquals(0, user2.numRemoteSourceGroupsOfType(MediaType.VIDEO)); user1.videoSourceAdd(new long[]{ u1VideoSSRC }); user1.videoSourceAdd( new long[]{ u1VideoSSRC, u1VideoSSRC2, u1VideoSSRC, u1VideoSSRC, u1VideoSSRC, u1VideoSSRC2 }); user1.videoSourceAdd(new long[]{ u1VideoSSRC2, u1VideoSSRC }); // There should be no source-add notifications sent assertNull(user2.waitForAddSource(500)); assertEquals(1 + /* jvb */ + 1, user2.numRemoteSourcesOfType(MediaType.AUDIO)); // There is 1 + 2 extra we've created here in the test assertEquals(1 + /* jvb */ + 3, user2.numRemoteSourcesOfType(MediaType.VIDEO)); user2.leave(); user1.leave(); testConf.stop(); } }
34.438914
114
0.685587
b2e40a259a296f183205d7e8184846244f221384
12,176
package com.example.campushelp_s.fragment; import android.app.Activity; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; import com.example.campushelp_s.R; import java.util.List; import bean.Task; import bean.User; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.datatype.BmobPointer; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.DownloadFileListener; import cn.bmob.v3.listener.FindListener; public class Main_Information_Fragment extends Fragment/* implements View.OnClickListener*/ { private View view; private User user; private Fragment currentFragment; //当前fragment对象 private com.example.campushelp_s.Model.userModel userModel; private ImageView image_edit; private ImageView image_head; private TextView tv_user_name; private TextView tv_user_ID; private TextView tv_user_sex; private TextView tv_user_phone; private TextView tv_user_email; private TextView tv_user_account; private ImageView image_user_account_record; private TextView tv_user_focus; private ImageView image_user_focus_show; private TextView tv_user_favorite; private ImageView image_user_collection_show; private TextView tv_user_finish_count; private ImageView image_user_finish_count_show; private TextView tv_user_grade; private ImageView image_user_grade; private TextView tv_user_introduction; private ImageView image_user_introduction_edit; private Button btn_loginout; private String TAG = "TAG"; private int number; private String num; private View mRoot; private Activity mActivity; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.personal_main_frag, container, false); userModel = new ViewModelProvider(getActivity()).get(com.example.campushelp_s.Model.userModel.class); user = (User) getActivity().getIntent().getSerializableExtra("user"); userModel.setUser(user); currentFragment = Main_Information_Fragment.this; Log.d("username", user.getName()); refresh(user); collection_Number(); follow_Number(); Log.d(TAG, "oncreate"); mRoot=view; mActivity=getActivity(); image_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jump_to_edit(); } }); image_user_collection_show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jump_to_collection(); } }); image_user_focus_show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jump_to_attention(); } }); // image_user_finish_count_show.setOnClickListener(this); // image_user_grade.setOnClickListener(this); // btn_loginout.setOnClickListener(this); return view; } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if (!hidden) { currentFragment = Main_Information_Fragment.this; userModel = new ViewModelProvider(getActivity()).get(com.example.campushelp_s.Model.userModel.class); userModel.getUser(); refresh(user); } } // @Override // public void onClick(View v) { // switch (v.getId()) { // case R.id.wd_bj://如果点击的是设置界面则跳转 // Log.d("test", "test"); // Edit_fragment edit_fragment = new Edit_fragment(); // showFragment(edit_fragment); // break; // case R.id.wd_scj_t: // Collection_Fragment collection_fragment = new Collection_Fragment(); // showFragment(collection_fragment); // break; // case R.id.wd_wcsl_t: // //跳转到主菜单的任务界面 // break; // case R.id.wd_pj_t: // //跳转到主菜单的任务界面 // break; // case R.id.wd_gz_t: // Attention_fragment attention_fragment = new Attention_fragment(user); // showFragment(attention_fragment); // break; // case R.id.wd_tcdl: // getActivity().finish(); // break; // default: // break; // // } // } /** * 用于初始化以及之后编辑子碎片返回时方便刷新 * * @param user */ public void refresh(User user) { // view.setVisibility(View.VISIBLE);//使当前主界面可见 image_edit = view.findViewById(R.id.wd_bj); image_head = view.findViewById(R.id.wd_tx); tv_user_name = view.findViewById(R.id.wd_name); tv_user_ID = view.findViewById(R.id.tv_user_ID); tv_user_sex = view.findViewById(R.id.wd_xb); tv_user_phone = view.findViewById(R.id.wd_sjh); tv_user_email = view.findViewById(R.id.wd_yx); tv_user_account = view.findViewById(R.id.wd_ye); //image_user_account_record = view.findViewById(R.id.wd_ye_t); tv_user_focus = view.findViewById(R.id.wd_gz); image_user_focus_show = view.findViewById(R.id.wd_gz_t); tv_user_favorite = view.findViewById(R.id.wd_scj); image_user_collection_show = view.findViewById(R.id.wd_scj_t); tv_user_finish_count = view.findViewById(R.id.wd_wcsl); //image_user_finish_count_show = view.findViewById(R.id.wd_wcsl_t); //tv_user_grade = view.findViewById(R.id.wd_pj); //image_user_grade = view.findViewById(R.id.wd_pj_t); tv_user_introduction = view.findViewById(R.id.wd_grjj); //image_user_introduction_edit = view.findViewById(R.id.wd_grjj_t); btn_loginout = view.findViewById(R.id.wd_tcdl); image_head = view.findViewById(R.id.wd_tx); //显示user数据 tv_user_name.setText(user.getName()); tv_user_ID.setText(user.getUserID()); tv_user_sex.setText(user.getSex()); tv_user_phone.setText(user.getPhone()); tv_user_email.setText(user.getEmail()); tv_user_account.setText(user.getBalance().toString()+" U币"); // collection_Number(); // Log.d("number",""+number); num = userModel.collection_Number(); tv_user_favorite.setText(""+num); tv_user_finish_count.setText(user.getDoneNumber().toString()); tv_user_introduction.setText(user.getInfo()); //testremovefans(); BmobFile icon = user.getImage(); if(icon!=null){ icon.download(new DownloadFileListener() { @Override public void done(String s, BmobException e) { if(e!=null){ Log.d("downloadIcon", e.toString()); }else{ image_head.setImageBitmap(BitmapFactory.decodeFile(s)); } } @Override public void onProgress(Integer integer, long l) { } }); }else{ image_head.setImageResource(R.drawable.default_user_icon); } } /** * 用来显示指定的fragment,方便复用 * * @param fragment */ public void showFragment(Fragment fragment) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.hide(currentFragment);//隐藏当前fragment if (!fragment.isAdded()) { transaction .addToBackStack(null) .add(R.id.fl_replace, fragment)//如果没有添加过则先添加在显示 .hide(currentFragment) .show(fragment) .commit(); } else { transaction .show(fragment) .hide(currentFragment) .commit(); } } /** * 简单收集一下收藏任务的数量,转换为string类型输出 * @return */ public void collection_Number() { BmobQuery<Task> taskQuery = new BmobQuery<>();//查找收藏的任务 taskQuery.addWhereRelatedTo("collection", new BmobPointer(user)); taskQuery.findObjects(new FindListener<Task>() { @Override public void done(List<Task> list, BmobException e) { if (e == null){ number = list.size(); Log.d("number",""+number); Log.d("listsize",""+list.size()); TextView tv_collectionNum = mRoot.findViewById(R.id.wd_scj); tv_collectionNum.setText(Integer.toString(number)); } else { Log.d("error1",e.toString()); } } }); } /** * 简单收集一下关注用户的数量,转换为string类型输出 * @return */ public void follow_Number() { BmobQuery<User> taskQuery = new BmobQuery<>();//查找收藏的任务 taskQuery.addWhereRelatedTo("follow", new BmobPointer(user)); taskQuery.findObjects(new FindListener<User>() { @Override public void done(List<User> list, BmobException e) { if (e == null){ number = list.size(); Log.d("number",""+number); Log.d("listsize",""+list.size()); TextView tv_followNum = mRoot.findViewById(R.id.wd_gz); tv_followNum.setText(Integer.toString(number)); } else { Log.d("error1",e.toString()); } } }); } //跳转到关注页面 public void jump_to_attention(){ FragmentTransaction transaction = getFragmentManager().beginTransaction(); //String textItem = ((TextView) view).getText().toString(); Attention_fragment attention_fragment = new Attention_fragment(user); Bundle bundle = new Bundle(); bundle.putString("currentUserObjectId", user.getObjectId());//原来是注释掉的 attention_fragment.setArguments(bundle); transaction .addToBackStack(null) //将当前fragment加入到返回栈中 .add(R.id.personal_replace,attention_fragment) .show(attention_fragment) .commit(); } //跳转到编辑页面 public void jump_to_edit(){ FragmentTransaction transaction = getFragmentManager().beginTransaction(); //String textItem = ((TextView) view).getText().toString(); Edit_fragment edit_fragment = new Edit_fragment(); Bundle bundle = new Bundle(); bundle.putString("currentUserObjectId", user.getObjectId());//原来是注释掉的 edit_fragment.setArguments(bundle); transaction .addToBackStack(null) //将当前fragment加入到返回栈中 .add(R.id.personal_replace,edit_fragment) .show(edit_fragment) .commit(); } //跳转到收藏页面 public void jump_to_collection(){ FragmentTransaction transaction = getFragmentManager().beginTransaction(); //String textItem = ((TextView) view).getText().toString(); Collection_Fragment collection_fragment = new Collection_Fragment(); Bundle bundle = new Bundle(); bundle.putString("currentUserObjectId", user.getObjectId());//原来是注释掉的 collection_fragment.setArguments(bundle); transaction .addToBackStack(null) //将当前fragment加入到返回栈中 .add(R.id.personal_replace,collection_fragment) .show(collection_fragment) .commit(); } }
35.498542
132
0.608574
431b93619080118dbe3ab565eb66d4a58f0c1a8f
1,825
package com.rewayaat.config; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.rewayaat.controllers.rest.TermsController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; /** * Verifies Google token ID's. */ public class GoogleTokenVerifier { private static final Logger LOGGER = LoggerFactory.getLogger(GoogleTokenVerifier.class); public static final String CLIENTID = "776365081062-5fc66doo0k5jpg4nfnimkag81e02sb81.apps.googleusercontent.com"; public String authenticate(String idTokenString) throws Exception { // Set up the HTTP transport and JSON factory HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) .setAudience(Collections.singletonList(CLIENTID)) .build(); // (Receive idTokenString by HTTPS POST) GoogleIdToken idToken = verifier.verify(idTokenString); if (idToken != null) { GoogleIdToken.Payload payload = idToken.getPayload(); // Print user identifier String userId = payload.getSubject(); LOGGER.info("User ID: " + userId); // Get profile information from payload String email = payload.getEmail(); return email; } else { throw new Exception("Could not authenticate this tokenid!"); } } }
40.555556
117
0.712329
1f55a10301c2710bcebc9789b77d72d50914935a
2,109
package org.jakartaeeprojects.coffee.drinks.boundary; import org.jakartaeeprojects.coffee.drinks.entity.Coffee; import org.jakartaeeprojects.coffee.drinks.entity.CoffeeDto; import javax.ejb.Stateless; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; @Stateless public class CoffeeService { static final List<Coffee> coffeeList = new ArrayList<>(); //Mimic a DB repo here for brevity sake static { coffeeList.add(Coffee.create("Flat White", 3.89)); coffeeList.add(Coffee.create("Mocha", 4.19)); coffeeList.add(Coffee.create("Cappuccino", 4.19)); coffeeList.add(Coffee.create("Espresso", 2.35)); coffeeList.add(Coffee.create("Double Espresso", 3.39)); coffeeList.add(Coffee.create("Short Macchiato", 3.89)); coffeeList.add(Coffee.create("Long Macchiato", 4.39)); coffeeList.add(Coffee.create("Caffe Latte", 3.10)); } public List<CoffeeDto> getAvailableCoffees() { return coffeeList.stream() .filter(Coffee::isInStock) .map(CoffeeDto::new) .collect(toList()); } public List<CoffeeDto> getAvailableCoffeesNotSoGoodApproach() { //DONT USE THIS return coffeeList.stream() .filter(c -> c.getStatus() == Coffee.Status.IN_STOCK) .map(c -> { CoffeeDto dto = new CoffeeDto(); dto.setType(c.getType()); dto.setBasePrice(c.getPrice()); // more work todo return dto; }) .collect(toList()); } public List<CoffeeDto> getAllCoffees() { return coffeeList.stream() .map(CoffeeDto::new) .collect(toList()); } public Optional<CoffeeDto> getCoffeeByType(final String type) { return coffeeList.stream() .filter(coffee -> coffee.getType().equalsIgnoreCase(type)) .map(CoffeeDto::new) .findAny(); } }
32.953125
74
0.596965
7b14e2903f4142a56b06830fd15daa1e5680d5e0
692
package com.ctrip.ferriswheel.quarks.syntax.lr; import com.ctrip.ferriswheel.quarks.exception.QuarksLexicalException; import com.ctrip.ferriswheel.quarks.exception.QuarksSyntaxException; import java.io.IOException; public class TestLR1ParsingTableConstructor { public static void main(String[] args) throws QuarksLexicalException, QuarksSyntaxException, IOException { String bnf = "quarks.bnf"; LR1ParsingTableConstructor constructor = new LR1ParsingTableConstructor(); ParsingTable table = constructor.construct(Thread.currentThread() .getContextClassLoader().getResourceAsStream(bnf)); System.out.println(table); } }
34.6
82
0.75289
f37a83a1c15a55a795e0c120efeca06b8e670799
870
package com.cognizant.bakingo.service; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.stereotype.Service; import com.cognizant.bakingo.bean.Cake; @Service public class CakeService { public static Map<Integer, Cake> orderList = new HashMap<>(); public static Map<String, Integer> flavorList = new LinkedHashMap<>(); static int orderId = 1000; // Constructor to populate flavorList public CakeService() { flavorList.put("None($0)", 0); flavorList.put("Custard($5)", 5); flavorList.put("Raspberry($10)", 10); flavorList.put("Pineapple($5)", 5); flavorList.put("Cherry($6)", 6); flavorList.put("Apricot($8)", 8); flavorList.put("Buttercream($7)", 7); flavorList.put("Chocolate($10)", 8); } public Integer addOrder(Cake cake) { orderList.put(++orderId, cake); return orderId; } }
24.857143
71
0.710345
f15faf46e58d4f4b37a43036eb9db2ff90e29d36
1,842
package com.paragon_software.dictionary_manager; import android.content.Context; import androidx.annotation.NonNull; import com.paragon_software.license_manager_api.LicenseFeature; import com.paragon_software.license_manager_api.LicenseManager; import com.paragon_software.trial_manager.TrialManagerAPI; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; class LicensePurchaseInfoGetter implements TrialManagerAPI.PurchaseInfoGetter { private static final long TIMEOUT = 5L * 60L * 1000L; @NonNull private final LicenseManager mLicenseManager; @NonNull private final LicenseManagerListener mLicenseManagerListener = new LicenseManagerListener(); private boolean needToWait = true; LicensePurchaseInfoGetter(@NonNull LicenseManager licenseManager) { mLicenseManager = licenseManager; } @Override public boolean isPurchased(Context context, @NonNull FeatureName featureName) { if (needToWait) { mLicenseManager.registerNotifier(mLicenseManagerListener); mLicenseManager.update(context); mLicenseManagerListener.await(TIMEOUT); mLicenseManager.unregisterNotifier(mLicenseManagerListener); needToWait = false; } return LicenseFeature.FEATURE_STATE.ENABLED.equals(mLicenseManager.checkFeature(featureName)); } private static class LicenseManagerListener implements LicenseManager.Notifier { @NonNull private final CountDownLatch latch = new CountDownLatch(1); @Override public void onChange() { latch.countDown(); } void await(long millis) { try { latch.await(millis, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { } } } }
32.315789
102
0.718241
5beb34a7b9fbb9aca354f5650dc73bf462e741ab
8,661
package com.yoloz.sample.jdbc; import java.sql.*; import java.util.Random; /** * Class.forName("oracle.jdbc.driver.OracleDriver") */ public class OracleTest { public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException { // Class.forName("oracle.jdbc.driver.OracleDriver"); // OracleTest oracleTest = new OracleTest(); // oracleTest.getUpdateCount(); // oracleTest.createTable(); // oracleTest.test(); String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; try (Connection conn = DriverManager.getConnection(url, "test", "test")) { Util.getCatalogs(conn); Util.getSchemas(conn); Util.getTables(conn, null, "TEST", "%", null); Util.getColumns(conn,null,"TEST","STU_SCORE_LOG","%"); } } public void test() { String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; String sql = "select * from pub_w3c_01"; sql = "alter table test_abc disable constraint SYS_C0011094"; try (Connection conn = DriverManager.getConnection(url, "test", "test"); Statement stmt = conn.createStatement()) { System.out.println(stmt.execute(sql)); // ResultSet resultSet = stmt.executeQuery(sql); // ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); // int colCount = resultSetMetaData.getColumnCount(); // int total =0; // while (resultSet.next()) { // StringBuilder line = new StringBuilder(); // for (int i = 1; i <= colCount; i++) { // line.append(resultSet.getObject(i)).append(','); // } // System.out.println(line.substring(0, line.length() - 1)); // total++; // } // System.out.println("=========="+total+"============"); // resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } public void createTable() { String sql = "CREATE TABLE TEST.PERSON (\n" + "SFZH VARCHAR2(100) NOT NULL,\n" + "BIRTH DATE NOT NULL,\n" + "AGE INTEGER NOT NULL,\n" + "IP VARCHAR2(100) NOT NULL,\n" + "POST INTEGER NOT NULL,\n" + "PRIMARY KEY (SFZH)\n" + ")"; String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; try (Connection conn = DriverManager.getConnection(url, "test", "test"); PreparedStatement stmt = conn.prepareStatement(sql)) { System.out.println(stmt.executeUpdate()); } catch (SQLException e) { e.printStackTrace(); } } //getResultSet可以多次取且每次取得都是最新的,一次返回多resultSet可以使用getMoreResults移动 public void getResultSet() { String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; try (Connection conn = DriverManager.getConnection(url, "test", "test"); Statement stmt = conn.createStatement()) { System.out.println(stmt.execute("select * from zyltest")); System.out.println(stmt.getResultSet()); System.out.println(stmt.getResultSet()); while (stmt.getResultSet().next()) { System.out.println(stmt.getResultSet().getObject(1)); } System.out.println(stmt.execute("select * from zyltest")); System.out.println(stmt.getResultSet()); System.out.println(stmt.getResultSet()); while (stmt.getResultSet().next()) { System.out.println(stmt.getResultSet().getObject(1)); } System.out.println(stmt.getMoreResults()); System.out.println(stmt.getResultSet()); while (stmt.getResultSet().next()) { //java.sql.SQLException: ORA-01001: invalid cursor System.out.println(stmt.getResultSet().getObject(1)); } } catch (SQLException throwables) { throwables.printStackTrace(); } } //getUpdateCount只可取一次,getLargeUpdateCount也可以取出来且也只有一次 public void getUpdateCount() { String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; try (Connection conn = DriverManager.getConnection(url, "test", "test"); PreparedStatement stmt = conn.prepareStatement("INSERT INTO zyltest(id,birth,age,ip,post) VALUES (?,?,?,?,?)")) { Random random = new Random(); stmt.setInt(1, 1); stmt.setDate(2, new Date(System.currentTimeMillis())); stmt.setInt(3, random.nextInt(80)); stmt.setString(4, "172.17.23." + random.nextInt(254)); stmt.setInt(5, 310004); stmt.execute(); System.out.println(stmt.getLargeUpdateCount()); System.out.println(stmt.getUpdateCount()); System.out.println(stmt.getUpdateCount()); } catch (SQLException e) { e.printStackTrace(); } } public void insertBatchSql() { String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; try (Connection conn = DriverManager.getConnection(url, "test", "test"); PreparedStatement stmt = conn.prepareStatement("INSERT INTO zyltest(id,birth,age,ip,post) VALUES (?,?,?,?,?)")) { Random random = new Random(); for (int j = 0; j < 30; j++) { for (int i = 0; i < 100; i++) { int id = (j * 100) + (i + 1); stmt.setInt(1, id); stmt.setDate(2, new Date(System.currentTimeMillis())); stmt.setInt(3, random.nextInt(80)); stmt.setString(4, "172.17.23." + random.nextInt(254)); stmt.setInt(5, 310004); stmt.addBatch(); } stmt.executeBatch(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 普通查询数据一次返回10条,可在下面循环中加断点并wireshark验证 */ public void simpleQuery() { String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; String sql = "select * from zyltest"; try (Connection conn = DriverManager.getConnection(url, "test", "test"); Statement stmt = conn.createStatement()) { ResultSet resultSet = stmt.executeQuery(sql); for (int i = 0; i < 30; i++) { if (resultSet.next()) { System.out.println(resultSet.getInt(1)); } } if ("oracle.jdbc.driver.ForwardOnlyResultSet".equals(resultSet.getClass().getName())) { System.out.println(resultSet.getFetchSize()); // Field maxRows = resultSet.getClass().getDeclaredField("maxRows"); // maxRows.setAccessible(true); // System.out.println("maxRows:" + maxRows.get(resultSet)); // Field fetchedRowCount = resultSet.getClass().getField("fetchedRowCount"); // fetchedRowCount.setAccessible(true); // System.out.println("fetchedRowCount:" + fetchedRowCount.get(resultSet)); } resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * 每次拉取指定size大小 */ public void cursorQuery() { String url = "jdbc:oracle:thin:@192.168.1.131:1521/XEPDB1"; String sql = "select * from zyltest"; try (Connection conn = DriverManager.getConnection(url, "test", "test"); Statement stmt = conn.createStatement()) { stmt.setFetchSize(1); ResultSet resultSet = stmt.executeQuery(sql); for (int i = 0; i < 3; i++) { if (resultSet.next()) { System.out.println(resultSet.getInt(1)); } } if ("oracle.jdbc.driver.ForwardOnlyResultSet".equals(resultSet.getClass().getName())) { System.out.println(resultSet.getFetchSize()); // Field maxRows = resultSet.getClass().getDeclaredField("maxRows"); // maxRows.setAccessible(true); // System.out.println("maxRows:" + maxRows.get(resultSet)); // Field fetchedRowCount = resultSet.getClass().getDeclaredField("fetchedRowCount"); // fetchedRowCount.setAccessible(true); // System.out.println("fetchedRowCount:" + fetchedRowCount.get(resultSet)); } resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } }
43.522613
126
0.552592
df4865ec33fda844d2d09ac92456e7ca8184e21d
1,799
package com.mbafour.mba.service.book; import com.mbafour.mba.domain.entity.AuctionEntity; import com.mbafour.mba.domain.entity.BookEntity; import com.mbafour.mba.domain.repository.BookRepository; import com.mbafour.mba.dto.book.BookRequest; import com.mbafour.mba.service.member.MemberStatusService; import com.mbafour.mba.service.auction.AuctionRegisterService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; @Service @AllArgsConstructor public class BookRegisterService { private final BookRepository bookRepository; private final MemberStatusService memberStatusService; private final AuctionRegisterService auctionRegisterService; public BookEntity addBook(HttpServletRequest request, BookRequest bookRequest){ AuctionEntity auctionEntity = auctionRegisterService.addAuction(bookRequest.getRowPrice(), memberStatusService.getStatus(request)); BookEntity bookEntity = BookEntity.builder() .title(bookRequest.getTitle()) .author(bookRequest.getAuthor()) .publisher(bookRequest.getPublisher()) .status(bookRequest.getStatus()) .lectureName(bookRequest.getLectureName()) .professorName(bookRequest.getProfessorName()) .increasePrice(bookRequest.getIncreasePrice()) .rowPrice(bookRequest.getRowPrice()) .startDay(bookRequest.getStartDay()) .endDay(bookRequest.getEndDay()) .thumbnail(bookRequest.getThumbnail()) .auctionEntity(auctionEntity) .seller(memberStatusService.getStatus(request)) .build(); return bookRepository.save(bookEntity); } }
39.977778
139
0.717065
879adfff3395505fec0690b6a256ce26493e5c42
4,797
package cn.ulyer.baseserver.api; import cn.hutool.core.util.StrUtil; import cn.ulyer.baseapi.entity.BaseApp; import cn.ulyer.baseapi.entity.BaseAppResource; import cn.ulyer.baseapi.vo.AuthorityVo; import cn.ulyer.baseserver.service.BaseAppResourceService; import cn.ulyer.baseserver.service.BaseAppService; import cn.ulyer.baseserver.service.BaseResourceService; import cn.ulyer.common.constants.SystemConstants; import cn.ulyer.common.utils.PageResult; import cn.ulyer.common.utils.R; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Date; import java.util.List; import java.util.Objects; /** * <p> * 前端控制器 * </p> * * @author mybatis-plus generator * @since 2021-04-15 */ @RestController @RequestMapping("/baseApp") public class BaseAppController{ @Autowired private BaseAppService baseAppService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private BaseResourceService baseResourceService; @Autowired private BaseAppResourceService baseAppResourceService; @GetMapping("/list") public R<List<BaseApp>> list(@RequestParam(value = SystemConstants.PAGE_NAME) Integer page, @RequestParam(value = SystemConstants.SIZE_PARAM) Integer pageSize, BaseApp app) { LambdaQueryWrapper<BaseApp> wrapper = Wrappers.lambdaQuery(); if (app != null) { wrapper.eq(StrUtil.isNotBlank(app.getAppName()), BaseApp::getAppName, app.getAppName()); wrapper.eq(Objects.nonNull(app.getAppId()), BaseApp::getAppId, app.getAppId()); } Page<BaseApp> pager = baseAppService.page(new Page<>(page, pageSize), wrapper); return R.success().setData(new PageResult<>(pager)); } @PostMapping("/createApp") public R createApp(@RequestBody @Valid BaseApp baseApp) { baseApp.setAppId(null); if (StrUtil.isNotBlank(baseApp.getJsonInformation())) { try { JSONObject.parseObject(baseApp.getJsonInformation()); } catch (Exception e) { throw new IllegalArgumentException("json信息格式不对"); } } baseApp.setAppSecret(passwordEncoder.encode(baseApp.getAppSecret())); baseAppService.save(baseApp); return R.success(); } @PostMapping("/update") public R update(@RequestBody @Valid BaseApp baseApp) { baseApp.setAppSecret(null); if (StrUtil.isNotBlank(baseApp.getJsonInformation())) { try { JSONObject.parseObject(baseApp.getJsonInformation()); } catch (Exception e) { throw new IllegalArgumentException("json信息格式不对"); } } baseAppService.updateById(baseApp); return R.success(); } @GetMapping("/listAppAuthorities") public R<List<AuthorityVo>> appAuthorities(@RequestParam Long appId) { return R.success().setData(baseResourceService.listAuthorityVoByAppId(appId)); } @PostMapping("/addAppAuthorities") public R addAppAuthorities(@RequestParam Long appId, @RequestParam List<Long> authorities) { BaseAppResource appResource = new BaseAppResource(); appResource.setAppId(appId); authorities.forEach(authority -> { appResource.setId(null); appResource.setResourceId(authority); baseAppResourceService.remove(Wrappers.<BaseAppResource>lambdaUpdate().eq(BaseAppResource::getAppId, appId).eq(BaseAppResource::getResourceId, authority)); baseAppResourceService.save(appResource); }); return R.success(); } @PostMapping("/updateAppAuthority") public R updateAppAuthorities(@RequestParam(required = false) @DateTimeFormat(pattern = "YYYY-MM-dd HH:mm:ss") Date expireTime, @RequestParam Long relationId) { BaseAppResource appResource = new BaseAppResource(); appResource.setId(relationId); appResource.setExpireTime(expireTime); baseAppResourceService.updateById(appResource); return R.success(); } @PostMapping("/removeAppAuthorities") public R removeAppAuthorities(@RequestParam List<Long> relationIds) { baseAppResourceService.removeByIds(relationIds); return R.success(); } }
35.533333
167
0.69335
18bdbfc9b36d09c0550d2e0f3b28a021c90aff56
668
package com.dreamworker; /** * 263 Ugly Number */ public class LeetCode263 { public static void main(String[] args) { LeetCode263 solution = new LeetCode263(); solution.isUgly(7); } public boolean isUgly(int num) { if (num == 0) { return false; } if (num == 1) { return true; } if (num % 2 != 0 && num % 3 != 0 && num % 5 != 0) { return false; } else if (num % 2 == 0) { return isUgly(num / 2); } else if (num % 3 == 0) { return isUgly(num / 3); } else { return isUgly(num / 5); } } }
20.242424
59
0.44012
45bb9f58843f8fc2a18adfb11c29611793517585
857
package info.shibafu528.blurhash; import org.jetbrains.annotations.NotNull; /*package*/ class Base83 { private static final String CHARCTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"; public static int decode(@NotNull String str) { int val = 0; int length = str.length(); for (int i = 0; i < length; ++i) { char c = str.charAt(i); if (Character.isHighSurrogate(c)) { throw new IllegalArgumentException("Invalid input. index = " + i + ", char = " + c); } int index = CHARCTERS.indexOf(c); if (index == -1) { throw new IllegalArgumentException("Invalid input. index = " + i + ", char = " + c); } val = val * 83 + index; } return val; } }
29.551724
130
0.541424
4beaf1d410a10a1cb93e1c2c8a40ab523e63c824
809
package com.jaquadro.minecraft.storagedrawers.integration; import com.jaquadro.minecraft.storagedrawers.integration.minetweaker.Compaction; import com.jaquadro.minecraft.storagedrawers.integration.minetweaker.OreDictionaryBlacklist; import com.jaquadro.minecraft.storagedrawers.integration.minetweaker.OreDictionaryWhitelist; import minetweaker.MineTweakerAPI; public class MineTweaker extends IntegrationModule { @Override public String getModID () { return "MineTweaker3"; } @Override public void init () throws Throwable { MineTweakerAPI.registerClass(OreDictionaryBlacklist.class); MineTweakerAPI.registerClass(OreDictionaryWhitelist.class); MineTweakerAPI.registerClass(Compaction.class); } @Override public void postInit () { } }
29.962963
92
0.776267
2fec33703da788d950baba809c23e2dcf03614eb
3,428
package org.benf.cfr.reader.bytecode.analysis.parse.utils.finalhelp; import org.benf.cfr.reader.bytecode.analysis.loc.BytecodeLoc; import org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement; import org.benf.cfr.reader.bytecode.analysis.parse.expression.LValueExpression; import org.benf.cfr.reader.bytecode.analysis.parse.statement.CatchStatement; import org.benf.cfr.reader.bytecode.analysis.parse.statement.Nop; import org.benf.cfr.reader.bytecode.analysis.parse.statement.ThrowStatement; import org.benf.cfr.reader.bytecode.analysis.parse.utils.BlockIdentifier; import org.benf.cfr.reader.util.collections.ListFactory; import org.benf.cfr.reader.util.collections.SetFactory; import java.util.LinkedList; import java.util.List; import java.util.Set; public class FinallyCatchBody { private final Op03SimpleStatement throwOp; private final boolean isEmpty; private final Op03SimpleStatement catchCodeStart; private final List<Op03SimpleStatement> body; private final Set<Op03SimpleStatement> bodySet; private FinallyCatchBody(Op03SimpleStatement throwOp, boolean isEmpty, Op03SimpleStatement catchCodeStart, List<Op03SimpleStatement> body) { this.throwOp = throwOp; this.isEmpty = isEmpty; this.catchCodeStart = catchCodeStart; this.body = body; this.bodySet = SetFactory.newOrderedSet(body); } public static FinallyCatchBody build(Op03SimpleStatement catchStart, List<Op03SimpleStatement> allStatements) { List<Op03SimpleStatement> targets = catchStart.getTargets(); if (targets.size() != 1) { return null; } if (!(catchStart.getStatement() instanceof CatchStatement)) return null; CatchStatement catchStatement = (CatchStatement) catchStart.getStatement(); final BlockIdentifier catchBlockIdentifier = catchStatement.getCatchBlockIdent(); final LinkedList<Op03SimpleStatement> catchBody = ListFactory.newLinkedList(); /* * Could do a graph search and a sort..... */ for (int idx = allStatements.indexOf(catchStart) + 1, len = allStatements.size(); idx < len; ++idx) { Op03SimpleStatement stm = allStatements.get(idx); boolean isNop = stm.getStatement() instanceof Nop; boolean contained = stm.getBlockIdentifiers().contains(catchBlockIdentifier); if (!(isNop || contained)) break; if (contained) catchBody.add(stm); } if (catchBody.isEmpty()) { return new FinallyCatchBody(null, true, null, catchBody); } ThrowStatement testThrow = new ThrowStatement(BytecodeLoc.TODO, new LValueExpression(catchStatement.getCreatedLValue())); Op03SimpleStatement throwOp = null; if (testThrow.equals(catchBody.getLast().getStatement())) { throwOp = catchBody.removeLast(); } return new FinallyCatchBody(throwOp, false, targets.get(0), catchBody); } public boolean isEmpty() { return isEmpty; } public int getSize() { return body.size(); } Op03SimpleStatement getCatchCodeStart() { return catchCodeStart; } Op03SimpleStatement getThrowOp() { return throwOp; } boolean hasThrowOp() { return throwOp != null; } public boolean contains(Op03SimpleStatement stm) { return bodySet.contains(stm); } }
39.402299
144
0.704492
453c555a733374b20b735984fa191bf1d218cf0e
691
package cn.cyejing.dam.common.expression.ast; import cn.cyejing.dam.common.expression.EvaluationContext; public class OpForwardNode extends Node { private String address; public OpForwardNode(String address, Node... operands) { super(operands); this.address = address; } @Override public Object evaluate(EvaluationContext evaluationContext) { Object res = getChild(0).evaluate(evaluationContext); if (res instanceof Boolean && (Boolean) res) { return address; } return null; } @Override public String toStringAST() { return getChild(0).toStringAST() + " => " + address + ";"; } }
23.827586
66
0.6411
26dbd114905847ab6afb0aacf9c15783c47dc12e
261
package de.psandro.nickify.api.model.exception; import de.psandro.nickify.api.exception.NickifyException; public final class ConfigurationException extends NickifyException { public ConfigurationException(String message) { super(message); } }
26.1
68
0.781609
9aac2840b9503fccdc79dd5df0a1ca8659c4c49d
2,079
package io.yokota.json.diff; import org.everit.json.schema.CombinedSchema; import org.everit.json.schema.Schema; import java.util.Iterator; import static io.yokota.json.diff.Difference.Type.COMPOSITION_METHOD_CHANGED; import static io.yokota.json.diff.Difference.Type.PRODUCT_TYPE_EXTENDED; import static io.yokota.json.diff.Difference.Type.PRODUCT_TYPE_NARROWED; import static io.yokota.json.diff.Difference.Type.SUM_TYPE_EXTENDED; import static io.yokota.json.diff.Difference.Type.SUM_TYPE_NARROWED; class CombinedSchemaDiff { static void compare(final Context ctx, final CombinedSchema original, final CombinedSchema update) { if (!original.getCriterion().equals(update.getCriterion())) { ctx.addDifference(COMPOSITION_METHOD_CHANGED); } else { int originalSize = original.getSubschemas().size(); int updateSize = update.getSubschemas().size(); if (originalSize < updateSize) { if (original.getCriterion() == CombinedSchema.ALL_CRITERION) { ctx.addDifference(PRODUCT_TYPE_EXTENDED); } else { ctx.addDifference(SUM_TYPE_EXTENDED); } } else if (originalSize > updateSize) { if (original.getCriterion() == CombinedSchema.ALL_CRITERION) { ctx.addDifference(PRODUCT_TYPE_NARROWED); } else { ctx.addDifference(SUM_TYPE_NARROWED); } } final Iterator<Schema> originalIterator = original.getSubschemas().iterator(); final Iterator<Schema> updateIterator = update.getSubschemas().iterator(); int index = 0; while (originalIterator.hasNext() && index < Math.min(originalSize, updateSize)) { try (Context.PathScope pathScope = ctx.enterPath(original.getCriterion() + "/" + index)) { SchemaDiff.compare(ctx, originalIterator.next(), updateIterator.next()); } index++; } } } }
44.234043
106
0.636364
e47a7fa9d937e4978e311831e8ae143a28040bf2
780
package ccc.ccc2002; import java.util.Scanner; public class J2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); for (String s = sc.nextLine(); !s.equals("quit!"); s = sc.nextLine()) { if (s.length() > 4 && s.endsWith("or") && !isVowel(s.charAt(s.length() - 3))) { s = s.substring(0, s.length() - 2) + "our"; } System.out.println(s); } } private static boolean isVowel(char c) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': return true; default: return false; } } }
26
92
0.423077
4fb97af7ecc173b7a6eee4660fd7ddae29fc6987
833
package com.frontbackend.java.io.list; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class ListFilesUsingVisitor { public static void main(String[] args) throws IOException { Files.walkFileTree(Paths.get("/tmp"), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (!Files.isDirectory(file)) { System.out.println(file.getFileName() .toString()); } return FileVisitResult.CONTINUE; } }); } }
32.038462
84
0.626651
54764d23709182b3de33e1129e914ff9b47bf53e
6,786
/******************************************************************************* * Copyright (c) 1999-2005 The Institute for Genomic Research (TIGR). * Copyright (c) 2005-2008, the Dana-Farber Cancer Institute (DFCI), * J. Craig Venter Institute (JCVI) and the University of Washington. * All rights reserved. *******************************************************************************/ /* * EaseThresholdPanel.java * * Created on August 20, 2004, 2:40 PM */ package org.tigr.microarray.mev.cluster.gui.impl.goseq.gotree; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import org.tigr.microarray.mev.cluster.gui.impl.dialogs.AlgorithmDialog; import org.tigr.microarray.mev.cluster.gui.impl.dialogs.DialogListener; import org.tigr.microarray.mev.cluster.gui.impl.dialogs.ParameterPanel; import org.tigr.microarray.mev.cluster.gui.impl.dialogs.dialogHelpUtil.HelpWindow; /** * * @author braisted */ public class EaseThresholdDialog extends AlgorithmDialog { private int result = JOptionPane.CANCEL_OPTION; private double origTOne, origTTwo; private JTextField tOneField; private JTextField tTwoField; /** Creates a new instance of EaseThresholdPanel */ public EaseThresholdDialog(JFrame parent, double T1, double T2) { super(parent, "EASE Tree Thresholds", true); origTOne = T1; origTTwo = T2; ParameterPanel params = new ParameterPanel("Threshold Selection"); params.setLayout(new GridBagLayout()); JLabel label = new JLabel("Lower Threshold"); tOneField = new JTextField("0.01", 8); params.add(label, new GridBagConstraints(0,0,1,1,0.0,0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10,0,0,15), 0, 0)); params.add(tOneField, new GridBagConstraints(1,0,1,1,0.0,0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(10,0,0,0), 0, 0)); label = new JLabel("Upper Threshold"); tTwoField = new JTextField("0.05", 8); params.add(label, new GridBagConstraints(0,1,1,1,0.0,0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(15,0,10,15), 0, 0)); params.add(tTwoField, new GridBagConstraints(1,1,1,1,0.0,0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(15,0,10,0), 0, 0)); addContent(params); setActionListeners(new EventListener()); pack(); } public double getLowerThreshold() { return Double.parseDouble(tOneField.getText()); } public double getUpperThreshold() { return Double.parseDouble(tTwoField.getText()); } /** Shows the dialog. * @return */ public int showModal() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screenSize.width - getSize().width)/2, (screenSize.height - getSize().height)/2); show(); return result; } private void resetControls() { this.tOneField.setText(String.valueOf(this.origTOne)); this.tTwoField.setText(String.valueOf(this.origTTwo)); this.tOneField.grabFocus(); this.tOneField.selectAll(); } private boolean validate(String a, String b) { double t1, t2; try { t1 = Double.parseDouble(a); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, "Number format error, entered value is not recognized as a number", "Input Error", JOptionPane.ERROR_MESSAGE); this.tOneField.grabFocus(); this.tOneField.selectAll(); return false; } try { t2 = Double.parseDouble(b); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(this, "Number format error, entered value is not recognized as a number", "Input Error", JOptionPane.ERROR_MESSAGE); this.tTwoField.grabFocus(); this.tTwoField.selectAll(); return false; } if(t1 <= 0 || t1 >= 1.0) { JOptionPane.showMessageDialog(this, "Threshold should be > 0 and < 1.0", "Input Error", JOptionPane.ERROR_MESSAGE); this.tOneField.grabFocus(); this.tOneField.selectAll(); return false; } if(t2 <= 0 || t2 >= 1.0) { JOptionPane.showMessageDialog(this, "Threshold should be > 0 and < 1.0", "Input Error", JOptionPane.ERROR_MESSAGE); this.tTwoField.grabFocus(); this.tTwoField.selectAll(); return false; } if(t1 >= t2) { JOptionPane.showMessageDialog(this, "The lower threshold should be less that the upper threshold.", "Input Error", JOptionPane.ERROR_MESSAGE); this.tOneField.grabFocus(); this.tOneField.selectAll(); return false; } return true; } /** * The class to listen to the dialog and check boxes items events. */ private class EventListener extends DialogListener { public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("ok-command")) { if(validate(tOneField.getText(), tTwoField.getText())) { result = JOptionPane.OK_OPTION; dispose(); } } else if (command.equals("cancel-command")) { result = JOptionPane.CANCEL_OPTION; dispose(); } else if (command.equals("reset-command")){ resetControls(); result = JOptionPane.CANCEL_OPTION; return; } else if (command.equals("info-command")){ HelpWindow hw = new HelpWindow(EaseThresholdDialog.this, "EASE Threshold Dialog"); } } public void windowClosing(WindowEvent e) { result = JOptionPane.CLOSED_OPTION; dispose(); } } /* public static void main(String [] args) { EaseThresholdDialog dialog = new EaseThresholdDialog(); dialog.showModal(); } */ }
37.285714
159
0.582818
7fdf576f33ed1fb0a429fb158e01400388c630d7
2,215
// Copyright (c) 2020-2021 Yinsen (Tesla) Zhang. // Use of this source code is governed by the MIT license that can be found in the LICENSE.md file. package org.aya.core.serde; import kala.collection.immutable.ImmutableSeq; import kala.collection.mutable.MutableMap; import org.aya.core.sort.Sort; import org.aya.generic.Level; import org.aya.util.Constants; import org.jetbrains.annotations.NotNull; import java.io.Serializable; /** * @author ice1000 */ public sealed interface SerLevel extends Serializable { @NotNull Level<Sort.LvlVar> de(@NotNull MutableMap<Integer, Sort.LvlVar> cache); record Const(int num) implements SerLevel { @Override public @NotNull Level<Sort.LvlVar> de(@NotNull MutableMap<Integer, Sort.LvlVar> cache) { return new Level.Constant<>(num); } } record LvlVar(int id) implements Serializable { public @NotNull Sort.LvlVar de(@NotNull MutableMap<Integer, Sort.LvlVar> cache) { return cache.getOrPut(id, () -> new Sort.LvlVar(Constants.ANONYMOUS_PREFIX, null)); } } record Ref(@NotNull LvlVar var, int lift) implements SerLevel { @Override public @NotNull Level<Sort.LvlVar> de(@NotNull MutableMap<Integer, Sort.LvlVar> cache) { return new Level.Reference<>(var.de(cache), lift); } } record Max(@NotNull ImmutableSeq<SerLevel> levels) implements Serializable { public @NotNull Sort de(@NotNull MutableMap<Integer, Sort.LvlVar> cache) { return new Sort(levels.map(l -> l.de(cache))); } } static @NotNull Max ser(@NotNull Sort level, @NotNull MutableMap<Sort.LvlVar, Integer> cache) { return new Max(level.levels().map(l -> ser(l, cache))); } static @NotNull SerLevel ser(@NotNull Level<Sort.LvlVar> level, @NotNull MutableMap<Sort.LvlVar, Integer> cache) { return switch (level) { case Level.Constant<Sort.LvlVar> constant -> new Const(constant.value()); case Level.Reference<Sort.LvlVar> ref -> new Ref(ser(ref.ref(), cache), ref.lift()); default -> throw new IllegalStateException(level.toString()); }; } static LvlVar ser(Sort.@NotNull LvlVar ref, @NotNull MutableMap<Sort.LvlVar, Integer> cache) { return new LvlVar(cache.getOrPut(ref, cache::size)); } }
36.916667
116
0.71377
172340729aacd5bf5b538977276a9f7bd978a8b7
2,826
package com.madlab.floatingactionbutton; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton; import com.google.android.material.floatingactionbutton.FloatingActionButton; public class MainActivity extends AppCompatActivity { FloatingActionButton add_alarm_fab,add_person_fab; ExtendedFloatingActionButton add_fab; TextView add_person_action_text,add_alarm_action_text; Boolean isAllFABVisible; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); add_alarm_fab = (FloatingActionButton) findViewById(R.id.add_alarm_fab); add_person_fab = (FloatingActionButton) findViewById(R.id.add_person_fab); add_fab = (ExtendedFloatingActionButton) findViewById(R.id.add_fab); add_person_action_text = (TextView) findViewById(R.id.add_person_action_text); add_alarm_action_text = (TextView) findViewById(R.id.add_alarm_action_text); add_alarm_fab.setVisibility(View.GONE); add_person_fab.setVisibility(View.GONE); add_person_action_text.setVisibility(View.GONE); add_alarm_action_text.setVisibility(View.GONE); isAllFABVisible = false; add_fab.shrink(); add_fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!isAllFABVisible){ add_alarm_fab.show(); add_person_fab.show(); add_person_action_text.setVisibility(View.VISIBLE); add_alarm_action_text.setVisibility(View.VISIBLE); add_fab.extend(); isAllFABVisible = true; }else { add_alarm_fab.hide(); add_person_fab.hide(); add_person_action_text.setVisibility(View.GONE); add_alarm_action_text.setVisibility(View.GONE); add_fab.shrink(); isAllFABVisible = false; } } }); add_person_fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"Person Added",Toast.LENGTH_SHORT).show(); } }); add_alarm_fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"Alarm Added",Toast.LENGTH_SHORT).show(); } }); } }
36.701299
91
0.650035
d1dcf1da68934fdf8eaa7b3bd38dbbe292b66d40
1,945
package seedu.tarence.testutil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.tarence.model.Application; import seedu.tarence.model.builder.TutorialBuilder; import seedu.tarence.model.tutorial.Tutorial; /** * A utility class containing a list of {@code Tutorial} objects to be used in tests. */ public class TypicalTutorials { public static final Tutorial CS1020_LAB01 = new TutorialBuilder().withModCode("CS1020") .withTutName("Lab 1").build(); public static final Tutorial CS2040_TUT02 = new TutorialBuilder().withModCode("CS2040") .withTutName("Tutorial 2").build(); public static final Tutorial CS1101S_LAB04 = new TutorialBuilder().withModCode("CS1101S") .withTutName("Lab 4").build(); public static final Tutorial CS1231_TUT10 = new TutorialBuilder().withModCode("CS1231") .withTutName("Tutorial 10").build(); public static final Tutorial CS2100_LAB02 = new TutorialBuilder().withModCode("CS2100") .withTutName("Lab 2").build(); public static final Tutorial CS2103_TUT14 = new TutorialBuilder().withModCode("CS2103") .withTutName("Tutorial 14").build(); public static final Tutorial CS3230_LAB03 = new TutorialBuilder().withModCode("CS3230") .withTutName("Lab 3").build(); private TypicalTutorials() {} // prevents instantiation /** * Returns an {@code Application} with all the typical tutorials. */ public static Application getTypicalApplication() { Application ta = new Application(); for (Tutorial tutorial : getTypicalTutorial()) { ta.addTutorial(tutorial); } return ta; } public static List<Tutorial> getTypicalTutorial() { return new ArrayList<>(Arrays.asList(CS1020_LAB01, CS1101S_LAB04, CS1231_TUT10, CS2040_TUT02, CS2100_LAB02, CS2103_TUT14, CS3230_LAB03)); } }
39.693878
101
0.693059
03579aae7a5127dfdf1d7f88b282f0192fad025b
3,671
package com.flurry.sdk; import com.flurry.sdk.C7554lc.C7555a; import java.net.SocketTimeoutException; /* renamed from: com.flurry.sdk.J */ class C7399J implements C7555a<byte[], String> { /* renamed from: a */ final /* synthetic */ C7423N f14510a; /* renamed from: b */ final /* synthetic */ C7440Q f14511b; /* renamed from: c */ final /* synthetic */ C7404K f14512c; C7399J(C7404K k, C7423N n, C7440Q q) { this.f14512c = k; this.f14510a = n; this.f14511b = q; } /* renamed from: a */ public final /* synthetic */ void mo23837a(C7554lc lcVar, Object obj) { boolean z; String str = (String) obj; C7423N n = this.f14510a; String str2 = n.f14563s; C7505da daVar = n.f14558n; String str3 = daVar.f14792h; C7552la laVar = daVar.f14789e; String b = C7404K.f14517k; StringBuilder sb = new StringBuilder("Pulse report to "); sb.append(str2); sb.append(" for "); sb.append(str3); sb.append(", HTTP status code is: "); sb.append(lcVar.f15017x); C7513ec.m16639a(3, b, sb.toString()); int i = lcVar.f15017x; C7440Q q = this.f14511b; int i2 = (int) lcVar.f15015v; if (i2 >= 0) { q.f14614l += (long) i2; } else if (q.f14614l <= 0) { q.f14614l = 0; } this.f14511b.f14608f = i; if (!lcVar.mo23989c()) { Exception exc = lcVar.f15016w; boolean z2 = true; if (exc == null || !(exc instanceof SocketTimeoutException)) { z = false; } else { z = true; } if (!lcVar.f14998B && !z) { z2 = false; } String str4 = ". Exception: "; if (z2) { if (lcVar.mo23990d()) { String b2 = C7404K.f14517k; StringBuilder sb2 = new StringBuilder("Timeout occurred when trying to connect to: "); sb2.append(str2); sb2.append(str4); sb2.append(lcVar.f15016w.getMessage()); C7513ec.m16639a(3, b2, sb2.toString()); } else { C7513ec.m16639a(3, C7404K.f14517k, "Manually managed http request timeout occurred for: ".concat(String.valueOf(str2))); } C7404K.m16382a(this.f14512c, this.f14511b, this.f14510a); } else { String b3 = C7404K.f14517k; StringBuilder sb3 = new StringBuilder("Error occurred when trying to connect to: "); sb3.append(str2); sb3.append(str4); sb3.append(exc.getMessage()); C7513ec.m16639a(3, b3, sb3.toString()); C7404K.m16384a(this.f14512c, this.f14511b, this.f14510a, str); } C7405a.m16393b(str2, str3, laVar); } else if (i >= 200 && i < 300) { C7404K.m16386b(this.f14512c, this.f14511b, this.f14510a); C7405a.m16392a(str2, str3, laVar); } else if (i < 300 || i >= 400) { String b4 = C7404K.f14517k; StringBuilder sb4 = new StringBuilder(); sb4.append(str3); sb4.append(" report failed sending to : "); sb4.append(str2); C7513ec.m16639a(3, b4, sb4.toString()); C7404K.m16384a(this.f14512c, this.f14511b, this.f14510a, str); C7405a.m16393b(str2, str3, laVar); } else { C7404K.m16383a(this.f14512c, this.f14511b, this.f14510a, lcVar); } } }
36.346535
140
0.518387
6f913cd2d56f7bd0ac1e19cf9444c6a6f0ab54e6
8,165
/* * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jserver.gsregistering; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.Map.Entry; import com.l2jserver.loginserver.GameServerTable; public class GameServerRegister extends BaseGameServerRegister { private LineNumberReader _in; public static void main(String[] args) { // Backwards compatibility, redirect to the new one BaseGameServerRegister.main(args); } /** * * @param bundle */ public GameServerRegister(ResourceBundle bundle) { super(bundle); this.load(); int size = GameServerTable.getInstance().getServerNames().size(); if (size == 0) { System.out.println(this.getBundle().getString("noServerNames")); System.exit(1); } } public void consoleUI() throws IOException { _in = new LineNumberReader(new InputStreamReader(System.in)); boolean choiceOk = false; String choice; while (true) { this.hr(); System.out.println("GSRegister"); System.out.println('\n'); System.out.println("1 - "+this.getBundle().getString("cmdMenuRegister")); System.out.println("2 - "+this.getBundle().getString("cmdMenuListNames")); System.out.println("3 - "+this.getBundle().getString("cmdMenuRemoveGS")); System.out.println("4 - "+this.getBundle().getString("cmdMenuRemoveAll")); System.out.println("5 - "+this.getBundle().getString("cmdMenuExit")); do { System.out.print(this.getBundle().getString("yourChoice")+' '); choice = _in.readLine(); try { int choiceNumber = Integer.parseInt(choice); choiceOk = true; switch (choiceNumber) { case 1: this.registerNewGS(); break; case 2: this.listGSNames(); break; case 3: this.unregisterSingleGS(); break; case 4: this.unregisterAllGS(); break; case 5: System.exit(0); break; default: System.out.printf(this.getBundle().getString("invalidChoice")+'\n', choice); choiceOk = false; } } catch (NumberFormatException nfe) { System.out.printf(this.getBundle().getString("invalidChoice")+'\n', choice); } } while (!choiceOk); } } /** * */ private void hr() { System.out.println("_____________________________________________________\n"); } /** * */ private void listGSNames() { int idMaxLen = 0; int nameMaxLen = 0; for (Entry<Integer, String> e : GameServerTable.getInstance().getServerNames().entrySet()) { if (e.getKey().toString().length() > idMaxLen) { idMaxLen = e.getKey().toString().length(); } if (e.getValue().length() > nameMaxLen) { nameMaxLen = e.getValue().length(); } } idMaxLen += 2; nameMaxLen += 2; String id; boolean inUse; String gsInUse = this.getBundle().getString("gsInUse"); String gsFree = this.getBundle().getString("gsFree"); int gsStatusMaxLen = Math.max(gsInUse.length(), gsFree.length()) + 2; for (Entry<Integer, String> e : GameServerTable.getInstance().getServerNames().entrySet()) { id = e.getKey().toString(); System.out.print(id); for (int i = id.length(); i < idMaxLen; i++) { System.out.print(' '); } System.out.print("| "); System.out.print(e.getValue()); for (int i = e.getValue().length(); i < nameMaxLen; i++) { System.out.print(' '); } System.out.print("| "); inUse = GameServerTable.getInstance().hasRegisteredGameServerOnId(e.getKey()); String inUseStr = (inUse ? gsInUse : gsFree); System.out.print(inUseStr); for (int i = inUseStr.length(); i < gsStatusMaxLen; i++) { System.out.print(' '); } System.out.println('|'); } } /** * @throws IOException * */ private void unregisterAllGS() throws IOException { if (this.yesNoQuestion(this.getBundle().getString("confirmRemoveAllText"))) { try { BaseGameServerRegister.unregisterAllGameServers(); System.out.println(this.getBundle().getString("unregisterAllOk")); } catch (SQLException e) { this.showError(this.getBundle().getString("sqlErrorUnregisterAll"), e); } } } private boolean yesNoQuestion(String question) throws IOException { do { this.hr(); System.out.println(question); System.out.println("1 - "+this.getBundle().getString("yes")); System.out.println("2 - "+this.getBundle().getString("no")); System.out.print(this.getBundle().getString("yourChoice")+' '); String choice; choice = _in.readLine(); if (choice.equals("1")) { return true; } else if (choice.equals("2")) { return false; } else { System.out.printf(this.getBundle().getString("invalidChoice")+'\n', choice); } } while (true); } /** * @throws IOException * */ private void unregisterSingleGS() throws IOException { String line; int id = Integer.MIN_VALUE; do { System.out.print(this.getBundle().getString("enterDesiredId")+' '); line = _in.readLine(); try { id = Integer.parseInt(line); } catch (NumberFormatException e) { System.out.printf(this.getBundle().getString("invalidChoice")+'\n', line); } } while (id == Integer.MIN_VALUE); String name = GameServerTable.getInstance().getServerNameById(id); if (name == null) { System.out.printf(this.getBundle().getString("noNameForId")+'\n', id); } else { if (GameServerTable.getInstance().hasRegisteredGameServerOnId(id)) { System.out.printf(this.getBundle().getString("confirmRemoveText")+'\n', id, name); try { BaseGameServerRegister.unregisterGameServer(id); System.out.printf(this.getBundle().getString("unregisterOk")+'\n', id); } catch (SQLException e) { this.showError(this.getBundle().getString("sqlErrorUnregister"), e); } } else { System.out.printf(this.getBundle().getString("noServerForId")+'\n', id); } } } private void registerNewGS() throws IOException { String line; int id = Integer.MIN_VALUE; do { System.out.println(this.getBundle().getString("enterDesiredId")); line = _in.readLine(); try { id = Integer.parseInt(line); } catch (NumberFormatException e) { System.out.printf(this.getBundle().getString("invalidChoice")+'\n', line); } } while (id == Integer.MIN_VALUE); String name = GameServerTable.getInstance().getServerNameById(id); if (name == null) { System.out.printf(this.getBundle().getString("noNameForId")+'\n', id); } else { if (GameServerTable.getInstance().hasRegisteredGameServerOnId(id)) { System.out.println(this.getBundle().getString("idIsNotFree")); } else { try { BaseGameServerRegister.registerGameServer(id, "."); } catch (IOException e) { this.showError(getBundle().getString("ioErrorRegister"), e); } } } } /** * @see com.l2jserver.gsregistering.BaseGameServerRegister#showError(java.lang.String, java.lang.Throwable) */ @Override public void showError(String msg, Throwable t) { String title; if (this.getBundle() != null) { title = this.getBundle().getString("error"); msg += '\n'+this.getBundle().getString("reason")+' '+t.getLocalizedMessage(); } else { title = "Error"; msg += "\nCause: "+t.getLocalizedMessage(); } System.out.println(title+": "+msg); } }
23.735465
108
0.642866
b030c9725696883632d050dce5831df140905d80
4,058
package com.hys.exam.struts.form; import com.hys.framework.web.form.BaseForm; /** * * 标题:考试支撑平台 * * 作者:tony 2010-2-3 * * 描述: * * 说明: */ public class OlemPaperForm extends BaseForm { private static final long serialVersionUID = -1251376418361496553L; private Long id; private String name; /** * 分类ID */ private Long typeId; /** * 试卷分类名称 */ private String typeName; /** * 试卷总分数 */ private Double paperScore; /** * 出卷方式 5:快捷策略 2:精细策略 3:手工组卷 4:卷中卷 */ private Integer paperMode; /** * 试题总数 */ private Integer questionNum; /** * 创建时间 */ private String createDate; /** * 难度 */ private Integer grade; /** * 是否多媒体 * 1 是 */ private Integer isnot_multimedia; /** * 状态 * 1 正常 * 2 禁用 * 3 已删除 */ private Integer state; /** * 有试卷有效期 */ private String usefulDate; /** * 安排方式 * 1:练习 * 2:考试 */ private Integer paperPlanType; /** * 答题时间 */ private Integer examinationTime; /** * 重考次数 */ private Integer redoNum; /** * 试卷导出:1:否 2:是 3: */ private Integer isNotExp; /** * 手工选择的试题 * 规则 1_2+2_3 试题id_每题分数+试题id_每题分数 */ private String seleQues; private String type_Ids; /** * 试卷个数 */ private Integer childPaperNum; private Integer tacticEditFlag; public String getType_Ids() { return type_Ids; } public void setType_Ids(String type_Ids) { this.type_Ids = type_Ids; } public Long getId() { return id; } public Integer getIsNotExp() { return isNotExp; } public Integer getChildPaperNum() { return childPaperNum; } public void setChildPaperNum(Integer childPaperNum) { this.childPaperNum = childPaperNum; } public void setIsNotExp(Integer isNotExp) { this.isNotExp = isNotExp; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getTypeId() { return typeId; } public void setTypeId(Long typeId) { this.typeId = typeId; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public Double getPaperScore() { return paperScore; } public void setPaperScore(Double paperScore) { this.paperScore = paperScore; } public Integer getPaperMode() { return paperMode; } public void setPaperMode(Integer paperMode) { this.paperMode = paperMode; } public Integer getQuestionNum() { return questionNum; } public void setQuestionNum(Integer questionNum) { this.questionNum = questionNum; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getUsefulDate() { return usefulDate; } public void setUsefulDate(String usefulDate) { this.usefulDate = usefulDate; } public Integer getPaperPlanType() { return paperPlanType; } public void setPaperPlanType(Integer paperPlanType) { this.paperPlanType = paperPlanType; } public Integer getExaminationTime() { return examinationTime; } public void setExaminationTime(Integer examinationTime) { this.examinationTime = examinationTime; } public Integer getRedoNum() { return redoNum; } public void setRedoNum(Integer redoNum) { this.redoNum = redoNum; } public String getSeleQues() { return seleQues; } public void setSeleQues(String seleQues) { this.seleQues = seleQues; } public Integer getIsnot_multimedia() { return isnot_multimedia; } public void setIsnot_multimedia(Integer isnot_multimedia) { this.isnot_multimedia = isnot_multimedia; } public Integer getTacticEditFlag() { return tacticEditFlag; } public void setTacticEditFlag(Integer tacticEditFlag) { this.tacticEditFlag = tacticEditFlag; } }
14.702899
68
0.679152
0ce4bcb19f23e221fed32255b23873088578163f
1,007
package catalinc.daydream.stars; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; public class DreamView extends SurfaceView implements SurfaceHolder.Callback { private RenderThread mRenderThread; public DreamView(Context context, AttributeSet attrs) { super(context, attrs); // Disable hardware acceleration so we can use BlurMaskFilter setLayerType(View.LAYER_TYPE_SOFTWARE, null); SurfaceHolder holder = getHolder(); holder.addCallback(this); mRenderThread = new RenderThread(context, holder); } @Override public void surfaceCreated(SurfaceHolder holder) { mRenderThread.go(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { mRenderThread.terminate(); } }
25.820513
89
0.71996
ed05251c637d37444575e7b5ad51242d5dbc5289
118
package io.emqx.extension.handler.codec; public interface HandlerReturn { public Object encode(ResultCode rc); }
14.75
40
0.779661
e38e1c81c7b302f30250f9407665038c9ccf11e0
516
package cn.org.rookie.mapper.entity; import cn.org.rookie.mapper.annotation.Primary; import cn.org.rookie.mapper.annotation.Table; @Table("admin_user") public class Test { @Primary private String id; private String username; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
16.645161
47
0.637597
8483ce0ec786313e5e931fd3fc5c1bf1afb8f70c
1,414
package ru.geekbrains.lesson2.apps; import ru.geekbrains.lesson2.database.SQLService; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; import java.util.Scanner; /** * Java Core. Professional level. Lesson 2 * * @author Zurbaevi Nika */ public class ClientApp { public ClientApp() { try { Socket socket = new Socket("localhost", 8081); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); new Thread(() -> { try { while (true) { String message = dataInputStream.readUTF(); System.out.println(message); } } catch (Exception e) { e.printStackTrace(); } }).start(); Scanner scanner = new Scanner(System.in); System.out.println("/reg (password, login), /auth (login, password)"); while (true) { try { dataOutputStream.writeUTF(scanner.nextLine()); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception exception) { exception.printStackTrace(); } } }
30.73913
95
0.533946
08d56527d95b66919f13b319b8699954ce1a7c0a
1,929
package com.algorithm.space.hancock.all.solution; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; public class SolutionOf0015 { public List<List<Integer>> threeSum(int[] nums) { List<Integer> sortedNums = Arrays.stream(nums).sorted().boxed().collect(Collectors.toList()); List<List<Integer>> result = new LinkedList<>(); for (int index = 0; index < sortedNums.size(); index++) { if (index > 0 && sortedNums.get(index).equals(sortedNums.get(index - 1))) { continue; } int pointerOne = index + 1; int pointerTwo = sortedNums.size() - 1; result.addAll(findThreeNumWithTwoPointers(sortedNums, index, pointerOne, pointerTwo)); } return result; } private List<List<Integer>> findThreeNumWithTwoPointers(List<Integer> sortedNums, int index, int pointerOne, int pointerTwo) { List<List<Integer>> result = new LinkedList<>(); while (pointerOne < pointerTwo) { if (pointerOne > index + 1 && sortedNums.get(pointerOne).equals(sortedNums.get(pointerOne - 1))) { pointerOne++; continue; } if (pointerTwo < sortedNums.size() - 1 && sortedNums.get(pointerTwo).equals(sortedNums.get(pointerTwo + 1))) { pointerTwo--; continue; } int sum = sortedNums.get(index) + sortedNums.get(pointerOne) + sortedNums.get(pointerTwo); if (sum > 0) { pointerTwo--; } else if (sum < 0) { pointerOne++; } else { result.add(Arrays.asList(sortedNums.get(index), sortedNums.get(pointerOne), sortedNums.get(pointerTwo))); pointerOne++; pointerTwo--; } } return result; } }
33.258621
130
0.572836
0dd1dcb201b5fa2b098d5dbe2894cc6058c8b8b8
808
package common.entity; import java.io.Serializable; import java.util.List; import javax.persistence.MappedSuperclass; import javax.xml.bind.annotation.XmlTransient; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Setter; /** * エンティティリストの基底クラス. */ @NoArgsConstructor @AllArgsConstructor @Setter @MappedSuperclass public abstract class BaseObjects<T extends Serializable> implements Serializable { /** エンティティリスト */ private List<T> objects; /** * 件数を取得する. * * @return 件数 */ public int getCount() { return objects.size(); } /** * エンティティリストを取得する. * * @return エンティティリスト */ @XmlTransient public List<T> getObjects() { return objects; } }
18.363636
84
0.633663
ea2a49318ebc0a0310f9a078f0151621f83eb050
21,169
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.fasterxml.jackson.databind.deser.impl; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.SettableAnyProperty; import com.fasterxml.jackson.databind.deser.SettableBeanProperty; import java.io.IOException; import java.util.BitSet; // Referenced classes of package com.fasterxml.jackson.databind.deser.impl: // ObjectIdReader, ReadableObjectId, PropertyValue public class PropertyValueBuffer { public PropertyValueBuffer(JsonParser jsonparser, DeserializationContext deserializationcontext, int i, ObjectIdReader objectidreader) { // 0 0:aload_0 // 1 1:invokespecial #26 <Method void Object()> _parser = jsonparser; // 2 4:aload_0 // 3 5:aload_1 // 4 6:putfield #28 <Field JsonParser _parser> _context = deserializationcontext; // 5 9:aload_0 // 6 10:aload_2 // 7 11:putfield #30 <Field DeserializationContext _context> _paramsNeeded = i; // 8 14:aload_0 // 9 15:iload_3 // 10 16:putfield #32 <Field int _paramsNeeded> _objectIdReader = objectidreader; // 11 19:aload_0 // 12 20:aload 4 // 13 22:putfield #34 <Field ObjectIdReader _objectIdReader> _creatorParameters = new Object[i]; // 14 25:aload_0 // 15 26:iload_3 // 16 27:anewarray Object[] // 17 30:putfield #36 <Field Object[] _creatorParameters> if(i < 32) //* 18 33:iload_3 //* 19 34:bipush 32 //* 20 36:icmpge 45 { _paramsSeenBig = null; // 21 39:aload_0 // 22 40:aconst_null // 23 41:putfield #38 <Field BitSet _paramsSeenBig> return; // 24 44:return } else { _paramsSeenBig = new BitSet(); // 25 45:aload_0 // 26 46:new #40 <Class BitSet> // 27 49:dup // 28 50:invokespecial #41 <Method void BitSet()> // 29 53:putfield #38 <Field BitSet _paramsSeenBig> return; // 30 56:return } } protected Object _findMissing(SettableBeanProperty settablebeanproperty) throws JsonMappingException { if(settablebeanproperty.getInjectableValueId() != null) //* 0 0:aload_1 //* 1 1:invokevirtual #52 <Method Object SettableBeanProperty.getInjectableValueId()> //* 2 4:ifnull 21 return _context.findInjectableValue(settablebeanproperty.getInjectableValueId(), ((com.fasterxml.jackson.databind.BeanProperty) (settablebeanproperty)), ((Object) (null))); // 3 7:aload_0 // 4 8:getfield #30 <Field DeserializationContext _context> // 5 11:aload_1 // 6 12:invokevirtual #52 <Method Object SettableBeanProperty.getInjectableValueId()> // 7 15:aload_1 // 8 16:aconst_null // 9 17:invokevirtual #58 <Method Object DeserializationContext.findInjectableValue(Object, com.fasterxml.jackson.databind.BeanProperty, Object)> // 10 20:areturn if(settablebeanproperty.isRequired()) //* 11 21:aload_1 //* 12 22:invokevirtual #62 <Method boolean SettableBeanProperty.isRequired()> //* 13 25:ifeq 59 throw _context.mappingException("Missing required creator property '%s' (index %d)", new Object[] { settablebeanproperty.getName(), Integer.valueOf(settablebeanproperty.getCreatorIndex()) }); // 14 28:aload_0 // 15 29:getfield #30 <Field DeserializationContext _context> // 16 32:ldc1 #64 <String "Missing required creator property '%s' (index %d)"> // 17 34:iconst_2 // 18 35:anewarray Object[] // 19 38:dup // 20 39:iconst_0 // 21 40:aload_1 // 22 41:invokevirtual #68 <Method String SettableBeanProperty.getName()> // 23 44:aastore // 24 45:dup // 25 46:iconst_1 // 26 47:aload_1 // 27 48:invokevirtual #72 <Method int SettableBeanProperty.getCreatorIndex()> // 28 51:invokestatic #78 <Method Integer Integer.valueOf(int)> // 29 54:aastore // 30 55:invokevirtual #82 <Method JsonMappingException DeserializationContext.mappingException(String, Object[])> // 31 58:athrow if(_context.isEnabled(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES)) //* 32 59:aload_0 //* 33 60:getfield #30 <Field DeserializationContext _context> //* 34 63:getstatic #88 <Field DeserializationFeature DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES> //* 35 66:invokevirtual #92 <Method boolean DeserializationContext.isEnabled(DeserializationFeature)> //* 36 69:ifeq 103 throw _context.mappingException("Missing creator property '%s' (index %d); DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES enabled", new Object[] { settablebeanproperty.getName(), Integer.valueOf(settablebeanproperty.getCreatorIndex()) }); // 37 72:aload_0 // 38 73:getfield #30 <Field DeserializationContext _context> // 39 76:ldc1 #94 <String "Missing creator property '%s' (index %d); DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES enabled"> // 40 78:iconst_2 // 41 79:anewarray Object[] // 42 82:dup // 43 83:iconst_0 // 44 84:aload_1 // 45 85:invokevirtual #68 <Method String SettableBeanProperty.getName()> // 46 88:aastore // 47 89:dup // 48 90:iconst_1 // 49 91:aload_1 // 50 92:invokevirtual #72 <Method int SettableBeanProperty.getCreatorIndex()> // 51 95:invokestatic #78 <Method Integer Integer.valueOf(int)> // 52 98:aastore // 53 99:invokevirtual #82 <Method JsonMappingException DeserializationContext.mappingException(String, Object[])> // 54 102:athrow else return settablebeanproperty.getValueDeserializer().getNullValue(_context); // 55 103:aload_1 // 56 104:invokevirtual #98 <Method JsonDeserializer SettableBeanProperty.getValueDeserializer()> // 57 107:aload_0 // 58 108:getfield #30 <Field DeserializationContext _context> // 59 111:invokevirtual #104 <Method Object JsonDeserializer.getNullValue(DeserializationContext)> // 60 114:areturn } public boolean assignParameter(int i, Object obj) { _creatorParameters[i] = obj; // 0 0:aload_0 // 1 1:getfield #36 <Field Object[] _creatorParameters> // 2 4:iload_1 // 3 5:aload_2 // 4 6:aastore return false; // 5 7:iconst_0 // 6 8:ireturn } public boolean assignParameter(SettableBeanProperty settablebeanproperty, Object obj) { int i; i = settablebeanproperty.getCreatorIndex(); // 0 0:aload_1 // 1 1:invokevirtual #72 <Method int SettableBeanProperty.getCreatorIndex()> // 2 4:istore_3 _creatorParameters[i] = obj; // 3 5:aload_0 // 4 6:getfield #36 <Field Object[] _creatorParameters> // 5 9:iload_3 // 6 10:aload_2 // 7 11:aastore if(_paramsSeenBig != null) goto _L2; else goto _L1 // 8 12:aload_0 // 9 13:getfield #38 <Field BitSet _paramsSeenBig> // 10 16:ifnonnull 61 _L1: int j = _paramsSeen; // 11 19:aload_0 // 12 20:getfield #112 <Field int _paramsSeen> // 13 23:istore 4 i = j | 1 << i; // 14 25:iload 4 // 15 27:iconst_1 // 16 28:iload_3 // 17 29:ishl // 18 30:ior // 19 31:istore_3 if(j == i) break MISSING_BLOCK_LABEL_99; // 20 32:iload 4 // 21 34:iload_3 // 22 35:icmpeq 99 _paramsSeen = i; // 23 38:aload_0 // 24 39:iload_3 // 25 40:putfield #112 <Field int _paramsSeen> i = _paramsNeeded - 1; // 26 43:aload_0 // 27 44:getfield #32 <Field int _paramsNeeded> // 28 47:iconst_1 // 29 48:isub // 30 49:istore_3 _paramsNeeded = i; // 31 50:aload_0 // 32 51:iload_3 // 33 52:putfield #32 <Field int _paramsNeeded> if(i > 0) break MISSING_BLOCK_LABEL_99; // 34 55:iload_3 // 35 56:ifgt 99 _L4: return true; // 36 59:iconst_1 // 37 60:ireturn _L2: int k; if(_paramsSeenBig.get(i)) break MISSING_BLOCK_LABEL_99; // 38 61:aload_0 // 39 62:getfield #38 <Field BitSet _paramsSeenBig> // 40 65:iload_3 // 41 66:invokevirtual #116 <Method boolean BitSet.get(int)> // 42 69:ifne 99 k = _paramsNeeded - 1; // 43 72:aload_0 // 44 73:getfield #32 <Field int _paramsNeeded> // 45 76:iconst_1 // 46 77:isub // 47 78:istore 4 _paramsNeeded = k; // 48 80:aload_0 // 49 81:iload 4 // 50 83:putfield #32 <Field int _paramsNeeded> if(k <= 0) goto _L4; else goto _L3 // 51 86:iload 4 // 52 88:ifle 59 _L3: _paramsSeenBig.set(i); // 53 91:aload_0 // 54 92:getfield #38 <Field BitSet _paramsSeenBig> // 55 95:iload_3 // 56 96:invokevirtual #120 <Method void BitSet.set(int)> return false; // 57 99:iconst_0 // 58 100:ireturn } public void bufferAnyProperty(SettableAnyProperty settableanyproperty, String s, Object obj) { _buffered = ((PropertyValue) (new PropertyValue.Any(_buffered, obj, settableanyproperty, s))); // 0 0:aload_0 // 1 1:new #124 <Class PropertyValue$Any> // 2 4:dup // 3 5:aload_0 // 4 6:getfield #126 <Field PropertyValue _buffered> // 5 9:aload_3 // 6 10:aload_1 // 7 11:aload_2 // 8 12:invokespecial #129 <Method void PropertyValue$Any(PropertyValue, Object, SettableAnyProperty, String)> // 9 15:putfield #126 <Field PropertyValue _buffered> // 10 18:return } public void bufferMapProperty(Object obj, Object obj1) { _buffered = ((PropertyValue) (new PropertyValue.Map(_buffered, obj1, obj))); // 0 0:aload_0 // 1 1:new #133 <Class PropertyValue$Map> // 2 4:dup // 3 5:aload_0 // 4 6:getfield #126 <Field PropertyValue _buffered> // 5 9:aload_2 // 6 10:aload_1 // 7 11:invokespecial #136 <Method void PropertyValue$Map(PropertyValue, Object, Object)> // 8 14:putfield #126 <Field PropertyValue _buffered> // 9 17:return } public void bufferProperty(SettableBeanProperty settablebeanproperty, Object obj) { _buffered = ((PropertyValue) (new PropertyValue.Regular(_buffered, obj, settablebeanproperty))); // 0 0:aload_0 // 1 1:new #140 <Class PropertyValue$Regular> // 2 4:dup // 3 5:aload_0 // 4 6:getfield #126 <Field PropertyValue _buffered> // 5 9:aload_2 // 6 10:aload_1 // 7 11:invokespecial #143 <Method void PropertyValue$Regular(PropertyValue, Object, SettableBeanProperty)> // 8 14:putfield #126 <Field PropertyValue _buffered> // 9 17:return } protected PropertyValue buffered() { return _buffered; // 0 0:aload_0 // 1 1:getfield #126 <Field PropertyValue _buffered> // 2 4:areturn } protected Object[] getParameters(SettableBeanProperty asettablebeanproperty[]) throws JsonMappingException { if(_paramsNeeded > 0) //* 0 0:aload_0 //* 1 1:getfield #32 <Field int _paramsNeeded> //* 2 4:ifle 106 if(_paramsSeenBig == null) //* 3 7:aload_0 //* 4 8:getfield #38 <Field BitSet _paramsSeenBig> //* 5 11:ifnonnull 64 { int i = _paramsSeen; // 6 14:aload_0 // 7 15:getfield #112 <Field int _paramsSeen> // 8 18:istore_2 int k = 0; // 9 19:iconst_0 // 10 20:istore_3 for(int i1 = _creatorParameters.length; k < i1;) //* 11 21:aload_0 //* 12 22:getfield #36 <Field Object[] _creatorParameters> //* 13 25:arraylength //* 14 26:istore 4 //* 15 28:iload_3 //* 16 29:iload 4 //* 17 31:icmpge 106 { if((i & 1) == 0) //* 18 34:iload_2 //* 19 35:iconst_1 //* 20 36:iand //* 21 37:ifne 53 _creatorParameters[k] = _findMissing(asettablebeanproperty[k]); // 22 40:aload_0 // 23 41:getfield #36 <Field Object[] _creatorParameters> // 24 44:iload_3 // 25 45:aload_0 // 26 46:aload_1 // 27 47:iload_3 // 28 48:aaload // 29 49:invokevirtual #149 <Method Object _findMissing(SettableBeanProperty)> // 30 52:aastore k++; // 31 53:iload_3 // 32 54:iconst_1 // 33 55:iadd // 34 56:istore_3 i >>= 1; // 35 57:iload_2 // 36 58:iconst_1 // 37 59:ishr // 38 60:istore_2 } } else //* 39 61:goto 28 { int l = _creatorParameters.length; // 40 64:aload_0 // 41 65:getfield #36 <Field Object[] _creatorParameters> // 42 68:arraylength // 43 69:istore_3 int j = 0; // 44 70:iconst_0 // 45 71:istore_2 do { j = _paramsSeenBig.nextClearBit(j); // 46 72:aload_0 // 47 73:getfield #38 <Field BitSet _paramsSeenBig> // 48 76:iload_2 // 49 77:invokevirtual #153 <Method int BitSet.nextClearBit(int)> // 50 80:istore_2 if(j >= l) break; // 51 81:iload_2 // 52 82:iload_3 // 53 83:icmpge 106 _creatorParameters[j] = _findMissing(asettablebeanproperty[j]); // 54 86:aload_0 // 55 87:getfield #36 <Field Object[] _creatorParameters> // 56 90:iload_2 // 57 91:aload_0 // 58 92:aload_1 // 59 93:iload_2 // 60 94:aaload // 61 95:invokevirtual #149 <Method Object _findMissing(SettableBeanProperty)> // 62 98:aastore j++; // 63 99:iload_2 // 64 100:iconst_1 // 65 101:iadd // 66 102:istore_2 } while(true); // 67 103:goto 72 } return _creatorParameters; // 68 106:aload_0 // 69 107:getfield #36 <Field Object[] _creatorParameters> // 70 110:areturn } public Object handleIdValue(DeserializationContext deserializationcontext, Object obj) throws IOException { label0: { Object obj1 = obj; // 0 0:aload_2 // 1 1:astore_3 if(_objectIdReader != null) //* 2 2:aload_0 //* 3 3:getfield #34 <Field ObjectIdReader _objectIdReader> //* 4 6:ifnull 66 { if(_idValue == null) break label0; // 5 9:aload_0 // 6 10:getfield #159 <Field Object _idValue> // 7 13:ifnull 68 deserializationcontext.findObjectId(_idValue, _objectIdReader.generator, _objectIdReader.resolver).bindItem(obj); // 8 16:aload_1 // 9 17:aload_0 // 10 18:getfield #159 <Field Object _idValue> // 11 21:aload_0 // 12 22:getfield #34 <Field ObjectIdReader _objectIdReader> // 13 25:getfield #165 <Field com.fasterxml.jackson.annotation.ObjectIdGenerator ObjectIdReader.generator> // 14 28:aload_0 // 15 29:getfield #34 <Field ObjectIdReader _objectIdReader> // 16 32:getfield #169 <Field com.fasterxml.jackson.annotation.ObjectIdResolver ObjectIdReader.resolver> // 17 35:invokevirtual #173 <Method ReadableObjectId DeserializationContext.findObjectId(Object, com.fasterxml.jackson.annotation.ObjectIdGenerator, com.fasterxml.jackson.annotation.ObjectIdResolver)> // 18 38:aload_2 // 19 39:invokevirtual #179 <Method void ReadableObjectId.bindItem(Object)> deserializationcontext = ((DeserializationContext) (_objectIdReader.idProperty)); // 20 42:aload_0 // 21 43:getfield #34 <Field ObjectIdReader _objectIdReader> // 22 46:getfield #183 <Field SettableBeanProperty ObjectIdReader.idProperty> // 23 49:astore_1 obj1 = obj; // 24 50:aload_2 // 25 51:astore_3 if(deserializationcontext != null) //* 26 52:aload_1 //* 27 53:ifnull 66 obj1 = ((SettableBeanProperty) (deserializationcontext)).setAndReturn(obj, _idValue); // 28 56:aload_1 // 29 57:aload_2 // 30 58:aload_0 // 31 59:getfield #159 <Field Object _idValue> // 32 62:invokevirtual #187 <Method Object SettableBeanProperty.setAndReturn(Object, Object)> // 33 65:astore_3 } return obj1; // 34 66:aload_3 // 35 67:areturn } throw deserializationcontext.mappingException("No _idValue when handleIdValue called, on instance of %s", new Object[] { obj.getClass().getName() }); // 36 68:aload_1 // 37 69:ldc1 #189 <String "No _idValue when handleIdValue called, on instance of %s"> // 38 71:iconst_1 // 39 72:anewarray Object[] // 40 75:dup // 41 76:iconst_0 // 42 77:aload_2 // 43 78:invokevirtual #193 <Method Class Object.getClass()> // 44 81:invokevirtual #196 <Method String Class.getName()> // 45 84:aastore // 46 85:invokevirtual #82 <Method JsonMappingException DeserializationContext.mappingException(String, Object[])> // 47 88:athrow } public boolean isComplete() { return _paramsNeeded <= 0; // 0 0:aload_0 // 1 1:getfield #32 <Field int _paramsNeeded> // 2 4:ifgt 9 // 3 7:iconst_1 // 4 8:ireturn // 5 9:iconst_0 // 6 10:ireturn } public boolean readIdProperty(String s) throws IOException { if(_objectIdReader != null && s.equals(((Object) (_objectIdReader.propertyName.getSimpleName())))) //* 0 0:aload_0 //* 1 1:getfield #34 <Field ObjectIdReader _objectIdReader> //* 2 4:ifnull 45 //* 3 7:aload_1 //* 4 8:aload_0 //* 5 9:getfield #34 <Field ObjectIdReader _objectIdReader> //* 6 12:getfield #203 <Field PropertyName ObjectIdReader.propertyName> //* 7 15:invokevirtual #208 <Method String PropertyName.getSimpleName()> //* 8 18:invokevirtual #214 <Method boolean String.equals(Object)> //* 9 21:ifeq 45 { _idValue = _objectIdReader.readObjectReference(_parser, _context); // 10 24:aload_0 // 11 25:aload_0 // 12 26:getfield #34 <Field ObjectIdReader _objectIdReader> // 13 29:aload_0 // 14 30:getfield #28 <Field JsonParser _parser> // 15 33:aload_0 // 16 34:getfield #30 <Field DeserializationContext _context> // 17 37:invokevirtual #218 <Method Object ObjectIdReader.readObjectReference(JsonParser, DeserializationContext)> // 18 40:putfield #159 <Field Object _idValue> return true; // 19 43:iconst_1 // 20 44:ireturn } else { return false; // 21 45:iconst_0 // 22 46:ireturn } } protected PropertyValue _buffered; protected final DeserializationContext _context; protected final Object _creatorParameters[]; protected Object _idValue; protected final ObjectIdReader _objectIdReader; protected int _paramsNeeded; protected int _paramsSeen; protected final BitSet _paramsSeenBig; protected final JsonParser _parser; }
39.568224
207
0.568048
49bbeee3d904e44f5bed49ababb53c4e898560b3
362
package com.wy; import javax.sql.DataSource; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ApplicationTests { @Autowired private DataSource datasource; @Test void contextLoads() { System.out.println(datasource); } }
19.052632
62
0.798343
b7a5331c7b01e4930cfb3470494c2b3400389d69
32,595
/* * This file was automatically generated by EvoSuite * Fri Aug 24 18:12:19 GMT 2018 */ package org.dom4j.io; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.shaded.org.mockito.Mockito.*; import static org.evosuite.runtime.EvoAssertions.*; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.Reader; import java.io.SequenceInputStream; import java.io.StringReader; import java.net.URL; import java.nio.CharBuffer; import java.util.Enumeration; import org.dom4j.DefaultDocumentFactory; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.ElementHandler; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMNamespace; import org.dom4j.io.DispatchHandler; import org.dom4j.io.ElementModifier; import org.dom4j.io.ElementStack; import org.dom4j.io.PruningDispatchHandler; import org.dom4j.io.PruningElementStack; import org.dom4j.io.SAXModifyElementHandler; import org.dom4j.io.SAXReader; import org.dom4j.tree.NamespaceStack; import org.dom4j.util.NonLazyElement; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.evosuite.runtime.ViolatedAssumptionAnswer; import org.evosuite.runtime.mock.java.io.MockFile; import org.evosuite.runtime.mock.java.net.MockURL; import org.jaxen.SimpleVariableContext; import org.jaxen.VariableContext; import org.junit.runner.RunWith; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.HandlerBase; import org.xml.sax.InputSource; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.ext.DefaultHandler2; import org.xml.sax.ext.Locator2Impl; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.helpers.ParserAdapter; import org.xml.sax.helpers.XMLFilterImpl; import org.xml.sax.helpers.XMLReaderAdapter; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class SAXReader_ESTest extends SAXReader_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test00() throws Throwable { SAXReader sAXReader0 = new SAXReader(); byte[] byteArray0 = new byte[6]; byteArray0[0] = (byte) (-58); byteArray0[1] = (byte)58; byteArray0[2] = (byte)83; byte byte0 = (byte)0; byteArray0[3] = (byte)0; byteArray0[4] = (byte)85; sAXReader0.setValidation(true); ElementStack elementStack0 = new ElementStack(); elementStack0.getDispatchHandler(); sAXReader0.getDispatchHandler(); String string0 = ""; DispatchHandler dispatchHandler0 = sAXReader0.getDispatchHandler(); // Undeclared exception! try { dispatchHandler0.onEnd(elementStack0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("java.util.ArrayList", e); } } /** //Test case number: 1 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test01() throws Throwable { DocumentFactory documentFactory0 = DefaultDocumentFactory.getInstance(); SAXReader sAXReader0 = new SAXReader(documentFactory0); sAXReader0.setEncoding("org.dom4j.tree.AbstractDocumentType"); assertFalse(sAXReader0.isMergeAdjacentText()); assertTrue(sAXReader0.isStringInternEnabled()); assertFalse(sAXReader0.isIncludeExternalDTDDeclarations()); assertFalse(sAXReader0.isStripWhitespaceText()); assertFalse(sAXReader0.isIgnoreComments()); assertFalse(sAXReader0.isIncludeInternalDTDDeclarations()); } /** //Test case number: 2 /*Coverage entropy=2.9444389791664403 */ @Test(timeout = 4000) public void test02() throws Throwable { SAXReader sAXReader0 = new SAXReader(true); sAXReader0.getXMLReader(); StringReader stringReader0 = new StringReader("SN}}:h-zXDO!zl4'0"); try { sAXReader0.read((Reader) stringReader0, ""); fail("Expecting exception: Exception"); } catch(Exception e) { // // Error on line 1 of document file:///home/ubuntu/ext1/evosuite_readability_gen/projects/62_dom4j/ : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog. // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 3 /*Coverage entropy=2.3025850929940455 */ @Test(timeout = 4000) public void test03() throws Throwable { SAXReader sAXReader0 = new SAXReader(); sAXReader0.setValidation(false); NonLazyElement nonLazyElement0 = new NonLazyElement((QName) null); DOMNamespace dOMNamespace0 = new DOMNamespace(nonLazyElement0, "i_nanRChvC1", "|E"); QName qName0 = new QName("|E", dOMNamespace0); dOMNamespace0.equals(sAXReader0); nonLazyElement0.selectObject("i_nanRChvC1"); DispatchHandler dispatchHandler0 = new DispatchHandler(); dOMNamespace0.getLastChild(); sAXReader0.setDefaultHandler(dispatchHandler0); qName0.getDocumentFactory(); sAXReader0.setDocumentFactory((DocumentFactory) null); boolean boolean0 = sAXReader0.isIncludeExternalDTDDeclarations(); assertFalse(boolean0); boolean boolean1 = sAXReader0.isMergeAdjacentText(); sAXReader0.getXMLFilter(); boolean boolean2 = sAXReader0.isStringInternEnabled(); assertFalse(boolean2 == boolean1); sAXReader0.setIgnoreComments(false); sAXReader0.getXMLFilter(); assertFalse(sAXReader0.isIgnoreComments()); assertFalse(sAXReader0.isValidating()); assertFalse(sAXReader0.isStripWhitespaceText()); assertFalse(sAXReader0.isIncludeInternalDTDDeclarations()); } /** //Test case number: 4 /*Coverage entropy=2.995732273553991 */ @Test(timeout = 4000) public void test04() throws Throwable { SAXReader sAXReader0 = new SAXReader(false); DefaultHandler defaultHandler0 = new DefaultHandler(); defaultHandler0.skippedEntity("Sn=G:A$YcgS<i1wG_"); defaultHandler0.skippedEntity("Sn=G:A$YcgS<i1wG_"); sAXReader0.setErrorHandler(defaultHandler0); sAXReader0.isStripWhitespaceText(); SAXReader.SAXEntityResolver sAXReader_SAXEntityResolver0 = new SAXReader.SAXEntityResolver(""); InputSource inputSource0 = sAXReader_SAXEntityResolver0.resolveEntity("", "m.+"); inputSource0.getByteStream(); try { sAXReader0.read(inputSource0); fail("Expecting exception: Exception"); } catch(Exception e) { // // /home/ubuntu/ext1/evosuite_readability_gen/projects/62_dom4j/m.+ (No such file or directory) Nested exception: /home/ubuntu/ext1/evosuite_readability_gen/projects/62_dom4j/m.+ (No such file or directory) // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 5 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test05() throws Throwable { XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl(); SAXReader sAXReader0 = new SAXReader(xMLFilterImpl0); String string0 = ""; MockFile mockFile0 = new MockFile(""); try { sAXReader0.read((File) mockFile0); fail("Expecting exception: Exception"); } catch(Exception e) { // // null Nested exception: null // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 6 /*Coverage entropy=2.995732273553991 */ @Test(timeout = 4000) public void test06() throws Throwable { Namespace namespace0 = Namespace.NO_NAMESPACE; QName qName0 = new QName("", namespace0, ""); qName0.getDocumentFactory(); SAXReader sAXReader0 = new SAXReader((DocumentFactory) null); boolean boolean0 = true; sAXReader0.setStringInternEnabled(true); StringReader stringReader0 = new StringReader(""); stringReader0.read(); char[] charArray0 = new char[2]; charArray0[0] = 'P'; charArray0[1] = '0'; stringReader0.read(charArray0); try { sAXReader0.read((Reader) stringReader0, "/"); fail("Expecting exception: Exception"); } catch(Exception e) { // // Error on line -1 of document : Premature end of file. Nested exception: Premature end of file. // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 7 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test07() throws Throwable { String string0 = "OS)~L"; SAXReader sAXReader0 = null; try { sAXReader0 = new SAXReader("OS)~L"); fail("Expecting exception: SAXException"); } catch(Throwable e) { // // SAX2 driver class OS)~L not found // verifyException("org.xml.sax.helpers.XMLReaderFactory", e); } } /** //Test case number: 8 /*Coverage entropy=2.833213344056216 */ @Test(timeout = 4000) public void test08() throws Throwable { XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl(); SAXReader sAXReader0 = new SAXReader(xMLFilterImpl0); sAXReader0.setXMLFilter(xMLFilterImpl0); XMLFilterImpl xMLFilterImpl1 = new XMLFilterImpl(xMLFilterImpl0); Locator2Impl locator2Impl0 = new Locator2Impl(); Locator2Impl locator2Impl1 = new Locator2Impl(locator2Impl0); locator2Impl0.getColumnNumber(); locator2Impl1.setLineNumber((-1)); SAXParseException sAXParseException0 = new SAXParseException(" data: ", locator2Impl1); xMLFilterImpl1.fatalError(sAXParseException0); String string0 = "G%%,"; // Undeclared exception! try { sAXReader0.read("G%%,"); fail("Expecting exception: StackOverflowError"); } catch(StackOverflowError e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 9 /*Coverage entropy=1.6674619334292948 */ @Test(timeout = 4000) public void test09() throws Throwable { boolean boolean0 = true; SAXReader sAXReader0 = new SAXReader(true); XMLReaderAdapter xMLReaderAdapter0 = new XMLReaderAdapter(); ParserAdapter parserAdapter0 = new ParserAdapter(xMLReaderAdapter0); parserAdapter0.getContentHandler(); DefaultHandler2 defaultHandler2_0 = new DefaultHandler2(); String string0 = "yisNu^Nn>"; defaultHandler2_0.startDTD("helC~BXKo.", "helC~BXKo.", "yisNu^Nn>"); sAXReader0.setIgnoreComments(true); DefaultDocumentFactory defaultDocumentFactory0 = new DefaultDocumentFactory(); QName qName0 = defaultDocumentFactory0.createQName("yisNu^Nn>", "yisNu^Nn>"); DOMNamespace dOMNamespace0 = new DOMNamespace((Element) null, "yisNu^Nn>", (String) null); QName.get("yisNu^Nn>", (Namespace) dOMNamespace0, "yisNu^Nn>"); DocumentFactory documentFactory0 = qName0.getDocumentFactory(); sAXReader0.setDocumentFactory(documentFactory0); try { sAXReader0.configureReader(parserAdapter0, defaultHandler2_0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Validation not supported for XMLReader: org.xml.sax.helpers.ParserAdapter@5d12dbe9 Nested exception: Feature: http://xml.org/sax/features/validation // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 10 /*Coverage entropy=1.945910149055313 */ @Test(timeout = 4000) public void test10() throws Throwable { SAXReader sAXReader0 = new SAXReader((String) null, true); String string0 = "X(PXUf'K?T=Lqz"; sAXReader0.removeHandler("X(PXUf'K?T=Lqz"); sAXReader0.isValidating(); try { sAXReader0.setFeature("G3]6y073E$Zx7?a06P(", true); fail("Expecting exception: SAXNotRecognizedException"); } catch(SAXNotRecognizedException e) { // // Feature 'G3]6y073E$Zx7?a06P(' is not recognized. // verifyException("org.apache.xerces.parsers.AbstractSAXParser", e); } } /** //Test case number: 11 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test11() throws Throwable { String string0 = null; SAXReader sAXReader0 = new SAXReader((String) null); StringReader stringReader0 = null; try { stringReader0 = new StringReader((String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("java.io.StringReader", e); } } /** //Test case number: 12 /*Coverage entropy=2.890371757896165 */ @Test(timeout = 4000) public void test12() throws Throwable { boolean boolean0 = true; SAXReader sAXReader0 = new SAXReader(true); byte[] byteArray0 = new byte[2]; byte byte0 = (byte)117; DefaultHandler2 defaultHandler2_0 = new DefaultHandler2(); sAXReader0.setEntityResolver(defaultHandler2_0); byteArray0[0] = (byte)117; byte byte1 = (byte) (-120); byteArray0[1] = (byte) (-120); ByteArrayInputStream byteArrayInputStream0 = new ByteArrayInputStream(byteArray0, (-2736), (byte)117); StringReader stringReader0 = new StringReader("N9jb0=Q4"); try { sAXReader0.read((Reader) stringReader0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Error on line 1 of document : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog. // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 13 /*Coverage entropy=2.9319232930107053 */ @Test(timeout = 4000) public void test13() throws Throwable { SAXReader sAXReader0 = new SAXReader(false); DocumentFactory documentFactory0 = DefaultDocumentFactory.getInstance(); sAXReader0.setDocumentFactory(documentFactory0); sAXReader0.getXMLFilter(); try { sAXReader0.read("6r9C~B<GEoR/%</"); fail("Expecting exception: Exception"); } catch(Exception e) { // // no protocol: 6r9C~B<GEoR/%</ Nested exception: no protocol: 6r9C~B<GEoR/%</ // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 14 /*Coverage entropy=2.0794415416798357 */ @Test(timeout = 4000) public void test14() throws Throwable { DefaultDocumentFactory defaultDocumentFactory0 = new DefaultDocumentFactory(); SAXReader sAXReader0 = new SAXReader(defaultDocumentFactory0); sAXReader0.getXMLFilter(); boolean boolean0 = true; SAXReader sAXReader1 = new SAXReader((XMLReader) null, true); DispatchHandler dispatchHandler0 = sAXReader1.getDispatchHandler(); String string0 = "=n%$:WgDY<!R!Dk64g"; dispatchHandler0.removeHandler("=n%$:WgDY<!R!Dk64g"); dispatchHandler0.addHandler("=n%$:WgDY<!R!Dk64g", (ElementHandler) null); try { sAXReader1.setProperty("=n%$:WgDY<!R!Dk64g", "=n%$:WgDY<!R!Dk64g"); fail("Expecting exception: SAXNotRecognizedException"); } catch(SAXNotRecognizedException e) { // // Property '=n%$:WgDY<!R!Dk64g' is not recognized. // verifyException("org.apache.xerces.parsers.AbstractSAXParser", e); } } /** //Test case number: 15 /*Coverage entropy=2.898745539586339 */ @Test(timeout = 4000) public void test15() throws Throwable { String string0 = "p~8lEE#]_yR'L"; SAXReader.SAXEntityResolver sAXReader_SAXEntityResolver0 = new SAXReader.SAXEntityResolver("p~8lEE#]_yR'L"); sAXReader_SAXEntityResolver0.resolveEntity("p~8lEE#]_yR'L", "p~8lEE#]_yR'L"); DocumentFactory documentFactory0 = DefaultDocumentFactory.getInstance(); SAXReader sAXReader0 = new SAXReader(documentFactory0); HandlerBase handlerBase0 = new HandlerBase(); LocatorImpl locatorImpl0 = new LocatorImpl(); LocatorImpl locatorImpl1 = new LocatorImpl(locatorImpl0); handlerBase0.setDocumentLocator(locatorImpl1); sAXReader0.setErrorHandler(handlerBase0); File file0 = MockFile.createTempFile("attributes", "Po@K"); try { sAXReader0.read(file0); fail("Expecting exception: Exception"); } catch(Exception e) { // // Error on line -1 of document : Premature end of file. Nested exception: Premature end of file. // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 16 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test16() throws Throwable { boolean boolean0 = true; SAXReader sAXReader0 = new SAXReader(true); String string0 = "/z-=5x"; sAXReader0.setStripWhitespaceText(false); PipedInputStream pipedInputStream0 = new PipedInputStream(); byte[] byteArray0 = new byte[8]; byteArray0[0] = (byte)0; byteArray0[1] = (byte)0; byteArray0[2] = (byte)58; byteArray0[3] = (byte)1; byteArray0[4] = (byte)99; byteArray0[5] = (byte)102; byteArray0[6] = (byte)40; byteArray0[7] = (byte)0; try { pipedInputStream0.read(byteArray0); fail("Expecting exception: IOException"); } catch(IOException e) { // // Pipe not connected // verifyException("java.io.PipedInputStream", e); } } /** //Test case number: 17 /*Coverage entropy=1.3862943611198906 */ @Test(timeout = 4000) public void test17() throws Throwable { SAXReader sAXReader0 = new SAXReader(); String[] stringArray0 = new String[6]; stringArray0[0] = "http://xml.org/sax/properties/lexical-handler"; stringArray0[1] = "t.z'3'$F|y,#XA"; stringArray0[2] = ""; stringArray0[3] = ""; stringArray0[4] = "http://xml.org/sax/features/validation"; stringArray0[5] = "COMMENT_NODE"; PruningDispatchHandler pruningDispatchHandler0 = new PruningDispatchHandler(); pruningDispatchHandler0.getHandler("t.z'3'$F|y,#XA"); PruningElementStack pruningElementStack0 = new PruningElementStack(stringArray0, (ElementHandler) null, 1335); pruningElementStack0.getPath(); pruningElementStack0.lastElementIndex = 347; DispatchHandler dispatchHandler0 = pruningElementStack0.getDispatchHandler(); sAXReader0.setDefaultHandler(dispatchHandler0); assertFalse(sAXReader0.isMergeAdjacentText()); sAXReader0.setMergeAdjacentText(true); assertTrue(sAXReader0.isMergeAdjacentText()); } /** //Test case number: 18 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test18() throws Throwable { SAXReader sAXReader0 = new SAXReader(false); sAXReader0.setIncludeInternalDTDDeclarations(false); assertTrue(sAXReader0.isStringInternEnabled()); assertFalse(sAXReader0.isIncludeExternalDTDDeclarations()); assertFalse(sAXReader0.isIgnoreComments()); assertFalse(sAXReader0.isIncludeInternalDTDDeclarations()); assertFalse(sAXReader0.isStripWhitespaceText()); assertFalse(sAXReader0.isValidating()); assertFalse(sAXReader0.isMergeAdjacentText()); } /** //Test case number: 19 /*Coverage entropy=2.995732273553991 */ @Test(timeout = 4000) public void test19() throws Throwable { XMLReaderAdapter xMLReaderAdapter0 = new XMLReaderAdapter(); xMLReaderAdapter0.endPrefixMapping("'WeF.euf"); ParserAdapter parserAdapter0 = new ParserAdapter(xMLReaderAdapter0); parserAdapter0.setContentHandler(xMLReaderAdapter0); SAXReader sAXReader0 = new SAXReader(parserAdapter0, true); sAXReader0.getEntityResolver(); sAXReader0.setEntityResolver((EntityResolver) null); char[] charArray0 = new char[8]; charArray0[0] = '_'; charArray0[1] = 'd'; charArray0[2] = '8'; charArray0[3] = '4'; charArray0[4] = '-'; charArray0[5] = 'P'; charArray0[6] = '+'; charArray0[7] = '!'; parserAdapter0.characters(charArray0, 0, 0); sAXReader0.isIgnoreComments(); StringReader stringReader0 = new StringReader(""); try { sAXReader0.read((Reader) stringReader0, ""); fail("Expecting exception: Exception"); } catch(Exception e) { // // Validation not supported for XMLReader: org.xml.sax.helpers.ParserAdapter@253c1b23 Nested exception: Feature: http://xml.org/sax/features/validation Nested exception: Validation not supported for XMLReader: org.xml.sax.helpers.ParserAdapter@253c1b23 Nested exception: Feature: http://xml.org/sax/features/validation // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 20 /*Coverage entropy=1.945910149055313 */ @Test(timeout = 4000) public void test20() throws Throwable { XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl((XMLReader) null); SAXReader sAXReader0 = new SAXReader(xMLFilterImpl0, false); sAXReader0.setErrorHandler(xMLFilterImpl0); sAXReader0.resetHandlers(); sAXReader0.getXMLReader(); sAXReader0.setStringInternEnabled(true); sAXReader0.isMergeAdjacentText(); String string0 = ""; LocatorImpl locatorImpl0 = new LocatorImpl(); LocatorImpl locatorImpl1 = new LocatorImpl(locatorImpl0); SAXParseException sAXParseException0 = new SAXParseException("u!o!y5<++[", locatorImpl1); xMLFilterImpl0.error(sAXParseException0); xMLFilterImpl0.endElement("u!o!y5<++[", "", ""); StringReader stringReader0 = new StringReader(""); stringReader0.ready(); // Undeclared exception! try { stringReader0.read((char[]) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("java.io.Reader", e); } } /** //Test case number: 21 /*Coverage entropy=2.0794415416798357 */ @Test(timeout = 4000) public void test21() throws Throwable { DocumentFactory documentFactory0 = DefaultDocumentFactory.getInstance(); SAXReader sAXReader0 = new SAXReader(documentFactory0); XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl(); LocatorImpl locatorImpl0 = new LocatorImpl(); LocatorImpl locatorImpl1 = new LocatorImpl(locatorImpl0); locatorImpl1.getSystemId(); locatorImpl0.setSystemId(""); Locator2Impl locator2Impl0 = new Locator2Impl(locatorImpl1); SAXParseException sAXParseException0 = new SAXParseException("", locatorImpl1); SAXParseException sAXParseException1 = new SAXParseException("", locator2Impl0, sAXParseException0); xMLFilterImpl0.fatalError(sAXParseException1); DefaultHandler2 defaultHandler2_0 = new DefaultHandler2(); String string0 = "#5so*[KF;2q3 "; PruningDispatchHandler pruningDispatchHandler0 = new PruningDispatchHandler(); String string1 = "6Cf(m{Wq"; defaultHandler2_0.startPrefixMapping("Ky].KY!zw", "6Cf(m{Wq"); sAXReader0.addHandler("#5so*[KF;2q3 ", pruningDispatchHandler0); sAXReader0.configureReader(xMLFilterImpl0, defaultHandler2_0); sAXReader0.setXMLReader(xMLFilterImpl0); sAXReader0.addHandler("#5so*[KF;2q3 ", pruningDispatchHandler0); try { sAXReader0.setXMLReaderClassName("#5so*[KF;2q3 "); fail("Expecting exception: SAXException"); } catch(SAXException e) { // // SAX2 driver class #5so*[KF;2q3 not found // verifyException("org.xml.sax.helpers.XMLReaderFactory", e); } } /** //Test case number: 22 /*Coverage entropy=2.848899705841817 */ @Test(timeout = 4000) public void test22() throws Throwable { NamespaceStack namespaceStack0 = new NamespaceStack(); SAXReader sAXReader0 = new SAXReader((DocumentFactory) null); sAXReader0.getXMLReader(); String string0 = "upper-case() requires at least one argument."; StringReader stringReader0 = new StringReader("upper-case() requires at least one argument."); String string1 = null; try { sAXReader0.read((Reader) stringReader0, (String) null); fail("Expecting exception: Exception"); } catch(Exception e) { // // Error on line 1 of document : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog. // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 23 /*Coverage entropy=2.0794415416798357 */ @Test(timeout = 4000) public void test23() throws Throwable { SAXReader sAXReader0 = new SAXReader(false); SAXReader.SAXEntityResolver sAXReader_SAXEntityResolver0 = new SAXReader.SAXEntityResolver((String) null); sAXReader_SAXEntityResolver0.uriPrefix = null; DispatchHandler dispatchHandler0 = sAXReader0.getDispatchHandler(); sAXReader_SAXEntityResolver0.resolveEntity("dqQ\"7c&3bL'#", "7"); sAXReader0.addHandler((String) null, dispatchHandler0); sAXReader_SAXEntityResolver0.resolveEntity("7", (String) null); sAXReader0.setIncludeExternalDTDDeclarations(false); sAXReader0.setDefaultHandler(dispatchHandler0); // Undeclared exception! try { sAXReader0.setXMLReaderClassName((String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 24 /*Coverage entropy=1.8143075196071257 */ @Test(timeout = 4000) public void test24() throws Throwable { XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl(); SAXReader sAXReader0 = new SAXReader(false); SAXReader.SAXEntityResolver sAXReader_SAXEntityResolver0 = new SAXReader.SAXEntityResolver("http://xml.org/sax/properties/lexical-handler"); DispatchHandler dispatchHandler0 = sAXReader0.getDispatchHandler(); sAXReader_SAXEntityResolver0.resolveEntity("7", "http://xml.org/sax/properties/lexical-handler"); sAXReader0.addHandler("http://xml.org/sax/properties/lexical-handler", dispatchHandler0); sAXReader_SAXEntityResolver0.resolveEntity("+*&p2Jg\"N<", (String) null); sAXReader0.setIncludeExternalDTDDeclarations(false); sAXReader0.setDefaultHandler(dispatchHandler0); SAXReader sAXReader1 = null; try { sAXReader1 = new SAXReader("Invalid path of length: ", false); fail("Expecting exception: SAXException"); } catch(Throwable e) { // // SAX2 driver class Invalid path of length: not found // verifyException("org.xml.sax.helpers.XMLReaderFactory", e); } } /** //Test case number: 25 /*Coverage entropy=2.9319232930107053 */ @Test(timeout = 4000) public void test25() throws Throwable { XMLReaderAdapter xMLReaderAdapter0 = new XMLReaderAdapter(); String string0 = "'WeF.euf"; xMLReaderAdapter0.endPrefixMapping("'WeF.euf"); ParserAdapter parserAdapter0 = new ParserAdapter(xMLReaderAdapter0); parserAdapter0.setContentHandler(xMLReaderAdapter0); SAXReader sAXReader0 = new SAXReader(parserAdapter0, true); sAXReader0.getEntityResolver(); sAXReader0.setEntityResolver((EntityResolver) null); char[] charArray0 = new char[8]; charArray0[0] = '_'; charArray0[1] = 'd'; charArray0[2] = '8'; charArray0[3] = '4'; charArray0[4] = '-'; charArray0[5] = 'P'; charArray0[6] = '8'; charArray0[7] = '!'; parserAdapter0.characters(charArray0, 0, 0); sAXReader0.isIgnoreComments(); StringReader stringReader0 = new StringReader(""); DOMDocument dOMDocument0 = new DOMDocument("'WeF.euf"); boolean boolean0 = false; try { sAXReader0.read((InputStream) null, (String) null); fail("Expecting exception: Exception"); } catch(Exception e) { // // Validation not supported for XMLReader: org.xml.sax.helpers.ParserAdapter@3b5a143c Nested exception: Feature: http://xml.org/sax/features/validation Nested exception: Validation not supported for XMLReader: org.xml.sax.helpers.ParserAdapter@3b5a143c Nested exception: Feature: http://xml.org/sax/features/validation // verifyException("org.dom4j.io.SAXReader", e); } } /** //Test case number: 26 /*Coverage entropy=1.7917594692280547 */ @Test(timeout = 4000) public void test26() throws Throwable { SAXReader sAXReader0 = new SAXReader((DocumentFactory) null); sAXReader0.getEncoding(); sAXReader0.getXMLFilter(); assertFalse(sAXReader0.isStripWhitespaceText()); assertFalse(sAXReader0.isIncludeInternalDTDDeclarations()); assertFalse(sAXReader0.isIgnoreComments()); assertFalse(sAXReader0.isIncludeExternalDTDDeclarations()); assertFalse(sAXReader0.isMergeAdjacentText()); assertTrue(sAXReader0.isStringInternEnabled()); XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl((XMLReader) null); SAXReader sAXReader1 = new SAXReader(xMLFilterImpl0); DispatchHandler dispatchHandler0 = sAXReader1.getDispatchHandler(); sAXReader1.setDispatchHandler(dispatchHandler0); assertFalse(sAXReader1.isStripWhitespaceText()); assertFalse(sAXReader1.isIncludeInternalDTDDeclarations()); assertFalse(sAXReader1.isMergeAdjacentText()); assertTrue(sAXReader1.isStringInternEnabled()); assertFalse(sAXReader1.isIncludeExternalDTDDeclarations()); assertFalse(sAXReader1.isIgnoreComments()); } /** //Test case number: 27 /*Coverage entropy=1.3321790402101223 */ @Test(timeout = 4000) public void test27() throws Throwable { SAXReader.SAXEntityResolver sAXReader_SAXEntityResolver0 = new SAXReader.SAXEntityResolver("<Cu]CE-Hus\"9"); sAXReader_SAXEntityResolver0.resolveEntity("7", ""); XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl(); SAXReader sAXReader0 = new SAXReader(xMLFilterImpl0); sAXReader_SAXEntityResolver0.resolveEntity("true", "7"); try { sAXReader0.setXMLReaderClassName("gNC"); fail("Expecting exception: SAXException"); } catch(SAXException e) { // // SAX2 driver class gNC not found // verifyException("org.xml.sax.helpers.XMLReaderFactory", e); } } /** //Test case number: 28 /*Coverage entropy=2.833213344056216 */ @Test(timeout = 4000) public void test28() throws Throwable { XMLFilterImpl xMLFilterImpl0 = new XMLFilterImpl(); SAXReader sAXReader0 = new SAXReader(xMLFilterImpl0); sAXReader0.setXMLFilter(xMLFilterImpl0); XMLFilter xMLFilter0 = sAXReader0.getXMLFilter(); XMLFilterImpl xMLFilterImpl1 = new XMLFilterImpl(xMLFilter0); Locator2Impl locator2Impl0 = new Locator2Impl(); Locator2Impl locator2Impl1 = new Locator2Impl(locator2Impl0); locator2Impl0.getColumnNumber(); locator2Impl0.setLineNumber((-179)); SAXParseException sAXParseException0 = new SAXParseException(" data: ", locator2Impl1); xMLFilterImpl1.fatalError(sAXParseException0); // Undeclared exception! try { sAXReader0.read((InputStream) null); fail("Expecting exception: StackOverflowError"); } catch(StackOverflowError e) { // // no message in exception (getMessage() returned null) // } } }
37.465517
327
0.67673
7379401b2eed7d8a1ef5e841ecef3beb9f337f24
18,057
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.wearable.watchface.CanvasWatchFaceService; import android.support.wearable.watchface.WatchFaceStyle; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.SurfaceHolder; import android.view.View; import android.view.WindowInsets; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.wearable.Asset; import com.google.android.gms.wearable.DataApi; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataItem; import com.google.android.gms.wearable.DataMap; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.Wearable; import java.io.InputStream; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; /** * Digital watch face with seconds. In ambient mode, the seconds aren't displayed. On devices with * low-bit ambient mode, the text is drawn without anti-aliasing in ambient mode. */ public class SunshineWatchFace extends CanvasWatchFaceService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, DataApi.DataListener, ResultCallback<DataApi.GetFdForAssetResult> { private static final String LOG_TAG = SunshineWatchFace.class.getCanonicalName(); private static final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL); private final String WATCHFACE_MAX_TEMP = "max_temp"; private final String WATCHFACE_MIN_TEMP = "min_temp"; private final String WATCHFACE_CONDITIONS = "conditions"; /** * Update rate in milliseconds for interactive mode. We update once a second since seconds are * displayed in interactive mode. */ private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1); /** * Handler message id for updating the time periodically in interactive mode. */ private static final int MSG_UPDATE_TIME = 0; int mHighTemp; int mLowTemp; Bitmap mIcon; GoogleApiClient mGoogleApiClient; @Override public Engine onCreateEngine() { Log.v(LOG_TAG, "OnCreateEngine"); mGoogleApiClient = new GoogleApiClient.Builder(SunshineWatchFace.this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Wearable.API) .build(); return new Engine(); } private static class EngineHandler extends Handler { private final WeakReference<SunshineWatchFace.Engine> mWeakReference; public EngineHandler(SunshineWatchFace.Engine reference) { mWeakReference = new WeakReference<>(reference); } @Override public void handleMessage(Message msg) { SunshineWatchFace.Engine engine = mWeakReference.get(); if (engine != null) { switch (msg.what) { case MSG_UPDATE_TIME: engine.handleUpdateTimeMessage(); break; } } } } @Override public void onConnected(@Nullable Bundle bundle) { Wearable.DataApi.addListener(mGoogleApiClient, this); Log.v(LOG_TAG, "Connected"); } @Override public void onConnectionSuspended(int i) { Log.d(LOG_TAG, "Connection Suspended"); } @Override public void onDataChanged(DataEventBuffer dataEventBuffer) { for(DataEvent dataEvent : dataEventBuffer) { if(dataEvent.getType() == DataEvent.TYPE_CHANGED) { DataItem item = dataEvent.getDataItem(); DataMap map = DataMapItem.fromDataItem(item).getDataMap(); mLowTemp = map.getInt(WATCHFACE_MIN_TEMP); mHighTemp = map.getInt(WATCHFACE_MAX_TEMP); Asset asset = map.getAsset(WATCHFACE_CONDITIONS); Wearable.DataApi.getFdForAsset(mGoogleApiClient, asset).setResultCallback(this); Log.d(LOG_TAG, "Data received: min="+mLowTemp + " max="+mHighTemp ); } } Log.v(LOG_TAG, "Data Changed"); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d(LOG_TAG, "Connection Failed"); } @Override public void onResult(@NonNull DataApi.GetFdForAssetResult getFdForAssetResult) { InputStream stream = getFdForAssetResult.getInputStream(); mIcon = BitmapFactory.decodeStream(stream); Log.v(LOG_TAG, "On Result"); } private class Engine extends CanvasWatchFaceService.Engine { final Handler mUpdateTimeHandler = new EngineHandler(this); boolean mRegisteredTimeZoneReceiver = false; Paint mBackgroundPaint; Paint mTextPaint; boolean mAmbient; Calendar mCalendar; Date mDate; final BroadcastReceiver mDataReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mCalendar.setTimeZone(TimeZone.getTimeZone(intent.getStringExtra("time-zone"))); } }; int mTapCount; float mHighlightSize; float mStandardSize; private int mSpecW; private int mSpecH; private final Point displaySize = new Point(); View mRootView; TextView mTimeView; TextView mDateView; TextView mHighView; TextView mLowView; ImageView mIconView; /** * Whether the display supports fewer bits for each color in ambient mode. When true, we * disable anti-aliasing in ambient mode. */ boolean mLowBitAmbient; SimpleDateFormat mDateFormat; private void initFormats() { mDateFormat = new SimpleDateFormat(getResources().getString(R.string.date_format), Locale.getDefault()); mDateFormat.setCalendar(mCalendar); } @Override public void onCreate(SurfaceHolder holder) { super.onCreate(holder); setWatchFaceStyle(new WatchFaceStyle.Builder(SunshineWatchFace.this) .setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE) .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE) .setShowSystemUiTime(false) .setAcceptsTapEvents(true) .build()); Resources resources = SunshineWatchFace.this.getResources(); mBackgroundPaint = new Paint(); mBackgroundPaint.setColor(resources.getColor(R.color.primary)); mTextPaint = createTextPaint(R.color.primary_text); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRootView = inflater.inflate(R.layout.watchface, null); mTimeView = (TextView) mRootView.findViewById(R.id.timeTextView); mDateView = (TextView) mRootView.findViewById(R.id.dateTextView); mHighView = (TextView) mRootView.findViewById(R.id.maxTempTextView); mLowView = (TextView) mRootView.findViewById(R.id.minTempTextView); mIconView = (ImageView) mRootView.findViewById(R.id.iconImageView); mTimeView.setLayerPaint(mTextPaint); mDateView.setLayerPaint(mTextPaint); mHighView.setLayerPaint(mTextPaint); mLowView.setLayerPaint(mTextPaint); Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); display.getSize(displaySize); mSpecW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY); mSpecH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY); mCalendar = Calendar.getInstance(); mDate = new Date(); initFormats(); } @Override public void onDestroy() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); super.onDestroy(); } private Paint createTextPaint(int textColor) { Paint paint = new Paint(); paint.setColor(textColor); paint.setTypeface(NORMAL_TYPEFACE); paint.setAntiAlias(true); return paint; } @Override public void onVisibilityChanged(boolean visible) { super.onVisibilityChanged(visible); Log.v(LOG_TAG, "Visibility Changed"); if (visible) { // Connect to phone if not visible mGoogleApiClient.connect(); registerReceiver(); // Update time zone in case it changed while we weren't visible. long now = System.currentTimeMillis(); mCalendar.setTimeInMillis(now); } else { unregisterReceiver(); // Disconnect from phone if it is in ambient mode if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } private void registerReceiver() { if (mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = true; IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED); SunshineWatchFace.this.registerReceiver(mDataReceiver, filter); } private void unregisterReceiver() { if (!mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = false; SunshineWatchFace.this.unregisterReceiver(mDataReceiver); } @Override public void onApplyWindowInsets(WindowInsets insets) { super.onApplyWindowInsets(insets); // Load resources that have alternate values for round watches. Resources resources = SunshineWatchFace.this.getResources(); boolean isRound = insets.isRound(); mHighlightSize = resources.getDimension(isRound ? R.dimen.digital_text_size_round : R.dimen.digital_text_size); mStandardSize = resources.getDimension(isRound ? R.dimen.digital_date_size_round : R.dimen.digital_date_size); } @Override public void onPropertiesChanged(Bundle properties) { super.onPropertiesChanged(properties); mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false); } @Override public void onTimeTick() { super.onTimeTick(); invalidate(); } @Override public void onAmbientModeChanged(boolean inAmbientMode) { super.onAmbientModeChanged(inAmbientMode); if (mAmbient != inAmbientMode) { mAmbient = inAmbientMode; if (mLowBitAmbient) { mTextPaint.setAntiAlias(!inAmbientMode); } invalidate(); } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } /** * Captures tap event (and tap type) and toggles the background color if the user finishes * a tap. */ @Override public void onTapCommand(int tapType, int x, int y, long eventTime) { mGoogleApiClient.connect(); Resources resources = SunshineWatchFace.this.getResources(); switch (tapType) { case TAP_TYPE_TOUCH: // The user has started touching the screen. break; case TAP_TYPE_TOUCH_CANCEL: // The user has started a different gesture or otherwise cancelled the tap. break; case TAP_TYPE_TAP: // The user has completed the tap gesture. mTapCount++; mBackgroundPaint.setColor(resources.getColor(mTapCount % 2 == 0 ? R.color.background : R.color.primary)); break; } invalidate(); } @Override public void onDraw(Canvas canvas, Rect bounds) { // Draw the background. if (isInAmbientMode()) { canvas.drawColor(Color.BLACK); int ambientText = getResources().getColor(R.color.digital_text); mTimeView.setTextColor(ambientText); mHighView.setTextColor(ambientText); mDateView.setTextColor(ambientText); mLowView.setTextColor(ambientText); } else { canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint); int primaryText = getResources().getColor(R.color.primary_text); int secondaryText = getResources().getColor(R.color.secondary_text); mTimeView.setTextColor(primaryText); mHighView.setTextColor(primaryText); mDateView.setTextColor(secondaryText); mLowView.setTextColor(secondaryText); } //Set Time to now long now = System.currentTimeMillis(); mCalendar.setTimeInMillis(now); int hour = mCalendar.get(Calendar.HOUR); int minutes = mCalendar.get(Calendar.MINUTE); int seconds = mCalendar.get(Calendar.SECOND); String dateText = mDateFormat.format(mDate); String suffix = "\u00B0"; // If in ambient mode do not show seconds String time = mAmbient?String.format("%d:%02d", hour, minutes):String.format("%d:%02d:%02d", hour, minutes, seconds); String highString = String.format("%d"+suffix, mHighTemp); String lowString = String.format("%d"+suffix, mLowTemp); mTimeView.setText(time); mTimeView.setTextSize(mHighlightSize); mDateView.setText(dateText); mDateView.setTextSize(mStandardSize); mHighView.setText(highString); mHighView.setTextSize(mStandardSize); mLowView.setText(lowString); mLowView.setTextSize(mStandardSize); mIconView.setImageBitmap(mIcon); //This is necessary to be able to use xml layout file mRootView.measure(mSpecW, mSpecH); mRootView.layout(0, 0, mRootView.getMeasuredWidth(), mRootView.getMeasuredHeight()); mRootView.draw(canvas); } /** * Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently * or stops it if it shouldn't be running but currently is. */ private void updateTimer() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); if (shouldTimerBeRunning()) { mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME); } } /** * Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should * only run when we're visible and in interactive mode. */ private boolean shouldTimerBeRunning() { return isVisible() && !isInAmbientMode(); } /** * Handle updating the time periodically in interactive mode. */ private void handleUpdateTimeMessage() { invalidate(); if (shouldTimerBeRunning()) { long timeMs = System.currentTimeMillis(); long delayMs = INTERACTIVE_UPDATE_RATE_MS - (timeMs % INTERACTIVE_UPDATE_RATE_MS); mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs); } } } }
38.094937
129
0.633715
958e24da70f6d3a8272267171d87ac01f68a907a
5,594
/* Copyright 2017 Zutubi Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zutubi.pulse.master.tove.config.project.reports; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Maps; import com.zutubi.pulse.core.model.Result; import com.zutubi.pulse.master.charting.model.DataPoint; import com.zutubi.pulse.master.charting.model.SeriesData; import com.zutubi.pulse.master.model.BuildResult; import com.zutubi.util.adt.Pair; import com.zutubi.util.math.AggregationFunction; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Implementation of {@link ReportContext} which handles both build and stage metrics and * separating/aggregating stage values. When using for stage metrics, the stage name must be set * before the metric is evaluated for that stage (see {@link #setStageName(String)}. */ public class DefaultReportContext implements ReportContext { private String customColour; private AggregationFunction aggregationFunction; private CustomFieldSource fieldSource; private Map<String, SeriesData> seriesDataByField = Maps.newLinkedHashMap(); private BuildResult currentBuild; private ListMultimap<String, Number> currentBuildValues = ArrayListMultimap.create(); private String stageName = null; /** * Creates a new context to collect values for the given series configuration. * * @param config configuration of the series to gather metrics for * @param fieldSource source of custom field values, used as a delegate */ public DefaultReportContext(ReportSeriesConfiguration config, CustomFieldSource fieldSource) { this.customColour = config.isUseCustomColour() ? config.getCustomColour() : null; if (config instanceof StageReportSeriesConfiguration) { StageReportSeriesConfiguration stageConfig = (StageReportSeriesConfiguration) config; if (stageConfig.isCombineStages()) { aggregationFunction = stageConfig.getAggregationFunction(); } } this.fieldSource = fieldSource; } public String getFieldValue(Result result, String name) { return fieldSource.getFieldValue(result, name); } public List<Pair<String, String>> getAllFieldValues(Result result, Pattern namePattern) { return fieldSource.getAllFieldValues(result, namePattern); } public void addMetricValue(String name, BuildResult build, Number value) { if (aggregationFunction == null) { String series = name; if (stageName != null) { series += " (" + stageName + ")"; } addDataPoint(series, build.getNumber(), value); } else { if (build != currentBuild) { aggregateCurrentValues(); currentBuild = build; } currentBuildValues.put(name, value); } } private void aggregateCurrentValues() { if (currentBuild != null) { Map<String, Collection<Number>> valueMap = currentBuildValues.asMap(); for (String seriesName: valueMap.keySet()) { List<Number> values = currentBuildValues.get(seriesName); if (!values.isEmpty()) { addDataPoint(seriesName, currentBuild.getNumber(), aggregationFunction.aggregate(values)); } } // This cannot be done in the above loop as it modifies the collection. We just empty the collection as it // is likely to be reused later as future builds will have similar series'. for (Collection<Number> values: valueMap.values()) { values.clear(); } currentBuild = null; } } private void addDataPoint(String seriesName, long buildNumber, Number value) { SeriesData seriesData = seriesDataByField.get(seriesName); if (seriesData == null) { seriesData = new SeriesData(seriesName, customColour); seriesDataByField.put(seriesName, seriesData); } seriesData.addPoint(new DataPoint(buildNumber, value)); } /** * Sets the current stage name. This must be called before evaluating a metric for a stage. * * @param stageName the name of the stage */ public void setStageName(String stageName) { this.stageName = stageName; } /** * Gets all metric data added to this context as resolved series', ready for entering into a * report. * * @return all metric data collected by this context */ public Collection<SeriesData> getAllSeriesData() { // Catch any values from the last build. aggregateCurrentValues(); return seriesDataByField.values(); } }
33.90303
119
0.656596
81d854d0354da8cbed969f521bf97797114432ab
3,065
package com.service.back; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.HqlDAO; import com.dao.ShuangseqiuKjggDAO; import com.pojo.ShuangseqiuKjgg; @Service public class CaiPiaoService { @Autowired private HqlDAO hqldao; @Autowired private ShuangseqiuKjggDAO shuangseqiuqishuDAO; public Map getAllkaijiang(String kjQishu, Timestamp mintime, Timestamp maxtime) { StringBuffer sb = new StringBuffer(); List listparam = new ArrayList(); sb.append(" where 1=1 "); if (kjQishu != null && kjQishu.trim().length() > 0) { sb.append("and time like ?"); listparam.add("%" + kjQishu + "%"); } if (mintime != null) { sb.append("and time>=?"); listparam.add(mintime); } if (maxtime != null) { sb.append(" and time<=?"); listparam.add(maxtime); } String sumHQL = "select count(*) from ShuangseqiuKjgg" + sb.toString(); List sumList = hqldao.query(sumHQL, listparam.toArray()); Object obj = sumList.get(0); int sum = Integer.parseInt(obj.toString()); if (sum < 1) return new HashMap(); // int count = sum%size==0 ? sum/size : sum/size+1; // // //越界检查 // if(page<1) page=1; // if(page>count) page=count; String hql = "from ShuangseqiuKjgg" + sb.toString() + " order by id desc"; List list = hqldao.query(hql, listparam.toArray()); Map map = new HashMap(); // map.put("size", size); // map.put("page", page); // map.put("count", count); map.put("sum", sum); map.put("list", list); return map; } public List getMaxQishu() { String hql = "select max(s.qihao) from ShuangseqiuKjgg s"; List list = hqldao.query(hql); return list; } public void updateKaiJiang(String blue, String oneRed, String twoRed, String threeRed, String fourRed, String fiveRed, String sixRed, String qishu) { // TODO Auto-generated method stub ShuangseqiuKjgg shuangseqiuqishu = new ShuangseqiuKjgg(); shuangseqiuqishu.setQihao(qishu); shuangseqiuqishu.setHongqiu1(oneRed); shuangseqiuqishu.setHongqiu2(twoRed); shuangseqiuqishu.setHongqiu3(threeRed); shuangseqiuqishu.setHongqiu4(fourRed); shuangseqiuqishu.setHongqiu5(fiveRed); shuangseqiuqishu.setHongqiu6(sixRed); shuangseqiuqishu.setLanqiu(blue); Date date = new Date(); Timestamp timestamp = new Timestamp(date.getTime()); shuangseqiuqishu.setKaijiangTime(timestamp); shuangseqiuqishuDAO.merge(shuangseqiuqishu); } public void delete(String kjId) { // TODO Auto-generated method stub String hql = "delete from ShuangseqiuKjgg where id in ("+kjId+")"; hqldao.bulkUpdate(hql); } public List getKaiJiangById(int id) { String hql = "from ShuangseqiuKjgg where id = ?"; List list=hqldao.findByHQL(hql, id); return list; } public void updateKaiJiang1(ShuangseqiuKjgg shuangseqiuqishu) { // TODO Auto-generated method stub shuangseqiuqishuDAO.merge(shuangseqiuqishu); } }
28.37963
103
0.711582
b27bd822b38093a6eddc23bbb64adc7c919dd88c
2,350
package io.github.belmomusta.validation.validator; import io.github.belmomusta.validation.annotation.Validation; import io.github.belmomusta.validation.criteria.Criteria; import io.github.belmomusta.validation.criteria.Criterion; import io.github.belmomusta.validation.enumeration.ErrorMessage; import io.github.belmomusta.validation.exception.ValidationException; import io.github.belmomusta.validation.utils.ReflectUtils; import java.lang.reflect.Field; import java.util.List; /** * CriteriaValidator class to perform validation over objects. * * @author Belmokhtar * @since 0.0.0.SNAPSHOT * @version 0.0.0 */ public class AnnotationValidator<T> extends CriteriaValidator<T> { /** * {@inheritDoc} */ @Override public boolean check(T object) throws ValidationException { Criteria<T> criteria = createCriteria(object); return super.check(criteria); } /** * {@inheritDoc} */ @Override public ValidationReport getValidationReport(T object) throws ValidationException { Criteria<T> criteria = createCriteria(object); return super.getValidationReport(criteria); } /** * Creates a {@link Criteria } object from the object in parameters * * @param object * @return {@link Criteria} * @throws ValidationException if validation is not successful */ private Criteria<T> createCriteria(T object) throws ValidationException { if (object == null) { throw new ValidationException(ErrorMessage.NULL_OBJECT_MSG.getLabel()); } final List<Field> annotatedFields = ReflectUtils.getAnnotatedFields(object.getClass(), Validation.class); Criteria<T> criteria = new Criteria<>(); criteria.setObject(object); for (Field field : annotatedFields) { final Object currentValue; try { currentValue = field.get(object); } catch (IllegalAccessException e) { throw new ValidationException(e); } final Validation validation = field.getAnnotation(Validation.class); final Criterion criterion = Criterion.of(field.getName()).operator(validation.operator()).found(currentValue).expected(validation.value()); criteria.add(criterion); } return criteria; } }
35.074627
151
0.682979
f723c44907aa40d777ec1d8f95dcfee24ee30b9f
2,296
/* * JBoss, Home of Professional Open Source * * Copyright 2013 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.picketlink.test.identity.federation.api.util; import junit.framework.TestCase; import org.picketlink.identity.federation.api.util.KeyUtil; import org.w3c.dom.Element; import java.io.InputStream; import java.security.KeyStore; import java.security.cert.Certificate; /** * Unit test the Key Util * * @author [email protected] * @since Apr 29, 2009 */ public class KeyUtilUnitTestCase extends TestCase { /** * Keystore (created 15Jan2009 and valid for 200K days) The Keystore has been created with the command (all in one * line) * keytool -genkey -alias servercert -keyalg RSA -keysize 1024 -dname * "CN=jbossidentity.jboss.org,OU=RD,O=JBOSS,L=Chicago,S=Illinois,C=US" -keypass test123 -keystore * jbid_test_keystore.jks * -storepass store123 -validity 200000 */ private String keystoreLocation = "keystore/jbid_test_keystore.jks"; private String keystorePass = "store123"; private String alias = "servercert"; public void testCertificate() throws Exception { ClassLoader tcl = Thread.currentThread().getContextClassLoader(); InputStream ksStream = tcl.getResourceAsStream(keystoreLocation); assertNotNull("Input keystore stream is not null", ksStream); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(ksStream, keystorePass.toCharArray()); assertNotNull("KeyStore is not null", ks); Certificate cert = ks.getCertificate(alias); assertNotNull("Cert not null", cert); Element keyInfo = KeyUtil.getKeyInfo(cert); assertNotNull(keyInfo); } }
36.444444
118
0.72169
cd65b3dbd47ca041d2b2dfb9456404226aba3405
1,589
package de.dytanic.cloudnet.driver.network.def.packet; import de.dytanic.cloudnet.common.document.gson.JsonDocument; import de.dytanic.cloudnet.driver.network.def.PacketConstants; import de.dytanic.cloudnet.driver.network.protocol.Packet; import de.dytanic.cloudnet.driver.service.ServiceEnvironmentType; import java.util.UUID; public final class PacketClientServerChannelMessage extends Packet { public PacketClientServerChannelMessage(String channel, String message, JsonDocument data) { super(PacketConstants.INTERNAL_EVENTBUS_CHANNEL, new JsonDocument("channel", channel).append("message", message).append("data", data), null); } public PacketClientServerChannelMessage(UUID targetServiceId, String channel, String message, JsonDocument data) { super(PacketConstants.INTERNAL_EVENTBUS_CHANNEL, new JsonDocument("channel", channel).append("message", message).append("data", data).append("uniqueId", targetServiceId), null); } public PacketClientServerChannelMessage(String taskName, String channel, String message, JsonDocument data) { super(PacketConstants.INTERNAL_EVENTBUS_CHANNEL, new JsonDocument("channel", channel).append("message", message).append("data", data).append("task", taskName), null); } public PacketClientServerChannelMessage(ServiceEnvironmentType environment, String channel, String message, JsonDocument data) { super(PacketConstants.INTERNAL_EVENTBUS_CHANNEL, new JsonDocument("channel", channel).append("message", message).append("data", data).append("environment", environment), null); } }
56.75
185
0.786029
74d2cfd32b14fedf70822387261fa290798175d3
2,771
package org.gmu.context; import android.location.Location; import android.os.Bundle; import org.gmu.control.Controller; import org.gmu.dao.OrderDefinition; import org.gmu.map.MapPosition; import org.gmu.pojo.NavigationItem; import org.gmu.pojo.PlaceElement; import org.gmu.utils.Utils; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * User: ttg * Date: 8/01/13 * Time: 12:20 * Contains context variables, representing application state */ public class GmuContext implements Serializable { private String currentGuide = null; private transient boolean updateInProgress=false; public PlaceElement filter = new PlaceElement(); public Integer playingAudio; public String[] playList; public Stack<NavigationItem> navigationStack = new Stack(); public String selectedChild = null; public String playingUID = null; public transient Location lastUserLocation; public transient float lastUserViewAngle=0; public long lastUpdated = 0; public boolean offlineMode = false; public boolean onlyGuidesDownloadedFilter = true; public String selectedListUID=null; public String lastPrivateGuideAccessed; public MapPosition lastMapCenterLocation; public OrderDefinition order=new OrderDefinition(); //script that will be fired on the next microsite load public Map<String,String> targetedScriptInvocations=new HashMap<String, String>(); public void setOnlyGuidesDownloadedFilter(boolean onlyGuidesDownloadedFilter) { this.onlyGuidesDownloadedFilter = onlyGuidesDownloadedFilter; if (filter != null) { this.filter.getAttributes().put("guidedownloaded", ("" + onlyGuidesDownloadedFilter).toUpperCase()); } } public GmuContext() { lastUserLocation = null; } public void serializeToBundle(Bundle bundle) { String serial = Utils.objectToString(this); bundle.putString("gmucontext", serial); } public static GmuContext deserializeFromBundle(Bundle bundle) { return (GmuContext) Utils.stringToObject(bundle.getString("gmucontext")); } public void setCurrentGuide(String currentGuide) { this.currentGuide = currentGuide; ((NavigationItem) navigationStack.peek()).guideuid=currentGuide; } public String getCurrentGuide() { return currentGuide; } public String toString() { return "Current guide="+currentGuide+"\n"+ "Stack size="+navigationStack.size(); } public boolean isUpdateInProgress() { return updateInProgress; } public void setUpdateInProgress(boolean updateInProgress) { this.updateInProgress = updateInProgress; } }
30.788889
112
0.717791
7788b6d959f0ce6fd3f6478992206d9542a4ef77
2,979
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 756. Pyramid Transition Matrix * * We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. * For every block of color `C` we place not in the bottom row, * we are placing it on top of a left block of color `A` and right block of color `B`. * We are allowed to place the block there only if `(A, B, C)` is an allowed triple. * We start with a bottom row of bottom, * represented as a single string. We also start with a list of allowed triples allowed. * Each allowed triple is represented as a string of length 3. * Return true if we can build the pyramid all the way to the top, otherwise false. Example 1: Input: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"] Output: true Explanation: We can stack the pyramid like this: A / \ D E / \ / \ X Y Z This works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples. Example 2: Input: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"] Output: false Explanation: We can't stack the pyramid to the top. Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D. Note: bottom will be a string with length in range [2, 8]. allowed will have length in range [0, 200]. Letters in all strings will be chosen from the set {'A', 'B', 'C', 'D', 'E', 'F', 'G'}. */ public class _756 { public static class Solution1 { /**credit: https://discuss.leetcode.com/topic/116042/java-solution-map-backtracking*/ public boolean pyramidTransition(String bottom, List<String> allowed) { Map<String, List<String>> map = new HashMap<>(); for (String s : allowed) { String key = s.substring(0, 2); if (!map.containsKey(key)) { map.put(key, new ArrayList<>()); } map.get(key).add(s.substring(2)); } return helper(bottom, map); } private boolean helper(String bottom, Map<String, List<String>> map) { if (bottom.length() == 1) { return true; } for (int i = 0; i < bottom.length() - 1; i++) { if (!map.containsKey(bottom.substring(i, i + 2))) { return false; } } List<String> ls = new ArrayList<>(); getList(bottom, 0, new StringBuilder(), ls, map); for (String s : ls) { if (helper(s, map)) { return true; } } return false; } private void getList(String bottom, int idx, StringBuilder sb, List<String> ls, Map<String, List<String>> map) { if (idx == bottom.length() - 1) { ls.add(sb.toString()); return; } for (String s : map.get(bottom.substring(idx, idx + 2))) { sb.append(s); getList(bottom, idx + 1, sb, ls, map); sb.deleteCharAt(sb.length() - 1); } } } }
31.691489
109
0.598859
df943bbc67e679f18519805916adfbf10c30b31a
1,755
package eu.minemania.watson.chat; import java.util.ArrayList; import eu.minemania.watson.analysis.CoreProtectAnalysis; import eu.minemania.watson.analysis.LbCoordsAnalysis; import eu.minemania.watson.analysis.LbToolBlockAnalysis; import eu.minemania.watson.analysis.ModModeAnalysis; import eu.minemania.watson.analysis.RatioAnalysis; import eu.minemania.watson.analysis.RegionInfoAnalysis; import eu.minemania.watson.analysis.ServerTime; import eu.minemania.watson.analysis.TeleportAnalysis; import eu.minemania.watson.config.Configs; import net.minecraft.util.text.ITextComponent; public class ChatProcessor { private static ChatProcessor INSTANCE = new ChatProcessor(); protected ArrayList<IChatHandler> _handlers = new ArrayList<IChatHandler>(); private ChatProcessor() { addChatHandler(new LbCoordsAnalysis()); addChatHandler(new LbToolBlockAnalysis()); addChatHandler(new TeleportAnalysis()); addChatHandler(new RatioAnalysis()); addChatHandler(ServerTime.getInstance()); addChatHandler(new ModModeAnalysis()); addChatHandler(new RegionInfoAnalysis()); addChatHandler(new CoreProtectAnalysis()); } public static ChatProcessor getInstance() { return INSTANCE; } public void addChatHandler(IChatHandler handler) { _handlers.add(handler); } public boolean onChat(ITextComponent chat) { if (Configs.Generic.ENABLED.getBooleanValue()) { boolean allow = true; for (IChatHandler handler : _handlers) { allow &= handler.onChat(chat); } return allow; } else { return true; } } }
28.770492
80
0.688889
2aa1ceaf8212de162c9a7ced53f52c9a307a5472
1,094
package com.ssm.service.impl; import com.github.pagehelper.Page; import com.ssm.dao.UserInfoDao; import com.ssm.entity.po.UserInfoPo; import com.ssm.service.UserInfoService; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("userInfoService") public class UserInfoServiceImpl implements UserInfoService { @Autowired public UserInfoDao userInfoDao; @Override public Page<UserInfoPo> selectPaged(RowBounds rowBounds) { return userInfoDao.selectPaged(rowBounds); } @Override public UserInfoPo selectByPrimaryKey(Integer id) { return userInfoDao.selectByPrimaryKey(id); } @Override public Integer deleteByPrimaryKey(Integer id) { return userInfoDao.deleteByPrimaryKey(id); } @Override public Integer insert(UserInfoPo userInfo) { return userInfoDao.insert(userInfo); } @Override public UserInfoPo selectByName(String name) { return userInfoDao.selectByName(name); } }
25.44186
62
0.74223
c100d3a6d03b2dd294587ce74e1b5ab5b01c0635
510
/** @lc id : 206 @problem : Reverse Linked List @author : github.com/rohitkumar-rk @url : https://leetcode.com/problems/reverse-linked-list/ @difficulty : easy @tags : Linked List */ class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode finalHead = reverseList(head.next); ListNode temp = head.next; temp.next = head; head.next = null; return finalHead; } }
20.4
57
0.601961
dacd75bc77b46c6f3222f58e339a61c6fd720f64
1,558
/* * Copyright 2017 Hippo B.V. (http://www.onehippo.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 org.hippoecm.frontend.plugins.richtext.htmlprocessor; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.request.cycle.RequestCycle; import org.onehippo.cms7.services.htmlprocessor.richtext.URLEncoder; public class WicketURLEncoder implements URLEncoder { public static final URLEncoder INSTANCE = new WicketURLEncoder(); private WicketURLEncoder() {} @Override public String encode(final String url) { String[] elements = StringUtils.split(url, '/'); for (int i = 0; i < elements.length; i++) { elements[i] = org.apache.wicket.util.encoding.UrlEncoder.PATH_INSTANCE.encode(elements[i], "UTF-8"); } final String encodedUrl = StringUtils.join(elements, '/'); RequestCycle requestCycle = RequestCycle.get(); return requestCycle != null ? requestCycle.getResponse().encodeURL(encodedUrl).toString() : encodedUrl; } }
38.95
112
0.715661
25a89150828058f7b9e1f89b4dd18a44de4dd1ba
232
package de.dieklaut.camtool.renderjob; import java.io.IOException; import java.nio.file.Path; public class NullRenderJob extends RenderJob { @Override void storeImpl(Path destination) throws IOException { // do nothing } }
16.571429
54
0.771552
220458422cf52cc692a47f65c858eb7ad0f3f7e1
853
package entity; import java.io.*; import javax.persistence.*; @Embeddable public class VoterDetail implements Serializable{ private String nrc, township, city, phoneno; public VoterDetail(){} public String getNrc() { return nrc; } public void setNrc(String nrc) { this.nrc = nrc; } public String getTownship() { return township; } public void setTownship(String township) { this.township = township; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPhoneno() { return phoneno; } public void setPhoneno(String phoneno) { this.phoneno = phoneno; } @Override public String toString() { return "nrc=" + nrc + ", township=" + township + ", city=" + city + ", phoneno=" + phoneno; } }
16.403846
94
0.631887
05e537b00abb0fe678a719a852e6751aa6919a8b
126
package com.ruoyi.system.domain; import lombok.Data; /** * 打印机实体类 */ @Data public class Printer { Integer shopId; }
9
32
0.666667
f2fb21a35263c0709690c4492174d5599b3adc23
1,576
package com.bradmcevoy.http.http11; import com.bradmcevoy.http.Resource; /** * Generates ETags, ie entity tags. * * Custom implementations must be injected into: * - DefaultHttp11ResponseHandler * - DefaultWebDavPropertySource * * .. or whatever you're using in their place * * Note that the Http11ResponseHandler interface extends this, since it response * handlers logically must know how to generate etags (or that they shouldnt be * generated) and it assists with wrapping to expose that functionality, without * exposing the dependency directly. * * * HTTP/1.1 origin servers: - SHOULD send an entity tag validator unless it is not feasible to generate one. - MAY send a weak entity tag instead of a strong entity tag, if performance considerations support the use of weak entity tags, or if it is unfeasible to send a strong entity tag. - SHOULD send a Last-Modified value if it is feasible to send one, unless the risk of a breakdown in semantic transparency that could result from using this date in an If-Modified-Since header would lead to serious problems. * * @author brad */ public interface ETagGenerator { /** * ETag's serve to identify a particular version of a particular resource. * * If the resource changes, or is replaced, then this value should change * * @param r - the resource to generate the ETag for * @return - an ETag which uniquely identifies this version of this resource */ String generateEtag( Resource r ); }
34.26087
80
0.711294
7591ea27f23412e7192032354ad52e338d4fc280
566
package harry.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.springframework.util.StringUtils; /** * * @author harry * */ public class CookieUtil { public static String getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if (cookies == null || StringUtils.isEmpty(name)) { return null; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } }
18.866667
75
0.65371
79eea1052f219256b72148ba2641735f1c775857
2,159
/** * */ package com.unionpay.orderprocess; import org.apache.log4j.Logger; import com.interactiontimes.database.OrderStatus; import com.pay.orderprocesschoose.OrderProcess; import com.pay.utiles.OrderInfoHttpTransfer; //import com.pay.utiles.XmlDocResolution; import com.unionpay.unionpayinfo.UnionPayInfo; import com.unionpay.unionpayinfo.UnionPayNotifyQueryTelegramModel; import com.unionpay.unionpayinfo.UnionPayNotifyXmlTelegramResolution; import com.unionpay.unionpayinfo.UnionXmlTelegram; //import com.unionpay.utiles.UnionPayVerfinSign; /** * @author Podevor * */ public class UnionPayOrderCheckProcess { public static String OrderCheckProcess(String xml){ Logger.getLogger(OrderProcess.class.getClass()).info("银联前置通知报文处理——解析报文"+xml); String checkOrderResult = OrderStatus.FAILURE; if(!"".equals(xml) && xml != null){ UnionPayNotifyXmlTelegramResolution unionPayXmlTelegram = new UnionPayNotifyXmlTelegramResolution(xml); UnionPayNotifyQueryTelegramModel unionPayNotifyQueryTelegram = unionPayXmlTelegram.getUnionPayNotifyQueryTelegramModel(); String respCodetoUnionServer = "1111"; if (/*0000".equals(unionPayNotifyQueryTelegram.getRespCode()) && */"00".equals(unionPayNotifyQueryTelegram.getCupsRespCode())) { //sign //String src = UnionXmlTelegram.getNotifySourceSign(unionPayNotifyQueryTelegram); //String sign = XmlDocResolution.getValueInXml(xml, "sign"); //verify data boolean verfied = true;//UnionPayVerfinSign.verifySign(UnionPayInfo.getMerchantPublicCerPath(), sign, src); if (verfied) { //verfy success respCodetoUnionServer = "0000"; checkOrderResult = OrderStatus.SUCCESS; } } //connect to the union server OrderInfoHttpTransfer connectUnionServer = new OrderInfoHttpTransfer(UnionPayInfo.getUnionServerUrl(), UnionPayInfo.getUnionServerTimeOut()); //update the merchantOrderId by from union notify telegram UnionPayInfo.setMerchantOrderId(unionPayNotifyQueryTelegram.getMerchantOrderId()); String telegram = UnionXmlTelegram.getVerifyRspTelegram(respCodetoUnionServer); connectUnionServer.sendMsg(telegram); } return checkOrderResult; } }
41.519231
144
0.794812
ac22adeecf429e0db155a01c031e91663a55c618
2,262
package ru.job4j.collections.pro.map; import java.util.Calendar; /** * Класс User3. * * @author Анастасия Гладун * @since 24.07.2017 */ public class User3 { private String name; private int children; private Calendar birthday; public User3(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } @Override public boolean equals(Object o) { if (o == this) {// проверяем равны ли ссылки на два объекта. Если ссылки равны, то объект один. Возвращаем true. return true; } if (o == null || o.getClass() != getClass()) {// если переменная o содержит пустую ссылку(то есть мы сравниваем объект с null), return false; // то возвращаем false. } // если классы двух сравниваемых объектов не равны, то возвращаем false. User3 user = (User3) o; // производим сужение типа Object до User3. if (name != null ? !name.equals(user.name) : user.name != null) { // Далее начинаем сравнивать поля объектов. return false;// если поле name не равно null, то сравниваем эти поля объектов. Если они не равны(по методу equals), } // то объекты не проходят проверку equals. Возвращаем false. В проверке других полей нет смысла. // если поле name равно null, а поле name другого объета не равно null, то возвращаем false. if (children != user.children) { // так как поле children не объектного типа, то для него достаточно проверки по одному условию. return false; // если поля не равны, то возвращаем false. } return birthday != null ? birthday.equals(user.birthday) : user.birthday == null; // если поле birthday не равно null, то сравниваем эти поля объектов. Если они не равны(по методу equals), // то объекты не проходят проверку equals. Возвращаем false. Так как это последнее проверяемое поле, то в противном случае возвращаем true. // если поле birthday равно null, а поле birthday другого объета не равно null, то возвращаем false. В противном случае возвращаем true. } }
51.409091
147
0.635279
a63458fe62a438eaf5eddb27a28a3635cd869ede
52,987
/* * @(#)Cubes.java * CubeTwister. Copyright © 2020 Werner Randelshofer, Switzerland. MIT License. */ package ch.randelshofer.rubik.cube; import ch.randelshofer.math.IntMath; import ch.randelshofer.rubik.CubeAttributes; import ch.randelshofer.rubik.notation.Notation; import ch.randelshofer.rubik.notation.Symbol; import ch.randelshofer.rubik.notation.Syntax; import org.jhotdraw.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This class provides static utility methods for Cube objects. * * @author Werner Randelshofer */ public class Cubes { /** * Creates a cube with the specified layer count. */ @Nonnull public static Cube create(int layerCount) { String n; switch (layerCount) { case 2: n = "ch.randelshofer.rubik.PocketCube"; break; case 3: n = "ch.randelshofer.rubik.RubiksCube"; break; case 4: n = "ch.randelshofer.rubik.RevengeCube"; break; case 5: n = "ch.randelshofer.rubik.ProfessorCube"; break; case 6: n = "ch.randelshofer.rubik.Cube6"; break; case 7: n = "ch.randelshofer.rubik.Cube7"; break; default: throw new IllegalArgumentException("Unsupported layer count " + layerCount); } try { return (Cube) Class.forName(n).getConstructor().newInstance(); } catch (Exception ex) { InternalError e = new InternalError("Couldn't create cube " + n); e.initCause(ex); throw e; } } @Nonnull public static String toVisualPermutationString(@Nonnull Cube cube, @Nonnull Notation notation) { if (notation.isSupported(Symbol.PERMUTATION)) { return toVisualPermutationString(cube, notation.getSyntax(Symbol.PERMUTATION), notation.getToken(Symbol.FACE_R), notation.getToken(Symbol.FACE_U), notation.getToken(Symbol.FACE_F), notation.getToken(Symbol.FACE_L), notation.getToken(Symbol.FACE_D), notation.getToken(Symbol.FACE_B), notation.getToken(Symbol.PERMUTATION_PLUS), notation.getToken(Symbol.PERMUTATION_PLUSPLUS), notation.getToken(Symbol.PERMUTATION_MINUS), notation.getToken(Symbol.PERMUTATION_BEGIN), notation.getToken(Symbol.PERMUTATION_END), notation.getToken(Symbol.PERMUTATION_DELIMITER)); } else { return toVisualPermutationString(cube); } } @Nonnull private static String toVisualPermutationString(@Nonnull Cube cube, Syntax syntax, String tR, String tU, String tF, String tL, String tD, String tB, String tPlus, String tPlusPlus, String tMinus, String tBegin, String tEnd, String tDelimiter) { StringBuilder buf = new StringBuilder(); String corners = toCornerPermutationString(cube, syntax, tR, tU, tF, tL, tD, tB, tPlus, tPlusPlus, tMinus, tBegin, tEnd, tDelimiter); String edges = toEdgePermutationString(cube, syntax, tR, tU, tF, tL, tD, tB, tPlus, tPlusPlus, tMinus, tBegin, tEnd, tDelimiter); String sides = toVisualSidePermutationString(cube, syntax, tR, tU, tF, tL, tD, tB, tPlus, tPlusPlus, tMinus, tBegin, tEnd, tDelimiter); buf.append(corners); if (buf.length() > 0 && edges.length() > 0) { buf.append('\n'); } buf.append(edges); if (buf.length() > 0 && sides.length() > 0) { buf.append('\n'); } buf.append(sides); if (buf.length() == 0) { buf.append(tBegin); buf.append(tEnd); } return buf.toString(); } /** * Prevent instance creation. */ private Cubes() { } /** * Returns a number that describes the order * of the permutation of the supplied cube. * <p> * The order says how many times the permutation * has to be applied to the cube to get the * initial state. * * @param cube A cube * @return the order of the permutation of the cube */ public static int getOrder(@Nonnull Cube cube) { int[] cornerLoc = cube.getCornerLocations(); int[] cornerOrient = cube.getCornerOrientations(); int[] edgeLoc = cube.getEdgeLocations(); int[] edgeOrient = cube.getEdgeOrientations(); int[] sideLoc = cube.getSideLocations(); int[] sideOrient = cube.getSideOrientations(); int order = 1; boolean[] visitedLocs; int i, j, k, n, p; int prevOrient; int length; // determine cycle lengths of the current corner permutation // and compute smallest common multiple visitedLocs = new boolean[cornerLoc.length]; for (i = 0; i < 8; i++) { if (!visitedLocs[i]) { if (cornerLoc[i] == i && cornerOrient[i] == 0) { continue; } length = 1; visitedLocs[i] = true; prevOrient = 0; for (j = 0; cornerLoc[j] != i; j++) { } while (!visitedLocs[j]) { visitedLocs[j] = true; prevOrient = (prevOrient + cornerOrient[j]) % 3; length++; for (k = 0; cornerLoc[k] != j; k++) { } j = k; } prevOrient = (prevOrient + cornerOrient[i]) % 3; if (prevOrient != 0) { //order = IntMath.scm(order, 3); length *= 3; } order = IntMath.scm(order, length); } } // determine cycle lengths of the current edge permutation // and compute smallest common multiple visitedLocs = new boolean[edgeLoc.length]; for (i = 0, n = edgeLoc.length; i < n; i++) { if (!visitedLocs[i]) { if (edgeLoc[i] == i && edgeOrient[i] == 0) { continue; } length = 1; visitedLocs[i] = true; prevOrient = 0; for (j = 0; edgeLoc[j] != i; j++) { } while (!visitedLocs[j]) { visitedLocs[j] = true; prevOrient ^= edgeOrient[j]; length++; for (k = 0; edgeLoc[k] != j; k++) { } j = k; } if ((prevOrient ^ edgeOrient[i]) == 1) { //order = IntMath.scm(order, 2); length *= 2; } order = IntMath.scm(order, length); } } // determine cycle lengths of the current side permutation // and compute smallest common multiple visitedLocs = new boolean[sideLoc.length]; for (i = 0, n = sideLoc.length; i < n; i++) { if (!visitedLocs[i]) { if (sideLoc[i] == i && sideOrient[i] == 0) { continue; } length = 1; visitedLocs[i] = true; prevOrient = 0; for (j = 0; sideLoc[j] != i; j++) { } while (!visitedLocs[j]) { visitedLocs[j] = true; length++; prevOrient = (prevOrient + sideOrient[j]) % 4; for (k = 0; sideLoc[k] != j; k++) { } j = k; } prevOrient = (prevOrient + sideOrient[i]) % 4; switch (prevOrient) { case 0: // no sign break; case 1: // '-' sign //order = IntMath.scm(order, 4); length *= 4; break; case 2: // '++' sign //order = IntMath.scm(order, 2); length *= 2; break; case 3: // '+' sign //order = IntMath.scm(order, 4); length *= 4; break; } order = IntMath.scm(order, length); } } return order; } /** * Returns a number that describes the order * of the permutation of the supplied cube, * assuming that all stickers only have a solid * color, and that all stickers on the same face * have the same color. * <p> * On a cube with such stickers, we can * not visually determine the orientation of its * side parts, and we can not visually determine * a permutation of side parts of which all side * parts are on the same face of the cube. * <p> * The order says how many times the permutation * has to be applied to the cube to get the * initial state. * * @param cube A cube * @return the order of the permutation of the cube */ public static int getVisibleOrder(@Nonnull Cube cube) { int[] cornerLoc = cube.getCornerLocations(); int[] cornerOrient = cube.getCornerOrientations(); int[] edgeLoc = cube.getEdgeLocations(); int[] edgeOrient = cube.getEdgeOrientations(); int[] sideLoc = cube.getSideLocations(); int[] sideOrient = cube.getSideOrientations(); int order = 1; boolean[] visitedLocs; int i, j, k, n, p; int prevOrient; int length; // determine cycle lengths of the current corner permutation // and compute smallest common multiple visitedLocs = new boolean[cornerLoc.length]; for (i = 0, n = cornerLoc.length; i < n; i++) { if (!visitedLocs[i]) { if (cornerLoc[i] == i && cornerOrient[i] == 0) { continue; } length = 1; visitedLocs[i] = true; prevOrient = 0; for (j = 0; cornerLoc[j] != i; j++) { // search first permuted part } while (!visitedLocs[j]) { visitedLocs[j] = true; prevOrient = (prevOrient + cornerOrient[j]) % 3; length++; for (k = 0; cornerLoc[k] != j; k++) { } j = k; } prevOrient = (prevOrient + cornerOrient[i]) % 3; if (prevOrient != 0) { length *= 3; } order = IntMath.scm(order, length); } } // determine cycle lengths of the current edge permutation // and compute smallest common multiple visitedLocs = new boolean[edgeLoc.length]; for (i = 0, n = edgeLoc.length; i < n; i++) { if (!visitedLocs[i]) { if (edgeLoc[i] == i && edgeOrient[i] == 0) { continue; } length = 1; visitedLocs[i] = true; prevOrient = 0; for (j = 0; edgeLoc[j] != i; j++) { // search first permuted part } while (!visitedLocs[j]) { visitedLocs[j] = true; prevOrient ^= edgeOrient[j]; length++; for (k = 0; edgeLoc[k] != j; k++) { } j = k; } if ((prevOrient ^ edgeOrient[i]) == 1) { length *= 2; } order = IntMath.scm(order, length); } } // Determine cycle lengths of the current side permutation // and compute smallest common multiple. // - Ignore changes of orientation. // - Ignore side permutations which are entirely on same face. visitedLocs = new boolean[sideLoc.length]; List<Integer> facesInPermutation = new ArrayList<>(); for (i = 0, n = sideLoc.length; i < n; i++) { if (!visitedLocs[i]) { if (sideLoc[i] == i && sideOrient[i] == 0) { continue; } length = 1; visitedLocs[i] = true; facesInPermutation.clear(); facesInPermutation.add(sideLoc[i] % 6); for (j = 0; sideLoc[j] != i; j++) { // search first permuted part } while (!visitedLocs[j]) { visitedLocs[j] = true; length++; facesInPermutation.add(sideLoc[j] % 6); for (k = 0; sideLoc[k] != j; k++) { // search next permuted part } j = k; } if (length > 0) { // If all parts at a distance of 3 are on the same face, the length can be divided by 3. // If all parts at a distance of 2 are on the same face, the length can be divided by 2 // If all parts are in the same face, the length can be reduced to 1 int reducedLength = length; SubcycleSearch: for (int subcycleLength = 1; subcycleLength < length; subcycleLength++) { if (subcycleLength > 0 && length % subcycleLength == 0) { boolean canReduceLength = true; for (j = subcycleLength; j < length; j += subcycleLength) { for (k = 0; k < subcycleLength; k++) { if (facesInPermutation.get(j + k - subcycleLength) != facesInPermutation.get(j + k)) { canReduceLength = false; break; } } } if (canReduceLength) { reducedLength = subcycleLength; break SubcycleSearch; } } } order = IntMath.scm(order, reducedLength); } } } return order; } /** * Returns a String that describes the current * location of the stickers. Ignores the rotation * of the cube. */ @Nonnull public static String toNormalizedStickersString(@Nonnull Cube cube) { char[] faces = new char[]{'R', 'U', 'F', 'L', 'D', 'B'}; int[][] stickers = StickerCubes.rubiksCubeToStickers(((RubiksCube) cube)); // This map is used to normalize the // possibly rotated cube. int[] faceMap = new int[6]; for (int i = 0; i < 6; i++) { faceMap[stickers[i][4]] = i; } StringBuilder buf = new StringBuilder(); for (int i = 0; i < stickers.length; i++) { if (i != 0) { buf.append('\n'); } buf.append(faces[faceMap[stickers[i][4]]]); buf.append(':'); for (int j = 0; j < stickers[i].length; j++) { buf.append(faces[faceMap[stickers[i][j]]]); } } return buf.toString(); } /** * Returns a String that describes the current * location of the stickers. Ignores the rotation * of the cube. */ @Nonnull public static String toMappedStickersString(@Nonnull Cube cube, int[] mappings) { //char[] faces = new char[]{'F', 'R', 'D', 'B', 'L', 'U'}; char[] faces = new char[]{'R', 'U', 'F', 'L', 'D', 'B'}; int[][] stickers = getMappedStickers(cube, mappings); // This map is used to normalize the // possibly rotated cube. int[] faceMap = new int[6]; for (int i = 0; i < 6; i++) { faceMap[stickers[i][4]] = i; } StringBuilder buf = new StringBuilder(); for (int i = 0; i < stickers.length; i++) { if (i != 0) { buf.append('\n'); } buf.append(faces[faceMap[stickers[i][4]]]); buf.append(':'); for (int j = 0; j < stickers[i].length; j++) { if (stickers[i][j] == -1) { buf.append('.'); } else { buf.append(faces[faceMap[stickers[i][j]]]); } } } return buf.toString(); } /** * Returns the stickers reflecting the current permutation of the cube. * * @param mappings An array with sticker mappings. It must have the * same structure as described for method setStickers(). * @return Array of stickers: int[6][9]. Same structure as in method setStickers(). */ public static int[][] getMappedStickers(@Nonnull Cube cube, int[] mappings) { int[][] perFaceMappings = new int[6][cube.getLayerCount() * cube.getLayerCount()]; int index = 0; for (int face = 0; face < perFaceMappings.length; face++) { for (int sticker = 0; sticker < perFaceMappings[face].length; sticker++) { perFaceMappings[face][sticker] = mappings[index++]; } } return getMappedStickers(cube, perFaceMappings); } /** * Returns the stickers reflecting the current permutation of the cube. * * @param mappings An array with sticker mappings. It must have the * same structure as described for method setStickers(). * @return Array of stickers: int[6][9]. Same structure as in method setStickers(). */ public static int[][] getMappedStickers(@Nonnull Cube cube, int[][] mappings) { int[][] stickers = StickerCubes.rubiksCubeToStickers(((RubiksCube) cube)); int[][] mappedStickers = stickers.clone(); for (int face = 0; face < stickers.length; face++) { for (int sticker = 0; sticker < stickers[face].length; sticker++) { mappedStickers[face][sticker] = mappings[stickers[face][sticker]][sticker]; } } return mappedStickers; } public static int getFaceOfSticker(@Nonnull CubeAttributes attr, int stickerIndex) { int face; for (face = 0; face < attr.getFaceCount(); face++) { if (attr.getStickerOffset(face) > stickerIndex) { break; } } return face - 1; } /** * Returns a String describing the state of the cube using * Bandelow's English permutation notation. * * @param cube a cube * @return a permutation String */ @Nonnull public static String toPermutationString(@Nonnull Cube cube) { return toPermutationString(cube, Syntax.PRECIRCUMFIX, "r", "u", "f", "l", "d", "b", "+", "++", "-", "(", ")", ","); } @Nonnull public static String toVisualPermutationString(@Nonnull Cube cube) { return toVisualPermutationString(cube, Syntax.PRECIRCUMFIX, "r", "u", "f", "l", "d", "b", "+", "++", "-", "(", ")", ","); } @Nonnull public static String toPermutationString(@Nonnull Cube cube, @Nonnull Notation notation) { if (notation.isSupported(Symbol.PERMUTATION)) { return toPermutationString(cube, notation.getSyntax(Symbol.PERMUTATION), notation.getToken(Symbol.FACE_R), notation.getToken(Symbol.FACE_U), notation.getToken(Symbol.FACE_F), notation.getToken(Symbol.FACE_L), notation.getToken(Symbol.FACE_D), notation.getToken(Symbol.FACE_B), notation.getToken(Symbol.PERMUTATION_PLUS), notation.getToken(Symbol.PERMUTATION_PLUSPLUS), notation.getToken(Symbol.PERMUTATION_MINUS), notation.getToken(Symbol.PERMUTATION_BEGIN), notation.getToken(Symbol.PERMUTATION_END), notation.getToken(Symbol.PERMUTATION_DELIMITER)); } else { return toPermutationString(cube); } } @Nonnull public static String toCornerPermutationString(@Nonnull Cube cube, @Nonnull Notation notation) { if (notation.isSupported(Symbol.PERMUTATION)) { return toCornerPermutationString(cube, notation.getSyntax(Symbol.PERMUTATION), notation.getToken(Symbol.FACE_R), notation.getToken(Symbol.FACE_U), notation.getToken(Symbol.FACE_F), notation.getToken(Symbol.FACE_L), notation.getToken(Symbol.FACE_D), notation.getToken(Symbol.FACE_B), notation.getToken(Symbol.PERMUTATION_PLUS), notation.getToken(Symbol.PERMUTATION_PLUSPLUS), notation.getToken(Symbol.PERMUTATION_MINUS), notation.getToken(Symbol.PERMUTATION_BEGIN), notation.getToken(Symbol.PERMUTATION_END), notation.getToken(Symbol.PERMUTATION_DELIMITER)); } else { return toCornerPermutationString(cube); } } @Nonnull public static String toCornerPermutationString(@Nonnull Cube cube) { return toCornerPermutationString(cube, Syntax.PRECIRCUMFIX, "r", "u", "f", "l", "d", "b", "+", "++", "-", "(", ")", ","); } @Nonnull public static String toEdgePermutationString(@Nonnull Cube cube, @Nonnull Notation notation) { if (notation.isSupported(Symbol.PERMUTATION)) { return toEdgePermutationString(cube, notation.getSyntax(Symbol.PERMUTATION), notation.getToken(Symbol.FACE_R), notation.getToken(Symbol.FACE_U), notation.getToken(Symbol.FACE_F), notation.getToken(Symbol.FACE_L), notation.getToken(Symbol.FACE_D), notation.getToken(Symbol.FACE_B), notation.getToken(Symbol.PERMUTATION_PLUS), notation.getToken(Symbol.PERMUTATION_PLUSPLUS), notation.getToken(Symbol.PERMUTATION_MINUS), notation.getToken(Symbol.PERMUTATION_BEGIN), notation.getToken(Symbol.PERMUTATION_END), notation.getToken(Symbol.PERMUTATION_DELIMITER)); } else { return toEdgePermutationString(cube); } } @Nonnull public static String toEdgePermutationString(@Nonnull Cube cube) { return toEdgePermutationString(cube, Syntax.PRECIRCUMFIX, "r", "u", "f", "l", "d", "b", "+", "++", "-", "(", ")", ","); } @Nonnull public static String toSidePermutationString(@Nonnull Cube cube, @Nonnull Notation notation) { if (notation.isSupported(Symbol.PERMUTATION)) { return toSidePermutationString(cube, notation.getSyntax(Symbol.PERMUTATION), notation.getToken(Symbol.FACE_R), notation.getToken(Symbol.FACE_U), notation.getToken(Symbol.FACE_F), notation.getToken(Symbol.FACE_L), notation.getToken(Symbol.FACE_D), notation.getToken(Symbol.FACE_B), notation.getToken(Symbol.PERMUTATION_PLUS), notation.getToken(Symbol.PERMUTATION_PLUSPLUS), notation.getToken(Symbol.PERMUTATION_MINUS), notation.getToken(Symbol.PERMUTATION_BEGIN), notation.getToken(Symbol.PERMUTATION_END), notation.getToken(Symbol.PERMUTATION_DELIMITER)); } else { return toEdgePermutationString(cube); } } @Nonnull public static String toVisualSidePermutationString(@Nonnull Cube cube, @Nonnull Notation notation) { if (notation.isSupported(Symbol.PERMUTATION)) { return toVisualSidePermutationString(cube, notation.getSyntax(Symbol.PERMUTATION), notation.getToken(Symbol.FACE_R), notation.getToken(Symbol.FACE_U), notation.getToken(Symbol.FACE_F), notation.getToken(Symbol.FACE_L), notation.getToken(Symbol.FACE_D), notation.getToken(Symbol.FACE_B), notation.getToken(Symbol.PERMUTATION_PLUS), notation.getToken(Symbol.PERMUTATION_PLUSPLUS), notation.getToken(Symbol.PERMUTATION_MINUS), notation.getToken(Symbol.PERMUTATION_BEGIN), notation.getToken(Symbol.PERMUTATION_END), notation.getToken(Symbol.PERMUTATION_DELIMITER)); } else { return toEdgePermutationString(cube); } } @Nonnull public static String toSidePermutationString(@Nonnull Cube cube) { return toSidePermutationString(cube, Syntax.PRECIRCUMFIX, "r", "u", "f", "l", "d", "b", "+", "++", "-", "(", ")", ","); } /** * Returns a String describing the permutation cycles of the parts in a cube. * * @param cube * @param syntax * @param tR * @param tU * @param tF * @param tL * @param tD * @param tB * @param tPlus * @param tPlusPlus * @param tMinus * @param tBegin * @param tEnd * @param tDelimiter * @return */ @Nonnull private static String toPermutationString(@Nonnull Cube cube, Syntax syntax, String tR, String tU, String tF, String tL, String tD, String tB, String tPlus, String tPlusPlus, String tMinus, String tBegin, String tEnd, String tDelimiter) { StringBuilder buf = new StringBuilder(); String corners = toCornerPermutationString(cube, syntax, tR, tU, tF, tL, tD, tB, tPlus, tPlusPlus, tMinus, tBegin, tEnd, tDelimiter); String edges = toEdgePermutationString(cube, syntax, tR, tU, tF, tL, tD, tB, tPlus, tPlusPlus, tMinus, tBegin, tEnd, tDelimiter); String sides = toSidePermutationString(cube, syntax, tR, tU, tF, tL, tD, tB, tPlus, tPlusPlus, tMinus, tBegin, tEnd, tDelimiter); buf.append(corners); if (buf.length() > 0 && edges.length() > 0) { buf.append('\n'); } buf.append(edges); if (buf.length() > 0 && sides.length() > 0) { buf.append('\n'); } buf.append(sides); if (buf.length() == 0) { buf.append(tBegin); buf.append(tEnd); } return buf.toString(); } /** * Returns a String describing the permutation cycles of the corner * parts in a cube. * * @param cube * @param syntax * @param tR * @param tU * @param tF * @param tL * @param tD * @param tB * @param tPlus * @param tPlusPlus * @param tMinus * @param tBegin * @param tEnd * @param tDelimiter * @return */ @Nonnull private static String toCornerPermutationString(@Nonnull Cube cube, Syntax syntax, String tR, String tU, String tF, String tL, String tD, String tB, String tPlus, String tPlusPlus, String tMinus, String tBegin, String tEnd, String tDelimiter) { int[] cornerLoc = cube.getCornerLocations(); int[] edgeLoc = cube.getEdgeLocations(); int[] sideLoc = cube.getSideLocations(); int[] cornerOrient = cube.getCornerOrientations(); int[] edgeOrient = cube.getEdgeOrientations(); int[] sideOrient = cube.getSideOrientations(); int[] cycle = new int[Math.max(Math.max(cube.getCornerCount(), cube.getEdgeCount()), cube.getSideCount())]; int layerCount = cube.getLayerCount(); boolean hasEvenLayerCount = layerCount % 2 == 0; StringBuilder buf = new StringBuilder(); boolean[] visitedLocs; int i, j, k, l, p, n; int prevOrient; boolean isFirst; // describe the state changes of the corner parts String[][] corners = { {tU, tR, tF},// urf {tD, tF, tR},// dfr {tU, tB, tR},// ubr {tD, tR, tB},// drb {tU, tL, tB},// ulb {tD, tB, tL},// dbl {tU, tF, tL},// ufl {tD, tL, tF}// dlf }; visitedLocs = new boolean[cube.getCornerCount()]; isFirst = true; for (i = 0, n = cube.getCornerCount(); i < n; i++) { if (!visitedLocs[i]) { if (cornerLoc[i] == i && cornerOrient[i] == 0) { continue; } // gather a permutation cycle int cycleLength = 0; int cycleStart = 0; j = i; while (!visitedLocs[j]) { visitedLocs[j] = true; cycle[cycleLength++] = j; if (cornerLoc[j] < cornerLoc[cycle[cycleStart]]) { cycleStart = cycleLength - 1; } for (k = 0; cornerLoc[k] != j; k++) { } j = k; } // print the permutation cycle if (isFirst) { isFirst = false; } else { buf.append(' '); } if (syntax == Syntax.PREFIX) { // the sign of the cycle will be inserted before the opening bracket p = buf.length(); buf.append(tBegin); } else if (syntax == Syntax.PRECIRCUMFIX) { // the sign of the cycle will be inserted after the opening bracket buf.append(tBegin); p = buf.length(); } else { buf.append(tBegin); p = -1; } prevOrient = 0; for (k = 0; k < cycleLength; k++) { j = cycle[(cycleStart + k) % cycleLength]; if (k != 0) { buf.append(tDelimiter); prevOrient = (prevOrient + cornerOrient[j]) % 3; } switch (prevOrient) { case 0: buf.append(corners[j][0]); buf.append(corners[j][1]); buf.append(corners[j][2]); break; case 2: buf.append(corners[j][1]); buf.append(corners[j][2]); buf.append(corners[j][0]); break; case 1: buf.append(corners[j][2]); buf.append(corners[j][0]); buf.append(corners[j][1]); break; } } j = cycle[cycleStart]; prevOrient = (prevOrient + cornerOrient[j]) % 3; if (syntax == Syntax.POSTCIRCUMFIX) { // the sign of the cycle will be inserted before the closing bracket p = buf.length(); buf.append(tEnd); } else if (syntax == Syntax.SUFFIX) { // the sign of the cycle will be inserted after the closing bracket buf.append(tEnd); p = buf.length(); } else { buf.append(tEnd); } // insert cycle sign if (prevOrient != 0) { buf.insert(p, (prevOrient == 1) ? tMinus : tPlus); } } } return buf.toString(); } /** * Returns a String describing the permutation cycles of the edge parts * in a cube. */ @Nonnull private static String toEdgePermutationString(@Nonnull Cube cube, Syntax syntax, String tR, String tU, String tF, String tL, String tD, String tB, String tPlus, String tPlusPlus, String tMinus, String tBegin, String tEnd, String tDelimiter) { int[] edgeLoc = cube.getEdgeLocations(); int[] edgeOrient = cube.getEdgeOrientations(); int[] cycle = new int[Math.max(Math.max(cube.getCornerCount(), cube.getEdgeCount()), cube.getSideCount())]; int layerCount = cube.getLayerCount(); boolean hasEvenLayerCount = layerCount % 2 == 0; StringBuilder buf = new StringBuilder(); boolean[] visitedLocs; int i, j, k, l, p, n; int prevOrient; boolean isFirst; // describe the state changes of the edge parts if (edgeLoc.length > 0) { String[][] edges = { {tU, tR}, //"ur" {tR, tF}, //"rf" {tD, tR}, //"dr" {tB, tU}, //"bu" {tR, tB}, //"rb" {tB, tD}, //"bd" {tU, tL}, //"ul" {tL, tB}, //"lb" {tD, tL}, //"dl" {tF, tU}, //"fu" {tL, tF}, //"lf" {tF, tD} //"fd" }; visitedLocs = new boolean[cube.getEdgeCount()]; isFirst = true; int previousCycleStartEdge = -1; for (i = 0, n = cube.getEdgeCount(); i < n; i++) { if (!visitedLocs[i]) { if (edgeLoc[i] == i && edgeOrient[i] == 0) { continue; } // gather a permutation cycle int cycleLength = 0; int cycleStart = 0; j = i; while (!visitedLocs[j]) { visitedLocs[j] = true; cycle[cycleLength++] = j; if (previousCycleStartEdge == j % 12) { cycleStart = cycleLength - 1; } for (k = 0; edgeLoc[k] != j; k++) { } j = k; } previousCycleStartEdge = cycle[cycleStart] % 12; // print the permutation cycle if (isFirst) { isFirst = false; } else { buf.append(' '); } if (syntax == Syntax.PREFIX) { // the sign of the cycle will be inserted before the opening bracket p = buf.length(); buf.append(tBegin); } else if (syntax == Syntax.PRECIRCUMFIX) { // the sign of the cycle will be inserted after the opening bracket buf.append(tBegin); p = buf.length(); } else { buf.append(tBegin); p = -1; } prevOrient = 0; for (k = 0; k < cycleLength; k++) { j = cycle[(cycleStart + k) % cycleLength]; if (k != 0) { buf.append(tDelimiter); prevOrient ^= edgeOrient[j]; } if (prevOrient == 1) { buf.append(edges[j % 12][1]); buf.append(edges[j % 12][0]); } else { buf.append(edges[j % 12][0]); buf.append(edges[j % 12][1]); } if (hasEvenLayerCount) { buf.append(j / 12 + 1); } else { if (j >= 12) { buf.append(j / 12); } } } j = cycle[cycleStart]; if (syntax == Syntax.POSTCIRCUMFIX) { // the sign of the cycle will be inserted before the closing bracket p = buf.length(); buf.append(tEnd); } else if (syntax == Syntax.SUFFIX) { // the sign of the cycle will be inserted after the closing bracket buf.append(tEnd); p = buf.length(); } else { buf.append(tEnd); } // insert cycle sign if ((prevOrient ^ edgeOrient[j]) == 1) { buf.insert(p, tPlus); } } } } return buf.toString(); } /** * Returns a String describing the permutation cycles of the side parts * in the cube. */ @Nonnull private static String toSidePermutationString(@Nonnull Cube cube, Syntax syntax, String tR, String tU, String tF, String tL, String tD, String tB, String tPlus, String tPlusPlus, String tMinus, String tBegin, String tEnd, String tDelimiter) { int[] sideLoc = cube.getSideLocations(); int[] sideOrient = cube.getSideOrientations(); int[] cycle = new int[Math.max(Math.max(cube.getCornerCount(), cube.getEdgeCount()), cube.getSideCount())]; int layerCount = cube.getLayerCount(); boolean hasEvenLayerCount = layerCount % 2 == 0; StringBuilder buf = new StringBuilder(); boolean[] visitedLocs; int i, j, k, l, p, n; int prevOrient; boolean isFirst; if (sideLoc.length > 0) { // describe the state changes of the side parts String[] sides = new String[]{ tR, tU, tF, tL, tD, tB // r u f l d b }; String[] sideOrients = new String[]{ "", tMinus, tPlusPlus, tPlus }; visitedLocs = new boolean[cube.getSideCount()]; isFirst = true; // First Pass: Only print permutation cycles which lie on a single // face of the cube. // Second pass: Only print permutation cycles which don't lie on // a singe fass of the cube. for (int twoPass = 0; twoPass < 2; twoPass++) { Arrays.fill(visitedLocs, false); for (int byFaces = 0, nf = 6; byFaces < nf; byFaces++) { for (int byParts = 0, np = cube.getSideCount() / 6; byParts < np; byParts++) { i = byParts + byFaces * np; if (!visitedLocs[i]) { if (sideLoc[i] == i && sideOrient[i] == 0) { continue; } // gather a permutation cycle int cycleLength = 0; int cycleStart = 0; boolean isOnSingleFace = true; j = i; while (!visitedLocs[j]) { visitedLocs[j] = true; cycle[cycleLength++] = j; if (j % 6 != i % 6) { isOnSingleFace = false; } if (cycle[cycleStart] > j) { cycleStart = cycleLength - 1; } for (k = 0; sideLoc[k] != j; k++) { } j = k; } if (isOnSingleFace == (twoPass == 0)) { // print the permutation cycle if (isFirst) { isFirst = false; } else { buf.append(' '); } if (syntax == Syntax.PREFIX) { // the sign of the cycle will be inserted before the opening bracket p = buf.length(); buf.append(tBegin); } else if (syntax == Syntax.PRECIRCUMFIX) { // the sign of the cycle will be inserted after the opening bracket buf.append(tBegin); p = buf.length(); } else { buf.append(tBegin); p = -1; } prevOrient = 0; for (k = 0; k < cycleLength; k++) { j = cycle[(cycleStart + k) % cycleLength]; if (k != 0) { buf.append(tDelimiter); prevOrient = (prevOrient + sideOrient[j]) % 4; } if (syntax == Syntax.PREFIX || syntax == Syntax.PRECIRCUMFIX || syntax == Syntax.POSTCIRCUMFIX) { buf.append(sideOrients[prevOrient]); } buf.append(sides[j % 6]); if (syntax == Syntax.SUFFIX) { buf.append(sideOrients[prevOrient]); } if (hasEvenLayerCount) { buf.append(j / 6 + 1); } else { if (j >= 6) { buf.append(j / 6); } } } j = cycle[cycleStart]; prevOrient = (prevOrient + sideOrient[j]) % 4; if (syntax == Syntax.POSTCIRCUMFIX) { // the sign of the cycle will be inserted before the closing bracket p = buf.length(); buf.append(tEnd); } else if (syntax == Syntax.SUFFIX) { // the sign of the cycle will be inserted after the closing bracket buf.append(tEnd); p = buf.length(); } else { buf.append(tEnd); } // insert cycle sign if (prevOrient != 0) { buf.insert(p, sideOrients[prevOrient]); } } } } } } } return buf.toString(); } /** * Returns a String describing the permutation cycles of the side parts * in the cube. * <p> * XXX - This method is not properly implemented. It should ignore part * orientations. */ @Nonnull private static String toVisualSidePermutationString(@Nonnull Cube cube, Syntax syntax, String tR, String tU, String tF, String tL, String tD, String tB, String tPlus, String tPlusPlus, String tMinus, String tBegin, String tEnd, String tDelimiter) { int[] sideLoc = cube.getSideLocations(); int[] sideOrient = cube.getSideOrientations(); int[] cycle = new int[Math.max(Math.max(cube.getCornerCount(), cube.getEdgeCount()), cube.getSideCount())]; int layerCount = cube.getLayerCount(); boolean hasEvenLayerCount = layerCount % 2 == 0; StringBuilder buf = new StringBuilder(); boolean[] visitedLocs; int i, j, k; int prevOrient; boolean isFirst; if (sideLoc.length > 0) { // describe the state changes of the side parts String[] sides = new String[]{ tR, tU, tF, tL, tD, tB // r u f l d b }; String[] sideOrients = new String[]{ "", tMinus, tPlusPlus, tPlus }; visitedLocs = new boolean[cube.getSideCount()]; isFirst = true; int previousCycleStartSide; // First Pass: Only print permutation cycles which lie on a single // face of the cube. // Second pass: Only print permutation cycles which don't lie on // a singe fass of the cube. for (int twoPass = 0; twoPass < 2; twoPass++) { Arrays.fill(visitedLocs, false); for (int byFaces = 0, nf = 6; byFaces < nf; byFaces++) { previousCycleStartSide = -1; for (int byParts = 0, np = cube.getSideCount() / 6; byParts < np; byParts++) { i = byParts + byFaces * np; if (!visitedLocs[i]) { if (sideLoc[i] == i && sideOrient[i] == 0) { continue; } // gather a permutation cycle int cycleLength = 0; int cycleStart = 0; boolean isOnSingleFace = true; j = i; while (!visitedLocs[j]) { visitedLocs[j] = true; cycle[cycleLength++] = j; if (j % 6 != i % 6) { isOnSingleFace = false; } if (cycle[cycleStart] > j) { cycleStart = cycleLength - 1; } for (k = 0; sideLoc[k] != j; k++) { } j = k; } previousCycleStartSide = cycle[cycleStart] % 6; if (isOnSingleFace == (twoPass == 0)) { // only print cycles which contain more than one part if (cycleLength > 1) { // print the permutation cycle if (isFirst) { isFirst = false; } else { buf.append(' '); } if (syntax == Syntax.PREFIX) { // the sign of the cycle will be inserted before the opening bracket buf.append(tBegin); } else if (syntax == Syntax.PRECIRCUMFIX) { // the sign of the cycle will be inserted after the opening bracket buf.append(tBegin); } else { buf.append(tBegin); } prevOrient = 0; for (k = 0; k < cycleLength; k++) { j = cycle[(cycleStart + k) % cycleLength]; if (k != 0) { buf.append(tDelimiter); prevOrient = (prevOrient + sideOrient[j]) % 4; } if (syntax == Syntax.PREFIX || syntax == Syntax.PRECIRCUMFIX || syntax == Syntax.POSTCIRCUMFIX) { // buf.append(sideOrients[prevOrient]); } buf.append(sides[j % 6]); if (syntax == Syntax.SUFFIX) { //buf.append(sideOrients[prevOrient]); } if (hasEvenLayerCount) { buf.append(j / 6 + 1); } else { if (j >= 6) { buf.append(j / 6); } } } j = cycle[cycleStart]; prevOrient = (prevOrient + sideOrient[j]) % 4; if (syntax == Syntax.POSTCIRCUMFIX) { // the sign of the cycle will be inserted before the closing bracket buf.append(tEnd); } else if (syntax == Syntax.SUFFIX) { // the sign of the cycle will be inserted after the closing bracket buf.append(tEnd); } else { buf.append(tEnd); } // insert cycle sign if (prevOrient != 0) { //buf.insert(p, sideOrients[prevOrient]); } } } } } } } } return buf.toString(); } }
39.631264
122
0.430653
cfaad11acdc190f8a1e77d5a24abf0106a823be4
3,043
/* * MIT License * * Copyright (c) 2017 Jeremy Wood, Elijah Poulos * * 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 wood.poulos.webcrawler.util; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.Configurator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.encoder.LayoutWrappingEncoder; import ch.qos.logback.core.spi.ContextAwareBase; import com.google.auto.service.AutoService; /** * A simple Logback Configurator. Automatically registered as a service. */ @AutoService(Configurator.class) public class LogbackConfigurator extends ContextAwareBase implements Configurator { /** * {@inheritDoc} */ @Override public void configure(LoggerContext loggerContext) { addInfo("Setting up logging configuration."); PatternLayout layout = new PatternLayout(); //layout.setPattern("%d{HH:mm:ss.SSS} [%thread/%highlight(%level)]: [%logger{15}] %msg%n"); layout.setPattern("[%gray(%thread)/%highlight(%level)]: %cyan([%logger{15}]) %msg%n"); layout.setContext(loggerContext); layout.start(); LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<>(); encoder.setContext(loggerContext); encoder.setLayout(layout); ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>(); appender.setContext(loggerContext); appender.setWithJansi(true); appender.setName("console"); appender.setEncoder(encoder); appender.start(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.addAppender(appender); String logLevelName = System.getProperty("logLevel"); if (logLevelName != null) { rootLogger.setLevel(Level.toLevel(logLevelName)); } } }
40.039474
99
0.727571
eb6a564e33c74aac6e42ab7b85f7ed5a5ce77fad
4,586
package dk.statsbiblioteket.doms.transformers.fileobjectcreator; import dk.statsbiblioteket.doms.transformers.fileobjectcreator.MuxFileChannelCalculator; import dk.statsbiblioteket.util.FileAlreadyExistsException; import jsr166y.ForkJoinPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.util.ArrayList; import java.util.List; public class FileObjectCreator { private static Logger log = LoggerFactory.getLogger(FileObjectCreator.class); private static final String baseName = "fileobjectcreator_"; private static FileObjectCreatorConfig config; private ResultWriter resultWriter; private static BufferedReader fileListReader = null; public static void main(String[] args) { File configFile = null; switch (args.length) { case 1: configFile = new File(args[0]); System.out.println("Reading data from stdin.."); fileListReader = new BufferedReader(new InputStreamReader(System.in)); run(configFile, fileListReader); break; case 2: configFile = new File(args[0]); System.out.println("Input file: " + args[1]); try { fileListReader = new BufferedReader(new FileReader(new File(args[1]))); run(configFile, fileListReader); } catch (FileNotFoundException e) { System.err.println("File not found: " + args[1]); System.exit(1); } break; default: System.out.println("Usage: bin/fileobjectcreator.sh config-file [input-file]"); System.exit(1); } } public static void run(File configFile, BufferedReader fileListReader) { if (!configFile.exists()) { System.out.println("Config file does not exist: " + config); System.exit(1); } if (!configFile.canRead()) { System.out.println("Could not read config file: " + config); System.exit(1); } try { config = new FileObjectCreatorConfig(configFile); System.out.println(config); new FileObjectCreator(fileListReader); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public FileObjectCreator(BufferedReader reader) { try { resultWriter = new ResultWriter(baseName, new ResultWriterErrorHandler() { @Override public void handleError(Throwable t) { FileObjectCreatorWorker.requestShutdown(); t.printStackTrace(); System.err.println(String.format("Could not write to logfile, shutting down..")); } }); resultWriter.setPrintProgress(true); List<String> data = new ArrayList<String>(); String line; while((line = reader.readLine()) != null) { data.add(line); } System.out.println(resultWriter.getHelpMessage()); MuxFileChannelCalculator muxFileChannelCalculator = new MuxFileChannelCalculator( Thread.currentThread().getContextClassLoader().getResourceAsStream("muxChannels.csv")); String baseUrl = config.getDomsBaseUrl(); if (baseUrl == null || baseUrl.isEmpty()) { System.out.println("Empty or non-existing DOMS base URL property in configuration."); System.exit(1); } FileObjectCreatorWorker fileObjectCreatorWorker = new FileObjectCreatorWorker(config, resultWriter, baseUrl, data, muxFileChannelCalculator); ForkJoinPool forkJoinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()*2); Long start = System.currentTimeMillis(); forkJoinPool.invoke(fileObjectCreatorWorker); Long end = System.currentTimeMillis(); System.out.println("Time taken: " + (end-start)); } catch (FileAlreadyExistsException e) { System.exit(1); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }
36.983871
111
0.603576