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
f02079bdd4b9270a7eaf9e68c01a3178adc02530
149
package de.servicezombie.thymeleaf; import org.thymeleaf.context.Context; public interface ThymeleadContextFactory { Context createContext(); }
14.9
42
0.812081
a8de64fa30934082525be7add58c19c048984b9e
624
package com.api.sportyyshoes.service; import java.util.List; import com.api.sportyyshoes.exceptionHandler.BusinessException; import com.api.sportyyshoes.model.User; public interface UserService { public User createUser(User user) throws BusinessException; public User updateUser(User user) ; public User getUserById(int id) throws BusinessException ; public void deleteUserById(int id) throws BusinessException; public List<User> getAllUsers(); public List<User> getAllUsersByName(String name) ; public List<User> purchaseReportByDate(String date); public List<User> purchaseReportByCategory(String category); }
32.842105
63
0.814103
314341d9f467c01ca13ea8a708d04daeb0262303
2,917
package helvidios.cp.ch3.completesearch; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class _00296_Safebreaker { public static void main(String... args){ String data = "4\r\n" + "6\r\n" + "9793 0/1\r\n" + "2384 0/2\r\n" + "6264 0/1\r\n" + "3383 1/0\r\n" + "2795 0/0\r\n" + "0218 1/0\r\n" + "1\r\n" + "1234 4/0\r\n" + "1\r\n" + "1234 2/2\r\n" + "2\r\n" + "6428 3/0\r\n" + "1357 3/0"; Scanner scanner = new Scanner(data); int nTestCases = scanner.nextInt(); while(nTestCases-- > 0){ int n = scanner.nextInt(); int[][] guesses = new int[n][3]; for(int i = 0; i < n; i++){ guesses[i][0] = scanner.nextInt(); String[] l = scanner.next().split("/"); guesses[i][1] = Integer.parseInt(l[0]); guesses[i][2] = Integer.parseInt(l[1]); } List<Integer> answer = guessCode(guesses); if(answer.size() == 0){ System.out.println("impossible"); }else if(answer.size() > 1){ System.out.println("indeterminate"); }else{ System.out.println(String.format("%04d", answer.get(0))); } } scanner.close(); } public static List<Integer> guessCode(int[][] guesses){ List<Integer> answer = new ArrayList<Integer>(); for(int code = 0; code <= 9999; code++){ if(codePossible(code, guesses)){ answer.add(code); } } return answer; } public static boolean codePossible(int code, int[][] guesses){ for(int[] guess : guesses){ if(!codeConsistentWithGuess(code, guess)) return false; } return true; } public static boolean codeConsistentWithGuess(int code, int[] guess){ String guessedNumberStr = String.format("%04d", guess[0]); String codeStr = String.format("%04d", code); int nCorrectDigits = guess[1]; int nCorrectDigitsInWrongPosition = guess[2]; return countCorrectDigits(codeStr, guessedNumberStr) == nCorrectDigits && countCorrectDigitsInWrongPosition(codeStr, guessedNumberStr) == nCorrectDigitsInWrongPosition; } public static int countCorrectDigits(String codeStr, String guessedNumberStr){ int count = 0; for(int i = 0; i < Math.min(guessedNumberStr.length(), codeStr.length()); i++){ if(codeStr.charAt(codeStr.length() - 1 - i) == guessedNumberStr.charAt(guessedNumberStr.length() - 1 - i)) count++; } return count; } public static int countCorrectDigitsInWrongPosition(String codeStr, String guessedNumberStr){ int[] freq1 = new int[10]; int[] freq2 = new int[10]; for(char c : guessedNumberStr.toCharArray()){ freq1[Character.getNumericValue(c)]++; } for(char c : codeStr.toCharArray()){ freq2[Character.getNumericValue(c)]++; } int nCommonDigits = 0; for(int i = 0; i < freq1.length; i++){ if(freq1[i] != 0 && freq2[i] != 0) nCommonDigits += Math.min(freq1[i], freq2[i]); } return nCommonDigits - countCorrectDigits(codeStr, guessedNumberStr); } }
29.464646
118
0.639013
dd877a788fe18f9baef407980dfabfbf4943f24b
3,891
package JavaConcurrency.cJDKTool; import java.util.concurrent.locks.StampedLock; //14 锁接口和类 public class nLock { //14.1 synchronized的不足之处 //14.2 锁的几种分类 //可重入锁和非可重入锁 //锁支持一个线程对资源重复加锁。 //synchronized关键字就是使用的重入锁。 //ReentrantLock的中文意思就是可重入锁。 //公平锁和非公平锁 //如果对一个锁来说,先对锁获取请求的线程一定会先被满足,后对锁获取请求的线程后被满足,那这个锁就是公平的。反之,那就是不公平的。 //一般情况下,非公平锁能提升一定的效率。但是非公平锁可能会发生线程饥饿(有一些线程长时间得不到锁)的情况。 //ReentrantLock支持非公平锁和公平锁两种。 //读写锁和排它锁 //"排它锁",这些锁在同一时刻只允许一个线程进行访问。 //读写锁可以在同一时刻允许多个读线程访问。注意,即使用读写锁,在写线程访问时,所有的读线程和其它写线程均被阻塞。 //14.3 JDK中有关锁的一些接口和类 //抽象类AQS/AQLS/AOS //AQS(AbstractQueuedSynchronizer) //AQLS(AbstractQueuedLongSynchronizer) //AOS(AbstractOwnableSynchronizer) //接口Condition/Lock/ReadWriteLock //ReentrantLock //ReentrantLock是一个非抽象类,它是Lock接口的JDK默认实现,实现了锁的基本功能。 //ReentrantReadWriteLock //这个类也是一个非抽象类,它是ReadWriteLock接口的JDK默认实现。 //ReentrantReadWriteLock实现了读写锁,但它有一个小弊端,就是在"写"操作的时候,其它线程不能写也不能读。我们称这种现象为"写饥饿"。 //StampedLock //在读的时候如果发生了写,应该通过重试的方式来获取新的值,而不应该阻塞写操作。这种模式也就是典型的无锁编程思想,和CAS自旋的思想一样。 //这种操作方式决定了StampedLock在读线程非常多而写线程非常少的场景下非常适用,同时还避免了写饥饿情况的发生。 static class Point { private double x, y; private final StampedLock sl = new StampedLock(); //写锁的使用 void move(double deltaX, double deltaY) { long stamp = sl.writeLock(); //读取写锁 try { x += deltaX; y += deltaY; } finally { sl.unlockWrite(stamp); //释放写锁 } } //乐观读锁的使用 double distanceFromOrigin() { long stamp = sl.tryOptimisticRead(); //获取乐观读锁 double currentX = x, currentY = y; if (!sl.validate(stamp)) { //检查获取乐观读锁之后,是否有其他写锁发生,有则返回false stamp = sl.readLock(); //获取悲观读锁 try { currentX = x; currentY = y; } finally { sl.unlockRead(stamp); //释放悲观读锁 } } return Math.sqrt(currentX * currentX + currentY * currentY); } //悲观读锁以及读锁升级写锁的使用 void moveIfAtOrigin(double newX, double newY) { long stamp = sl.readLock(); //获取悲观读锁 try { while (x == 0.0 && y == 0.0) { //读锁尝试转换为写锁:转换成功后相当于获取了写锁,转换失败相当于有写锁被占用 long ws = sl.tryConvertToWriteLock(stamp); if (ws != 0L) { //如果转换成功 stamp = ws; //读锁的票据更新为写锁 x = newX; y = newY; break; } else { //如果转换失败 sl.unlockRead(stamp); //释放读锁 stamp = sl.writeLock(); //强制获取写锁 } } } finally { sl.unlock(stamp); //释放所有锁 } } } //乐观读锁的意思就是先假定在这个锁获取期间,共享变量不会被改变,既然假定不会被改变,那就不需要上锁。 //在获取乐观读锁之后进行了一些操作,然后又调用了validate方法,这个方法就是用来验证tryOptimisticRead之后,是否有写操作执行过, //如果有,则获取一个悲观读锁,这里的悲观读锁和ReentrantReadWriteLock中的读锁类似,也是个共享锁。 //https://redspider.gitbook.io/concurrent/di-san-pian-jdk-gong-ju-pian/14#141-synchronized-de-bu-zu-zhi-chu //StampedLock的性能是非常优异的,基本上可以取代ReentrantReadWriteLock的作用。 }
43.233333
119
0.485479
cdc7e2983ea5ce824c128b90d1ea473d7e76a0e5
467
package io.protostuff.compiler.model; import java.util.List; import java.util.Map; import org.immutables.value.Value; /** * Module represents a compilation unit - a set of proto files, * generator name and generation options. * * @author Kostiantyn Shchepanovskyi */ @Value.Immutable public interface Module { String getName(); List<Proto> getProtos(); String getOutput(); Map<String, Object> getOptions(); UsageIndex usageIndex(); }
17.296296
63
0.713062
894052792ad8c6e3cc476316c4f96d661736f9f8
760
package com.poa.POAvanzados.dao.row_mappers; import com.poa.POAvanzados.model.item_model.ItemCount; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class ItemCountRowMapper implements RowMapper<ItemCount> { @Override public ItemCount mapRow(ResultSet resultSet, int i) throws SQLException { ItemCount itemCount= new ItemCount(); itemCount.setIdItem(resultSet.getInt("idItem")); itemCount.setName(resultSet.getString("name")); itemCount.setCritical(resultSet.getBoolean("critical")); itemCount.setUsedCount(resultSet.getInt("usedCount")); itemCount.setDiscardedCount(resultSet.getInt("discardedCount")); return itemCount; } }
36.190476
77
0.747368
1a48d74beeb144276837f39b0b6a7aa43ea3ef29
764
/** * author: salimt */ package ui; import model.*; import static model.TransactionType.*; public class Main { public static void main(String[] args) { TransactionSummary ts = new TransactionSummary("Ada Lovelace"); Transaction t1 = new Transaction("Movie", "May 1st", 10, ENTERTAINMENT); Transaction t3 = new Transaction("Movie", "May 1st", 10, ENTERTAINMENT); Transaction t2 = new Transaction("Restaurant", "May 11th", 20, FOOD); ts.addTransaction(t1); ts.addTransaction(t2); ts.addTransaction(t3); System.out.println(ts.getTransactions()); System.out.println(ts.getNumTransactions()); System.out.println(ts.averageTransactionCost()); } }
29.384615
82
0.628272
0987e773176e9b66ac29d628c425a4b0cb0cce9e
2,696
package com.exasol.projectkeeper.sources; import static com.exasol.projectkeeper.shared.config.ProjectKeeperConfig.SourceType.MAVEN; import static com.exasol.projectkeeper.shared.config.ProjectKeeperModule.JAR_ARTIFACT; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertAll; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Set; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.hamcrest.Matchers; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import com.exasol.mavenpluginintegrationtesting.MavenIntegrationTestEnvironment; import com.exasol.projectkeeper.TestEnvBuilder; import com.exasol.projectkeeper.shared.config.ProjectKeeperConfig; import com.exasol.projectkeeper.shared.config.ProjectKeeperModule; import com.exasol.projectkeeper.test.TestMavenModel; @Tag("integration") class SourceAnalyzerIT { private static final Set<ProjectKeeperModule> MODULES = Set.of(JAR_ARTIFACT); private static final MavenIntegrationTestEnvironment TEST_ENV = TestEnvBuilder.getTestEnv(); @TempDir Path tempDir; @Test void testAnalyze() throws IOException, GitAPIException { Git.init().setDirectory(this.tempDir.toFile()).call().close(); new TestMavenModel().writeAsPomToProject(this.tempDir); final Path path = this.tempDir.resolve("pom.xml"); final List<AnalyzedSource> result = SourceAnalyzer .create(null, TEST_ENV.getLocalMavenRepository(), TestEnvBuilder.CURRENT_VERSION) .analyze(this.tempDir, List.of(ProjectKeeperConfig.Source.builder().modules(MODULES).path(path) .advertise(true).type(MAVEN).build())); final AnalyzedMavenSource first = (AnalyzedMavenSource) result.get(0); assertAll(// () -> assertThat(result, Matchers.hasSize(1)), () -> assertThat(first.getPath(), equalTo(path)), () -> assertThat(first.getModules(), equalTo(MODULES)), () -> assertThat(first.isAdvertise(), equalTo(true)), () -> assertThat(first.getArtifactId(), equalTo(TestMavenModel.PROJECT_ARTIFACT_ID)), () -> assertThat(first.getProjectName(), equalTo(TestMavenModel.PROJECT_NAME)), () -> assertThat(first.getVersion(), equalTo(TestMavenModel.PROJECT_VERSION)), () -> assertThat(first.getDependencies(), not(nullValue())), () -> assertThat(first.getDependencyChanges(), not(nullValue()))// ); } }
49.018182
112
0.72181
682d01727d9075e681f8dc7036e25d2c419d056b
203
package net.duguying.o.exception; /** * Created by duguying on 15/11/25. */ public class DBException extends RuntimeException { public DBException(Exception cause) { super(cause); } }
18.454545
51
0.684729
8ef25c94edb0f63e0aa65c0c5622cc1bb1911e4b
8,563
package ro.pub.cs.systems.eim.practicaltest02.network; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; import cz.msebera.android.httpclient.HttpEntity; import cz.msebera.android.httpclient.HttpResponse; import cz.msebera.android.httpclient.NameValuePair; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.client.ResponseHandler; import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity; import cz.msebera.android.httpclient.client.methods.HttpGet; import cz.msebera.android.httpclient.client.methods.HttpPost; import cz.msebera.android.httpclient.impl.client.BasicResponseHandler; import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; import cz.msebera.android.httpclient.message.BasicNameValuePair; import cz.msebera.android.httpclient.protocol.HTTP; import cz.msebera.android.httpclient.util.EntityUtils; import ro.pub.cs.systems.eim.practicaltest02.general.Constants; import ro.pub.cs.systems.eim.practicaltest02.general.Utilities; import ro.pub.cs.systems.eim.practicaltest02.model.CurrencyInformation; public class CommunicationThread extends Thread { private ServerThread serverThread; private Socket socket; public CommunicationThread(ServerThread serverThread, Socket socket) { this.serverThread = serverThread; this.socket = socket; } public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) { long diffInMillies = date2.getTime() - date1.getTime(); return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS); } @Override public void run() { if (socket == null) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] Socket is null!"); return; } try { BufferedReader bufferedReader = Utilities.getReader(socket); PrintWriter printWriter = Utilities.getWriter(socket); if (bufferedReader == null || printWriter == null) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] Buffered Reader / Print Writer are null!"); return; } Log.i(Constants.TAG, "[COMMUNICATION THREAD] Waiting for parameters from client (currency type)!"); String informationType = bufferedReader.readLine(); if (informationType == null || informationType.isEmpty()) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] Error receiving parameters from client (currency type)!"); return; } HashMap<String, CurrencyInformation> data = serverThread.getData(); CurrencyInformation currencyInformation = null; if (data.containsKey(informationType)) { Log.i(Constants.TAG, "[COMMUNICATION THREAD] Getting the information from the cache..."); String dateCurrencyString = data.get(informationType).getUpdated(); Date dateCurrency = new Date(dateCurrencyString); Date now = new Date(); Long diff = getDateDiff(dateCurrency, now, TimeUnit.MINUTES); if (diff > 1) { Log.i(Constants.TAG, "[COMMUNICATION THREAD] Invalidated cache..."); Log.i(Constants.TAG, "[COMMUNICATION THREAD] Getting the information from the webservice because c..."); HttpClient httpClient = new DefaultHttpClient(); String pageSourceCode = ""; HttpGet httpGet = new HttpGet("https://api.coindesk.com/v1/bpi/currentprice/" + informationType + ".json"); HttpResponse httpGetResponse = httpClient.execute(httpGet); HttpEntity httpGetEntity = httpGetResponse.getEntity(); if (httpGetEntity != null) { pageSourceCode = EntityUtils.toString(httpGetEntity); } if (pageSourceCode == null) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] Error getting the information from the webservice!"); return; } else Log.i(Constants.TAG, pageSourceCode); JSONObject content = new JSONObject(pageSourceCode); JSONObject main = content.getJSONObject("bpi"); JSONObject currencyDetails = main.getJSONObject(informationType); String code = currencyDetails.getString("code"); String rate = currencyDetails.getString("rate"); String description = currencyDetails.getString("description"); String rate_float = currencyDetails.getString("rate_float"); JSONObject time = content.getJSONObject("time"); String updated = time.getString("updated"); currencyInformation = new CurrencyInformation( code, rate, description, rate_float, updated ); serverThread.setData(informationType, currencyInformation); } else { currencyInformation = data.get(informationType); } } else { Log.i(Constants.TAG, "[COMMUNICATION THREAD] Getting the information from the webservice..."); HttpClient httpClient = new DefaultHttpClient(); String pageSourceCode = ""; HttpGet httpGet = new HttpGet("https://api.coindesk.com/v1/bpi/currentprice/" + informationType + ".json"); HttpResponse httpGetResponse = httpClient.execute(httpGet); HttpEntity httpGetEntity = httpGetResponse.getEntity(); if (httpGetEntity != null) { pageSourceCode = EntityUtils.toString(httpGetEntity); } if (pageSourceCode == null) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] Error getting the information from the webservice!"); return; } else Log.i(Constants.TAG, pageSourceCode); JSONObject content = new JSONObject(pageSourceCode); JSONObject main = content.getJSONObject("bpi"); JSONObject currencyDetails = main.getJSONObject(informationType); String code = currencyDetails.getString("code"); String rate = currencyDetails.getString("rate"); String description = currencyDetails.getString("description"); String rate_float = currencyDetails.getString("rate_float"); JSONObject time = content.getJSONObject("time"); String updated = time.getString("updated"); currencyInformation = new CurrencyInformation( code, rate, description, rate_float, updated ); serverThread.setData(informationType, currencyInformation); } if (currencyInformation == null) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] Weather Forecast Information is null!"); return; } String result = currencyInformation.toString(); printWriter.println(result); printWriter.flush(); } catch (IOException ioException) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] An exception has occurred: " + ioException.getMessage()); ioException.printStackTrace(); } catch (JSONException jsonException) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] An exception has occurred: " + jsonException.getMessage()); jsonException.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException ioException) { Log.e(Constants.TAG, "[COMMUNICATION THREAD] An exception has occurred: " + ioException.getMessage()); ioException.printStackTrace(); } } } } }
44.832461
127
0.621511
e98c259c7e0db0b616428d85d4173333be7cb7f1
2,473
package ar.edu.itba.paw.webapp.rest.error; import ar.edu.itba.paw.model.error.ErrorType; import ar.edu.itba.paw.model.error.GetOutError; import ar.edu.itba.paw.model.support.GetOutException; import ar.edu.itba.paw.webapp.support.GetOutMediaType; import javax.ws.rs.NotAllowedException; import javax.ws.rs.NotFoundException; import javax.ws.rs.NotSupportedException; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.glassfish.jersey.server.ParamException.PathParamException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.String.format; /** * <p>Controla los errores asociados a la infraestructura web. Los errores * desconocidos deben mapearse hacia errores internos del servidor para * evitar que el cliente identifique posibles <i>exploits</i>.</p> */ @Provider @Produces(GetOutMediaType.APPLICATION_GETOUT_v1_JSON) public class WebAppErrorController implements ExceptionMapper<WebApplicationException> { private static final Logger log = LoggerFactory.getLogger(WebAppErrorController.class); @Override public Response toResponse(final WebApplicationException exception) { final GetOutException getoutException = inferException(exception); return Response.status(getoutException.getStatus()) .header(HttpHeaders.CONTENT_TYPE, GetOutMediaType.APPLICATION_GETOUT_v1_JSON) .entity(new GetOutError(getoutException)) .build(); } protected GetOutException inferException(final WebApplicationException exception) { log.error("----------------------------------------------------------------------------------------------------"); log.error(format("WEBAPP ERROR FOUND -> Exception Class: %s\tMessage: %s.", exception.getClass().getCanonicalName(), exception.getMessage())); if (exception instanceof NotFoundException) { return GetOutException.of(ErrorType.RESOURCE_NOT_FOUND); } else if (exception instanceof NotAllowedException) { return GetOutException.of(ErrorType.METHOD_NOT_ALLOWED); } else if (exception instanceof NotSupportedException) { return GetOutException.of(ErrorType.UNSUPPORTED_MEDIA_TYPE); } else if (exception instanceof PathParamException) { return GetOutException.of(ErrorType.INVALID_PATH_PARAMETER); } else { return GetOutException.of(ErrorType.UNKNOWN_ERROR); } } }
38.640625
116
0.767489
593787cbb1f641ba4b017452d534815ce243989a
481
package ru.merkurev.hibernate.training.spring.jdbc.entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import java.time.LocalDate; /** * Person entity. * * @author MerkurevSergei */ @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class Person { private long id; private String firstName; private String lastName; private LocalDate birthDate; }
18.5
58
0.775468
22ca153fe7bc64c2d4fa6fd2f660b33101bf2e67
1,923
package org.infinispan.cdi; import org.infinispan.cdi.util.defaultbean.DefaultBean; import org.infinispan.configuration.cache.Configuration; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; /** * <p>The default {@link EmbeddedCacheManager} producer.</p> * * <p>The cache manager produced by default is an instance of {@link DefaultCacheManager} initialized with the default * configuration produced by the {@link DefaultEmbeddedCacheConfigurationProducer}. The default cache manager can be * overridden by creating a producer which produces the new default cache manager. The cache manager produced must have * the scope {@link ApplicationScoped} and the {@linkplain javax.enterprise.inject.Default Default} qualifier.</p> * * @author Kevin Pollet <[email protected]> (C) 2011 SERLI */ public class DefaultEmbeddedCacheManagerProducer { /** * Produces the default embedded cache manager. * * @param defaultConfiguration the default configuration produced by the {@link DefaultEmbeddedCacheConfigurationProducer}. * @return the default embedded cache manager used by the application. */ @Produces @ApplicationScoped @DefaultBean(EmbeddedCacheManager.class) public EmbeddedCacheManager getDefaultEmbeddedCacheManager(Configuration defaultConfiguration) { return new DefaultCacheManager(defaultConfiguration); } /** * Stops the default embedded cache manager when the corresponding instance is released. * * @param defaultEmbeddedCacheManager the default embedded cache manager. */ @SuppressWarnings("unused") private void stopCacheManager(@Disposes EmbeddedCacheManager defaultEmbeddedCacheManager) { defaultEmbeddedCacheManager.stop(); } }
40.914894
126
0.785751
d7297b19ed9ea58c56dc5c9515cffbe328810e00
216
package javaf.prelude; /** * This is essentially a binary operator, say a function with two arguments where argument types and result type coincide. */ public interface BinaryOperator<X> { X apply(X x1, X x2); }
24
122
0.740741
eccda536794b5e275bfd7266b2c9a98c79c33286
2,792
package dev.axt.fsmw.core; import dev.axt.fsmw.representation.ActorTrigger; import dev.axt.fsmw.representation.Trigger; import org.apache.commons.lang3.ArrayUtils; /** * Workflow's state configuration * * @author alextremp * @param <STATE> * @param <TRIGGER> * @param <ROLE> */ public class WorkflowStateConfig<STATE, TRIGGER, ROLE> extends StateConfig<STATE, TRIGGER> { private ROLE[] allowedRoles; public WorkflowStateConfig(WorkflowConfig<STATE, TRIGGER, ROLE> stateMachine, STATE source) { super(stateMachine, source); } /** * Restricts this state to a set of allowed actor roles. A runtime actor * won't be able to trigger events at this state if the actor does not have * any of the allowed roles. * * @param roles * @return this state configuration */ public WorkflowStateConfig<STATE, TRIGGER, ROLE> actors(ROLE... roles) { log().info(machine().getName() + " - added roles restriction for " + ArrayUtils.toString(roles) + " on " + this); this.allowedRoles = roles; return this; } /** * * @return the workflow's configuration */ @Override public WorkflowConfig<STATE, TRIGGER, ROLE> machine() { return (WorkflowConfig<STATE, TRIGGER, ROLE>) super.machine(); } /** * Creates a self transition to catch actions with no state changes * * @param trigger the trigger that can fire the event * @return the new transition config */ @Override public WorkflowTransitionConfig<STATE, TRIGGER, ROLE> self(TRIGGER trigger) { return (WorkflowTransitionConfig<STATE, TRIGGER, ROLE>) super.self(trigger); } /** * Creates a new outgoing transition from this state * * @param trigger the trigger that can fire the event * @param target the state after transition succeeds * @return the new transition config */ @Override public WorkflowTransitionConfig<STATE, TRIGGER, ROLE> transition(TRIGGER trigger, STATE target) { return (WorkflowTransitionConfig<STATE, TRIGGER, ROLE>) super.transition(trigger, target); } @Override protected TransitionConfig instantiateTransitionConfig(TRIGGER trigger, STATE target) { return new WorkflowTransitionConfig<>(this, trigger, target); } @Override WorkflowTransitionConfig<STATE, TRIGGER, ROLE> getFirstActiveTransition(Trigger<TRIGGER> trigger) { if (allowedRoles == null || (trigger.is(ActorTrigger.class) && trigger.as(ActorTrigger.class).getActor().hasAnyRole(allowedRoles))) { return (WorkflowTransitionConfig<STATE, TRIGGER, ROLE>) super.getFirstActiveTransition(trigger); } else { log().debug(machine().getName() + " - Actor restriction " + ArrayUtils.toString(allowedRoles) + " has not been acomplished on " + this + " for " + trigger + ""); } return null; } @Override public String toString() { return "Workflow" + super.toString(); } }
31.022222
164
0.726719
cf78f3fb9b11044ccca72aa6d469c97c36b81fe3
1,722
/* * Copyright 2015 Textocat * * 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.textocat.textokit.morph.dictionary.resource; import com.textocat.textokit.morph.model.Lemma; import com.textocat.textokit.morph.model.LemmaLinkType; import com.textocat.textokit.morph.model.Wordform; import java.util.BitSet; import java.util.List; import java.util.Map; /** * @author Rinat Gareev */ public interface MorphDictionary { String getVersion(); String getRevision(); GramModel getGramModel(); List<Wordform> getEntries(String str); LemmaLinkType getLemmaLinkType(short id); /** * @param lemmaId * @return lemma with given id * @throws IllegalStateException if lemma with given id is not found */ Lemma getLemma(int lemmaId); // TODO move to a interface that is kind of MutableMorphDictionary void addLemma(Lemma lemma); int getLemmaMaxId(); Map<Integer, LemmaLinkType> getLemmaOutlinks(int lemmaId); Map<Integer, LemmaLinkType> getLemmaInlinks(int lemmaId); /** * @param tag * @return true if this dictionary has the given tag */ boolean containsGramSet(BitSet tag); }
26.90625
78
0.708479
96f572df3b3e3a9db0bec39fd18b69edf45811a0
99
package datastructures.tree; public interface MaxValue { int getMaxValue(Node currentNode); }
16.5
38
0.777778
cea0e01d0623eebe77b20d793e27fe807ad4a439
1,102
package cc.mrbird.febs.dca.service; import cc.mrbird.febs.dca.entity.DcaBScientificprize; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; import com.baomidou.mybatisplus.core.metadata.IPage; import cc.mrbird.febs.common.domain.QueryRequest; import com.baomidou.mybatisplus.core.metadata.IPage; /** * <p> * 任现职以来科研获奖情况 服务类 * </p> * * @author viki * @since 2020-11-06 */ public interface IDcaBScientificprizeService extends IService<DcaBScientificprize> { IPage<DcaBScientificprize> findDcaBScientificprizes(QueryRequest request, DcaBScientificprize dcaBScientificprize); IPage<DcaBScientificprize> findDcaBScientificprizeList(QueryRequest request, DcaBScientificprize dcaBScientificprize); void createDcaBScientificprize(DcaBScientificprize dcaBScientificprize); void updateDcaBScientificprize(DcaBScientificprize dcaBScientificprize); void deleteDcaBScientificprizes(String[]Ids); void deleteByuseraccount(String userAccount); int getMaxDisplayIndexByuseraccount(String userAccount); }
31.485714
126
0.788566
81a4b2ce4ba51bf00a6c869f4a0acdabe551ce58
70
package testPullUpGen.test31d.test; public class C implements B { }
11.666667
35
0.771429
ece30b61bbeb2396038eeafb9496e2e14dc31b16
2,633
package com.eva.hr.report.conts; public class EVAConstants { public static final String COMMA = ","; public static final String NEW_LINE = "\r\n"; public static final String PUNCH_IN = "Punch In"; public static final String PUNCH_OUT = "Punch Out"; public static final String OVERTIME_IN = "Overtime In"; public static final String OVERTIME_OUT = "Overtime Out"; public static final String IN = "In"; public static final String OUT = "Out"; public static final String BLANK = ""; public static final String UTF_8 = "UTF-8"; public static final String FLAG_Y = "Y"; public static final String FLAG_N = "N"; public static final String DATE_FORMAT_YYYYMMDD = "yyyyMMdd"; public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd"; //Fields Main File public static final String EMP_CODE = "EMP_CODE"; public static final String EMP_NAME = "EMP_NAME"; public static final String DEPARTMENT = "DEPARTMENT"; public static final String DAY_COUNT = "DAY_COUNT"; public static final String DATE = "DATE"; public static final String PUNCH_KIND = "PUNCH_KIND"; public static final String TIME = "TIME"; public static StringBuilder HEADER_CSV1 = new StringBuilder(EMP_CODE) .append(COMMA).append(EMP_NAME).append(COMMA).append(DEPARTMENT) .append(COMMA).append(DAY_COUNT).append(COMMA).append(DATE).append(COMMA) .append(PUNCH_KIND).append(COMMA).append(TIME); //Fields Process File CSV public static final String PUNCH_KIND_1 = "PUNCH_KIND_1"; public static final String TIME_1 = "TIME_1"; public static final String PUNCH_KIND_2 = "PUNCH_KIND_2"; public static final String TIME_2 = "TIME_2"; public static final String OFF_1 = "OFF_1"; public static final String OFF_2 = "OFF_2"; public static final String OFF_ALL = "OFF_ALL"; public static final String OT_1 = "OT_1"; public static final String OT_2 = "OT_2"; public static final String OT_ALL = "OT_ALL"; public static final String REMARK_1 = "REMARK_1"; public static final String REMARK_2 = "REMARK_2"; public static StringBuilder HEADER_CSV2 = new StringBuilder(EMP_CODE) .append(COMMA).append(EMP_NAME) .append(COMMA).append(DEPARTMENT) .append(COMMA).append(DAY_COUNT) .append(COMMA).append(DATE) .append(COMMA).append(PUNCH_KIND_1) .append(COMMA).append(TIME_1) .append(COMMA).append(OFF_1) .append(COMMA).append(OT_1) .append(COMMA).append(REMARK_1) .append(COMMA).append(PUNCH_KIND_2) .append(COMMA).append(TIME_2) .append(COMMA).append(OFF_2) .append(COMMA).append(OT_2) .append(COMMA).append(REMARK_2) .append(COMMA).append(OFF_ALL) .append(COMMA).append(OT_ALL); }
38.720588
76
0.742119
714062d5007c11b921a30ebf7616be056389d0ae
1,415
/* * Copyright (C) 2015 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.android.documentsui.dirlist; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.test.mock.MockContentResolver; public final class TestContext { /** * Returns a Context configured with test provider for authority. */ static Context createStorageTestContext(Context context, String authority) { final MockContentResolver testResolver = new MockContentResolver(); TestContentProvider provider = new TestContentProvider(); testResolver.addProvider(authority, provider); return new ContextWrapper(context) { @Override public ContentResolver getContentResolver() { return testResolver; } }; } }
33.690476
80
0.718021
0c4dfc25ba6c019f6fd4a2ee6d88ad9b78014006
494
package com.myprogect.mywarehouse.service; import com.myprogect.mywarehouse.service.dto.StorekeeperDTO; import com.myprogect.mywarehouse.service.dto.StorekeeperWithInformationDTO; import java.util.List; public interface StorekeeperService { StorekeeperWithInformationDTO byId(Long id); void saveOrUpdate(StorekeeperDTO storekeeper); List<StorekeeperDTO> findAllRecord(); List<StorekeeperDTO> findOnlyNameAndId(); StorekeeperDTO findByEmployeeCode(Integer employeeCode); }
35.285714
75
0.821862
8bdaa4ce725d097d4704cfbd22575c9888639c3f
2,467
package com.scen.cache.service.impl; import com.scen.cache.service.SsoCacheService; import com.scen.common.utils.JsonUtils; import com.scen.pojo.User; import com.scen.vo.ScenResult; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.Map; import java.util.concurrent.TimeUnit; /** * 单点登录缓存服务 * * @author Scen * @date 2018/5/26 20:12 */ @RestController public class SsoCacheServiceImpl implements SsoCacheService { @Autowired private RedisTemplate<String, String> redisTemplate; @Value("${REDIS_USER_SESSION_KEY}") private String REDIS_USER_SESSION_KEY; @Value("${SSO_SESSION_EXPIRE}") private Long SSO_SESSION_EXPIRE; @Override @RabbitListener(queues = "addUserSession") @RabbitHandler public void addUserSession(@RequestBody Map<String, String> map) { if (map != null) { String token = map.get("token"); String user = map.get("user"); redisTemplate.opsForValue().set(REDIS_USER_SESSION_KEY + ":" + token, user); redisTemplate.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE, TimeUnit.SECONDS); } } @Override public ScenResult getUserByToken(String token) { // 根据token从redis中查询用户信息 String json = redisTemplate.opsForValue().get(REDIS_USER_SESSION_KEY + ":" + token); // 判断是否为空 if (StringUtils.isBlank(json)) { return ScenResult.build(400, "此session已经过期,请重新登录"); } // 更新过期时间 redisTemplate.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE, TimeUnit.SECONDS); // 返回用户信息 return ScenResult.ok(JsonUtils.jsonToPojo(json, User.class)); } @Override public ScenResult logoutUserByToken(String token) { try { redisTemplate.delete(REDIS_USER_SESSION_KEY + ":" + token); return ScenResult.ok(""); } catch (Exception e) { e.printStackTrace(); return ScenResult.build(500, "服务器繁忙。。。"); } } }
33.337838
109
0.690717
0119e1ad7e76fbb60a0cdd098a96b70a6fc9221d
3,297
/*********************************************************************************************************************** * * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.api.java.typeutils; import eu.stratosphere.types.TypeInformation; import org.apache.hadoop.io.Writable; import eu.stratosphere.api.common.typeutils.TypeComparator; import eu.stratosphere.api.common.typeutils.TypeSerializer; import eu.stratosphere.api.java.functions.InvalidTypesException; import eu.stratosphere.api.java.typeutils.runtime.WritableComparator; import eu.stratosphere.api.java.typeutils.runtime.WritableSerializer; public class WritableTypeInfo<T extends Writable> extends TypeInformation<T> implements AtomicType<T> { private final Class<T> typeClass; public WritableTypeInfo(Class<T> typeClass) { if (typeClass == null) { throw new NullPointerException(); } if (!Writable.class.isAssignableFrom(typeClass) || typeClass == Writable.class) { throw new IllegalArgumentException("WritableTypeInfo can only be used for subclasses of " + Writable.class.getName()); } this.typeClass = typeClass; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public TypeComparator<T> createComparator(boolean sortOrderAscending) { if(Comparable.class.isAssignableFrom(typeClass)) { return new WritableComparator(sortOrderAscending, typeClass); } else { throw new UnsupportedOperationException("Cannot create Comparator for "+typeClass.getCanonicalName()+". " + "Class does not implement Comparable interface."); } } @Override public boolean isBasicType() { return false; } @Override public boolean isTupleType() { return false; } @Override public int getArity() { return 1; } @Override public Class<T> getTypeClass() { return this.typeClass; } @Override public boolean isKeyType() { return Comparable.class.isAssignableFrom(typeClass); } @Override public TypeSerializer<T> createSerializer() { return new WritableSerializer<T>(typeClass); } @Override public String toString() { return "WritableType<" + typeClass.getName() + ">"; } // -------------------------------------------------------------------------------------------- static final <T extends Writable> TypeInformation<T> getWritableTypeInfo(Class<T> typeClass) { if (Writable.class.isAssignableFrom(typeClass) && !typeClass.equals(Writable.class)) { return new WritableTypeInfo<T>(typeClass); } else { throw new InvalidTypesException("The given class is no subclass of " + Writable.class.getName()); } } }
33.30303
121
0.673339
ce2cc3e0235866c6e88b7c5358ded6aed3592eb6
1,492
package com.example.lab.android.nuc.chat.Base.Message; public class Msg { private String questionTitle; private String questionDetail; private String questionTime; public int questionNumber; public static final int TYPE_RECEVIED = 0; public static final int TYOE_SEND = 1; //消息内容 public String content; //放松的消息的类型 private int type; public Msg(String content,int type){ this.content = content; this.type = type; } public String getContent() { return content; } public int getType() { return type; } public int getQuestionNumber() { return questionNumber; } public void setQuestionTitle(String questionTitle) { this.questionTitle = questionTitle; } public String getQuestionTitle() { return questionTitle; } public void setQuestionTime(String questionTime) { this.questionTime = questionTime; } public String getQuestionTime() { return questionTime; } public void setQuestionNumber(int questionNumber) { this.questionNumber = questionNumber; } public String getQuestionDetail() { return questionDetail; } public void setQuestionDetail(String questionDetail) { this.questionDetail = questionDetail; } public void setType(int type) { this.type = type; } public void setContent(String content) { this.content = content; } }
19.893333
58
0.646113
2e79007c2638e963647d0b0a8623fa8036e4fd8b
610
package com.github.mschroeder.github.jasgl.positioner; import com.github.mschroeder.github.jasgl.Keyboard; import com.github.mschroeder.github.jasgl.Mouse; import com.github.mschroeder.github.jasgl.positioner.Positioner; /** * The positioner moves sprites based on input (e.g. key pressed or mouse clicked). * @author Markus Schr&ouml;der */ public abstract class InputBasedPositioner extends Positioner { public abstract void input(Keyboard keyboard, Mouse mouse); /** * Use this method to reset the input-memory of the positioner. */ public abstract void reset(); }
29.047619
83
0.739344
78d588e49201ace84a0ce83b0402483fe368972f
287
package Practice_Question; public class Integer_To_String { public static void main(String[] args) { //int num=56784; //String str = Integer.toString(num); //System.out.println(str); //} // int num=34556; String str = String.valueOf(num); System.out.println(num); } }
17.9375
41
0.675958
c17b1786bfe3d828b887d628c1d920b6a893dfcb
2,218
/** * This software is released as part of the Pumpernickel project. * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.image.transition; import com.pump.geom.RectangularTransform; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; /** * This splits a frame down the middle and squishes the two left and right * halves, as if a curtain is being opened. * * <P> * This is basically a "Split Vertical", except the two halves are squished. * Here is a playback sample: * <p> * <img src= * "https://raw.githubusercontent.com/mickleness/pumpernickel/master/resources/transition/CurtainTransition2D/Curtain * .gif" * alt="CurtainTransition2D Demo"> * */ public class CurtainTransition2D extends Transition2D { @Override public Transition2DInstruction[] getInstructions(float progress, Dimension size) { progress = 1 - progress; Rectangle2D rect1 = new Rectangle2D.Double(0, 0, size.width / 2f * progress, size.height); Rectangle2D rect2 = new Rectangle2D.Double(size.width - rect1.getWidth(), 0, rect1.getWidth(), rect1.getHeight()); AffineTransform transform1 = RectangularTransform.create( new Rectangle2D.Float(0, 0, size.width / 2f, size.height), rect1); AffineTransform transform2 = RectangularTransform.create( new Rectangle2D.Float(size.width / 2f, 0, size.width / 2f, size.height), rect2); return new Transition2DInstruction[]{ new ImageInstruction(false), new ImageInstruction(true, transform1, rect1), new ImageInstruction(true, transform2, rect2)}; } @Override public String toString() { return "Curtain"; } }
34.123077
117
0.633904
47b6538b50998ef2069783d40dd0530f40a8872b
4,842
package net.minecraft.client.gui; import java.util.List; import java.util.ListIterator; import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Supplier; import javax.annotation.Nullable; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public interface INestedGuiEventHandler extends IGuiEventListener { List<? extends IGuiEventListener> children(); /** * Returns the first event listener that intersects with the mouse coordinates. */ default Optional<IGuiEventListener> getEventListenerForPos(double mouseX, double mouseY) { for(IGuiEventListener iguieventlistener : this.children()) { if (iguieventlistener.isMouseOver(mouseX, mouseY)) { return Optional.of(iguieventlistener); } } return Optional.empty(); } default boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) { for(IGuiEventListener iguieventlistener : this.children()) { if (iguieventlistener.mouseClicked(p_mouseClicked_1_, p_mouseClicked_3_, p_mouseClicked_5_)) { this.setFocused(iguieventlistener); if (p_mouseClicked_5_ == 0) { this.setDragging(true); } return true; } } return false; } default boolean mouseReleased(double p_mouseReleased_1_, double p_mouseReleased_3_, int p_mouseReleased_5_) { this.setDragging(false); return this.getEventListenerForPos(p_mouseReleased_1_, p_mouseReleased_3_).filter((p_212931_5_) -> { return p_212931_5_.mouseReleased(p_mouseReleased_1_, p_mouseReleased_3_, p_mouseReleased_5_); }).isPresent(); } default boolean mouseDragged(double p_mouseDragged_1_, double p_mouseDragged_3_, int p_mouseDragged_5_, double p_mouseDragged_6_, double p_mouseDragged_8_) { return this.getFocused() != null && this.isDragging() && p_mouseDragged_5_ == 0 ? this.getFocused().mouseDragged(p_mouseDragged_1_, p_mouseDragged_3_, p_mouseDragged_5_, p_mouseDragged_6_, p_mouseDragged_8_) : false; } boolean isDragging(); void setDragging(boolean p_setDragging_1_); default boolean mouseScrolled(double p_mouseScrolled_1_, double p_mouseScrolled_3_, double p_mouseScrolled_5_) { return this.getEventListenerForPos(p_mouseScrolled_1_, p_mouseScrolled_3_).filter((p_212929_6_) -> { return p_212929_6_.mouseScrolled(p_mouseScrolled_1_, p_mouseScrolled_3_, p_mouseScrolled_5_); }).isPresent(); } default boolean keyPressed(int p_keyPressed_1_, int p_keyPressed_2_, int p_keyPressed_3_) { return this.getFocused() != null && this.getFocused().keyPressed(p_keyPressed_1_, p_keyPressed_2_, p_keyPressed_3_); } default boolean keyReleased(int keyCode, int scanCode, int modifiers) { return this.getFocused() != null && this.getFocused().keyReleased(keyCode, scanCode, modifiers); } default boolean charTyped(char p_charTyped_1_, int p_charTyped_2_) { return this.getFocused() != null && this.getFocused().charTyped(p_charTyped_1_, p_charTyped_2_); } @Nullable IGuiEventListener getFocused(); void setFocused(@Nullable IGuiEventListener p_setFocused_1_); default void setFocusedDefault(@Nullable IGuiEventListener eventListener) { this.setFocused(eventListener); } default void func_212932_b(@Nullable IGuiEventListener eventListener) { this.setFocused(eventListener); } default boolean changeFocus(boolean p_changeFocus_1_) { IGuiEventListener iguieventlistener = this.getFocused(); boolean flag = iguieventlistener != null; if (flag && iguieventlistener.changeFocus(p_changeFocus_1_)) { return true; } else { List<? extends IGuiEventListener> list = this.children(); int j = list.indexOf(iguieventlistener); int i; if (flag && j >= 0) { i = j + (p_changeFocus_1_ ? 1 : 0); } else if (p_changeFocus_1_) { i = 0; } else { i = list.size(); } ListIterator<? extends IGuiEventListener> listiterator = list.listIterator(i); BooleanSupplier booleansupplier = p_changeFocus_1_ ? listiterator::hasNext : listiterator::hasPrevious; Supplier<? extends IGuiEventListener> supplier = p_changeFocus_1_ ? listiterator::next : listiterator::previous; while(booleansupplier.getAsBoolean()) { IGuiEventListener iguieventlistener1 = supplier.get(); if (iguieventlistener1.changeFocus(p_changeFocus_1_)) { this.setFocused(iguieventlistener1); return true; } } this.setFocused((IGuiEventListener)null); return false; } } }
39.365854
222
0.706733
4284c1b9e95be9df8e1821d96f4f3019f07da206
8,394
package edu.stanford.nlp.sempre.interactive.test; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.testng.Assert; import org.testng.annotations.Test; import edu.stanford.nlp.sempre.ContextValue; import edu.stanford.nlp.sempre.Executor; import edu.stanford.nlp.sempre.Formula; import edu.stanford.nlp.sempre.Formulas; import edu.stanford.nlp.sempre.Json; import edu.stanford.nlp.sempre.NaiveKnowledgeGraph; import edu.stanford.nlp.sempre.StringValue; import edu.stanford.nlp.sempre.interactive.DALExecutor; import edu.stanford.nlp.sempre.interactive.Item; import edu.stanford.nlp.sempre.interactive.SymbolTable; import edu.stanford.nlp.sempre.interactive.World; import edu.stanford.nlp.sempre.interactive.voxelurn.Color; import edu.stanford.nlp.sempre.interactive.voxelurn.Voxel; import fig.basic.LispTree; import fig.basic.LogInfo; /** * Tests the DALExecutor * * @author sidaw */ public class SymbolTest { DALExecutor executor = new DALExecutor(); public static void runFormula(DALExecutor executor, String formula, ContextValue context, Predicate<World> checker) { Formulas.opts.shortNamedValue = true; LogInfo.begin_track("formula: %s", formula); DALExecutor.opts.worldType = "VoxelWorld"; Executor.Response response = executor.execute(Formulas.fromLispTree(LispTree.proto.parseFromString(formula)), context); NaiveKnowledgeGraph graph = (NaiveKnowledgeGraph) context.graph; String wallString = ((StringValue) graph.triples.get(0).e1).value; // LogInfo.logs("Preconvert %s", response.value); String jsonStr = ((StringValue) response.value).value; LogInfo.logs("Start:\t%s", wallString); LogInfo.logs("Result:\t%s", jsonStr); LogInfo.end_track(); if (checker != null) { if (!checker.test(World.fromContext("VoxelWorld", getContext(jsonStr)))) { LogInfo.end_track(); Assert.fail(jsonStr); } } } private static Formula F(String form) { return Formulas.fromLispTree(LispTree.proto.parseFromString(form)); } private static ContextValue getContext(String blocks) { // a hack to pass in the world state without much change to the code String strigify2 = Json.writeValueAsStringHard(blocks); // some parsing // issue inside // lisptree parser return ContextValue.fromString( String.format("(context (graph NaiveKnowledgeGraph ((string \"%s\") (name b) (name c))))", strigify2)); } @Test(groups = { "Interactive" }) public void testDefine() { // a rare unsupported operations bug String defaultBlocks = "[[1,1,1,\"fake\",[\"S\"]]]"; ContextValue context = getContext(defaultBlocks); LogInfo.begin_track("testDefine"); SymbolTable.singleton().addSymbol("tower", F("(:loop (number 3) (: add (name red color) (name top dir)))")); runFormula(executor, "(:: tower)", context, x -> x.allItems.size() == 4); runFormula(executor, "(:def tower (:loop (number 4) (: add (name red color) (name top dir))))", context, x -> true); runFormula(executor, "(:: tower 1)", context, x -> x.allItems.size() == 5); runFormula(executor, "(:: tower 0)", context, x -> x.allItems.size() == 4); LogInfo.end_track(); } @Test(groups = { "Interactive" }) public void testBasicSub() { // a rare unsupported operations bug String defaultBlocks = "[[1,1,1,\"fake\",[\"S\"]]]"; ContextValue context = getContext(defaultBlocks); LogInfo.begin_track("testBasicSub"); runFormula(executor, "(:def tower2 (:loop (number 4) (: add (name red color) (name top dir))))", context, x -> true); runFormula(executor, "(:sub (:: tower2 0) (number 4) (number 5))", context, x -> x.allItems.size() == 6); runFormula(executor, "(:sub (:: tower2 0) red blue)", context, x -> x.allItems.size() == 5); runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) (name top dir))) (number 4) (number 5))", context, x -> x.allItems.size() == 6); runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) (name top dir))) red blue)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).color.equals(Color.fromString("blue")))); runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) (name top dir))) top bot)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).height < 0)); // check that some variations behave normally runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) (name top dir))) (name red color) blue)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).color.equals(Color.fromString("blue")))); runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) top)) (name top dir) bot)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).height < 0)); LogInfo.end_track(); } @Test(groups = { "Interactive" }) public void testShortForm() { // a rare unsupported operations bug String defaultBlocks = "[[1,1,1,\"fake\",[\"S\"]]]"; ContextValue context = getContext(defaultBlocks); LogInfo.begin_track("testBasicSub"); runFormula(executor, "(:def tower2 (:loop (number 4) (: add red:C top:D)))", context, x -> true); runFormula(executor, "(:sub (:: tower2 0) (number 4) (number 5))", context, x -> x.allItems.size() == 6); runFormula(executor, "(:sub (:: tower2 0) red blue)", context, x -> x.allItems.size() == 5); runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) (name top dir))) (number 4) (number 5))", context, x -> x.allItems.size() == 6); runFormula(executor, "(:sub (:loop (number 4) (: add red:C (name top dir))) red:C blue:C)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).color.equals(Color.fromString("blue")))); runFormula(executor, "(:sub (:loop (number 4) (: add red:C top:D)) top bot)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).height < 0)); // check that some variations behave normally runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) (name top dir))) red:C blue)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).color.equals(Color.fromString("blue")))); runFormula(executor, "(:sub (:loop (number 4) (: add (name red color) top:D)) (name top D) bot)", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).height < 0)); LogInfo.end_track(); } // currently, do not expand all named functions recursively @Test(groups = { "Interactive" }) public void testRecurisveSub() { // a rare unsupported operations bug String defaultBlocks = "[[1,1,1,\"fake\",[\"S\"]]]"; ContextValue context = getContext(defaultBlocks); LogInfo.begin_track("testRecurisveSub"); runFormula(executor, "(:def tower2 (:loop (number 4) (: add (name red color) (name top dir))))", context, x -> true); runFormula(executor, "(:sub (:loop (number 3) (:: tower2 0)) (number 3) (number 5))", context, x -> x.allItems.size() == 21); runFormula(executor, "(:sub (:sub (:loop (number 4) (: add (name red color) top)) red blue) (number 4) (number 5))", context, x -> x.allItems.size() == 6 && x.all().stream().anyMatch(i -> ((Voxel)i).color.equals(Color.fromString("blue")))); runFormula(executor, "(:sub (:sub (:: tower2 0) red blue) (number 4) (number 5))", context, x -> x.allItems.size() == 5 && x.all().stream().anyMatch(i -> ((Voxel)i).color.equals(Color.fromString("blue")))); runFormula(executor, "(:sub (:sub (:sub (:loop (number 4) (: add (name red color) top)) red blue) (number 4) (number 5)) top bot)", context, x -> x.allItems.size() == 6 && x.all().stream().anyMatch(i -> ((Voxel)i).color.equals(Color.fromString("blue"))) && x.all().stream().anyMatch(i -> ((Voxel)i).height < 0)); LogInfo.end_track(); } }
45.868852
135
0.62092
43c54ca47237503dedade1ffb1d2603e7fde7b64
13,070
// VeriBlock NodeCore // Copyright 2017-2021 Xenios SEZC // All rights reserved. // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. package nodecore.api.ucp.commands; import nodecore.api.ucp.arguments.UCPArgument; import nodecore.api.ucp.commands.client.*; import nodecore.api.ucp.commands.server.*; import org.veriblock.core.types.Pair; import java.util.ArrayList; /** * UCP, or Universal Client Protocol, is a means for clients to communicate with a NodeCore instance over a raw socket * and get information regarding the current state of the blockchain and participate in a pool if a NodeCore operator * decides to operate one. */ public abstract class UCPCommand { public enum Command { // Commands that a UCP client sends to a UCP server MINING_AUTH(MiningAuth.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("username", UCPArgument.UCPType.USERNAME), new Pair<String, UCPArgument.UCPType>("password", UCPArgument.UCPType.PASSWORD)), MINING_SUBSCRIBE(MiningSubscribe.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("update_frequency_ms", UCPArgument.UCPType.FREQUENCY_MS)), MINING_SUBMIT(MiningSubmit.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("job_id", UCPArgument.UCPType.JOB_ID), new Pair<String, UCPArgument.UCPType>("nTime", UCPArgument.UCPType.TIMESTAMP), new Pair<String, UCPArgument.UCPType>("nonce", UCPArgument.UCPType.NONCE), new Pair<String, UCPArgument.UCPType>("extra_nonce", UCPArgument.UCPType.EXTRA_NONCE)), MINING_UNSUBSCRIBE(MiningUnsubscribe.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), MINING_RESET_ACK(MiningResetACK.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), MINING_MEMPOOL_UPDATE_ACK(MiningMempoolUpdateACK.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), GET_STATUS(GetStatus.class, new Pair<String, UCPArgument.UCPType>("", UCPArgument.UCPType.REQUEST_ID)), GET_ADDRESS_BALANCE_AND_INDEX(GetAddressBalanceAndIndex.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("address", UCPArgument.UCPType.ADDRESS)), GET_TRANSACTIONS_MATCHING_FILTER(GetTransactionsMatchingFilter.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("bloom_filter", UCPArgument.UCPType.BLOOM_FILTER), new Pair<String, UCPArgument.UCPType>("start_block", UCPArgument.UCPType.BLOCK_INDEX), new Pair<String, UCPArgument.UCPType>("stop_block", UCPArgument.UCPType.BLOCK_INDEX)), GET_BLOCK_HEADERS(GetBlockHeaders.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("start_block", UCPArgument.UCPType.BLOCK_INDEX), new Pair<String, UCPArgument.UCPType>("stop_block", UCPArgument.UCPType.BLOCK_INDEX)), SEND_TRANSACTION(SendTransaction.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("raw_transaction_data", UCPArgument.UCPType.TRANSACTION_DATA)), // Commands that a UCP server sends to a UCP client CAPABILITIES(Capabilities.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("capabilities", UCPArgument.UCPType.BITFLAG)), MINING_RESET(MiningReset.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), MINING_JOB(MiningJob.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("job_id", UCPArgument.UCPType.JOB_ID), new Pair<String, UCPArgument.UCPType>("block_index", UCPArgument.UCPType.BLOCK_INDEX), new Pair<String, UCPArgument.UCPType>("block_version", UCPArgument.UCPType.BLOCK_VERSION), new Pair<String, UCPArgument.UCPType>("previous_block_hash", UCPArgument.UCPType.BLOCK_HASH), new Pair<String, UCPArgument.UCPType>("second_previous_block_hash", UCPArgument.UCPType.BLOCK_HASH), new Pair<String, UCPArgument.UCPType>("third_previous_block_hash", UCPArgument.UCPType.BLOCK_HASH), new Pair<String, UCPArgument.UCPType>("pool_address", UCPArgument.UCPType.ADDRESS), new Pair<String, UCPArgument.UCPType>("merkle_root", UCPArgument.UCPType.TOP_LEVEL_MERKLE_ROOT), new Pair<String, UCPArgument.UCPType>("timestamp", UCPArgument.UCPType.TIMESTAMP), new Pair<String, UCPArgument.UCPType>("difficulty", UCPArgument.UCPType.DIFFICULTY), new Pair<String, UCPArgument.UCPType>("mining_target", UCPArgument.UCPType.TARGET), new Pair<String, UCPArgument.UCPType>("ledger_hash", UCPArgument.UCPType.LEDGER_HASH), new Pair<String, UCPArgument.UCPType>("coinbase_txid", UCPArgument.UCPType.TRANSACTION_ID), new Pair<String, UCPArgument.UCPType>("pop_datastore_hash", UCPArgument.UCPType.POP_DATASTORE_HASH), new Pair<String, UCPArgument.UCPType>("miner_comment", UCPArgument.UCPType.MINER_COMMENT), new Pair<String, UCPArgument.UCPType>("pop_transaction_merkle_root", UCPArgument.UCPType.INTERMEDIATE_LEVEL_MERKLE_ROOT), new Pair<String, UCPArgument.UCPType>("normal_transaction_merkle_root", UCPArgument.UCPType.INTERMEDIATE_LEVEL_MERKLE_ROOT), new Pair<String, UCPArgument.UCPType>("extra_nonce_start", UCPArgument.UCPType.EXTRA_NONCE), new Pair<String, UCPArgument.UCPType>("extra_nonce_end", UCPArgument.UCPType.EXTRA_NONCE), new Pair<String, UCPArgument.UCPType>("intermediate_metapackage_hash", UCPArgument.UCPType.INTERMEDIATE_METAPACKAGE_HASH)), MINING_MEMPOOL_UPDATE(MiningMempoolUpdate.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("job_id", UCPArgument.UCPType.JOB_ID), new Pair<String, UCPArgument.UCPType>("pop_transaction_merkle_root", UCPArgument.UCPType.INTERMEDIATE_LEVEL_MERKLE_ROOT), new Pair<String, UCPArgument.UCPType>("normal_transaction_merkle_root", UCPArgument.UCPType.INTERMEDIATE_LEVEL_MERKLE_ROOT), new Pair<String, UCPArgument.UCPType>("new_merkle_root", UCPArgument.UCPType.TOP_LEVEL_MERKLE_ROOT), new Pair<String, UCPArgument.UCPType>("intermediate_metapackage_hash", UCPArgument.UCPType.INTERMEDIATE_METAPACKAGE_HASH)), MINING_AUTH_SUCCESS(MiningAuthSuccess.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), MINING_AUTH_FAILURE(MiningAuthFailure.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("reason", UCPArgument.UCPType.MESSAGE)), MINING_SUBSCRIBE_SUCCESS(MiningSubscribeSuccess.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), MINING_SUBSCRIBE_FAILURE(MiningSubscribeFailure.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("reason", UCPArgument.UCPType.MESSAGE)), MINING_UNSUBSCRIBE_SUCCESS(MiningUnsubscribeSuccess.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), MINING_UNSUBSCRIBE_FAILURE(MiningUnsubscribeFailure.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("reason", UCPArgument.UCPType.MESSAGE)), MINING_SUBMIT_SUCCESS(MiningSubmitSuccess.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), MINING_SUBMIT_FAILURE(MiningSubmitFailure.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("reason", UCPArgument.UCPType.MESSAGE)), ADDRESS_BALANCE_AND_INDEX(AddressBalanceAndIndex.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("address", UCPArgument.UCPType.ADDRESS), new Pair<String, UCPArgument.UCPType>("balance", UCPArgument.UCPType.BALANCE), new Pair<String, UCPArgument.UCPType>("index", UCPArgument.UCPType.SIGNATURE_INDEX), new Pair<String, UCPArgument.UCPType>("ledger_merkle_path", UCPArgument.UCPType.MERKLE_PATH)), TRANSACTIONS_MATCHING_FILTER(TransactionsMatchingFilter.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("transactions_with_context", UCPArgument.UCPType.TRANSACTIONS_WITH_CONTEXT)), TRANSACTION_SENT(TransactionSent.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("transaction_id", UCPArgument.UCPType.TRANSACTION_ID)), BLOCK_HEADERS(BlockHeaders.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("block_headers", UCPArgument.UCPType.BLOCK_HEADER_LIST)), ERROR_TRANSACTION_INVALID(ErrorTransactionInvalid.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID), new Pair<String, UCPArgument.UCPType>("raw_transaction_data", UCPArgument.UCPType.TRANSACTION_DATA)), ERROR_RANGE_TOO_LONG(ErrorRangeTooLong.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), ERROR_RANGE_INVALID(ErrorRangeInvalid.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), ERROR_RANGE_NOT_AVAILABLE(ErrorRangeNotAvailable.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)), ERROR_UNKNOWN_COMMAND(ErrorUnknownCommand.class, new Pair<String, UCPArgument.UCPType>("request_id", UCPArgument.UCPType.REQUEST_ID)); private final ArrayList<Pair<String, UCPArgument.UCPType>> pattern; private final Class<? extends UCPCommand> implementingClass; @SafeVarargs Command(Class<? extends UCPCommand> implementation, Pair<String, UCPArgument.UCPType> ... arguments) { this.implementingClass = implementation; ArrayList<Pair<String, UCPArgument.UCPType>> args = new ArrayList<Pair<String, UCPArgument.UCPType>>(); for (int i = 0; i < arguments.length; i++) { args.add(arguments[i]); } this.pattern = args; } public ArrayList<Pair<String, UCPArgument.UCPType>> getPattern() { return pattern; } public Class<? extends UCPCommand> getCommandImplementingClass() { return implementingClass; } } /** * The "equality" of two UCPCommand objects should be based on producing identical serialized results * @param o Object to compare * @return Whether the provided object is equivalent to this object */ public boolean equals(Object o) { if (!(o instanceof UCPCommand)) { return false; } if (this.compileCommand().equals(((UCPCommand)(o)).compileCommand())) { return true; } return false; } @Override public int hashCode() { return compileCommand().hashCode(); } public abstract String compileCommand(); }
57.577093
140
0.697552
5a34212470fea58ea305b97113a2ad85caab609b
19,642
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/services/conversion_upload_service.proto package com.google.ads.googleads.v10.services; public final class ConversionUploadServiceProto { private ConversionUploadServiceProto() {} 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_v10_services_UploadClickConversionsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_UploadClickConversionsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_UploadClickConversionsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_UploadClickConversionsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_UploadCallConversionsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_UploadCallConversionsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_UploadCallConversionsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_UploadCallConversionsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_ClickConversion_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_ClickConversion_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_CallConversion_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_CallConversion_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_ExternalAttributionData_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_ExternalAttributionData_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_ClickConversionResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_ClickConversionResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_CallConversionResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_CallConversionResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_CustomVariable_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_CustomVariable_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_CartData_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_CartData_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_CartData_Item_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_CartData_Item_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nAgoogle/ads/googleads/v10/services/conv" + "ersion_upload_service.proto\022!google.ads." + "googleads.v10.services\0327google/ads/googl" + "eads/v10/common/offline_user_data.proto\032" + "\034google/api/annotations.proto\032\027google/ap" + "i/client.proto\032\037google/api/field_behavio" + "r.proto\032\031google/api/resource.proto\032\027goog" + "le/rpc/status.proto\"\274\001\n\035UploadClickConve" + "rsionsRequest\022\030\n\013customer_id\030\001 \001(\tB\003\340A\002\022" + "L\n\013conversions\030\002 \003(\01322.google.ads.google" + "ads.v10.services.ClickConversionB\003\340A\002\022\034\n" + "\017partial_failure\030\003 \001(\010B\003\340A\002\022\025\n\rvalidate_" + "only\030\004 \001(\010\"\236\001\n\036UploadClickConversionsRes" + "ponse\0221\n\025partial_failure_error\030\001 \001(\0132\022.g" + "oogle.rpc.Status\022I\n\007results\030\002 \003(\01328.goog" + "le.ads.googleads.v10.services.ClickConve" + "rsionResult\"\272\001\n\034UploadCallConversionsReq" + "uest\022\030\n\013customer_id\030\001 \001(\tB\003\340A\002\022K\n\013conver" + "sions\030\002 \003(\01321.google.ads.googleads.v10.s" + "ervices.CallConversionB\003\340A\002\022\034\n\017partial_f" + "ailure\030\003 \001(\010B\003\340A\002\022\025\n\rvalidate_only\030\004 \001(\010" + "\"\234\001\n\035UploadCallConversionsResponse\0221\n\025pa" + "rtial_failure_error\030\001 \001(\0132\022.google.rpc.S" + "tatus\022H\n\007results\030\002 \003(\01327.google.ads.goog" + "leads.v10.services.CallConversionResult\"" + "\376\004\n\017ClickConversion\022\022\n\005gclid\030\t \001(\tH\000\210\001\001\022" + "\016\n\006gbraid\030\022 \001(\t\022\016\n\006wbraid\030\023 \001(\t\022\036\n\021conve" + "rsion_action\030\n \001(\tH\001\210\001\001\022!\n\024conversion_da" + "te_time\030\013 \001(\tH\002\210\001\001\022\035\n\020conversion_value\030\014" + " \001(\001H\003\210\001\001\022\032\n\rcurrency_code\030\r \001(\tH\004\210\001\001\022\025\n" + "\010order_id\030\016 \001(\tH\005\210\001\001\022]\n\031external_attribu" + "tion_data\030\007 \001(\0132:.google.ads.googleads.v" + "10.services.ExternalAttributionData\022K\n\020c" + "ustom_variables\030\017 \003(\01321.google.ads.googl" + "eads.v10.services.CustomVariable\022>\n\tcart" + "_data\030\020 \001(\0132+.google.ads.googleads.v10.s" + "ervices.CartData\022I\n\020user_identifiers\030\021 \003" + "(\0132/.google.ads.googleads.v10.common.Use" + "rIdentifierB\010\n\006_gclidB\024\n\022_conversion_act" + "ionB\027\n\025_conversion_date_timeB\023\n\021_convers" + "ion_valueB\020\n\016_currency_codeB\013\n\t_order_id" + "\"\223\003\n\016CallConversion\022\026\n\tcaller_id\030\007 \001(\tH\000" + "\210\001\001\022!\n\024call_start_date_time\030\010 \001(\tH\001\210\001\001\022\036" + "\n\021conversion_action\030\t \001(\tH\002\210\001\001\022!\n\024conver" + "sion_date_time\030\n \001(\tH\003\210\001\001\022\035\n\020conversion_" + "value\030\013 \001(\001H\004\210\001\001\022\032\n\rcurrency_code\030\014 \001(\tH" + "\005\210\001\001\022K\n\020custom_variables\030\r \003(\01321.google." + "ads.googleads.v10.services.CustomVariabl" + "eB\014\n\n_caller_idB\027\n\025_call_start_date_time" + "B\024\n\022_conversion_actionB\027\n\025_conversion_da" + "te_timeB\023\n\021_conversion_valueB\020\n\016_currenc" + "y_code\"\253\001\n\027ExternalAttributionData\022(\n\033ex" + "ternal_attribution_credit\030\003 \001(\001H\000\210\001\001\022\'\n\032" + "external_attribution_model\030\004 \001(\tH\001\210\001\001B\036\n" + "\034_external_attribution_creditB\035\n\033_extern" + "al_attribution_model\"\222\002\n\025ClickConversion" + "Result\022\022\n\005gclid\030\004 \001(\tH\000\210\001\001\022\016\n\006gbraid\030\010 \001" + "(\t\022\016\n\006wbraid\030\t \001(\t\022\036\n\021conversion_action\030" + "\005 \001(\tH\001\210\001\001\022!\n\024conversion_date_time\030\006 \001(\t" + "H\002\210\001\001\022I\n\020user_identifiers\030\007 \003(\0132/.google" + ".ads.googleads.v10.common.UserIdentifier" + "B\010\n\006_gclidB\024\n\022_conversion_actionB\027\n\025_con" + "version_date_time\"\352\001\n\024CallConversionResu" + "lt\022\026\n\tcaller_id\030\005 \001(\tH\000\210\001\001\022!\n\024call_start" + "_date_time\030\006 \001(\tH\001\210\001\001\022\036\n\021conversion_acti" + "on\030\007 \001(\tH\002\210\001\001\022!\n\024conversion_date_time\030\010 " + "\001(\tH\003\210\001\001B\014\n\n_caller_idB\027\n\025_call_start_da" + "te_timeB\024\n\022_conversion_actionB\027\n\025_conver" + "sion_date_time\"{\n\016CustomVariable\022Z\n\032conv" + "ersion_custom_variable\030\001 \001(\tB6\372A3\n1googl" + "eads.googleapis.com/ConversionCustomVari" + "able\022\r\n\005value\030\002 \001(\t\"\371\001\n\010CartData\022\023\n\013merc" + "hant_id\030\006 \001(\003\022\031\n\021feed_country_code\030\002 \001(\t" + "\022\032\n\022feed_language_code\030\003 \001(\t\022\036\n\026local_tr" + "ansaction_cost\030\004 \001(\001\022?\n\005items\030\005 \003(\01320.go" + "ogle.ads.googleads.v10.services.CartData" + ".Item\032@\n\004Item\022\022\n\nproduct_id\030\001 \001(\t\022\020\n\010qua" + "ntity\030\002 \001(\005\022\022\n\nunit_price\030\003 \001(\0012\364\004\n\027Conv" + "ersionUploadService\022\211\002\n\026UploadClickConve" + "rsions\[email protected]" + "es.UploadClickConversionsRequest\032A.googl" + "e.ads.googleads.v10.services.UploadClick" + "ConversionsResponse\"j\202\323\344\223\002:\"5/v10/custom" + "ers/{customer_id=*}:uploadClickConversio" + "ns:\001*\332A\'customer_id,conversions,partial_" + "failure\022\205\002\n\025UploadCallConversions\022?.goog" + "le.ads.googleads.v10.services.UploadCall" + "ConversionsRequest\[email protected]" + "s.v10.services.UploadCallConversionsResp" + "onse\"i\202\323\344\223\0029\"4/v10/customers/{customer_i" + "d=*}:uploadCallConversions:\001*\332A\'customer" + "_id,conversions,partial_failure\032E\312A\030goog" + "leads.googleapis.com\322A\'https://www.googl" + "eapis.com/auth/adwordsB\210\002\n%com.google.ad" + "s.googleads.v10.servicesB\034ConversionUplo" + "adServiceProtoP\001ZIgoogle.golang.org/genp" + "roto/googleapis/ads/googleads/v10/servic" + "es;services\242\002\003GAA\252\002!Google.Ads.GoogleAds" + ".V10.Services\312\002!Google\\Ads\\GoogleAds\\V10" + "\\Services\352\002%Google::Ads::GoogleAds::V10:" + ":Servicesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v10.common.OfflineUserDataProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.rpc.StatusProto.getDescriptor(), }); internal_static_google_ads_googleads_v10_services_UploadClickConversionsRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v10_services_UploadClickConversionsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_UploadClickConversionsRequest_descriptor, new java.lang.String[] { "CustomerId", "Conversions", "PartialFailure", "ValidateOnly", }); internal_static_google_ads_googleads_v10_services_UploadClickConversionsResponse_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v10_services_UploadClickConversionsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_UploadClickConversionsResponse_descriptor, new java.lang.String[] { "PartialFailureError", "Results", }); internal_static_google_ads_googleads_v10_services_UploadCallConversionsRequest_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v10_services_UploadCallConversionsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_UploadCallConversionsRequest_descriptor, new java.lang.String[] { "CustomerId", "Conversions", "PartialFailure", "ValidateOnly", }); internal_static_google_ads_googleads_v10_services_UploadCallConversionsResponse_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_ads_googleads_v10_services_UploadCallConversionsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_UploadCallConversionsResponse_descriptor, new java.lang.String[] { "PartialFailureError", "Results", }); internal_static_google_ads_googleads_v10_services_ClickConversion_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_ads_googleads_v10_services_ClickConversion_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_ClickConversion_descriptor, new java.lang.String[] { "Gclid", "Gbraid", "Wbraid", "ConversionAction", "ConversionDateTime", "ConversionValue", "CurrencyCode", "OrderId", "ExternalAttributionData", "CustomVariables", "CartData", "UserIdentifiers", "Gclid", "ConversionAction", "ConversionDateTime", "ConversionValue", "CurrencyCode", "OrderId", }); internal_static_google_ads_googleads_v10_services_CallConversion_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_ads_googleads_v10_services_CallConversion_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_CallConversion_descriptor, new java.lang.String[] { "CallerId", "CallStartDateTime", "ConversionAction", "ConversionDateTime", "ConversionValue", "CurrencyCode", "CustomVariables", "CallerId", "CallStartDateTime", "ConversionAction", "ConversionDateTime", "ConversionValue", "CurrencyCode", }); internal_static_google_ads_googleads_v10_services_ExternalAttributionData_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_ads_googleads_v10_services_ExternalAttributionData_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_ExternalAttributionData_descriptor, new java.lang.String[] { "ExternalAttributionCredit", "ExternalAttributionModel", "ExternalAttributionCredit", "ExternalAttributionModel", }); internal_static_google_ads_googleads_v10_services_ClickConversionResult_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_ads_googleads_v10_services_ClickConversionResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_ClickConversionResult_descriptor, new java.lang.String[] { "Gclid", "Gbraid", "Wbraid", "ConversionAction", "ConversionDateTime", "UserIdentifiers", "Gclid", "ConversionAction", "ConversionDateTime", }); internal_static_google_ads_googleads_v10_services_CallConversionResult_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_ads_googleads_v10_services_CallConversionResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_CallConversionResult_descriptor, new java.lang.String[] { "CallerId", "CallStartDateTime", "ConversionAction", "ConversionDateTime", "CallerId", "CallStartDateTime", "ConversionAction", "ConversionDateTime", }); internal_static_google_ads_googleads_v10_services_CustomVariable_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_ads_googleads_v10_services_CustomVariable_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_CustomVariable_descriptor, new java.lang.String[] { "ConversionCustomVariable", "Value", }); internal_static_google_ads_googleads_v10_services_CartData_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_ads_googleads_v10_services_CartData_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_CartData_descriptor, new java.lang.String[] { "MerchantId", "FeedCountryCode", "FeedLanguageCode", "LocalTransactionCost", "Items", }); internal_static_google_ads_googleads_v10_services_CartData_Item_descriptor = internal_static_google_ads_googleads_v10_services_CartData_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v10_services_CartData_Item_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_CartData_Item_descriptor, new java.lang.String[] { "ProductId", "Quantity", "UnitPrice", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.ClientProto.defaultHost); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.AnnotationsProto.http); registry.add(com.google.api.ClientProto.methodSignature); registry.add(com.google.api.ClientProto.oauthScopes); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); com.google.ads.googleads.v10.common.OfflineUserDataProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.rpc.StatusProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
67.731034
327
0.77823
b30951f47299e4318d892b8356bb3cb9bdf3ceeb
10,206
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.nexial.core.variable; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.text.WordUtils; import org.nexial.commons.utils.RegexUtils; import org.nexial.commons.utils.TextUtils; import org.nexial.core.utils.ConsoleUtils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.NumberFormat; import static java.io.File.separator; import static java.lang.Double.MIN_VALUE; import static org.nexial.core.NexialConst.*; /** * Cheatsheet here - http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html */ public class Format { private static final NumberFormat FORMAT_INT = NumberFormat.getIntegerInstance(); private static final NumberFormat FORMAT_PERCENT = NumberFormat.getPercentInstance(); private static final NumberFormat FORMAT_CURRENCY = NumberFormat.getCurrencyInstance(); public Format() { init(); } public String upper(String text) { return StringUtils.upperCase(text); } public String lower(String text) { return StringUtils.lowerCase(text); } public String titlecase(String text) { return WordUtils.capitalizeFully(text); } public String left(String text, String length) { if (!NumberUtils.isDigits(length)) { ConsoleUtils.error("Error at Format.left() - length " + length + " is not a number"); return text; } return StringUtils.left(text, NumberUtils.toInt(length)); } public String right(String text, String length) { if (!NumberUtils.isDigits(length)) { ConsoleUtils.error("Error at Format.right() - length " + length + " is not a number"); return text; } return StringUtils.right(text, NumberUtils.toInt(length)); } public String integer(String text) { return numberFormat(text, FORMAT_INT); } public String number(String text, String format) { String onlyNumbers = toNumeric(text); if (StringUtils.isBlank(format)) { return onlyNumbers; } double converted = NumberUtils.toDouble(onlyNumbers, MIN_VALUE); if (converted == MIN_VALUE) { ConsoleUtils.error("Format.number(): Unable to convert into number - " + text + "; TEXT UNCHANGED"); return text; } return new DecimalFormat(format).format(converted); } public String percent(String text) { return numberFormat(text, FORMAT_PERCENT); } public String dollar(String text) { return numberFormat(text, FORMAT_CURRENCY); } /** format text into xxx-xxx-xxxx format */ public String ssn(String text) { if (StringUtils.isBlank(text)) { return text; } //return text.replaceAll("(...)(...)(.*)", "$1-$2-$3"); if (StringUtils.length(text) < 4) { return text; } text = StringUtils.substring(text, 0, 3) + "-" + StringUtils.substring(text, 3); if (StringUtils.length(text) < 7) { return text; } text = StringUtils.substring(text, 0, 6) + "-" + StringUtils.substring(text, 6); return text; } public String phone(String text) { if (StringUtils.isBlank(text)) { return text; } text = StringUtils.trim(RegexUtils.removeMatches(text.trim(), "[\\.\\-\\(\\)]+")); if (StringUtils.length(text) < 7) { return text; } if (StringUtils.length(text) == 7) { return text.replaceAll("(...)(.+)", "$1-$2"); } if (StringUtils.length(text) == 10) { return text.replaceAll("(...)(...)(.+)", "($1)$2-$3"); } if (StringUtils.length(text) == 11) { return text.replaceAll("(.)(...)(...)(.+)", "$1($2)$3-$4"); } String newPhone = TextUtils.insert(StringUtils.reverse(text), 4, "-"); if (StringUtils.length(newPhone) >= 11) { newPhone = TextUtils.insert(newPhone, 8, ")"); newPhone = TextUtils.insert(newPhone, 12, "("); } else { newPhone = TextUtils.insert(newPhone, 8, "-"); } return StringUtils.reverse(newPhone); } public String strip(String text, String omit) { if (StringUtils.isEmpty(text)) { return text; } if (StringUtils.isEmpty(omit)) { return text; } return StringUtils.replaceEach(text, new String[]{omit}, new String[]{""}); } /** * special characters:<ul> * <li>` (back tick)- 1 character</li> * <li>all other characters - formatting characters</li> * </ul> * <br/> * For example: {@code custom("1234567890ABCDE", "(```) ```-````")} would yield {@code "(123) 456-7890"}. All * extra characters are thrown out */ public String custom(String text, String format) { if (StringUtils.isBlank(format)) { return text; } if (StringUtils.isEmpty(text)) { return text; } int currentPos = 0; StringBuilder buffer = new StringBuilder(); char[] template = format.toCharArray(); for (Character c : template) { if (c != '`') { buffer.append(c); } else { buffer.append(StringUtils.substring(text, currentPos, 1 + currentPos)); currentPos++; } } return buffer.toString(); } public String mask(String text, String start, String end, String maskChar) { if (StringUtils.isBlank(text)) { return text; } if (!NumberUtils.isDigits(start)) { ConsoleUtils.error("Error at Format.mask() - start " + start + " is not a number"); return text; } if (!NumberUtils.isDigits(end)) { ConsoleUtils.error("Error at Format.mask() - end " + end + " is not a number"); return text; } int startNum = NumberUtils.toInt(start); int endNum = NumberUtils.toInt(end); if (startNum < 0) { ConsoleUtils.error("Error at Format.mask() - start " + start + " is less than zero"); return text; } if (endNum < 0) { ConsoleUtils.error("Error at Format.mask() - end " + end + " is less than zero"); return text; } if (endNum > text.length()) { endNum = text.length(); } if (startNum >= endNum) { ConsoleUtils.error("Error at Format.mask() - start " + start + " is greater or equal to end " + end); return text; } int maskLength = endNum - startNum; if (StringUtils.isEmpty(maskChar)) { maskChar = "#"; } return StringUtils.substring(text, 0, startNum) + StringUtils.repeat(maskChar.charAt(0), maskLength) + StringUtils.substring(text, endNum); } public String urlencode(String text) { try { return URLEncoder.encode(text, DEF_CHARSET); } catch (UnsupportedEncodingException e) { ConsoleUtils.error("Unable to url-encode " + text + ": " + e.getMessage()); return text; } } public String urldecode(String text) { try { return URLDecoder.decode(text, DEF_CHARSET); } catch (UnsupportedEncodingException e) { ConsoleUtils.error("Unable to url-encode " + text + ": " + e.getMessage()); return text; } } /** * convert a fully qualified local path to a file URI (i.e. file://...). * <p> * Invalid or unresolved path will resort to using the current project directory. */ public String fileURI(String text) { if (StringUtils.isBlank(text)) { return text; } java.io.File f = new java.io.File(text); String normalized = f.exists() ? f.getAbsolutePath() : new java.io.File( StringUtils.appendIfMissing(new Syspath().project("fullpath"), separator) + text ).getAbsolutePath(); normalized = StringUtils.replace(normalized, " ", "%20"); normalized = StringUtils.replace(normalized, "\\", "/"); if (RegexUtils.isExact(normalized, "^[A-Za-z]\\:.+$")) { normalized = "/" + normalized; } return "file://" + normalized; } public String base64encode(String text) { return TextUtils.base64encode(text); } public String base64decode(String text) { return TextUtils.base64decode(text); } protected void init() { FORMAT_INT.setGroupingUsed(false); FORMAT_PERCENT.setMaximumFractionDigits(2); } protected String numberFormat(String text, NumberFormat formatter) { String onlyNumbers = toNumeric(text); double converted = NumberUtils.toDouble(onlyNumbers, MIN_VALUE); if (converted == MIN_VALUE) { ConsoleUtils.error(TOKEN_FUNCTION_START + "format" + TOKEN_FUNCTION_END + ": Unable to convert into number - " + text + "; TEXT UNCHANGED"); return text; } return formatter.format(converted); } protected static String toNumeric(String text) { // sanity check if (StringUtils.isBlank(text)) { return text; } // trim first to avoid false interpretation of negative signs String text1 = StringUtils.trim(text); // remove non-numeric chars, but include decimal points String onlyNumbers = RegexUtils.replace(text1, "([^0-9.]+)*", ""); // add back the negative sign, if any if (StringUtils.startsWithAny(text1, "-")) { onlyNumbers = "-" + onlyNumbers; } return onlyNumbers; } }
37.94052
114
0.611503
c21c2491ef23a80b416669727335999289867d13
1,153
package com.walmartlabs.concord.common; /*- * ***** * Concord * ----- * Copyright (C) 2017 - 2020 Walmart 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. * ===== */ public final class StringUtils { public static String abbreviate(String str, int maxWidth) { if (str == null) { return null; } if (maxWidth < 4) { throw new IllegalArgumentException("Minimum abbreviation width is 4"); } if (str.length() <= maxWidth) { return str; } return str.substring(0, maxWidth - 3) + "..."; } private StringUtils() { } }
26.204545
82
0.62706
27a242d2ef3d5aecf5fbc43e5c15885ebbe29d57
1,483
package laz.tirphycraft.content.entities.goal.necromancer; import java.util.EnumSet; import java.util.Random; import laz.tirphycraft.content.entities.froz.EntityNecromancer; import laz.tirphycraft.util.TirphycraftUtils; import net.minecraft.entity.ai.goal.Goal; import net.minecraft.util.math.BlockPos; public class TeleportGoal extends Goal { EntityNecromancer attacker; boolean done; public TeleportGoal(EntityNecromancer creature) { this.attacker = creature; this.setMutexFlags(EnumSet.of(Goal.Flag.LOOK, Goal.Flag.TARGET)); this.done = false; } @Override public boolean shouldExecute() { if (attacker.c1 == null || attacker.c2 == null) return false; if (attacker.getAttackTarget() != null) { BlockPos pos1 = attacker.getPosition(); BlockPos pos2 = attacker.getAttackTarget().getPosition(); double dist = TirphycraftUtils.hypot(pos1.getX() - pos2.getX(), pos1.getY() - pos2.getY(), pos1.getZ() - pos2.getZ()); if (dist < 6) { return attacker.getRNG().nextInt((int) (dist +1)) == 0; } return false; } return false; } public boolean shouldContinueExecuting() { return false; } @Override public void tick() { Random rand = attacker.getRNG(); double x = attacker.c2.getX() - attacker.c1.getX() - 2; double z = attacker.c2.getZ() - attacker.c1.getZ() - 2; attacker.setPositionAndUpdate(attacker.c1.getX() + rand.nextInt((int) x) + 1, attacker.getPosY(), attacker.c1.getZ() + rand.nextInt((int) z) + 1); } }
28.519231
99
0.706001
6f2902c467ea6e2cc659ee01ab10f2104bbad606
777
/* * Copyright 2018 Dragon-Labs.net * * 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 */ package de.dragonlabs.scaleadapter.library.exceptions; import de.dragonlabs.scaleadapter.library.packet.ScalePacket; /** * This Exception is be called when someone try to register a packet with an id, that is already registered */ public class PacketIdAlreadyExistsException extends RuntimeException { public PacketIdAlreadyExistsException(Byte id, Class<? extends ScalePacket> packetClass) { super("Packet with ID '" + id + "' already registered and can't use for " + packetClass); } }
33.782609
171
0.7426
63bf866400cd4ba39d0046f111a2095ca2b6fdf5
4,366
package com.mmall.util.XML; /** * Created by IntelliJ IDEA * User: leroy * Time: 2017/12/1 10:49 */ import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import com.alibaba.fastjson.JSON; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * 入口程序 * * @author ChenFeng * @version [版本号, 2009-12-21] * @see [相关类/方法] * @since [产品/模块版本] */ public class XMLParseUtilTest { /** * 入口函数 * * @param args * @see [类、类#方法、类#成员] */ public static void main(String[] args) { String path ="D:\\Project\\JAVA\\imooc\\mmall_learning\\src\\main\\java\\com\\mmall\\util\\XML\\Book.xml"; XMLParseUtil xmlParse = null; try { xmlParse = new XMLParseUtil(); } catch (ParserConfigurationException e) { System.out.println("异常:创建XML解析器过程中有一个严重的配置错误!"); e.printStackTrace(); } if (null != xmlParse) { Document doc = null; try { doc = xmlParse.parseDocument(path); } catch (MalformedURLException e) { System.out.println("异常:传入文件路径错误!找不到要解析的文件!"); e.printStackTrace(); } catch (SAXParseException e) { System.out.println("异常:文件格式错误!无法解析!"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (null != doc) { NodeList bookNodeList = null; try { /** * [title/@lang='en']表示选取的book节点,必须满足子节点title的lang属性为en */ bookNodeList = (NodeList) xmlParse.selectNodes(doc, "//bookstore/book[title/@lang='en']"); } catch (XPathExpressionException e) { System.out.println("异常:XPath表达式错误!"); e.printStackTrace(); } if (null != bookNodeList) { List<Book> bookList = new ArrayList<Book>(); for (int i = 0; i < bookNodeList.getLength(); i++) { Node node = bookNodeList.item(i); Book book = parseBookNode(xmlParse, node); bookList.add(book); } for (Book book : bookList) { System.out.println(book.toString()); } } } } } /** * 解析单个book节点 * * @param util * @param node * @return * @throws XPathExpressionException * @see [类、类#方法、类#成员] */ public static Book parseBookNode(XMLParseUtil util, Node node) { String lang = ""; String title = ""; String author = ""; String year = ""; String price = ""; try { title = util.getNodeStringValue(node, "./title"); } catch (XPathExpressionException e) { System.out.println("异常:XPath表达式错误!"); e.printStackTrace(); } try { lang = util.getNodeStringValue(node, "./title/@lang"); } catch (XPathExpressionException e) { System.out.println("异常:XPath表达式错误!"); e.printStackTrace(); } try { author = util.getNodeStringValue(node, "./author"); } catch (XPathExpressionException e) { System.out.println("异常:XPath表达式错误!"); e.printStackTrace(); } try { year = util.getNodeStringValue(node, "./year"); } catch (XPathExpressionException e) { System.out.println("异常:XPath表达式错误!"); e.printStackTrace(); } try { price = util.getNodeStringValue(node, "./price"); } catch (XPathExpressionException e) { System.out.println("异常:XPath表达式错误!"); e.printStackTrace(); } Book book = new Book(lang, title, author, year, price); return book; } }
29.90411
114
0.514888
dce435d97f9b4b66f17d49f96a5ceb38c7b041fe
367
package ru.job4j.basepatterns.behavioral.iterator.example2.social_networks; import ru.job4j.basepatterns.behavioral.iterator.example2.iterators.ProfileIterator; /** * Интерфейс социальной сети */ public interface SocialNetwork { ProfileIterator createFriendsIterator(String profileEmail); ProfileIterator createCoworkersIterator(String profileEmail); }
26.214286
84
0.825613
ef5490e234415c399a9f1293e38ed135a709c776
426
package de.percsi.products.dackelcmdb; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; @SpringBootApplication public class DackelCMDBTestPersistenceService { public static void main(String[] args) { SpringApplication.run(DackelCMDBTestPersistenceService.class, args); } }
32.769231
72
0.838028
45da7fed0c01a8a842a33e6e58a9fc964bab6827
2,941
/** * */ package com.lanking.uxb.zycon.task.form; import com.alibaba.fastjson.JSON; import com.lanking.cloud.domain.yoo.honor.userTask.UserTaskRuleCfg; import com.lanking.cloud.domain.yoo.honor.userTask.UserTaskStatus; import com.lanking.cloud.domain.yoo.honor.userTask.UserTaskUserScope; /** * @author <a href="mailto:[email protected]">zemin.song</a> * */ public class ZycUserTaskForm { private Integer code; private Long icon; private String name; private String note; private String growthNote; private String coinsNote; private int type; private UserTaskUserScope userScope; private UserTaskUserScope userTaskUserScope; private String ruleCfg; private UserTaskRuleCfg userTaskRuleCfg; private Integer sequence; private UserTaskStatus userTaskStatus; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Long getIcon() { return icon; } public void setIcon(Long icon) { this.icon = icon; } public UserTaskUserScope getUserScope() { return userScope; } public void setUserScope(UserTaskUserScope userScope) { this.userScope = userScope; } public String getName() { return name; } public void setName(String name) { this.name = name; } public UserTaskUserScope getUserTaskUserScope() { return userTaskUserScope; } public void setUserTaskUserScope(UserTaskUserScope userTaskUserScope) { this.userTaskUserScope = userTaskUserScope; } public String getRuleCfg() { return ruleCfg; } public void setRuleCfg(String ruleCfg) { this.ruleCfg = ruleCfg; } public UserTaskRuleCfg getUserTaskRuleCfg() { if (getRuleCfg() == null) { return null; } return JSON.parseObject(getRuleCfg(), UserTaskRuleCfg.class); } public void setUserTaskRuleCfg(UserTaskRuleCfg userTaskRuleCfg) { if (userTaskRuleCfg == null) { setRuleCfg(null); } else { setRuleCfg(userTaskRuleCfg.toString()); } this.userTaskRuleCfg = userTaskRuleCfg; } public int getType() { return type; } public void setType(int type) { this.type = type; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getGrowthNote() { return growthNote; } public void setGrowthNote(String growthNote) { this.growthNote = growthNote; } public String getCoinsNote() { return coinsNote; } public void setCoinsNote(String coinsNote) { this.coinsNote = coinsNote; } public UserTaskStatus getUserTaskStatus() { return userTaskStatus; } public void setUserTaskStatus(UserTaskStatus userTaskStatus) { this.userTaskStatus = userTaskStatus; } }
19.097403
73
0.696702
4d7a5746b2bdd46f708e6e0cbf3a8fe6a3947436
3,552
package io.kestra.core.services; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.junit.jupiter.api.Test; import io.kestra.core.models.flows.Flow; import io.kestra.core.tasks.debugs.Return; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @MicronautTest class FlowServiceTest { @Inject private FlowService flowService; private static Flow create(String flowId, String taskId, Integer revision) { return Flow.builder() .id(flowId) .namespace("io.kestra.unittest") .revision(revision) .tasks(Collections.singletonList(Return.builder() .id(taskId) .type(Return.class.getName()) .format("test") .build())) .build(); } @Test public void sameRevisionWithDeletedOrdered() { Stream<Flow> stream = Stream.of( create("test", "test", 1), create("test", "test2", 2), create("test", "test2", 2).toDeleted(), create("test", "test2", 4) ); List<Flow> collect = flowService.keepLastVersion(stream).collect(Collectors.toList()); assertThat(collect.size(), is(1)); assertThat(collect.get(0).isDeleted(), is(false)); assertThat(collect.get(0).getRevision(), is(4)); } @Test public void sameRevisionWithDeletedSameRevision() { Stream<Flow> stream = Stream.of( create("test2", "test2", 1), create("test", "test", 1), create("test", "test2", 2), create("test", "test3", 3), create("test", "test2", 2).toDeleted() ); List<Flow> collect = flowService.keepLastVersion(stream).collect(Collectors.toList()); assertThat(collect.size(), is(1)); assertThat(collect.get(0).isDeleted(), is(false)); assertThat(collect.get(0).getId(), is("test2")); } @Test public void sameRevisionWithDeletedUnordered() { Stream<Flow> stream = Stream.of( create("test", "test", 1), create("test", "test2", 2), create("test", "test2", 4), create("test", "test2", 2).toDeleted() ); List<Flow> collect = flowService.keepLastVersion(stream).collect(Collectors.toList()); assertThat(collect.size(), is(1)); assertThat(collect.get(0).isDeleted(), is(false)); assertThat(collect.get(0).getRevision(), is(4)); } @Test public void multipleFlow() { Stream<Flow> stream = Stream.of( create("test", "test", 2), create("test", "test2", 1), create("test2", "test2", 1), create("test2", "test3", 3), create("test3", "test1", 2), create("test3", "test2", 3) ); List<Flow> collect = flowService.keepLastVersion(stream).collect(Collectors.toList()); assertThat(collect.size(), is(3)); assertThat(collect.stream().filter(flow -> flow.getId().equals("test")).findFirst().orElseThrow().getRevision(), is(2)); assertThat(collect.stream().filter(flow -> flow.getId().equals("test2")).findFirst().orElseThrow().getRevision(), is(3)); assertThat(collect.stream().filter(flow -> flow.getId().equals("test3")).findFirst().orElseThrow().getRevision(), is(3)); } }
34.485437
129
0.595439
210fb0cfa851ee694907ed270f7f376c91eb8a88
2,067
package org.cwjweixin.weixin.Json; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import org.cwjweixin.weixin.domain.InMessage; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonRedisSerializer<T> extends Jackson2JsonRedisSerializer<T> { private ObjectMapper objectMapper=new ObjectMapper(); @SuppressWarnings("unchecked") public JsonRedisSerializer() { super((Class<T>) InMessage.class); } @Override public T deserialize(byte[] bytes) throws SerializationException { ByteArrayInputStream bis =new ByteArrayInputStream(bytes); DataInputStream in =new DataInputStream(bis); try { int len = in.readInt(); byte[] classNameBytes=new byte[len]; in.readFully(classNameBytes); String className=new String(classNameBytes,"UTF-8"); @SuppressWarnings("unchecked") Class<T> cla=(Class<T>) Class.forName(className); T o=objectMapper.readValue(Arrays.copyOfRange(bytes, len + 4, bytes.length), cla); return o; } catch (IOException | ClassNotFoundException e) { throw new SerializationException(e.getLocalizedMessage(),e); } } @Override public byte[] serialize(Object t) throws SerializationException { ByteArrayOutputStream bos=new ByteArrayOutputStream(); DataOutputStream out=new DataOutputStream(bos); try { // out.writeUTF(t.getClass().getName()); String className=t.getClass().getName(); byte[] classNameBytes=className.getBytes(); out.writeInt(classNameBytes.length); out.write(classNameBytes); out.write(super.serialize(t)); out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bos.toByteArray(); } }
28.315068
86
0.72327
7c18431044315da503ca8bbec74bd54a37f595d8
547
package com.ansorgit.plugins.bash.lang.psi.fileInclude; import org.junit.Test; public class FunctionResolveFileIncludeTestCase extends AbstractFileIncludeTest { @Override protected String getTestDataPath() { return super.getTestDataPath() + "functionResolve/"; } @Test public void testSimpleResolve1() throws Exception { checkWithIncludeFile("includedFile.bash", true); } @Test public void testSimpleResolve2() throws Exception { checkWithIncludeFile("includedFile.bash", true); } }
26.047619
81
0.718464
e9b6313d2b9bdc9a26aef21a0d8411207d2a0fca
2,599
package bank.acquirer; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import bank.acquirer.dto.TransactionRequestDTO; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonMappingTests { @Test public void mapTransactionRequestToJson_ShouldContainAllTransactionAttributes() throws JsonProcessingException { ObjectMapper mapper = createObjectMapper(); TransactionRequestDTO request = TransactionsUtil.createValidTransactionRequest(); String requestAsJson = mapper.writeValueAsString(request); boolean jsonContainsCardInfo = requestAsJson.indexOf("cardInfo") != -1; boolean jsonContainsAcquirerInfo = requestAsJson.indexOf("acquirerInfo") != -1; boolean jsonContainsTransactionAmount = requestAsJson.indexOf("transactionAmount") != -1; boolean allAttributesMapped = jsonContainsCardInfo && jsonContainsAcquirerInfo && jsonContainsTransactionAmount; assertTrue(allAttributesMapped); } @Test public void parseJsonFromInputStream_WithValidJson_ShouldCreateTransactionRequest() { ObjectMapper objectMapper = createObjectMapper(); InputStream inputStream = getClass().getClassLoader() .getResourceAsStream("validTransactionRequest.json"); TransactionRequestDTO transacactionRequest = null; try { transacactionRequest = objectMapper.readValue(inputStream, TransactionRequestDTO.class); } catch (IOException e) { e.printStackTrace(); } assertNotNull(transacactionRequest); } @Test(expected = JsonMappingException.class) public void parseJsonFromInputStream_WithInvalidAcquirerTimestampFormat_ShouldThrowException() throws JsonParseException, JsonMappingException, IOException { ObjectMapper objectMapper = createObjectMapper(); InputStream inputStream = getClass().getClassLoader() .getResourceAsStream("invalidTimestampFormatTransactionRequest.json"); objectMapper.readValue(inputStream, TransactionRequestDTO.class); } @Test public void testMappingObjectToJson() throws JsonProcessingException { TransactionRequestDTO request = TransactionsUtil.createValidTransactionRequest(); ObjectMapper mapper = createObjectMapper(); System.out.println(mapper.writeValueAsString(request)); } private static ObjectMapper createObjectMapper() { return new ObjectMapper(); } }
32.08642
113
0.807234
332cd68137ef292afdf7c7c3854728488b3e76ff
5,742
/* */ package org.netlib.util; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class MatConv /* */ { /* */ public static double[] doubleTwoDtoOneD(double[][] paramArrayOfDouble) /* */ { /* 35 */ int i = paramArrayOfDouble.length; /* 36 */ double[] arrayOfDouble = new double[i * paramArrayOfDouble[0].length]; /* */ /* 38 */ for (int j = 0; j < i; j++) { /* 39 */ for (int k = 0; k < paramArrayOfDouble[0].length; k++) /* 40 */ arrayOfDouble[(j + k * i)] = paramArrayOfDouble[j][k]; /* */ } /* 42 */ return arrayOfDouble; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static double[][] doubleOneDtoTwoD(double[] paramArrayOfDouble, int paramInt) /* */ { /* 57 */ double[][] arrayOfDouble = new double[paramInt][paramArrayOfDouble.length / paramInt]; /* */ /* */ /* 60 */ for (int i = 0; i < paramInt; i++) { /* 61 */ for (int j = 0; j < arrayOfDouble[0].length; j++) /* 62 */ arrayOfDouble[i][j] = paramArrayOfDouble[(i + j * paramInt)]; /* */ } /* 64 */ return arrayOfDouble; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static float[] floatTwoDtoOneD(float[][] paramArrayOfFloat) /* */ { /* 82 */ int i = paramArrayOfFloat.length; /* 83 */ float[] arrayOfFloat = new float[i * paramArrayOfFloat[0].length]; /* */ /* 85 */ for (int j = 0; j < i; j++) { /* 86 */ for (int k = 0; k < paramArrayOfFloat[0].length; k++) /* 87 */ arrayOfFloat[(j + k * i)] = paramArrayOfFloat[j][k]; /* */ } /* 89 */ return arrayOfFloat; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static float[][] floatOneDtoTwoD(float[] paramArrayOfFloat, int paramInt) /* */ { /* 104 */ float[][] arrayOfFloat = new float[paramInt][paramArrayOfFloat.length / paramInt]; /* */ /* 106 */ for (int i = 0; i < paramInt; i++) { /* 107 */ for (int j = 0; j < arrayOfFloat[0].length; j++) /* 108 */ arrayOfFloat[i][j] = paramArrayOfFloat[(i + j * paramInt)]; /* */ } /* 110 */ return arrayOfFloat; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static int[] intTwoDtoOneD(int[][] paramArrayOfInt) /* */ { /* 128 */ int i = paramArrayOfInt.length; /* 129 */ int[] arrayOfInt = new int[i * paramArrayOfInt[0].length]; /* */ /* 131 */ for (int j = 0; j < i; j++) { /* 132 */ for (int k = 0; k < paramArrayOfInt[0].length; k++) /* 133 */ arrayOfInt[(j + k * i)] = paramArrayOfInt[j][k]; /* */ } /* 135 */ return arrayOfInt; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static int[][] intOneDtoTwoD(int[] paramArrayOfInt, int paramInt) /* */ { /* 150 */ int[][] arrayOfInt = new int[paramInt][paramArrayOfInt.length / paramInt]; /* */ /* */ /* 153 */ for (int i = 0; i < paramInt; i++) { /* 154 */ for (int j = 0; j < arrayOfInt[0].length; j++) /* 155 */ arrayOfInt[i][j] = paramArrayOfInt[(i + j * paramInt)]; /* */ } /* 157 */ return arrayOfInt; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static void copyOneDintoTwoD(double[][] paramArrayOfDouble, double[] paramArrayOfDouble1) /* */ { /* 172 */ int k = paramArrayOfDouble.length; /* */ /* 174 */ for (int i = 0; i < k; i++) { /* 175 */ for (int j = 0; j < paramArrayOfDouble[0].length; j++) { /* 176 */ paramArrayOfDouble[i][j] = paramArrayOfDouble1[(i + j * k)]; /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static void copyOneDintoTwoD(float[][] paramArrayOfFloat, float[] paramArrayOfFloat1) /* */ { /* 191 */ int k = paramArrayOfFloat.length; /* */ /* 193 */ for (int i = 0; i < k; i++) { /* 194 */ for (int j = 0; j < paramArrayOfFloat[0].length; j++) { /* 195 */ paramArrayOfFloat[i][j] = paramArrayOfFloat1[(i + j * k)]; /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static void copyOneDintoTwoD(int[][] paramArrayOfInt, int[] paramArrayOfInt1) /* */ { /* 210 */ int k = paramArrayOfInt.length; /* */ /* 212 */ for (int i = 0; i < k; i++) { /* 213 */ for (int j = 0; j < paramArrayOfInt[0].length; j++) { /* 214 */ paramArrayOfInt[i][j] = paramArrayOfInt1[(i + j * k)]; /* */ } /* */ } /* */ } /* */ } /* Location: /Users/assaad/Downloads/arpack_combined_all/!/org/netlib/util/MatConv.class * Java compiler version: 4 (48.0) * JD-Core Version: 0.7.1 */
25.633929
108
0.3814
f79fd7f3135aae9435bd4b82a1560889b17e577c
754
package project.spring.article.vo; public class Editor_imageVO { private int ed_idx; private String img_url; private String kind; private String code; public int getEd_idx() { return ed_idx; } public void setEd_idx(int ed_idx) { this.ed_idx = ed_idx; } public String getImg_url() { return img_url; } public void setImg_url(String img_url) { this.img_url = img_url; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String toString() { return "Editor_imageVO [ed_idx=" + ed_idx + ", img_url=" + img_url + ", kind=" + kind + ", code=" + code + "]"; } }
20.378378
113
0.676393
de68c36c7cb877ebb00b6769ab3fc5188419e736
10,342
/* Copyright (c) 2012-2013, University of Edinburgh. * 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 University of Edinburgh 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. * * * This software is derived from (and contains code from) QTItools and MathAssessEngine. * QTItools is (c) 2008, University of Southampton. * MathAssessEngine is (c) 2010, University of Edinburgh. */ package uk.ac.ed.ph.qtiworks.mathassess; import static uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants.ATTR_RETURN_TYPE_NAME; import static uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants.ATTR_SIMPLIFY_NAME; import static uk.ac.ed.ph.qtiworks.mathassess.MathAssessConstants.MATHASSESS_NAMESPACE_URI; import uk.ac.ed.ph.qtiworks.mathassess.attribute.ReturnTypeAttribute; import uk.ac.ed.ph.qtiworks.mathassess.glue.MathAssessBadCasCodeException; import uk.ac.ed.ph.qtiworks.mathassess.glue.MathsContentTooComplexException; import uk.ac.ed.ph.qtiworks.mathassess.glue.maxima.QtiMaximaProcess; import uk.ac.ed.ph.qtiworks.mathassess.glue.maxima.QtiMaximaTypeConversionException; import uk.ac.ed.ph.qtiworks.mathassess.glue.types.ValueWrapper; import uk.ac.ed.ph.qtiworks.mathassess.value.ReturnTypeType; import uk.ac.ed.ph.jqtiplus.attribute.value.BooleanAttribute; import uk.ac.ed.ph.jqtiplus.exception.QtiLogicException; import uk.ac.ed.ph.jqtiplus.group.expression.ExpressionGroup; import uk.ac.ed.ph.jqtiplus.node.expression.ExpressionParent; import uk.ac.ed.ph.jqtiplus.running.ItemProcessingContext; import uk.ac.ed.ph.jqtiplus.validation.ValidationContext; import uk.ac.ed.ph.jqtiplus.value.BaseType; import uk.ac.ed.ph.jqtiplus.value.BooleanValue; import uk.ac.ed.ph.jqtiplus.value.Cardinality; import uk.ac.ed.ph.jqtiplus.value.NullValue; import uk.ac.ed.ph.jqtiplus.value.Value; import uk.ac.ed.ph.jacomax.MaximaTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Defines the <tt>org.qtitools.mathassess.CasProcess</tt> customOperator * * @author Jonathon Hare */ public final class CasProcess extends MathAssessOperator { private static final long serialVersionUID = -2916041095499411867L; private static final Logger logger = LoggerFactory.getLogger(CasProcess.class); public CasProcess(final ExpressionParent parent) { super(parent); getAttributes().add(new ReturnTypeAttribute(this, ATTR_RETURN_TYPE_NAME, MATHASSESS_NAMESPACE_URI)); getAttributes().add(new BooleanAttribute(this, ATTR_SIMPLIFY_NAME, MATHASSESS_NAMESPACE_URI, false, false)); // Allow 1 child only getNodeGroups().clear(); getNodeGroups().add(new ExpressionGroup(this, 1, 1)); } public ReturnTypeType getReturnType() { return ((ReturnTypeAttribute) getAttributes().get(ATTR_RETURN_TYPE_NAME, MATHASSESS_NAMESPACE_URI)) .getComputedValue(); } public void setReturnType(final ReturnTypeType returnTypeType) { ((ReturnTypeAttribute) getAttributes().get(ATTR_RETURN_TYPE_NAME, MATHASSESS_NAMESPACE_URI)) .setValue(returnTypeType); } public boolean getSimplify() { return ((BooleanAttribute) getAttributes().get(ATTR_SIMPLIFY_NAME, MATHASSESS_NAMESPACE_URI)) .getComputedNonNullValue(); } public void setSimplify(final Boolean simplify) { ((BooleanAttribute) getAttributes().get(ATTR_SIMPLIFY_NAME, MATHASSESS_NAMESPACE_URI)) .setValue(simplify); } @Override protected void doAdditionalValidation(final ValidationContext context) { /* Nothing extra to do here */ } @Override protected Value maximaEvaluate(final MathAssessExtensionPackage mathAssessExtensionPackage, final ItemProcessingContext context, final Value[] childValues) { final boolean simplify = getSimplify(); final String code = childValues[0].toQtiString().trim(); logger.debug("Performing casProcess: code={}, simplify={}", code, simplify); final QtiMaximaProcess qtiMaximaProcess = mathAssessExtensionPackage.obtainMaximaSessionForThread(); /* Pass variables to Maxima */ passVariablesToMaxima(qtiMaximaProcess, context); /* Run Maxima code and extract result */ logger.trace("Running code to determine result of casProcess"); final Class<? extends ValueWrapper> resultClass = GlueValueBinder.getCasReturnClass(getReturnType()); ValueWrapper maximaResult; try { maximaResult = qtiMaximaProcess.executeCasProcess(code, simplify, resultClass); } catch (final MaximaTimeoutException e) { context.fireRuntimeError(this, "A timeout occurred executing the CasCondition logic. Returning NULL"); return NullValue.INSTANCE; } catch (final MathsContentTooComplexException e) { context.fireRuntimeError(this, "An unexpected problem occurred querying the result of CasProcess, so returning NULL"); return NullValue.INSTANCE; } catch (final MathAssessBadCasCodeException e) { context.fireRuntimeError(this, "Your CasProcess code did not work as expected. The CAS input was '" + e.getMaximaInput() + "' and the CAS output was '" + e.getMaximaOutput() + "'. The failure reason was: " + e.getReason()); return NullValue.INSTANCE; } catch (final QtiMaximaTypeConversionException e) { context.fireRuntimeError(this, "Your CasProcess code did not produce a result that could be converted into the required QTI type. The CAS input was '" + e.getMaximaInput() + "' and the CAS output was '" + e.getMaximaOutput() + "'"); return NullValue.INSTANCE; } catch (final RuntimeException e) { logger.warn("Unexpected Maxima failure", e); context.fireRuntimeError(this, "An unexpected problem occurred while executing this CasProcess"); return BooleanValue.FALSE; } /* Bind result */ final Value result = GlueValueBinder.casToJqti(maximaResult); if (result==null) { context.fireRuntimeError(this, "Failed to convert result from Maxima back to a QTI variable - returning NULL"); return NullValue.INSTANCE; } return result; } private BaseType getReturnBaseType() { if (getReturnType() == null) { return null; } switch (getReturnType()) { case INTEGER: case INTEGER_MULTIPLE: case INTEGER_ORDERED: return BaseType.INTEGER; case FLOAT: case FLOAT_MULTIPLE: case FLOAT_ORDERED: return BaseType.FLOAT; case BOOLEAN: case BOOLEAN_MULTIPLE: case BOOLEAN_ORDERED: return BaseType.BOOLEAN; case MATHS_CONTENT: return null; default: throw new QtiLogicException("Unexpected switch case " + getReturnType()); } } @Override public BaseType[] getProducedBaseTypes(final ValidationContext context) { if (getReturnType() != null) { final BaseType type = getReturnBaseType(); return type != null ? new BaseType[] { type } : BaseType.values(); } return super.getProducedBaseTypes(context); } private Cardinality getReturnCardinality() { if (getReturnType() == null) { return null; } switch (getReturnType()) { case MATHS_CONTENT: return Cardinality.RECORD; case INTEGER: case FLOAT: case BOOLEAN: return Cardinality.SINGLE; case INTEGER_MULTIPLE: case FLOAT_MULTIPLE: case BOOLEAN_MULTIPLE: return Cardinality.MULTIPLE; case INTEGER_ORDERED: case FLOAT_ORDERED: case BOOLEAN_ORDERED: return Cardinality.ORDERED; default: throw new QtiLogicException("Unexpected switch case " + getReturnType()); } } @Override public Cardinality[] getProducedCardinalities(final ValidationContext context) { if (getReturnType() != null) { return new Cardinality[] { getReturnCardinality() }; } return super.getProducedCardinalities(context); } @Override public BaseType[] getRequiredBaseTypes(final ValidationContext context, final int index) { return new BaseType[] { BaseType.STRING }; } @Override public Cardinality[] getRequiredCardinalities(final ValidationContext context, final int index) { return new Cardinality[] { Cardinality.SINGLE }; } }
40.398438
162
0.6842
f65726657e47335d1fdbfa26c778ce4b91b3c740
1,204
package com.softicar.platform.emf; import com.softicar.platform.common.core.user.CurrentBasicUser; import com.softicar.platform.db.runtime.test.AbstractDbTest; import com.softicar.platform.dom.elements.testing.engine.IDomTestExecutionEngine; import com.softicar.platform.dom.elements.testing.engine.document.DomDocumentTestExecutionEngine; import com.softicar.platform.emf.test.IEmfTestEngineMethods; import com.softicar.platform.emf.test.module.EmfTestModuleInstance; import com.softicar.platform.emf.test.user.EmfTestUser; import org.junit.Rule; /** * Abstract base class for UI tests with database access. * * @author Alexander Schmidt * @author Oliver Richers */ public abstract class AbstractEmfTest extends AbstractDbTest implements IEmfTestEngineMethods { @Rule public final IDomTestExecutionEngine engine = new DomDocumentTestExecutionEngine(); protected final EmfTestModuleInstance moduleInstance; protected final EmfTestUser user; public AbstractEmfTest() { this.moduleInstance = new EmfTestModuleInstance(); this.user = EmfTestUser.insert("current", "user"); CurrentBasicUser.set(user); } @Override public IDomTestExecutionEngine getEngine() { return engine; } }
30.871795
97
0.813123
cf21edbdcb3d5d5f9495c2320cf8cb22d622e002
8,324
/* * K-scope * Copyright 2012-2013 RIKEN, Japan * * 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 jp.riken.kscope.component; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.tree.DefaultMutableTreeNode; import jp.riken.kscope.common.FILTER_TYPE; /** * フィルタノードクラス * @author RIKEN */ public class FilterTreeNode extends DefaultMutableTreeNode { /** シリアル番号 */ private static final long serialVersionUID = 1L; /** * ノードの追加フラグ * true=ノードを親ノードに追加する。ノードがフィルタ一致、又は、子ノードが存在する場合 */ private boolean passed = true; /** フィルタ一致子ノードリスト */ private List<FilterTreeNode> filteredChildren = new ArrayList<FilterTreeNode>(); /** ノードフィルタのクラス */ private List<FILTER_TYPE> listFilter; /** 子孫ノードの未展開の深さ */ private int depth; /** * コンストラクタ * @param userObject ノードユーザオブジェクト */ public FilterTreeNode(Object userObject) { super(userObject); depth = 0; } /** * コンストラクタ * @param userObject ノードユーザオブジェクト * @param depth ノード */ public FilterTreeNode(Object userObject, int depth) { super(userObject); this.depth = depth; } /** * コンストラクタ */ public FilterTreeNode() { super(); } /** * ノードフィルタを行う */ public void find() { passed = false; filteredChildren.clear(); // フィルタの有無チェック if (!validateFilter()) { // フィルタ無しであるので、無条件追加 passed = true; // 子ノード検索 passFilterDown(); } else if (pass(this)) { // フィルタクラス一致によるノード追加 passed = true; // 子ノード検索 passFilterDown(); } else { // 子ノード検索 passFilterDown(); passed = filteredChildren.size() != 0; } } /** * 追加ノードであるかチェックする.<br/> * true=フィルタ一致ノードである.<br/> * true=フィルタ条件がない.<br/> * @param node ノード * @return true=追加ノード */ protected boolean pass(FilterTreeNode node) { // フィルタの有無チェック if (!validateFilter()) { return true; } // フィルタ対象ノードクラスであるかチェックする Object obj = node.getUserObject(); if (!isFilter(obj)) { return false; } return true; } /** * 子ノードのフィルタを行う. */ private void passFilterDown() { int childCount = super.getChildCount(); for (int i = 0; i < childCount; i++) { FilterTreeNode child = (FilterTreeNode) super.getChildAt(i); // フィルタを設定する。 child.setListFilter(this.listFilter); child.find(); if (child.isPassed()) { filteredChildren.add(child); } } } /** * 子ノードを追加する * @param node 追加子ノード * @return 追加子ノード */ public FilterTreeNode add(FilterTreeNode node) { FilterTreeNode result = node; if (!containsChild(node)) { int index = super.getChildCount(); super.insert(node, index); } else { result = (FilterTreeNode)equalsChild(node); } // フィルタを設定する。 node.setListFilter(this.listFilter); node.find(); if (node.isPassed()) { if (!containsList(node, filteredChildren)) { filteredChildren.add(node); } } return result; } /** * 子ノードを削除する * @param childIndex 子ノードインデックス */ @Override public void remove(int childIndex) { // フィルタの有無チェック if (!validateFilter()) { // as child indexes might be inconsistent.. throw new IllegalStateException( "Can't remove while the filter is active"); } super.remove(childIndex); } /** * 子ノード数を取得する * @return 子ノード数 */ @Override public int getChildCount() { // フィルタの有無チェック if (!validateFilter()) { return super.getChildCount(); } return (filteredChildren.size()); } /** * 子ノードを取得する * @return 子ノードインデックス */ @Override public FilterTreeNode getChildAt(int index) { // フィルタの有無チェック if (!validateFilter()) { return (FilterTreeNode) super.getChildAt(index); } return filteredChildren.get(index); } /** * 親ノードへ追加ノードであるか取得する. * @return true=追加ノード */ public boolean isPassed() { return passed; } /** * フィルタが設定されているかチェックする. * @return true=フィルタ設定済み */ protected boolean validateFilter() { if (this.listFilter == null) return false; if (this.listFilter.contains(FILTER_TYPE.ALL)) { // すべて表示であるので、フィルタ適用なし return false; } return true; } /** * フィルタ対象のノードオブジェクトであるかチェックする。 * @param node ノードユーザオブジェクト * @return true=フィルタ対象ノード(表示ノード) */ private boolean isFilter(Object node) { if (this.listFilter == null) return false; // フィルタ対象のノードオブジェクトであるかチェックする。 for (FILTER_TYPE filter : this.listFilter) { if (filter.isFilter(node)) { return true; } } return false; } /** * ノードフィルタを取得する * @return ノードフィルタ */ public List<FILTER_TYPE> getListFilter() { return listFilter; } /** * ノードフィルタを設定する * @param list ノードフィルタ */ public void setListFilter(List<FILTER_TYPE> list) { this.listFilter = list; } /** * 子孫ノードの未展開の深さを取得する * @return 子孫ノードの未展開の深さ */ public int getDepth() { return this.depth; } /** * 子孫ノードの未展開の深さを設定する * @param depth 子孫ノードの未展開の深さ */ public void setDepth(int depth) { this.depth = depth; } /** * 子要素をすべて削除する */ @Override public void removeAllChildren() { // 一時的にフィルタを削除する。 List<FILTER_TYPE> filters = this.listFilter; this.listFilter = null; for (int i = super.getChildCount()-1; i >= 0; i--) { super.remove(i); } filteredChildren.clear(); this.listFilter = filters; } /** * 子ノードに存在するかチェックする. * @param child 対象ノード * @return true=子ノードである */ private boolean containsChild(FilterTreeNode child) { return (equalsChild(child) != null); } /** * 子ノードから同一ノードを取得する. * @param child 対象ノード * @return 同一ノード */ private DefaultMutableTreeNode equalsChild(FilterTreeNode child) { if (child == null) { return null; } try { if (super.getChildCount() == 0) { return null; } for (int i=0; i<super.getChildCount(); i++) { if (super.getChildAt(i) == null) continue; if (super.getChildAt(i) == child) { return (DefaultMutableTreeNode)super.getChildAt(i); } if (((DefaultMutableTreeNode)super.getChildAt(i)).getUserObject() == child.getUserObject()) { return (DefaultMutableTreeNode)super.getChildAt(i); } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * ノードリストにチェックノードが存在するかチェックする * @param child チェックノード * @param list ノードリスト * @return true=存在する */ private boolean containsList(FilterTreeNode child, List<FilterTreeNode> list) { if (child == null) { return false; } if (list == null || list.size() <= 0) { return false; } try { CopyOnWriteArrayList<FilterTreeNode> copyList = new CopyOnWriteArrayList<FilterTreeNode>(list); for (FilterTreeNode node : copyList) { if (child == null) return false; if (node == null) continue; if (node == child) { return true; } if (node.getUserObject() == child.getUserObject()) { return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } }
22.619565
101
0.572802
b2d8f2f9ca3be04b557cc6fd18e7fce3e0c605d3
1,325
package sorts.bogo; import main.ArrayVisualizer; import sorts.templates.BogoSorting; /* PORTED TO ARRAYV BY PCBOYGAMES ------------------------------ - FUNGAMER2'S SCRATCH VISUAL - ------------------------------ */ public final class WatermelonWavesSort extends BogoSorting { public WatermelonWavesSort(ArrayVisualizer arrayVisualizer) { super(arrayVisualizer); this.setSortListName("Watermelon Waves"); this.setRunAllSortsName("Watermelon Waves Sort"); this.setRunSortName("Watermelon Waves Sort"); this.setCategory("Bogo Sorts"); this.setComparisonBased(true); this.setBucketSort(false); this.setRadixSort(false); this.setUnreasonablySlow(true); this.setUnreasonableLimit(11); this.setBogoSort(true); } @Override public void runSort(int[] array, int currentLength, int bucketCount) { int i; while (!this.isArraySorted(array, currentLength)) { i = BogoSorting.randInt(0, currentLength - 1); while (i < currentLength - 1) { if (Reads.compareIndices(array, i, i + 1, 0.001, true) == 0) break; else { Writes.swap(array, i, i + 1, 0.001, true, false); i++; } } } } }
30.113636
83
0.578113
8f03f9d8c8ad83be276cda4d57264d1a15a4e90d
6,724
/* * Copyright 2020-2021 Steinar Bang * * 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 no.priv.bang.oldalbum.db.liquibase.urlinit; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.util.Date; import java.util.Properties; import javax.sql.DataSource; import org.junit.jupiter.api.Test; import org.ops4j.pax.jdbc.derby.impl.DerbyDataSourceFactory; import org.osgi.service.jdbc.DataSourceFactory; import no.priv.bang.osgi.service.mocks.logservice.MockLogService; class OldAlbumSchemeTest { DataSourceFactory derbyDataSourceFactory = new DerbyDataSourceFactory(); @Test void testPrepare() throws Exception { String sqlUrl = "https://gist.githubusercontent.com/steinarb/8a1de4e37f82d4d5eeb97778b0c8d459/raw/6cddf18f12e98d704e85af6264d81867f68a097c/dumproutes.sql"; Environment environment = mock(Environment.class); when(environment.getEnv(anyString())).thenReturn(sqlUrl); DataSource datasource = createDataSource("oldalbum"); MockLogService logservice = new MockLogService(); OldAlbumScheme hook = new OldAlbumScheme(); hook.setLogService(logservice); hook.activate(); hook.prepare(datasource); addAlbumEntries(datasource); assertAlbumEntries(datasource); } @Test void testCreateInitialSchemaWithLiquibaseException() throws Exception { DataSource datasource = mock(DataSource.class); Connection connection = mock(Connection.class); when(connection.getMetaData()).thenThrow(SQLException.class); when(datasource.getConnection()).thenReturn(connection); MockLogService logservice = new MockLogService(); OldAlbumScheme hook = new OldAlbumScheme(); hook.setLogService(logservice); hook.activate(); hook.createInitialSchema(datasource); assertEquals(1, logservice.getLogmessages().size()); } private DataSource createDataSource(String dbname) throws Exception { Properties properties = new Properties(); properties.setProperty(DataSourceFactory.JDBC_URL, "jdbc:derby:memory:" + dbname + ";create=true"); return derbyDataSourceFactory.createDataSource(properties); } private void assertAlbumEntries(DataSource datasource) throws Exception { try (Connection connection = datasource.getConnection()) { assertAlbumEntry(connection, 1, 0, "/album/", true, "Album", "This is an album", null, null, 1, null, null, 0); assertAlbumEntry(connection, 2, 1, "/album/bilde01", false, "VFR at Arctic Circle", "This is the VFR up north", "https://www.bang.priv.no/sb/pics/moto/vfr96/acirc1.jpg", "https://www.bang.priv.no/sb/pics/moto/vfr96/icons/acirc1.gif", 2, new Date(800275785000L), "image/jpeg", 128186); } } private void assertAlbumEntry(Connection connection, int id, int parent, String path, boolean album, String title, String description, String imageUrl, String thumbnailUrl, int sort, Date lastmodified, String contenttype, int size) throws Exception { String sql = "select * from albumentries where albumentry_id = ?"; try(PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, id); try(ResultSet result = statement.executeQuery()) { if (result.next()) { assertEquals(parent, result.getInt(2)); assertEquals(path, result.getString(3)); assertEquals(album, result.getBoolean(4)); assertEquals(title, result.getString(5)); assertEquals(description, result.getString(6)); assertEquals(imageUrl, result.getString(7)); assertEquals(thumbnailUrl, result.getString(8)); assertEquals(sort, result.getInt(9)); assertEquals(lastmodified, result.getTimestamp(10) != null ? Date.from(result.getTimestamp(10).toInstant()) : null); assertEquals(contenttype, result.getString(11)); assertEquals(size, result.getInt(12)); } else { fail(String.format("Didn't find albumentry with id=d", id)); } } } } private void addAlbumEntries(DataSource datasource) throws Exception { try (Connection connection = datasource.getConnection()) { addAlbumEntry(connection, 0, "/album/", true, "Album", "This is an album", null, null, 1, null, null, 0); addAlbumEntry(connection, 1, "/album/bilde01", false, "VFR at Arctic Circle", "This is the VFR up north", "https://www.bang.priv.no/sb/pics/moto/vfr96/acirc1.jpg", "https://www.bang.priv.no/sb/pics/moto/vfr96/icons/acirc1.gif", 2, new Date(800275785000L), "image/jpeg", 128186); } } private void addAlbumEntry(Connection connection, int parent, String path, boolean album, String title, String description, String imageUrl, String thumbnailUrl, int sort, Date lastmodified, String contenttype, int size) throws Exception { String sql = "insert into albumentries (parent, localpath, album, title, description, imageurl, thumbnailurl, sort, lastmodified, contenttype, contentlength) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try(PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, parent); statement.setString(2, path); statement.setBoolean(3, album); statement.setString(4, title); statement.setString(5, description); statement.setString(6, imageUrl); statement.setString(7, thumbnailUrl); statement.setInt(8, sort); statement.setTimestamp(9, lastmodified != null ? Timestamp.from(Instant.ofEpochMilli(lastmodified.getTime())) : null); statement.setString(10, contenttype); statement.setInt(11, size); statement.executeUpdate(); } } }
50.556391
296
0.678763
7219e6b733ef42756c9015943504c1be88c955b5
255
package uk.gov.ons.ctp.common.event.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class UacPayload { private UacUpdate uacUpdate = new UacUpdate(); }
18.214286
48
0.807843
bd678ef036018d1a010c877e8ea71bb55f4ebafc
510
package tk.woppo.sunday.widget.jazzylistview.effects; import android.view.View; import com.nineoldandroids.view.ViewPropertyAnimator; import tk.woppo.sunday.widget.jazzylistview.JazzyEffect; public class StandardEffect implements JazzyEffect { @Override public void initView(View item, int position, int scrollDirection) { // no op } @Override public void setupAnimation(View item, int position, int scrollDirection, ViewPropertyAnimator animator) { // no op } }
23.181818
109
0.741176
cbff7d1234a77eb3bad19352be4e5e9d1c7f9f21
589
package com.cefoler.configuration.core.error.reflection.impl.member.impl.executable; import com.cefoler.configuration.core.error.reflection.impl.member.MemberError; public abstract class ExecutableError extends MemberError { private static final long serialVersionUID = 6122762182921381964L; protected ExecutableError() { } protected ExecutableError(final String error) { super(error); } protected ExecutableError(final Throwable cause) { super(cause); } protected ExecutableError(final String error, final Throwable cause) { super(error, cause); } }
23.56
84
0.7691
ca54dea12cb94f7c9b0951f45e3d104321227254
1,942
package me.icro.leetcodingchallenge2004.maximalsquare; /** * @author lin * @version v 0.1 2020/4/27 **/ public class Solution { public int maximalSquare(char[][] matrix) { if (null == matrix || 0 == matrix.length) { return 0; } int[][] dp = new int[matrix.length + 1][matrix[0].length + 1]; int result = 0; for (int i = 1; i <= matrix.length; i++) { for (int j = 1; j <= matrix[0].length; j++) { if ('1' == matrix[i - 1][j - 1]) { dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1; result = Math.max(result, dp[i][j]); } } } return result * result; } public static void main(String[] args) { System.out.println(new Solution().maximalSquare(new char[][] { new char[] {'1', '0', '1', '0', '0'}, new char[] {'1', '0', '1', '1', '1'}, new char[] {'1', '1', '1', '1', '1'}, new char[] {'1', '0', '0', '1', '0'}, })); System.out.println(new Solution().maximalSquare(new char[][] { new char[] {'1', '0', '1', '0', '0'}, new char[] {'1', '0', '1', '1', '1'}, new char[] {'1', '1', '1', '0', '1'}, new char[] {'1', '0', '0', '1', '0'}, })); System.out.println(new Solution().maximalSquare(new char[][] { new char[] {'1', '0', '1', '0', '0'}, new char[] {'1', '0', '1', '1', '1'}, new char[] {'1', '1', '1', '1', '1'}, new char[] {'1', '0', '1', '1', '1'}, })); System.out.println(new Solution().maximalSquare(new char[][] { new char[] {'1'} })); System.out.println(new Solution().maximalSquare(new char[][] { new char[] {} })); } }
37.346154
100
0.393409
8b07e67c0f242700bb3096e0e2e0321f767e4d55
510
package com.ssafy.happyhouse.repo; import java.util.List; import com.ssafy.happyhouse.dto.HouseDeal; import com.ssafy.happyhouse.dto.SearchInfo; public interface HouseDealRepo { List<HouseDeal> selectAll(); int insert(HouseDeal deal); int delete(int no); HouseDeal searchNo(int no); List<HouseDeal> selectByKeword(SearchInfo search); HouseDeal selectOne(String id); Integer dealsCount(SearchInfo info); List<HouseDeal> dealBySearch(SearchInfo info); List<HouseDeal> recentDeal(HouseDeal deal); }
25.5
51
0.790196
0094407dbcdc88b234a7083e14608554454a7585
370
package designpatterns.builder.improve; /** * @author happy * @since 2021-04-17 */ public abstract class HouseBuilder { protected House house = new House(); //将建造流程写好 public abstract void buildBasic(); public abstract void buildWalls(); public abstract void buildProof(); //返回产品 public House getHouse(){ return house; } }
16.818182
40
0.654054
e6f8afaaf1f24b71d2917999223a90d264babb85
431
package uo.ri.ui.foreman; import alb.util.menu.BaseMenu; /** * Clase menu de Jefe de taller con todas las clases a las que puede acceder * este * * @author UO250999 * */ public class MainMenu extends BaseMenu { public MainMenu() { menuOptions = new Object[][] { { "Jefe de Taller", null }, { "Gestión de clientes", ClientesMenu.class }, }; } public static void main(String[] args) { new MainMenu().execute(); } }
20.52381
110
0.668213
1a00165b09df0d00d8bf89baf75060718944fc82
25,408
/* * Copyright (c) 2016, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.dva.argus.entity; import java.io.IOException; import java.io.Serializable; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NoResultException; import javax.persistence.Query; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import static com.salesforce.dva.argus.system.SystemAssert.requireArgument; /** * Encapsulates information about an alert notification. When a condition is triggered, it sends one or more notifications. The interval over which * the trigger conditions are evaluated is the entire interval specified by the alert expression. * * @author Tom Valine ([email protected]), Raj Sarkapally([email protected]) */ @SuppressWarnings("serial") @Entity @Table(name = "NOTIFICATION", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "alert_id" })) public class Notification extends JPAEntity implements Serializable { public static class Serializer extends JsonSerializer<Notification> { @Override public void serialize(Notification notification, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("id", notification.getId().toString()); jgen.writeStringField("name", notification.getName()); jgen.writeStringField("notifier", notification.getNotifierName()); jgen.writeNumberField("cooldownPeriod", notification.getCooldownPeriod()); jgen.writeBooleanField("srActionable", notification.getSRActionable()); jgen.writeNumberField("severityLevel", notification.getSeverityLevel()); if(notification.getCustomText() != null) { jgen.writeStringField("customText", notification.getCustomText()); } jgen.writeArrayFieldStart("subscriptions"); for(String subscription : notification.getSubscriptions()) { jgen.writeString(subscription); } jgen.writeEndArray(); jgen.writeArrayFieldStart("metricsToAnnotate"); for(String metricToAnnotate : notification.getMetricsToAnnotate()) { jgen.writeString(metricToAnnotate); } jgen.writeEndArray(); jgen.writeArrayFieldStart("triggers"); for(Trigger trigger : notification.getTriggers()) { jgen.writeString(trigger.getId().toString()); } jgen.writeEndArray(); // Getting these values requires a lot of queries to rdbms at runtime, and so these are excluded for now // as the current usecases do not need these values to be serialized //jgen.writeObjectField("cooldownExpirationByTriggerAndMetric", notification.getCooldownExpirationMap()); //jgen.writeObjectField("activeStatusByTriggerAndMetric", notification.getActiveStatusMap()); jgen.writeEndObject(); } } public static class Deserializer extends JsonDeserializer<Notification> { @Override public Notification deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Notification notification = new Notification(); JsonNode rootNode = jp.getCodec().readTree(jp); BigInteger id = new BigInteger(rootNode.get("id").asText()); notification.id = id; String name = rootNode.get("name").asText(); notification.setName(name); String notifierName = rootNode.get("notifier").asText(); notification.setNotifierName(notifierName); long cooldownPeriod = rootNode.get("cooldownPeriod").asLong(); notification.setCooldownPeriod(cooldownPeriod); boolean srActionable = rootNode.get("srActionable").asBoolean(); notification.setSRActionable(srActionable); int severity = rootNode.get("severityLevel").asInt(); notification.setSeverityLevel(severity); if(rootNode.get("customText") != null) { notification.setCustomText(rootNode.get("customText").asText()); } List<String> subscriptions = new ArrayList<>(); JsonNode subscriptionsArrayNode = rootNode.get("subscriptions"); if(subscriptionsArrayNode.isArray()) { for(JsonNode subscriptionNode : subscriptionsArrayNode) { subscriptions.add(subscriptionNode.asText()); } } notification.setSubscriptions(subscriptions); List<String> metricsToAnnotate = new ArrayList<>(); JsonNode metricsToAnnotateArrayNode = rootNode.get("metricsToAnnotate"); if(metricsToAnnotateArrayNode.isArray()) { for(JsonNode metricToAnnotateNode : metricsToAnnotateArrayNode) { metricsToAnnotate.add(metricToAnnotateNode.asText()); } } notification.setMetricsToAnnotate(metricsToAnnotate); List<Trigger> triggers = new ArrayList<>(); JsonNode triggersArrayNode = rootNode.get("triggers"); if(triggersArrayNode.isArray()) { for(JsonNode triggerNode : triggersArrayNode) { BigInteger triggerId = new BigInteger(triggerNode.asText()); Trigger trigger = new Trigger(); trigger.id = triggerId; triggers.add(trigger); } } notification.setTriggers(triggers); // Commenting this part out as these fields are not currently serialized /*Map<String, Boolean> activeStatusByTriggerAndMetric = new HashMap<>(); JsonNode activeStatusByTriggerAndMetricNode = rootNode.get("activeStatusByTriggerAndMetric"); if(activeStatusByTriggerAndMetricNode.isObject()) { Iterator<Entry<String, JsonNode>> fieldsIter = activeStatusByTriggerAndMetricNode.fields(); while(fieldsIter.hasNext()) { Entry<String, JsonNode> field = fieldsIter.next(); activeStatusByTriggerAndMetric.put(field.getKey(), field.getValue().asBoolean()); } } notification.activeStatusByTriggerAndMetric = activeStatusByTriggerAndMetric; Map<String, Long> cooldownExpirationByTriggerAndMetric = new HashMap<>(); JsonNode cooldownExpirationByTriggerAndMetricNode = rootNode.get("cooldownExpirationByTriggerAndMetric"); if(cooldownExpirationByTriggerAndMetricNode.isObject()) { Iterator<Entry<String, JsonNode>> fieldsIter = cooldownExpirationByTriggerAndMetricNode.fields(); while(fieldsIter.hasNext()) { Entry<String, JsonNode> field = fieldsIter.next(); cooldownExpirationByTriggerAndMetric.put(field.getKey(), field.getValue().asLong()); } } notification.cooldownExpirationByTriggerAndMetric = cooldownExpirationByTriggerAndMetric;*/ return notification; } } //~ Instance fields ****************************************************************************************************************************** @Basic(optional = false) @Column(name = "name", nullable = false) String name; String notifierName; @ElementCollection @Column(length = 2048) List<String> subscriptions = new ArrayList<>(0); @ElementCollection List<String> metricsToAnnotate = new ArrayList<>(0); long cooldownPeriod; @ManyToOne(optional = false, fetch=FetchType.LAZY) @JoinColumn(name = "alert_id") private Alert alert; @ManyToMany @JoinTable( name = "NOTIFICATION_TRIGGER", joinColumns = @JoinColumn(name = "TRIGGER_ID"), inverseJoinColumns = @JoinColumn(name = "NOTIFICATION_ID") ) List<Trigger> triggers = new ArrayList<>(0); boolean isSRActionable = false; int severityLevel = 5; @Lob private String customText; @ElementCollection private Map<String, Long> cooldownExpirationByTriggerAndMetric = new HashMap<>(); @ElementCollection private Map<String, Boolean> activeStatusByTriggerAndMetric = new HashMap<>(); //~ Constructors ********************************************************************************************************************************* /** * Creates a new Notification object with a cool down of one hour and having specified no metrics on which to create annotations. * * @param name The notification name. Cannot be null or empty. * @param alert The alert with which the notification is associated. * @param notifierName The notifier implementation class name. * @param subscriptions The notifier specific list of subscriptions to which notification shall be sent. * @param cooldownPeriod The cool down period of the notification */ public Notification(String name, Alert alert, String notifierName, List<String> subscriptions, long cooldownPeriod) { super(alert.getOwner()); setAlert(alert); setName(name); setNotifierName(notifierName); setSubscriptions(subscriptions); setCooldownPeriod(cooldownPeriod); } /** Creates a new Notification object. */ protected Notification() { super(null); } //~ Static Methods ******************************************************************************************************************************* @SuppressWarnings("unchecked") public static void updateActiveStatusAndCooldown(EntityManager em, List<Notification> notifications) { requireArgument(em != null, "Entity manager can not be null."); if(notifications.isEmpty()) return; Map<BigInteger, Notification> notificationsByIds = new HashMap<>(notifications.size()); StringBuilder sb = new StringBuilder(); for(Notification n : notifications) { notificationsByIds.put(n.getId(), n); n.activeStatusByTriggerAndMetric.clear(); n.cooldownExpirationByTriggerAndMetric.clear(); sb.append(n.getId()).append(","); } String ids = sb.substring(0, sb.length()-1); try { Query q = em.createNativeQuery("select * from notification_cooldownexpirationbytriggerandmetric where notification_id IN (" + ids + ")"); List<Object[]> objects = q.getResultList(); for(Object[] object : objects) { BigInteger notificationId = new BigInteger(String.valueOf(Long.class.cast(object[0]))); Long cooldownExpiration = Long.class.cast(object[1]); String key = String.class.cast(object[2]); notificationsByIds.get(notificationId).cooldownExpirationByTriggerAndMetric.put(key, cooldownExpiration); } q = em.createNativeQuery("select * from notification_activestatusbytriggerandmetric where notification_id IN (" + ids + ")"); objects = q.getResultList(); for(Object[] object : objects) { BigInteger notificationId = new BigInteger(String.valueOf(Long.class.cast(object[0]))); Boolean isActive; try { isActive = Boolean.class.cast(object[1]); } catch (ClassCastException e) { // This is because Embedded Derby stores booleans as 0, 1. isActive = Integer.class.cast(object[1]) == 0 ? Boolean.FALSE : Boolean.TRUE; } String key = String.class.cast(object[2]); notificationsByIds.get(notificationId).activeStatusByTriggerAndMetric.put(key, isActive); } } catch(NoResultException ex) { return; } } //~ Methods ************************************************************************************************************************************** /** * Given a metric to annotate expression, return a corresponding metric object. * * @param metric The metric to annotate expression. * * @return The corresponding metric or null if the metric to annotate expression is invalid. */ public static Metric getMetricToAnnotate(String metric) { Metric result = null; if (metric != null && !metric.isEmpty()) { Pattern pattern = Pattern.compile( "([\\w,\\-,\\.,/]+):([\\w,\\-,\\.,/]+)(\\{(?:[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)(?:,[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)*\\})?:([\\w,\\-,\\.,/]+)"); Matcher matcher = pattern.matcher(metric.replaceAll("\\s", "")); if (matcher.matches()) { String scopeName = matcher.group(1); String metricName = matcher.group(2); String tagString = matcher.group(3); Map<String, String> tags = new HashMap<>(); if (tagString != null) { tagString = tagString.replaceAll("\\{", "").replaceAll("\\}", ""); for (String tag : tagString.split(",")) { String[] entry = tag.split("="); tags.put(entry[0], entry[1]); } } result = new Metric(scopeName, metricName); result.setTags(tags); } } return result; } //~ Methods ************************************************************************************************************************************** /** * Returns the alert with which the notification is associated. * * @return The associated alert. */ public Alert getAlert() { return alert; } /** * Sets the alert with which the notification is associated. * * @param alert The associated alert. Cannot be null. */ public void setAlert(Alert alert) { requireArgument(alert != null, "The alert with which the notification is associated cannot be null."); this.alert = alert; } /** * Returns the notifier implementation class name associated with the notification. * * @return The notifier implementation class name. */ public String getNotifierName() { return notifierName; } /** * Sets the notifier implementation class name. * * @param notifierName The notifier implementation class name. Cannot be null. */ public void setNotifierName(String notifierName) { this.notifierName = notifierName; } /** * Returns the subscriptions used by the notifier to send the notifications. * * @return The list of subscriptions. */ public List<String> getSubscriptions() { return Collections.unmodifiableList(subscriptions); } /** * Replaces the subscriptions used by the notifier to send the notifications. * * @param subscriptions The subscription list. */ public void setSubscriptions(List<String> subscriptions) { this.subscriptions.clear(); if (subscriptions != null && !subscriptions.isEmpty()) { this.subscriptions.addAll(subscriptions); } } /** * Returns the cool down period of notification. * * @return cool down period in milliseconds */ public long getCooldownPeriod() { return cooldownPeriod; } /** * Sets the cool down period to notification. * * @param cooldownPeriod cool down period in milliseconds */ public void setCooldownPeriod(long cooldownPeriod) { requireArgument(cooldownPeriod >= 0, "Cool down period cannot be negative."); this.cooldownPeriod = cooldownPeriod; } /** * Returns the cool down expiration time of the notification given a metric,trigger combination. * * @param trigger The trigger * @param metric The metric * @return cool down expiration time in milliseconds */ public long getCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric) { String key = _hashTriggerAndMetric(trigger, metric); return this.cooldownExpirationByTriggerAndMetric.containsKey(key) ? this.cooldownExpirationByTriggerAndMetric.get(key) : 0; } /** * Sets the cool down expiration time of the notification given a metric,trigger combination. * * @param trigger The trigger * @param metric The metric * @param cooldownExpiration cool down expiration time in milliseconds */ public void setCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric, long cooldownExpiration) { requireArgument(cooldownExpiration >= 0, "Cool down expiration time cannot be negative."); String key = _hashTriggerAndMetric(trigger, metric); this.cooldownExpirationByTriggerAndMetric.put(key, cooldownExpiration); } public Map<String, Long> getCooldownExpirationMap() { return cooldownExpirationByTriggerAndMetric; } public void setCooldownExpirationMap(Map<String, Long> cooldownExpirationByTriggerAndMetric) { this.cooldownExpirationByTriggerAndMetric = cooldownExpirationByTriggerAndMetric; } /** * Returns all metrics to be annotated. * * @return list of metrics */ public List<String> getMetricsToAnnotate() { return metricsToAnnotate; } /** * Sets metrics to be annotated. * * @param metricsToAnnotate list of metrics. */ public void setMetricsToAnnotate(List<String> metricsToAnnotate) { this.metricsToAnnotate.clear(); if (metricsToAnnotate != null && !metricsToAnnotate.isEmpty()) { for (String metric : metricsToAnnotate) { requireArgument(getMetricToAnnotate(metric) != null, "Metrics to annotate should be of the form 'scope:metric[{[tagk=tagv]+}]"); this.metricsToAnnotate.add(metric); } } } public boolean onCooldown(Trigger trigger, Metric metric) { return getCooldownExpirationByTriggerAndMetric(trigger, metric) >= System.currentTimeMillis(); } /** * returns the notification name. * * @return notification name. */ public String getName() { return name; } /** * Sets the notification name. * * @param name Notification name. Cannot be null or empty. */ public void setName(String name) { this.name = name; } /** * Returns the triggers associated with the notification. * * @return The triggers associated with the notification. */ public List<Trigger> getTriggers() { return Collections.unmodifiableList(triggers); } /** * Replaces the triggers associated with the notification. * * @param triggers The triggers associated with the notification. */ public void setTriggers(List<Trigger> triggers) { this.triggers.clear(); if (triggers != null) { this.triggers.addAll(triggers); } } /** * Given a metric,notification combination, indicates whether a triggering condition associated with this notification is still in a triggering state. * * @param trigger The Trigger that caused this notification * @param metric The metric that caused this notification * * @return True if the triggering condition is still in a triggering state. */ public boolean isActiveForTriggerAndMetric(Trigger trigger, Metric metric) { String key = _hashTriggerAndMetric(trigger, metric); return this.activeStatusByTriggerAndMetric.containsKey(key) ? activeStatusByTriggerAndMetric.get(key) : false; } /** * When a notification is sent out when a metric violates the trigger threshold, set this notification active for that trigger,metric combination * * @param trigger The Trigger that caused this notification * @param metric The metric that caused this notification * @param active Whether to set the notification to active */ public void setActiveForTriggerAndMetric(Trigger trigger, Metric metric, boolean active) { String key = _hashTriggerAndMetric(trigger, metric); this.activeStatusByTriggerAndMetric.put(key, active); } /** * Indicates whether the notification is monitored by SR * * @return True if notification is monitored by SR */ public boolean getSRActionable() { return isSRActionable; } /** * Specifies whether the notification should be monitored by SR (actionable by SR) * * @param isSRActionable True if SR should monitor the notification */ public void setSRActionable(boolean isSRActionable) { this.isSRActionable = isSRActionable; } /** * Gets the severity level of notification * * @return The severity level */ public int getSeverityLevel() { return severityLevel; } /** * Sets the severity level of notification * * @param severityLevel The severity level */ public void setSeverityLevel(int severityLevel) { if (severityLevel < 1 || severityLevel > 5) { throw new IllegalArgumentException("The severty level should be between 1-5"); } this.severityLevel = severityLevel; } public Map<String, Boolean> getActiveStatusMap() { return activeStatusByTriggerAndMetric; } public void setActiveStatusMap(Map<String, Boolean> activeStatusByTriggerAndMetric) { this.activeStatusByTriggerAndMetric = activeStatusByTriggerAndMetric; } /** * Return the custom text in order to include in the notification * @return the customText is optional */ public String getCustomText() { return customText; } /** * Sets the custom text to the notification * @param customText customText is optional */ public void setCustomText(String customText) { this.customText = customText; } @Override public int hashCode() { int hash = 5; hash = 29 * hash + Objects.hashCode(this.name); hash = 29 * hash + Objects.hashCode(this.alert); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Notification other = (Notification) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.alert, other.alert)) { return false; } return true; } @Override public String toString() { return "Notification{" + "name=" + name + ", notifierName=" + notifierName + ", subscriptions=" + subscriptions + ", metricsToAnnotate=" + metricsToAnnotate + ", cooldownPeriod=" + cooldownPeriod + ", triggers=" + triggers + ", severity=" + severityLevel + ", srActionable=" + isSRActionable + ", customText;" + customText + '}'; } private String _hashTriggerAndMetric(Trigger trigger, Metric metric) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(metric != null, "Metric cannot be null"); if(trigger.getId()!=null) { return trigger.getId().toString() + "$$" + metric.getIdentifier().hashCode(); }else { return "0$$" + metric.getIdentifier().hashCode(); } } } /* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
36.558273
204
0.664948
8ac450e850d02be5d435893f269077c715b9deb1
1,089
package Hilos; /** * * @author damian */ public class mainClass { public static void main(String[] args) { hilo1 hilo1 = new hilo1(); hilo2 hilo2 = new hilo2(); hilo3 hilo3 = new hilo3(); hilo4 hilo4 = new hilo4(); hilo1.start(); try { hilo1.sleep(10); } catch (InterruptedException ex) { System.out.println("Error en el hilo1 " + ex); } hilo2.start(); try { hilo2.sleep(10); } catch (InterruptedException ex) { System.out.println("Error en el hilo2 " + ex); } hilo3.start(); try { hilo3.sleep(10); } catch (InterruptedException ex) { System.out.println("Error en el hilo3 " + ex); } hilo4.start(); try { hilo4.sleep(10); } catch (InterruptedException ex) { System.out.println("Error en el hilo4 " + ex); } } }
23.170213
59
0.442608
0723464d1e00c8d8d9ddeadbc86160be5a9ceea9
2,559
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.ibatis; import java.sql.SQLException; import com.ibatis.sqlmap.client.SqlMapExecutor; /** * Callback interface for data access code that works with the iBATIS * {@link com.ibatis.sqlmap.client.SqlMapExecutor} interface. To be used * with {@link SqlMapClientTemplate}'s <code>execute</code> method, * assumably often as anonymous classes within a method implementation. * * @author Juergen Hoeller * @since 24.02.2004 * @see SqlMapClientTemplate * @see org.springframework.jdbc.datasource.DataSourceTransactionManager */ public interface SqlMapClientCallback { /** * Gets called by <code>SqlMapClientTemplate.execute</code> with an active * <code>SqlMapExecutor</code>. Does not need to care about activating * or closing the <code>SqlMapExecutor</code>, or handling transactions. * * <p>If called without a thread-bound JDBC transaction (initiated by * DataSourceTransactionManager), the code will simply get executed on the * underlying JDBC connection with its transactional semantics. If using * a JTA-aware DataSource, the JDBC connection and thus the callback code * will be transactional if a JTA transaction is active. * * <p>Allows for returning a result object created within the callback, * i.e. a domain object or a collection of domain objects. * A thrown custom RuntimeException is treated as an application exception: * It gets propagated to the caller of the template. * * @param executor an active iBATIS SqlMapSession, passed-in as * SqlMapExecutor interface here to avoid manual lifecycle handling * @return a result object, or <code>null</code> if none * @throws SQLException if thrown by the iBATIS SQL Maps API * @see SqlMapClientTemplate#execute * @see SqlMapClientTemplate#executeWithListResult * @see SqlMapClientTemplate#executeWithMapResult */ Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException; }
40.619048
76
0.763189
5763cf838681e1edf9475804e55e0d444e4a5389
1,747
package com.xinsite.mybatis.datasource.master.service; import com.xinsite.mybatis.datasource.master.entity.TbObjectAtt; import com.xinsite.mybatis.datasource.master.mapper.TbObjectAttMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * create by zhangxiaxin * create time: 2019-10-29 */ @Service public class TbObjectAttService { @Autowired private TbObjectAttMapper tbObjectAttMapper; /** * 查询集合 * @return 集合 */ public List<TbObjectAtt> getTbObjectAttList(Map<String, Object> params) { return tbObjectAttMapper.getTbObjectAttList(params); } /** * 新增 */ public void addTbObjectAtt(TbObjectAtt tbObjectAtt) { tbObjectAttMapper.addTbObjectAtt(tbObjectAtt); } /** * 修改 */ public void updateTbObjectAttById(TbObjectAtt tbObjectAtt) { tbObjectAttMapper.updateTbObjectAttById(tbObjectAtt); } /** * 删除 */ public void deleteTbObjectAttById(int Primarykey) { try { tbObjectAttMapper.deleteTbObjectAttById(Primarykey); } catch (Exception e) { e.printStackTrace(); } } public TbObjectAtt dealUpdateBean(TbObjectAtt tbObjectAtt, Map<String, Object> params) { tbObjectAtt = new TbObjectAtt(); return tbObjectAtt; } public TbObjectAtt dealCreateBean(Map<String, Object> params) { TbObjectAtt tbObjectAtt = new TbObjectAtt(); return tbObjectAtt; } /** * 查询 * @return */ public TbObjectAtt getTbObjectAttById(int Primarykey) { return tbObjectAttMapper.getTbObjectAttById(Primarykey); } }
24.263889
92
0.680023
72ed07e43cfe77a4a1c1441976534a05c61f5b55
339
package zlogger.logic.dao; import zlogger.logic.models.Commentary; import zlogger.logic.models.Post; import zlogger.logic.models.User; import java.util.List; public interface CommentaryDao extends GenericDao<Long, Commentary> { public List<Commentary> listByPost(Post post); public List<Commentary> listForUser(User user); }
21.1875
69
0.784661
ddfaf394b4785f9597c368d6fc9271da53b4c0fd
1,036
import org.checkerframework.checker.initialization.qual.NotOnlyInitialized; import org.checkerframework.checker.initialization.qual.UnderInitialization; public class NotOnlyInitializedTest { @NotOnlyInitialized NotOnlyInitializedTest f; NotOnlyInitializedTest g; public NotOnlyInitializedTest() { f = new NotOnlyInitializedTest(); g = new NotOnlyInitializedTest(); } public NotOnlyInitializedTest(char i) { // we can store something that is under initialization (like this) in f, but not in g f = this; // :: error: (assignment.type.incompatible) g = this; } static void testDeref(NotOnlyInitializedTest o) { // o is fully iniatlized, so we can dereference its fields o.f.toString(); o.g.toString(); } static void testDeref2(@UnderInitialization NotOnlyInitializedTest o) { // o is not fully iniatlized, so we cannot dereference its fields // :: error: (dereference.of.nullable) o.f.toString(); // :: error: (dereference.of.nullable) o.g.toString(); } }
29.6
89
0.718147
b32040fd90123c08bafbb473f198a865e41babe9
5,468
import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("jp") @Implements("EnumDefinition") public class EnumDefinition extends DualNode { @ObfuscatedName("z") @ObfuscatedSignature( descriptor = "Lic;" ) @Export("EnumDefinition_archive") static AbstractArchive EnumDefinition_archive; @ObfuscatedName("k") @ObfuscatedSignature( descriptor = "Lel;" ) @Export("EnumDefinition_cached") static EvictingDualNodeHashTable EnumDefinition_cached; @ObfuscatedName("s") @Export("inputType") public char inputType; @ObfuscatedName("t") @Export("outputType") public char outputType; @ObfuscatedName("i") @Export("defaultStr") public String defaultStr; @ObfuscatedName("o") @ObfuscatedGetter( intValue = -1401922337 ) @Export("defaultInt") public int defaultInt; @ObfuscatedName("x") @ObfuscatedGetter( intValue = -1452935225 ) @Export("outputCount") public int outputCount; @ObfuscatedName("w") @Export("keys") public int[] keys; @ObfuscatedName("g") @Export("intVals") public int[] intVals; @ObfuscatedName("m") @Export("strVals") public String[] strVals; static { EnumDefinition_cached = new EvictingDualNodeHashTable(64); // L: 12 } EnumDefinition() { this.defaultStr = "null"; // L: 15 this.outputCount = 0; // L: 17 } // L: 22 @ObfuscatedName("s") @ObfuscatedSignature( descriptor = "(Lkf;I)V", garbageValue = "-2086226438" ) @Export("decode") void decode(Buffer var1) { while (true) { int var2 = var1.readUnsignedByte(); // L: 40 if (var2 == 0) { // L: 41 return; // L: 44 } this.decodeNext(var1, var2); // L: 42 } } @ObfuscatedName("t") @ObfuscatedSignature( descriptor = "(Lkf;IB)V", garbageValue = "57" ) @Export("decodeNext") void decodeNext(Buffer var1, int var2) { if (var2 == 1) { // L: 47 this.inputType = (char)var1.readUnsignedByte(); } else if (var2 == 2) { // L: 48 this.outputType = (char)var1.readUnsignedByte(); } else if (var2 == 3) { // L: 49 this.defaultStr = var1.readStringCp1252NullTerminated(); } else if (var2 == 4) { // L: 50 this.defaultInt = var1.readInt(); } else { int var3; if (var2 == 5) { // L: 51 this.outputCount = var1.readUnsignedShort(); // L: 52 this.keys = new int[this.outputCount]; // L: 53 this.strVals = new String[this.outputCount]; // L: 54 for (var3 = 0; var3 < this.outputCount; ++var3) { // L: 55 this.keys[var3] = var1.readInt(); // L: 56 this.strVals[var3] = var1.readStringCp1252NullTerminated(); // L: 57 } } else if (var2 == 6) { // L: 60 this.outputCount = var1.readUnsignedShort(); // L: 61 this.keys = new int[this.outputCount]; // L: 62 this.intVals = new int[this.outputCount]; // L: 63 for (var3 = 0; var3 < this.outputCount; ++var3) { // L: 64 this.keys[var3] = var1.readInt(); // L: 65 this.intVals[var3] = var1.readInt(); // L: 66 } } } } // L: 70 @ObfuscatedName("i") @ObfuscatedSignature( descriptor = "(B)I", garbageValue = "1" ) @Export("size") public int size() { return this.outputCount; // L: 73 } @ObfuscatedName("i") @ObfuscatedSignature( descriptor = "(Ljava/lang/CharSequence;I)[B", garbageValue = "-2060894177" ) public static byte[] method4644(CharSequence var0) { int var1 = var0.length(); // L: 84 byte[] var2 = new byte[var1]; // L: 85 for (int var3 = 0; var3 < var1; ++var3) { // L: 86 char var4 = var0.charAt(var3); // L: 87 if (var4 > 0 && var4 < 128 || var4 >= 160 && var4 <= 255) { // L: 88 var2[var3] = (byte)var4; } else if (var4 == 8364) { // L: 89 var2[var3] = -128; } else if (var4 == 8218) { // L: 90 var2[var3] = -126; } else if (var4 == 402) { // L: 91 var2[var3] = -125; } else if (var4 == 8222) { // L: 92 var2[var3] = -124; } else if (var4 == 8230) { // L: 93 var2[var3] = -123; } else if (var4 == 8224) { // L: 94 var2[var3] = -122; } else if (var4 == 8225) { // L: 95 var2[var3] = -121; } else if (var4 == 710) { // L: 96 var2[var3] = -120; } else if (var4 == 8240) { // L: 97 var2[var3] = -119; } else if (var4 == 352) { var2[var3] = -118; // L: 98 } else if (var4 == 8249) { // L: 99 var2[var3] = -117; } else if (var4 == 338) { // L: 100 var2[var3] = -116; } else if (var4 == 381) { // L: 101 var2[var3] = -114; } else if (var4 == 8216) { // L: 102 var2[var3] = -111; } else if (var4 == 8217) { // L: 103 var2[var3] = -110; } else if (var4 == 8220) { // L: 104 var2[var3] = -109; } else if (var4 == 8221) { // L: 105 var2[var3] = -108; } else if (var4 == 8226) { // L: 106 var2[var3] = -107; } else if (var4 == 8211) { // L: 107 var2[var3] = -106; } else if (var4 == 8212) { // L: 108 var2[var3] = -105; } else if (var4 == 732) { // L: 109 var2[var3] = -104; } else if (var4 == 8482) { // L: 110 var2[var3] = -103; } else if (var4 == 353) { // L: 111 var2[var3] = -102; } else if (var4 == 8250) { // L: 112 var2[var3] = -101; } else if (var4 == 339) { // L: 113 var2[var3] = -100; } else if (var4 == 382) { // L: 114 var2[var3] = -98; } else if (var4 == 376) { // L: 115 var2[var3] = -97; } else { var2[var3] = 63; // L: 116 } } return var2; // L: 118 } }
26.803922
73
0.584857
1791b5d46b2143ae228f6f23703d223e03ce0422
3,056
/******************************************************************************* * Copyright 2019 The EVL 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 eu.daproject.evl; /** * Class providing a base class for the method comparators. * The arguments passed to the calling invoke are set at thread-local and can be used for predicate based dispatch where there is no cache. */ public abstract class MethodComparator { private ThreadLocal<Object[]> threadLocalArgs = new ThreadLocal<Object[]>(); /** * Gets the arguments. * @return the arguments */ public Object[] args() { return threadLocalArgs.get(); } /** * Sets the arguments. * @param args the arguments */ void setArgs(Object[] args) { threadLocalArgs.set(args); } /** * Compares two {@link MethodItem} objects with priority after the tuple comparison. * This is a helper method to define easily the real <code>compare</code> methods. * @param m1 * @param m2 * @param tupleComparison * @return -1, zero, or 1 as <code>m1</code> is less than, equal to, or greater than <code>m2</code> */ protected int compareWithPriority(MethodItem m1, MethodItem m2, int tupleComparison) { // Compare the distance tuple of each multimethod. if (tupleComparison == 0) { Priority priority1 = null; if (m1.getData() == null) { priority1 = Priority.valueOf(0); } else if (m1.getData() instanceof Priority) { priority1 = (Priority)m1.getData(); } Priority priority2 = null; if (m2.getData() == null) { priority2 = Priority.valueOf(0); } else if (m2.getData() instanceof Priority) { priority2 = (Priority)m2.getData(); } if (priority1 != null) { // We search for the "closest" tuple, so if we want to choose m1 if it has greater priority i.e. m1 < m2, // then we need to invert the result. return -priority1.compareTo(priority2); } if (priority2 != null) { // We let the result because we compare priority2 < priority1. return priority2.compareTo(priority1); } } return tupleComparison; } /** * Compares two {@link MethodItem} objects. * The method must be implemented in the concrete method comparator. * @param m1 the first method item * @param m2 the second method item * @return -1, zero, or 1 as <code>m1</code> is less than, equal to, or greater than <code>m2</code> */ public abstract int compare(MethodItem m1, MethodItem m2); }
32.168421
139
0.650196
b6ae504e67c897721d72d3e5192fc8cc3361dc11
2,061
package com.potato369.find.dynamic.config; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.util.ArrayList; import java.util.List; @Configuration @SuppressWarnings({"unchecked", "rawtypes"}) public class MvcConfig extends WebMvcConfigurationSupport { @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat); fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 处理中文乱码问题 List fastMediaTypes = new ArrayList<>(); fastMediaTypes.add("application/json;charset=utf-8"); fastMediaTypes.add("application/xml;charset=utf-8"); fastMediaTypes.add("multipart/form-data;charset=utf-8"); fastConvert.setSupportedMediaTypes(fastMediaTypes); fastConvert.setFastJsonConfig(fastJsonConfig); return new HttpMessageConverters(fastConvert); } // 解决跨域问题 @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // **代表所有路径 .allowedOrigins("*") // allowOrigin指可以通过的ip,*代表所有,可以使用指定的ip,多个的话可以用逗号分隔,默认为* .allowedMethods("GET", "POST", "HEAD", "PUT", "DELETE") // 指请求方式 默认为* .allowCredentials(false) // 支持证书,默认为true .maxAge(3600) // 最大过期时间,默认为-1 .allowedHeaders("*"); } }
42.9375
112
0.806405
e16c2dea7ffcafebd94f7bc6dfcf83035171877d
2,751
/* * This file is part of Hammer, licensed under the MIT License (MIT). * * Copyright (c) 2015 Daniel Naylor * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package uk.co.drnaylor.minecraft.hammer.bukkit.text; import org.bukkit.ChatColor; import uk.co.drnaylor.minecraft.hammer.core.text.HammerText; import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextColours; import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextFormats; public final class HammerTextConverter { private HammerTextConverter() { } /** * Constructs a message from the collection of {@link HammerText} messages. * * @param message The {@link HammerText} messages. * @return The completed message. */ public static String constructMessage(HammerText message) { StringBuilder sb = new StringBuilder(); for (HammerText.Element t : message.getElements()) { if (sb.length() > 0) { sb.append(ChatColor.RESET); } convertColour(t.colour, sb); convertFormats(t.formats, sb); sb.append(t.message); } return sb.toString(); } private static void convertColour(HammerTextColours colour, StringBuilder sb) { ChatColor c = HammerTextToCodeConverter.getCodeFromHammerText(colour); if (c != null) { sb.append(c); } } private static void convertFormats(HammerTextFormats[] formats, StringBuilder sb) { for (HammerTextFormats f : formats) { ChatColor cf = HammerTextToCodeConverter.getCodeFromHammerText(f); if (cf != null) { sb.append(cf); } } } }
36.68
87
0.688477
ac5a3aa684f76ad3732f3029071d48bfb6ab96b9
1,495
package com.webank.wecross.stub.bcos; import com.webank.wecross.stub.Stub; import org.fisco.bcos.web3j.crypto.EncryptType; @Stub("GM_BCOS2.0") public class BCOSGMStubFactory extends BCOSBaseStubFactory { public BCOSGMStubFactory() { super(EncryptType.SM2_TYPE, "sm2p256v1", "GM_BCOS2.0"); } public static void main(String[] args) throws Exception { System.out.println( "This is BCOS2.0 Guomi Stub Plugin. Please copy this file to router/plugin/"); System.out.println("For deploy WeCrossProxy:"); System.out.println( " java -cp conf/:lib/*:plugin/* com.webank.wecross.stub.bcos.guomi.preparation.ProxyContractDeployment"); System.out.println("For deploy WeCrossHub:"); System.out.println( " java -cp conf/:lib/*:plugin/* com.webank.wecross.stub.bcos.guomi.preparation.HubContractDeployment"); System.out.println("For chain performance test, please run the command for more info:"); System.out.println( " Pure: java -cp conf/:lib/*:plugin/* " + com.webank.wecross.stub.bcos.performance.hellowecross.PerformanceTest .class.getName()); System.out.println( " Proxy: java -cp conf/:lib/*:plugin/* " + com.webank.wecross.stub.bcos.performance.hellowecross.proxy .PerformanceTest.class.getName()); } }
45.30303
124
0.615385
c599a444cca5d9c61b05192023f3a4885e283294
443
/** * Copyright (C) 2018-2020 * All rights reserved, Designed By www.yixiang.co * 注意: * 本软件为www.yixiang.co开发研制 */ //package co.yixiang.gen.service.mapper; // //import co.yixiang.common.mapper.CoreMapper; //import co.yixiang.gen.domain.GenConfig; //import org.apache.ibatis.annotations.Mapper; //import org.springframework.stereotype.Repository; // //@Repository //@Mapper //public interface GenConfigMapper extends CoreMapper<GenConfig> { //}
24.611111
66
0.756208
571403d0aa28cb6544407ff69fddf13a84d83d84
8,171
/* * Copyright (C) 2011 in-somnia * * This file is part of JAAD. * * JAAD is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * JAAD 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, see <http://www.gnu.org/licenses/>. */ package net.sourceforge.jaad.aac.ps2; interface FilterbankTables { float[] FILTER_20_2 = { 0.0f, 0.01899487526049f, 0.0f, -0.07293139167538f, 0.0f, 0.30596630545168f, 0.5f }; float[][][] FILTER_20_8 = { {{-0.005275603f, 0.005275603f}, {-0.008688525f, 0.020975955f}, {2.7841524E-18f, 0.04546866f}, {0.027806213f, 0.06713013f}, {0.06989827f, 0.06989827f}, {0.108959675f, 0.045132574f}, {0.125f, -0.0f}}, {{0.005275603f, 0.005275603f}, {0.020975955f, -0.008688525f}, {-8.352457E-18f, -0.04546866f}, {-0.06713013f, -0.027806213f}, {-0.06989827f, 0.06989827f}, {0.045132574f, 0.108959675f}, {0.125f, -0.0f}}, {{0.005275603f, -0.005275603f}, {-0.020975955f, -0.008688525f}, {1.3920761E-17f, 0.04546866f}, {0.06713013f, -0.027806213f}, {-0.06989827f, -0.06989827f}, {-0.045132574f, 0.108959675f}, {0.125f, -0.0f}}, {{-0.005275603f, -0.005275603f}, {0.008688525f, 0.020975955f}, {-1.9489067E-17f, -0.04546866f}, {-0.027806213f, 0.06713013f}, {0.06989827f, -0.06989827f}, {-0.108959675f, 0.045132574f}, {0.125f, -0.0f}}, {{-0.005275603f, 0.005275603f}, {0.008688525f, -0.020975955f}, {2.5057372E-17f, 0.04546866f}, {-0.027806213f, -0.06713013f}, {0.06989827f, 0.06989827f}, {-0.108959675f, -0.045132574f}, {0.125f, -0.0f}}, {{0.005275603f, 0.005275603f}, {-0.020975955f, 0.008688525f}, {-1.1139424E-16f, -0.04546866f}, {0.06713013f, 0.027806213f}, {-0.06989827f, 0.06989827f}, {-0.045132574f, -0.108959675f}, {0.125f, -0.0f}}, {{0.005275603f, -0.005275603f}, {0.020975955f, 0.008688525f}, {-4.4574583E-17f, 0.04546866f}, {-0.06713013f, 0.027806213f}, {-0.06989827f, -0.06989827f}, {0.045132574f, -0.108959675f}, {0.125f, -0.0f}}, {{-0.005275603f, -0.005275603f}, {-0.008688525f, -0.020975955f}, {-1.2253085E-16f, -0.04546866f}, {0.027806213f, -0.06713013f}, {0.06989827f, -0.06989827f}, {0.108959675f, -0.045132574f}, {0.125f, -0.0f}} }; float[][][] FILTER_34_12 = { {{2.4990022E-18f, 0.0408118f}, {0.009868281f, 0.036828928f}, {0.025724541f, 0.04455621f}, {0.04525364f, 0.04525364f}, {0.064331084f, 0.03714157f}, {0.07824335f, 0.020965243f}, {0.083333336f, -0.0f}}, {{-7.497006E-18f, -0.0408118f}, {-0.026960645f, -0.026960645f}, {-0.051449083f, 6.300696E-18f}, {-0.04525364f, 0.04525364f}, {4.5485305E-18f, 0.07428314f}, {0.057278108f, 0.057278108f}, {0.083333336f, -0.0f}}, {{4.8743166E-17f, 0.0408118f}, {0.036828928f, 0.009868281f}, {0.025724541f, -0.04455621f}, {-0.04525364f, -0.04525364f}, {-0.064331084f, 0.03714157f}, {0.020965243f, 0.07824335f}, {0.083333336f, -0.0f}}, {{-1.7493014E-17f, -0.0408118f}, {-0.036828928f, 0.009868281f}, {0.025724541f, 0.04455621f}, {0.04525364f, -0.04525364f}, {-0.064331084f, -0.03714157f}, {-0.020965243f, 0.07824335f}, {0.083333336f, -0.0f}}, {{2.2491018E-17f, 0.0408118f}, {0.026960645f, -0.026960645f}, {-0.051449083f, 1.8902086E-17f}, {0.04525364f, 0.04525364f}, {-1.3645591E-17f, -0.07428314f}, {-0.057278108f, 0.057278108f}, {0.083333336f, -0.0f}}, {{-9.998534E-17f, -0.0408118f}, {-0.009868281f, 0.036828928f}, {0.025724541f, -0.04455621f}, {-0.04525364f, 0.04525364f}, {0.064331084f, -0.03714157f}, {-0.07824335f, 0.020965243f}, {0.083333336f, -0.0f}}, {{-4.0009294E-17f, 0.0408118f}, {-0.009868281f, -0.036828928f}, {0.025724541f, 0.04455621f}, {-0.04525364f, -0.04525364f}, {0.064331084f, 0.03714157f}, {-0.07824335f, -0.020965243f}, {0.083333336f, -0.0f}}, {{-2.54974E-16f, -0.0408118f}, {0.026960645f, 0.026960645f}, {-0.051449083f, 1.228954E-16f}, {0.04525364f, -0.04525364f}, {8.871933E-17f, 0.07428314f}, {-0.057278108f, -0.057278108f}, {0.083333336f, -0.0f}}, {{-1.7500593E-16f, 0.0408118f}, {-0.036828928f, -0.009868281f}, {0.025724541f, -0.04455621f}, {0.04525364f, 0.04525364f}, {-0.064331084f, 0.03714157f}, {-0.020965243f, -0.07824335f}, {0.083333336f, -0.0f}}, {{-1.1997735E-16f, -0.0408118f}, {0.036828928f, -0.009868281f}, {0.025724541f, 0.04455621f}, {-0.04525364f, 0.04525364f}, {-0.064331084f, -0.03714157f}, {0.020965243f, -0.07824335f}, {0.083333336f, -0.0f}}, {{-2.0017278E-17f, 0.0408118f}, {-0.026960645f, 0.026960645f}, {-0.051449083f, 4.410487E-17f}, {-0.04525364f, -0.04525364f}, {-3.1839714E-17f, -0.07428314f}, {0.057278108f, -0.057278108f}, {0.083333336f, -0.0f}}, {{-1.2997337E-16f, -0.0408118f}, {0.009868281f, -0.036828928f}, {0.025724541f, -0.04455621f}, {0.04525364f, -0.04525364f}, {0.064331084f, -0.03714157f}, {0.07824335f, -0.020965243f}, {0.083333336f, -0.0f}} }; float[][][] FILTER_34_8 = { {{-0.011070998f, 0.011070998f}, {-0.014361023f, 0.034670576f}, {3.3175017E-18f, 0.054178912f}, {0.032210633f, 0.07776334f}, {0.07288393f, 0.07288393f}, {0.11292073f, 0.0467733f}, {0.125f, -0.0f}}, {{0.011070998f, 0.011070998f}, {0.034670576f, -0.014361023f}, {-9.952505E-18f, -0.054178912f}, {-0.07776334f, -0.032210633f}, {-0.07288393f, 0.07288393f}, {0.0467733f, 0.11292073f}, {0.125f, -0.0f}}, {{0.011070998f, -0.011070998f}, {-0.034670576f, -0.014361023f}, {1.6587507E-17f, 0.054178912f}, {0.07776334f, -0.032210633f}, {-0.07288393f, -0.07288393f}, {-0.0467733f, 0.11292073f}, {0.125f, -0.0f}}, {{-0.011070998f, -0.011070998f}, {0.014361023f, 0.034670576f}, {-2.3222512E-17f, -0.054178912f}, {-0.032210633f, 0.07776334f}, {0.07288393f, -0.07288393f}, {-0.11292073f, 0.0467733f}, {0.125f, -0.0f}}, {{-0.011070998f, 0.011070998f}, {0.014361023f, -0.034670576f}, {2.9857514E-17f, 0.054178912f}, {-0.032210633f, -0.07776334f}, {0.07288393f, 0.07288393f}, {-0.11292073f, -0.0467733f}, {0.125f, -0.0f}}, {{0.011070998f, 0.011070998f}, {-0.034670576f, 0.014361023f}, {-1.327336E-16f, -0.054178912f}, {0.07776334f, 0.032210633f}, {-0.07288393f, 0.07288393f}, {-0.0467733f, -0.11292073f}, {0.125f, -0.0f}}, {{0.011070998f, -0.011070998f}, {0.034670576f, 0.014361023f}, {-5.311356E-17f, 0.054178912f}, {-0.07776334f, 0.032210633f}, {-0.07288393f, -0.07288393f}, {0.0467733f, -0.11292073f}, {0.125f, -0.0f}}, {{-0.011070998f, -0.011070998f}, {-0.014361023f, -0.034670576f}, {-1.460036E-16f, -0.054178912f}, {0.032210633f, -0.07776334f}, {0.07288393f, -0.07288393f}, {0.11292073f, -0.0467733f}, {0.125f, -0.0f}} }; float[][][] FILTER_34_4 = { {{1.0853208E-17f, 0.059082113f}, {0.034446694f, 0.034446694f}, {-0.0f, 0.0f}, {-0.055003885f, 0.055003885f}, {1.009495E-17f, 0.16486304f}, {0.16461344f, 0.16461344f}, {0.25f, -0.0f}}, {{-3.2559626E-17f, -0.059082113f}, {-0.034446694f, 0.034446694f}, {-0.0f, 0.0f}, {0.055003885f, 0.055003885f}, {-3.0284846E-17f, -0.16486304f}, {-0.16461344f, 0.16461344f}, {0.25f, -0.0f}}, {{1.5921696E-16f, 0.059082113f}, {-0.034446694f, -0.034446694f}, {-0.0f, 0.0f}, {0.055003885f, -0.055003885f}, {5.0474746E-17f, 0.16486304f}, {-0.16461344f, -0.16461344f}, {0.25f, -0.0f}}, {{2.897846E-17f, -0.059082113f}, {0.034446694f, -0.034446694f}, {-0.0f, 0.0f}, {-0.055003885f, -0.055003885f}, {-7.066465E-17f, -0.16486304f}, {0.16461344f, -0.16461344f}, {0.25f, -0.0f}} }; }
31.306513
72
0.620854
523f75a466068a5f54234ed45f9ebba27801db53
2,673
package mage.cards.s; import java.util.UUID; import mage.MageInt; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.common.DamageTargetEffect; import mage.constants.SubType; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Zone; import mage.filter.common.FilterControlledPlaneswalkerPermanent; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.target.common.TargetAnyTarget; /** * * @author TheElk801 */ public final class SarkhansWhelp extends CardImpl { public SarkhansWhelp(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{R}"); this.subtype.add(SubType.DRAGON); this.power = new MageInt(2); this.toughness = new MageInt(2); // Flying this.addAbility(FlyingAbility.getInstance()); // Whenever you activate an ability of a Sarkhan planeswalker, Sarkhan's Whelp deals 1 damage to any target. this.addAbility(new SarkhansWhelpTriggeredAbility()); } private SarkhansWhelp(final SarkhansWhelp card) { super(card); } @Override public SarkhansWhelp copy() { return new SarkhansWhelp(this); } } class SarkhansWhelpTriggeredAbility extends TriggeredAbilityImpl { private static final FilterControlledPlaneswalkerPermanent filter = new FilterControlledPlaneswalkerPermanent( SubType.SARKHAN, "a Sarkhan planeswalker" ); public SarkhansWhelpTriggeredAbility() { super(Zone.BATTLEFIELD, new DamageTargetEffect(1), false); this.addTarget(new TargetAnyTarget()); } public SarkhansWhelpTriggeredAbility(final SarkhansWhelpTriggeredAbility ability) { super(ability); } @Override public SarkhansWhelpTriggeredAbility copy() { return new SarkhansWhelpTriggeredAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.ACTIVATED_ABILITY; } @Override public boolean checkTrigger(GameEvent event, Game game) { Permanent source = game.getPermanentOrLKIBattlefield(event.getSourceId()); return event.getPlayerId().equals(getControllerId()) && source != null && filter.match(source, game); } @Override public String getRule() { return "Whenever you activate an ability of a Sarkhan planeswalker, " + super.getRule(); } }
30.033708
116
0.700711
e4d0e4557664314b13cd95c3d838dc074ff0d037
4,446
package com.fdahpstudydesigner.bo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "active_task_lang") public class ActiveTaskLangBO implements Serializable { @EmbeddedId private ActiveTaskLangPK activeTaskLangPK; @Column(name = "study_id") private Integer studyId; @Column(name = "display_name") private String displayName; @Column(name = "instruction") private String instruction; @Column(name = "stat_name") private String statName; @Column(name = "stat_name2") private String statName2; @Column(name = "stat_name3") private String statName3; @Column(name = "chart_title") private String chartTitle; @Column(name = "chart_title2") private String chartTitle2; @Column(name = "chart_title3") private String chartTitle3; @Column(name = "created_by") private Integer createdBy; @Column(name = "created_on") private String createdOn; @Column(name = "modified_by") private Integer modifiedBy; @Column(name = "modified_on") private String modifiedOn; @Column(name = "display_units_stat") private String displayUnitStat; @Column(name = "display_units_stat2") private String displayUnitStat2; @Column(name = "display_units_stat3") private String displayUnitStat3; @Column(name = "active") private Boolean active = true; @Column(name = "status") private Boolean status = false; public ActiveTaskLangPK getActiveTaskLangPK() { return activeTaskLangPK; } public void setActiveTaskLangPK(ActiveTaskLangPK activeTaskLangPK) { this.activeTaskLangPK = activeTaskLangPK; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getChartTitle2() { return chartTitle2; } public void setChartTitle2(String chartTitle2) { this.chartTitle2 = chartTitle2; } public String getChartTitle3() { return chartTitle3; } public void setChartTitle3(String chartTitle3) { this.chartTitle3 = chartTitle3; } public String getInstruction() { return instruction; } public void setInstruction(String instruction) { this.instruction = instruction; } public String getStatName() { return statName; } public void setStatName(String statName) { this.statName = statName; } public String getStatName2() { return statName2; } public void setStatName2(String statName2) { this.statName2 = statName2; } public String getStatName3() { return statName3; } public void setStatName3(String statName3) { this.statName3 = statName3; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public String getCreatedOn() { return createdOn; } public void setCreatedOn(String createdOn) { this.createdOn = createdOn; } public Integer getModifiedBy() { return modifiedBy; } public void setModifiedBy(Integer modifiedBy) { this.modifiedBy = modifiedBy; } public String getChartTitle() { return chartTitle; } public Integer getStudyId() { return studyId; } public void setStudyId(Integer studyId) { this.studyId = studyId; } public void setChartTitle(String chartTitle) { this.chartTitle = chartTitle; } public String getModifiedOn() { return modifiedOn; } public void setModifiedOn(String modifiedOn) { this.modifiedOn = modifiedOn; } public String getDisplayUnitStat() { return displayUnitStat; } public void setDisplayUnitStat(String displayUnitStat) { this.displayUnitStat = displayUnitStat; } public String getDisplayUnitStat2() { return displayUnitStat2; } public void setDisplayUnitStat2(String displayUnitStat2) { this.displayUnitStat2 = displayUnitStat2; } public String getDisplayUnitStat3() { return displayUnitStat3; } public void setDisplayUnitStat3(String displayUnitStat3) { this.displayUnitStat3 = displayUnitStat3; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } }
20.117647
70
0.715475
053e88a28e65de9a6d860fa9925af91914ac725d
1,604
package com.labeling.demo.service.impl; import com.labeling.demo.entity.User; import com.labeling.demo.repository.UserMapper; import com.labeling.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class UserServiceImpl implements UserService { private UserMapper userMapper; //构造器注入 //尽量避免使用属性注入 @Autowired public UserServiceImpl(UserMapper userMapper) { this.userMapper = userMapper; } @Override public User findUser(String username) { return this.userMapper.selectByPrimaryKey(username); } @Override public List<User> findAll() { return userMapper.findAll(); } @Override @Transactional(rollbackFor = Exception.class) public boolean addUser(User user) { if(null == findUser(user.getUsername())){ return this.userMapper.insertSelective(user) >= 1; } return false; } @Override @Transactional(rollbackFor = Exception.class) public boolean updateUser(User user) { return this.userMapper.updateByPrimaryKeySelective(user) >= 1; } @Override public boolean updateBatchUser(List<User> users) { boolean isOk = false; for (User user: users) { isOk = this.updateUser(user); } return isOk; } @Override public List<User> findUserWithoutTeam() { return userMapper.findUserWithoutTeam(); } }
24.676923
70
0.683292
8ebda6085a2c1714332d2fcf0902fef18c6f960d
384
package com.clockworkcode.pentagonbusinesscomv2.repository; import com.clockworkcode.pentagonbusinesscomv2.model.product.ProductCategory; import org.springframework.data.jpa.repository.JpaRepository; public interface ProductCategoryRepository extends JpaRepository<ProductCategory,Long> { ProductCategory getProductCategoryByProductCategoryName(String productCategoryName); }
34.909091
88
0.875
e6b8b886d08d3727b6ccde2b27192dc1153a2311
12,564
/* * 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.skywalking.e2e.browser; import io.grpc.ManagedChannel; import io.grpc.internal.DnsNameResolverProvider; import io.grpc.netty.NettyChannelBuilder; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.UUID; import java.util.concurrent.CountDownLatch; import lombok.extern.slf4j.Slf4j; import org.apache.skywalking.apm.network.common.v3.Commands; import org.apache.skywalking.apm.network.language.agent.v3.BrowserPerfData; import org.apache.skywalking.apm.network.language.agent.v3.BrowserPerfServiceGrpc; import org.apache.skywalking.apm.network.language.agent.v3.ErrorCategory; import org.apache.skywalking.e2e.annotation.ContainerHostAndPort; import org.apache.skywalking.e2e.annotation.DockerCompose; import org.apache.skywalking.e2e.base.SkyWalkingE2E; import org.apache.skywalking.e2e.base.SkyWalkingTestAdapter; import org.apache.skywalking.e2e.base.TrafficController; import org.apache.skywalking.e2e.common.HostAndPort; import org.apache.skywalking.e2e.retryable.RetryableTest; import org.apache.skywalking.e2e.service.Service; import org.apache.skywalking.e2e.service.ServicesMatcher; import org.apache.skywalking.e2e.service.ServicesQuery; import org.apache.skywalking.e2e.service.endpoint.Endpoint; import org.apache.skywalking.e2e.service.endpoint.EndpointQuery; import org.apache.skywalking.e2e.service.endpoint.Endpoints; import org.apache.skywalking.e2e.service.endpoint.EndpointsMatcher; import org.apache.skywalking.e2e.service.instance.Instance; import org.apache.skywalking.e2e.service.instance.Instances; import org.apache.skywalking.e2e.service.instance.InstancesMatcher; import org.apache.skywalking.e2e.service.instance.InstancesQuery; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.testcontainers.containers.DockerComposeContainer; import static org.apache.skywalking.e2e.metrics.BrowserMetricsQuery.ALL_BROWSER_METRICS; import static org.apache.skywalking.e2e.metrics.BrowserMetricsQuery.ALL_BROWSER_PAGE_METRICS; import static org.apache.skywalking.e2e.metrics.BrowserMetricsQuery.ALL_BROWSER_PAGE_MULTIPLE_LINEAR_METRICS; import static org.apache.skywalking.e2e.metrics.BrowserMetricsQuery.ALL_BROWSER_SINGLE_VERSION_METRICS; import static org.apache.skywalking.e2e.metrics.MetricsMatcher.verifyMetrics; import static org.apache.skywalking.e2e.metrics.MetricsMatcher.verifyPercentileMetrics; import static org.apache.skywalking.e2e.utils.Times.now; import static org.apache.skywalking.e2e.utils.Yamls.load; @Slf4j @SkyWalkingE2E public class BrowserE2E extends SkyWalkingTestAdapter { private static final int MAX_INBOUND_MESSAGE_SIZE = 1024 * 1024 * 50; private static final String BROWSER_NAME = "e2e"; private static final String BROWSER_SINGLE_VERSION_NAME = "v1.0.0"; @SuppressWarnings("unused") @DockerCompose({ "docker/browser/docker-compose.${SW_STORAGE}.yml", }) private DockerComposeContainer<?> justForSideEffects; @SuppressWarnings("unused") @ContainerHostAndPort(name = "oap", port = 12800) private HostAndPort swWebappHostPort; @SuppressWarnings("unused") @ContainerHostAndPort(name = "oap", port = 11800) private HostAndPort oapHostPort; private BrowserPerfServiceGrpc.BrowserPerfServiceStub browserPerfServiceStub; @BeforeAll public void setUp() { queryClient(swWebappHostPort); final ManagedChannel channel = NettyChannelBuilder.forAddress(oapHostPort.host(), oapHostPort.port()) .nameResolverFactory(new DnsNameResolverProvider()) .maxInboundMessageSize(MAX_INBOUND_MESSAGE_SIZE) .usePlaintext() .build(); browserPerfServiceStub = BrowserPerfServiceGrpc.newStub(channel); generateTraffic(); } @AfterAll public void tearDown() { trafficController.stop(); } @RetryableTest public void verifyBrowserData() throws Exception { final List<Service> services = graphql.browserServices( new ServicesQuery().start(startTime).end(now())); LOGGER.info("services: {}", services); load("expected/browser/services.yml").as(ServicesMatcher.class).verify(services); for (Service service : services) { LOGGER.info("verifying service version: {}", service); // browser metrics verifyBrowserMetrics(service); // browser single version verifyBrowserSingleVersion(service); // browser page path verifyBrowserPagePath(service); } } @RetryableTest public void errorLogs() throws Exception { List<BrowserErrorLog> logs = graphql.browserErrorLogs(new BrowserErrorLogQuery().start(startTime).end(now())); LOGGER.info("errorLogs: {}", logs); load("expected/browser/error-log.yml").as(BrowserErrorLogsMatcher.class).verifyLoosely(logs); } private void verifyBrowserMetrics(final Service service) throws Exception { for (String metricName : ALL_BROWSER_METRICS) { verifyMetrics(graphql, metricName, service.getKey(), startTime); } } private void verifyBrowserSingleVersion(final Service service) throws Exception { Instances instances = graphql.instances( new InstancesQuery().serviceId(service.getKey()).start(startTime).end(now()) ); LOGGER.info("instances: {}", instances); load("expected/browser/version.yml").as(InstancesMatcher.class).verify(instances); // service version metrics for (Instance instance : instances.getInstances()) { verifyBrowserSingleVersionMetrics(instance); } } private void verifyBrowserSingleVersionMetrics(Instance instance) throws Exception { for (String metricName : ALL_BROWSER_SINGLE_VERSION_METRICS) { verifyMetrics(graphql, metricName, instance.getKey(), startTime); } } private void verifyBrowserPagePath(final Service service) throws Exception { Endpoints endpoints = graphql.endpoints(new EndpointQuery().serviceId(String.valueOf(service.getKey()))); LOGGER.info("endpoints: {}", endpoints); load("expected/browser/page-path.yml").as(EndpointsMatcher.class).verify(endpoints); // service page metrics for (Endpoint endpoint : endpoints.getEndpoints()) { verifyBrowserPagePathMetrics(endpoint); } } private void verifyBrowserPagePathMetrics(Endpoint endpoint) throws Exception { for (String metricName : ALL_BROWSER_PAGE_METRICS) { verifyMetrics(graphql, metricName, endpoint.getKey(), startTime); } for (String metricName : ALL_BROWSER_PAGE_MULTIPLE_LINEAR_METRICS) { verifyPercentileMetrics(graphql, metricName, endpoint.getKey(), startTime); } } private void generateTraffic() { trafficController = TrafficController.builder() .sender(this::sendBrowserData) .build() .start(); } private boolean sendBrowserData() { try { BrowserPerfData.Builder builder = BrowserPerfData.newBuilder() .setService(BROWSER_NAME) .setServiceVersion(BROWSER_SINGLE_VERSION_NAME) .setPagePath("/e2e-browser") .setRedirectTime(10) .setDnsTime(10) .setTtfbTime(10) .setTcpTime(10) .setTransTime(10) .setDomAnalysisTime(10) .setFptTime(10) .setDomReadyTime(10) .setLoadPageTime(10) .setResTime(10) .setSslTime(10) .setTtlTime(10) .setFirstPackTime(10) .setFmpTime(10); sendBrowserPerfData(builder.build()); for (ErrorCategory category : ErrorCategory.values()) { if (category == ErrorCategory.UNRECOGNIZED) { continue; } org.apache.skywalking.apm.network.language.agent.v3.BrowserErrorLog.Builder errorLogBuilder = org.apache.skywalking.apm.network.language.agent.v3.BrowserErrorLog .newBuilder() .setUniqueId(UUID.randomUUID().toString()) .setService(BROWSER_NAME) .setServiceVersion(BROWSER_SINGLE_VERSION_NAME) .setPagePath("/e2e-browser") .setCategory(category) .setMessage("test") .setLine(1) .setCol(1) .setStack("e2e") .setErrorUrl("/e2e-browser"); if (category == ErrorCategory.js) { errorLogBuilder.setFirstReportedError(true); } sendBrowserErrorLog(errorLogBuilder.build()); } return true; } catch (Exception e) { LOGGER.warn(e.getMessage(), e); return false; } } private void sendBrowserPerfData(BrowserPerfData browserPerfData) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); browserPerfServiceStub.collectPerfData(browserPerfData, new StreamObserver<Commands>() { @Override public void onNext(Commands commands) { } @Override public void onError(Throwable throwable) { LOGGER.warn(throwable.getMessage(), throwable); latch.countDown(); } @Override public void onCompleted() { latch.countDown(); } }); latch.await(); } private void sendBrowserErrorLog(org.apache.skywalking.apm.network.language.agent.v3.BrowserErrorLog browserErrorLog) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); StreamObserver<org.apache.skywalking.apm.network.language.agent.v3.BrowserErrorLog> collectStream = browserPerfServiceStub .collectErrorLogs( new StreamObserver<Commands>() { @Override public void onNext(Commands commands) { } @Override public void onError(Throwable throwable) { LOGGER.warn(throwable.getMessage(), throwable); latch.countDown(); } @Override public void onCompleted() { latch.countDown(); } }); collectStream.onNext(browserErrorLog); collectStream.onCompleted(); latch.await(); } }
43.175258
177
0.619707
3988ae5fcc7f73c3037a1db789b6ef16f1f7d3fe
3,804
package org.yidu.novel.action; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.interceptor.ServletResponseAware; import org.yidu.novel.action.base.AbstractPublicBaseAction; import org.yidu.novel.constant.YiDuConstants; import org.yidu.novel.entity.TOrder; import org.yidu.novel.utils.DateUtils; /** * * <p> * 手机画面用各种ajax接口 * </p> * Copyright(c) 2014 YiDu-Novel. All rights reserved. * * @version 1.1.9 * @author shinpa.you */ @Action(value = "zzfpayreturn") public class PayZZFReturnAction extends AbstractPublicBaseAction implements ServletResponseAware{ /** * 串行化版本统一标识符 */ private static final long serialVersionUID = -5966399886620363535L; /** * 订单号 */ private String cporderid; /** * 平台订单号 */ private String orderid; /** * 交易金额 */ private int appfee; /** * 支付完成时间 */ private String time_end; /** * 透传参数 */ private String attach; /** * 交易金额 */ private int status; private String feemode; /** * 交易金额 */ private int pay_type; private javax.servlet.http.HttpServletResponse response; // 获得HttpServletResponse对象 public void setServletResponse(HttpServletResponse response) { this.response = response; } public String getCporderid() { return cporderid; } public void setCporderid(String cporderid) { this.cporderid = cporderid; } public String getOrderid() { return orderid; } public void setOrderid(String orderid) { this.orderid = orderid; } public int getAppfee() { return appfee; } public void setAppfee(int appfee) { this.appfee = appfee; } public javax.servlet.http.HttpServletResponse getResponse() { return response; } public void setResponse(javax.servlet.http.HttpServletResponse response) { this.response = response; } public String getTime_end() { return time_end; } public void setTime_end(String time_end) { this.time_end = time_end; } public String getAttach() { return attach; } public void setAttach(String attach) { this.attach = attach; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getPay_type() { return pay_type; } public void setPay_type(int pay_type) { this.pay_type = pay_type; } public String getFeemode() { return feemode; } public void setFeemode(String feemode) { this.feemode = feemode; } @Override public String execute() { logger.debug("execute payreturn started. "); TOrder tOrder =new TOrder(); tOrder.setOrderno(cporderid); tOrder.setTotalfee(appfee); tOrder.setTimeend(DateUtils.getTimes()); tOrder.setTransactionid(orderid); if("1000200010000000".equals(feemode)){ pay_type=1; } else if("1000200020000000".equals(feemode)) { pay_type=2; } tOrder.setPaytype(pay_type); tOrder.setAttach(attach); tOrder.setModifytime(new Date()); orderService.save(tOrder); logger.debug("execute payreturn normally end. "); //回调输出 try { response.getWriter().write("0"); response.getWriter().flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public int getPageType() { return YiDuConstants.Pagetype.PAGE_OTHERS; } @Override protected void loadData() { } @Override public String getTempName() { return null; } }
17.449541
97
0.642219
57f4388b41eeebd83b17a5dd73a3ecf970e7a6d1
806
package com.example.creditwahana.Model.Login; import com.google.gson.annotations.SerializedName; public class LoginData { @SerializedName("jabatan") private String jabatan; @SerializedName("name") private String name; @SerializedName("id_user") private String idUser; @SerializedName("username") private String username; public void setJabatan(String jabatan){ this.jabatan = jabatan; } public String getJabatan(){ return jabatan; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setIdUser(String idUser){ this.idUser = idUser; } public String getIdUser(){ return idUser; } public void setUsername(String username){ this.username = username; } public String getUsername(){ return username; } }
16.12
50
0.729529
f7aafb9981e48d91b291e618f37ac00661f49233
1,985
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Mon 30 Apr 2007 at 13:18:35 PST by lamport // modified on Sat Feb 17 12:07:55 PST 2001 by yuanyu package tlc2.tool; public class TLCStateInfo { public static final String INITIAL_PREDICATE = "<Initial predicate>"; public TLCStateInfo predecessorState; public long stateNumber; public final TLCState state; public Object info; public Long fp; public TLCStateInfo(TLCState initialState) { this.state = initialState; this.info = INITIAL_PREDICATE; this.stateNumber = 1; this.fp = initialState.fingerPrint(); } public TLCStateInfo(TLCState s, Object info) { this.state = s; this.info = info; } public TLCStateInfo(TLCState state, int stateOrdinal) { this.state = state; this.stateNumber = stateOrdinal; this.info = ""; } public TLCStateInfo(TLCState s, String info, int stateNum) { this(s, info); stateNumber = stateNum; } public TLCStateInfo(TLCState s, String info, int stateNum, long fp) { this(s, info); stateNumber = stateNum; this.fp = fp; } public TLCStateInfo(TLCState s, TLCStateInfo info) { this(s, info.info); this.stateNumber = info.stateNumber; this.fp = info.fp; } public final long fingerPrint() { if (fp == null) { fp = this.state.fingerPrint(); } return fp.longValue(); } public final String toString() { return this.state.toString(); } public boolean equals(Object other) { if (other instanceof TLCStateInfo) { TLCStateInfo sinfo = (TLCStateInfo) other; return this.state.equals(sinfo.state); } else if (other instanceof TLCState) { TLCState state = (TLCState) other; return this.state.equals(state); } return false; } public int hashCode() { return this.state.hashCode(); } public TLCState getOriginalState() { return state; } }
24.207317
75
0.684131
d3fa7336fc91ac03ef05948ad3d706c7c8ac0527
617
package io.github.jitwxs.easydata.core.mock.mocker.explicit; import io.github.jitwxs.easydata.common.bean.MockConfig; import io.github.jitwxs.easydata.core.mock.EasyMock; import io.github.jitwxs.easydata.core.mock.mocker.IMocker; import java.time.LocalDate; import java.time.LocalDateTime; /** * @author [email protected] * @since 2022-03-20 16:48 */ public class LocalDateMocker implements IMocker<LocalDate> { @Override public LocalDate mock(MockConfig mockConfig) { final LocalDateTime ldt = EasyMock.run(LocalDateTime.class); return ldt == null ? null : ldt.toLocalDate(); } }
28.045455
68
0.747164
4c9d61903eebe793e5323115a95c466376582435
3,910
/* * Copyright 2018, Oath Inc * Licensed under the terms of the Apache License 2.0. Please refer to accompanying LICENSE file for terms. */ package com.oath.halodb; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Arjun Mannaly */ public class DBDirectoryTest { private static final File directory = Paths.get("tmp", "DBDirectoryTest").toFile(); private DBDirectory dbDirectory; private static Integer[] dataFileIds = {7, 12, 1, 8, 10}; private static Integer[] tombstoneFileIds = {21, 13, 12}; @Test public void testListIndexFiles() { List<Integer> actual = dbDirectory.listIndexFiles(); List<Integer> expected = Stream.of(dataFileIds).sorted().collect(Collectors.toList()); Assert.assertEquals(actual, expected); Assert.assertEquals(actual.size(), dataFileIds.length); } @Test public void testListDataFiles() { File[] files = dbDirectory.listDataFiles(); List<String> actual = Stream.of(files).map(File::getName).collect(Collectors.toList()); List<String> expected = Stream.of(dataFileIds).map(i -> i + HaloDBFile.DATA_FILE_NAME).collect(Collectors.toList()); MatcherAssert.assertThat(actual, Matchers.containsInAnyOrder(expected.toArray())); Assert.assertEquals(actual.size(), dataFileIds.length); } @Test public void testListTombstoneFiles() { File[] files = dbDirectory.listTombstoneFiles(); List<String> actual = Stream.of(files).map(File::getName).collect(Collectors.toList()); List<String> expected = Stream.of(tombstoneFileIds).sorted().map(i -> i + TombstoneFile.TOMBSTONE_FILE_NAME).collect(Collectors.toList()); Assert.assertEquals(actual, expected); Assert.assertEquals(actual.size(), tombstoneFileIds.length); } @Test public void testSyncMetaDataNoError() { dbDirectory.syncMetaData(); } @BeforeMethod public void createDirectory() throws IOException { dbDirectory = DBDirectory.open(directory); Path directoryPath = dbDirectory.getPath(); for (int i : dataFileIds) { try(PrintWriter writer = new PrintWriter(new FileWriter( directoryPath.resolve(i + IndexFile.INDEX_FILE_NAME).toString()))) { writer.append("test"); } try(PrintWriter writer = new PrintWriter(new FileWriter( directoryPath.resolve(i + HaloDBFile.DATA_FILE_NAME).toString()))) { writer.append("test"); } } // repair file, should be skipped. try(PrintWriter writer = new PrintWriter(new FileWriter( directoryPath.resolve(10000 + HaloDBFile.DATA_FILE_NAME + ".repair").toString()))) { writer.append("test"); } for (int i : tombstoneFileIds) { try(PrintWriter writer = new PrintWriter(new FileWriter( directoryPath.resolve(i + TombstoneFile.TOMBSTONE_FILE_NAME).toString()))) { writer.append("test"); } } // repair file, should be skipped. try(PrintWriter writer = new PrintWriter(new FileWriter( directoryPath.resolve(20000 + TombstoneFile.TOMBSTONE_FILE_NAME + ".repair").toString()))) { writer.append("test"); } } @AfterMethod public void deleteDirectory() throws IOException { dbDirectory.close(); TestUtils.deleteDirectory(directory); } }
35.225225
146
0.66445
1cde1aba142c7735ea6e0759c1dce34b15ae96ca
1,495
/* Copyrigh (c) Jasper Reddin 2013 All rights reserved */ package mathquizgame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; public final class timerControl implements ActionListener{ Timer timer; int secondsElapsed = 0; int overallDelaySeconds = 0; String threadName = ""; public timerControl(int seconds){ timer = new Timer(1000, this); timer.setRepeats(true); timer.setInitialDelay(1000); overallDelaySeconds = seconds; } public void start(){ MathQuizGame.frame.setTitle("MathQuizGame " + MathQuizGame.VERSION_ID + " — " + (overallDelaySeconds) + " seconds remaining."); timer.start(); } public void restart(){ timer.restart(); secondsElapsed = 0; } public void stop(){ timer.stop(); secondsElapsed = 0; MathQuizGame.frame.setTitle("MathQuizGame " + MathQuizGame.VERSION_ID + " — Timer set to " + overallDelaySeconds + " seconds."); } public void setInitialDelay(int delay){ timer.setInitialDelay(delay); } @Override public void actionPerformed(ActionEvent e) { secondsElapsed++; if(threadName.equals("")){ threadName = Thread.currentThread().getName(); } if(secondsElapsed > overallDelaySeconds){ MathQuizGame.EnterText("\nTimer reached " + overallDelaySeconds + " seconds."); MathQuizGame.endGame(); }else{ MathQuizGame.frame.setTitle("MathQuizGame " + MathQuizGame.VERSION_ID + " — " + (overallDelaySeconds - secondsElapsed) + " seconds remaining."); } } }
26.696429
147
0.717726
63ee9b13bd7821ff6f9d50a58974a60bf2f846fc
1,113
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.aegroto.gui; import com.aegroto.common.Helpers; import com.jme3.math.Vector2f; import java.util.ArrayList; import lombok.Getter; /** * * @author lorenzo */ public abstract class GUIInteractiveElement extends GUINode { @Getter protected GUIImage img; protected ArrayList<GUIInteractiveElement> interactiveGUIsList; /*@Override public void setPos(Vector2f pos) { img.setPos(pos.x, pos.y); this.pos=pos; } @Override public Vector2f getScale() { return scale; } @Override public Vector2f getPos() { return pos; }*/ public boolean isClickedOn(Vector2f point) { return Helpers.pointInArea(point, getGlobalPos(), getGlobalPos().add(scale)); } public abstract void funcClicked(Vector2f mousePos); public abstract void funcLeft(Vector2f mousePos); public void funcClickedContinously(Vector2f mousePos) { } }
22.714286
67
0.636119
396cc891350038de09419d9f6ed4b32607e10968
1,447
package com.stfalcon.imageviewer.viewer.builder; import android.graphics.Color; import android.view.View; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import com.stfalcon.imageviewer.listeners.OnDismissListener; import com.stfalcon.imageviewer.listeners.OnImageChangeListener; import com.stfalcon.imageviewer.loader.ImageLoader; import java.util.List; @RestrictTo(value = RestrictTo.Scope.LIBRARY) public final class BuilderData<T> { public int backgroundColor; public int startPosition; @Nullable public OnImageChangeListener imageChangeListener; @Nullable public OnDismissListener onDismissListener; @Nullable public View overlayView; public int imageMarginPixels; @NonNull public int[] containerPaddingPixels; public boolean shouldStatusBarHide; public boolean isZoomingAllowed; public boolean isSwipeToDismissAllowed; @Nullable public ImageView transitionView; @NonNull public final List<T> images; @NonNull public final ImageLoader<T> imageLoader; public BuilderData(@NonNull List<T> images, @NonNull ImageLoader<T> imageLoader) { this.images = images; this.imageLoader = imageLoader; this.backgroundColor = Color.BLACK; this.containerPaddingPixels = new int[4]; this.shouldStatusBarHide = true; this.isZoomingAllowed = true; this.isSwipeToDismissAllowed = true; } }
30.787234
84
0.794748
c78ebfcd4ed9cadbb35653b32ebadb1c8111f130
4,060
package top.nowandfuture.gamebrowser; import net.minecraft.client.Minecraft; import net.minecraft.client.world.ClientWorld; import net.minecraft.world.IWorld; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.event.server.FMLServerStartingEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import top.nowandfuture.gamebrowser.setup.ClientProxy; import top.nowandfuture.gamebrowser.setup.CommonProxy; import top.nowandfuture.gamebrowser.setup.Config; import top.nowandfuture.gamebrowser.setup.IProxy; import static top.nowandfuture.gamebrowser.InGameBrowser.ID; // The value here should match an entry in the META-INF/mods.toml file @Mod(value = ID) public class InGameBrowser { private static String HOME_PAGE; // Directly reference a log4j logger. public static IProxy proxy; public final static String ID = "gamebrowser"; public static final Logger LOGGER = LogManager.getLogger(ID); public static String getHomePage() { return HOME_PAGE; } public InGameBrowser() { ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, Config.CLIENT_CONFIG); // Register the setup method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // Register the doClientStuff method for modloading FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onLoad); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onReload); // Register ourselves for server and other game events we are interested in MinecraftForge.EVENT_BUS.register(this); proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); } public void onLoad(final ModConfig.Loading configEvent) { loadConfig(); } public void onReload(final ModConfig.Reloading configEvent) { loadConfig(); } public void loadConfig(){ HOME_PAGE = Config.HOME_PAGE.get(); } @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onMouseInput(InputEvent.RawMouseEvent inputEvent){ int btn = inputEvent.getButton(); int action = inputEvent.getAction(); if (Minecraft.getInstance().currentScreen == null) { boolean consume = ScreenManager.getInstance().updateMouseAction(btn, action, inputEvent.getMods()); if(consume){ inputEvent.setCanceled(true); } } } @OnlyIn(Dist.CLIENT) @SubscribeEvent public void onMouseScrolled(InputEvent.MouseScrollEvent inputEvent){ double d = inputEvent.getScrollDelta(); boolean consume = ScreenManager.getInstance().updateMouseScrolled(d); if(consume){ inputEvent.setCanceled(true); } } private void setup(final FMLCommonSetupEvent event){ proxy.setup(event); } private void doClientStuff(final FMLClientSetupEvent event) { proxy.doClientStuff(event); } @SubscribeEvent public void onServerStarting(FMLServerStartingEvent event) { // do something when the server starts LOGGER.info("HELLO from server starting"); } }
36.909091
111
0.739163
1ea6942dec91a10638da88960c846664cde554ee
2,083
package com.Volod878.volod_telegrambot.command; import com.Volod878.volod_telegrambot.repository.entity.TelegramUser; import com.Volod878.volod_telegrambot.service.SendBotMessageService; import com.Volod878.volod_telegrambot.service.TelegramUserService; import org.telegram.telegrambots.meta.api.objects.Update; /** * Start {@link Command}. */ public class StartCommand implements Command { private final SendBotMessageService sendBotMessageService; private final TelegramUserService telegramUserService; public final static String START_MESSAGE = "Привет. Меня немного научили общяться\uD83D\uDE0E\nНо я всеравно дико влюблен в Викусичку:)\n"+ "К тому же я помогу тебе быть в курсе последних статей на JavaRush тех авторов, которые тебе интересны.\n\n" + "Нажимай /addgroupsub чтобы подписаться на группу статей в JavaRush.\n" + "Не знаешь о чем я? Напиши /help, чтобы узнать что я умею."; // Здесь не добавляем сервис через получение из Application Context. // Потому что если это сделать так, то будет циклическая зависимость, которая // ломает работу приложения. public StartCommand(SendBotMessageService sendBotMessageService, TelegramUserService telegramUserService) { this.sendBotMessageService = sendBotMessageService; this.telegramUserService = telegramUserService; } @Override public void execute(Update update) { String chatId = update.getMessage().getChatId().toString(); telegramUserService.findByChatId(chatId).ifPresentOrElse( user -> { user.setActive(true); telegramUserService.save(user); }, () -> { TelegramUser telegramUser = new TelegramUser(); telegramUser.setActive(true); telegramUser.setChatId(chatId); telegramUserService.save(telegramUser); }); sendBotMessageService.sendMessage(chatId, START_MESSAGE); } }
42.510204
130
0.680269
ee39900e93e39520349ed6f184f149286450e688
1,792
package com.createchance.imageeditor.shaders; import android.opengl.GLES20; /** * Color balance adjustment fragment shader. * * @author createchance * @date 2018/12/21 */ public class ColorBalanceFragmentShader extends AbstractShader { private static final String TAG = "ColorBalanceFragmentSha"; private final String FRAGMENT_SHADER = "ColorBalanceFragmentShader.glsl"; private final String U_INPUT_TEXTURE = "u_InputTexture"; private final String U_RED_SHIFT = "u_RedShift"; private final String U_GREEN_SHIFT = "u_GreenShift"; private final String U_BLUE_SHIFT = "u_BlueShift"; private int mUInputTexture, mURedShift, mUGreenShift, mUBlueShift; public ColorBalanceFragmentShader() { initShader(FRAGMENT_SHADER, GLES20.GL_FRAGMENT_SHADER); } @Override public void initLocation(int programId) { mUInputTexture = GLES20.glGetUniformLocation(programId, U_INPUT_TEXTURE); mURedShift = GLES20.glGetUniformLocation(programId, U_RED_SHIFT); mUGreenShift = GLES20.glGetUniformLocation(programId, U_GREEN_SHIFT); mUBlueShift = GLES20.glGetUniformLocation(programId, U_BLUE_SHIFT); } public void setUInputTexture(int textureTarget, int textureId) { // bind texture GLES20.glActiveTexture(textureTarget); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); GLES20.glUniform1i(mUInputTexture, textureTarget - GLES20.GL_TEXTURE0); } public void setURedShift(float redShift) { GLES20.glUniform1f(mURedShift, redShift); } public void setUGreenShift(float greenShift) { GLES20.glUniform1f(mUGreenShift, greenShift); } public void setUBlueShift(float blueShift) { GLES20.glUniform1f(mUBlueShift, blueShift); } }
33.185185
81
0.736049
5d93406efd9327f3011c5b02a40d21ad6ab84c52
2,019
/** * <p>给定一个 <strong>正整数</strong> <code>num</code> ,编写一个函数,如果 <code>num</code> 是一个完全平方数,则返回 <code>true</code> ,否则返回 <code>false</code> 。</p> * * <p><strong>进阶:不要</strong> 使用任何内置的库函数,如 <code>sqrt</code> 。</p> * * <p> </p> * * <p><strong>示例 1:</strong></p> * * <pre> * <strong>输入:</strong>num = 16 * <strong>输出:</strong>true * </pre> * * <p><strong>示例 2:</strong></p> * * <pre> * <strong>输入:</strong>num = 14 * <strong>输出:</strong>false * </pre> * * <p> </p> * * <p><strong>提示:</strong></p> * * <ul> * <li><code>1 <= num <= 2^31 - 1</code></li> * </ul> * <div><div>Related Topics</div><div><li>数学</li><li>二分查找</li></div></div><br><div><li>👍 330</li><li>👎 0</li></div> */ package leetcode4; public class ValidPerfectSquare { public static void main(String[] args) { Solution solution = new ValidPerfectSquare().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public boolean isPerfectSquare(int num) { long left = 0, right = num; while (left < right) { long mid = (right - left + 1) / 2 + left; long val = mid * mid; if (val == num) { return true; } else if (val > num) { right = mid - 1; } else { left = mid; } } return false; } } //leetcode submit region end(Prohibit modification and deletion) class Solution2 { public boolean isPerfectSquare(int num) { long left = 0; long right = (num + 1) / 2; while (left < right) { long mid = (right - left + 1) / 2 + left; long m = mid * mid; if (m <= num) { left = mid; } else { right = mid - 1; } } return left * left == num; } } }
25.884615
138
0.460624
4e3a13ffbd8034a87b2de28eaea968f1491cc787
15,996
package com.riel_dev.hayaku; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.preference.Preference; import androidx.preference.PreferenceManager; import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import androidx.core.app.RemoteInput; import android.app.TaskStackBuilder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.load.resource.bitmap.RoundedCorners; import com.bumptech.glide.request.RequestOptions; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.initialization.InitializationStatus; import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; import com.google.android.gms.oss.licenses.OssLicensesMenuActivity; import java.util.Random; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.RequestToken; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; public class MainActivity extends AppCompatActivity{ // Global Basic Types public static final int NOTIFICATION_ID = 1; public static final String KEY_TWEET = "key_tweet"; public Boolean isAlreadyLoggedInToTwitter; public String profilePicUrl; // Global View Type Objects CardView accountCard; ImageView imageView; TextView textView; TextView textView2; SettingsFragment settingsFragment; NotificationCompat.Builder builder; Intent sendTwitterIntent; private AdView adView; // Global Twitter Type Objects RequestToken requestToken; ConfigurationBuilder configurationBuilder; TwitterFactory twitterFactory; Twitter twitter; RemoteInput remoteInput; @Override protected void onCreate(Bundle savedInstanceState) { @SuppressLint("HandlerLeak") Handler twitterDataLoadHandler = new Handler(){ public void handleMessage(Message msg){ setTwitterDataToViews(); } }; /* Bring Twitter Login Data with PreferenceManager then show into TextViews */ isAlreadyLoggedInToTwitter = CustomPreferenceManager.getBoolean(getApplicationContext(),"login"); if(isAlreadyLoggedInToTwitter){ configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(getString(R.string.consumer_key)); configurationBuilder.setOAuthConsumerSecret(getString(R.string.consumer_key_secret)); configurationBuilder.setOAuthAccessToken(CustomPreferenceManager.getString(getApplicationContext(), "access_token")); configurationBuilder.setOAuthAccessTokenSecret(CustomPreferenceManager.getString(getApplicationContext(), "access_secret")); twitterFactory = new TwitterFactory(configurationBuilder.build()); twitter = twitterFactory.getInstance(); sendTwitterIntent = new Intent(getApplicationContext(), SendTweetService.class); startService(sendTwitterIntent); Thread twitterDataLoadThread = new Thread(new Runnable() { @Override public void run() { try { loadTwitterData(); Message msg = twitterDataLoadHandler.obtainMessage(); twitterDataLoadHandler.sendMessage(msg); } catch (TwitterException e) { e.printStackTrace(); } } }); twitterDataLoadThread.start(); } Thread sleepThread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000); }catch (Exception e){ e.printStackTrace(); } } }); sleepThread.start(); setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar = getSupportActionBar(); Spannable text = new SpannableString(actionBar.getTitle()); text.setSpan(new ForegroundColorSpan(Color.BLACK), 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); actionBar.setTitle(text); actionBar.setElevation(0); loadSettingPreferences(); MobileAds.initialize(this, new OnInitializationCompleteListener() { @Override public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) { } }); adView = findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); /* Connect Views with findViewById */ accountCard = findViewById(R.id.twitterAccountCardView); imageView = findViewById(R.id.imageView); textView = findViewById(R.id.textView); textView2 = findViewById(R.id.textView2); /* Describe When User touches CardView (Twitter Account Information) */ accountCard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // If Application is not logged in to Twitter, go to LoginActivity if(!isAlreadyLoggedInToTwitter){ Thread twitterLoginThread = new Thread(new Runnable() { @Override public void run() { try { final String consumer_key = getString(R.string.consumer_key); final String consumer_key_secret = getString(R.string.consumer_key_secret); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(consumer_key); builder.setOAuthConsumerSecret(consumer_key_secret); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); requestToken = twitter.getOAuthRequestToken(); // intent to LoginActivity String twitterAuthURL = requestToken.getAuthorizationURL(); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); intent.putExtra("url", twitterAuthURL); intent.putExtra("twitter", twitter); intent.putExtra("requestToken", requestToken); startActivity(intent); finish(); } catch (TwitterException exception) { Toast.makeText(MainActivity.this, exception.toString(), Toast.LENGTH_SHORT).show(); } } }); twitterLoginThread.start(); }else{ // If Application is already logged in, show logout dialog showLogoutDialog(); } } }); } /* Dialog For Twitter Logout */ public void showLogoutDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Logout?").setMessage("Do you want to logout?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CustomPreferenceManager.clear(getApplicationContext()); Toast.makeText(getApplicationContext(), R.string.logout_notification, Toast.LENGTH_SHORT).show(); removeNotification(); reload(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } /* ReLoad View for some reasons such as Twitter data load */ public void reload(){ Intent intent = getIntent(); overridePendingTransition(0, 0); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); finish(); overridePendingTransition(0, 0); startActivity(intent); } private void show() { Intent resultIntent = new Intent(this, MainActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addNextIntentWithParentStack(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder = new NotificationCompat.Builder(this, "twitterId") .setSmallIcon(R.drawable.ic_twitter) .setContentTitle("Hayaku is running") .setContentIntent(resultPendingIntent) .setShowWhen(false) .setOngoing(true) .setContentText("Logged into " + CustomPreferenceManager.getString(getApplicationContext(), "twitterId")); Log.d("알림 생성", "성공"); remoteInput = new RemoteInput.Builder(KEY_TWEET) .setLabel("What's happening?") .build(); int randomRequestCode = new Random().nextInt(54325); Intent resultIntent2 = new Intent(getApplicationContext(), SendTweetService.class); PendingIntent tweetPendingIntent = PendingIntent.getService(getApplicationContext(),randomRequestCode, resultIntent2, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Action tweetAction = new NotificationCompat.Action.Builder(R.drawable.ic_edit, "Tweet", tweetPendingIntent) .addRemoteInput(remoteInput) .setAllowGeneratedReplies(true) .build(); builder.addAction(tweetAction); Log.d("트윗 액션 부착: ", "성공"); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationManager.createNotificationChannel(new NotificationChannel("twitterId", KEY_TWEET, NotificationManager.IMPORTANCE_LOW)); } notificationManager.notify(0, builder.build()); } private void hide() { NotificationManagerCompat.from(this).cancel(0); } public void createNotification() { show(); } public void removeNotification() { hide(); } /* 프리퍼런스 연결 */ private void loadSettingPreferences(){ settingsFragment = (SettingsFragment)getSupportFragmentManager().findFragmentById(R.id.fragment); // Open Source Notices Preference OssPreference = null; Preference tutorialPreference = null; Preference infoPreference = null; if (settingsFragment != null) { OssPreference = settingsFragment.findPreference("openSourceNotices"); tutorialPreference = settingsFragment.findPreference("tutorial"); infoPreference = settingsFragment.findPreference("information"); } if (OssPreference != null) { OssPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { OssLicensesMenuActivity.setActivityTitle("Open Source Licenses"); startActivity(new Intent(getApplicationContext(), OssLicensesMenuActivity.class)); return true; } }); } if (tutorialPreference != null) { tutorialPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { // 튜토리얼 추가 startActivity(new Intent(getApplicationContext(), TutorialActivity.class)); return true; } }); } if (infoPreference != null) { infoPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { // 인포메이션 추가 startActivity(new Intent(getApplicationContext(),AboutActivity.class)); return true; } }); } } private void loadTwitterData() throws TwitterException { User user = twitter.showUser(twitter.getId()); profilePicUrl = user.getOriginalProfileImageURLHttps(); CustomPreferenceManager.setString(getApplicationContext(), "profilePicUrl", profilePicUrl); Log.d("Profile Picture Url: ", profilePicUrl); String nickname = user.getName(); CustomPreferenceManager.setString(getApplicationContext(), "nickname", nickname); Log.d("Twitter Nickname: ", nickname); String twitterId = user.getScreenName(); Log.d("Twitter ID: ", twitterId); CustomPreferenceManager.setString(getApplicationContext(), "twitterId", "\u0040" + twitterId); } private void setTwitterDataToViews(){ /* Load Twitter Profile Image into ImageView */ if(CustomPreferenceManager.getString(getApplicationContext(), "profilePicUrl") != null) { Log.d("Profile Pic Url", CustomPreferenceManager.getString(getApplicationContext(), "profilePicUrl")); RequestOptions requestOptions = new RequestOptions(); requestOptions = requestOptions.transform(new CenterCrop(), new RoundedCorners(30)); Glide.with(MainActivity.this) .load(Uri.parse(CustomPreferenceManager.getString(getApplicationContext(), "profilePicUrl"))) .apply(requestOptions) .placeholder(R.drawable.egg) .error(R.drawable.egg) .into(imageView); }else{ Glide.with(this).load(R.drawable.egg).into(imageView); } textView = findViewById(R.id.textView); textView.setText(CustomPreferenceManager.getString(getApplicationContext(), "nickname")); textView2 = findViewById(R.id.textView2); textView2.setText(CustomPreferenceManager.getString(getApplicationContext(), "twitterId")); } }
44.557103
143
0.643223
df9d5478cdb36bd4f8334b6d3d58c33dc04d4aad
1,728
package org.technbolts.util; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ProcessGroupTest { private ProcessGroup<Integer> group; @BeforeMethod public void setUp () { group = new ProcessGroup<Integer>(Executors.newFixedThreadPool(4)); } @Test public void usecase () throws InterruptedException { final int NB = 100; final int NB_TASKS = 15; final AtomicInteger counter = new AtomicInteger(); for(int i=0;i<NB;i++) { final int iRef = i; group.spawn(new Runnable () { public void run() { for(int i=0;i<NB_TASKS;i++) { group.spawn(new Task(iRef+"-"+i, counter)); } } }); } group.awaitTermination(); assertThat(counter.get(), equalTo(NB*NB_TASKS)); } private Random random = new Random(13L); class Task implements Runnable { final AtomicInteger counter; final String id; private Task(String id, AtomicInteger counter) { super(); this.id = id; this.counter = counter; } public void run() { try { Thread.sleep(random.nextInt(17)); counter.incrementAndGet(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
27
75
0.561921
a7f83e4fe886cd0a33130fd2c34cb69d03b632aa
564
package org.adridadou.ethereum.propeller.solidity.converters.decoders; import org.adridadou.ethereum.propeller.values.EthData; import java.lang.reflect.Type; /** * Created by davidroon on 23.04.17. * This code is released under Apache 2 license */ public class EthDataDecoder implements SolidityTypeDecoder { @Override public EthData decode(Integer index, EthData data, Type resultType) { return data.word(index); } @Override public boolean canDecode(Class<?> resultCls) { return EthData.class.equals(resultCls); } }
25.636364
73
0.730496
c9ecdec92983660efdf582332d5a0c756f6acfe3
4,250
package com.lemon.demo.thread; /** * @author lemon * @return * @description join方法释放的是被调用join()方法的线程锁,而不是调用方。 join()可以保证让一个线程在另一个线程之前执行结束。 * 如何保证一个工作在另一个工作结束之前完成,就可以使用join()方法。 * @date 2019-11-11 17:07 */ public class JoinThread { // 定义锁 private static final Object LOCK = new Object(); public static void main(String[] args) throws InterruptedException { // otherObjectLock(); // joinThreadLock(); joinThreadLockWithWait(); } /** * @return void * @description join方法释放的是被调用join()方法的线程锁,而不是调用方 * @author lemon * @date 2019-11-14 17:36 */ private static void otherObjectLock() throws InterruptedException { final Thread thread1 = new Thread(() -> { synchronized (LOCK) { try { System.out.println("线程1开始运行....."); // 为了验证线程1在线程2之前运行结束,这里让线程1睡眠3秒 Thread.sleep(3000); System.out.println("线程1运行结束....."); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread thread2 = new Thread(() -> { // 调用join不会释放锁 synchronized (LOCK) { try { System.out.println("线程2开始运行 获取了锁....."); // 确保thread1线程已启动 Thread.sleep(200); // 线程2运行到这里会等待线程1运行结束 thread1.join(); System.out.println("线程2运行结束....."); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread2.setName("thread2-join"); thread2.start();// 先开启线程2 Thread.sleep(10); thread1.setName("thread1-join"); thread1.start();// 在开启线程1 } /** * @return void * @description thread1.join()释放的是thread1持有的锁 * @author lemon * @date 2019-11-14 18:02 */ private static void joinThreadLock() throws InterruptedException { class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; } @Override public void run() { synchronized (this) { for (int i = 0; i < 100; i++) { System.out.println(name + i); } } } } Thread thread1 = new MyThread("thread1 -- "); thread1.start(); synchronized (thread1) { for (int i = 0; i < 100; i++) { if (i == 20) { try { thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " -- " + i); } } } /** * @return void * @description wait模拟join方法,效果一样 * @author lemon * @date 2019-11-14 18:04 */ private static void joinThreadLockWithWait() throws InterruptedException { class MyThread extends Thread { private String name; private Object oo; public MyThread(String name, Object oo) { this.name = name; this.oo = oo; } @Override public void run() { synchronized (oo) { for (int i = 0; i < 100; i++) { System.out.println(name + i); } oo.notifyAll(); } } } Thread thread1 = new MyThread("thread1 -- ", LOCK); thread1.start(); synchronized (LOCK) { for (int i = 0; i < 100; i++) { if (i == 20) { try { LOCK.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " -- " + i); } } } }
28.145695
82
0.444471
dab43095dcaca3710f417b8557ed8e92bcd7f2ca
1,516
package com.github.ConcordiaSOEN341.Reader; import com.github.ConcordiaSOEN341.Logger.ILogger; import com.github.ConcordiaSOEN341.Logger.LoggerFactory; import com.github.ConcordiaSOEN341.Logger.LoggerType; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Reader implements IReader { private final int EOF = -1; private final String fileName; private FileInputStream inputStream; private final ILogger logger; public Reader(String f, LoggerFactory lf) { fileName = f; logger = lf.getLogger(LoggerType.READER); try { File file = new File(fileName); inputStream = new FileInputStream(file); } catch (FileNotFoundException | NullPointerException e) { System.out.println("FATAL ERROR: File not found"); System.exit(0); } logger.log("Created file \"" + fileName + "\""); } public final int getEof() { return EOF; } public void closeStream() { try { inputStream.close(); logger.log("Closed file \"" + fileName + "\""); } catch (IOException e) { System.out.println("Error closing file stream."); System.exit(0); } } public int read() { try { return inputStream.read(); } catch (IOException e) { System.out.println(e.getMessage()); return -1; } } }
27.071429
66
0.609499
85174591e90e625adff7ee09fe95de1a01f2944d
5,841
/* * Copyright (c) 2018 ACINO Consortium * * 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.onosproject.orchestrator.dismi.compiler; import org.onlab.util.Bandwidth; import org.onosproject.net.intent.constraint.EncryptionConstraint; import org.onosproject.net.intent.constraint.LatencyConstraint; import org.onosproject.orchestrator.dismi.primitives.AvailabilityConstraint; import org.onosproject.orchestrator.dismi.primitives.Constraint; import org.onosproject.orchestrator.dismi.primitives.HighAvailabilityConstraint; import org.onosproject.orchestrator.dismi.primitives.SecurityConstraint; import org.onosproject.orchestrator.dismi.primitives.extended.AvailabilityConstraintExtended; import org.onosproject.orchestrator.dismi.primitives.extended.BandwidthConstraintExtended; import org.onosproject.orchestrator.dismi.primitives.extended.DelayConstraintExtended; import org.slf4j.Logger; import java.time.Duration; import java.util.LinkedList; import java.util.List; import static org.slf4j.LoggerFactory.getLogger; public class ConstraintCompiler { private final Logger log = getLogger(getClass()); private List<Constraint> dismiConstraints = null; public ConstraintCompiler(List<Constraint> dismiConstraints) { this.dismiConstraints = dismiConstraints; } public List<org.onosproject.net.intent.Constraint> toAciConstraints() { //log.info("Converting DISMI constraints to ACI constraints !"); final List<org.onosproject.net.intent.Constraint> constraints = new LinkedList<>(); for (Constraint dismiConstraint : dismiConstraints) { if (dismiConstraint instanceof BandwidthConstraintExtended) { log.info("Converting DISMI BandwidthConstraint to ACI Bandwidth constraint !"); BandwidthConstraintExtended bandwidthConstraintExtended = (BandwidthConstraintExtended) dismiConstraint; // Check for a bandwidth specification Bandwidth bandwidth = Bandwidth.bps(bandwidthConstraintExtended.getBitrateExt()); constraints.add(new org.onosproject.net.intent.constraint.BandwidthConstraint(bandwidth)); } // Check for a latency specification else if (dismiConstraint instanceof DelayConstraintExtended) { log.info("Converting DISMI DelayConstraint to ACI LatencyConstraint constraint !"); LatencyConstraint latency; DelayConstraintExtended delayConstraintExtended = (DelayConstraintExtended) dismiConstraint; // delayConstraintExtended.getLatencyExt returns double value which represents duration in seconds // since LatencyConstraint accepts duration in millis therefore we multiplied LatencyExt with 1000 // for conversion. long inMillis = Math.round(delayConstraintExtended.getLatencyExt().doubleValue() * 1000); latency = new LatencyConstraint(Duration.ofMillis(inMillis)); constraints.add(latency); } else if (dismiConstraint instanceof SecurityConstraint) { log.info("Converting DISMI SecurityConstraint to ACI EncryptionConstraint constraint !"); SecurityConstraint securityConstraint = (SecurityConstraint) dismiConstraint; if (securityConstraint.getEncryption()) { constraints.add(new EncryptionConstraint()); } } else if (dismiConstraint instanceof HighAvailabilityConstraint) { log.info("Converting DISMI HighAvailabilityConstraint to ACI HighAvailabilityConstraint constraint !"); HighAvailabilityConstraint highAvailabilityConstraint = (HighAvailabilityConstraint) dismiConstraint; if (highAvailabilityConstraint.getAvailability()) { org.onosproject.net.intent.constraint.HighAvailabilityConstraint highAvailabilityConstraintAci = new org .onosproject.net.intent.constraint.HighAvailabilityConstraint(); constraints.add(highAvailabilityConstraintAci); } } else if (dismiConstraint instanceof AvailabilityConstraint) { log.info("Converting DISMI AvailabilityConstraint to ACI AvailabilityConstraint constraint !"); AvailabilityConstraintExtended availabilityConstraintExtended = (AvailabilityConstraintExtended) dismiConstraint; double availabilityExt = availabilityConstraintExtended.getAvailabilityExt(); if (availabilityExt == 99.9999) { org.onosproject.net.intent.constraint.HighAvailabilityConstraint highAvailabilityConstraintAci = new org.onosproject.net.intent.constraint.HighAvailabilityConstraint(); constraints.add(highAvailabilityConstraintAci); } else { org.onosproject.net.intent.constraint.AvailabilityConstraint availabilityConstraint = new org .onosproject.net.intent.constraint.AvailabilityConstraint(availabilityExt); constraints.add(availabilityConstraint); } } } return constraints; } }
57.831683
120
0.707756
08b4bf1d70a5a410626f243199c1f19305e26ec0
1,961
package com.itbuzzpress.microprofile.service; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.itbuzzpress.microprofile.model.SimpleProperty; import org.eclipse.microprofile.metrics.annotation.*; import org.eclipse.microprofile.metrics.MetricUnits; @Path("/simple") public class SimpleRESTService { @GET @Path("/time") @Gauge(unit = "time", absolute = true, name="checkTime") public Long checkTime() { return System.currentTimeMillis(); } @GET @Path("/hello") @Counted(description = "How many greetings", absolute = true, name="countHello") public String countHello () { return "hello world!"; } @GET @Path("/json") @Produces(MediaType.APPLICATION_JSON) @Metered(name = "getJSON", unit = MetricUnits.MINUTES, description = "Metrics to monitor frequency of getPropertyJSON.", absolute = true) public SimpleProperty getPropertyJSON () { SimpleProperty p = new SimpleProperty("key","value"); return p; } @GET @Path("/xml") @Produces(MediaType.APPLICATION_XML) @Timed(name = "getXML", absolute = true) public SimpleProperty getPropertyXML () { SimpleProperty p = new SimpleProperty("key","value"); try { Thread.sleep((long)(Math.random() * 1000)); } catch (Exception exc) { exc.printStackTrace(); } return p; } }
26.5
138
0.721571
04d0920e51761b948023a8b5a26bc972e0f9ec24
945
package com.codetaylor.mc.artisanworktables.api.internal.recipe; import net.minecraft.item.crafting.Ingredient; import javax.annotation.Nullable; public class InputReplacementEntry { private final IArtisanIngredient toReplace; private final IArtisanIngredient replacement; public InputReplacementEntry(@Nullable IArtisanIngredient toReplace, @Nullable IArtisanIngredient replacement) { this.toReplace = toReplace; this.replacement = replacement; } public boolean matches(IArtisanIngredient toMatch) { if (this.toReplace == null) { return (toMatch == null || toMatch == ArtisanIngredient.EMPTY || toMatch.toIngredient() == Ingredient.EMPTY); } for (IArtisanItemStack itemStack : toMatch.getMatchingStacks()) { if (this.toReplace.matches(itemStack)) { return true; } } return false; } public IArtisanIngredient getReplacement() { return this.replacement; } }
23.625
115
0.732275
11600d6d621fe4937b8d6a2b5d9766ba038bb99f
2,212
/* * Copyright 2012 akquinet * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.akquinet.innovation.play.maven; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; /** * Provide useful helper functions. */ public class Helper { //TODO Test clean mojo public static final File JAVA_APP_ROOT = new File("src/test/resources/java/app"); public static final File SCALA_APP_ROOT = new File("src/test/resources/scala/app"); public static final File MAVEN_APP_ROOT = new File("src/test/resources/sbt-properties/app"); public static void copyJavaApp(File out) throws IOException { if (out.exists()) { FileUtils.deleteQuietly(out); } out.mkdirs(); FileUtils.copyDirectory(JAVA_APP_ROOT, out); } public static void copyMavenApp(File out) throws IOException { if (out.exists()) { FileUtils.deleteQuietly(out); } out.mkdirs(); FileUtils.copyDirectory(MAVEN_APP_ROOT, out); } public static void copyScalaApp(File out) throws IOException { if (out.exists()) { FileUtils.deleteQuietly(out); } out.mkdirs(); FileUtils.copyDirectory(SCALA_APP_ROOT, out); } public static boolean detectPlay2() { String home = System.getProperty(AbstractPlay2Mojo.ENV_PLAY2_HOME); if (home != null && home.length() != 0) { return true; } // Second check, environment variable home = System.getenv(AbstractPlay2Mojo.ENV_PLAY2_HOME); if (home != null && home.length() != 0) { return true; } return false; } }
29.493333
96
0.657776
b503f8764e6f6c1aa18c254bf2c5928e54ab52a3
7,162
/** * Classe base para acceso a base de datos. * @author Marc Perez Rodriguez */ package io.github.marcperez06.java_utilities.database; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.List; public abstract class Database { private String url; private String user; private String password; protected Connection connection; protected Statement statement; protected PreparedStatement preparedStatement; protected ResultSet resultSet; public Database() { this.url = null; this.user = null; this.password = null; this.connection = null; this.statement = null; this.preparedStatement = null; this.resultSet = null; } public Database(String url, String user, String password) { this(); this.url = url; this.user = user; this.password = password; } @Override protected void finalize() { this.close(); } public String getUrl() { return this.user; } public void setUrl(String url) { this.url = url; } public String getUser() { return this.user; } public void setUser(String user) { this.user = user; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public abstract void createConnection(String url, String user, String password) throws SQLException, IllegalAccessException, ClassNotFoundException, Exception; public Connection getConnection() { return this.connection; } public void setConnection(Connection connection) { this.connection = connection; } public Statement getStatement() { return this.statement; } public PreparedStatement getPreparedStatement() { return this.preparedStatement; } public ResultSet getResultSet() { ResultSet resultSet = null; try { if (this.resultSet != null && this.resultSet.isClosed() == false) { resultSet = this.resultSet; } } catch (SQLException e) { resultSet = null; } return resultSet; } public int executeSQL(String sql) { int success = 0; try { this.openConnection(); this.statement = this.createStatement(); if (this.statement != null) { success = this.statement.executeUpdate(sql); this.statement.close(); this.connection.close(); } } catch (Exception e) { e.printStackTrace(); success = 0; } return success; } public void openConnection() { try { if (this.connection != null && this.connection.isClosed() == true) { this.createConnection(this.url, this.user, this.password); } } catch (Exception e) { e.printStackTrace(); } } public Statement createStatement() { Statement st = null; try { if (this.connection != null) { if (this.statement != null) { this.statement.close(); } st = this.connection.createStatement(); } } catch (SQLException e) { e.printStackTrace(); st = null; } return st; } public void executeQuery(String sql) { try { this.openConnection(); this.statement = this.createStatement(); if (this.statement != null) { this.resultSet = this.statement.executeQuery(sql); } } catch (Exception e) { e.printStackTrace(); } } public int executePreparedSQL(String sql, List<Object> parameters) { int success = 0; try { this.openConnection(); if (this.connection != null) { this.preparedStatement = this.createPreparedStatement(sql); for (int i = 0; i < parameters.size(); i++) { this.setPreparedValue(i, parameters.get(i)); } if (this.preparedStatement != null) { success = this.preparedStatement.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); success = 0; } return success; } public PreparedStatement createPreparedStatement(String sql) { PreparedStatement st = null; try { if (this.connection != null) { if (this.preparedStatement != null) { this.preparedStatement.close(); } st = this.connection.prepareStatement(sql); } } catch (SQLException e) { e.printStackTrace(); st = null; } return st; } public void executePreparedQuery(String sql, List<Object> parameters) { try { this.openConnection(); if (this.connection != null) { this.preparedStatement = this.createPreparedStatement(sql); for (int i = 0; i < parameters.size(); i++) { this.setPreparedValue(i, parameters.get(i)); } if (this.preparedStatement != null) { this.resultSet = this.preparedStatement.executeQuery(); } } } catch (SQLException e) { e.printStackTrace(); } } private void setPreparedValue(int indexOfParameter, Object parameter) throws SQLException { // correct the index of parameter value, to avoid exception, prepared statement values start in 1. int index = indexOfParameter + 1; if (this.preparedStatement != null) { if (parameter == null) { this.preparedStatement.setObject(index, parameter); } else if (parameter instanceof String) { String value = (String) parameter; this.preparedStatement.setString(index, value); } else if (parameter instanceof Integer) { Integer value = (Integer) parameter; this.preparedStatement.setInt(index, value.intValue()); } else if (parameter instanceof Double) { Double value = (Double) parameter; this.preparedStatement.setDouble(index, value.doubleValue()); } else if (parameter instanceof Float) { Float value = (Float) parameter; this.preparedStatement.setFloat(index, value.floatValue()); } else if (parameter instanceof Long) { Long value = (Long) parameter; this.preparedStatement.setLong(index, value.longValue()); } else if (parameter instanceof Date) { Date value = (Date) parameter; this.preparedStatement.setDate(index, value); } else if (parameter instanceof Timestamp) { Timestamp value = (Timestamp) parameter; this.preparedStatement.setTimestamp(index, value); } else if (parameter instanceof java.util.Date) { java.util.Date javaDate = (java.util.Date) parameter; if (javaDate != null) { Date value = new Date(javaDate.getTime()); this.preparedStatement.setDate(index, value); } } } } public void close() { try { if (this.statement != null) { this.statement.close(); } if (this.preparedStatement != null) { this.preparedStatement.close(); } if (this.connection != null) { this.connection.close(); } if (this.resultSet != null) { this.resultSet.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
22.59306
101
0.630829
16fe5d35d75195e8622d662bc7506c99ee68ac86
712
package com.springboot.show_web.endpoint; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 自定义事件端点 * Created by yaosheng on 2019/12/1. */ //@Endpoint(id = "datetime") public class DateTimeEndpoint { private String format = "yyyy-MM-DD HH:mm:ss"; //显示监控指标 //@ReadOperation public Map<String,Object> info(){ Map<String,Object> info = new HashMap<>(); info.put("name","Great"); info.put("age",24); info.put("datetime",new SimpleDateFormat(format).format(new Date())); return info; } //@WriteOperation public void setFormat(String foemat){ this.format = format; } }
23.733333
77
0.643258
2a10e6e06d7fb57f996e786d156482613e73b15f
8,595
package org.benetech.servicenet.web.rest.external; import com.codahale.metrics.annotation.Timed; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import javax.validation.Valid; import org.benetech.servicenet.domain.ClientProfile; import org.benetech.servicenet.domain.Organization; import org.benetech.servicenet.domain.OrganizationMatch; import org.benetech.servicenet.domain.enumeration.RecordType; import org.benetech.servicenet.errors.BadRequestAlertException; import org.benetech.servicenet.security.AuthoritiesConstants; import org.benetech.servicenet.security.SecurityUtils; import org.benetech.servicenet.service.ActivityService; import org.benetech.servicenet.service.ClientProfileService; import org.benetech.servicenet.service.OrganizationMatchService; import org.benetech.servicenet.service.OrganizationService; import org.benetech.servicenet.service.RecordsService; import org.benetech.servicenet.service.dto.external.RecordDetailsDTO; import org.benetech.servicenet.service.dto.external.RecordDto; import org.benetech.servicenet.service.dto.external.RecordRequest; import org.benetech.servicenet.service.dto.provider.ProviderRecordDTO; import org.benetech.servicenet.web.rest.util.PaginationUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * REST controller for managing external records request. */ @RestController @RequestMapping("/partner-api") @Api(tags = "external-access", description = "Endpoints with external access") public class RecordsResource { private final Logger log = LoggerFactory.getLogger(RecordsResource.class); @Autowired private OrganizationService organizationService; @Autowired private RecordsService recordsService; @Autowired private OrganizationMatchService organizationMatchService; @Autowired private ClientProfileService clientProfileService; @Autowired private ActivityService activityService; /** * POST /records : Resource to get the list of similar organizations * * @param recordRequest object containing string of id of searched organization and number of similarity threshold * @return the ResponseEntity with status 200 (OK) and list of RecordDto */ @PreAuthorize("hasRole('" + AuthoritiesConstants.EXTERNAL + "')") @PostMapping("/records") @Timed @ApiOperation(value = "Resource to get the list of organizations within a similarity threshold to" + " organization with provided id. Given ID can be either the ID of the organization in ServiceNet database" + " or ID from the external database of that organization's provider.") public ResponseEntity<List<RecordDto>> getOrganizationMatchInfos( @Valid @RequestBody RecordRequest recordRequest) throws URISyntaxException, BadRequestAlertException { log.debug("REST request to get Record : {}", recordRequest); String clientId = SecurityUtils.getCurrentClientId(); Optional<ClientProfile> optionalClientProfile = clientProfileService.findById(clientId); if (optionalClientProfile.isEmpty()) { throw new BadRequestAlertException("There is no provider associated with this account.", RecordType.ORGANIZATION.toString(), "id"); } ClientProfile clientProfile = optionalClientProfile.get(); UUID providerId = clientProfile.getSystemAccount().getId(); Optional<Organization> optionalOrganization = organizationService.findByIdOrExternalDbId( recordRequest.getId(), providerId); if (optionalOrganization.isEmpty()) { throw new BadRequestAlertException("There is no organization with such id.", RecordType.ORGANIZATION.toString(), "id"); } Organization organization = optionalOrganization.get(); List<OrganizationMatch> matches = organizationMatchService.findAllMatchesForOrganization(organization.getId()); List<RecordDto> results = this.mapMatchesToExternalRecords(matches, recordRequest.getSimilarity()); return ResponseEntity.ok() .body(results); } /** * GET /record-details : Resource to get all the record details for the specific organization * * @param elementId string * @return the ResponseEntity with status 200 (OK) and RecordDetailsDTO */ @PreAuthorize("hasRole('" + AuthoritiesConstants.EXTERNAL + "')") @GetMapping("/record-details/{elementId}") @Timed @ApiOperation(value = "Resource to get all the record details for the organization object found" + " by provided elementId. elementId can be either ServiceNet's database ID of organization, " + " service or location or external provider's database ID of organization, service or location." + " Returned are record details for organization related to the object with elementId.") public ResponseEntity<RecordDetailsDTO> getRecordDetails(@PathVariable String elementId) { Optional<Organization> optionalOrganization = organizationService.findWithEagerByIdOrExternalDbId(elementId); if (optionalOrganization.isEmpty()) { throw new BadRequestAlertException("There is no organization associated to given id.", RecordType.ORGANIZATION.toString(), "id"); } Organization organization = optionalOrganization.get(); return ResponseEntity.ok().body(recordsService.getRecordDetailsFromOrganization(organization)); } /** * GET /all-records : Resource to get all the records for Client's Silo and System Account * * @return the ResponseEntity with status 200 (OK) and a list of ProviderRecordDTO */ @PreAuthorize("hasRole('" + AuthoritiesConstants.EXTERNAL + "')") @GetMapping("/all-records") @Timed @ApiOperation(value = "Resource to get all the records for Client's Silo and System Account.") public ResponseEntity<List<ProviderRecordDTO>> getAllRecords(Pageable pageable) { String clientId = SecurityUtils.getCurrentClientId(); Optional<ClientProfile> optionalClientProfile = clientProfileService.findById(clientId); if (optionalClientProfile.isEmpty()) { throw new BadRequestAlertException("There is no provider associated with this account.", RecordType.ORGANIZATION.toString(), "id"); } ClientProfile clientProfile = optionalClientProfile.get(); UUID siloId = (clientProfile.getSilo() != null) ? clientProfile.getSilo().getId() : null; UUID systemAccountId = (clientProfile.getSystemAccount() != null) ? clientProfile.getSystemAccount().getId() : null; Page<ProviderRecordDTO> page = activityService.getAllPartnerActivities( siloId, systemAccountId, pageable); HttpHeaders headers = PaginationUtil .generatePaginationHttpHeaders(page, "/partner-api/all-records"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } private List<RecordDto> mapMatchesToExternalRecords(List<OrganizationMatch> matches, double similarity) { List<RecordDto> results = new ArrayList<>(); for (OrganizationMatch match : matches) { RecordDto response = new RecordDto(); response.setServiceNetId(match.getPartnerVersion().getId()); response.setOrganizationName(match.getPartnerVersion().getName()); response.setExternalDbId(match.getPartnerVersion().getExternalDbId()); response.setSimilarity(match.getSimilarity().doubleValue()); if (match.getSimilarity().doubleValue() >= similarity) { results.add(response); } } return results; } }
49.396552
124
0.743921