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
d17b9e88dd09f5618795a314ffc13dbe5fd04ece
166
package com.github.gv2011.util.beans; @FunctionalInterface public interface Parser<T> { T parse(final String encoded, ExtendedBeanBuilder<T> builder); }
18.444444
65
0.740964
44dd39785cc800d354c8d262bed9f52c2c547e05
592
package org.flowable.rest.servlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; @Configuration @ComponentScan({ "org.flowable.rest.dmn.exception", "org.flowable.rest.dmn.service.api" }) @EnableAsync public class DmnDispatcherServletConfiguration extends BaseDispatcherServletConfiguration { protected final Logger log = LoggerFactory.getLogger(DmnDispatcherServletConfiguration.class); }
34.823529
98
0.842905
020c2d10726d467416b639beec7b47aa882de680
16,130
/******************************************************************************* * Copyright 2011 Netflix * * 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.netflix.astyanax.test; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.BadRequestException; import com.netflix.astyanax.connectionpool.exceptions.ConnectionAbortedException; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.HostDownException; import com.netflix.astyanax.connectionpool.exceptions.OperationTimeoutException; import com.netflix.astyanax.connectionpool.exceptions.TimeoutException; import com.netflix.astyanax.connectionpool.exceptions.TransportException; import com.netflix.astyanax.connectionpool.impl.OperationResultImpl; public enum TestHostType { ALWAYS_DOWN { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { throw new TransportException("TransportException"); } }, CONNECT_WITH_UNCHECKED_EXCEPTION { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return null; } @Override public void open(long timeout) throws ConnectionException { throw new RuntimeException("UNCHECKED_OPEN_EXCEPTION"); } }, CONNECT_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new IllegalStateException(CONNECT_TIMEOUT.name()); } @Override public void open(long timeout) throws ConnectionException { try { Thread.sleep(50); } catch (InterruptedException e) { } throw new TimeoutException("TimeoutException"); } }, CONNECT_TRANSPORT_ERROR { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new IllegalStateException(CONNECT_TRANSPORT_ERROR.name()); } @Override public void open(long timeout) throws ConnectionException { throw new TransportException(CONNECT_TRANSPORT_ERROR.name()); } }, CONNECT_FAIL_FIRST { private AtomicInteger count = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { if (count.getAndIncrement() == 0) { throw new TransportException("connection refused"); } } }, CONNECT_FAIL_FIRST_TWO { private AtomicInteger count = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { if (count.incrementAndGet() <= 2) { throw new TransportException("connection refused"); } } }, LOST_CONNECTION { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { } }, SOCKET_TIMEOUT_AFTER10 { private AtomicInteger count = new AtomicInteger(0); private int failAfter = 10; @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (count.incrementAndGet() >= failAfter) { throw new TimeoutException("TimeoutException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(5)); } @Override public void open(long timeout) throws ConnectionException { if (count.get() >= failAfter) { think(1000); throw new TimeoutException("Timeout"); // count.set(0); } } }, OPERATION_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new OperationTimeoutException("TimedOutException"); } @Override public void open(long timeout) throws ConnectionException { } }, SOCKET_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { think(2000); throw new TimeoutException("SocketTimeException"); } @Override public void open(long timeout) throws ConnectionException { } }, ALTERNATING_SOCKET_TIMEOUT_200 { private AtomicLong counter = new AtomicLong(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (counter.incrementAndGet() / 200 % 2 == 1) { think(200); throw new TimeoutException("SocketTimeException"); } else { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(0)); } } @Override public void open(long timeout) throws ConnectionException { } }, CONNECT_BAD_REQUEST_EXCEPTION { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { throw new BadRequestException("BadRequestException"); } }, GOOD_SLOW { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(500)); } @Override public void open(long timeout) throws ConnectionException { think(500); } }, GOOD_FAST { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(5)); } @Override public void open(long timeout) throws ConnectionException { } }, GOOD_IMMEDIATE { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, FAIL_AFTER_100 { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (counter.incrementAndGet() > 100) { counter.set(0); throw new TransportException("TransportException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, FAIL_AFTER_100_RANDOM { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (counter.incrementAndGet() > new Random().nextInt(1000)) { counter.set(0); throw new TransportException("TransportException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, THRASHING_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { think(50 + new Random().nextInt(1000)); throw new TimeoutException("thrashing_timeout"); } @Override public void open(long timeout) throws ConnectionException { } }, RECONNECT_2ND_TRY { int retry = 0; @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { if (++retry == 2) { // success } else { throw new TransportException("TransportException"); } } }, ABORTED_CONNECTION { boolean aborted = true; @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (aborted) { aborted = false; throw new ConnectionAbortedException( "ConnectionAbortedException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, FAIL_AFTER_10_SLOW_CLOSE { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { think(100); if (counter.incrementAndGet() > 10) { counter.set(0); throw new TransportException("TransportException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } @Override public void close() { // LOG.info("Closing"); think(15000); } }, SWAP_EVERY_200 { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if ((counter.incrementAndGet() / 20) % 2 == 0) { think(100); } else { think(1); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } @Override public void close() { // LOG.info("Closing"); think(15000); } }, RANDOM_ALL { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { double p = new Random().nextDouble(); if (p < 0.002) { throw new HostDownException("HostDownException"); } else if (p < 0.004) { throw new TimeoutException("HostDownException"); } else if (p < 0.006) { throw new TransportException("TransportException"); } think(200); } @Override public void close() { // LOG.info("Closing"); think(10); } }; private static final Logger LOG = LoggerFactory .getLogger(TestHostType.class); private static final Map<Integer, TestHostType> lookup = new HashMap<Integer, TestHostType>(); static { for (TestHostType type : EnumSet.allOf(TestHostType.class)) lookup.put(type.ordinal(), type); } public static TestHostType get(int ordinal) { return lookup.get(ordinal); } public abstract <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException; public abstract void open(long timeout) throws ConnectionException; public void close() { } private static int think(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { } return time; } }
32.651822
100
0.584439
c9adfe62c3e83b8e33d5b80bcd1de1bc29fb92a1
410
package com.xiaomi.channel.commonutils.logger; import org.android.agoo.common.AgooConstants; public class a implements LoggerInterface { private String a; public a() { this.a = AgooConstants.MESSAGE_SYSTEM_SOURCE_XIAOMI; } public void log(String str) { } public void log(String str, Throwable th) { } public void setTag(String str) { this.a = str; } }
18.636364
60
0.660976
799c48c43031c0a48880d9504e61f16e22f514dd
1,061
package org.narrative.common.persistence.hibernate; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.type.Type; import java.util.List; /** * Created by IntelliJ IDEA. * User: Paul * Date: Jan 23, 2006 * Time: 4:47:21 PM */ public class MySQLBitwiseAndFunction extends StandardSQLFunction implements SQLFunction { public MySQLBitwiseAndFunction(String name) { super(name); } public MySQLBitwiseAndFunction(String name, Type typeValue) { super(name, typeValue); } @Override public String render(Type firstArgumentType, List args, SessionFactoryImplementor sessionFactory) { if (args.size() != 2) { throw new IllegalArgumentException("the function must be passed 2 arguments"); } StringBuffer buffer = new StringBuffer(args.get(0).toString()); buffer.append(" & ").append(args.get(1)); return buffer.toString(); } }
29.472222
103
0.71065
c492185334194c17515cd70aff2d13ad90ca7697
4,274
package org.hzero.admin.domain.entity; import com.fasterxml.jackson.annotation.JsonInclude; import io.choerodon.core.exception.CommonException; import io.choerodon.mybatis.annotation.ModifyAudit; import io.choerodon.mybatis.annotation.MultiLanguage; import io.choerodon.mybatis.annotation.MultiLanguageField; import io.choerodon.mybatis.annotation.VersionAudit; import io.choerodon.mybatis.domain.AuditDomain; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hibernate.validator.constraints.Length; import org.hzero.admin.domain.repository.ServiceRouteRepository; import org.hzero.core.util.Regexs; import org.hzero.mybatis.domian.Condition; import org.hzero.mybatis.util.Sqls; import org.hzero.starter.keyencrypt.core.Encrypt; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.Pattern; import java.util.Date; /** * 应用服务 * * @author zhiying.dong@hand-china.com 2018-11-14 11:04:42 */ @ApiModel("应用服务") @VersionAudit @ModifyAudit @MultiLanguage @JsonInclude(JsonInclude.Include.NON_NULL) @Table(name = "hadm_service") public class HService extends AuditDomain { public static final String ENCRYPT_KEY = "hadm_service"; public static final String FIELD_SERVICE_ID = "serviceId"; public static final String FIELD_SERVICE_CODE = "serviceCode"; public static final String FIELD_SERVICE_NAME = "serviceName"; public static final String FIELD_SERVICE_LOGO = "serviceLogo"; public static final String FIELD_VERSION_NUMBER = "versionNumber"; /** * 校验是否存在服务路由引用该服务 */ public void checkServiceRef(ServiceRouteRepository routeRepository) { int count = routeRepository.selectCountByCondition(Condition.builder(ServiceRoute.class) .andWhere(Sqls.custom() .andEqualTo(ServiceRoute.FIELD_SERVICE_ID, serviceId) ).build()); if (count != 0) { throw new CommonException("hadm.error.has_route_rely"); } } @Encrypt @Id @GeneratedValue @ApiModelProperty("服务ID") private Long serviceId; @ApiModelProperty("服务编码") @Length(max = 60) @Pattern(regexp = Regexs.CODE) private String serviceCode; @ApiModelProperty("服务名称") @MultiLanguageField @Length(max = 90) private String serviceName; @ApiModelProperty("服务图标") private String serviceLogo; @Transient @ApiModelProperty("服务版本") private String versionNumber; @Transient @ApiModelProperty("发布时间") private Date releaseDate; @Transient @ApiModelProperty("更新时间") private Date updateDate; // // getter/setter // ------------------------------------------------------------------------------ /** * @return 表ID,主键 */ public Long getServiceId() { return serviceId; } public void setServiceId(Long serviceId) { this.serviceId = serviceId; } /** * @return 服务编码 */ public String getServiceCode() { return serviceCode; } public HService setServiceCode(String serviceCode) { this.serviceCode = serviceCode; return this; } /** * @return 服务名称 */ public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } /** * @return 服务图标 */ public String getServiceLogo() { return serviceLogo; } public void setServiceLogo(String serviceLogo) { this.serviceLogo = serviceLogo; } public String getVersionNumber() { return versionNumber; } public HService setVersionNumber(String versionNumber) { this.versionNumber = versionNumber; return this; } public Date getReleaseDate() { return releaseDate; } public HService setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; return this; } public Date getUpdateDate() { return updateDate; } public HService setUpdateDate(Date updateDate) { this.updateDate = updateDate; return this; } }
26.382716
96
0.676416
7cc4d19390c3188084d994d140cf2b164c8cc38a
4,619
package example; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Scanner; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.client.util.Data; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.BigqueryScopes; import com.google.api.services.bigquery.model.GetQueryResultsResponse; import com.google.api.services.bigquery.model.QueryRequest; import com.google.api.services.bigquery.model.QueryResponse; import com.google.api.services.bigquery.model.TableCell; import com.google.api.services.bigquery.model.TableRow; import com.lin.web.util.LinMobileConstants; import com.lin.web.util.LinMobileVariables; public class TestBQ { // Enter your Google Developer Project number or string id. private static final String PROJECT_ID = "LinDigital"; // Use a Google APIs Client standard client_secrets.json OAuth 2.0 parameters file. private static final String CLIENTSECRETS_LOCATION = "auth.json"; // Objects for handling HTTP transport and JSON formatting of API calls. private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); private static final JsonFactory JSON_FACTORY = new JacksonFactory(); public static void main(String[] args) throws IOException, GeneralSecurityException { List SCOPES=new ArrayList<String>(); SCOPES.add(LinMobileConstants.GOOGLE_BIGQUERY_SCOPE); GoogleCredential credential = null; credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY) .setServiceAccountId(LinMobileConstants.GOOGLE_API_SERVICE_ACCOUNT_EMAIL_ADDRESS) .setServiceAccountScopes(SCOPES) //.setServiceAccountPrivateKeyFromP12File(new File("892d0834292bff62001a53a17624d1b22f1002a3-privatekey.p12")) .setServiceAccountPrivateKeyFromP12File(new File("C:/Users/user/git/linmobile-dev/src/main/resources/env/keys/" + LinMobileVariables.SERVICE_ACCOUNT_KEY)) .build(); Bigquery bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) .setApplicationName("BigQuery-Service-Accounts/0.1") .setHttpRequestInitializer(credential).build(); String query = "SELECT * FROM [LinDigital:LIN_DEV.test_table] "; runQueryRpcAndPrint(bigquery, PROJECT_ID, query, System.out); } static void runQueryRpcAndPrint( Bigquery bigquery, String projectId, String query, PrintStream out) throws IOException { QueryRequest queryRequest = new QueryRequest().setQuery(query); QueryResponse queryResponse = bigquery.jobs().query(projectId, queryRequest).execute(); if (queryResponse.getJobComplete()) { printRows(queryResponse.getRows(), out); if (null == queryResponse.getPageToken()) { return; } } // This loop polls until results are present, then loops over result pages. String pageToken = null; while (true) { GetQueryResultsResponse queryResults = bigquery.jobs() .getQueryResults(projectId, queryResponse.getJobReference().getJobId()) .setPageToken(pageToken).execute(); if (queryResults.getJobComplete()) { printRows(queryResults.getRows(), out); pageToken = queryResults.getPageToken(); if (null == pageToken) { return; } } } } private static void printRows(List<TableRow> rows, PrintStream out) { if (rows != null) { for (TableRow row : rows) { for (TableCell cell : row.getF()) { // Data.isNull() is the recommended way to check for the 'null object' in TableCell. out.printf("%s, ", Data.isNull(cell.getV()) ? "null" : cell.getV().toString()); } out.println(); } } } }
41.612613
114
0.740204
f6e520c43d9c94289f8203bd43fbdb383e646e79
322
package com.example.BookService; import com.example.BookService.database.Database; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public Database database() { return new Database(); } }
20.125
60
0.763975
5367c2d2bbc5c060568e069803910657ea0143ec
85
int factorial(n = 4) { if (4 <= 1) return 1; return 4 * factorial(3); }
14.166667
27
0.494118
0f5287e23a42a8d83711f30f3a731fa6764d1207
183
package org.lefmaroli.factorgenerator; public interface NumberGenerator<N extends Number> extends ReusableGenerator, Iterable<N> { N getNext(); NumberGenerator<N> getCopy(); }
20.333333
91
0.775956
3d4bab45650d4688b097162844b82e22acd4ed76
15,874
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.remote; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.geogit.api.ObjectId; import org.geogit.api.Ref; import org.geogit.api.RepositoryFilter.FilterDescription; import org.geogit.api.RevCommit; import org.geogit.api.RevObject; import org.geogit.api.RevObject.TYPE; import org.geogit.api.SymRef; import org.geogit.api.plumbing.RevObjectParse; import org.geogit.api.plumbing.diff.DiffEntry; import org.geogit.api.porcelain.DiffOp; import org.geogit.repository.Repository; import org.geogit.storage.ObjectSerializingFactory; import org.geogit.storage.ObjectWriter; import org.geogit.storage.datastream.DataStreamSerializationFactory; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Provides a means of communicating between a local sparse clone and a remote http full repository. * * @see AbstractMappedRemoteRepo */ class HttpMappedRemoteRepo extends AbstractMappedRemoteRepo { private URL repositoryURL; /** * Constructs a new {@code HttpMappedRemoteRepo}. * * @param repositoryURL the URL of the repository * @param localRepository the local sparse repository */ public HttpMappedRemoteRepo(URL repositoryURL, Repository localRepository) { super(localRepository); String url = repositoryURL.toString(); if (url.endsWith("/")) { url = url.substring(0, url.lastIndexOf('/')); } try { this.repositoryURL = new URL(url); } catch (MalformedURLException e) { this.repositoryURL = repositoryURL; } } /** * Currently does nothing for HTTP Remote. * * @throws IOException */ @Override public void open() throws IOException { } /** * Currently does nothing for HTTP Remote. * * @throws IOException */ @Override public void close() throws IOException { } /** * List the mapped versions of the remote's {@link Ref refs}. For example, if the remote ref * points to commit A, the returned ref will point to the commit that A is mapped to. * * @param getHeads whether to return refs in the {@code refs/heads} namespace * @param getTags whether to return refs in the {@code refs/tags} namespace * @return an immutable set of refs from the remote */ @Override public ImmutableSet<Ref> listRefs(boolean getHeads, boolean getTags) { HttpURLConnection connection = null; ImmutableSet.Builder<Ref> builder = new ImmutableSet.Builder<Ref>(); try { String expanded = repositoryURL.toString() + "/repo/manifest"; connection = (HttpURLConnection) new URL(expanded).openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoOutput(true); // Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; try { while ((line = rd.readLine()) != null) { if ((getHeads && line.startsWith("refs/heads")) || (getTags && line.startsWith("refs/tags"))) { Ref remoteRef = HttpUtils.parseRef(line); Ref newRef = remoteRef; if (!(newRef instanceof SymRef) && localRepository.getGraphDatabase().exists( remoteRef.getObjectId())) { ObjectId mappedCommit = localRepository.getGraphDatabase().getMapping( remoteRef.getObjectId()); if (mappedCommit != null) { newRef = new Ref(remoteRef.getName(), mappedCommit, remoteRef.getType()); } } builder.add(newRef); } } } finally { rd.close(); } } catch (Exception e) { throw Throwables.propagate(e); } finally { HttpUtils.consumeErrStreamAndCloseConnection(connection); } return builder.build(); } /** * @return the remote's HEAD {@link Ref}. */ @Override public Ref headRef() { HttpURLConnection connection = null; Ref headRef = null; try { String expanded = repositoryURL.toString() + "/repo/manifest"; connection = (HttpURLConnection) new URL(expanded).openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoOutput(true); // Get Response InputStream is = connection.getInputStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { if (line.startsWith("HEAD")) { headRef = HttpUtils.parseRef(line); } } rd.close(); } finally { is.close(); } } catch (Exception e) { Throwables.propagate(e); } finally { HttpUtils.consumeErrStreamAndCloseConnection(connection); } return headRef; } /** * Delete a {@link Ref} from the remote repository. * * @param refspec the ref to delete */ @Override public void deleteRef(String refspec) { updateRemoteRef(refspec, null, true); } /** * @return the {@link RepositoryWrapper} for this remote */ @Override protected RepositoryWrapper getRemoteWrapper() { return new HttpRepositoryWrapper(repositoryURL); } /** * Gets all of the changes from the target commit that should be applied to the sparse clone. * * @param commit the commit to get changes from * @return an iterator for changes that match the repository filter */ @Override protected FilteredDiffIterator getFilteredChanges(RevCommit commit) { // Get affected features ImmutableList<ObjectId> affectedFeatures = HttpUtils.getAffectedFeatures(repositoryURL, commit.getId()); // Create a list of features I have List<ObjectId> tracked = new LinkedList<ObjectId>(); for (ObjectId id : affectedFeatures) { if (localRepository.blobExists(id)) { tracked.add(id); } } // Get changes from commit, pass filter and my list of features final JsonObject message = createFetchMessage(commit.getId(), tracked); final URL resourceURL; try { resourceURL = new URL(repositoryURL.toString() + "/repo/filteredchanges"); } catch (MalformedURLException e) { throw Throwables.propagate(e); } final Gson gson = new Gson(); final HttpURLConnection connection; final OutputStream out; final Writer writer; try { connection = (HttpURLConnection) resourceURL.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); out = connection.getOutputStream(); writer = new OutputStreamWriter(out); gson.toJson(message, writer); writer.flush(); } catch (IOException e) { throw Throwables.propagate(e); } final InputStream in; try { in = connection.getInputStream(); } catch (IOException e) { throw Throwables.propagate(e); } BinaryPackedChanges unpacker = new BinaryPackedChanges(localRepository); return new HttpFilteredDiffIterator(in, unpacker); } private JsonObject createFetchMessage(ObjectId commitId, List<ObjectId> tracked) { JsonObject message = new JsonObject(); JsonArray trackedArray = new JsonArray(); for (ObjectId id : tracked) { trackedArray.add(new JsonPrimitive(id.toString())); } message.add("commitId", new JsonPrimitive(commitId.toString())); message.add("tracked", trackedArray); JsonArray filterArray = new JsonArray(); ImmutableList<FilterDescription> repoFilters = filter.getFilterDescriptions(); for (FilterDescription description : repoFilters) { JsonObject typeFilter = new JsonObject(); typeFilter.add("featurepath", new JsonPrimitive(description.getFeaturePath())); typeFilter.add("type", new JsonPrimitive(description.getFilterType())); typeFilter.add("filter", new JsonPrimitive(description.getFilter())); filterArray.add(typeFilter); } message.add("filter", filterArray); return message; } /** * Gets the remote ref that matches the provided ref spec. * * @param refspec the refspec to parse * @return the matching {@link Ref} or {@link Optional#absent()} if the ref could not be found */ @Override protected Optional<Ref> getRemoteRef(String refspec) { return HttpUtils.getRemoteRef(repositoryURL, refspec); } /** * Perform pre-push actions. */ @Override protected void beginPush() { HttpUtils.beginPush(repositoryURL); } /** * Perform post-push actions, this includes verification that the remote wasn't changed while we * were pushing. * * @param refspec the refspec that we are pushing to * @param newCommitId the new commit id * @param originalRefValue the original value of the ref before pushing */ @Override protected void endPush(String refspec, ObjectId newCommitId, String originalRefValue) { HttpUtils.endPush(repositoryURL, refspec, newCommitId, originalRefValue); } /** * Pushes a sparse commit to a remote repository and updates all mappings. * * @param commitId the commit to push */ @Override protected void pushSparseCommit(ObjectId commitId) { Repository from = localRepository; Optional<RevObject> object = from.command(RevObjectParse.class).setObjectId(commitId) .call(); if (object.isPresent() && object.get().getType().equals(TYPE.COMMIT)) { RevCommit commit = (RevCommit) object.get(); ObjectId parent = ObjectId.NULL; List<ObjectId> newParents = new LinkedList<ObjectId>(); for (int i = 0; i < commit.getParentIds().size(); i++) { ObjectId parentId = commit.getParentIds().get(i); if (i != 0) { Optional<ObjectId> commonAncestor = from.getGraphDatabase() .findLowestCommonAncestor(commit.getParentIds().get(0), parentId); if (commonAncestor.isPresent()) { if (from.getGraphDatabase().isSparsePath(parentId, commonAncestor.get())) { // This should be the base commit to preserve changes that were filtered // out. newParents.add(0, from.getGraphDatabase().getMapping(parentId)); continue; } } } newParents.add(from.getGraphDatabase().getMapping(parentId)); } if (newParents.size() > 0) { parent = from.getGraphDatabase().getMapping(newParents.get(0)); } Iterator<DiffEntry> diffIter = from.command(DiffOp.class).setNewVersion(commitId) .setOldVersion(parent).setReportTrees(true).call(); // connect and send packed changes final URL resourceURL; try { resourceURL = new URL(repositoryURL.toString() + "/repo/applychanges"); } catch (MalformedURLException e) { throw Throwables.propagate(e); } final HttpURLConnection connection; final OutputStream out; try { connection = (HttpURLConnection) resourceURL.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); out = connection.getOutputStream(); // pack the commit object final ObjectSerializingFactory factory = new DataStreamSerializationFactory(); final ObjectWriter<RevCommit> commitWriter = factory .createObjectWriter(TYPE.COMMIT); commitWriter.write(commit, out); // write the new parents out.write(newParents.size()); for (ObjectId parentId : newParents) { out.write(parentId.getRawValue()); } // pack the changes BinaryPackedChanges changes = new BinaryPackedChanges(from); changes.write(out, diffIter); } catch (IOException e) { throw Throwables.propagate(e); } final InputStream in; try { in = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = rd.readLine(); if (line != null) { ObjectId remoteCommitId = ObjectId.valueOf(line); from.getGraphDatabase().map(commit.getId(), remoteCommitId); from.getGraphDatabase().map(remoteCommitId, commit.getId()); } } catch (IOException e) { throw Throwables.propagate(e); } } } /** * Retrieves an object with the specified id from the remote. * * @param objectId the object to get * @return the fetched object */ @Override protected Optional<RevObject> getObject(ObjectId objectId) { return HttpUtils.getNetworkObject(repositoryURL, null, objectId); } /** * Updates the remote ref that matches the given refspec. * * @param refspec the ref to update * @param commitId the new value of the ref * @param delete if true, the remote ref will be deleted * @return the updated ref */ @Override protected Ref updateRemoteRef(String refspec, ObjectId commitId, boolean delete) { return HttpUtils.updateRemoteRef(repositoryURL, refspec, commitId, delete); } /** * Gets the depth of the remote repository. * * @return the depth of the repository, or {@link Optional#absent()} if the repository is not * shallow */ @Override public Optional<Integer> getDepth() { return HttpUtils.getDepth(repositoryURL, null); } }
36.077273
100
0.595817
7ff0e6529e784b2dce078f3cda1af9010df49d0d
2,146
/** * Copyright (C) 2006-2016 INRIA and contributors * Spoon - http://spoon.gforge.inria.fr/ * * This software is governed by the CeCILL-C License under French law and * abiding by the rules of distribution of free software. You can use, modify * and/or redistribute the software under the terms of the CeCILL-C license as * circulated by CEA, CNRS and INRIA at http://www.cecill.info. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the CeCILL-C License for more details. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. */ package spoon.support.reflect.reference; import spoon.reflect.factory.Factory; import spoon.reflect.factory.FactoryImpl; import spoon.reflect.reference.CtReference; import spoon.reflect.visitor.CtVisitor; import spoon.reflect.visitor.DefaultJavaPrettyPrinter; import spoon.support.reflect.declaration.CtElementImpl; import java.io.Serializable; import java.lang.reflect.AnnotatedElement; public abstract class CtReferenceImpl extends CtElementImpl implements CtReference, Serializable { private static final long serialVersionUID = 1L; protected String simplename = ""; public CtReferenceImpl() { super(); } protected abstract AnnotatedElement getActualAnnotatedElement(); @Override public String getSimpleName() { return simplename; } @Override public <T extends CtReference> T setSimpleName(String simplename) { Factory factory = getFactory(); if (factory instanceof FactoryImpl) { simplename = ((FactoryImpl) factory).dedup(simplename); } this.simplename = simplename; return (T) this; } @Override public String toString() { DefaultJavaPrettyPrinter printer = new DefaultJavaPrettyPrinter( getFactory().getEnvironment()); printer.scan(this); return printer.toString(); } @Override public abstract void accept(CtVisitor visitor); @Override public CtReference clone() { return (CtReference) super.clone(); } }
29.805556
98
0.767008
48080063760e9c8d582836236ec8bbe77aebead6
1,422
package hello.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "T_SYS_USER") public class SysUser implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "SN") private String sn; @Column(name = "password") private String pwd; @Column(name = "FULL_NAME") private String fullName; public SysUser() { super(); } public SysUser(String sn, String pwd, String fullName) { super(); this.sn = sn; this.pwd = pwd; this.fullName = fullName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } @Override public String toString() { return String.format("SysUser [id=%s, sn=%s, pwd=%s, fullName=%s]", id, sn, pwd, fullName); } }
17.775
94
0.658228
eff8dc1bf54e704f0b4cae17236b784b8ed04036
355
package io.renren.modules.saas.dao; import io.renren.modules.saas.entity.AuthenEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * * * @author blooze * @email 1459264166@qq.com * @date 2019-04-25 11:34:20 */ @Mapper public interface AuthenDao extends BaseMapper<AuthenEntity> { }
19.722222
61
0.752113
40f6017ceed81f99dc65c3c81017857d875e374d
3,249
package betterwithaddons.util; import net.minecraft.block.BlockBanner; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemBanner; import net.minecraft.item.ItemShield; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class BannerUtil { public static ItemStack getBannerItemFromBlock(World world, BlockPos pos) { IBlockState blockstate = world.getBlockState(pos); if (blockstate.getBlock() instanceof BlockBanner) { BlockBanner bannerblock = (BlockBanner) blockstate.getBlock(); return bannerblock.getItem(world, pos, blockstate); } return ItemStack.EMPTY; } public static boolean isSameBanner(ItemStack bannerA, ItemStack bannerB) { if(isAnyBanner(bannerA) && isAnyBanner(bannerB)) { boolean baseequal = ItemBanner.getBaseColor(bannerA) == ItemBanner.getBaseColor(bannerB); NBTTagList patternsA = null; NBTTagList patternsB = null; if(bannerA.hasTagCompound() && bannerA.getTagCompound().hasKey("BlockEntityTag", 10)) { NBTTagCompound compound = bannerA.getTagCompound().getCompoundTag("BlockEntityTag"); if (compound.hasKey("Patterns")) { patternsA = compound.getTagList("Patterns", 10); } } if(bannerB.hasTagCompound() && bannerB.getTagCompound().hasKey("BlockEntityTag", 10)) { NBTTagCompound compound = bannerB.getTagCompound().getCompoundTag("BlockEntityTag"); if (compound.hasKey("Patterns")) { patternsB = compound.getTagList("Patterns", 10); } } //this is shitty. boolean bothnull = (patternsA == null || patternsA.tagCount() == 0) && (patternsB == null || patternsB.tagCount() == 0); return baseequal && (bothnull || patternsA.equals(patternsB)); } return false; } public static boolean isSameBanner(ItemStack banner, Entity bannerHolder) { boolean match = false; if(bannerHolder instanceof EntityLivingBase) { ItemStack helmet = ((EntityLivingBase) bannerHolder).getItemStackFromSlot(EntityEquipmentSlot.HEAD); ItemStack mainhand = ((EntityLivingBase) bannerHolder).getItemStackFromSlot(EntityEquipmentSlot.MAINHAND); ItemStack offhand = ((EntityLivingBase) bannerHolder).getItemStackFromSlot(EntityEquipmentSlot.OFFHAND); if(isAnyBanner(helmet)) match |= isSameBanner(banner,helmet); if(isAnyBanner(mainhand)) match |= isSameBanner(banner,mainhand); if(isAnyBanner(offhand)) match |= isSameBanner(banner,offhand); } return match; } public static boolean isAnyBanner(ItemStack stack) { return stack.getItem() instanceof ItemBanner || stack.getItem() instanceof ItemShield; } }
40.6125
132
0.661127
f524bc756d29493b0a3808a5950a3359ac8a814c
5,529
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra GraphQL Extension * Copyright (C) 2018 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.graphql.repositories.impl; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.zimbra.common.soap.Element; import com.zimbra.cs.service.mail.AutoComplete; import com.zimbra.cs.service.mail.Search; import com.zimbra.graphql.models.RequestContext; import com.zimbra.graphql.models.inputs.GQLSearchRequestInput; import com.zimbra.graphql.utilities.GQLAuthUtilities; import com.zimbra.graphql.utilities.XMLDocumentUtilities; import com.zimbra.soap.ZimbraSoapContext; import com.zimbra.soap.type.GalSearchType; /** * Test class for {@link ZXMLSearchRepository}. */ @RunWith(PowerMockRunner.class) @PrepareForTest({GQLAuthUtilities.class, XMLDocumentUtilities.class, ZimbraSoapContext.class}) public class ZXMLSearchRepositoryTest { /** * Mock soap context for testing. */ protected ZimbraSoapContext mockZsc; /** * Mock request element for testing. */ protected Element mockRequest; /** * Mock response element for testing. */ protected Element mockResponse; /** * Mock request context for testing. */ protected RequestContext rctxt; /** * Setup for tests. * * @throws Exception If there are issues mocking */ @Before public void setUp() throws Exception { mockZsc = EasyMock.createMock(ZimbraSoapContext.class); mockRequest = EasyMock.createMock(Element.class); mockResponse = EasyMock.createMock(Element.class); rctxt = EasyMock.createMock(RequestContext.class); PowerMock.mockStaticPartial(GQLAuthUtilities.class, "getZimbraSoapContext"); PowerMock.mockStaticPartial(XMLDocumentUtilities.class, "executeDocument", "fromElement", "toElement"); } /** * Test method for {@link ZXMLSearchRepository#search}<br> * Validates that the search request is executed. * * @throws Exception If there are issues testing */ @Test public void testSearch() throws Exception { final ZXMLSearchRepository repository = PowerMock .createPartialMockForAllMethodsExcept(ZXMLSearchRepository.class, "search"); // expect to create a zimbra soap context GQLAuthUtilities.getZimbraSoapContext(rctxt); PowerMock.expectLastCall().andReturn(mockZsc); // expect to unmarshall a request XMLDocumentUtilities.toElement(anyObject()); PowerMock.expectLastCall().andReturn(mockRequest); // expect to execute an element on the Search document handler expect(XMLDocumentUtilities .executeDocument(anyObject(Search.class), eq(mockZsc), eq(mockRequest), eq(rctxt))) .andReturn(mockResponse); // expect to marshall a response XMLDocumentUtilities.fromElement(eq(mockResponse), anyObject()); PowerMock.expectLastCall().andReturn(null); PowerMock.replay(GQLAuthUtilities.class); PowerMock.replay(XMLDocumentUtilities.class); repository.search(rctxt, new GQLSearchRequestInput()); PowerMock.verify(GQLAuthUtilities.class); PowerMock.verify(XMLDocumentUtilities.class); } /** * Test method for {@link ZXMLSearchRepository#autoComplete}<br> * Validates that the auto-complete request is executed. * * @throws Exception If there are issues testing */ @Test public void testAutoComplete() throws Exception { final ZXMLSearchRepository repository = PowerMock .createPartialMockForAllMethodsExcept(ZXMLSearchRepository.class, "autoComplete"); // expect to create a zimbra soap context GQLAuthUtilities.getZimbraSoapContext(rctxt); PowerMock.expectLastCall().andReturn(mockZsc); // expect to unmarshall a request XMLDocumentUtilities.toElement(anyObject()); PowerMock.expectLastCall().andReturn(mockRequest); // expect to execute an element on the AutoComplete document handler expect(XMLDocumentUtilities .executeDocument(anyObject(AutoComplete.class), eq(mockZsc), eq(mockRequest), eq(rctxt))) .andReturn(null); PowerMock.replay(GQLAuthUtilities.class); PowerMock.replay(XMLDocumentUtilities.class); repository.autoComplete(rctxt, "test-name", GalSearchType.all, false, "", false); PowerMock.verify(GQLAuthUtilities.class); PowerMock.verify(XMLDocumentUtilities.class); } }
36.615894
111
0.716043
3cf748eee6b29cf612118015ca4fcbb9e462b96c
116
package cardibuddy.model.flashcard; /** * Type of card. */ public enum CardType { FLASHCARD, IMAGECARD }
11.6
35
0.663793
9c2f5e4e516c3d809929b9b48d4259d3c27d7bac
607
package javaapp; public class ExceptionDemo { public static boolean isValidUser(String user) throws InvalidUser { if(!user.contentEquals("admin")) { throw new InvalidUser(); } else return true; } public static void main(String[] args) { // TODO Auto-generated method stub try { isValidUser("admine"); } catch(InvalidUser e) { System.out.println(e.invalid()); } } } class InvalidUser extends Exception { public InvalidUser() { } InvalidUser(String message) { System.out.println(message); } public String invalid() { return "This user is Invalid"; } }
14.116279
66
0.672158
7c3378de16e05224ff49bd25d7648c14ac6be680
2,086
package de.seine_eloquenz.lbcfs.utils; import java.util.StringJoiner; /** * Class containing utils for Strings */ public final class StringUtils { /** * Concatenates the string array to a message using blanks as delimiters * @param args args to concat * @return concatenated string */ public static String createMessageFromArgs(final String[] args) { return createMessageFromArgs(args, 0, args.length - 1); } /** * Concatenates the string array to a message using blanks as delimiters * @param args args to concat * @param beginIndex first index to include in concatenation * @return concatenated string */ public static String createMessageFromArgs(final String[] args, final int beginIndex) { return createMessageFromArgs(args, beginIndex, args.length - 1); } /** * Concatenates the string array to a message using blanks as delimiters * @param args args to concat * @param beginIndex first index to include in concatenation * @param endIndex last index to include in concatenation * @return concatenated string */ public static String createMessageFromArgs(final String[] args, final int beginIndex, final int endIndex) { if (beginIndex < 0) { throw new IllegalArgumentException("Begin index may not be smaller than 0"); } else if (beginIndex >= args.length) { throw new IllegalArgumentException("Begin index may not be larger than the last element of the array"); } else if (beginIndex > endIndex) { throw new IllegalArgumentException("Begin index must be smaller than the end index"); } else if (endIndex >= args.length) { throw new IllegalArgumentException("End index must not be larger than the last element of the array"); } final StringJoiner joiner = new StringJoiner(" "); for (int i = beginIndex; i <= endIndex; i++) { joiner.add(args[i]); } return joiner.toString(); } private StringUtils() { } }
36.596491
115
0.663471
9def8f1d194530dbb0bb1bc27d1b3efe73a194ce
1,238
/* * Meltwater Streaming API v2 * The Meltwater Streaming API provides the needed resources for Meltwater clients to create & delete REST Hooks and stream Meltwater search results to your specified destination. * * OpenAPI spec version: 2.0.0 * Contact: support@api.meltwater.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.api; import io.swagger.client.ApiException; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for SwaggerDocApi */ @Ignore public class SwaggerDocApiTest { private final SwaggerDocApi api = new SwaggerDocApi(); /** * Meltwater API Swagger Spec * * Get the complete Swagger Spec that describes all Meltwater API endpoints. * * @throws ApiException * if the Api call fails */ @Test public void getCompleteSwaggerSpecTest() throws ApiException { String userKey = null; api.getCompleteSwaggerSpec(userKey); // TODO: test validations } }
24.27451
179
0.703554
553ec671fd0787080f13b1489e151b1d4418d656
8,310
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.pulsar.jms; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import com.datastax.oss.pulsar.jms.utils.PulsarCluster; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.jms.Connection; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.Topic; import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.client.api.SubscriptionType; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @Slf4j public class SelectorsTest { @TempDir public static Path tempDir; private static PulsarCluster cluster; @BeforeAll public static void before() throws Exception { cluster = new PulsarCluster(tempDir); cluster.start(); } @AfterAll public static void after() throws Exception { if (cluster != null) { cluster.close(); } } @Test public void sendMessageReceiveFromQueueWithSelector() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("webServiceUrl", cluster.getAddress()); properties.put("jms.enableClientSideEmulation", "true"); try (PulsarConnectionFactory factory = new PulsarConnectionFactory(properties); ) { try (Connection connection = factory.createConnection()) { connection.start(); try (Session session = connection.createSession(); ) { Queue destination = session.createQueue("persistent://public/default/test-" + UUID.randomUUID()); try (MessageConsumer consumer1 = session.createConsumer(destination, "lastMessage=TRUE"); ) { assertEquals( SubscriptionType.Shared, ((PulsarMessageConsumer) consumer1).getSubscriptionType()); assertEquals("lastMessage=TRUE", consumer1.getMessageSelector()); try (MessageProducer producer = session.createProducer(destination); ) { for (int i = 0; i < 10; i++) { TextMessage textMessage = session.createTextMessage("foo-" + i); if (i == 9) { textMessage.setBooleanProperty("lastMessage", true); } producer.send(textMessage); } } TextMessage textMessage = (TextMessage) consumer1.receive(); assertEquals("foo-9", textMessage.getText()); // no more messages assertNull(consumer1.receiveNoWait()); } } } } } @Test public void sendMessageReceiveFromTopicWithSelector() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("webServiceUrl", cluster.getAddress()); properties.put("jms.enableClientSideEmulation", "false"); try (PulsarConnectionFactory factory = new PulsarConnectionFactory(properties); ) { try (Connection connection = factory.createConnection()) { connection.start(); try (Session session = connection.createSession(); ) { Topic destination = session.createTopic("persistent://public/default/test-" + UUID.randomUUID()); try (MessageConsumer consumer1 = session.createConsumer(destination, "lastMessage=TRUE"); ) { assertEquals( SubscriptionType.Exclusive, ((PulsarMessageConsumer) consumer1).getSubscriptionType()); assertEquals("lastMessage=TRUE", consumer1.getMessageSelector()); try (MessageProducer producer = session.createProducer(destination); ) { for (int i = 0; i < 10; i++) { TextMessage textMessage = session.createTextMessage("foo-" + i); if (i == 9) { textMessage.setBooleanProperty("lastMessage", true); } producer.send(textMessage); } } TextMessage textMessage = (TextMessage) consumer1.receive(); assertEquals("foo-9", textMessage.getText()); // no more messages assertNull(consumer1.receiveNoWait()); } } } } } @Test public void sendMessageReceiveFromExclusiveSubscriptionWithSelector() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("webServiceUrl", cluster.getAddress()); properties.put("jms.enableClientSideEmulation", "false"); properties.put("jms.clientId", "id"); try (PulsarConnectionFactory factory = new PulsarConnectionFactory(properties); ) { try (Connection connection = factory.createConnection()) { connection.start(); try (Session session = connection.createSession(); ) { Topic destination = session.createTopic("persistent://public/default/test-" + UUID.randomUUID()); try (MessageConsumer consumer1 = session.createDurableConsumer(destination, "sub1", "lastMessage=TRUE", false); ) { assertEquals( SubscriptionType.Exclusive, ((PulsarMessageConsumer) consumer1).getSubscriptionType()); assertEquals("lastMessage=TRUE", consumer1.getMessageSelector()); try (MessageProducer producer = session.createProducer(destination); ) { for (int i = 0; i < 10; i++) { TextMessage textMessage = session.createTextMessage("foo-" + i); if (i == 9) { textMessage.setBooleanProperty("lastMessage", true); } producer.send(textMessage); } } TextMessage textMessage = (TextMessage) consumer1.receive(); assertEquals("foo-9", textMessage.getText()); // no more messages assertNull(consumer1.receiveNoWait()); } } } } } @Test public void sendMessageReceiveFromSharedSubscriptionWithSelector() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("webServiceUrl", cluster.getAddress()); properties.put("jms.enableClientSideEmulation", "true"); try (PulsarConnectionFactory factory = new PulsarConnectionFactory(properties); ) { try (Connection connection = factory.createConnection()) { connection.start(); try (Session session = connection.createSession(); ) { Topic destination = session.createTopic("persistent://public/default/test-" + UUID.randomUUID()); try (MessageConsumer consumer1 = session.createSharedDurableConsumer(destination, "sub1", "lastMessage=TRUE"); ) { assertEquals( SubscriptionType.Shared, ((PulsarMessageConsumer) consumer1).getSubscriptionType()); assertEquals("lastMessage=TRUE", consumer1.getMessageSelector()); try (MessageProducer producer = session.createProducer(destination); ) { for (int i = 0; i < 10; i++) { TextMessage textMessage = session.createTextMessage("foo-" + i); if (i == 9) { textMessage.setBooleanProperty("lastMessage", true); } producer.send(textMessage); } } TextMessage textMessage = (TextMessage) consumer1.receive(); assertEquals("foo-9", textMessage.getText()); // no more messages assertNull(consumer1.receiveNoWait()); } } } } } }
37.432432
100
0.634296
905c5a7fd03b2fe29c4446fbd896d2a6d49b5aa7
1,924
package com.github.chrisblutz.trinity.lang.types.nativeutils; import com.github.chrisblutz.trinity.lang.types.bool.TYBoolean; import com.github.chrisblutz.trinity.natives.TrinityNatives; /** * @author Christopher Lutz */ class NativeFloat { protected static void register() { TrinityNatives.registerField(TrinityNatives.Classes.FLOAT, "NaN", (runtime, thisObj, params) -> TrinityNatives.wrapNumber(Double.NaN)); TrinityNatives.registerField(TrinityNatives.Classes.FLOAT, "POSITIVE_INFINITY", (runtime, thisObj, params) -> TrinityNatives.wrapNumber(Double.POSITIVE_INFINITY)); TrinityNatives.registerField(TrinityNatives.Classes.FLOAT, "NEGATIVE_INFINITY", (runtime, thisObj, params) -> TrinityNatives.wrapNumber(Double.NEGATIVE_INFINITY)); TrinityNatives.registerField(TrinityNatives.Classes.FLOAT, "MIN_VALUE", (runtime, thisObj, params) -> TrinityNatives.wrapNumber(Double.MIN_VALUE)); TrinityNatives.registerField(TrinityNatives.Classes.FLOAT, "MAX_VALUE", (runtime, thisObj, params) -> TrinityNatives.wrapNumber(Double.MAX_VALUE)); TrinityNatives.registerMethod(TrinityNatives.Classes.FLOAT, "isNaN", (runtime, thisObj, params) -> { double thisDouble = TrinityNatives.toFloat(thisObj); return TYBoolean.valueFor(Double.isNaN(thisDouble)); }); TrinityNatives.registerMethod(TrinityNatives.Classes.FLOAT, "isFinite", (runtime, thisObj, params) -> { double thisDouble = TrinityNatives.toFloat(thisObj); return TYBoolean.valueFor(Double.isFinite(thisDouble)); }); TrinityNatives.registerMethod(TrinityNatives.Classes.FLOAT, "isInfinite", (runtime, thisObj, params) -> { double thisDouble = TrinityNatives.toFloat(thisObj); return TYBoolean.valueFor(Double.isInfinite(thisDouble)); }); } }
52
171
0.709979
0bbe4296fd7daacd6472b927902dad69e11066f3
8,776
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.analyze; import io.crate.analyze.expressions.ExpressionAnalysisContext; import io.crate.analyze.expressions.ExpressionAnalyzer; import io.crate.analyze.relations.DocTableRelation; import io.crate.analyze.relations.NameFieldProvider; import io.crate.analyze.symbol.Symbol; import io.crate.analyze.symbol.SymbolFormatter; import io.crate.analyze.symbol.ValueSymbolVisitor; import io.crate.exceptions.PartitionUnknownException; import io.crate.exceptions.UnsupportedFeatureException; import io.crate.metadata.PartitionName; import io.crate.metadata.TableIdent; import io.crate.metadata.doc.DocTableInfo; import io.crate.metadata.table.TableInfo; import io.crate.sql.tree.*; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Singleton; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; @Singleton public class CopyStatementAnalyzer extends DefaultTraversalVisitor<CopyAnalyzedStatement, Analysis> { private final AnalysisMetaData analysisMetaData; @Inject public CopyStatementAnalyzer(AnalysisMetaData analysisMetaData) { this.analysisMetaData = analysisMetaData; } public AnalyzedStatement analyze(Node node, Analysis analysis) { analysis.expectsAffectedRows(true); return super.process(node, analysis); } @Override public CopyAnalyzedStatement visitCopyFromStatement(CopyFromStatement node, Analysis analysis) { CopyAnalyzedStatement statement = new CopyAnalyzedStatement(); DocTableInfo tableInfo = analysisMetaData.referenceInfos().getWritableTable( TableIdent.of(node.table(), analysis.parameterContext().defaultSchema())); statement.table(tableInfo); DocTableRelation tableRelation = new DocTableRelation(tableInfo); ExpressionAnalyzer expressionAnalyzer = new ExpressionAnalyzer( analysisMetaData, analysis.parameterContext(), new NameFieldProvider(tableRelation), tableRelation); expressionAnalyzer.resolveWritableFields(true); ExpressionAnalysisContext expressionAnalysisContext = new ExpressionAnalysisContext(); Symbol pathSymbol = expressionAnalyzer.convert(node.path(), expressionAnalysisContext); statement.uri(pathSymbol); if (tableInfo.schemaInfo().systemSchema() || (tableInfo.isAlias() && !tableInfo.isPartitioned())) { throw new UnsupportedOperationException( String.format("Cannot COPY FROM %s INTO '%s', table is read-only", SymbolFormatter.format(pathSymbol), tableInfo)); } if (node.genericProperties().isPresent()) { statement.settings(settingsFromProperties( node.genericProperties().get(), expressionAnalyzer, expressionAnalysisContext)); } statement.mode(CopyAnalyzedStatement.Mode.FROM); if (!node.table().partitionProperties().isEmpty()) { statement.partitionIdent(PartitionPropertiesAnalyzer.toPartitionIdent( tableInfo, node.table().partitionProperties(), analysis.parameterContext().parameters())); } return statement; } @Override public CopyAnalyzedStatement visitCopyTo(CopyTo node, Analysis analysis) { CopyAnalyzedStatement statement = new CopyAnalyzedStatement(); statement.mode(CopyAnalyzedStatement.Mode.TO); TableInfo tableInfo = analysisMetaData.referenceInfos().getTableInfo( TableIdent.of(node.table(), analysis.parameterContext().defaultSchema())); if (!(tableInfo instanceof DocTableInfo)) { throw new UnsupportedOperationException(String.format( "Cannot COPY %s TO. COPY TO only supports user tables", tableInfo.ident())); } statement.table((DocTableInfo) tableInfo); DocTableRelation tableRelation = new DocTableRelation(statement.table()); ExpressionAnalyzer expressionAnalyzer = new ExpressionAnalyzer( analysisMetaData, analysis.parameterContext(), new NameFieldProvider(tableRelation), tableRelation); ExpressionAnalysisContext expressionAnalysisContext = new ExpressionAnalysisContext(); if (node.genericProperties().isPresent()) { statement.settings(settingsFromProperties( node.genericProperties().get(), expressionAnalyzer, expressionAnalysisContext)); } if (!node.table().partitionProperties().isEmpty()) { String partitionIdent = PartitionPropertiesAnalyzer.toPartitionIdent( statement.table(), node.table().partitionProperties(), analysis.parameterContext().parameters()); if (!partitionExists(statement.table(), partitionIdent)) { throw new PartitionUnknownException(tableInfo.ident().fqn(), partitionIdent); } statement.partitionIdent(partitionIdent); } Symbol uri = expressionAnalyzer.normalize(expressionAnalyzer.convert(node.targetUri(), expressionAnalysisContext)); statement.uri(uri); statement.directoryUri(node.directoryUri()); List<Symbol> columns = new ArrayList<>(node.columns().size()); for (Expression expression : node.columns()) { columns.add(expressionAnalyzer.normalize(expressionAnalyzer.convert(expression, expressionAnalysisContext))); } statement.selectedColumns(columns); return statement; } private boolean partitionExists(DocTableInfo table, @Nullable String partitionIdent) { if (table.isPartitioned() && partitionIdent != null) { for (PartitionName partitionName : table.partitions()) { if (partitionName.tableIdent().equals(table.ident()) && partitionName.ident().equals(partitionIdent)) { return true; } } } return false; } private Settings settingsFromProperties(GenericProperties properties, ExpressionAnalyzer expressionAnalyzer, ExpressionAnalysisContext expressionAnalysisContext) { ImmutableSettings.Builder builder = ImmutableSettings.builder(); for (Map.Entry<String, Expression> entry : properties.properties().entrySet()) { String key = entry.getKey(); Expression expression = entry.getValue(); if (expression instanceof ArrayLiteral) { throw new IllegalArgumentException("Invalid argument(s) passed to parameter"); } if (expression instanceof QualifiedNameReference) { throw new IllegalArgumentException(String.format( "Can't use column reference in property assignment \"%s = %s\". Use literals instead.", key, ((QualifiedNameReference) expression).getName().toString())); } Symbol v = expressionAnalyzer.convert(expression, expressionAnalysisContext); if (!v.symbolType().isValueSymbol()) { throw new UnsupportedFeatureException("Only literals are allowed as parameter values"); } builder.put(key, ValueSymbolVisitor.STRING.process(v)); } return builder.build(); } }
45.237113
135
0.677302
2aac3703d07872819634b0133dfa2d9b49ebca5e
688
import java.util.Scanner; public class ReverseCString { public static void main(String[] args) { // Accepts a string as input and shows output of reverseCString Scanner s = new Scanner(System.in); System.out.println("Enter a string."); String str = s.next(); System.out.println("The string " + str + " reversed is " + reverseCString(str) + "."); s.close(); } static String reverseCString(String str) { // Reverses a C-style string StringBuilder strB = new StringBuilder(str); for (int i = 0, j = str.length() - 1; i < j; i++, j--) { char temp = strB.charAt(i); strB.setCharAt(i, strB.charAt(j)); strB.setCharAt(j, temp); } return strB.toString(); } }
28.666667
88
0.655523
7b76a5b2f9144f089dcd569f50517842d5cf710e
3,533
/* * Copyright (C) 2008 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.tools.layoutlib.create; import static org.junit.Assert.assertArrayEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Set; /** * Unit tests for some methods of {@link AsmGenerator}. */ public class AsmGeneratorTest { private MockLog mLog; private ArrayList<String> mOsJarPath; private String mOsDestJar; private File mTempFile; @Before public void setUp() throws Exception { mLog = new MockLog(); URL url = this.getClass().getClassLoader().getResource("data/mock_android.jar"); mOsJarPath = new ArrayList<String>(); mOsJarPath.add(url.getFile()); mTempFile = File.createTempFile("mock", "jar"); mOsDestJar = mTempFile.getAbsolutePath(); mTempFile.deleteOnExit(); } @After public void tearDown() throws Exception { if (mTempFile != null) { mTempFile.delete(); mTempFile = null; } } @Test public void testClassRenaming() throws IOException, LogAbortException { ICreateInfo ci = new ICreateInfo() { @Override public Class<?>[] getInjectedClasses() { // classes to inject in the final JAR return new Class<?>[0]; } @Override public String[] getDelegateMethods() { return new String[0]; } @Override public String[] getDelegateClassNatives() { return new String[0]; } @Override public String[] getOverriddenMethods() { // methods to force override return new String[0]; } @Override public String[] getRenamedClasses() { // classes to rename (so that we can replace them) return new String[] { "mock_android.view.View", "mock_android.view._Original_View", "not.an.actual.ClassName", "anoter.fake.NewClassName", }; } @Override public String[] getDeleteReturns() { // methods deleted from their return type. return new String[0]; } }; AsmGenerator agen = new AsmGenerator(mLog, mOsDestJar, ci); AsmAnalyzer aa = new AsmAnalyzer(mLog, mOsJarPath, agen, null, // derived from new String[] { // include classes "**" }); aa.analyze(); agen.generate(); Set<String> notRenamed = agen.getClassesNotRenamed(); assertArrayEquals(new String[] { "not/an/actual/ClassName" }, notRenamed.toArray()); } }
29.441667
92
0.585621
c37e5c15963037940a822bc03225a4d67d041c76
1,204
/* * Queryman. Java tools for working with queries of PostgreSQL database. * * License: MIT License * To see license follow by http://queryman.org/license.txt */ package org.queryman.builder.command.update; import org.queryman.builder.Query; import org.queryman.builder.token.Expression; /** * UPDATE .. SET .. step. * * @author Timur Shaidullin */ public interface UpdateSetStep { /** * Set a column name and an expression that is be assigned to the column. * * @param column column name * @param value expression value * @return itself */ <T> UpdateSetManyStep set(String column, T value); /** * Set a columns names and an expression list that are be assigned to the columns. * * @param listColumns columns names * @param listValues expressions list * @return itself */ UpdateSetManyStep set(Expression listColumns, Expression listValues); /** * Set a columns names and a sub-select that is be assigned to the columns. * * @param listColumns columns names * @param subSelect sub-select * @return itself */ UpdateSetManyStep set(Expression listColumns, Query subSelect); }
26.755556
86
0.673588
e75525723f7ca88125cff2b8fcabef0c6eec55fb
10,324
package org.support.project.knowledge.control.admin; import java.util.ArrayList; import java.util.List; import org.support.project.common.bean.ValidateError; import org.support.project.common.util.StringUtils; import org.support.project.di.DI; import org.support.project.di.Instance; import org.support.project.knowledge.config.AnalyticsConfig; import org.support.project.knowledge.config.AppConfig; import org.support.project.knowledge.config.SystemConfig; import org.support.project.knowledge.control.Control; import org.support.project.knowledge.logic.SystemConfigLogic; import org.support.project.web.annotation.Auth; import org.support.project.web.boundary.Boundary; import org.support.project.web.common.HttpUtil; import org.support.project.web.control.service.Get; import org.support.project.web.control.service.Post; import org.support.project.web.dao.LdapConfigsDao; import org.support.project.web.dao.MailConfigsDao; import org.support.project.web.dao.SystemAttributesDao; import org.support.project.web.dao.SystemConfigsDao; import org.support.project.web.dao.SystemsDao; import org.support.project.web.entity.LdapConfigsEntity; import org.support.project.web.entity.MailConfigsEntity; import org.support.project.web.entity.SystemAttributesEntity; import org.support.project.web.entity.SystemConfigsEntity; import org.support.project.web.entity.SystemsEntity; @DI(instance = Instance.Prototype) public class ConfigControl extends Control { /** * ユーザ登録方法設定画面を表示 * * @return */ @Get(publishToken = "admin") @Auth(roles = "admin") public Boundary config() { SystemConfigsDao dao = SystemConfigsDao.get(); SystemConfigsEntity userAddType = dao.selectOnKey(SystemConfig.USER_ADD_TYPE, AppConfig.get().getSystemName()); if (userAddType == null) { userAddType = new SystemConfigsEntity(SystemConfig.USER_ADD_TYPE, AppConfig.get().getSystemName()); userAddType.setConfigValue(SystemConfig.USER_ADD_TYPE_VALUE_ADMIN); } setAttribute("userAddType", userAddType.getConfigValue()); SystemConfigsEntity userAddNotify = dao.selectOnKey(SystemConfig.USER_ADD_NOTIFY, AppConfig.get().getSystemName()); if (userAddNotify == null) { userAddNotify = new SystemConfigsEntity(SystemConfig.USER_ADD_NOTIFY, AppConfig.get().getSystemName()); userAddNotify.setConfigValue(SystemConfig.USER_ADD_NOTIFY_OFF); } setAttribute("userAddNotify", userAddNotify.getConfigValue()); LdapConfigsDao ldapConfigsDao = LdapConfigsDao.get(); LdapConfigsEntity ldapConfigsEntity = ldapConfigsDao.selectOnKey(AppConfig.get().getSystemName()); if (ldapConfigsEntity == null || ldapConfigsEntity.getAuthType() == null) { setAttribute("authType", 0); } else { setAttribute("authType", ldapConfigsEntity.getAuthType().intValue()); } return forward("config.jsp"); } /** * ユーザ登録方法設定を保存 * * @return */ @Post(subscribeToken = "admin") @Auth(roles = "admin") public Boundary save() { List<ValidateError> errors = new ArrayList<>(); String type = getParam("userAddType"); String notify = getParam("userAddNotify"); // メール送信の場合、メールの設定が完了しているかチェック if (type != null && type.equals(SystemConfig.USER_ADD_TYPE_VALUE_MAIL)) { MailConfigsDao mailConfigsDao = MailConfigsDao.get(); MailConfigsEntity mailConfigsEntity = mailConfigsDao.selectOnKey(AppConfig.get().getSystemName()); if (mailConfigsEntity == null) { ValidateError error = new ValidateError("knowledge.config.mail.require"); errors.add(error); } } if (!errors.isEmpty()) { setResult(null, errors); return forward("config.jsp"); } SystemConfigsDao dao = SystemConfigsDao.get(); SystemConfigsEntity userAddType = new SystemConfigsEntity(SystemConfig.USER_ADD_TYPE, AppConfig.get().getSystemName()); userAddType.setConfigValue(type); dao.save(userAddType); SystemConfigsEntity userAddNotify = new SystemConfigsEntity(SystemConfig.USER_ADD_NOTIFY, AppConfig.get().getSystemName()); userAddNotify.setConfigValue(notify); dao.save(userAddNotify); String successMsg = "message.success.save"; setResult(successMsg, errors); return forward("config.jsp"); } /** * システム設定画面を表示 * * @return */ @Get(publishToken = "admin") @Auth(roles = "admin") public Boundary system() { SystemConfigsDao dao = SystemConfigsDao.get(); SystemConfigsEntity config = dao.selectOnKey(SystemConfig.SYSTEM_URL, AppConfig.get().getSystemName()); if (config == null) { String url = HttpUtil.getContextUrl(getRequest()); config = new SystemConfigsEntity(SystemConfig.SYSTEM_URL, AppConfig.get().getSystemName()); config.setConfigValue(url); dao.save(config); } setAttribute("systemurl", config.getConfigValue()); config = dao.selectOnKey(SystemConfig.SYSTEM_EXPOSE_TYPE, AppConfig.get().getSystemName()); if (config != null) { setAttribute("system_open_type", config.getConfigValue()); } config = dao.selectOnKey(SystemConfig.UPLOAD_MAX_MB_SIZE, AppConfig.get().getSystemName()); if (config != null) { setAttribute("uploadMaxMBSize", config.getConfigValue()); } else { setAttribute("uploadMaxMBSize", "10"); // default } config = dao.selectOnKey(SystemConfig.LIKE_CONFIG, AppConfig.get().getSystemName()); if (config != null) { setAttribute("like_config", config.getConfigValue()); } SystemsEntity entity = SystemsDao.get().selectOnKey(AppConfig.get().getSystemName()); if (entity != null) { setAttribute("db_version", entity.getVersion()); } return forward("system.jsp"); } /** * システム設定を保存 * @return */ @Post(subscribeToken = "admin", checkReferer=false, checkReqToken = true) @Auth(roles = "admin") public Boundary save_params() { List<ValidateError> errors = new ArrayList<>(); String systemurl = getParam("systemurl"); // メール送信の場合、メールの設定が完了しているかチェック if (StringUtils.isEmpty(systemurl)) { ValidateError error = new ValidateError("errors.required", getResource("knowledge.config.system.label.url")); errors.add(error); } String uploadMaxMBSize = getParam("uploadMaxMBSize"); if (StringUtils.isEmpty(uploadMaxMBSize) || !StringUtils.isInteger(uploadMaxMBSize)) { ValidateError error = new ValidateError("errors.required", getResource("knowledge.config.system.label.limit.attach")); errors.add(error); } int size = Integer.parseInt(uploadMaxMBSize); if (size < 1 || size > 300) { ValidateError error = new ValidateError("errors.range", getResource("knowledge.config.system.label.limit.attach"), "1", "300"); errors.add(error); } if (!errors.isEmpty()) { setResult(null, errors); return forward("system.jsp"); } SystemConfigsDao dao = SystemConfigsDao.get(); SystemConfigsEntity config = new SystemConfigsEntity(SystemConfig.SYSTEM_URL, AppConfig.get().getSystemName()); config.setConfigValue(systemurl); dao.save(config); String systemOpenType = getParam("system_open_type"); if (StringUtils.isNotEmpty(systemOpenType)) { config = new SystemConfigsEntity(SystemConfig.SYSTEM_EXPOSE_TYPE, AppConfig.get().getSystemName()); config.setConfigValue(systemOpenType); dao.save(config); if (SystemConfig.SYSTEM_EXPOSE_TYPE_CLOSE.equals(systemOpenType)) { SystemConfigLogic.get().setClose(true); } else { SystemConfigLogic.get().setClose(false); } } config = new SystemConfigsEntity(SystemConfig.UPLOAD_MAX_MB_SIZE, AppConfig.get().getSystemName()); config.setConfigValue(uploadMaxMBSize); dao.save(config); String like_config = getParam("like_config"); if (StringUtils.isNotEmpty(like_config)) { config = new SystemConfigsEntity(SystemConfig.LIKE_CONFIG, AppConfig.get().getSystemName()); config.setConfigValue(like_config); dao.save(config); } String successMsg = "message.success.save"; setResult(successMsg, errors); return forward("system.jsp"); } /** * Analytics設定画面を表示 * * @return */ @Get(publishToken = "admin") @Auth(roles = "admin") public Boundary analytics() { SystemAttributesDao dao = SystemAttributesDao.get(); SystemAttributesEntity config = dao.selectOnKey(SystemConfig.ANALYTICS, AppConfig.get().getSystemName()); if (config != null) { setAttribute("analytics_script", config.getConfigValue()); // 設定を毎回DBから取得するのはパフォーマンス面で良くないので、メモリに保持する AnalyticsConfig.get().setAnalyticsScript(config.getConfigValue()); } return forward("analytics.jsp"); } /** * Analytics設定を保存 * * @return */ @Post(subscribeToken = "admin") @Auth(roles = "admin") public Boundary analytics_save() { String analyticsScript = getParam("analytics_script"); SystemAttributesDao dao = SystemAttributesDao.get(); SystemAttributesEntity config = dao.selectOnKey(SystemConfig.ANALYTICS, AppConfig.get().getSystemName()); if (config == null) { config = new SystemAttributesEntity(SystemConfig.ANALYTICS, AppConfig.get().getSystemName()); } config.setConfigValue(analyticsScript); dao.save(config); // 設定を毎回DBから取得するのはパフォーマンス面で良くないので、メモリに保持する AnalyticsConfig.get().setAnalyticsScript(analyticsScript); addMsgSuccess("message.success.save"); return analytics(); } }
39.254753
131
0.657691
6a7fd690f6b16d2678dd8de8e9ae96e8573d7392
3,555
package ru.timmson.jloan; import lombok.Getter; import java.math.BigDecimal; import java.math.MathContext; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.math.BigDecimal.ZERO; import static java.math.BigDecimal.valueOf; import static java.math.RoundingMode.HALF_UP; import static java.time.temporal.ChronoUnit.MONTHS; /** * LoanSchedule DTO * * @author Artem Krotov */ @Getter class LoanSchedule { private final BigDecimal overallInterest; private final BigDecimal firstPayment; private final BigDecimal lastPayment; private final BigDecimal minPaymentAmount; private final BigDecimal maxPaymentAmount; private final long termInMonth; private final BigDecimal amount; private final BigDecimal efficientRate; private final BigDecimal fullAmount; private final LinkedList<LoanPayment> payments; public LoanSchedule(LinkedList<LoanPayment> payments) { this.payments = payments; final var firstPayment = payments.getFirst(); final var lastPayment = payments.getLast(); this.firstPayment = payments.get(1).getAmount(); this.lastPayment = lastPayment.getAmount(); this.minPaymentAmount = payments.stream().map(LoanPayment::getAmount).min(Comparator.naturalOrder()).orElse(ZERO); this.maxPaymentAmount = payments.stream().map(LoanPayment::getAmount).max(Comparator.naturalOrder()).orElse(ZERO); this.termInMonth = MONTHS.between(firstPayment.getDate().withDayOfMonth(1), lastPayment.getDate().withDayOfMonth(1)); this.amount = firstPayment.getFinalBalance(); this.overallInterest = payments.stream().map(LoanPayment::getInterestAmount).reduce(BigDecimal::add).orElse(ZERO); this.efficientRate = this.overallInterest.divide(this.amount, MathContext.DECIMAL32).multiply(valueOf(100)).setScale(2, HALF_UP); this.fullAmount = this.overallInterest.add(this.amount); } public static LoanSchedule build(LinkedList<LoanPayment> payments) { return new LoanSchedule(payments); } public List<LoanPayment> getPayments() { return Collections.unmodifiableList(this.payments); } @Override public String toString() { StringBuilder sb = new StringBuilder(); String border = IntStream.range(0, 14).mapToObj(i -> "-").collect(Collectors.joining()); String allBorder = String.format("+%s+%s+%s+%s+%s+%s+%n", border, border, border, border, border, border); sb.append(allBorder); sb.append(String.format( "| %-12s | %-12s | %-12s | %-27s | %-12s |%n", "", "", "", "Including", "" )); sb.append(String.format( "| %-12s | %-12s | %-12s +%s+%s+ %-12s |%n", "Date", "In. Balance", "Payment", border, border, "Out. Balance" )); sb.append(String.format( "| %-12s | %-12s | %-12s | %-12s | %-12s | %-12s |%n", "", "", "", "Principal", "Interest", "" )); sb.append(allBorder); sb.append(payments.stream().map(LoanPayment::toString).collect(Collectors.joining(""))); sb.append(allBorder); sb.append(String.format( "| %-12s | %-12s | %-12s | %-12s | %-12s | %-12s |%n", "", "", fullAmount, amount, overallInterest, "" )); sb.append(allBorder); return sb.toString(); } }
37.819149
137
0.651195
e31b8812ecb41a21f51d14ed6de3633f567b3a14
2,192
// WARNING: This file is autogenerated. DO NOT EDIT! // Generated 2018-09-20 19:13:06 +0200 package jnr.constants.platform.solaris; public enum Fcntl implements jnr.constants.Constant { F_DUPFD(0L), // FAPPEND not defined // FREAD not defined // FWRITE not defined // FASYNC not defined // FFSYNC not defined // FNONBLOCK not defined // FNDELAY not defined F_GETFD(1L), F_SETFD(2L), F_GETFL(3L), F_SETFL(4L), F_GETOWN(23L), F_SETOWN(24L), F_GETLK(14L), F_SETLK(6L), F_SETLKW(7L), // F_CHKCLEAN not defined // F_PREALLOCATE not defined // F_SETSIZE not defined // F_RDADVISE not defined // F_RDAHEAD not defined // F_READBOOTSTRAP not defined // F_WRITEBOOTSTRAP not defined // F_NOCACHE not defined // F_LOG2PHYS not defined // F_GETPATH not defined // F_FULLFSYNC not defined // F_PATHPKG_CHECK not defined // F_FREEZE_FS not defined // F_THAW_FS not defined // F_GLOBAL_NOCACHE not defined // F_ADDSIGS not defined // F_MARKDEPENDENCY not defined F_RDLCK(1L), F_UNLCK(3L), F_WRLCK(2L); // F_ALLOCATECONTIG not defined // F_ALLOCATEALL not defined private final long value; private Fcntl(long value) { this.value = value; } public static final long MIN_VALUE = 0L; public static final long MAX_VALUE = 24L; static final class StringTable { public static final java.util.Map<Fcntl, String> descriptions = generateTable(); public static final java.util.Map<Fcntl, String> generateTable() { java.util.Map<Fcntl, String> map = new java.util.EnumMap<Fcntl, String>(Fcntl.class); map.put(F_DUPFD, "F_DUPFD"); map.put(F_GETFD, "F_GETFD"); map.put(F_SETFD, "F_SETFD"); map.put(F_GETFL, "F_GETFL"); map.put(F_SETFL, "F_SETFL"); map.put(F_GETOWN, "F_GETOWN"); map.put(F_SETOWN, "F_SETOWN"); map.put(F_GETLK, "F_GETLK"); map.put(F_SETLK, "F_SETLK"); map.put(F_SETLKW, "F_SETLKW"); map.put(F_RDLCK, "F_RDLCK"); map.put(F_UNLCK, "F_UNLCK"); map.put(F_WRLCK, "F_WRLCK"); return map; } } public final String toString() { return StringTable.descriptions.get(this); } public final int value() { return (int) value; } public final int intValue() { return (int) value; } public final long longValue() { return value; } public final boolean defined() { return true; } }
29.226667
89
0.731296
824ebf64fa711597915d3b5f36cd63a78eff9a42
274
package de.chris.apps.cars.vehicle; public class VehicleNotExisting extends RuntimeException { private static final long serialVersionUID = 8460613660424609112L; VehicleNotExisting(String vin) { super("Vehicle with vin: " + vin + " not existing"); } }
27.4
70
0.726277
76dca1bdd10d459b44ba9e19e4c9dc13c0972f35
7,290
/* * 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 com.bald.uriah.baldphone.activities.alarms; import android.content.Context; import android.content.Intent; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import com.bald.uriah.baldphone.R; import com.bald.uriah.baldphone.activities.TimedBaldActivity; import com.bald.uriah.baldphone.databases.alarms.Alarm; import com.bald.uriah.baldphone.databases.alarms.AlarmScheduler; import com.bald.uriah.baldphone.databases.alarms.AlarmsDatabase; import com.bald.uriah.baldphone.utils.Animations; import com.bald.uriah.baldphone.utils.BPrefs; import com.bald.uriah.baldphone.utils.BaldToast; import com.bald.uriah.baldphone.utils.D; import com.bald.uriah.baldphone.utils.S; /** * Alarm screen, will be called from {@link com.bald.uriah.baldphone.broadcast_receivers.AlarmReceiver} */ public class AlarmScreenActivity extends TimedBaldActivity { private static final String TAG = AlarmScreenActivity.class.getSimpleName(); private static final int TIME_DELAYED_SCHEDULE = 100; private static final AudioAttributes alarmAttributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_ALARM) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build(); private TextView tv_name, snooze; private ImageView cancel; private Ringtone ringtone; private Alarm alarm; public static Ringtone getRingtone(Context context) { Uri alert = RingtoneManager .getActualDefaultRingtoneUri(context.getApplicationContext(), RingtoneManager.TYPE_ALARM); if (alert == null) alert = RingtoneManager .getActualDefaultRingtoneUri(context.getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION); if (alert == null) alert = RingtoneManager .getActualDefaultRingtoneUri(context.getApplicationContext(), RingtoneManager.TYPE_RINGTONE); final Ringtone ringtone = RingtoneManager.getRingtone(context, alert); final AudioManager audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE); if (audioManager != null) {//who knows lol - btw don't delete user's may lower the alarm sounds by mistake final int alarmVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM) * (BPrefs.get(context).getInt(BPrefs.ALARM_VOLUME_KEY, BPrefs.ALARM_VOLUME_DEFAULT_VALUE) + 6) / 10; audioManager.setStreamVolume(AudioManager.STREAM_ALARM, alarmVolume, 0); } ringtone.setAudioAttributes(alarmAttributes); return ringtone; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); S.logImportant("alarmScreen was called!"); setContentView(R.layout.alarm_screen); attachXml(); final Intent intent = getIntent(); if (intent == null) throw new AssertionError(); int key = intent.getIntExtra(Alarm.ALARM_KEY_VIA_INTENTS, -1); if (key == -1) throw new AssertionError(); alarm = AlarmsDatabase.getInstance(this).alarmsDatabaseDao().getByKey(key); if (alarm == null) { S.logImportant("alarm == null!, returning"); return; } final String name = alarm.getName(); if (name == null) tv_name.setVisibility(View.GONE); else tv_name.setText(name); cancel.setOnClickListener(v -> { if (vibrator != null) vibrator.vibrate(D.vibetime); if (alarm.getName().equals(getString(R.string.timer))) AlarmsDatabase.getInstance(this).alarmsDatabaseDao().delete(alarm); finish(); }); cancel.setOnLongClickListener(v -> { if (vibrator != null) vibrator.vibrate(D.vibetime); if (alarm.getName().equals(getString(R.string.timer))) AlarmsDatabase.getInstance(this).alarmsDatabaseDao().delete(alarm); finish(); return true; }); snooze.setOnClickListener((v) -> snooze()); snooze.setOnLongClickListener((v) -> { snooze(); return true; }); ringtone = getRingtone(this); try { ringtone.play(); } catch (Exception e) { BaldToast.error(this); Log.e(TAG, e.getMessage()); e.printStackTrace(); } Animations.makeBiggerAndSmaller(this, cancel, () -> { if (vibrator != null) vibrator.vibrate(D.vibetime); }); scheduleNextAlarm(); } @Override protected void onStart() { super.onStart(); if (ringtone != null) ringtone.play(); } @Override protected void onStop() { if (ringtone != null) ringtone.stop(); super.onStop(); } @Override protected void onDestroy() { if (ringtone != null) ringtone.stop(); super.onDestroy(); } private void attachXml() { tv_name = findViewById(R.id.alarm_name); cancel = findViewById(R.id.alarm_cancel); snooze = findViewById(R.id.snooze); } private void snooze() { if (vibrator != null) vibrator.vibrate(D.vibetime); AlarmScheduler.scheduleSnooze(alarm, this); finish(); } private void scheduleNextAlarm() { new Handler().postDelayed(() -> { if (alarm.isEnabled()) { if (alarm.getDays() == -1) { AlarmsDatabase.getInstance(this) .alarmsDatabaseDao().update(alarm.getKey(), false); } else { AlarmScheduler.scheduleAlarm(alarm, this); } } }, TIME_DELAYED_SCHEDULE); } @Override public void onBackPressed() { snooze(); super.onBackPressed(); } @Override protected int screenTimeout() { return D.MINUTE * 5; } @Override protected int requiredPermissions() { return PERMISSION_NONE; } }
35.217391
195
0.646228
26d7c6ca4120fbc4344f88c74276f53f655ef434
2,657
package som.interpreter.actors; import som.primitives.ObjectPrims.IsValue; import som.primitives.ObjectPrimsFactory.IsValueFactory; import som.vmobjects.SArray.STransferArray; import som.vmobjects.SObject; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.Node; public abstract class WrapReferenceNode extends Node { public abstract Object execute(Object ref, Actor target, Actor owner); @Specialization(guards = "target == owner") public Object inSameActor(final Object ref, final Actor target, final Actor owner) { return ref; } @Specialization(guards = "ref.getActor() == target") public Object farRefToTarget(final SFarReference ref, final Actor target, final Actor owner) { return ref.getValue(); } @Specialization(guards = "ref.getActor() != target") public SFarReference farRefNotToTarget(final SFarReference ref, final Actor target, final Actor owner) { return ref; } @Specialization(guards = "promise.getOwner() == target") public SPromise promiseOwnedByTarget(final SPromise promise, final Actor target, final Actor owner) { return promise; } @Specialization(guards = "promise.getOwner() != target") public SPromise promiseNotOwnedByTarget(final SPromise promise, final Actor target, final Actor owner) { return promise.getChainedPromiseFor(target); } protected static final boolean isNeitherFarRefNorPromise(final Object obj) { return !(obj instanceof SFarReference) && !(obj instanceof SPromise); } @Child protected IsValue isValue = IsValueFactory.create(null, null); protected final boolean isValue(final Object obj) { return isValue.executeEvaluated(obj); } @Specialization(guards = {"isNeitherFarRefNorPromise(obj)", "isValue(obj)"}) public Object isValueObject(final Object obj, final Actor target, final Actor owner) { return obj; } protected final boolean isTransferObj(final Object obj) { // TODO: optimize! return TransferObject.isTransferObject(obj); } @Specialization(guards = {"isNeitherFarRefNorPromise(obj)", "!isValue(obj)", "!isTransferObj(obj)"}) public Object isNotValueObject(final Object obj, final Actor target, final Actor owner) { return new SFarReference(owner, obj); } @Specialization(guards = {"isTransferObj(obj)"}) public Object isTransferObject(final SObject obj, final Actor target, final Actor owner) { return TransferObject.transfer(obj, owner, target, null); } @Specialization public Object isTransferArray(final STransferArray obj, final Actor target, final Actor owner) { return TransferObject.transfer(obj, owner, target, null); } }
34.960526
106
0.7516
f85f0a6fa78962754c09f254d6849c42963f43e2
336
package org.infinispan.api.sync; import org.infinispan.api.common.MutableCacheEntry; import org.infinispan.api.common.process.CacheEntryProcessorContext; /** * @since 14.0 **/ @FunctionalInterface public interface SyncCacheEntryProcessor<K, V, T> { T process(MutableCacheEntry<K, V> entry, CacheEntryProcessorContext context); }
25.846154
80
0.791667
33d4f614208b687ab9faaefb05afe941161be626
3,648
package tt.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.security.SecureRandom; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import tt.util.RandomUtil; public class AuthImg extends HttpServlet { /** * */ private static final long serialVersionUID = -7099312208878086233L; // private static final String CONTENT_TYPE = "text/html; charset=UTF-8"; // 设置验证码字体样式 private Font mFont = new Font("微软雅黑", Font.BOLD, 18); // Initialize global variables public void init() throws ServletException {} // Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); ServletOutputStream out = response.getOutputStream(); // 设置验证码图片大小 int width = 65; int height = 23; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); SecureRandom random = new SecureRandom(); // 设置图片背景颜色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(mFont); // 绘制干扰线 g.setColor(getRandColor(160, 200)); for (int i = 0; i < 50; i++ ) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } // String rand = RandomStringUtils.randomNumeric(4); String rand = RandomUtil.getStringRandom(4); char c; for (int i = 0; i < 4; i++ ) { c = rand.charAt(i); // 设置每个字的颜色 g.setColor(new Color(10 + random.nextInt(120), 10 + random.nextInt(120), 10 + random.nextInt(120))); // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(String.valueOf(c), 13 * i + 6, 20); } // 放入Session,解决Cookie出错的问题 HttpSession seesion = request.getSession(); seesion.setAttribute("authCode", rand); // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // encoder.encode(image); ImageIO.write(image, "JPEG", response.getOutputStream()); out.close(); } // Process the HTTP Post request public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } // Clean up resources public void destroy() {} private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色 SecureRandom random = new SecureRandom(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } public boolean validate(String authImg, HttpServletRequest request) { HttpSession session = request.getSession(); String authCode = (String)session.getAttribute("authCode"); return authCode.equals(authImg); } }
28.061538
91
0.613761
2568773df08cf27d934c7758c3bd516823bafb23
756
/** * Copyright (C) 2013-2016 The Rythm Engine project * for LICENSE and other details see: * https://github.com/rythmengine/rythmengine */ package org.rythmengine; import com.google.appengine.api.LifecycleManager; enum GaeShutdownService implements ShutdownService { INSTANCE; @Override public void setShutdown(final Runnable runnable) { try { LifecycleManager.getInstance().setShutdownHook(new LifecycleManager.ShutdownHook() { @Override public void shutdown() { if (runnable != null) { runnable.run(); } } }); } catch (Throwable t) { // Nothing to do } } }
25.2
96
0.562169
4775c26f6a4508039dfdffb18e34c8b439897b4d
14,317
/* * Copyright (c) 2010-2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.model.impl.expr; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.xml.namespace.QName; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import org.xml.sax.SAXException; import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; import com.evolveum.midpoint.repo.common.expression.ExpressionUtil; import com.evolveum.midpoint.repo.common.expression.ExpressionVariables; import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; import com.evolveum.midpoint.prism.PrimitiveType; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismPropertyValue; import com.evolveum.midpoint.prism.query.AllFilter; import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.query.NoneFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.RefFilter; import com.evolveum.midpoint.prism.query.UndefinedFilter; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.MidPointPrismContextFactory; import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.constants.ExpressionConstants; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType; @ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestFilterExpression extends AbstractInternalModelIntegrationTest { private static final String TEST_DIR = "src/test/resources/expr"; @Autowired(required = true) private ExpressionFactory expressionFactory; @Autowired(required = true) private TaskManager taskManager; @BeforeSuite public void setup() throws SchemaException, SAXException, IOException { PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX); PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY); } @Test public void test100EvaluateExpressionEmployeeTypeUndefinedFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeUndefinedFilter"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-undefined-filter.xml", null, UndefinedFilter.class, task, result); executeFilter(filter, 5, task, result); } @Test public void test110EvaluateExpressionEmployeeTypeNoneFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeNoneFilter"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-none-filter.xml", null, NoneFilter.class, task, result); executeFilter(filter, 0, task, result); } @Test public void test120EvaluateExpressionEmployeeTypeAllFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeAllFilter"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-all-filter.xml", null, AllFilter.class, task, result); executeFilter(filter, 5, task, result); } @Test public void test130EvaluateExpressionEmployeeTypeError() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeError"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); try { evaluateExpressionAssertFilter("expression-employeeType-error.xml", null, NoneFilter.class, task, result); AssertJUnit.fail("Unexpected success"); } catch (ExpressionEvaluationException e) { // this is expected assertTrue("Unexpected exception message: "+e.getMessage(), e.getMessage().contains("evaluated to no value")); } } @Test public void test140EvaluateExpressionEmployeeTypeEmptyFilter() throws Exception { final String TEST_NAME = "testEvaluateExpressionEmployeeTypeEmptyFilter"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-empty-filter.xml", null, EqualFilter.class, task, result); EqualFilter equalFilter = (EqualFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + equalFilter.getValues(), equalFilter.getValues()); executeFilter(filter, 4, task, result); } @Test public void test150EvaluateExpressionEmployeeTypeDefaultsNull() throws Exception { final String TEST_NAME = "test150EvaluateExpressionEmployeeTypeDefaultsNull"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-filter-defaults.xml", null, EqualFilter.class, task, result); EqualFilter equalFilter = (EqualFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + equalFilter.getValues(), equalFilter.getValues()); executeFilter(filter, 4, task, result); } @Test public void test152EvaluateExpressionEmployeeTypeDefaultsCaptain() throws Exception { final String TEST_NAME = "test152EvaluateExpressionEmployeeTypeDefaultsCaptain"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-employeeType-filter-defaults.xml", "CAPTAIN", EqualFilter.class, task, result); EqualFilter equalFilter = (EqualFilter) filter; PrismAsserts.assertValues("Wrong values in filter", equalFilter.getValues(), "CAPTAIN"); executeFilter(filter, 1, task, result); } @Test public void test200EvaluateExpressionLinkRefDefaultsNull() throws Exception { final String TEST_NAME = "test200EvaluateExpressionLinkRefDefaultsNull"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-filter-defaults.xml", null, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + refFilter.getValues(), refFilter.getValues()); executeFilter(filter, 2, task, result); } @Test public void test202EvaluateExpressionLinkRefObjectReferenceTypeDefaultsNull() throws Exception { final String TEST_NAME = "test202EvaluateExpressionLinkRefObjectReferenceTypeDefaultsNull"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-object-reference-type-filter-defaults.xml", null, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; AssertJUnit.assertNull("Expected NO values in filter, but found " + refFilter.getValues(), refFilter.getValues()); executeFilter(filter, 2, task, result); } @Test public void test210EvaluateExpressionLinkRefDefaultsVal() throws Exception { final String TEST_NAME = "test210EvaluateExpressionLinkRefDefaultsVal"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-filter-defaults.xml", ACCOUNT_SHADOW_GUYBRUSH_OID, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; assertEquals("Wrong number of values in filter: " + refFilter.getValues(), 1, refFilter.getValues().size()); executeFilter(filter, 1, task, result); } @Test public void test212EvaluateExpressionLinkRefObjectReferenceTypeDefaultsVal() throws Exception { final String TEST_NAME = "test212EvaluateExpressionLinkRefObjectReferenceTypeDefaultsVal"; TestUtil.displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestFilterExpression.class.getName() + "." + TEST_NAME); Task task = taskManager.createTaskInstance(TEST_NAME); ObjectFilter filter = evaluateExpressionAssertFilter("expression-linkref-object-reference-type-filter-defaults.xml", ACCOUNT_SHADOW_GUYBRUSH_OID, RefFilter.class, task, result); RefFilter refFilter = (RefFilter) filter; assertEquals("Wrong number of values in filter: " + refFilter.getValues(), 1, refFilter.getValues().size()); executeFilter(filter, 1, task, result); } private ObjectFilter evaluateExpressionAssertFilter(String filename, String input, Class<? extends ObjectFilter> expectedType, Task task, OperationResult result) throws SchemaException, IOException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { PrismContext prismContext = PrismTestUtil.getPrismContext(); SearchFilterType filterType = PrismTestUtil.parseAtomicValue(new File(TEST_DIR, filename), SearchFilterType.COMPLEX_TYPE); ObjectFilter filter = prismContext.getQueryConverter().createObjectFilter(UserType.class, filterType); PrismPropertyValue<String> pval = null; if (input != null) { pval = prismContext.itemFactory().createPropertyValue(input); } ExpressionVariables variables = createVariables( ExpressionConstants.VAR_INPUT, pval, PrimitiveType.STRING); // WHEN ObjectFilter evaluatedFilter = ExpressionUtil.evaluateFilterExpressions(filter, variables, MiscSchemaUtil.getExpressionProfile(), expressionFactory, prismContext, "evaluating filter with null value not allowed", task, result); // THEN display("Evaluated filter", evaluatedFilter); AssertJUnit.assertTrue("Expression should be evaluated to "+expectedType+", but was "+evaluatedFilter, expectedType.isAssignableFrom(evaluatedFilter.getClass())); return evaluatedFilter; } private void executeFilter(ObjectFilter filter, int expectedNumberOfResults, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { ObjectQuery query = prismContext.queryFactory().createQuery(filter); SearchResultList<PrismObject<UserType>> objects = modelService.searchObjects(UserType.class, query, null, task, result); display("Found objects", objects); assertEquals("Wrong number of results (found: "+objects+")", expectedNumberOfResults, objects.size()); } }
45.741214
272
0.746595
fc54cfed1a4e4dabb9fcafe7e91e9613065a2c7b
2,727
/* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ package com.ib.api.dde.utils; import java.util.ArrayList; import com.ib.api.dde.socket2dde.data.TickByTickData; import com.ib.api.dde.utils.Utils; import com.ib.client.Bar; import com.ib.client.HistogramEntry; /** Class contains some utility methods related to historical data */ public class HistoricalDataUtils { /** Method creates single table row (array of strings) from Bar */ static ArrayList<String> createTableItem(Bar bar) { ArrayList<String> item = new ArrayList<String>(); item.add(Utils.toString(bar.time())); item.add(Utils.toString(bar.open())); item.add(Utils.toString(bar.high())); item.add(Utils.toString(bar.low())); item.add(Utils.toString(bar.close())); item.add(Utils.toString(bar.volume())); item.add(Utils.toString(bar.count())); item.add(Utils.toString(bar.wap())); return item; } /** Method creates single table row (array of strings) from TickByTickData */ static ArrayList<String> createTableItem(TickByTickData tick) { ArrayList<String> item = new ArrayList<String>(); item.add(Utils.longSecondsToDateTimeString(tick.time(), "yyyyMMdd HH:mm:ss")); if (tick.isAllLast()) { item.add(Utils.toString(tick.price())); item.add(Utils.toString(tick.size())); item.add(Utils.toString(tick.tickAttribLast().pastLimit())); item.add(Utils.toString(tick.tickAttribLast().unreported())); item.add(Utils.toString(tick.exchange())); item.add(Utils.toString(tick.specialConditions())); } else if (tick.isBidAsk()) { item.add(Utils.toString(tick.bidPrice())); item.add(Utils.toString(tick.bidSize())); item.add(Utils.toString(tick.askPrice())); item.add(Utils.toString(tick.askSize())); item.add(Utils.toString(tick.tickAttribBidAsk().bidPastLow())); item.add(Utils.toString(tick.tickAttribBidAsk().askPastHigh())); } else if (tick.isMidPoint()) { item.add(Utils.toString(tick.price())); } return item; } /** Method creates single table row (array of strings) from HistogramEntry */ static ArrayList<String> createTableItem(HistogramEntry histogramEntry) { ArrayList<String> item = new ArrayList<String>(); item.add(Utils.toString(histogramEntry.price)); item.add(Utils.toString(histogramEntry.size)); return item; } }
42.609375
106
0.649432
35fbe314a7fac3052640afcb218000f3316873e2
860
package com.block.xjfkchain.data; /** * Copyright (C) 2020, Relx * FilEarnListEntity * <p> * Description * * @author muwenlei * @version 1.0 * <p> * Ver 1.0, 2020/10/22, muwenlei, Create file */ public class FilEarnListEntity { /** * id : 1869 * tran_id : 1869 * uid : 2553 * type : recharge * type_txt : 充值 * symbol : FIL * amount : 6.0E-4 * fee : 0 * addr_to : f1ih7lnh75ce542kbept3tdfob2dxv3iw4hupzyvi * status : 3 * status_txt : 成功 * created_at : 2020-10-19 */ public String id; public String tran_id; public String uid; public String type; public String type_txt; public String symbol; public String amount; public String fee; public String addr_to; public String status; public String status_txt; public String created_at; }
20
58
0.613953
821ae357a50684d7d85542d15efa8ec551f00ca2
760
import java.util.*; public class TestClass { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int arr[] = new int[n+1]; for(int i =0;i<n;i++) arr[i+1]= in.nextInt(); long sum[] = new long [n+1]; for(int i=1;i<=n;i++) sum[i]=sum[i-1]+arr[i]; long dp[] = new long[n+1]; for(int i =1;i<=n;i++) { for(int j=i;j>i-m&&j>=1;j--) { long val = sum[i]-sum[j-1]+dp[j-1]-k; dp[i]= Math.max(dp[i],val); } } long max =0; for(int i =1;i<=n;i++) max=Math.max(max,dp[i]); System.out.println(max); } }
21.111111
46
0.447368
f3073f4cad793b8cfb50ee0920076245285cd335
1,507
package fi.vincit.multiusertest; import fi.vincit.multiusertest.annotation.RunWithUsers; import fi.vincit.multiusertest.configuration.TestBaseClass; import org.junit.Test; import static fi.vincit.multiusertest.rule.expectation.TestExpectations.expectException; import static fi.vincit.multiusertest.rule.expectation.TestExpectations.expectNotToFail; import static fi.vincit.multiusertest.util.UserIdentifiers.roles; import static fi.vincit.multiusertest.util.UserIdentifiers.users; @RunWithUsers(producers = {"role:ROLE_ADMIN"}, consumers = {"role:ROLE_ADMIN","user:foo"}) public class ComponentInheritanceTest extends TestBaseClass { public void pass() { } public void fail() { throw new IllegalStateException(); } @Test public void passes() throws Throwable { authorizationRule.given(this::pass) .whenCalledWithAnyOf(roles("ROLE_ADMIN")) .then(expectNotToFail()) .test(); } @Test public void passes_users_roles_syntax() throws Throwable { authorizationRule.given(this::pass) .whenCalledWithAnyOf(roles("ROLE_ADMIN"), users("foo")) .then(expectNotToFail()) .test(); } @Test public void fails() throws Throwable { authorizationRule.given(this::fail) .whenCalledWithAnyOf(roles("ROLE_ADMIN"), users("foo")) .then(expectException(IllegalStateException.class)) .test(); } }
32.76087
90
0.678832
d2700438dcf8e7d545ceaf8e223cb436c019caef
404
package com.engineeringplus.blocks; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraftforge.common.ToolType; public class BlockAluminium extends Block{ public BlockAluminium(){ super(Properties.of(Material.METAL) .strength( 4.0f, 5.0f) .harvestLevel(1) .harvestTool(ToolType.PICKAXE)); } }
23.764706
48
0.680693
d813665d8e3dd52a3ab65f4cc3cb739027dfa0aa
2,681
package com.y1ph.easy.design.security.oauth.controller; import com.y1ph.easy.design.common.enums.Locked; import com.y1ph.easy.design.security.annotation.PreAuthorize; import com.y1ph.easy.design.security.beans.AccessToken; import com.y1ph.easy.design.security.beans.Principal; import com.y1ph.easy.design.security.oauth.beans.OauthClient; import com.y1ph.easy.design.security.oauth.beans.OauthParameter; import com.y1ph.easy.design.security.oauth.context.GrantFactory; import com.y1ph.easy.design.security.oauth.enums.GrantType; import com.y1ph.easy.design.security.oauth.service.ClientService; import com.y1ph.easy.design.security.oauth.service.CodeService; import com.y1ph.easy.design.security.service.AccessTokenService; import com.y1ph.easy.design.security.utils.SecurityUtil; import lombok.RequiredArgsConstructor; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.*; import java.io.Serializable; /** * 认证控制器 * * @author WFT * @since 2022/1/5 */ @RestController @RequiredArgsConstructor @RequestMapping(value = "/grant") public class GrantController { private final GrantFactory factory; private final AccessTokenService tokenService; private final ClientService<? extends OauthClient<?>> clientService; private final CodeService codeService; /** * 退出接口 */ @PreAuthorize @DeleteMapping public void logout() { this.tokenService.remove(SecurityUtil.getContext()); } /** * 获取授权码 * * @param clientId {@link String} 客户端编号 * @return {@link String} 授权码 */ @PreAuthorize @GetMapping(value = "/{clientId}") public String getCode(@PathVariable(value = "clientId") String clientId) { // 获取客户端信息 OauthClient<? extends Serializable> client = this.clientService.select(clientId); Assert.notNull(client, "客户端编号不存在"); // 参数校验 Assert.isTrue(client.getLocked().equals(Locked.enable), "客户端被锁定,请与管理员联系"); Assert.isTrue(client.getGrantType().equals(GrantType.authorization_code), "此客户端不支持授权码模式"); // 获取当前登录用户 Principal<?> principal = SecurityUtil.get(); // 生成授权码 return this.codeService.generate(principal, client); } /** * 获取获取访问令牌接口 * * @param parameter {@link OauthParameter} 认证参数 * @return {@link AccessToken} 访问令牌 */ @PostMapping public AccessToken getToken(@RequestBody OauthParameter parameter) { // 获取当前登录用户 Principal<?> principal = this.factory.get(parameter.getGrantType()).grant(parameter); // 生成访问令牌 return this.tokenService.generate(principal, parameter.getClientId()); } }
31.916667
98
0.712421
7b93dd5d483bd1950b578ce75a26d5669b8a6d7c
2,062
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import com.sun.javacard.apduio.CadTransportException; public class OracleSimulator implements Simulator { private JavaCardHostApp hostApp = new JavaCardHostApp(); public void initaliseSimulator() throws IOException, CadTransportException { hostApp.establishConnectionToSimulator(); hostApp.powerUp(); } public void disconnectSimulator() throws IOException, CadTransportException { hostApp.closeConnection(); hostApp.powerDown(); } public boolean setupKeymasterOnSimulator() { try { ArrayList<byte[]> scriptApdus = ScriptParser.getApdusFromScript("res/JavaCardKeymaster.scr"); // if(true) return false; for (byte[] apdu : scriptApdus) { byte[] response = null; if ((response = executeApdu(apdu)) != null) { if (!Arrays.equals(response, STATUS_OK)) { System.out.println("Error response from simulator " + Utils.byteArrayToHexString(response)); return false; } } else { return false; } } return true; } catch (IOException e) { e.printStackTrace(); return false; } catch (CadTransportException e) { e.printStackTrace(); return false; } } public byte[] executeApdu(byte[] apdu) throws IOException, CadTransportException { System.out.println("Exeuting apdu " + Utils.byteArrayToHexString(apdu)); if (hostApp.decodeApduBytes(apdu)) { hostApp.exchangeTheAPDUWithSimulator(); byte[] response = hostApp.decodeStatus(); System.out.println("Decode status length:" + response.length); // for(int i = 0; i < response.length; i++) { System.out.print(Utils.byteArrayToHexString(response)); // } System.out.println(); return response; } else { System.out.println("Failed to decode APDU [" + Utils.byteArrayToHexString(apdu) + "]"); return null; } } public byte[] decodeDataOut() { return hostApp.decodeDataOut(); } }
31.242424
104
0.660524
42f6e216a686b5f7e9db2949aade50fbf69bf0e2
1,163
package io.github.bettersupport.lock.core.model; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.StandardLockInternalsDriver; import org.apache.zookeeper.CreateMode; import java.util.concurrent.TimeUnit; /** * zookeeper 获取锁驱动 * @author wang.wencheng * date 2021-7-30 * describe */ public class ZookeeperLockDriver extends StandardLockInternalsDriver { private long ttl; public ZookeeperLockDriver(long leaseTime, TimeUnit unit) { this.ttl = unit.toMillis(leaseTime); } @Override public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception { String ourPath; if ( lockNodeBytes != null ) { ourPath = client.create().withTtl(ttl).creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL).forPath(path, lockNodeBytes); } else { ourPath = client.create().withTtl(ttl).creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL).forPath(path); } return ourPath; } }
30.605263
184
0.738607
2e1cb30991cc293a04629075e8de5580064981ac
3,156
/* * Copyright (c) 2015, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * 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 aic-praise 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.sri.ai.test.util.computation.anytime.treecomputation.api; import static com.sri.ai.util.Util.arrayList; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.sri.ai.util.Util; import com.sri.ai.util.base.NullaryFunction; import com.sri.ai.util.computation.treecomputation.api.EagerTreeComputation; /** * @author braz * */ public class TreeComputationTest { static class OneTwoTreeComputation implements EagerTreeComputation<Integer> { private int depth; public OneTwoTreeComputation(int depth) { this.depth = depth; } @Override public ArrayList<? extends NullaryFunction<Integer>> getSubs() { if (depth == 0) { return arrayList( () -> 1, () -> 2, () -> 3 ); } else { return arrayList( new OneTwoTreeComputation(depth - 1), new OneTwoTreeComputation(depth - 1), new OneTwoTreeComputation(depth - 1) ); } } @Override public Integer function(List<Integer> subsValues) { return (Integer) Util.sum(subsValues); } } @Test public void test() { Assert.assertEquals(6, new OneTwoTreeComputation(0).apply().intValue()); Assert.assertEquals(18, new OneTwoTreeComputation(1).apply().intValue()); } }
33.221053
79
0.71071
8db254d7a2d40bbece88d632d6d130ff45fa1aee
1,179
package tracesListener; import java.awt.Color; import java.util.prefs.Preferences; public class ProgFilter { String name = null; Color color = null; int pid = -1; /** * @param name */ public ProgFilter(String name, Color color) { super(); this.name = name; this.color = color; pid = -1; } public ProgFilter(Preferences aNode) { super(); loadPrefs(aNode); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public boolean nameMatches(String progName) { return this.name.equals(progName); } public boolean pidMatches(int progPid) { return pid == progPid; } public void loadPrefs(Preferences aNode) { name = aNode.get("name", ""); color = new Color(ByteUtil.parseHexInteger(aNode.get("color", "0x00000000"))); pid = -1; } public void savePrefs(Preferences aNode) { aNode.put("name", name); aNode.put("color", ByteUtil.formatHexInteger(color.getRGB())); } }
16.842857
80
0.661578
42951437e69564af73f6de20359422e2f2422cd6
9,038
/* * * Copyright 2015-2018 Vladimir Bukhtoyarov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bucket4j; import io.github.bucket4j.serialization.DeserializationAdapter; import io.github.bucket4j.serialization.SerializationHandle; import io.github.bucket4j.serialization.SerializationAdapter; import java.io.IOException; import java.io.Serializable; import java.time.Duration; import java.util.Objects; /** * <h3>Anatomy of bandwidth:</h3> * The bandwidth is key building block for bucket. * The bandwidth consists from {@link #capacity} and {@link Refill refill}. Where: * <ul> * <li><b>Capacity</b> - defines the maximum count of tokens which can be hold by bucket.</li> * <li><b>Refill</b> - defines the speed in which tokens are regenerated in bucket.</li> * </ul> * * <h3>Classic and simple bandwidth definitions:</h3> * The bandwidth can be initialized in the two way: * <ul> * <li>{@link #simple(long, Duration) Simple} - most popular way, which does not require from you to fully understand the token-bucket algorithm. * Use this way when you just want to specify easy limitation <tt>N</tt> tokens per <tt>M</tt> time window. * See <a href="https://github.com/vladimir-bukhtoyarov/bucket4j/blob/1.3/doc-pages/basic-usage.md#example-1---limiting-the-rate-of-heavy-work">this example</a> of usage. * </li> * <li>{@link #classic(long, Refill)} Classic} - hard way to specify limitation, * use it when you want to utilize the whole power of token-bucket. See <a href="https://github.com/vladimir-bukhtoyarov/bucket4j/blob/1.3/doc-pages/basic-usage.md#example-3---limiting-the-rate-of-access-to-rest-api">this example</a> of usage. * </li> * </ul> * * <h3>Multiple bandwidths:</h3> * Most likely you will use only one bandwidth per bucket, * but in general it is possible to specify more than one bandwidth per bucket, * and bucket will handle all bandwidth in strongly atomic way. * Strongly atomic means that token will be consumed from all bandwidth or from nothing, * in other words any token can not be partially consumed. * <br> Example of multiple bandwidth: * <pre>{@code // Adds bandwidth that restricts to consume not often 1000 tokens per 1 minute and not often than 100 tokens per second * Bucket bucket = Bucket4j.builder(). * .addLimit(Bandwidth.create(1000, Duration.ofMinutes(1))); * .addLimit(Bandwidth.create(100, Duration.ofSeconds(1))); * .build() * }</pre> */ public class Bandwidth implements Serializable { private static final long serialVersionUID = 101L; final long capacity; final long initialTokens; final long refillPeriodNanos; final long refillTokens; final boolean refillIntervally; final long timeOfFirstRefillMillis; final boolean useAdaptiveInitialTokens; private Bandwidth(long capacity, long refillPeriodNanos, long refillTokens, long initialTokens, boolean refillIntervally, long timeOfFirstRefillMillis, boolean useAdaptiveInitialTokens) { this.capacity = capacity; this.initialTokens = initialTokens; this.refillPeriodNanos = refillPeriodNanos; this.refillTokens = refillTokens; this.refillIntervally = refillIntervally; this.timeOfFirstRefillMillis = timeOfFirstRefillMillis; this.useAdaptiveInitialTokens = useAdaptiveInitialTokens; } /** * Specifies simple limitation <tt>capacity</tt> tokens per <tt>period</tt> time window. * * @param capacity * @param period * * @return */ public static Bandwidth simple(long capacity, Duration period) { Refill refill = Refill.greedy(capacity, period); return classic(capacity, refill); } /** * Specifies limitation in <a href="https://github.com/vladimir-bukhtoyarov/bucket4j/blob/1.3/doc-pages/token-bucket-brief-overview.md#token-bucket-algorithm">classic interpretation</a> of token-bucket algorithm. * * @param capacity * @param refill * * @return */ public static Bandwidth classic(long capacity, Refill refill) { if (capacity <= 0) { throw BucketExceptions.nonPositiveCapacity(capacity); } if (refill == null) { throw BucketExceptions.nullBandwidthRefill(); } return new Bandwidth(capacity, refill.periodNanos, refill.tokens, capacity, refill.refillIntervally, refill.timeOfFirstRefillMillis, refill.useAdaptiveInitialTokens); } /** * By default new created bandwidth has amount tokens that equals its capacity. * This method allows to replace initial tokens. * * @param initialTokens * * @return the copy of this bandwidth with new value ofof initial tokens. */ public Bandwidth withInitialTokens(long initialTokens) { if (initialTokens < 0) { throw BucketExceptions.nonPositiveInitialTokens(initialTokens); } if (isIntervallyAligned() && useAdaptiveInitialTokens) { throw BucketExceptions.intervallyAlignedRefillWithAdaptiveInitialTokensIncompatipleWithManualSpecifiedInitialTokens(); } return new Bandwidth(capacity, refillPeriodNanos, refillTokens, initialTokens, refillIntervally, timeOfFirstRefillMillis, useAdaptiveInitialTokens); } public boolean isIntervallyAligned() { return timeOfFirstRefillMillis != Refill.UNSPECIFIED_TIME_OF_FIRST_REFILL; } public long getCapacity() { return capacity; } public long getInitialTokens() { return initialTokens; } public long getRefillPeriodNanos() { return refillPeriodNanos; } public long getRefillTokens() { return refillTokens; } public boolean isRefillIntervally() { return refillIntervally; } public boolean isUseAdaptiveInitialTokens() { return useAdaptiveInitialTokens; } public static long getSerialVersionUID() { return serialVersionUID; } public long getTimeOfFirstRefillMillis() { return timeOfFirstRefillMillis; } public static SerializationHandle<Bandwidth> SERIALIZATION_HANDLE = new SerializationHandle<Bandwidth>() { @Override public <S> Bandwidth deserialize(DeserializationAdapter<S> adapter, S input) throws IOException { long capacity = adapter.readLong(input); long initialTokens = adapter.readLong(input); long refillPeriodNanos = adapter.readLong(input); long refillTokens = adapter.readLong(input); boolean refillIntervally = adapter.readBoolean(input); long timeOfFirstRefillMillis = adapter.readLong(input); boolean useAdaptiveInitialTokens = adapter.readBoolean(input); return new Bandwidth(capacity, refillPeriodNanos, refillTokens, initialTokens, refillIntervally, timeOfFirstRefillMillis, useAdaptiveInitialTokens); } @Override public <O> void serialize(SerializationAdapter<O> adapter, O output, Bandwidth bandwidth) throws IOException { adapter.writeLong(output, bandwidth.capacity); adapter.writeLong(output, bandwidth.initialTokens); adapter.writeLong(output, bandwidth.refillPeriodNanos); adapter.writeLong(output, bandwidth.refillTokens); adapter.writeBoolean(output, bandwidth.refillIntervally); adapter.writeLong(output, bandwidth.timeOfFirstRefillMillis); adapter.writeBoolean(output, bandwidth.useAdaptiveInitialTokens); } @Override public int getTypeId() { return 1; } @Override public Class<Bandwidth> getSerializedType() { return Bandwidth.class; } }; @Override public String toString() { final StringBuilder sb = new StringBuilder("Bandwidth{"); sb.append("capacity=").append(capacity); sb.append(", initialTokens=").append(initialTokens); sb.append(", refillPeriodNanos=").append(refillPeriodNanos); sb.append(", refillTokens=").append(refillTokens); sb.append(", refillIntervally=").append(refillIntervally); sb.append(", timeOfFirstRefillMillis=").append(timeOfFirstRefillMillis); sb.append(", useAdaptiveInitialTokens=").append(useAdaptiveInitialTokens); sb.append('}'); return sb.toString(); } }
40.348214
247
0.691082
311444b9874a914b9fe7bfed4765dc048c835c90
1,143
package ua.com.fielden.platform.serialisation.jackson.entities; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.annotation.DescTitle; import ua.com.fielden.platform.entity.annotation.Ignore; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.entity.annotation.MapTo; import ua.com.fielden.platform.entity.annotation.Observable; import ua.com.fielden.platform.entity.annotation.Title; import ua.com.fielden.platform.entity.validation.annotation.GreaterOrEqual; import ua.com.fielden.platform.types.Money; /** * Entity class used for testing. * * @author TG Team * */ @KeyType(String.class) @DescTitle("Description") public class EntityWithMoney extends AbstractEntity<String> { @IsProperty @MapTo @Title(value = "Title", desc = "Desc") @Ignore private Money prop; @Observable @GreaterOrEqual(34) public EntityWithMoney setProp(final Money prop) { this.prop = prop; return this; } public Money getProp() { return prop; } }
27.214286
75
0.748031
9fa4f2ea0fa45da00f776039eb4fa2821b352b79
3,394
/* * Copyright 2014, The Sporting Exchange Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.exemel.disco.util; import uk.co.exemel.disco.api.UUIDGenerator; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UUIDGeneratorImpl implements UUIDGenerator { private static Pattern VALID_UUID_COMPONENT = Pattern.compile("[\\w\\d\\-]{20,50}", Pattern.CASE_INSENSITIVE); public static final String DEFAULT_HOSTNAME = "localhost"; private static final AtomicLong count = new AtomicLong(); private static final String uuidPrefix; static { String host; try { host = InetAddress.getLocalHost().getHostName(); Pattern HOST_FINDER = Pattern.compile("([\\w\\d\\-]{1,30}+).*", Pattern.CASE_INSENSITIVE); Matcher m = HOST_FINDER.matcher(host); if (m.matches()) { host = m.group(1); } else { host = DEFAULT_HOSTNAME; } } catch (UnknownHostException e) { host = DEFAULT_HOSTNAME; } uuidPrefix = host + String.format("-%1$tm%1$td%1$tH%1$tM-",new Date()); } @Override public String getNextUUID() { return randomUUID(); } @Override public String[] validateUuid(String uuid) { String[] components = uuid.split(Pattern.quote(UUIDGenerator.COMPONENT_SEPARATOR)); if (components.length != 1 && components.length != 3) { throw new IllegalArgumentException("UUid "+uuid+" has "+components.length+" component parts, expected 1 or 3"); } for (int i=0; i<components.length; i++) { if (!VALID_UUID_COMPONENT.matcher(components[i]).matches()) { throw new IllegalArgumentException("UUid component "+i+"("+components[i]+") invalid - must match pattern "+ VALID_UUID_COMPONENT.pattern()); } } if (components.length == 1) { return new String[] { null, null, uuid }; } return components; } private static String randomUUID() { long val = count.getAndIncrement()%0xFFFFFFFFFFL; // loop at 0xFFFFFFFFFFL return uuidPrefix + getPrefixZeros(val) + Long.toHexString(val); } private static String getPrefixZeros(long val) { if (val <= 0xFL) return "000000000"; if (val <= 0xFfL) return "00000000"; if (val <= 0xFFFL) return "0000000"; if (val <= 0xFFFFL) return "000000"; if (val <= 0xFFFFFL) return "00000"; if (val <= 0xFFFFFFL) return "0000"; if (val <= 0xFFFFFFFL) return "000"; if (val <= 0xFFFFFFFFL) return "00"; if (val <= 0xFFFFFFFFFL) return "0"; return ""; } }
35.354167
156
0.63406
f773d46e1c6f7fec66e63da443c76a0a8dc23244
18,421
package eu.isas.peptideshaker.scoring; import com.compomics.util.waiting.WaitingHandler; import eu.isas.peptideshaker.filtering.AssumptionFilter; import eu.isas.peptideshaker.scoring.targetdecoy.TargetDecoyMap; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Set; import javax.swing.RowFilter; /** * This class contains basic information about the hits as imported from the * various search engine result files. * * @author Marc Vaudel */ public class InputMap implements Serializable { /** * Serial version UID for post-serialization compatibility. */ static final long serialVersionUID = 1117083720476649996L; /** * Map of the hits as imported. One target/decoy map per identification * advocate (referenced by their compomics utilities index). */ private HashMap<Integer, TargetDecoyMap> inputMap = new HashMap<Integer, TargetDecoyMap>(); /** * Map of the hits per file as imported. advocate index &gt; file name &gt; * target decoy map */ private HashMap<Integer, HashMap<String, TargetDecoyMap>> inputSpecificMap = new HashMap<Integer, HashMap<String, TargetDecoyMap>>(); /** * Map of the intermediate scores. Name of the file &gt; advocate index &gt; * score index */ private HashMap<String, HashMap<Integer, HashMap<Integer, TargetDecoyMap>>> intermediateScores = new HashMap<String, HashMap<Integer, HashMap<Integer, TargetDecoyMap>>>(); /** * The filters to use to flag doubtful matches. * * @deprecated use ValidationQCPreferences instead */ private ArrayList<AssumptionFilter> doubtfulMatchesFilters = null; /** * Map of the search engine contribution. Advocate Id &gt; Spectrum file name * &gt; number of validated hits. */ private HashMap<Integer, HashMap<String, Integer>> advocateContribution; /** * Map of the search engine contribution. Advocate Id &gt; Spectrum file name * &gt; number of validated hits found by this advocate only. */ private HashMap<Integer, HashMap<String, Integer>> advocateUniqueContribution; /** * Returns true for multiple search engines investigations. * * @return true for multiple search engines investigations */ public boolean isMultipleAlgorithms() { return inputMap.size() > 1; } /** * Returns the number of algorithms in the input map. * * @return the number of algorithms in the input map */ public int getNalgorithms() { return inputMap.size(); } /** * Returns a set containing the indexes of the algorithms scored in this * input map. * * @return a set containing the indexes of the algorithms scored in this * input map */ public Set<Integer> getInputAlgorithms() { return inputMap.keySet(); } /** * Returns a sorted arraylist containing the indexes of the algorithms * scored in this input map. * * @return a set containing the indexes of the algorithms scored in this * input map */ public ArrayList<Integer> getInputAlgorithmsSorted() { Object[] keys = inputMap.keySet().toArray(); Arrays.sort(keys); ArrayList<Integer> sortedKeys = new ArrayList<Integer>(); for (Object key : keys) { sortedKeys.add((Integer) key); // @TODO: is there a quicker way of doing this..? } return sortedKeys; } /** * Returns the algorithms having an intermediate score for the given * spectrum file. * * @param fileName the name of the spectrum file of interest * * @return the algorithm having an intermediate score for this file */ public Set<Integer> getIntermediateScoreInputAlgorithms(String fileName) { return intermediateScores.get(fileName).keySet(); } /** * Returns the target decoy map attached to the given algorithm. * * @param algorithm the utilities index of the algorithm of interest * * @return the target decoy map of interest */ public TargetDecoyMap getTargetDecoyMap(int algorithm) { return inputMap.get(algorithm); } /** * Returns the target decoy map attached to the given algorithm for a * specific spectrum file. Null if not found. * * @param algorithm the utilities index of the algorithm of interest * @param fileName the name of the spectrum file of interest * * @return the target decoy map of interest */ public TargetDecoyMap getTargetDecoyMap(int algorithm, String fileName) { HashMap<String, TargetDecoyMap> algorithmInput = inputSpecificMap.get(algorithm); if (algorithmInput == null) { return null; } return algorithmInput.get(fileName); } /** * Returns the first target/decoy map of the input map in case a single * algorithm was used. * * @return the first target/decoy map of the input map */ public TargetDecoyMap getMap() { if (inputMap == null || inputMap.isEmpty()) { throw new IllegalArgumentException("No algorithm input found."); } if (isMultipleAlgorithms()) { throw new IllegalArgumentException("Multiple search engine results found."); } for (TargetDecoyMap firstMap : inputMap.values()) { return firstMap; } return null; } /** * Estimates the posterior error probability for each search engine. * * @param waitingHandler the handler displaying feedback to the user */ public void estimateProbabilities(WaitingHandler waitingHandler) { int max = getNEntries(); waitingHandler.setSecondaryProgressCounterIndeterminate(false); waitingHandler.resetSecondaryProgressCounter(); waitingHandler.setMaxSecondaryProgressCounter(max); for (TargetDecoyMap hitmap : inputMap.values()) { waitingHandler.increaseSecondaryProgressCounter(); hitmap.estimateProbabilities(waitingHandler); if (waitingHandler.isRunCanceled()) { return; } } for (HashMap<String, TargetDecoyMap> algorithmMaps : inputSpecificMap.values()) { for (TargetDecoyMap targetDecoyMap : algorithmMaps.values()) { waitingHandler.increaseSecondaryProgressCounter(); targetDecoyMap.estimateProbabilities(waitingHandler); if (waitingHandler.isRunCanceled()) { return; } } } waitingHandler.setSecondaryProgressCounterIndeterminate(true); } /** * returns the posterior error probability associated to the given e-value * for the given search-engine (indexed by its utilities index) * * @param searchEngine The search engine * @param eValue The e-value * @return the posterior error probability corresponding */ public double getProbability(int searchEngine, double eValue) { return inputMap.get(searchEngine).getProbability(eValue); } /** * Returns a list of search engines indexed by utilities index presenting a * suspicious input * * @return a list of search engines presenting a suspicious input */ public ArrayList<Integer> suspiciousInput() { ArrayList<Integer> result = new ArrayList<Integer>(); if (inputMap.size() == 1) { return result; } for (int key : inputMap.keySet()) { if (inputMap.get(key).suspiciousInput()) { result.add(key); } } return result; } /** * Constructor. */ public InputMap() { } /** * Adds an entry to the input map. * * @param searchEngine The search engine used referenced by its compomics * index * @param spectrumFileName the name of the inspected spectrum file * @param eValue The search engine e-value * @param isDecoy boolean indicating whether the hit was decoy or target * (resp. true/false) */ public synchronized void addEntry(int searchEngine, String spectrumFileName, double eValue, boolean isDecoy) { TargetDecoyMap targetDecoyMap = inputMap.get(searchEngine); if (targetDecoyMap == null) { targetDecoyMap = new TargetDecoyMap(); inputMap.put(searchEngine, targetDecoyMap); } targetDecoyMap.put(eValue, isDecoy); HashMap<String, TargetDecoyMap> algorithmMap = inputSpecificMap.get(searchEngine); if (algorithmMap == null) { algorithmMap = new HashMap<String, TargetDecoyMap>(); inputSpecificMap.put(searchEngine, algorithmMap); } targetDecoyMap = algorithmMap.get(spectrumFileName); if (targetDecoyMap == null) { targetDecoyMap = new TargetDecoyMap(); algorithmMap.put(spectrumFileName, targetDecoyMap); } targetDecoyMap.put(eValue, isDecoy); } /** * Returns the number of entries. * * @return the number of entries */ public int getNEntries() { int result = 0; for (TargetDecoyMap targetDecoyMap : inputMap.values()) { result += targetDecoyMap.getMapSize(); } return result; } /** * Resets the advocate contribution mappings for the given file. * * @param fileName the file of interest */ public void resetAdvocateContributions(String fileName) { if (advocateContribution == null) { advocateContribution = new HashMap<Integer, HashMap<String, Integer>>(); } else { for (HashMap<String, Integer> advocateMapping : advocateContribution.values()) { advocateMapping.put(fileName, 0); } } if (advocateUniqueContribution == null) { advocateUniqueContribution = new HashMap<Integer, HashMap<String, Integer>>(); } else { for (HashMap<String, Integer> advocateMapping : advocateUniqueContribution.values()) { advocateMapping.put(fileName, 0); } } } /** * Resets the advocate contribution mappings. */ public void resetAdvocateContributions() { if (advocateContribution == null) { advocateContribution = new HashMap<Integer, HashMap<String, Integer>>(); } else { advocateContribution.clear(); } if (advocateUniqueContribution == null) { advocateUniqueContribution = new HashMap<Integer, HashMap<String, Integer>>(); } else { advocateUniqueContribution.clear(); } } /** * Adds an advocate contribution. * * @param advocateId the index of the advocate * @param fileName the name of the spectrum file of interest * @param unique boolean indicating whether the advocate was the only * advocate for the considered assumption */ public synchronized void addAdvocateContribution(Integer advocateId, String fileName, boolean unique) { HashMap<String, Integer> advocateContributions = advocateContribution.get(advocateId); if (advocateContributions == null) { advocateContributions = new HashMap<String, Integer>(); advocateContribution.put(advocateId, advocateContributions); } Integer contribution = advocateContributions.get(fileName); if (contribution == null) { advocateContributions.put(fileName, 1); } else { advocateContributions.put(fileName, contribution + 1); } if (unique) { HashMap<String, Integer> advocateUniqueContributions = advocateUniqueContribution.get(advocateId); if (advocateUniqueContributions == null) { advocateUniqueContributions = new HashMap<String, Integer>(); advocateUniqueContribution.put(advocateId, advocateUniqueContributions); } Integer uniqueContribution = advocateUniqueContributions.get(fileName); if (uniqueContribution == null) { advocateUniqueContributions.put(fileName, 1); } else { advocateUniqueContributions.put(fileName, uniqueContribution + 1); } } } /** * Returns the contribution of validated hits of the given advocate for the * given file. * * @param advocateId the advocate index * @param fileName the name of the spectrum file * * @return the number of validated hits supported by this advocate */ public int getAdvocateContribution(Integer advocateId, String fileName) { HashMap<String, Integer> advocateContributions = advocateContribution.get(advocateId); if (advocateContributions != null) { Integer contribution = advocateContributions.get(fileName); if (contribution != null) { return contribution; } } return 0; } /** * Returns the contribution of validated hits of the given advocate for the * entire dataset. * * @param advocateId the advocate index * * @return the number of validated hits supported by this advocate */ public int getAdvocateContribution(Integer advocateId) { HashMap<String, Integer> advocateContributions = advocateContribution.get(advocateId); if (advocateContributions != null) { int contribution = 0; for (int tempContribution : advocateContributions.values()) { contribution += tempContribution; } return contribution; } return 0; } /** * Returns the contribution of unique validated hits of the given advocate * for the given file. * * @param advocateId the advocate index * @param fileName the name of the spectrum file * * @return the number of validated hits uniquely supported by this advocate */ public int getAdvocateUniqueContribution(Integer advocateId, String fileName) { HashMap<String, Integer> advocateContributions = advocateUniqueContribution.get(advocateId); if (advocateContributions != null) { Integer contribution = advocateContributions.get(fileName); if (contribution != null) { return contribution; } } return 0; } /** * Returns the contribution of unique validated hits of the given advocate * for the entire dataset. * * @param advocateId the advocate index * * @return the number of validated hits uniquely supported by this advocate */ public int getAdvocateUniqueContribution(Integer advocateId) { HashMap<String, Integer> advocateContributions = advocateUniqueContribution.get(advocateId); if (advocateContributions != null) { int contribution = 0; for (int tempContribution : advocateContributions.values()) { contribution += tempContribution; } return contribution; } return 0; } /** * Returns a list of all target decoy maps contained in this mapping. * * @return all target decoy maps contained in this mapping */ public ArrayList<TargetDecoyMap> getTargetDecoyMaps() { ArrayList<TargetDecoyMap> result = new ArrayList<TargetDecoyMap>(inputMap.values()); for (HashMap<String, TargetDecoyMap> advocateMapping : inputSpecificMap.values()) { result.addAll(advocateMapping.values()); } return result; } /** * Indicates whether the advocate contributions are present in this map. * * @return a boolean indicating whether the advocate contributions are * present in this map */ public boolean hasAdvocateContribution() { return advocateContribution != null; } /** * Adds an intermediate score for a given match. * * @param fileName the name of the spectrum file of interest * @param advocateIndex the index of the advocate * @param scoreIndex the index of the score * @param score the score of the match * @param decoy indicates whether the match maps to a target or a decoy * protein */ public synchronized void setIntermediateScore(String fileName, int advocateIndex, int scoreIndex, double score, boolean decoy) { HashMap<Integer, HashMap<Integer, TargetDecoyMap>> advocateMap = intermediateScores.get(fileName); if (advocateMap == null) { advocateMap = new HashMap<Integer, HashMap<Integer, TargetDecoyMap>>(); intermediateScores.put(fileName, advocateMap); } HashMap<Integer, TargetDecoyMap> scoreMap = advocateMap.get(advocateIndex); if (scoreMap == null) { scoreMap = new HashMap<Integer, TargetDecoyMap>(); advocateMap.put(advocateIndex, scoreMap); } TargetDecoyMap targetDecoyMap = scoreMap.get(scoreIndex); if (targetDecoyMap == null) { targetDecoyMap = new TargetDecoyMap(); scoreMap.put(scoreIndex, targetDecoyMap); } targetDecoyMap.put(score, decoy); } /** * Returns the target decoy map associated to a given spectrum file, * advocate and score type. Null if not found. * * @param fileName the name of the spectrum file * @param advocateIndex the index of the advocate * @param scoreIndex the index of the score * * @return the target decoy map associated to the given spectrum file, * advocate and score type */ public TargetDecoyMap getIntermediateScoreMap(String fileName, int advocateIndex, int scoreIndex) { HashMap<Integer, HashMap<Integer, TargetDecoyMap>> advocateMap = intermediateScores.get(fileName); if (advocateMap != null) { HashMap<Integer, TargetDecoyMap> scoreMap = advocateMap.get(advocateIndex); if (scoreMap != null) { TargetDecoyMap targetDecoyMap = scoreMap.get(scoreIndex); return targetDecoyMap; } } return null; } }
36.405138
175
0.642148
4cbb268ae47eca5887ed9a96aa9f4955276d689d
1,389
package by.jackraidenph.dragonsurvival.network.emotes; import by.jackraidenph.dragonsurvival.common.capability.DragonStateProvider; import by.jackraidenph.dragonsurvival.network.IMessage; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent; import java.util.function.Supplier; public class SyncEmoteStatsServer implements IMessage<SyncEmoteStatsServer> { private boolean menuOpen; public SyncEmoteStatsServer(boolean menuOpen) { this.menuOpen = menuOpen; } public SyncEmoteStatsServer() { } @Override public void encode(SyncEmoteStatsServer message, PacketBuffer buffer) { buffer.writeBoolean(message.menuOpen); } @Override public SyncEmoteStatsServer decode(PacketBuffer buffer) { boolean menuOpen = buffer.readBoolean(); return new SyncEmoteStatsServer(menuOpen); } @Override public void handle(SyncEmoteStatsServer message, Supplier<NetworkEvent.Context> supplier) { ServerPlayerEntity playerEntity = supplier.get().getSender(); if(playerEntity == null) return; DragonStateProvider.getCap(playerEntity).ifPresent(dragonStateHandler -> { dragonStateHandler.getEmotes().emoteMenuOpen = message.menuOpen; }); } }
29.553191
95
0.728582
116f2e008a6250e85910fb2b318220263446e17d
124
package com.mdj20.quickgraph.quickgraph.main; public interface DiGraph<V> extends BaseDiGraph<V,DirectedEdge<V>> { }
20.666667
69
0.758065
eb98e3a849279a7b5ae90f6ad5bb4a7ce5dedf20
934
package org.parseout.java; import org.parseout.ContentType; import org.parseout.run.Run; /** * Runs of (non punctuation symbols) * * OPERATOR * SEPARATOR * */ public class OperatorRun extends Run.ContentRun { public static ContentType CONTENT_TYPE = new ContentType("Operator", ContentType.OPERATOR); public static OperatorRun INSTANCE = new OperatorRun(); public static final String CHARS_STRING = "`~@#%^&*-_+=\\|/?"; //separator '.', ',', ':' //signifier '@', '\\' //contextual '$', '_' // private OperatorRun() { super(CONTENT_TYPE, '`', '~', '@', '#', '%', '^', '&', '*', '-', '_', '+', '=', '/', '\\', '|', '?'); } }
21.227273
95
0.407923
9e2b56464d385a1c8f71bfde94cbefd6764e0d31
1,771
package mullak99.mullak99sMod.container; import java.awt.Dimension; import java.awt.List; import java.util.ArrayList; import java.util.Iterator; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; public class MCraftingShapeless implements IRecipe { /** Is the ItemStack that you get when craft the recipe. */ private final ItemStack recipeOutput; /** Is a List of ItemStack that composes the recipe. */ public final ArrayList recipeItems; public MCraftingShapeless(ItemStack par1ItemStack, ArrayList var3) { this.recipeOutput = par1ItemStack; this.recipeItems = var3; } public ItemStack getRecipeOutput() { return this.recipeOutput; } /** * Used to check if a recipe matches current crafting inventory */ public boolean matches(InventoryCrafting par1InventoryCrafting, World par2World) { ArrayList arraylist = new ArrayList(); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 3; ++j) { ItemStack itemstack = par1InventoryCrafting.getStackInRowAndColumn(j, i); if (itemstack != null) { boolean flag = false; Iterator iterator = arraylist.iterator(); while (iterator.hasNext()) { ItemStack itemstack1 = (ItemStack)iterator.next(); if (itemstack.itemID == itemstack1.itemID && (itemstack1.getItemDamage() == 32767 || itemstack.getItemDamage() == itemstack1.getItemDamage())) { flag = true; arraylist.remove(itemstack1); break; } } if (!flag) { return false; } } } } return arraylist.isEmpty(); } /** * Returns an Item that is the result of this recipe */ public ItemStack getCraftingResult(InventoryCrafting par1InventoryCrafting) { return this.recipeOutput.copy(); } @Override public int getRecipeSize() { return this.recipeItems.size(); } }
20.593023
142
0.760023
58e6a756bc2a78bf3dde138ad1fe9ff5971bb7d7
967
package miage.skillz.models; import lombok.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor @ToString public class QuizImpl { private Long idQuiz; private String name; private String theme; private Long idNiveau; private Long seuilValidation; private Long duree; private Long idCompetence; @Builder.Default private String dateOfCreation= new SimpleDateFormat("dd-MM-yyyy").format(new Date()); @Builder.Default private Set<Long> quizQuestionsId = new HashSet<>(); public QuizImpl(String name, Long idNiveau, String theme, Long seuilValidation, long duree, Long idCompetence) { this.name = name; this.idNiveau = idNiveau; this.theme = theme; this.seuilValidation = seuilValidation; this.duree = duree; this.idCompetence = idCompetence; } }
24.794872
116
0.709411
098248b7760ec8e8061ac082b4f7e816b23e859c
2,349
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.github.eddyosos.e_sus_ab_factory.cds.esus.cds.consumoalimentar; import br.gov.saude.esus.cds.transport.generated.thrift.consumoalimentar.PerguntaQuestionarioCriancasMenoresSeisMesesThrift; /** * * @author eddyosos */ public interface IPerguntaQuestionarioCriancasMenoresSeisMeses { /** * Instance para encapsulamento do Thrifit * @return instance */ /** * Identificador da pergunta referente ao questionário para cidadãos menores de seis meses * @return instance */ PerguntaQuestionarioCriancasMenoresSeisMesesThrift getInstance(); /** * Identificador da pergunta referente ao questionário para cidadãos menores de seis meses * */ void getPergunta(); /** * Identificador da pergunta referente ao questionário para cidadãos menores de seis meses * @return questionário para cidadãos menores de seis meses * caso a dataNascimento seja menos que 6 meses anterior à DataAtendimento */ boolean isSetPergunta(); /** * Resposta referente à pergunta * @return Resposta referente à pergunta * Caso a dataNascimento seja menos que 6 meses anterior à DataAtendimento */ boolean isSetRespostaUnicaEscolha(); void setPerguntaIsSet(boolean value); /** * Resposta referente à pergunta * @param value */ void setRespostaUnicaEscolhaIsSet(boolean value); void unsetPergunta(); void unsetRespostaUnicaEscolha(); /** * Valida questionário para cidadãos menores de seis meses * @return questionário para cidadãos menores de seis meses * É condicinal */ boolean validaPergunta(); /** * Valida Resposta referente à pergunta * @return Resposta referente à pergunta * Também pode ser Condicional de acordo com dataNascimento */ boolean validaRespostaUnicaEscolha(); /** * Metodo validade cria os metodos que fazem as validações * Chama todos os metodos que fazem validações * @return Todos os metodos de validação * PerguntaQuestionarioCriancasMenoresSeisMeses e respostaUnicaEscolha */ boolean validades(); }
29
124
0.708812
7554d76ac23ac172635c931bf67954f79b6608f6
7,481
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.demo.uif.controller; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.kuali.rice.krad.demo.uif.form.KradSampleAppForm; import org.kuali.rice.krad.service.KRADServiceLocatorWeb; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.view.ViewTheme; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.web.controller.MethodAccessible; import org.kuali.rice.krad.web.controller.UifControllerBase; import org.kuali.rice.krad.web.form.UifFormBase; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; /** * Basic controller for the KRAD sample application * * @author Kuali Rice Team (rice.collab@kuali.org) */ @Controller @RequestMapping(value = "/kradsampleapp") public class KradSampleAppController extends UifControllerBase { @Override protected KradSampleAppForm createInitialForm(HttpServletRequest request) { return new KradSampleAppForm(); } @Override @MethodAccessible @RequestMapping(params = "methodToCall=start") public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, HttpServletRequest request, HttpServletResponse response) { //TODO tbd return super.start(form, request, response); } @RequestMapping(method = RequestMethod.GET, params = "methodToCall=changeTheme") public ModelAndView changeTheme(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) { changeTheme(form); return getUIFModelAndView(form); } @RequestMapping(method = RequestMethod.POST, params = "methodToCall=validateView") public ModelAndView validateView(@ModelAttribute("KualiForm") UifFormBase uiTestForm, BindingResult result, HttpServletRequest request, HttpServletResponse response) { KRADServiceLocatorWeb.getViewValidationService().validateView(uiTestForm); return getUIFModelAndView(uiTestForm); } @MethodAccessible @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addGrowl") public ModelAndView addGrowl(@ModelAttribute("KualiForm") UifFormBase uiTestForm, BindingResult result, HttpServletRequest request, HttpServletResponse response) { String extraInfo = (String) request.getParameter("extraInfo"); if (extraInfo == null) { extraInfo = "none"; } GlobalVariables.getMessageMap().addGrowlMessage("Growl Message", "demo.fakeGrowl", extraInfo); return getUIFModelAndView(uiTestForm); } private void changeTheme(UifFormBase form) { String theme = ((KradSampleAppForm) form).getThemeName(); if (theme != null) { ViewTheme newTheme = (ViewTheme) (KRADServiceLocatorWeb.getDataDictionaryService().getDictionaryBean( theme)); if (newTheme != null) { form.getView().setTheme(newTheme); } } } /** * Changes the view to readOnly and returns. * * @param uifForm * @param result * @param request * @param response * @return readOnly View */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=makeReadOnly") public ModelAndView makeReadOnly(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result, HttpServletRequest request, HttpServletResponse response) { //set View to readOnly uifForm.getView().setReadOnly(true); return getUIFModelAndView(uifForm); } /** * Adds errors to fields defined in the validationMessageFields array */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addStandardSectionsErrors") public ModelAndView addStandardSectionsErrors(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) { GlobalVariables.getMessageMap().putError("Demo-ValidationMessages-Section1", "errorSectionTest"); GlobalVariables.getMessageMap().putError("Demo-ValidationMessages-Section2", "errorSectionTest"); Set<String> inputFieldIds = form.getViewPostMetadata().getInputFieldIds(); for (String id : inputFieldIds) { if (form.getViewPostMetadata().getComponentPostData(id, UifConstants.PostMetadata.PATH) != null) { String key = (String) form.getViewPostMetadata().getComponentPostData(id, UifConstants.PostMetadata.PATH); GlobalVariables.getMessageMap().putError(key, "error1Test"); } } return getUIFModelAndView(form); } /** * Refreshes the group * * @param form * @param result * @param request * @param response * @return */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=refreshProgGroup") public ModelAndView refreshProgGroup(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) { return getUIFModelAndView(form); } /** * Refresh and set server messages * * @param form * @param result * @param request * @param response * @return */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=refreshWithServerMessages") public ModelAndView refreshWithServerMessages(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) { GlobalVariables.getMessageMap().putError("inputField4", "serverTestError"); GlobalVariables.getMessageMap().putWarning("inputField4", "serverTestWarning"); GlobalVariables.getMessageMap().putInfo("inputField4", "serverTestInfo"); return getUIFModelAndView(form); } @RequestMapping(method = RequestMethod.POST, params = "methodToCall=customRefresh") public ModelAndView customRefresh(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) { GlobalVariables.getMessageMap().addGrowlMessage("Test", "serverTestInfo"); return getUIFModelAndView(form); } }
42.265537
123
0.702714
c5a227bf495d275f27275a72f1a10274849346d9
634
package org.firstinspires.ftc.team2981.old; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.Servo; import org.firstinspires.ftc.team2981.old.systems.FourBar; import org.firstinspires.ftc.team2981.old.systems.RobotDrive; import org.firstinspires.ftc.team2981.systems.*; public class Robot { public RobotDrive drive; //public MCUnit mc; public Servo marker; public FourBar fbar; public Robot(HardwareMap map){ drive = new RobotDrive(map); // mc = new MCUnit(map); marker = map.get(Servo.class, "marker"); fbar = new FourBar(map); } }
25.36
61
0.716088
c0adbf5de7d97b31b7f73ad3357a220f3db94902
1,185
package com.muscleape.excel.test.model; import com.muscleape.excel.annotation.ExcelProperty; import lombok.Data; import java.math.BigDecimal; import java.util.Date; @Data public class ReadModel extends BaseReadModel { @ExcelProperty(index = 2) private Integer mm; @ExcelProperty(index = 3) private BigDecimal money; @ExcelProperty(index = 4) private Long times; @ExcelProperty(index = 5) private Double activityCode; @ExcelProperty(index = 6, format = "yyyy-MM-dd") private Date date; @ExcelProperty(index = 7) private String lx; @ExcelProperty(index = 8) private String name; @ExcelProperty(index = 18) private String kk; @Override public String toString() { return "JavaModel{" + "str='" + str + '\'' + ", ff=" + ff + ", mm=" + mm + ", money=" + money + ", times=" + times + ", activityCode=" + activityCode + ", date=" + date + ", lx='" + lx + '\'' + ", name='" + name + '\'' + ", kk='" + kk + '\'' + '}'; } }
22.788462
52
0.518143
de19640026d6d56ae1f3a9f7feb757475c385dd8
5,387
/** * Copyright 2018-2021 Deere & Company * * 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.deere.isg.worktracker.spring; import com.deere.clock.Clock; import com.deere.isg.worktracker.OutstandingWork; import com.deere.isg.worktracker.servlet.ConnectionLimits; import com.deere.isg.worktracker.servlet.HttpFloodSensor; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Optional; import static com.deere.isg.worktracker.servlet.WorkContextListener.FLOOD_SENSOR_ATTR; import static com.deere.isg.worktracker.spring.TestWorkUtils.SIZE; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class SpringRequestBouncerHandlerInterceptorTest { @Mock private OutstandingWork<SpringWork> outstanding; @Mock private Object handler; @Mock private ServletContext context; private HttpServletRequest request; private HttpServletResponse response; private HttpFloodSensor<SpringWork> floodSensor; private SpringRequestBouncerHandlerInterceptor handlerInterceptor; private ConnectionLimits<SpringWork> limit; @Before public void setUp() { Clock.freeze(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); limit = new ConnectionLimits<>(); floodSensor = new HttpFloodSensor<>(outstanding, limit); when(context.getAttribute(FLOOD_SENSOR_ATTR)).thenReturn(floodSensor); handlerInterceptor = new SpringRequestBouncerHandlerInterceptor(); handlerInterceptor.setServletContext(context); when(outstanding.stream()).thenAnswer(invocationOnMock -> TestWorkUtils.getWorkList(SIZE).stream()); when(outstanding.current()).thenReturn(Optional.of(TestWorkUtils.createWork())); } @After public void tearDown() { Clock.clear(); } @Test public void preHandleIsTrueIfMayProceedSameUser() throws Exception { limit.addConnectionLimit(SIZE, ConnectionLimits.USER).method(SpringWork::getRemoteUser); assertThat(handlerInterceptor.preHandle(request, response, handler), is(true)); } @Test public void preHandleIsFalseIfMayNotProceedSameUser() throws Exception { limit.addConnectionLimit(SIZE - 1, ConnectionLimits.USER).method(SpringWork::getRemoteUser); assertThat(handlerInterceptor.preHandle(request, response, handler), is(false)); } @Test public void preHandleIsTrueIfMayProceedSameService() throws Exception { limit.addConnectionLimit(SIZE, ConnectionLimits.SERVICE).method(SpringWork::getService); assertThat(handlerInterceptor.preHandle(request, response, handler), is(true)); } @Test public void preHandleIsFalseIfMayNotProceedSameService() throws Exception { limit.addConnectionLimit(SIZE - 1, ConnectionLimits.SERVICE).method(SpringWork::getService); assertThat(handlerInterceptor.preHandle(request, response, handler), is(false)); } @Test public void preHandleIsTrueIfMayProceedSameSession() throws Exception { limit.addConnectionLimit(SIZE, ConnectionLimits.SESSION).method(SpringWork::getSessionId); assertThat(handlerInterceptor.preHandle(request, response, handler), is(true)); } @Test public void preHandleIsFalseIfMayNotProceedSameSession() throws Exception { limit.addConnectionLimit(SIZE - 1, ConnectionLimits.SESSION).method(SpringWork::getSessionId); assertThat(handlerInterceptor.preHandle(request, response, handler), is(false)); } @Test public void preHandleIsTrueIfMayProceedTooManyTotal() throws Exception { limit.addConnectionLimit(SIZE, ConnectionLimits.TOTAL).test(x -> true); assertThat(handlerInterceptor.preHandle(request, response, handler), is(true)); } @Test public void preHandleIsFalseIfMayNotProceedTooManyTotal() throws Exception { limit.addConnectionLimit(SIZE - 1, ConnectionLimits.TOTAL).test(x -> true); assertThat(handlerInterceptor.preHandle(request, response, handler), is(false)); } @Test public void nullFloodSensorReturnsTruePreHandle() throws Exception { when(context.getAttribute(FLOOD_SENSOR_ATTR)).thenReturn(null); handlerInterceptor.setServletContext(context); assertThat(handlerInterceptor.preHandle(request, response, handler), is(true)); } }
36.646259
108
0.754037
7434f0cb8d27fc29e72b1b680b00827ba1cbcdcc
3,229
package sonar.flux.network; import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import sonar.core.SonarCore; import sonar.core.helpers.NBTHelper.SyncType; import sonar.flux.FluxNetworks; import sonar.flux.api.ClientFlux; import sonar.flux.api.NetworkFluxFolder; import sonar.flux.api.network.IFluxNetwork; import sonar.flux.connection.NetworkSettings; import java.util.ArrayList; import java.util.List; public class PacketConnectionsClientList implements IMessage { public List<ClientFlux> connections; public List<NetworkFluxFolder> folders; public int networkID; public PacketConnectionsClientList() {} public PacketConnectionsClientList(IFluxNetwork network) { this.connections = network.getSetting(NetworkSettings.CLIENT_CONNECTIONS); this.folders = network.getSetting(NetworkSettings.NETWORK_FOLDERS); this.networkID = network.getSetting(NetworkSettings.NETWORK_ID); } @Override public void fromBytes(ByteBuf buf) { this.networkID = buf.readInt(); NBTTagCompound compound = ByteBufUtils.readTag(buf); NBTTagList flux_list = compound.getTagList("flux", Constants.NBT.TAG_COMPOUND); this.connections = new ArrayList<>(); for (int i = 0; i < flux_list.tagCount(); i++) { NBTTagCompound c = flux_list.getCompoundTagAt(i); connections.add(new ClientFlux(c)); } NBTTagList folders_list = compound.getTagList("network_folders", Constants.NBT.TAG_COMPOUND); this.folders = new ArrayList<>(); for (int i = 0; i < folders_list.tagCount(); i++) { NBTTagCompound c = folders_list.getCompoundTagAt(i); folders.add(new NetworkFluxFolder(c)); } } @Override public void toBytes(ByteBuf buf) { buf.writeInt(networkID); NBTTagCompound tag = new NBTTagCompound(); NBTTagList flux_list = new NBTTagList(); connections.forEach(flux -> flux_list.appendTag(flux.writeData(new NBTTagCompound(), SyncType.SAVE))); tag.setTag("flux", flux_list); NBTTagList folders_list = new NBTTagList(); folders.forEach(flux -> folders_list.appendTag(flux.writeData(new NBTTagCompound(), SyncType.SAVE))); tag.setTag("network_folders", folders_list); ByteBufUtils.writeTag(buf, tag); } public static class Handler implements IMessageHandler<PacketConnectionsClientList, IMessage> { @Override public IMessage onMessage(PacketConnectionsClientList message, MessageContext ctx) { if (ctx.side == Side.CLIENT) { SonarCore.proxy.getThreadListener(ctx.side).addScheduledTask(() -> { IFluxNetwork common = FluxNetworks.getClientCache().getNetwork(message.networkID); if (!common.isFakeNetwork()) { common.setSettingInternal(NetworkSettings.CLIENT_CONNECTIONS, message.connections); common.setSettingInternal(NetworkSettings.NETWORK_FOLDERS, message.folders); } }); } return null; } } }
35.097826
104
0.771137
0419e5341d0f5b8983aa01f94f2f943a4589e016
1,157
package com.kfzx.leyou.user.pojo; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.validator.constraints.Length; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Pattern; import java.util.Date; /** * @author VicterTian * @version V1.0 * @Date 2019/1/4 */ @Data @NoArgsConstructor @AllArgsConstructor @Table(name = "tb_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 用户名 */ @NotEmpty(message = "用户名不能为空") @Length(min = 4, max = 30, message = "用户名只能在4~30位之间") private String username; /** * 密码 */ @JsonIgnore @Length(min = 4, max = 30, message = "用户名只能在4~30位之间") private String password; /** * 电话 */ @Pattern(regexp = "^1[35678]\\d{9}$", message = "手机号格式不正确") private String phone; /** * 创建时间 */ private Date created; /** * 密码的盐值 */ @JsonIgnore private String salt; }
20.298246
60
0.719965
f3dc28126ad18a67d81fed9739e772169836f03d
1,678
package com.sun.mobileshop.db; import android.database.sqlite.SQLiteDatabase; import com.sun.mobileshop.common.MyApplication; import com.sun.mobileshop.gen.DaoMaster; import com.sun.mobileshop.gen.DaoSession; /** * Created by Administrator on 2019/5/3 0003. * <p> * 数据库配置 */ public class GreenDaoManager { // DevOpenHelper:创建SQLite数据库的SQLiteOpenHelper的具体实现 // DaoMaster:GreenDao的顶级对象,作为数据库对象、用于创建表和删除表 // DaoSession:管理所有的Dao对象,Dao对象中存在着增删改查等API private static GreenDaoManager mInstance; private static DaoMaster mDaoMaster; private static DaoSession mDaoSession; public GreenDaoManager() { if (mInstance == null) { //创建数据库mydb DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MyApplication.getContext(), "mydb", null); //打开一个数据库,并且返回一个可以对数据库读写的对象 SQLiteDatabase db = devOpenHelper.getWritableDatabase(); //获取数据库对象 mDaoMaster = new DaoMaster(db); //获取Dao对象管理者 mDaoSession = mDaoMaster.newSession(); } } //单例模式 public static GreenDaoManager getmInstance(){ if (mInstance==null){ synchronized (GreenDaoManager.class){ if (mInstance==null){ mInstance=new GreenDaoManager(); } } } return mInstance; } public static DaoMaster getmDaoMaster() { return mDaoMaster; } public static DaoSession getmDaoSession() { return mDaoSession; } public static DaoSession getNewSession(){ mDaoSession=mDaoMaster.newSession(); return mDaoSession; } }
25.044776
122
0.643027
92838f7bed037e9be5667d2c8c9a728f996350b3
3,399
package com.lofidewanto.demo.server.domain; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "results", "start", "limit", "size", "_links" }) public class Labels { @JsonProperty("results") private List<Object> results = new ArrayList<Object>(); @JsonProperty("start") private int start; @JsonProperty("limit") private int limit; @JsonProperty("size") private int size; @JsonProperty("_links") private Links links; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public Labels() { } /** * * @param limit * @param results * @param start * @param links * @param size */ public Labels(List<Object> results, int start, int limit, int size, Links links) { super(); this.results = results; this.start = start; this.limit = limit; this.size = size; this.links = links; } @JsonProperty("results") public List<Object> getResults() { return results; } @JsonProperty("results") public void setResults(List<Object> results) { this.results = results; } public Labels withResults(List<Object> results) { this.results = results; return this; } @JsonProperty("start") public int getStart() { return start; } @JsonProperty("start") public void setStart(int start) { this.start = start; } public Labels withStart(int start) { this.start = start; return this; } @JsonProperty("limit") public int getLimit() { return limit; } @JsonProperty("limit") public void setLimit(int limit) { this.limit = limit; } public Labels withLimit(int limit) { this.limit = limit; return this; } @JsonProperty("size") public int getSize() { return size; } @JsonProperty("size") public void setSize(int size) { this.size = size; } public Labels withSize(int size) { this.size = size; return this; } @JsonProperty("_links") public Links getLinks() { return links; } @JsonProperty("_links") public void setLinks(Links links) { this.links = links; } public Labels withLinks(Links links) { this.links = links; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public Labels withAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); return this; } }
22.361842
86
0.620477
bd2a9f178abd7eb0551c622d190112104ea6e745
7,157
package com.company; import java.sql.*; import java.util.List; import com.company.model.*; public class Main { public static void main(String[] args) { // write your code here Datasource datasource = new Datasource(); if(!datasource.open()) { System.out.println("Can't open datasource"); return; } District district = datasource.queryDistrict(2); if (district == null) { System.out.println("No district!"); return; } System.out.println("District: "); System.out.println("ID: " + district.getId() + "\nName: " + district.getName() + "\nZoneId: " + district.getZoneId() + "\nCoordinatorId: " + district.getCoordinatorId()); Coordinator coordinator = datasource.queryCoordinator(1); if (coordinator == null) { System.out.println("\nNo Coordinator!"); return; } System.out.println("\nCoordinator: "); System.out.println("ID: " + coordinator.getId() + "\nName: " + coordinator.getFullName() + "\nUserId: " + coordinator.getUserId()); Education education = datasource.queryEducation(1); if (education == null) { System.out.println("\nNo Education"); return; } System.out.println("\nEducation: "); System.out.println("ID: " + education.getId() + "\nEnrollmentStatus: " + education.getEnrollmentStatus().toString().toLowerCase() + "\nSchoolName: " + education.getSchoolName() + "\nSchoolType: " + education.getTypeOfSchool().toString().toLowerCase() + "\nYear: " + education.getYear() + "\nSchoolLeve: " + education.getLevel().toString().toLowerCase() + "\nReason: " + education.getReason()); Father father = datasource.queryFather(1); if (father == null) { System.out.println("\nNo Father"); return; } System.out.println("\nFather: "); System.out.println("ID: " + father.getId() + "\nFirstName: " + father.getFirstName() + "\nLastName: " + father.getLastName() + "\nDateOfBirth: " + father.getDateOfBirth() + "\nDateOfDeath: " + father.getDateOfDeath() + "\nCauseOfDeath: " + father.getCauseOfDeath() + "\nDeathCertificateUrl: " + father.getDeathCertificateUrl()); Guardian guardian = datasource.queryGuardian(1); if (guardian == null) { System.out.println("\nNo Guardian"); return; } System.out.println("\nGuardian: "); System.out.println("ID: " + guardian.getId() + "\n" + "FirstName: " + guardian.getFirstName() + "\n" + "MiddleName: " + guardian.getMiddleName() + "\n" + "LastName: " + guardian.getLastName() + "\n" + "Gender: " + guardian.getGender() + "\n" + "DateOfBirth: " + guardian.getDateOfBirth() + "\n" + "RelationToOrphan: " + guardian.getRelationToOrphan() + "\n" + "E-mail: " + guardian.getEmail() + "\n" + "MobileNumber: " + guardian.getMobileNumber() + "\n" + "TelephoneNumber: " + guardian.getTelephoneNumber() + "\n" + "Nationality: " + guardian.getNationality()); // --------------------------------------------------------------------------------------------------- DistrictJoin districtJoin = datasource.queryDistrictJoin(); if(districtJoin == null) { System.out.println("No DistrictJoin"); return; } System.out.println("\nDistrictJoin: "); System.out.println("DistrictName: " + districtJoin.getDistrict().getName() + "\n" + "ZoneName: " + districtJoin.getZone().getName() + "\n" + "Coordinator: " + districtJoin.getCoordinator().getFullName()); Orphan orphan = datasource.queryOrphan(2); if(orphan == null) { System.out.println("No Orphan"); return; } System.out.println("\nOrphan: "); System.out.println("OrphanName: " + orphan.getFirstName() + " " + orphan.getFather().getFirstName() + " " + orphan.getFather().getLastName() + "\n" + "MotherName: " + orphan.getMother().getFirstName() + " " + orphan.getMother().getMiddleName() + " " + orphan.getMother().getLastName() + "\n" + "GuardianName: " + orphan.getGuardian().getFirstName() + " " + orphan.getGuardian().getMiddleName() + " " + orphan.getGuardian().getLastName() + "\n" + "EnrollmentStatus: " + orphan.getEducation().getEnrollmentStatus() + "\n" + "VillageName: " + orphan.getVillage().getName() + "\n"); // List<Orphan> orphans = datasource.queryAllOrphans(1); // // for (Orphan orphan : // orphans) { // System.out.println("id " + orphan.getId()); // System.out.println("cr@ " + orphan.getCreated_at()); // System.out.println("up@ " + orphan.getUpdated_at()); // System.out.println("fn " + orphan.getFirstName()); // System.out.println("g " + orphan.getGender()); // System.out.println("pob " + orphan.getPlaceOfBirth()); // System.out.println("dob " + orphan.getDateOfBirth()); // System.out.println("sl " + orphan.getSpokenLanguages()); // System.out.println("gamr " + orphan.getGradeAgeMismatchReason()); // System.out.println("h " + orphan.getHobbies()); // System.out.println("r " + orphan.getReligion()); // System.out.println("icu " + orphan.getIdCardUrl()); // System.out.println("pu " + orphan.getPassportUrl()); // System.out.println("tylu " + orphan.getThankyouLetterUrl()); // System.out.println("bcu " + orphan.getBirthCertificateUrl()); // System.out.println("hd " + orphan.getHealthDescription()); // System.out.println("ps " + orphan.getPsychologicalStatus()); // System.out.println("sId " + orphan.getSiblingId()); // System.out.println("moId " + orphan.getMotherId()); // System.out.println("faId " + orphan.getFatherId()); // System.out.println("guId " + orphan.getGuardianId()); // System.out.println("edId " + orphan.getEducationId()); // System.out.println("doId " + orphan.getDonorId()); // System.out.println("hopId " + orphan.getHouse_propertyId()); // System.out.println("ViId " + orphan.getVillageId()); // } datasource.insertCoordinator("Eyob Aschenaki", "ethioeyoba@gmail.com", "W@duuminMySQL"); datasource.close(); } }
51.862319
115
0.521867
3e5dcabd1b534d0a68c36ee4dde523c797a0442c
671
package com.hospital.management.exception; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; public class GlobalResponse { public GlobalResponse() { } public Date getDate() { return date; } public GlobalResponse(Date date, String message) { this.date = date; this.message = message; } public void setDate(Date date) { this.date = date; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } private Date date; private String message; }
17.657895
54
0.642325
7db69257ee798accbd6efedc5c6bfc57bfe6c79d
9,727
package com.biermacht.brews.frontend.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.Switch; import android.widget.TextView; import com.biermacht.brews.DragDropList.DragSortListView; import com.biermacht.brews.R; import com.biermacht.brews.database.DatabaseAPI; import com.biermacht.brews.frontend.adapters.FermentableArrayAdapter; import com.biermacht.brews.frontend.adapters.RecipeSpinnerAdapter; import com.biermacht.brews.ingredient.Fermentable; import com.biermacht.brews.recipe.Recipe; import com.biermacht.brews.utils.BrewCalculator; import com.biermacht.brews.utils.Units; import com.biermacht.brews.utils.Utils; import com.biermacht.brews.utils.interfaces.BiermachtFragment; import java.util.ArrayList; public class EfficiencyCalculatorFragment extends Fragment implements BiermachtFragment { private static int resource = R.layout.fragment_efficiency_calculator; View pageView; Context c; // Edit texts which the user fills out. EditText gravityEditText; EditText wortVolumeEditText; EditText tempEditText; // Titles TextView tempTitleView; TextView wortVolumeTitle; // Views which the calculator populates. TextView efficiencyView; TextView maxGravityView; // Other helper views. ScrollView scrollView; Spinner recipeSpinner; Switch showListSwitch; // Special ListView and adapter to implement "swipe-to-dismiss". public DragSortListView listView; public FermentableArrayAdapter arrayAdapter; Recipe selectedRecipe; private ArrayList<Fermentable> ingredientList; private AdapterView.OnItemClickListener mClickListener; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { pageView = inflater.inflate(resource, container, false); setHasOptionsMenu(true); // Get context c = getActivity(); // Get views we care about gravityEditText = (EditText) pageView.findViewById(R.id.measured_gravity_edit_text); wortVolumeEditText = (EditText) pageView.findViewById(R.id.final_volume_edit_text); wortVolumeTitle = (TextView) pageView.findViewById(R.id.final_volume_title); tempEditText = (EditText) pageView.findViewById(R.id.meas_temp_edit_text); tempTitleView = (TextView) pageView.findViewById(R.id.meas_temp_title); efficiencyView = (TextView) pageView.findViewById(R.id.calculated_efficiency_view); maxGravityView = (TextView) pageView.findViewById(R.id.max_gravity_view); listView = (DragSortListView) pageView.findViewById(R.id.ingredient_list); scrollView = (ScrollView) pageView.findViewById(R.id.scrollview); recipeSpinner = (Spinner) pageView.findViewById(R.id.recipe_spinner); showListSwitch = (Switch) pageView.findViewById(R.id.show_list_switch); // Configure the switch onSetListener. showListSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { listView.setVisibility(View.VISIBLE); } else { listView.setVisibility(View.GONE); } } }); // By default, show the ingredient list. showListSwitch.setChecked(true); // Set the temperature view to an appropriate default value. if (Units.getTemperatureUnits().equals(Units.CELSIUS)) { tempTitleView.setText(String.format("Temp (%s)", Units.CELSIUS)); tempEditText.setText(String.format("%2.1f", 21.0)); tempEditText.setHint("21.0"); } else { tempTitleView.setText(String.format("Temp (%s)", Units.FAHRENHEIT)); tempEditText.setText(String.format("%2.0f", 68.0)); tempEditText.setHint("68"); } // Set the volume based on configured units. if (Units.getVolumeUnits().equals(Units.LITERS)) { wortVolumeTitle.setText("Measured Volume (L)"); } else { wortVolumeTitle.setText("Measured Volume (gal)"); } // Initialize the ingredient list. ingredientList = new ArrayList<>(); // Configure the recipe spinner adapter. DatabaseAPI db = new DatabaseAPI(this.getActivity().getApplicationContext()); final ArrayList<Recipe> recipes = db.getRecipeList(); // TODO: Better handling of case where there are no recipes. if (recipes.size() == 0) { Recipe r = new Recipe(); recipes.add(r); } RecipeSpinnerAdapter spinnerAdapter = new RecipeSpinnerAdapter(this.getActivity().getApplicationContext(), recipes, "Recipes"); recipeSpinner.setAdapter(spinnerAdapter); // Configure the recipe spinner listener. // Handle fermentable type selections recipeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { selectedRecipe = recipes.get(position); Log.d("EfficiencyCalc", "Selected recipe: " + selectedRecipe.toString()); // Update the fermentables list and listview. populateFermentablesListFromRecipe(); // Set some text. maxGravityView.setText(String.format("Available Gravity Points: %2.2f", BrewCalculator.GravityPoints(ingredientList))); wortVolumeEditText.setText(String.format("%2.2f", selectedRecipe.getDisplayBoilSize())); } public void onNothingSelected(AdapterView<?> parentView) { } }); recipeSpinner.setSelection(0); // Initialize the list view. populateFermentablesListFromRecipe(); return pageView; } private void populateFermentablesListFromRecipe() { // If a recipe is selected, then use that ingredient list. Otherwise use an empty list. if (selectedRecipe != null) { ingredientList.removeAll(ingredientList); ingredientList.addAll(selectedRecipe.getFermentablesList()); } arrayAdapter = new FermentableArrayAdapter(getActivity(), ingredientList); listView.setAdapter(arrayAdapter); listView.setDropListener(onDrop); listView.setRemoveListener(onRemove); listView.setDragEnabled(true); Utils.setListViewHeightBasedOnChildren(listView); } // Callback for when a fermentable is removed from the list. public DragSortListView.RemoveListener onRemove = new DragSortListView.RemoveListener() { @Override public void remove(int pos) { Log.d("EfficiencyCalc", "Removing ingredient at position: " + pos); arrayAdapter.remove(ingredientList.get(pos)); Utils.setListViewHeightBasedOnChildren(listView); maxGravityView.setText(String.format("Available Gravity Points: %2.3f", BrewCalculator.GravityPoints(ingredientList))); } }; // We don't currently support OnDrop actions here. public DragSortListView.DropListener onDrop = new DragSortListView.DropListener() { @Override public void drop(int oldPosition, int newPosition) { } }; public void calculate() { double gravity; double volume; double temp; double eff = 0.0; // Acquire data. If an invalid double is supplied, short-circuit, but don't crash. try { gravity = Double.parseDouble(gravityEditText.getText().toString().replace(",", "" + ".")); volume = Double.parseDouble(wortVolumeEditText.getText().toString().replace(",", ".")); temp = Double.parseDouble(tempEditText.getText().toString().replace(",", ".")); } catch (Exception e) { return; } // If we're in metric mode, convert the volume to gallons for the calculation below. if (Units.getVolumeUnits().equals(Units.LITERS)) { volume = Units.litersToGallons(volume); } // Convert temp. if (Units.getTemperatureUnits().equals(Units.CELSIUS)) { temp = Units.celsiusToFahrenheit(temp); } // Adjust the measured gravity. double adjustedGravity = BrewCalculator.adjustGravityForTemp(gravity, temp, 68); // Determine total gravity points in the wort. double measuredGravityPoints = (adjustedGravity - 1) * 1000 * volume; // Ideal gravity points. double idealGravityPoints = BrewCalculator.GravityPoints(ingredientList); eff = (measuredGravityPoints / idealGravityPoints) * 100; efficiencyView.setText(String.format("%2.2f", eff)); } public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_efficiency_menu, menu); } //************************************************************************** // The following set of methods implement the Biermacht Fragment Interface //************************************************************************** @Override public void update() { } @Override public boolean onOptionsItemSelected(MenuItem item) { return false; } @Override public String name() { return "Efficiency Calculator"; } @Override public void handleClick(View v) { if (v.getId() == R.id.calculate_button) { this.calculate(); // The page is a bit long - scroll to the bottom so the user can see the // calculation output. scrollView.post(new Runnable() { @Override public void run() { scrollView.fullScroll(View.FOCUS_DOWN); } }); } } }
34.739286
131
0.714198
a609cc57d046234d3692e49442a9afe8a4a3bd74
1,534
package chav1961.necrosql; import java.io.File; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Enumeration; import org.junit.Assert; import org.junit.Test; public class SimpleDriverTest { @Test public void spiAndURITest() throws SQLException { final Enumeration<Driver> list = DriverManager.getDrivers(); boolean found = false; while (list.hasMoreElements()) { final Driver driver = list.nextElement(); if (driver instanceof SimpleDriver) { try{DriverManager.getConnection("jdbc:dbf:unknown"); Assert.fail("Mandartory exception was not detected (non-existent directory for the DBFs)"); } catch (SQLException exc) { } final File f = new File("./src/test/resources/chav1961/necrosql"); final Connection conn = DriverManager.getConnection("jdbc:dbf:"+f.getAbsolutePath().replace('\\','/')); Assert.assertNotNull(conn); Assert.assertTrue(conn instanceof SimpleConnection); conn.close(); found = true; } } Assert.assertTrue(found); try{DriverManager.getConnection("jdbc:unknown"); Assert.fail("Mandartory exception was not detected (no suitable driver for the given connection string)"); } catch (SQLException exc) { } try{DriverManager.getConnection("jdbc"); Assert.fail("Mandartory exception was not detected (no suitable driver for the given connection string)"); } catch (SQLException exc) { } } }
31.306122
110
0.698827
daffcce42c646fcacca1c43a4e20425d785be3ec
1,797
/* * #%L * ELK OWL Model Implementation * * $Id$ * $HeadURL$ * %% * Copyright (C) 2011 Department of Computer Science, University of Oxford * %% * 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. * #L% */ package org.semanticweb.elk.owl.iris; import org.semanticweb.elk.owl.visitors.ElkFullIriVisitor; import org.semanticweb.elk.owl.visitors.ElkIriVisitor; /** * Represents a fully expanded IRI. This class is just a String wrapper. * * @author Frantisek Simancik * */ public class ElkFullIri extends ElkIri { protected final String iri; public ElkFullIri(String iri) { super(iri.hashCode()); this.iri = iri; } public ElkFullIri(ElkPrefix prefix, String localName) { this(prefix.getIri().getFullIriAsString() + localName); } @Override public String getFullIriAsString() { return iri; } @Override public String toString() { return "<" + getFullIriAsString() + ">"; } /** * Accept an {@link ElkFullIriVisitor}. * * @param visitor * the visitor that can work with this object type * @return the output of the visitor */ public <O> O accept(ElkFullIriVisitor<O> visitor) { return visitor.visit(this); } @Override public <O> O accept(ElkIriVisitor<O> visitor) { return accept((ElkFullIriVisitor<O>) visitor); } }
24.616438
75
0.702838
fcd475e4ad040a82ca0ae20c45d462f4523760f1
1,811
package com.boot.controller; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.boot.model.Shipwreck; import com.boot.repository.ShipwreckRepository; @RestController @RequestMapping("api/v1/") public class ShipwreckController { @Autowired private ShipwreckRepository shipwreckRepository; @RequestMapping(value = "shipwrecks", method = RequestMethod.GET) public List<Shipwreck> list() { return shipwreckRepository.findAll(); } @RequestMapping(value = "shipwrecks", method = RequestMethod.POST) public Shipwreck create(@RequestBody Shipwreck shipwreck) { return shipwreckRepository.saveAndFlush(shipwreck); } @RequestMapping(value = "shipwrecks/{id}", method = RequestMethod.GET) public Shipwreck get(@PathVariable Long id) { return shipwreckRepository.findOne(id); } @RequestMapping(value = "shipwrecks/{id}", method = RequestMethod.PUT) public Shipwreck update(@PathVariable Long id, @RequestBody Shipwreck shipwreck) { Shipwreck existingShipwreck = shipwreckRepository.findOne(id); BeanUtils.copyProperties(shipwreck, existingShipwreck); return shipwreckRepository.saveAndFlush(existingShipwreck); } @RequestMapping(value = "shipwrecks/{id}", method = RequestMethod.DELETE) public Shipwreck delete(@PathVariable Long id) { Shipwreck existingShipwreck = shipwreckRepository.findOne(id); shipwreckRepository.delete(existingShipwreck); return existingShipwreck; } }
34.169811
83
0.805632
5d208e925d93340e87462fcdbac282e6dfa81d73
2,299
package com.jbproductions.liszt; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverter; import androidx.room.TypeConverters; import androidx.sqlite.db.SupportSQLiteDatabase; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * RoomDatabase class to work with TaskDao and perform asynchronous queries. */ @Database(entities = {Task.class, TaskList.class}, version = 1, exportSchema = false) @TypeConverters(DateTypeConverter.class) public abstract class TaskRoomDatabase extends RoomDatabase { private static final int NUMBER_OF_THREADS = 2; static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS); private static volatile TaskRoomDatabase INSTANCE; private static final RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); databaseWriteExecutor.execute(() -> { TaskDao taskDao = INSTANCE.taskDao(); ListDao listDao = INSTANCE.listDao(); Task task1 = new Task("Apples", false); Task task2 = new Task("Oranges", false); taskDao.insert(task1); taskDao.insert(task2); TaskList inbox = new TaskList("inbox"); listDao.insert(inbox); }); } }; static TaskRoomDatabase getDatabase(final Context context) { if (INSTANCE == null) { synchronized (TaskRoomDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), TaskRoomDatabase.class, "task_database") .addCallback(sRoomDatabaseCallback).build(); } } } return INSTANCE; } public abstract TaskDao taskDao(); public abstract ListDao listDao(); }
35.369231
108
0.667682
ac214ac8adae7c24723b415b6d5f1a43eca87c96
954
package kr.ac.hs.se.controller; import kr.ac.hs.se.container.Container; import kr.ac.hs.se.dto.Guestbook; import kr.ac.hs.se.service.GuestbookService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/guestbook") public class LookupGuestbookController extends HttpServlet { private final GuestbookService guestbookService = Container.guestbookService; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { List<Guestbook> list = guestbookService.getGuestbooks(); request.setAttribute("guestbookList", list); request.getRequestDispatcher("/WEB-INF/view/guestbookView.jsp").forward(request, response); } }
34.071429
121
0.793501
769108efd380ee72defd445e16ca764dfbf8f83f
407
/* * Copyright (c) TIKI Inc. * MIT license. See LICENSE file in root directory. */ package com.mytiki.kgraph_generate; import java.util.List; public class KGraphDefs { private List<KGraphDefsVertex> vertices; public List<KGraphDefsVertex> getVertices() { return vertices; } public void setVertices(List<KGraphDefsVertex> vertices) { this.vertices = vertices; } }
19.380952
62
0.690418
dd4691377930e3e9a069c9bd9db2482b14df2691
663
package org.apereo.cas.adaptors.duo.web.flow; import org.apereo.cas.web.flow.resolver.impl.AbstractCasWebflowEventResolver; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import java.util.Set; /** * This is {@link DuoAuthenticationWebflowEventResolver }. * * @author Misagh Moayyed * @since 5.0.0 */ public class DuoAuthenticationWebflowEventResolver extends AbstractCasWebflowEventResolver { @Override protected Set<Event> resolveInternal(final RequestContext requestContext) { return handleAuthenticationTransactionAndGrantTicketGrantingTicket(requestContext); } }
28.826087
92
0.803922
f127fa0466a0e692c6b26887dcb87f11dca48084
1,952
/* * Copyright 2018 Charles University in Prague * Copyright 2018 Vojtech Horky * * 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 cz.cuni.mff.d3s.perf; import org.junit.*; public class NativeThreadsTest { private static class SpinningWorker implements Runnable { public volatile boolean terminate = false; public volatile boolean started = false; @Override public void run() { started = true; while (!terminate) {} } } private SpinningWorker worker; private Thread thread; @Before public void setup() { worker = new SpinningWorker(); thread = new Thread(worker); } @After public void teardown() { if (thread.isAlive()) { worker.terminate = true; try { thread.join(); } catch (InterruptedException e) {} } } @Test public void newThreadsAreAutomaticallyRegistered() { thread.start(); while (!worker.started) {} long id = NativeThreads.getNativeId(thread); // Getting here means the previous call has not thrown any // exception, thus the thread was registered. Assert.assertTrue(true); } @Test public void impossibleToRegisterThreadTwice() { Assert.assertFalse(NativeThreads.registerJavaThread(Thread.currentThread(), 0)); } }
28.705882
88
0.637295
a58177c3d3fda36dd3373363961183a40a5debb3
1,120
package util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; public class FileUtil { public static String readFileInSameFolder() { try { String jarpath = System.getProperty("java.class.path"); int firstIndex = jarpath.lastIndexOf(System.getProperty("path.separator")) + 1; int lastIndex = jarpath.lastIndexOf(File.separator) + 1; jarpath = jarpath.substring(firstIndex, lastIndex); File conffile =new File(jarpath + "conf.json"); if(conffile.exists() != true) { return "false"; } InputStreamReader confrd = new InputStreamReader (new FileInputStream(conffile),"UTF-8"); BufferedReader confbf = new BufferedReader(confrd); int ch = 0; StringBuffer sb = new StringBuffer(); while((ch = confbf.read()) != -1) { sb.append((char) ch); } return sb.toString(); }catch (Exception e) { return "false"; } } }
31.111111
101
0.580357
76c06682e70a28991893ab3e69068b64f0534d78
784
package fr.anatom3000.gwwhit.mixin; import fr.anatom3000.gwwhit.WrappedPack; import net.minecraft.resource.ReloadableResourceManagerImpl; import net.minecraft.resource.ResourcePack; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @Mixin(ReloadableResourceManagerImpl.class) public class ReloadableResourceManagerImplMixin { @ModifyArg(method = "beginMonitoredReload(L;L;L;L;)Lnet/minecraft/resource/ResourceReloadMonitor;", at = @At(value = "INVOKE", target = "Lnet/minecraft/resource/ReloadableResourceManagerImpl;addPack(Lnet/minecraft/resource/ResourcePack;)V"), index = 0) private ResourcePack modifyPack(ResourcePack pack) { return new WrappedPack(pack); } }
49
256
0.808673
0194ebf2501896c1f5e98038b9fdf43dc074f359
12,445
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.datasource.formula; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CharStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import org.diirt.datasource.expression.DesiredRateExpression; import org.diirt.datasource.expression.DesiredRateExpressionList; import org.diirt.datasource.expression.DesiredRateExpressionListImpl; import org.diirt.util.text.StringUtil; /** * The abstract syntax tree corresponding to a formula expression. * This class provides a logical representation of the expression, * static factory methods to create such expressions from text representation * (i.e. parsing) and the ability to convert to datasource expressions. * * @author carcassi */ public class FormulaAst { /** * The type of a formula AST node. */ public enum Type { /** * An operator/function node */ OP, /** * A String literal node */ STRING, /** * An integer literal node */ INTEGER, /** * A floating point literal node */ FLOATING_POINT, /** * A channel node */ CHANNEL, /** * An id node */ ID}; private final Type type; private final List<FormulaAst> children; private final Object value; private FormulaAst(Type type, List<FormulaAst> children, Object value) { this.type = type; this.children = children; this.value = value; } /** * The type of the AST node. * * @return the node type */ public Type getType() { return type; } /** * The value corresponding to the node. The value depends on the type * as follows: * <ul> * <li>OP: String with the name of the function/operator</li> * <li>STRING: the String constant (unquoted)</li> * <li>INTEGER: the Integer constant</li> * <li>FLOATING_POINT: the Double constant</li> * <li>CHANNEL: String with the channel name (unquoted)</li> * <li>ID: String with the name of the id</li> * </ul> * @return the value of the node */ public Object getValue() { return value; } /** * The children of this node, if IO, null otherwise. * * @return the node children; null if no children */ public List<FormulaAst> getChildren() { return children; } /** * Lists all the channel names used in the AST. * * @return a list of channel names */ public List<String> listChannelNames() { List<String> names = new ArrayList<>(); listChannelNames(names); return Collections.unmodifiableList(names); } private void listChannelNames(List<String> names) { switch(getType()) { case OP: for (FormulaAst child : getChildren()) { child.listChannelNames(names); } break; case CHANNEL: names.add((String) getValue()); default: } } /** * A STRING node from a quoted token. * * @param token the quoted string * @return the new node */ public static FormulaAst stringFromToken(String token) { return string(StringUtil.unquote(token)); } /** * A STRING node representing the given string. * * @param unquotedString the string * @return the new node */ public static FormulaAst string(String unquotedString) { return new FormulaAst(Type.STRING, null, unquotedString); } /** * An INTEGER node from a token. * * @param token a string parsable to an integer * @return the new node */ public static FormulaAst integerFromToken(String token) { return integer(Integer.parseInt(token)); } /** * An INTEGER node from the given value. * * @param integer the integer value * @return the new node */ public static FormulaAst integer(int integer) { return new FormulaAst(Type.INTEGER, null, integer); } /** * A FLOATING_POINT node from a token. * * @param token a string parseable to a double * @return the new node */ public static FormulaAst floatingPointFromToken(String token) { return floatingPoint(Double.parseDouble(token)); } /** * A FLOATING_POINT node from the given value. * * @param floatingPoint the double value * @return the new node */ public static FormulaAst floatingPoint(double floatingPoint) { return new FormulaAst(Type.FLOATING_POINT, null, floatingPoint); } /** * A CHANNEL node from a quoted token. * * @param token the quoted channel name * @return the new node */ public static FormulaAst channelFromToken(String token) { return channel(StringUtil.unquote(token)); } /** * A CHANNEL node representing the given channel name. * * @param channelName the channel name * @return the new node */ public static FormulaAst channel(String channelName) { return new FormulaAst(Type.CHANNEL, null, channelName); } /** * An ID node representing the given id. * * @param id the id * @return the new node */ public static FormulaAst id(String id) { return new FormulaAst(Type.ID, null, id); } /** * An OP node representing the given operator/function with the given * arguments. * * @param opName the name of the operator/function * @param children the node children * @return the new node */ public static FormulaAst op(String opName, FormulaAst... children) { return op(opName, Arrays.asList(children)); } /** * An OP node representing the given operator/function with the given * arguments. * * @param opName the name of the operator/function * @param children the node children * @return the new node */ public static FormulaAst op(String opName, List<FormulaAst> children) { return new FormulaAst(Type.OP, children, opName); } /** * Creates a parser for the given text. * * @param text the string to be parsed * @return the new parser */ static FormulaParser createParser(String text) { CharStream stream = new ANTLRStringStream(text); FormulaLexer lexer = new FormulaLexer(stream); TokenStream tokenStream = new CommonTokenStream(lexer); return new FormulaParser(tokenStream); } /** * The AST corresponding to the parsed formula. * * @param formula the string to be parsed * @return the parsed AST */ public static FormulaAst formula(String formula) { FormulaAst ast = staticChannel(formula); if (ast != null) { return ast; } formula = formula.substring(1); try { ast = createParser(formula).formula(); if (ast == null) { throw new IllegalArgumentException("Parsing failed"); } return ast; } catch (Exception ex) { throw new IllegalArgumentException("Error parsing formula: " + ex.getMessage(), ex); } } private static FormulaAst staticChannel(String formula) { if (formula.startsWith("=")) { return null; } if (formula.trim().matches(StringUtil.SINGLEQUOTED_STRING_REGEX)) { return channel(formula.trim()); } return channel(formula); } /** * The AST corresponding to a single channel, if the formula represents one, * or null, if the formula is not a single channel. * * @param formula the string to be parsed * @return the parsed AST */ public static FormulaAst singleChannel(String formula) { FormulaAst ast = staticChannel(formula); if (ast != null) { return ast; } formula = formula.substring(1); try { ast = createParser(formula).singleChannel(); return ast; } catch (Exception ex) { return null; } } /** * Converts the AST to a datasource expression. * * @return the new expression */ public DesiredRateExpression<?> toExpression() { switch(getType()) { case CHANNEL: return new LastOfChannelExpression<>((String) getValue(), Object.class); case FLOATING_POINT: return org.diirt.datasource.vtype.ExpressionLanguage.vConst((Double) getValue()); case INTEGER: return org.diirt.datasource.vtype.ExpressionLanguage.vConst((Integer) getValue()); case STRING: return org.diirt.datasource.vtype.ExpressionLanguage.vConst((String) getValue()); case ID: return ExpressionLanguage.namedConstant((String) getValue()); case OP: DesiredRateExpressionList<Object> expressions = new DesiredRateExpressionListImpl<>(); for (FormulaAst child : getChildren()) { expressions.and(child.toExpression()); } return ExpressionLanguage.function((String) getValue(), expressions); default: throw new IllegalArgumentException("Unsupported type " + getType() + " for ast"); } } /** * Returns a new AST where the channel nodes that match the keys of the map * are substituted with the values of the map. * * @param substitutions from channel name to new AST * @return a new AST */ public FormulaAst substituteChannels(Map<String, FormulaAst> substitutions) { switch(getType()) { case CHANNEL: FormulaAst sub = substitutions.get((String) getValue()); if (sub == null) { sub = this; } return sub; case OP: FormulaAst[] subs = new FormulaAst[getChildren().size()]; for (int i = 0; i < subs.length; i++) { subs[i] = getChildren().get(i).substituteChannels(substitutions); } return op((String) getValue(), subs); default: return this; } } @Override public String toString() { switch(getType()) { case OP: return FormulaFunctions.format((String) getValue(), new AbstractList<String>() { @Override public String get(int index) { return getChildren().get(index).toString(); } @Override public int size() { return getChildren().size(); } }); default: return getValue().toString(); } } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof FormulaAst) { FormulaAst other = (FormulaAst) obj; return Objects.equals(getType(), other.getType()) && Objects.equals(getValue(), other.getValue()) && Objects.equals(getChildren(), other.getChildren()); } else { return false; } } @Override public int hashCode() { int hash = 3; hash = 89 * hash + Objects.hashCode(this.type); hash = 89 * hash + Objects.hashCode(this.children); hash = 89 * hash + Objects.hashCode(this.value); return hash; } }
29.56057
102
0.571073
abc69b91e233ffadf9fd1a545a37c61b2d602715
350
package ch.evel.warehouse.db.dao; import ch.evel.warehouse.db.model.UserRole; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.UUID; public interface UserRolesRepository extends CrudRepository<UserRole, Long> { List<UserRole> findUserRoleById(UUID uuid); UserRole findByRole(String role); }
25
77
0.805714
6af085e117d822fe6a95b024debd913247f6390e
4,719
package com.clj.blesample.tool.operation; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.View; import com.clj.blesample.R; import com.clj.blesample.tool.BluetoothService; import java.util.ArrayList; import java.util.List; public class OperationActivity extends AppCompatActivity { private Toolbar toolbar; private List<Fragment> fragments = new ArrayList<>(); private int currentPage = 0; private String[] titles = new String[]{"服务列表", "特征列表", "操作控制台"}; private BluetoothService mBluetoothService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_operation); initView(); bindService(); } @Override protected void onDestroy() { super.onDestroy(); if (mBluetoothService != null) mBluetoothService.closeConnect(); unbindService(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (currentPage != 0) { currentPage--; changePage(currentPage); return true; } else { finish(); return true; } } return super.onKeyDown(keyCode, event); } private void initView() { toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("特征列表"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (currentPage != 0) { currentPage--; changePage(currentPage); } else { finish(); } } }); } private void initPage() { prepareFragment(); changePage(0); } public void changePage(int page) { currentPage = page; toolbar.setTitle(titles[page]); updateFragment(page); if (currentPage == 1) { ((CharacteristicListFragment) fragments.get(1)).showData(); } else if (currentPage == 2) { ((CharacteristicOperationFragment) fragments.get(2)).showData(); } } private void prepareFragment() { fragments.add(new ServiceListFragment()); fragments.add(new CharacteristicListFragment()); fragments.add(new CharacteristicOperationFragment()); for (Fragment fragment : fragments) { getSupportFragmentManager().beginTransaction().add(R.id.fragment, fragment).hide(fragment).commit(); } } private void updateFragment(int position) { if (position > fragments.size() - 1) { return; } for (int i = 0; i < fragments.size(); i++) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); Fragment fragment = fragments.get(i); if (i == position) { transaction.show(fragment); } else { transaction.hide(fragment); } transaction.commit(); } } public BluetoothService getBluetoothService() { return mBluetoothService; } private void bindService() { Intent bindIntent = new Intent(this, BluetoothService.class); this.bindService(bindIntent, mFhrSCon, Context.BIND_AUTO_CREATE); } private void unbindService() { this.unbindService(mFhrSCon); } private ServiceConnection mFhrSCon = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mBluetoothService = ((BluetoothService.BluetoothBinder) service).getService(); mBluetoothService.setConnectCallback(callback); initPage(); } @Override public void onServiceDisconnected(ComponentName name) { mBluetoothService = null; } }; private BluetoothService.Callback2 callback = new BluetoothService.Callback2() { @Override public void onDisConnected() { finish(); } }; }
29.867089
112
0.614325
13ed71aaf4d8e76e914db42bf875ac3858f98d7f
175
package de.gematik.demis.exceptions; public class ParseRuntimeException extends RuntimeException { public ParseRuntimeException(Throwable cause) { super(cause); } }
19.444444
61
0.782857
fb08397f62d0f9fefc040cdfa7b785814537c306
850
package io.github.swingboot.example.editor.control; import javax.inject.Inject; import io.github.swingboot.control.Control; import io.github.swingboot.example.editor.model.SpellCheckingService; import io.github.swingboot.example.editor.view.DocumentView; public class CorrectSpellingControl implements Control<Void> { private final DocumentView documentView; private final SpellCheckingService spellCheckingService; @Inject public CorrectSpellingControl(DocumentView documentView, SpellCheckingService spellCheckingService) { this.documentView = documentView; this.spellCheckingService = spellCheckingService; } @Override public void perform(Void parameter) { String contents = documentView.getContents(); String correctContents = spellCheckingService.correctSpelling(contents); documentView.setContents(correctContents); } }
31.481481
102
0.830588
f9bd74f9ce6bd6650726e5a993f9b6e292cdc74d
259
package org.bukkit.block; import org.bukkit.material.Colorable; /** * Represents a captured state of a bed. * @deprecated does not provide useful information beyond the material itself */ @Deprecated public interface Bed extends TileState, Colorable { }
23.545455
77
0.772201
8111094db818125655bb9c40fc71be53c554248a
466
package com.anokbook.Models; import java.io.Serializable; public class EditPostImageModel implements Serializable { String image_id,image_url; public String getImage_id() { return image_id; } public void setImage_id(String image_id) { this.image_id = image_id; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } }
18.64
57
0.669528
f8fe940ef76c8e693a874ee8122e7b208cd20dc7
4,035
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.carros.resources; import co.edu.uniandes.csw.carros.dtos.AutomovilDTO; import co.edu.uniandes.csw.carros.ejb.AutomovilLogic; import co.edu.uniandes.csw.carros.entities.AutomovilEntity; import co.edu.uniandes.csw.carros.exceptions.BusinessLogicException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; /** * * @author Andres Forero */ @Path("automoviles") @Produces("application/json") @Consumes("application/json") @RequestScoped public class AutomovilResource { private static final Logger LOGGER = Logger.getLogger(AutomovilResource.class.getName()); @Inject private AutomovilLogic autoLogic; @POST public AutomovilDTO createAutomovil(AutomovilDTO auto) throws BusinessLogicException{ LOGGER.log(Level.INFO, "AutomovilResource createAutomovil: input: {0}" + " modelo : " + auto.getModelo(), auto); AutomovilDTO nuevoAutomovilDTO = new AutomovilDTO(autoLogic.createAutomovil(auto.toEntity())); LOGGER.log(Level.INFO, "FacturaResource createFactura: output: {0}", nuevoAutomovilDTO); return nuevoAutomovilDTO; } @GET public List<AutomovilDTO> getAutomoviles(){ LOGGER.info("FacturaResource getFacturas: input: void"); List<AutomovilDTO> listaFacturas = listEntity2DetailDTO(autoLogic.getAutomoviles()); LOGGER.log(Level.INFO, "FacturaResource getFacturas: output: {0}", listaFacturas); return listaFacturas; } @GET @Path("{autoId: \\d+}") public AutomovilDTO getAutomovil(@PathParam("autoId") Long autoId){ LOGGER.log(Level.INFO, "AutomovilResource getAutomovil: input: {0}", autoId); AutomovilEntity autoEntity = autoLogic.getAutomovil(autoId); if (autoEntity == null) { throw new WebApplicationException("El recurso /automoviles/" + autoId + " no existe.", 404); } AutomovilDTO autoDTO = new AutomovilDTO(autoEntity); LOGGER.log(Level.INFO, "FacturaResource getFactura: output: {0}", autoDTO); return autoDTO; } @PUT @Path("{autoId: \\d+}") public AutomovilDTO updateAutomovil(@PathParam("autoId") Long autoId, AutomovilDTO auto) throws BusinessLogicException{ LOGGER.log(Level.INFO, "Automovilresorice updateAutomovil: input: id:{0} , auto: {1}", new Object[]{autoId, auto}); auto.setAutoId(autoId); if (autoLogic.getAutomovil(autoId) == null) { throw new WebApplicationException("El recurso /Automovil/" + autoId + " no existe.", 404); } AutomovilDTO DTO = new AutomovilDTO(autoLogic.updateAutomovil(auto.toEntity())); LOGGER.log(Level.INFO, "Automovilresorice updateAutomovil: output: {0}", DTO); return DTO; } @DELETE @Path("{autoId: \\d+}") public void deleteAutomovil(@PathParam("autoId") Long autoID){ AutomovilEntity entity = autoLogic.getAutomovil(autoID); if (entity == null) { throw new WebApplicationException("El recurso /automoviles/" + autoID + " no existe.", 404); } autoLogic.deleteAutomovil(autoID); } private List<AutomovilDTO> listEntity2DetailDTO(List<AutomovilEntity> entityList){ List<AutomovilDTO> list = new ArrayList<>(); for (AutomovilEntity entity : entityList) { list.add(new AutomovilDTO(entity)); } return list; } }
36.351351
123
0.685998
e8f5f228adddfaeb1357009ad96251ea82e9f422
1,134
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.intellij.inspection; import com.intellij.codeInspection.LocalInspectionTool; import org.jetbrains.annotations.NotNull; import org.mapstruct.intellij.MapstructBaseCompletionTestCase; /** * @author Filip Hrisafov */ public abstract class BaseInspectionTest extends MapstructBaseCompletionTestCase { @Override protected String getTestDataPath() { return "testData/inspection"; } @Override protected void setUp() throws Exception { super.setUp(); } @NotNull protected abstract Class<? extends LocalInspectionTool> getInspection(); protected void doTest() { String testName = getTestName( false ); configureByFile( testName + ".java" ); myFixture.enableInspections( getInspection() ); // Disable info checks as there is a difference between 2018.x and 2019.x // Links in 2019.x have an info highlighting myFixture.testHighlighting( true, false, true ); } }
29.076923
105
0.710758
0e58c313af3c6bd0aafa7460a2d4094859f59600
256
package com.wangjie.recyclerview.example; import com.wangjie.androidinject.annotation.present.AIAppCompatActivity; /** * Author: wangjie * Email: tiantian.china.2@gmail.com * Date: 7/10/15. */ public class BaseActivity extends AIAppCompatActivity{ }
21.333333
72
0.777344
99920590cd2e03b5a67f5bdd12b228403fb1f03e
18,268
package com.donkingliang.imageselector; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SimpleItemAnimator; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.TextView; import com.donkingliang.imageselector.adapter.FolderAdapter; import com.donkingliang.imageselector.adapter.ImageAdapter; import com.donkingliang.imageselector.constant.Constants; import com.donkingliang.imageselector.entry.Folder; import com.donkingliang.imageselector.entry.Image; import com.donkingliang.imageselector.model.ImageModel; import com.donkingliang.imageselector.utils.DateUtils; import com.donkingliang.imageselector.utils.ImageSelectorUtils; import java.util.ArrayList; public class ImageSelectorActivity extends AppCompatActivity { private TextView tvTime; private TextView tvFolderName; private TextView tvConfirm; private TextView tvPreview; private FrameLayout btnConfirm; private FrameLayout btnPreview; private RecyclerView rvImage; private RecyclerView rvFolder; private View masking; private ImageAdapter mAdapter; private GridLayoutManager mLayoutManager; private ArrayList<Folder> mFolders; private Folder mFolder; private boolean isToSettings = false; private static final int PERMISSION_REQUEST_CODE = 0X00000011; private boolean isOpenFolder; private boolean isShowTime; private boolean isInitFolder; private boolean isSingle; private int mMaxCount; private Handler mHideHandler = new Handler(); private Runnable mHide = new Runnable() { @Override public void run() { hideTime(); } }; /** * 启动图片选择器 * * @param activity * @param requestCode * @param isSingle 是否单选 * @param maxSelectCount 图片的最大选择数量,小于等于0时,不限数量,isSingle为false时才有用。 */ public static void openActivity(Activity activity, int requestCode, boolean isSingle, int maxSelectCount) { Intent intent = new Intent(activity, ImageSelectorActivity.class); intent.putExtra(Constants.MAX_SELECT_COUNT, maxSelectCount); intent.putExtra(Constants.IS_SINGLE, isSingle); activity.startActivityForResult(intent, requestCode); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_select); Intent intent = getIntent(); mMaxCount = intent.getIntExtra(Constants.MAX_SELECT_COUNT, 0); isSingle = intent.getBooleanExtra(Constants.IS_SINGLE, false); setStatusBarColor(); initView(); initListener(); initImageList(); checkPermissionAndLoadImages(); hideFolderList(); setSelectImageCount(0); } /** * 修改状态栏颜色 */ private void setStatusBarColor() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.parseColor("#373c3d")); } } private void initView() { rvImage = (RecyclerView) findViewById(R.id.rv_image); rvFolder = (RecyclerView) findViewById(R.id.rv_folder); tvConfirm = (TextView) findViewById(R.id.tv_confirm); tvPreview = (TextView) findViewById(R.id.tv_preview); btnConfirm = (FrameLayout) findViewById(R.id.btn_confirm); btnPreview = (FrameLayout) findViewById(R.id.btn_preview); tvFolderName = (TextView) findViewById(R.id.tv_folder_name); tvTime = (TextView) findViewById(R.id.tv_time); masking = findViewById(R.id.masking); } private void initListener() { findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); btnPreview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ArrayList<Image> images = new ArrayList<>(); images.addAll(mAdapter.getSelectImages()); toPreviewActivity(images, 0); } }); btnConfirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { confirm(); } }); findViewById(R.id.btn_folder).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isInitFolder) { if (isOpenFolder) { closeFolder(); } else { openFolder(); } } } }); masking.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { closeFolder(); } }); rvImage.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); changeTime(); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); changeTime(); } }); } /** * 初始化图片列表 */ private void initImageList() { // 判断屏幕方向 Configuration configuration = getResources().getConfiguration(); if (configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { mLayoutManager = new GridLayoutManager(this, 3); } else { mLayoutManager = new GridLayoutManager(this, 5); } rvImage.setLayoutManager(mLayoutManager); mAdapter = new ImageAdapter(this, mMaxCount, isSingle); rvImage.setAdapter(mAdapter); ((SimpleItemAnimator) rvImage.getItemAnimator()).setSupportsChangeAnimations(false); if (mFolders != null && !mFolders.isEmpty()) { setFolder(mFolders.get(0)); } mAdapter.setOnImageSelectListener(new ImageAdapter.OnImageSelectListener() { @Override public void OnImageSelect(Image image, boolean isSelect, int selectCount) { setSelectImageCount(selectCount); } }); mAdapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() { @Override public void OnItemClick(Image image, int position) { toPreviewActivity(mAdapter.getData(), position); } }); } /** * 初始化图片文件夹列表 */ private void initFolderList() { if (mFolders != null && !mFolders.isEmpty()) { isInitFolder = true; rvFolder.setLayoutManager(new LinearLayoutManager(ImageSelectorActivity.this)); FolderAdapter adapter = new FolderAdapter(ImageSelectorActivity.this, mFolders); adapter.setOnFolderSelectListener(new FolderAdapter.OnFolderSelectListener() { @Override public void OnFolderSelect(Folder folder) { setFolder(folder); closeFolder(); } }); rvFolder.setAdapter(adapter); } } /** * 刚开始的时候文件夹列表默认是隐藏的 */ private void hideFolderList() { rvFolder.post(new Runnable() { @Override public void run() { rvFolder.setTranslationY(rvFolder.getHeight()); rvFolder.setVisibility(View.GONE); } }); } /** * 设置选中的文件夹,同时刷新图片列表 * * @param folder */ private void setFolder(Folder folder) { if (folder != null && mAdapter != null && !folder.equals(mFolder)) { mFolder = folder; tvFolderName.setText(folder.getName()); rvImage.scrollToPosition(0); mAdapter.refresh(folder.getImages()); } } private void setSelectImageCount(int count) { if (count == 0) { btnConfirm.setEnabled(false); btnPreview.setEnabled(false); tvConfirm.setText("确定"); tvPreview.setText("预览"); } else { btnConfirm.setEnabled(true); btnPreview.setEnabled(true); tvPreview.setText("预览(" + count + ")"); if (isSingle) { tvConfirm.setText("确定"); } else if (mMaxCount > 0) { tvConfirm.setText("确定(" + count + "/" + mMaxCount + ")"); } else { tvConfirm.setText("确定(" + count + ")"); } } } /** * 弹出文件夹列表 */ private void openFolder() { if (!isOpenFolder) { masking.setVisibility(View.VISIBLE); ObjectAnimator animator = ObjectAnimator.ofFloat(rvFolder, "translationY", rvFolder.getHeight(), 0).setDuration(300); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); rvFolder.setVisibility(View.VISIBLE); } }); animator.start(); isOpenFolder = true; } } /** * 收起文件夹列表 */ private void closeFolder() { if (isOpenFolder) { masking.setVisibility(View.GONE); ObjectAnimator animator = ObjectAnimator.ofFloat(rvFolder, "translationY", 0, rvFolder.getHeight()).setDuration(300); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); rvFolder.setVisibility(View.GONE); } }); animator.start(); isOpenFolder = false; } } /** * 隐藏时间条 */ private void hideTime() { if (isShowTime) { ObjectAnimator.ofFloat(tvTime, "alpha", 1, 0).setDuration(300).start(); isShowTime = false; } } /** * 显示时间条 */ private void showTime() { if (!isShowTime) { ObjectAnimator.ofFloat(tvTime, "alpha", 0, 1).setDuration(300).start(); isShowTime = true; } } /** * 改变时间条显示的时间(显示图片列表中的第一个可见图片的时间) */ private void changeTime() { int firstVisibleItem = getFirstVisibleItem(); if (firstVisibleItem > 0 && firstVisibleItem < mAdapter.getData().size()) { Image image = mAdapter.getData().get(firstVisibleItem); String time = DateUtils.getImageTime(image.getTime() * 1000); tvTime.setText(time); showTime(); mHideHandler.removeCallbacks(mHide); mHideHandler.postDelayed(mHide, 1500); } } private int getFirstVisibleItem() { return mLayoutManager.findFirstVisibleItemPosition(); } private void confirm() { if (mAdapter == null) { return; } //因为图片的实体类是Image,而我们返回的是String数组,所以要进行转换。 ArrayList<Image> selectImages = mAdapter.getSelectImages(); ArrayList<String> images = new ArrayList<>(); for (Image image : selectImages) { images.add(image.getPath()); } //点击确定,把选中的图片通过Intent传给上一个Activity。 Intent intent = new Intent(); intent.putStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT, images); setResult(RESULT_OK, intent); finish(); } private void toPreviewActivity(ArrayList<Image> images, int position) { if (images != null && !images.isEmpty()) { PreviewActivity.openActivity(this, images, mAdapter.getSelectImages(), isSingle, mMaxCount, position); } } @Override protected void onStart() { super.onStart(); if (isToSettings) { isToSettings = false; checkPermissionAndLoadImages(); } } /** * 处理图片预览页返回的结果 * * @param requestCode * @param resultCode * @param data */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.RESULT_CODE) { if (data != null && data.getBooleanExtra(Constants.IS_CONFIRM, false)) { //如果用户在预览页点击了确定,就直接把用户选中的图片返回给用户。 confirm(); } else { //否则,就刷新当前页面。 mAdapter.notifyDataSetChanged(); setSelectImageCount(mAdapter.getSelectImages().size()); } } } /** * 横竖屏切换处理 * * @param newConfig */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mLayoutManager != null && mAdapter != null) { //切换为竖屏 if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { mLayoutManager.setSpanCount(3); } //切换为横屏 else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { mLayoutManager.setSpanCount(5); } mAdapter.notifyDataSetChanged(); } } /** * 检查权限并加载SD卡里的图片。 */ private void checkPermissionAndLoadImages() { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // Toast.makeText(this, "没有图片", Toast.LENGTH_LONG).show(); return; } int hasWriteContactsPermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE); if (hasWriteContactsPermission == PackageManager.PERMISSION_GRANTED) { //有权限,加载图片。 loadImageForSDCard(); } else { //没有权限,申请权限。 ActivityCompat.requestPermissions(ImageSelectorActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } } /** * 处理权限申请的回调。 * * @param requestCode * @param permissions * @param grantResults */ @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == PERMISSION_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //允许权限,加载图片。 loadImageForSDCard(); } else { //拒绝权限,弹出提示框。 showExceptionDialog(); } } } /** * 发生没有权限等异常时,显示一个提示dialog. */ private void showExceptionDialog() { new AlertDialog.Builder(this) .setCancelable(false) .setTitle("提示") .setMessage("该相册需要赋予访问存储的权限,请到“设置”>“应用”>“权限”中配置权限。") .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); finish(); } }).setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); startAppSettings(); isToSettings = true; } }).show(); } /** * 从SDCard加载图片。 */ private void loadImageForSDCard() { ImageModel.loadImageForSDCard(this, new ImageModel.DataCallback() { @Override public void onSuccess(ArrayList<Folder> folders) { mFolders = folders; runOnUiThread(new Runnable() { @Override public void run() { if (mFolders != null && !mFolders.isEmpty()) { initFolderList(); setFolder(mFolders.get(0)); } } }); } }); } /** * 启动应用的设置 */ private void startAppSettings() { Intent intent = new Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && isOpenFolder) { closeFolder(); return true; } return super.onKeyDown(keyCode, event); } }
32.738351
108
0.588515
59b77c27eb143414d1b36bb1c28676134c059607
49,361
package fy.game.blockpuzzle.gamepiece.sets; import fy.game.blockpuzzle.gamepiece.IGamePieceSet; /** GENERATED */ public class GamePieceSet0010 implements IGamePieceSet { @Override public String[] getGamePieceSet() { String[] r = new String[1600]; r[0] = "#1#4#4"; r[1] = "#4#5#2"; r[2] = "#Ecke2#Ecke2#4"; r[3] = "#Ecke2#Ecke2#2"; r[4] = "#2x2#4#Ecke2"; r[5] = "#3#2#Ecke2"; r[6] = "#2#2x2#1"; r[7] = "#Ecke2#3#3"; r[8] = "#2#5#3"; r[9] = "#1#4#5"; r[10] = "#1#1#3"; r[11] = "#4#3#2"; r[12] = "#2#1#Ecke2"; r[13] = "#4#3#2"; r[14] = "#5#3x3#1"; r[15] = "#Ecke2#5#2"; r[16] = "#2#Ecke3#Ecke2"; r[17] = "#4#Ecke2#Ecke2"; r[18] = "#2#3#Ecke3"; r[19] = "#4#L#3x3"; r[20] = "#3#3#Ecke2"; r[21] = "#4#5#3"; r[22] = "#2x2#3#Ecke3"; r[23] = "#Ecke2#Ecke3#4"; r[24] = "#Ecke3#2#4"; r[25] = "#5#Ecke2#Ecke2"; r[26] = "#J:............L............#2"; r[27] = "#4#4#J"; r[28] = "#Ecke3#Ecke2#1"; r[29] = "#Ecke3#Ecke2#3"; r[30] = "#5#4#3"; r[31] = "#4#4#Ecke3"; r[32] = "#5#3#4"; r[33] = "#2#2x2_Bonus#3x3"; r[34] = "#4#1#Ecke3"; r[35] = "#Ecke3#5#J"; r[36] = "#2#2x2#2"; r[37] = "#5#Ecke2#3x3"; r[38] = "#2#Ecke2#2x2_Bonus"; r[39] = "#2x2#Ecke3#5"; r[40] = "#J#4#Ecke2"; r[41] = "#J#2#5"; r[42] = "#2#5#J"; r[43] = "#3#Ecke3#3"; r[44] = "#Ecke3#4#5"; r[45] = "#Ecke3#Ecke2#4"; r[46] = "#1#2x2_Bonus#J"; r[47] = "#4#2#5"; r[48] = "#5#4#Ecke2"; r[49] = "#5#3#2"; r[50] = "#2#Ecke3#3x3"; r[51] = "#5#Ecke3#1"; r[52] = "#1#1#J"; r[53] = "#5#2#2"; r[54] = "#3#L#2"; r[55] = "#Ecke2#4#3"; r[56] = "#2#1#Ecke2"; r[57] = "#4#5#Ecke3"; r[58] = "#3#Ecke3#3"; r[59] = "#5#5#Ecke2"; r[60] = ":..2....L....2....2....2..#5#Ecke2"; r[61] = "#4#Ecke3#L"; r[62] = "#3#1#Ecke3"; r[63] = "#Ecke3#Ecke3#3"; r[64] = "#3#3#Ecke2"; r[65] = "#Ecke2#2#4"; r[66] = "#Ecke3#4#1"; r[67] = "#4#3#2"; r[68] = "#J#L#2"; r[69] = "#L#2x2#L"; r[70] = "#4#Ecke3#Ecke2"; r[71] = "#Ecke3#5#3"; r[72] = "#4#3#1"; r[73] = "#J#5#3"; r[74] = "#3#5#1"; r[75] = "#1#4#L"; r[76] = "#1#J#3"; r[77] = "#5#2#Ecke3"; r[78] = "#4#5#Ecke2"; r[79] = "#Ecke2#J#2x3_Bonus"; r[80] = "#1#Ecke2#1"; r[81] = "#2#J#5"; r[82] = "#Ecke2#2#3"; r[83] = "#J#S#4"; r[84] = "#3#3x3#Ecke2"; r[85] = "#J#Ecke2#Ecke3"; r[86] = "#2x3_Bonus#3#Ecke2"; r[87] = "#L#Ecke3#3"; r[88] = "#2x2:........4....4..4S4......#3"; r[89] = "#4#2#3x3"; r[90] = "#Z#Ecke3#S"; r[91] = "#L#3#1"; r[92] = "#5#2x2#Ecke2"; r[93] = "#2x3_Bonus#4#2x3"; r[94] = ":......44L....4....4......#3#3"; r[95] = "#L#1#3"; r[96] = "#3#Ecke2#2x2_Bonus"; r[97] = "#J#2x3#1"; r[98] = "#2x2_Bonus#2x3_Bonus#J"; r[99] = "#2x2_Bonus#4#1"; r[100] = "#5#Ecke2#L"; r[101] = "#2x3#2x3_Bonus#2x3"; r[102] = "#3#4#1"; r[103] = "#Ecke3#2x2_Bonus#5"; r[104] = "#1#4#1"; r[105] = "#4#4#2x2"; r[106] = "#Ecke2#Ecke2#5"; r[107] = "#L#4#2x2"; r[108] = "#Ecke2#1#4"; r[109] = "#3#2x2_Bonus#5"; r[110] = "#J#3#Ecke2"; r[111] = "#Ecke2#3#2"; r[112] = "#Z#Ecke3#L"; r[113] = "#1#2#Ecke3"; r[114] = "#3x3#2x3#Ecke2"; r[115] = "#5#5#Ecke2"; r[116] = "#2x3#2x2#5"; r[117] = "#5#3#3"; r[118] = "#4#3#3"; r[119] = "#1#3x3_Bonus1#1"; r[120] = "#2#5#Ecke2"; r[121] = "#1#4#4"; r[122] = "#3x3_Bonus1#2x2#3"; r[123] = "#4#3x3#5"; r[124] = "#5#Ecke3#5"; r[125] = "#1#3x3_Bonus1#3x3_Bonus1"; r[126] = "#2#4#3"; r[127] = "#3x3_Bonus1#2x3_Bonus:............L............"; r[128] = "#5#3#5"; r[129] = "#1#2#1"; r[130] = "#3#3x3_Bonus1#5"; r[131] = "#3#2x3#2x2"; r[132] = "#Ecke2#2#1"; r[133] = "#4#3#4"; r[134] = "#T#T#Z"; r[135] = "#Ecke2#3x3#T"; r[136] = "#4#Ecke3#3"; r[137] = "#3#2#Ecke3"; r[138] = "#3#4#3"; r[139] = "#Ecke3#2#4"; r[140] = "#Z#4#2x3_Bonus"; r[141] = "#3#2x2#Ecke2"; r[142] = "#3#2#T"; r[143] = "#1#1#Ecke2"; r[144] = "#2x3_Bonus#2x2#3"; r[145] = "#L#2x3#2x3"; r[146] = "#3#Ecke3#5"; r[147] = "#4#3x3_Bonus1#4"; r[148] = "#3#3#2x3_Bonus"; r[149] = "#5#4#J"; r[150] = "#Ecke2#Ecke2#3x3"; r[151] = "#Ecke2#2x2#5"; r[152] = "#4#3x3_Bonus3#Z"; r[153] = "#4#2#4"; r[154] = "#J#2x3:......33...3S............"; r[155] = "#2x2#Ecke3#Ecke2"; r[156] = "#3x3_Bonus3#2x3_Bonus#3"; r[157] = "#Ecke3#1#T"; r[158] = "#4#T#3"; r[159] = "#1#T#Ecke3"; r[160] = "#2x3#T#3"; r[161] = "#Ecke3#2x3:............55..5L......."; r[162] = "#2#3x3_Bonus2#S"; r[163] = "#Ecke2#1#S"; r[164] = "#5#S#L"; r[165] = "#1#3#Z"; r[166] = "#Z#3x3_Bonus2#2"; r[167] = "#4#5#5"; r[168] = "#1#3#2"; r[169] = "#4#2#3"; r[170] = "#1#2#2x2_Bonus"; r[171] = "#3#5#3x3_Bonus1"; r[172] = "#1#2x3#4"; r[173] = "#Ecke3#3x3_Bonus1#L"; r[174] = "#3x3_Bonus2#4#5"; r[175] = "#1#3#3"; r[176] = "#T#2#3"; r[177] = "#5#3x3#3"; r[178] = "#4#3x3_Bonus3#Ecke2"; r[179] = "#Ecke3#1#2x3_Bonus"; r[180] = "#3#3x3_Bonus1#J"; r[181] = "#3#2x2_Bonus#T"; r[182] = "#2#2x2#3x3"; r[183] = "#3x3_Bonus1#1#Ecke3_Bonus1A"; r[184] = "#3#5#Ecke3_Bonus1A"; r[185] = "#Ecke3#2x3#Ecke2"; r[186] = "#J#3x3#5"; r[187] = "#3#5#2x3"; r[188] = "#Ecke3#S#Ecke3"; r[189] = "#3#2x3_Bonus#4_Bonus"; r[190] = "#3#T#T"; r[191] = "#J#L#1"; r[192] = "#5#3x3#3"; r[193] = "#3x3_Bonus1#Ecke2#T"; r[194] = "#S#Ecke3_Bonus1A#4"; r[195] = "#Ecke2:.......5...55L...........#T"; r[196] = "#T#3#T"; r[197] = "#T#L#T"; r[198] = "#3#4_Bonus#3x3"; r[199] = "#S#3#3"; r[200] = "#Ecke2#3#5"; r[201] = "#J#3#Ecke3_Bonus1B"; r[202] = "#2#4#4"; r[203] = "#3#2#J"; r[204] = "#4#3#2"; r[205] = "#1#5#T"; r[206] = "#2Dots#5#T"; r[207] = "#Ecke3_Bonus1B#3#4"; r[208] = "#S#2x3#4"; r[209] = "#J#Ecke2#3x3_Bonus2"; r[210] = "#3#5#3x3"; r[211] = "#Z#3#3x3_Bonus1"; r[212] = "#Ecke3#4#2"; r[213] = "#T#5#Ecke3"; r[214] = "#2#3#3"; r[215] = "#Ecke2#3#J"; r[216] = "#3#J#1"; r[217] = "#2Dots#3x3_Bonus3#4_Bonus"; r[218] = "#Ecke2#Ecke3_Bonus1B#Ecke3"; r[219] = "#3#3x3_Bonus1#L"; r[220] = "#Ecke3#1#Ecke2"; r[221] = "#3x3_Bonus1#3x3_Bonus1#5"; r[222] = "#J#4#3x3_Bonus3"; r[223] = "#5#1#T"; r[224] = "#1#5#4"; r[225] = "#3#Ecke3_Bonus1B#S"; r[226] = "#2x2_Bonus#Z#4"; r[227] = "#X#4#5"; r[228] = "#1#T#Ecke2"; r[229] = ":......333..L33..333......#1#Ecke3"; r[230] = "#2#4#2"; r[231] = "#2#1#1"; r[232] = "#2#4#L"; r[233] = "#2x3_Bonus#4#3"; r[234] = "#3#3x3_Bonus2#2x3_Bonus"; r[235] = "#4#3x3_Bonus1#Ecke3_Bonus1A"; r[236] = "#Ecke2#1#Ecke3"; r[237] = "#Ecke3#5#S"; r[238] = "#X#J#3"; r[239] = "#4#3#Ecke3_Bonus1B"; r[240] = "#5#Ecke3#4"; r[241] = "#Ecke3#1#Ecke3"; r[242] = ":........4....4..44S......#3x3#Ecke2"; r[243] = "#3#T#2"; r[244] = "#3x3#Ecke3_Bonus1A#3x3"; r[245] = "#2#T#T"; r[246] = "#3#4#2Dots"; r[247] = "#Ecke2#Ecke2#3"; r[248] = "#5#1#Ecke3_Bonus1A"; r[249] = "#5#4_Bonus#4"; r[250] = "#4#3x3_Bonus2#3x3_Bonus3"; r[251] = "#Ecke2#3#5"; r[252] = "#S#2Dots#1"; r[253] = "#1_Bonus1#Ecke3_Bonus1A#Ecke3"; r[254] = "#1#T#2"; r[255] = "#3x3_Bonus3:......111..1S1...........#Ecke2"; r[256] = "#J#Ecke2#T"; r[257] = "#Ecke2#1#T"; r[258] = "#J#2x3_Bonus#L"; r[259] = "#2x3_Bonus#2#4"; r[260] = "#3x3_Bonus3#J#T"; r[261] = "#3#1#J"; r[262] = "#2#1_Bonus1#L"; r[263] = "#2:......4....4....44L......#4"; r[264] = "#1#2x3#T"; r[265] = "#3#2x2#X"; r[266] = "#5#3x3_Bonus3#1"; r[267] = "#5#4#4_Bonus"; r[268] = "#5#T#1_Bonus1"; r[269] = "#4#3x3_Bonus1#L"; r[270] = "#3x3_Bonus1#2#4"; r[271] = "#3#2#2"; r[272] = "#S#T#2"; r[273] = "#S#4_Bonus#4"; r[274] = "#Ecke3_Bonus1B#1#1_Bonus1"; r[275] = "#1_Bonus1#T#2x2"; r[276] = "#L#T#Ecke3"; r[277] = "#J#2x3#T"; r[278] = "#3#Ecke3#1_Bonus1"; r[279] = "#Ecke2#T#2Dots"; r[280] = "#3#Ecke3#T"; r[281] = "#2x2_Bonus#S#2"; r[282] = "#T#5#4"; r[283] = "#T#2x2_Bonus#1"; r[284] = "#S#1#Ecke3"; r[285] = "#3#4#Ecke2"; r[286] = "#X#Ecke3#3x3"; r[287] = "#4#2#Ecke2"; r[288] = "#T#3x3_Bonus3#1"; r[289] = "#2x3_Bonus#Ecke2#2"; r[290] = "#Ecke2#2x2#4"; r[291] = "#1_Bonus1#3x3#2"; r[292] = "#2x3_Bonus#5#5"; r[293] = "#3#2Dots#T"; r[294] = "#1_Bonus1#2#3x3_Bonus3"; r[295] = "#2x2#4#1"; r[296] = "#3x3_Bonus1#1#4"; r[297] = ":......5.5...L...5.5......#1#2x3"; r[298] = "#2x2_Bonus#4#T"; r[299] = "#5#1#T"; r[300] = "#4_Bonus#2#1"; r[301] = "#Ecke2#Ecke2#1"; r[302] = "#2#Ecke3#3x3_Bonus3"; r[303] = "#L#1#3"; r[304] = "#T#Ecke3_Bonus1A#3x3"; r[305] = "#4#Ecke3#3"; r[306] = "#2#4#Z"; r[307] = "#Ecke3#3#2"; r[308] = "#3#1_Bonus1#2"; r[309] = "#Ecke3_Bonus1B#S#X"; r[310] = "#T#Ecke3#3x3_Bonus2"; r[311] = "#3#Ecke3#3x3"; r[312] = "#Z#3x3#T"; r[313] = "#4#2x3_Bonus#2"; r[314] = "#2Dots#Ecke2#3"; r[315] = "#Ecke3#2x2#T"; r[316] = "#4#1_Bonus1#4_Bonus"; r[317] = "#T#2Dots#L"; r[318] = "#Ecke3#Ecke3#2Dots"; r[319] = "#5#5#2x2"; r[320] = "#Ecke2#2x3#Ecke3_Bonus1A"; r[321] = "#1#1#1_Bonus1"; r[322] = "#2#4#3x3"; r[323] = "#2x3_Bonus#1#4"; r[324] = "#J#4#Ecke3_Bonus1A"; r[325] = "#Ecke3#S:........S....4..444......"; r[326] = "#4#2Dots#3x3_Bonus2"; r[327] = "#2x2_Bonus#2x3#S"; r[328] = "#3x3_Bonus3#Ecke3#3"; r[329] = "#5#2Dots#4"; r[330] = "#Z#4#Z"; r[331] = ":...........1L............#Ecke3_Bonus1B#5"; r[332] = "#3x3_Bonus3#3#3"; r[333] = "#5#L#Ecke2"; r[334] = "#X#4#T"; r[335] = "#2#4_Bonus#4_Bonus"; r[336] = "#T#3x3#T"; r[337] = "#4_Bonus#5#4"; r[338] = "#S#5#Ecke2"; r[339] = "#4_Bonus#Ecke3_Bonus2#Ecke2"; r[340] = "#5#T#2x3"; r[341] = "#X#5#Ecke2"; r[342] = "#2#Ecke2#Ecke3_Bonus2"; r[343] = "#Ecke3_Bonus2#Ecke3#Ecke3"; r[344] = "#Ecke2#5#3x3_Bonus2"; r[345] = "#T#2#S"; r[346] = "#2Dots#3#4"; r[347] = "#2x2_Bonus#Ecke3_Bonus2#2x3_Bonus"; r[348] = "#L#T#5"; r[349] = "#5#1#2x2_Bonus"; r[350] = "#Ecke3_Bonus2#2#4"; r[351] = "#1#1#Z"; r[352] = "#3#T#3x3"; r[353] = "#T#Ecke3#Ecke3"; r[354] = "#2#1#3"; r[355] = "#3#2#3"; r[356] = "#X#1_Bonus1#Ecke3"; r[357] = "#T#3x3_Bonus1#4_Bonus"; r[358] = "#Ecke2#3#Z"; r[359] = "#Ecke2#3#3x3_Bonus3"; r[360] = "#Ecke2#1#1"; r[361] = "#Ecke2#2#4_Bonus"; r[362] = "#4#3x3_Bonus2#1"; r[363] = "#Ecke2#Ecke3#T"; r[364] = "#2x3_Bonus#J:......444....L....4......"; r[365] = "#3#5#Ecke2"; r[366] = "#1#3x3_Bonus2#Ecke3_Bonus1B"; r[367] = "#Ecke3_Bonus2#X#4"; r[368] = "#1#2Dots#1"; r[369] = "#Ecke3_Bonus1B#2x2_Bonus#1"; r[370] = "#4#3#4_Bonus"; r[371] = "#Ecke3_Bonus2#X#2x2_Bonus"; r[372] = "#3#Ecke2#T"; r[373] = "#5#5#T"; r[374] = "#3#3x3_Bonus1#X"; r[375] = "#2x3#2x3_Bonus#Ecke2"; r[376] = "#Z#2x2#Ecke2"; r[377] = "#Ecke3_Bonus1A#Z#Ecke3"; r[378] = "#Z#3x3_Bonus3#T"; r[379] = "#1#T#2Dots"; r[380] = "#4#5#Ecke2"; r[381] = "#2x2#2#4"; r[382] = "#3#Ecke2#1"; r[383] = "#X#2#Ecke3_Bonus1B"; r[384] = "#3x3_Bonus2#1#4"; r[385] = "#2x2:............S............#L"; r[386] = "#2#5#T"; r[387] = "#1_Bonus1#J#T"; r[388] = "#1#1#T"; r[389] = "#1#Ecke3#T"; r[390] = "#3#3#4_Bonus"; r[391] = "#L#2x2_Bonus#Ecke2"; r[392] = "#5#T#4"; r[393] = "#Z#Ecke3#Ecke2"; r[394] = "#L#1_Bonus1#4"; r[395] = "#1_Bonus1#1#2"; r[396] = "#2#T#5"; r[397] = "#3#Ecke2#Ecke3_Bonus2"; r[398] = "#Ecke2#2:............L............"; r[399] = "#1_Bonus1#3x3_Bonus1#Z"; r[400] = "#4#2#2"; r[401] = "#Z#3x3#1_Bonus1"; r[402] = "#Ecke2#2x2_Bonus#T"; r[403] = "#4#1#L"; r[404] = "#1#5#Ecke2"; r[405] = "#3#2#2x3"; r[406] = "#3x3_Bonus2#Ecke2#Ecke3_Bonus1B"; r[407] = "#3#T#Z"; r[408] = "#1_Bonus1#3#2"; r[409] = "#3x3_Bonus2#Ecke2#4"; r[410] = "#Ecke3_Bonus1B#5#3"; r[411] = "#J#4#Ecke2"; r[412] = "#5#4#4"; r[413] = "#4#5#5"; r[414] = "#3x3#J#4_Bonus"; r[415] = "#Ecke2#Ecke2#Ecke2"; r[416] = "#3x3_Bonus1#T#4"; r[417] = "#Ecke3#5#1_Bonus1"; r[418] = "#T#T#2"; r[419] = "#2Dots#Ecke2#5"; r[420] = "#3x3#2x3_Bonus#1"; r[421] = "#2Dots#4#3x3_Bonus1"; r[422] = "#2#2Dots#3x3"; r[423] = "#5#4#3"; r[424] = "#3#T#Ecke3_Bonus2"; r[425] = "#1#2#T"; r[426] = "#5#1_Bonus1#T"; r[427] = "#5#Ecke2#Ecke2"; r[428] = "#2x3_Bonus#1_Bonus1#4_Bonus"; r[429] = "#3#Ecke3#2"; r[430] = "#3x3_Bonus3#1_Bonus1#4"; r[431] = "#T#2#3"; r[432] = "#2:..1....1....L....1.......#L"; r[433] = "#2#S#2x3_Bonus"; r[434] = "#1#2Dots#T"; r[435] = "#Ecke3#4#4_Bonus"; r[436] = "#5#3x3_Bonus1#1"; r[437] = "#J#T#T"; r[438] = "#3#Ecke3_Bonus1B#3x3"; r[439] = "#T#3#4"; r[440] = "#J#T#5"; r[441] = "#3#X#Ecke3_Bonus1A"; r[442] = "#3x3#L#Ecke3"; r[443] = "#4#2x2#3"; r[444] = "#3x3_Bonus3#5#4"; r[445] = "#2#Ecke2#1_Bonus1"; r[446] = "#2x2_Bonus#3x3_Bonus1#1"; r[447] = "#1_Bonus1#2x3#2x3"; r[448] = "#3x3_Bonus3#3x3_Bonus1#3"; r[449] = "#Ecke3_Bonus2#3x3_Bonus3#4"; r[450] = "#Ecke3#2x2_Bonus#5"; r[451] = "#2x2_Bonus#3#3"; r[452] = "#2x3#2#1_Bonus1"; r[453] = "#2Dots#Ecke3#3"; r[454] = "#Ecke3_Bonus2#4#L"; r[455] = "#4#Z#3"; r[456] = "#1#1_Bonus1#2"; r[457] = "#3x3_Bonus3#Ecke3_Bonus1A#S"; r[458] = "#1_Bonus1#Ecke2#3"; r[459] = "#4#T#Ecke3"; r[460] = "#4#Ecke3_Bonus1B#Ecke3_Bonus1B"; r[461] = "#3x3_Bonus3#4#Ecke3"; r[462] = "#T#X#4_Bonus"; r[463] = "#2#Ecke3#T"; r[464] = "#3x3_Bonus1#T#3x3_Bonus3"; r[465] = "#Ecke3_Bonus1B#J#T"; r[466] = ":...........L6....66......#2#2x3"; r[467] = "#2x2#4#Ecke2"; r[468] = "#Ecke3#1_Bonus1#X"; r[469] = "#2x2#4#T"; r[470] = "#1#1#4"; r[471] = "#3#4#3"; r[472] = "#Ecke3_Bonus2#2Dots#Ecke2"; r[473] = "#2x3_Bonus#Ecke3#2x2"; r[474] = "#1_Bonus1#Ecke3#2"; r[475] = "#Ecke2#2Dots#5"; r[476] = "#1_Bonus1#3#2x3"; r[477] = "#5#2#3"; r[478] = "#X#2x3#2x3"; r[479] = "#Ecke3_Bonus2#2#1"; r[480] = "#Ecke3#2x2_Bonus#4"; r[481] = "#Ecke2#Ecke2#Ecke2"; r[482] = "#Ecke2#3#Ecke3"; r[483] = "#T#4#3x3"; r[484] = "#3#3x3_Bonus3#1_Bonus1"; r[485] = "#Ecke3#2#5"; r[486] = "#3x3#4#2Dots"; r[487] = "#4#2#Z"; r[488] = "#2#1#3"; r[489] = "#Ecke3_Bonus1A#1:.......5....55...S......."; r[490] = "#3#X#Ecke2"; r[491] = "#4#2x3_Bonus#Ecke3"; r[492] = "#T#2x3#Ecke3_Bonus2"; r[493] = "#4#2x2#X"; r[494] = "#1_Bonus1#Ecke2#T"; r[495] = "#3x3_Bonus2#5#3"; r[496] = "#1#Ecke2#2x2_Bonus"; r[497] = "#Ecke3_Bonus2#T#3"; r[498] = "#T#1#Ecke2"; r[499] = "#3x3#2#J"; r[500] = ":......5.5...L...5.5......#Ecke2#3"; r[501] = "#2x3_Bonus#4#5"; r[502] = "#2x3_Bonus#2#Ecke3_Bonus1A"; r[503] = "#T#5#2x3_Bonus"; r[504] = "#2#Ecke3#Ecke2"; r[505] = "#Ecke2#2x2_Bonus#Ecke3"; r[506] = "#3x3_Bonus3#Slash#T"; r[507] = "#2x3_Bonus#Ecke3#T"; r[508] = "#Ecke3_Bonus1A#Ecke3_Bonus1A#3x3_Bonus1"; r[509] = "#Ecke2#3#5"; r[510] = "#4#2x2#Ecke2"; r[511] = "#T#2x3#Ecke3"; r[512] = "#Ecke3#Z#J"; r[513] = "#T#T#T"; r[514] = "#Ecke2#1#5"; r[515] = "#Z#Ecke3#4"; r[516] = "#1_Bonus1#T#T"; r[517] = "#3#J#5"; r[518] = "#3#4#5"; r[519] = "#3x3_Bonus1#2#3"; r[520] = "#3x3_Bonus3#Z#Slash"; r[521] = "#3x3_Bonus3#Ecke2#S"; r[522] = "#Ecke3_Bonus1B#1#5"; r[523] = "#1#3x3_Bonus3#1"; r[524] = "#Slash#T#Ecke3"; r[525] = "#T#3x3#3"; r[526] = "#1_Bonus1#T#3x3_Bonus2"; r[527] = "#T#S#Ecke3_Bonus1B"; r[528] = "#T#Ecke3_Bonus2#4"; r[529] = "#4_Bonus#Ecke3#3"; r[530] = "#2Dots#3x3_Bonus2#3"; r[531] = "#Ecke3_Bonus1A#4#2Dots"; r[532] = "#1#2#1"; r[533] = "#3#2x3:.......5...5L5..........."; r[534] = "#X#2Dots#3"; r[535] = "#1#1_Bonus1#4"; r[536] = "#5#Ecke2#Ecke3"; r[537] = "#J#1#4_Bonus"; r[538] = "#S#2x3#3x3"; r[539] = "#1_Bonus1#Ecke2:............S............"; r[540] = "#Z#T#2"; r[541] = "#5#Ecke3#1"; r[542] = "#Ecke2#Ecke3_Bonus1B#T"; r[543] = "#2#4#Ecke2"; r[544] = "#3x3_Bonus1#Ecke2#4_Bonus"; r[545] = "#Ecke3#Ecke2#2Dots"; r[546] = "#1_Bonus1#L#T"; r[547] = "#Slash#2Dots#L"; r[548] = "#2x2#T#1"; r[549] = "#1#J#2x3_Bonus"; r[550] = "#Ecke2#4#Ecke3"; r[551] = "#4#4#Ecke3"; r[552] = "#4#Ecke2#3"; r[553] = "#4#Ecke2#4"; r[554] = "#2x2_Bonus#2x3#J"; r[555] = "#1_Bonus1#2x3#Ecke3_Bonus1A"; r[556] = "#1_Bonus1#J#Ecke2"; r[557] = "#3x3#Z#T"; r[558] = "#3x3_Bonus1#2x2_Bonus#Ecke2"; r[559] = "#4_Bonus#5#T"; r[560] = "#3x3_Bonus3#Ecke3_Bonus2#Ecke2"; r[561] = "#5#1#4"; r[562] = "#1#3#2x3_Bonus"; r[563] = "#1_Bonus1#1_Bonus1#4"; r[564] = "#2#Ecke2#J"; r[565] = "#Ecke2#Z#X"; r[566] = "#J#1_Bonus1#1"; r[567] = "#1_Bonus1#X:..........2L222.........."; r[568] = "#2#4#S"; r[569] = "#Ecke2#X#4_Bonus"; r[570] = "#3#1_Bonus1#T"; r[571] = "#3x3#2x2_Bonus#3"; r[572] = "#4#3#4"; r[573] = "#1#T#X"; r[574] = "#T#Ecke2#3x3"; r[575] = "#Ecke3#5#Ecke3_Bonus1B"; r[576] = "#4#2x3_Bonus#T"; r[577] = "#2x3_Bonus#Ecke3_Bonus1B#L"; r[578] = "#S#1#Ecke2"; r[579] = "#X#4#T"; r[580] = "#1_Bonus1#1_Bonus1#Ecke3_Bonus1A"; r[581] = "#2#5#Ecke3"; r[582] = "#2#2x3#2"; r[583] = "#S#2#5"; r[584] = "#4#4#Z"; r[585] = "#2#Ecke2#1_Bonus1"; r[586] = "#4#5#2x2"; r[587] = "#T#T#1"; r[588] = "#J#Ecke3_Bonus1A#Ecke2"; r[589] = "#2x3_Bonus#Ecke3_Bonus1B#4"; r[590] = "#5#4#Ecke2"; r[591] = "#4#4#1"; r[592] = "#2x2#2x2#5"; r[593] = "#4#1_Bonus1#T"; r[594] = "#T#Ecke2#Ecke3_Bonus1B"; r[595] = "#5#3#X"; r[596] = "#Ecke3#Ecke2#T"; r[597] = "#Ecke3#2#Slash"; r[598] = "#3#4#Slash"; r[599] = "#2#Ecke2#3x3_Bonus1"; r[600] = "#3#2x3#1_Bonus1"; r[601] = "#X:............L............#Z"; r[602] = "#Ecke3#T#2Dots"; r[603] = "#2#1_Bonus1#5"; r[604] = "#1_Bonus1#5#T"; r[605] = "#2#1#2"; r[606] = "#2#T#Ecke3_Bonus1A"; r[607] = "#4#5#2"; r[608] = "#3x3_Bonus3#T#2x2_Bonus"; r[609] = "#S#3#3"; r[610] = "#1#T#2x3"; r[611] = "#4#Z#T"; r[612] = "#3#1#3x3"; r[613] = "#Ecke2#T#Ecke3"; r[614] = "#5#2x3#Ecke2"; r[615] = "#4_Bonus#Ecke3_Bonus2#Ecke3_Bonus1B"; r[616] = "#X#2#Ecke2"; r[617] = "#T#2Dots#Ecke3_Bonus2"; r[618] = "#X#3x3_Bonus3#T"; r[619] = "#1#J#2x2_Bonus"; r[620] = "#Ecke3_Bonus1B#5#5"; r[621] = "#3x3_Bonus3#2x2#T"; r[622] = "#2x2_Bonus#Ecke3_Bonus2#Ecke3"; r[623] = "#4#3x3_Bonus1#T"; r[624] = "#3x3#1#3"; r[625] = "#4#2Dots#3x3_Bonus3"; r[626] = ":............S4....4......#2x2#2x2_Bonus"; r[627] = "#J#1_Bonus1#Z"; r[628] = "#J#4#Z"; r[629] = "#3#2#2x2_Bonus"; r[630] = "#T#J#Ecke2"; r[631] = "#3x3_Bonus3#1#T"; r[632] = "#T#Ecke3_Bonus2#Ecke2"; r[633] = "#3#2#1"; r[634] = "#4#3#3"; r[635] = "#1:.......5....L5...5.......#3x3_Bonus1"; r[636] = "#3#5#T"; r[637] = "#1#Ecke2#3x3_Bonus1"; r[638] = "#1#4#1"; r[639] = "#2#4#3x3"; r[640] = "#3x3_Bonus2#4#4_Bonus"; r[641] = "#3x3_Bonus1#1#Ecke3_Bonus2"; r[642] = "#Ecke3#1_Bonus1#T"; r[643] = "#4_Bonus#Ecke2#J"; r[644] = "#Ecke3#2x2#2x3_Bonus"; r[645] = "#Ecke3_Bonus1B#Ecke2#Ecke3"; r[646] = "#Ecke3_Bonus1B#X#1"; r[647] = "#Z#Z#3"; r[648] = "#4#4#Ecke3"; r[649] = "#4#2x3_Bonus#T"; r[650] = "#2#Z#X"; r[651] = "#Ecke2#T#5"; r[652] = "#Ecke3#Ecke3_Bonus2#2"; r[653] = "#5#5#Ecke3"; r[654] = "#T#3#2Dots"; r[655] = "#2x2_Bonus#2Dots#2"; r[656] = "#T#Ecke3_Bonus1B#3x3_Bonus2"; r[657] = "#Ecke2#T#T"; r[658] = "#Ecke3_Bonus1B#1_Bonus1#Ecke3_Bonus2"; r[659] = "#T#3x3_Bonus2#3x3_Bonus2"; r[660] = "#5#2#2x3"; r[661] = "#1_Bonus1#T#Ecke3"; r[662] = "#3#T#4"; r[663] = "#1#1#Ecke2"; r[664] = "#3#5#S"; r[665] = "#T#2#4"; r[666] = "#3#3#Ecke2"; r[667] = "#Ecke2#X#T"; r[668] = "#4#Ecke3_Bonus1A#2"; r[669] = ":..........L111...........#Ecke3#Ecke3_Bonus2"; r[670] = "#Z#2x2#Ecke3"; r[671] = "#2x3#3#T"; r[672] = "#Ecke2#Ecke3#1"; r[673] = "#3x3#S#5"; r[674] = "#Ecke3_Bonus1A#Ecke3_Bonus1B#J"; r[675] = "#1#Ecke3#Ecke2"; r[676] = "#4#2#2x2_Bonus"; r[677] = "#T#5#3"; r[678] = "#4#5#2x3_Bonus"; r[679] = "#L#5#1"; r[680] = "#3#3#4"; r[681] = "#3x3_Bonus2#3x3_Bonus3#2"; r[682] = "#2#X#X"; r[683] = "#1_Bonus1#S#3"; r[684] = "#5#2#Ecke3_Bonus1A"; r[685] = "#Ecke3_Bonus1B#T#1"; r[686] = "#Ecke3_Bonus2#4#2x2_Bonus"; r[687] = "#2#1_Bonus1#5"; r[688] = "#5#5#S"; r[689] = "#J#2x2_Bonus#1_Bonus1"; r[690] = "#J#J#3x3"; r[691] = "#3x3:.......5...S5....5.......#4_Bonus"; r[692] = "#3x3#4#4"; r[693] = "#Ecke3#L:......33S..333..333......"; r[694] = "#Ecke3_Bonus2#3#Z"; r[695] = "#1#2x2#4"; r[696] = "#1#Ecke2#1"; r[697] = "#Ecke3_Bonus2#1_Bonus1#Ecke3"; r[698] = "#J#Ecke3#2"; r[699] = "#4#1#5"; r[700] = "#3#T#3"; r[701] = "#L#Ecke3#5"; r[702] = "#5#Ecke2#T"; r[703] = "#4_Bonus:..........L111...........#T"; r[704] = "#Ecke2#S#3"; r[705] = "#Ecke2#4_Bonus#2"; r[706] = "#2x2_Bonus#1#2x2_Bonus"; r[707] = "#T:......S33..333..333......#2x3"; r[708] = "#T#2#5"; r[709] = "#Ecke3#T#1"; r[710] = "#X#2#T"; r[711] = "#3x3_Bonus3#3x3_Bonus1#S"; r[712] = "#4#2#Ecke3"; r[713] = "#4_Bonus#1#3"; r[714] = "#Ecke3_Bonus1A#3x3_Bonus2#4"; r[715] = "#L#Ecke3_Bonus2#3x3"; r[716] = "#1#1#2x2"; r[717] = "#3#3x3_Bonus1#4"; r[718] = "#5#Ecke3#T"; r[719] = "#Ecke3_Bonus2#Ecke3_Bonus2#2"; r[720] = "#2x3#X#T"; r[721] = "#T#Ecke3#2"; r[722] = "#X#4_Bonus#Z"; r[723] = "#4_Bonus#1#2"; r[724] = "#2#3x3#2x3"; r[725] = "#1_Bonus1#Ecke2#3x3"; r[726] = "#Ecke3#T#Slash"; r[727] = "#3x3_Bonus2#Ecke2#3"; r[728] = "#T#2Dots#3"; r[729] = "#2Dots#3#T"; r[730] = "#Z#2x2#Ecke3_Bonus1A"; r[731] = "#T#4_Bonus#Ecke2"; r[732] = "#L#Ecke3_Bonus2#J"; r[733] = "#T#3#1_Bonus1"; r[734] = "#4#2x3#Ecke3"; r[735] = "#2#3x3#T"; r[736] = "#4#1#3x3_Bonus3"; r[737] = "#1:......5.5...4...5.L......#2x2"; r[738] = "#Ecke3#4#3x3_Bonus2"; r[739] = "#T#4#3x3"; r[740] = "#L#Ecke3#Ecke2"; r[741] = "#3x3_Bonus1#Slash#S"; r[742] = "#2Dots#3x3#1"; r[743] = "#Ecke2#3x3_Bonus1#4"; r[744] = "#2#2Dots#4"; r[745] = "#Z#2x3#1_Bonus1"; r[746] = "#4_Bonus#5#1_Bonus1"; r[747] = "#T#3x3_Bonus4#3x3_Bonus1"; r[748] = "#2x3#1#Z"; r[749] = "#3x3#Ecke3_Bonus1B#3"; r[750] = "#2Dots#Z#S"; r[751] = "#3#Ecke3#S"; r[752] = "#Ecke3_Bonus1B#4#3x3_Bonus1"; r[753] = "#Ecke2#Ecke3#T"; r[754] = "#4#S#1_Bonus1"; r[755] = "#4#Ecke3#Ecke3"; r[756] = "#T#T#1"; r[757] = "#2#Ecke2#3"; r[758] = "#Ecke3#Ecke2#2x3_Bonus"; r[759] = "#Ecke3_Bonus2#3x3_Bonus3#3"; r[760] = "#2x2#1#2x2_Bonus"; r[761] = "#3#4#3x3_Bonus1"; r[762] = "#4_Bonus#1#2x2"; r[763] = "#5#3#T"; r[764] = "#Z#3x3_Bonus2#1_Bonus1"; r[765] = "#3x3_Bonus1#4#T"; r[766] = "#3x3#T#T"; r[767] = "#1#1#Z"; r[768] = "#Ecke3#2x3#3"; r[769] = "#Ecke2#Ecke3_Bonus1B#T"; r[770] = "#4#Ecke3#2"; r[771] = ":......111..11L...........#5#3x3_Bonus1"; r[772] = "#Ecke3_Bonus1A#4#Z"; r[773] = "#3#Ecke2#4"; r[774] = "#1_Bonus1#T#3x3"; r[775] = "#2#T#3"; r[776] = "#4#4#1_Bonus1"; r[777] = "#Ecke3#Z#2x2"; r[778] = "#4_Bonus#3#T"; r[779] = "#4_Bonus#2x2#T"; r[780] = "#Ecke3#Ecke3_Bonus2#L"; r[781] = "#Ecke2#1#Ecke3_Bonus1B"; r[782] = "#4_Bonus#3x3_Bonus2#T"; r[783] = "#J#Ecke2#2x3_Bonus"; r[784] = "#5#T#Ecke3_Bonus1B"; r[785] = "#4#1_Bonus1#Ecke2"; r[786] = "#1#3#1"; r[787] = "#4#1#3x3_Bonus1"; r[788] = "#2Dots#Ecke2#2x2_Bonus"; r[789] = "#1#4#5"; r[790] = "#Ecke3#1_Bonus1#X"; r[791] = "#4#Ecke2#3"; r[792] = "#3#2x3_Bonus#Ecke3_Bonus1B"; r[793] = "#Ecke3#T#T"; r[794] = "#4#2#Ecke2"; r[795] = "#Ecke3_Bonus2#2Dots#T"; r[796] = "#T#Ecke2#3"; r[797] = "#4#4#5"; r[798] = "#Ecke2#Ecke2#2x2_Bonus"; r[799] = "#1#Ecke2#2"; r[800] = "#X#T#3"; r[801] = "#J#X#Ecke2"; r[802] = "#5#X#Ecke2"; r[803] = "#T#2x2_Bonus#3x3"; r[804] = "#2#Ecke3_Bonus1B:...........11L..........."; r[805] = "#2x2_Bonus#3#Ecke3"; r[806] = "#3#Ecke2#5"; r[807] = "#Ecke3#2x3_Bonus#Ecke2"; r[808] = "#Z#2x2_Bonus#2Dots"; r[809] = "#4#Ecke3#4"; r[810] = "#3#4_Bonus#L"; r[811] = "#3x3_Bonus3#3#4"; r[812] = "#Ecke3#T#2x3"; r[813] = "#1_Bonus1#Ecke2#1"; r[814] = "#Ecke3_Bonus2#Ecke2#Ecke3_Bonus1B"; r[815] = "#1_Bonus1#2Dots#Ecke2"; r[816] = "#5#1_Bonus1#Ecke3"; r[817] = "#5#3#Ecke2"; r[818] = "#3x3_Bonus3#X#1"; r[819] = "#4#S#5"; r[820] = "#Ecke3#T#3x3_Bonus2"; r[821] = "#Ecke2#Z#Ecke3"; r[822] = "#2#2Dots#3"; r[823] = "#1#5#4"; r[824] = "#3x3_Bonus3#Ecke3_Bonus2#S"; r[825] = "#2x2_Bonus#4#1_Bonus1"; r[826] = "#2x3#2#4"; r[827] = "#J#3x3_Bonus4#2"; r[828] = "#3x3_Bonus1#Z#L"; r[829] = "#1_Bonus1#Ecke2#1"; r[830] = "#Ecke3#2x3_Bonus#2x2"; r[831] = "#Ecke2#3#4_Bonus"; r[832] = "#1_Bonus1#Ecke3#Ecke3"; r[833] = "#2x3_Bonus#J#2x2"; r[834] = "#2x2_Bonus#2x3_Bonus#T"; r[835] = "#Ecke2#T#Z"; r[836] = "#Ecke3_Bonus1B#2x3_Bonus#5"; r[837] = "#1#Ecke3#Z"; r[838] = "#5:.......1....1....L.......#S"; r[839] = "#Slash#2#3"; r[840] = "#1_Bonus1#2Dots#Slash"; r[841] = "#Ecke3_Bonus2#2#3x3_Bonus1"; r[842] = "#2#5#Ecke2"; r[843] = "#BigSlash#2x3_Bonus#Ecke3"; r[844] = "#T#2x2#2x3_Bonus"; r[845] = "#2#5#Ecke3_Bonus1A"; r[846] = "#3x3#J#2x3"; r[847] = "#Ecke3#Ecke2#Ecke3"; r[848] = "#Ecke3#1_Bonus1#Ecke2"; r[849] = "#Ecke3#X#T"; r[850] = "#Ecke3_Bonus1A#1_Bonus2#Slash"; r[851] = "#5#1#T"; r[852] = "#J#Slash#Ecke3_Bonus1B"; r[853] = "#L#Ecke2#Ecke3"; r[854] = "#4#2x3#J"; r[855] = "#2#1#3x3_Bonus3"; r[856] = "#L#Ecke2#Z"; r[857] = "#2#1#3x3_Bonus1"; r[858] = "#3#2x2#3x3_Bonus2"; r[859] = "#2#3#Ecke3_Bonus1A"; r[860] = "#Ecke2#2x2#3"; r[861] = "#T#3x3_Bonus4#2x2_Bonus"; r[862] = "#Ecke3#1#2"; r[863] = "#Z#Ecke3_Bonus2#1"; r[864] = "#T#Ecke2#4"; r[865] = "#Ecke3_Bonus2#3x3_Bonus1#T"; r[866] = "#Slash#Z#3x3_Bonus3"; r[867] = "#2x3_Bonus#4#1_Bonus2"; r[868] = "#Ecke3_Bonus1A#Ecke3#3"; r[869] = ":.......5...5S....5.......#L#2"; r[870] = "#Ecke2#1#2x2"; r[871] = "#Ecke2#T#J"; r[872] = "#5:.......5...L5....5.......#4"; r[873] = "#2#S#2"; r[874] = "#2#Ecke3#2x2_Bonus"; r[875] = "#T#T#2"; r[876] = "#4#1_Bonus2#Ecke3_Bonus1A"; r[877] = "#2x3_Bonus#2x2_Bonus#Ecke3"; r[878] = "#3x3#Ecke2#2x2_Bonus"; r[879] = "#3x3_Bonus4#5#4"; r[880] = "#5#T#J"; r[881] = "#Ecke3#2#T"; r[882] = "#4#1#2x3"; r[883] = "#3x3_Bonus4#Ecke3_Bonus1B#4_Bonus"; r[884] = "#T#3#2"; r[885] = "#T#3#3"; r[886] = "#5#Ecke3#2x2_Bonus"; r[887] = "#Ecke3#Ecke3#3"; r[888] = "#2x2_Bonus#5#X"; r[889] = "#Ecke3#T#3"; r[890] = "#2x2#5#1"; r[891] = "#J#Ecke3_Bonus2#2"; r[892] = "#Ecke3_Bonus2#1_Bonus1#3x3_Bonus2"; r[893] = "#2x2_Bonus#BigSlash#3"; r[894] = "#2#2#3x3_Bonus2"; r[895] = "#T#Ecke3_Bonus1B#5"; r[896] = "#3x3#Ecke2#4"; r[897] = "#4#3x3_Bonus4#Ecke3"; r[898] = "#Ecke2#X#Ecke3_Bonus1A"; r[899] = "#2x2#3x3_Bonus4#5"; r[900] = "#T#Ecke3_Bonus1B#J"; r[901] = "#J#Ecke3_Bonus1B#2"; r[902] = "#3#Ecke2#T"; r[903] = "#1_Bonus1#3x3_Bonus4#3"; r[904] = "#1#1#1_Bonus2"; r[905] = "#3x3_Bonus4#2x3_Bonus#L"; r[906] = ":............L............#X#J"; r[907] = "#Slash#T#Z"; r[908] = "#Ecke2#3x3_Bonus1#3"; r[909] = "#3x3#2x3_Bonus#T"; r[910] = "#1_Bonus1#Ecke3_Bonus1A#1"; r[911] = "#2#3#Ecke2"; r[912] = "#3#1_Bonus2#4"; r[913] = "#2Dots#Ecke2#T"; r[914] = "#Ecke3#Ecke3_Bonus1A#2"; r[915] = "#BigSlash#Slash#T"; r[916] = "#S#T#3x3"; r[917] = "#5#Ecke3#5"; r[918] = "#1_Bonus1#Ecke2#3x3_Bonus1"; r[919] = "#T#1#4_Bonus"; r[920] = "#2Dots#Ecke3_Bonus1A#5"; r[921] = "#Ecke3_Bonus1B#Ecke3_Bonus2#4_Bonus"; r[922] = "#T#3#Ecke2"; r[923] = "#4#1_Bonus2#X"; r[924] = "#BigSlash#T#2Dots"; r[925] = "#3x3_Bonus3#1_Bonus2#3"; r[926] = "#2#S#1_Bonus1"; r[927] = "#3#3#1"; r[928] = "#1_Bonus1#1#Z"; r[929] = "#2x2#1#1"; r[930] = "#3#2x3#Slash"; r[931] = "#4#Ecke2#3"; r[932] = "#2Dots#3#Ecke3"; r[933] = "#1_Bonus2#1_Bonus2#T"; r[934] = "#1_Bonus2#5#3x3_Bonus1"; r[935] = "#J#2x3#3"; r[936] = "#5#Slash#BigSlash"; r[937] = "#2x2#Ecke3_Bonus1A#3"; r[938] = "#X#3#Ecke2"; r[939] = "#Ecke2#Ecke3_Bonus2:............L............"; r[940] = "#L#3#T"; r[941] = "#1_Bonus2#T#T"; r[942] = "#3#X#Ecke3"; r[943] = "#2#3x3_Bonus1#T"; r[944] = "#3x3_Bonus2#T#5"; r[945] = "#T#Ecke3#2x3_Bonus"; r[946] = "#S#3x3_Bonus1#Ecke2"; r[947] = "#T#5#3x3_Bonus3"; r[948] = ":......333..333..3S3......#1#3x3_Bonus3"; r[949] = "#Ecke3#T#2"; r[950] = "#Ecke3#4#Ecke2"; r[951] = "#Ecke2#Ecke3#1"; r[952] = "#3#4_Bonus#Slash"; r[953] = "#Ecke2#Ecke3_Bonus2#2Dots"; r[954] = "#3#3x3_Bonus4#Ecke2"; r[955] = "#1_Bonus2#4#1"; r[956] = "#T#Slash#BigSlash"; r[957] = "#3#3x3_Bonus2#Ecke2"; r[958] = "#2x3#3x3_Bonus1#Ecke2"; r[959] = "#3x3_Bonus4#1#Z"; r[960] = "#1#3#Ecke3_Bonus2"; r[961] = "#Ecke3#3x3_Bonus1#1_Bonus2"; r[962] = "#1_Bonus1#3#J"; r[963] = "#X#Ecke2#Ecke3_Bonus1A"; r[964] = "#2x3#T#2Dots"; r[965] = "#1_Bonus2#5#X"; r[966] = "#X#Ecke3#1_Bonus2"; r[967] = "#4#2Dots#T"; r[968] = "#1#2x3_Bonus#2"; r[969] = "#T#T#1_Bonus1"; r[970] = "#2#3#X"; r[971] = "#2x2#2#L"; r[972] = "#S#3x3#T"; r[973] = "#3x3_Bonus4#Ecke2:............L............"; r[974] = "#3#2#Z"; r[975] = "#T#Z#4"; r[976] = "#BigSlash#3x3#2"; r[977] = "#1#Ecke3_Bonus1B#BigSlash"; r[978] = "#1#1#Ecke3_Bonus1B"; r[979] = "#2x2_Bonus#1#Ecke3_Bonus1A"; r[980] = "#2#1_Bonus2#4"; r[981] = "#3#Ecke2#3x3_Bonus2"; r[982] = "#3#5#J"; r[983] = "#4_Bonus#T#Ecke2"; r[984] = "#T#3x3#5"; r[985] = "#4#1#3x3_Bonus4"; r[986] = "#X#3#S"; r[987] = "#1_Bonus1#1_Bonus1#5"; r[988] = "#3:......444....S....4......#J"; r[989] = "#T#2#2Dots"; r[990] = "#1_Bonus2#3#T"; r[991] = "#2Dots#Z#1"; r[992] = "#Ecke3_Bonus1A#S#Ecke2"; r[993] = "#Ecke2#X#4_Bonus"; r[994] = "#2x2#5#T"; r[995] = "#4#T#1_Bonus2"; r[996] = ":......5....S55...........#2x3#Ecke3"; r[997] = "#Ecke3_Bonus1B#5#3x3_Bonus1"; r[998] = "#Ecke2#Ecke2#3"; r[999] = "#Ecke2#L#4_Bonus"; r[1000] = "#Ecke2#T#3x3"; r[1001] = "#2x3_Bonus#2x2_Bonus#1_Bonus1"; r[1002] = "#1_Bonus1#Z#Ecke3_Bonus2"; r[1003] = "#Z#L#1_Bonus1"; r[1004] = "#5#4#Ecke2"; r[1005] = "#T#T#3"; r[1006] = "#3x3_Bonus3#2#BigSlash"; r[1007] = "#1#Ecke3_Bonus1A#2"; r[1008] = ":............L............#Ecke3#4_Bonus"; r[1009] = "#4#3x3_Bonus4#Ecke3"; r[1010] = "#1_Bonus2#J#Ecke3_Bonus2"; r[1011] = "#Ecke2#1#1_Bonus1"; r[1012] = "#X_Bonus#X_Bonus#S"; r[1013] = "#5#2#3x3_Bonus1"; r[1014] = "#3x3#1_Bonus2#3x3_Bonus3"; r[1015] = "#4#2x2_Bonus#2"; r[1016] = "#T#J#Ecke3"; r[1017] = "#1_Bonus2#3x3_Bonus3#T"; r[1018] = "#Ecke2#X_Bonus#3x3"; r[1019] = "#Ecke2#2x2_Bonus#1"; r[1020] = "#5#Ecke3#3x3"; r[1021] = "#3x3_Bonus1#5#L"; r[1022] = "#5#BigSlash#3x3_Bonus4"; r[1023] = "#T#Ecke2#5"; r[1024] = "#2#4#Ecke3_Bonus1A"; r[1025] = "#1#L#T"; r[1026] = "#4#3x3_Bonus4#1_Bonus2"; r[1027] = "#5#2x2#T"; r[1028] = "#X#4#2"; r[1029] = "#Ecke2#Z#Ecke3_Bonus1B"; r[1030] = "#T#T#3"; r[1031] = "#BigSlash#5#2x2"; r[1032] = "#Z#1_Bonus2#2"; r[1033] = "#4#Ecke2#5"; r[1034] = "#Ecke2#Ecke2#1"; r[1035] = "#Ecke3#2Dots#3"; r[1036] = "#4#3x3_Bonus2#Ecke3"; r[1037] = "#Ecke2#3x3_Bonus2#3x3_Bonus3"; r[1038] = "#L#S#3x3_Bonus4"; r[1039] = "#L#1#3"; r[1040] = "#L#L#Ecke2"; r[1041] = "#1_Bonus2#Ecke2:...........1L............"; r[1042] = "#2#X_Bonus#X_Bonus"; r[1043] = "#3x3_Bonus2#BigSlash#Ecke3_Bonus2"; r[1044] = "#2x2#3#3x3_Bonus1"; r[1045] = "#3x3_Bonus3#3#Ecke2"; r[1046] = "#L#Ecke3#2x2_Bonus"; r[1047] = "#2x3_Bonus#4#3"; r[1048] = "#5#5#L"; r[1049] = "#T#Ecke3_Bonus1A#Slash"; r[1050] = "#2x2_Bonus#1#3"; r[1051] = "#Ecke2#1_Bonus2#5"; r[1052] = "#3#2x2_Bonus#Ecke3_Bonus1B"; r[1053] = "#5#4#1_Bonus2"; r[1054] = "#3x3#3x3#3"; r[1055] = "#T#2x2_Bonus#1"; r[1056] = "#Ecke3_Bonus2#2Dots#5"; r[1057] = "#1#2x2_Bonus#3x3_Bonus2"; r[1058] = "#Z#1_Bonus2#X_Bonus"; r[1059] = "#1#X_Bonus#T"; r[1060] = "#T#3#Ecke2"; r[1061] = "#1_Bonus2#Z#L"; r[1062] = "#T#X_Bonus#2x2"; r[1063] = "#Ecke3#S#3"; r[1064] = "#3#Ecke2#1"; r[1065] = "#3x3#1_Bonus1#Ecke3"; r[1066] = "#Ecke3#2#3"; r[1067] = "#4#3#Ecke3_Bonus2"; r[1068] = "#2#1_Bonus2#3"; r[1069] = "#2x3_Bonus#5#4"; r[1070] = "#J#3#T"; r[1071] = "#Ecke3_Bonus1B#4_Bonus#3"; r[1072] = "#1_Bonus1#4#1"; r[1073] = "#3#4#5"; r[1074] = "#3x3_Bonus3#Ecke3_Bonus1A#Ecke2"; r[1075] = "#1:...........L1............#1"; r[1076] = "#4#4#2"; r[1077] = "#Ecke2#Ecke2#X_Bonus"; r[1078] = "#4#1_Bonus1#2x3_Bonus"; r[1079] = "#Ecke2#T#1_Bonus1"; r[1080] = "#Ecke2#X#2x3"; r[1081] = "#Ecke3#T#Ecke3"; r[1082] = "#5#Ecke3#X_Bonus"; r[1083] = "#S#S#3x3"; r[1084] = "#1#T#BigSlash"; r[1085] = "#2x2_Bonus#Ecke2#2"; r[1086] = "#2#Ecke3_Bonus1B#BigSlash"; r[1087] = "#3x3_Bonus2#1#2"; r[1088] = "#5#5#L"; r[1089] = "#4#2#2"; r[1090] = "#2x2_Bonus#3x3_Bonus1#2"; r[1091] = "#1#1_Bonus2#2Dots"; r[1092] = "#Z#Ecke3_Bonus1B#2x3"; r[1093] = "#BigSlash#4#Ecke3_Bonus1A"; r[1094] = "#2x2_Bonus#BigSlash#3x3_Bonus1"; r[1095] = "#5#Ecke3_Bonus1B#2x3"; r[1096] = "#3#T#Ecke3_Bonus2"; r[1097] = "#Slash#Ecke3_Bonus1B#BigSlash"; r[1098] = "#Ecke3_Bonus2#1#3x3_Bonus3"; r[1099] = "#2x2#1_Bonus1#3x3"; r[1100] = "#1_Bonus2#Ecke3_Bonus1B#1_Bonus2"; r[1101] = "#3x3_Bonus1#Ecke3_Bonus1B#T"; r[1102] = "#X#T#X"; r[1103] = "#Slash#1_Bonus1#1_Bonus2"; r[1104] = "#3#Slash#Ecke2"; r[1105] = "#1_Bonus1#X_Bonus#Ecke3"; r[1106] = "#X_Bonus#2#2Dots"; r[1107] = "#T#Ecke3#1"; r[1108] = "#Ecke3#BigSlash#T"; r[1109] = ":............L............#3#1"; r[1110] = "#4#3#2"; r[1111] = "#L#1_Bonus1#3x3_Bonus2"; r[1112] = "#Ecke2#J#L"; r[1113] = "#Ecke2:......S33..333..333......#3x3_Bonus1"; r[1114] = "#Ecke3_Bonus2#2x2_Bonus#3x3"; r[1115] = "#T#4#2x2_Bonus"; r[1116] = "#3#L#4"; r[1117] = "#1_Bonus1#2Dots#J"; r[1118] = "#1_Bonus2#Slash#Ecke3"; r[1119] = "#2x2_Bonus#2#3x3_Bonus3"; r[1120] = "#5#5#3"; r[1121] = "#Ecke3_Bonus2#1#3"; r[1122] = "#Ecke3_Bonus1B#L#1_Bonus1"; r[1123] = "#2#3#Ecke2"; r[1124] = "#5#Ecke3#Ecke3_Bonus1A"; r[1125] = "#3#3x3_Bonus1#T"; r[1126] = "#Ecke3_Bonus2#3x3_Bonus1#Slash"; r[1127] = "#X_Bonus#Ecke3#3x3_Bonus1"; r[1128] = "#Slash#S#1"; r[1129] = "#J#L#2x3"; r[1130] = "#Slash#3#4"; r[1131] = "#Ecke2#2#3x3_Bonus4"; r[1132] = "#2Dots#4_Bonus#2x3"; r[1133] = "#Z#T#2"; r[1134] = "#X_Bonus#4#1_Bonus1"; r[1135] = "#T#Ecke2#Ecke3"; r[1136] = "#Ecke2#Ecke3_Bonus1A#1"; r[1137] = "#T#3#1_Bonus2"; r[1138] = "#4#3#4_Bonus"; r[1139] = "#Ecke3_Bonus1A#Ecke2#Ecke2"; r[1140] = "#2#X#Ecke3"; r[1141] = "#Ecke2#3#2x3_Bonus"; r[1142] = "#Ecke2#Ecke3#S"; r[1143] = ":......5....55L...........#Ecke3#Slash"; r[1144] = "#2x3_Bonus#Ecke2#1"; r[1145] = "#3x3_Bonus2#T#Ecke3"; r[1146] = "#Z#Ecke3#Ecke3_Bonus2"; r[1147] = "#2x2_Bonus#1_Bonus1#L"; r[1148] = "#1_Bonus2#2x2#2x3_Bonus"; r[1149] = "#Ecke2#3x3_Bonus3#S"; r[1150] = "#2x2#T#S"; r[1151] = "#2#1_Bonus1#X"; r[1152] = "#4#Ecke3#2x3"; r[1153] = "#5#2#T"; r[1154] = "#3x3_Bonus1#Ecke2#Ecke2"; r[1155] = "#1#1#Ecke2"; r[1156] = "#1#S#Z"; r[1157] = "#3x3_Bonus4:.......4S...4............#5"; r[1158] = "#Ecke2#T#1_Bonus2"; r[1159] = "#4#Ecke3#T"; r[1160] = "#T#4#T"; r[1161] = "#X:...........1S............#1"; r[1162] = "#Ecke3#1#5"; r[1163] = "#3#Ecke2#T"; r[1164] = "#3#2x2_Bonus#5"; r[1165] = "#2Dots#2x2_Bonus#T"; r[1166] = "#2Dots#3x3_Bonus3#J"; r[1167] = "#BigSlash#3#S"; r[1168] = "#T#BigSlash#T"; r[1169] = "#3#4_Bonus#4_Bonus"; r[1170] = "#2#Ecke3#Ecke2"; r[1171] = "#Slash#T#Ecke3_Bonus1A"; r[1172] = "#Ecke3_Bonus1A#1_Bonus3#Ecke2"; r[1173] = "#1#T#Ecke3"; r[1174] = "#1_Bonus1#T#2x3_Bonus"; r[1175] = "#3#Ecke3_Bonus1A#Slash"; r[1176] = "#Ecke2#4#BigSlash"; r[1177] = "#3:..........11L1...........#Ecke3_Bonus1A"; r[1178] = "#3x3_Bonus4#4#3"; r[1179] = "#4#T#3x3"; r[1180] = "#2x2_Bonus#4_Bonus#2"; r[1181] = "#Ecke3#T#1_Bonus2"; r[1182] = "#2x2#Ecke3#4"; r[1183] = "#1#X_Bonus#1"; r[1184] = "#5#Ecke3#Ecke3"; r[1185] = "#2#3#2"; r[1186] = "#4#J#1_Bonus1"; r[1187] = "#Ecke2#1#T"; r[1188] = "#3#3#3"; r[1189] = "#3x3_Bonus3#2x3#X_Bonus"; r[1190] = "#3#3#BigSlash"; r[1191] = "#1_Bonus1#3#5"; r[1192] = "#3x3_Bonus3#Ecke2#3x3"; r[1193] = "#1#2x3_Bonus#BigSlash"; r[1194] = "#3:.......5....55...S.......#3x3"; r[1195] = "#X#2Dots#5"; r[1196] = "#1_Bonus3#4#3x3_Bonus4"; r[1197] = "#3#4#5"; r[1198] = "#L#X#BigSlash"; r[1199] = "#1_Bonus2#4#X"; r[1200] = "#3#T#BigSlash"; r[1201] = "#T#4#4"; r[1202] = "#1_Bonus1#3#5"; r[1203] = "#1#1#X"; r[1204] = "#4#Ecke3#3x3_Bonus2"; r[1205] = "#X#4#4_Bonus"; r[1206] = "#1_Bonus1#Ecke2#Ecke3"; r[1207] = "#4#Ecke3#T"; r[1208] = "#1_Bonus1#2#5"; r[1209] = "#5#T#3x3_Bonus4"; r[1210] = "#X#1#T"; r[1211] = "#1:..........111L...........#X"; r[1212] = "#1_Bonus3#2#1"; r[1213] = "#1_Bonus2#1_Bonus2#X_Bonus"; r[1214] = "#T#Z#1_Bonus2"; r[1215] = "#3#Ecke3#Ecke3"; r[1216] = "#3x3_Bonus2#2x2#3x3_Bonus1"; r[1217] = "#1_Bonus1#1#5"; r[1218] = "#3#2#2x3_Bonus"; r[1219] = "#Ecke3#3#T"; r[1220] = "#T#3x3_Bonus4#4"; r[1221] = "#4#4#2x2_Bonus"; r[1222] = "#X_Bonus#Ecke3#2"; r[1223] = "#Ecke2#Z#3x3_Bonus3"; r[1224] = "#T#Z#3x3_Bonus1"; r[1225] = "#2x2_Bonus#Ecke2#Ecke3"; r[1226] = "#L#5#1_Bonus2"; r[1227] = "#3x3_Bonus1#3#1_Bonus3"; r[1228] = ":......33...S3............#Z#2"; r[1229] = "#Ecke2#5#Ecke3"; r[1230] = "#Z#3x3_Bonus4#3x3"; r[1231] = "#T#2x3#3"; r[1232] = "#Ecke2#2x3_Bonus#2"; r[1233] = "#1_Bonus2#3x3_Bonus4#4"; r[1234] = "#1_Bonus1#4#3x3_Bonus2"; r[1235] = "#Ecke2#T#3"; r[1236] = "#T#Ecke2#3x3_Bonus1"; r[1237] = "#2#BigSlash#Ecke3_Bonus1A"; r[1238] = "#T#1_Bonus1#3x3_Bonus2"; r[1239] = "#1_Bonus2#1#4"; r[1240] = "#4_Bonus#1_Bonus3#3x3"; r[1241] = "#Ecke3#3#X_Bonus"; r[1242] = "#3x3_Bonus4#T#Ecke2"; r[1243] = "#3x3#2x3_Bonus#T"; r[1244] = "#Ecke2#4_Bonus#1_Bonus2"; r[1245] = "#Ecke3_Bonus2:............L............#BigSlash"; r[1246] = "#3x3#2Dots#Ecke2"; r[1247] = "#Ecke2#1#5"; r[1248] = "#2Dots#Ecke3_Bonus2#5"; r[1249] = "#Ecke2#2#4"; r[1250] = "#T#4#2x2_Bonus"; r[1251] = "#T#1_Bonus1#5"; r[1252] = "#1#Slash#4"; r[1253] = "#2x2#1_Bonus1#Ecke3_Bonus1A"; r[1254] = "#5#5#2x3"; r[1255] = "#T#1_Bonus1#3"; r[1256] = "#Ecke2#3x3_Bonus4#T"; r[1257] = "#X_Bonus#5#5"; r[1258] = "#T#Ecke3_Bonus1A#S"; r[1259] = "#5#3x3_Bonus1#2x3_Bonus"; r[1260] = "#1#3x3_Bonus1#3"; r[1261] = "#T#2x3_Bonus#Slash"; r[1262] = "#3x3_Bonus2#4#Ecke3"; r[1263] = "#T#Slash#4"; r[1264] = "#BigSlash#4#2x3"; r[1265] = "#Ecke3_Bonus2#2Dots#Ecke3"; r[1266] = "#Ecke2#X_Bonus#4_Bonus"; r[1267] = "#Ecke2#2Dots#3"; r[1268] = "#3#Ecke3_Bonus2#3x3_Bonus2"; r[1269] = "#1_Bonus1#3x3_Bonus1#J"; r[1270] = "#3x3#1#T"; r[1271] = "#2x3_Bonus#T#5"; r[1272] = "#Ecke3#3#Slash"; r[1273] = "#3#2x2#Ecke3_Bonus1B"; r[1274] = "#X#X_Bonus#Ecke3"; r[1275] = "#T#T#2x3"; r[1276] = "#3x3_Bonus4#X_Bonus#Ecke3_Bonus2"; r[1277] = "#Ecke2#1#2"; r[1278] = "#5#Ecke3_Bonus1A#3x3"; r[1279] = ":......333..L33..333......#1_Bonus1#1_Bonus1"; r[1280] = "#3x3_Bonus2#2x2#Slash"; r[1281] = "#3x3_Bonus2#1_Bonus2#X"; r[1282] = "#2#5#3x3_Bonus3"; r[1283] = "#T#3#2"; r[1284] = "#3#3x3_Bonus2#5"; r[1285] = "#T#T#4_Bonus"; r[1286] = "#2x2#1#2Dots"; r[1287] = "#2#T#5"; r[1288] = "#2#5#Ecke3_Bonus2"; r[1289] = "#Z#T#Ecke2"; r[1290] = "#3#T#2x3"; r[1291] = "#Ecke3_Bonus2#1#Ecke3"; r[1292] = "#1#4#X"; r[1293] = "#1#2#1"; r[1294] = "#2#Ecke3#3x3_Bonus4"; r[1295] = "#Ecke3_Bonus1B#Slash#3x3_Bonus4"; r[1296] = "#X_Bonus#1_Bonus2#Ecke3"; r[1297] = "#2x2#2#2"; r[1298] = "#BigSlash#T#3"; r[1299] = "#3#3#J"; r[1300] = "#1_Bonus1#Ecke3_Bonus1A#2Dots"; r[1301] = "#2x3#X_Bonus#Ecke3_Bonus2"; r[1302] = "#1_Bonus1#1_Bonus2#S"; r[1303] = "#2x2#1_Bonus1#4"; r[1304] = "#X#5#J"; r[1305] = "#4_Bonus#4#2x2"; r[1306] = "#1_Bonus2#3x3_Bonus1#S"; r[1307] = "#4#1#BigSlash"; r[1308] = "#Ecke3_Bonus2#T#Ecke2"; r[1309] = "#4#2x3#X"; r[1310] = "#5#Slash#3x3_Bonus4"; r[1311] = "#2#BigSlash#1_Bonus1"; r[1312] = "#3#1:.......1....1....L......."; r[1313] = "#1_Bonus1#4#2Dots"; r[1314] = "#T#5#Ecke3"; r[1315] = "#1_Bonus2#4_Bonus#Slash"; r[1316] = "#3x3#Slash#4"; r[1317] = "#2#T#Ecke2"; r[1318] = "#4#2#3x3_Bonus3"; r[1319] = "#Ecke2#3x3_Bonus1#4"; r[1320] = "#3x3_Bonus1#1_Bonus1#T"; r[1321] = "#Ecke3_Bonus1A#1#Ecke2"; r[1322] = "#3x3_Bonus1#1_Bonus2#Ecke3_Bonus2"; r[1323] = "#Ecke2#3x3_Bonus4#L"; r[1324] = "#X_Bonus#Z#2"; r[1325] = "#4_Bonus#2x3#2x2_Bonus"; r[1326] = "#5#3#Ecke3_Bonus1B"; r[1327] = "#5#BigSlash#Z"; r[1328] = "#2x2_Bonus#5#S"; r[1329] = "#5#X#3x3_Bonus2"; r[1330] = "#4_Bonus#Ecke3_Bonus1A#1"; r[1331] = "#1#2x2#3"; r[1332] = "#Ecke2#T#X_Bonus"; r[1333] = "#T#1#1"; r[1334] = "#Ecke2#L#Slash"; r[1335] = "#Ecke2#Slash#Ecke3"; r[1336] = "#4#1_Bonus2#S"; r[1337] = "#X_Bonus#4_Bonus#Ecke3_Bonus1B"; r[1338] = "#1_Bonus1#Slash#X_Bonus"; r[1339] = "#T#3x3_Bonus3#Ecke2"; r[1340] = "#1#Ecke3#2Dots"; r[1341] = "#Ecke2#Ecke2#3x3_Bonus1"; r[1342] = "#1_Bonus3#Slash#Ecke2"; r[1343] = "#Ecke3_Bonus2#S#X_Bonus"; r[1344] = "#4#2#2x2"; r[1345] = "#X_Bonus2#2Dots#2x3_Bonus"; r[1346] = "#S:.......L....1....1.......#X_Bonus2"; r[1347] = "#3#T#2x2"; r[1348] = "#Ecke2#Ecke2#Slash"; r[1349] = "#2#4#Ecke3_Bonus1B"; r[1350] = "#2x2#1_Bonus3#2"; r[1351] = "#3x3_Bonus3#Ecke3_Bonus2#Ecke2"; r[1352] = "#2#2x3#5"; r[1353] = "#2x2_Bonus#3#1_Bonus2"; r[1354] = "#X_Bonus2#T#1_Bonus2"; r[1355] = "#1_Bonus1#1_Bonus1#Ecke2"; r[1356] = "#2#Slash#3"; r[1357] = "#3#Ecke3_Bonus1B#3"; r[1358] = "#T#5#1_Bonus1"; r[1359] = "#Ecke3#Ecke3_Bonus2#3"; r[1360] = "#Ecke3#1_Bonus1#4_Bonus"; r[1361] = "#2Dots#2x3#1"; r[1362] = "#BigSlash#Ecke2#T"; r[1363] = "#4#2x3_Bonus#2x2_Bonus"; r[1364] = "#Ecke3_Bonus1A#T#3x3"; r[1365] = "#J#3x3_Bonus3#L"; r[1366] = ":......333..333..S33......#T#Ecke2"; r[1367] = "#3x3_Bonus2#2x3#1_Bonus1"; r[1368] = "#2#J#2x3_Bonus"; r[1369] = "#Ecke3#Ecke2#3x3_Bonus3"; r[1370] = "#2#Ecke3#X"; r[1371] = "#Ecke3#3#3x3_Bonus2"; r[1372] = "#5#X_Bonus2#3"; r[1373] = "#5#X_Bonus#2x3"; r[1374] = "#Slash#3#4"; r[1375] = "#T#1#1_Bonus1"; r[1376] = "#Slash#Ecke3#3"; r[1377] = "#5#2x2_Bonus#Ecke3"; r[1378] = "#3x3_Bonus4#4#2"; r[1379] = "#5#1_Bonus1#4"; r[1380] = "#1:............L............#J"; r[1381] = "#T#5#T"; r[1382] = "#4#2#T"; r[1383] = "#T#2#2"; r[1384] = "#3x3_Bonus4#2x3_Bonus#1_Bonus1"; r[1385] = "#3#Slash#3"; r[1386] = "#2#Ecke2#2Dots"; r[1387] = "#3x3_Bonus2#X#Ecke3"; r[1388] = "#4#1#X"; r[1389] = "#Ecke2#3x3_Bonus1#T"; r[1390] = "#X#4#Slash"; r[1391] = "#T#3x3_Bonus2#1_Bonus2"; r[1392] = "#Ecke3_Bonus1A#Z#1_Bonus2"; r[1393] = "#X#5#X"; r[1394] = "#1#5#Ecke2"; r[1395] = "#3#Ecke2#3"; r[1396] = "#2x3_Bonus#5#S"; r[1397] = "#1#1#Ecke2"; r[1398] = "#Ecke2#3x3_Bonus3#Ecke3_Bonus2"; r[1399] = "#3#3#Ecke3_Bonus2"; r[1400] = "#1_Bonus1#3#Ecke3_Bonus1B"; r[1401] = "#2#1_Bonus1#1"; r[1402] = "#Ecke3_Bonus2#Ecke2#1"; r[1403] = "#2#5#Ecke2"; r[1404] = "#S#J#1"; r[1405] = "#T#3#Ecke2"; r[1406] = "#1_Bonus3#J#1_Bonus1"; r[1407] = "#3x3_Bonus3#5#3x3_Bonus2"; r[1408] = "#Ecke2#Ecke3_Bonus1B#5"; r[1409] = "#4#4#4_Bonus"; r[1410] = "#1_Bonus1#T#3x3_Bonus3"; r[1411] = "#3#Ecke2#Ecke2"; r[1412] = "#X_Bonus2#3#Ecke2"; r[1413] = "#2#1#1_Bonus1"; r[1414] = ":.......5...55....L.......#3x3_Bonus4#Ecke2"; r[1415] = "#3#3x3_Bonus4#Ecke2"; r[1416] = "#2#2x3_Bonus#3x3"; r[1417] = "#3#1_Bonus1#3"; r[1418] = "#Ecke2#Ecke2#5"; r[1419] = "#4#2Dots#1_Bonus1"; r[1420] = "#3#1_Bonus1#3"; r[1421] = "#3#2x3#1"; r[1422] = "#3x3_Bonus2#J#X_Bonus2"; r[1423] = "#X_Bonus#L#L"; r[1424] = "#Slash#X#3x3_Bonus2"; r[1425] = "#1_Bonus1#2x2#L"; r[1426] = "#1_Bonus1#1_Bonus2#S"; r[1427] = "#2#J#3"; r[1428] = "#X#S#Z"; r[1429] = "#Ecke3#2#1"; r[1430] = "#5#4#5"; r[1431] = "#2#S#5"; r[1432] = "#Ecke2#3x3_Bonus2#J"; r[1433] = "#4#X_Bonus2#Slash"; r[1434] = "#4_Bonus#1_Bonus2#5"; r[1435] = "#4_Bonus#3x3_Bonus1#T"; r[1436] = "#2x3_Bonus#2Dots#1_Bonus2"; r[1437] = "#Z#T#1_Bonus1"; r[1438] = "#2#4#5"; r[1439] = "#1_Bonus2#Ecke2#1_Bonus1"; r[1440] = "#1_Bonus1#Ecke2#Ecke3"; r[1441] = "#2#1#1_Bonus2"; r[1442] = "#Slash#Ecke3_Bonus2#2"; r[1443] = "#3#2x2_Bonus#Ecke3_Bonus2"; r[1444] = "#2x3#5#2x3_Bonus"; r[1445] = "#X_Bonus#3#Ecke3"; r[1446] = "#BigSlash#Ecke3_Bonus1B#3x3_Bonus2"; r[1447] = "#2#4_Bonus:...........L6....66......"; r[1448] = "#Ecke3#5#2"; r[1449] = "#1_Bonus2#X_Bonus2#1"; r[1450] = "#2x3#1#2Dots"; r[1451] = "#BigSlash#1_Bonus2#1"; r[1452] = "#2#Ecke3#Slash"; r[1453] = "#L#1#1_Bonus3"; r[1454] = "#3#Ecke2#2"; r[1455] = "#Ecke2#2#S"; r[1456] = "#3#1_Bonus1#X_Bonus2"; r[1457] = "#Ecke3#3x3_Bonus3#2Dots"; r[1458] = "#Z#1_Bonus3#2"; r[1459] = "#Ecke2#Ecke2#Ecke2"; r[1460] = "#S#S#T"; r[1461] = "#5#3#T"; r[1462] = "#1#1_Bonus1#Ecke2"; r[1463] = "#1#X_Bonus2#BigSlash"; r[1464] = "#BigSlash#2#1"; r[1465] = "#Ecke3#Ecke3_Bonus1B#S"; r[1466] = "#2x2#Z#4"; r[1467] = "#2#Ecke3_Bonus1B#2Dots"; r[1468] = "#L#Ecke3#3"; r[1469] = "#4#Z#4"; r[1470] = "#J#1#1_Bonus1"; r[1471] = "#4#3#Z"; r[1472] = "#X_Bonus#Ecke2#2"; r[1473] = "#3x3#J#1"; r[1474] = "#L#5#4_Bonus"; r[1475] = "#5#Ecke3#4"; r[1476] = "#1#Ecke2#1"; r[1477] = "#X_Bonus2#X#Ecke2"; r[1478] = "#3#3x3_Bonus1#T"; r[1479] = "#T#T#T"; r[1480] = "#Ecke2#4_Bonus#J"; r[1481] = "#2:......5.5...L...5.5......#X_Bonus"; r[1482] = "#Ecke3_Bonus1A#3x3_Bonus2#1_Bonus2"; r[1483] = "#2x2_Bonus#T#3"; r[1484] = "#Ecke3#3x3#4"; r[1485] = "#1#2#5"; r[1486] = "#X_Bonus2#Ecke2#Ecke2"; r[1487] = "#3#Ecke2#4"; r[1488] = "#5#2x2_Bonus#T"; r[1489] = "#2Dots#Ecke2#X_Bonus"; r[1490] = "#1_Bonus3#2x3_Bonus#Z"; r[1491] = "#X_Bonus2#2#4_Bonus"; r[1492] = "#1_Bonus2#2x2_Bonus#1"; r[1493] = "#Ecke3_Bonus1B#X#S"; r[1494] = "#T#L#T"; r[1495] = "#Ecke2#1_Bonus2#Ecke2"; r[1496] = "#4_Bonus#Ecke3#Ecke3_Bonus2"; r[1497] = "#2x2_Bonus#5#S"; r[1498] = "#5#1_Bonus2#3x3_Bonus3"; r[1499] = "#Ecke3#3x3#Ecke3"; r[1500] = "#3x3#Ecke2#2"; r[1501] = "#2#1#Ecke3"; r[1502] = "#3x3_Bonus4#3#J"; r[1503] = "#BigSlash#3x3#4"; r[1504] = "#4#T#1"; r[1505] = "#S#3x3_Bonus4#3x3_Bonus4"; r[1506] = "#T#3x3_Bonus2#BigSlash"; r[1507] = "#2#3#1_Bonus2"; r[1508] = "#DT#Ecke3#2x2"; r[1509] = "#L#1_Bonus2#DT"; r[1510] = "#Ecke3_Bonus2#1#Ecke2"; r[1511] = "#4#1_Bonus2#Ecke3_Bonus1A"; r[1512] = "#Z#2x2_Bonus#Ecke3"; r[1513] = "#3#3#4"; r[1514] = "#2#T#1_Bonus3"; r[1515] = ":......5.L...4...5.5......#1_Bonus1#2"; r[1516] = "#DT#T#2x2_Bonus"; r[1517] = "#X_Bonus#3#1"; r[1518] = "#X_Bonus2#4#5"; r[1519] = "#Z#3x3_Bonus2#3x3_Bonus4"; r[1520] = "#1_Bonus2#4#Ecke2"; r[1521] = "#1_Bonus1#Ecke3#Ecke2"; r[1522] = "#3x3_Bonus1#Ecke3#Ecke3_Bonus1B"; r[1523] = "#BigSlash#3x3_Bonus2#DT"; r[1524] = "#5#3x3_Bonus1#4"; r[1525] = "#1_Bonus2#3#Ecke2"; r[1526] = "#1#4_Bonus#X_Bonus2"; r[1527] = "#L#T#1_Bonus3"; r[1528] = "#Z#1_Bonus2#Slash"; r[1529] = "#4_Bonus#5#1"; r[1530] = "#Ecke3_Bonus1B#3#2x3"; r[1531] = "#5#1_Bonus3#Ecke3_Bonus2"; r[1532] = "#Slash#Ecke3#3x3_Bonus1"; r[1533] = "#3#Z#T"; r[1534] = "#2#X_Bonus2#Ecke2"; r[1535] = "#Ecke2#3x3_Bonus4#Z"; r[1536] = "#DT#Ecke3_Bonus1B#3"; r[1537] = "#BigSlash#Ecke2#1_Bonus2"; r[1538] = "#X_Bonus#DT#4"; r[1539] = "#1_Bonus1#X_Bonus2#1"; r[1540] = "#2x3_Bonus#2x2#Ecke2"; r[1541] = "#T#3x3_Bonus1#Ecke3_Bonus1B"; r[1542] = "#T#X_Bonus2#2Dots"; r[1543] = "#2#T#3x3_Bonus4"; r[1544] = "#2#T#3"; r[1545] = "#2#3x3_Bonus3#T"; r[1546] = "#1#2#Ecke3_Bonus1B"; r[1547] = "#Ecke2#1_Bonus1#3"; r[1548] = "#2#Ecke3_Bonus1B:......4....4....4L4......"; r[1549] = "#Ecke2#3x3_Bonus3#4"; r[1550] = "#3x3_Bonus4#3#Ecke3"; r[1551] = "#Ecke3_Bonus1B#3x3_Bonus4#5"; r[1552] = "#4_Bonus#DT#2x3"; r[1553] = "#Ecke3#2x3#Ecke2"; r[1554] = "#Ecke3#L#Ecke2"; r[1555] = "#T#1#3x3_Bonus2"; r[1556] = "#2#X#X"; r[1557] = "#4#BigSlash#T"; r[1558] = "#L#2x2_Bonus#5"; r[1559] = "#1_Bonus1#Ecke3#3"; r[1560] = "#T#1_Bonus2#2Dots"; r[1561] = "#Ecke3_Bonus1B#5#Ecke3"; r[1562] = "#2x2_Bonus#Ecke3_Bonus1A#1"; r[1563] = "#Ecke3#3x3_Bonus4#Ecke2"; r[1564] = "#1#5#1"; r[1565] = "#Ecke3#Ecke2#Slash"; r[1566] = "#S#1_Bonus2#3x3_Bonus1"; r[1567] = "#3x3_Bonus1#S#1_Bonus3"; r[1568] = "#1#1#2Dots"; r[1569] = "#1_Bonus2#T#3x3"; r[1570] = "#1_Bonus3#2x2#1_Bonus2"; r[1571] = "#1_Bonus2#Ecke2#4_Bonus"; r[1572] = "#BigSlash#1_Bonus1#Ecke2"; r[1573] = "#Ecke3_Bonus2#2#4_Bonus"; r[1574] = "#Ecke3_Bonus1A#Ecke2#5"; r[1575] = "#X#2#2"; r[1576] = "#X#X#4_Bonus"; r[1577] = "#Ecke2#1_Bonus2#Ecke3"; r[1578] = "#T#T#3x3_Bonus1"; r[1579] = "#X#J#2x2"; r[1580] = "#Ecke3#2x3_Bonus#1_Bonus1"; r[1581] = "#1#3#Ecke3_Bonus2"; r[1582] = "#1_Bonus2:..1....1....1....L.......#S"; r[1583] = "#Slash#2x2#Ecke3_Bonus1B"; r[1584] = "#3x3_Bonus3#Ecke2#Ecke3"; r[1585] = "#5#4#5"; r[1586] = "#4_Bonus#X_Bonus#4"; r[1587] = "#T#2#T"; r[1588] = "#Ecke3_Bonus2#3#1_Bonus2"; r[1589] = "#Ecke2#Ecke3_Bonus1B#3"; r[1590] = "#2#1_Bonus3#Ecke3"; r[1591] = "#L#2#3x3_Bonus4"; r[1592] = "#2#1_Bonus1#5"; r[1593] = "#2x3_Bonus#T#3x3_Bonus3"; r[1594] = "#Ecke3_Bonus1B#4#5"; r[1595] = "#3x3_Bonus3#1#4"; r[1596] = "#Z#5#Ecke2"; r[1597] = "#4#1#L"; r[1598] = "#T#3x3_Bonus3#T"; r[1599] = "#Ecke3_Bonus1A#4#1_Bonus3"; return r; } }
30.583024
63
0.515488
b6abbc75bc7f59a779ffabf77860572e1402c892
7,039
package com.eventyay.organizer.ui.binding; import android.content.Context; import android.content.Intent; import android.content.res.ColorStateList; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.net.Uri; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.ColorInt; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.DrawableCompat; import androidx.core.view.ViewCompat; import androidx.databinding.BindingAdapter; import androidx.databinding.BindingConversion; import androidx.databinding.InverseBindingAdapter; import androidx.databinding.InverseBindingListener; import androidx.databinding.InverseMethod; import com.eventyay.organizer.R; import com.eventyay.organizer.ui.ViewUtils; import com.eventyay.organizer.ui.views.DatePicker; import com.eventyay.organizer.ui.views.TimePicker; import com.eventyay.organizer.utils.Utils; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.mikhaellopez.circularprogressbar.CircularProgressBar; @SuppressWarnings("PMD.AvoidCatchingGenericException") public final class BindingAdapters { private BindingAdapters() { // Never Called } @BindingConversion @InverseMethod("strToLong") public static String longToStr(Long value) { return value == null ? "" : String.valueOf(value); } @BindingConversion @InverseMethod("strToFloat") public static String floatToStr(Float value) { return value == null ? "" : String.valueOf(value); } @InverseMethod("strToDouble") public static String doubleToStr(Double value) { return value == null ? "" : String.valueOf(value); } @BindingConversion @InverseMethod("strToInteger") public static String integerToStr(Integer value) { return value == null ? "" : String.valueOf(value); } @SuppressWarnings("PMD") public static Long strToLong(String value) { return Utils.isEmpty(value) ? null : Long.parseLong(value); } @SuppressWarnings("PMD") public static Float strToFloat(String value) { return Utils.isEmpty(value) ? null : Float.parseFloat(value); } @SuppressWarnings("PMD") public static Double strToDouble(String value) { return Utils.isEmpty(value) ? null : Double.parseDouble(value); } @SuppressWarnings("PMD.NullAssignment") public static Integer strToInteger(String value) { return Utils.isEmpty(value) ? null : Integer.parseInt(value); } @InverseMethod("getType") public static int toId(String ticketType) { if (ticketType == null) return R.id.free; switch (ticketType) { case "free": return R.id.free; case "paid": return R.id.paid; case "donation": return R.id.donation; default: return -1; } } public static String getType(int id) { switch (id) { case R.id.free: return "free"; case R.id.paid: return "paid"; case R.id.donation: return "donation"; default: return "free"; } } @BindingAdapter("tint") public static void setTintColor(ImageView imageView, @ColorInt int color) { DrawableCompat.setTint(imageView.getDrawable(), color); } @BindingAdapter("backgroundTint") public static void setBackgroundTintColor(View view, @ColorInt int color) { ViewCompat.setBackgroundTintList(view, ColorStateList.valueOf(color)); } @BindingAdapter("srcCompat") public static void bindSrcCompat(FloatingActionButton fab, Drawable drawable) { fab.setImageDrawable(drawable); } @BindingAdapter("srcCompat") public static void bindSrcImageView(ImageView imageView, Drawable drawable) { imageView.setImageDrawable(drawable); } @BindingAdapter("progress_with_animation") public static void bindCircularProgress(CircularProgressBar circularProgressBar, int progress) { circularProgressBar.setProgressWithAnimation(progress, 500L); } @BindingAdapter("circular_progress_color") public static void bindCircularProgressColor(CircularProgressBar circularProgressBar, String colorName) { Context context = circularProgressBar.getContext(); Resources resources = circularProgressBar.getResources(); int color = ContextCompat.getColor(context, resources.getIdentifier(colorName + "_500", "color", context.getPackageName())); int bgColor = ContextCompat.getColor(context, resources.getIdentifier(colorName + "_100", "color", context.getPackageName())); circularProgressBar.setProgressBarColor(color); circularProgressBar.setBackgroundColor(bgColor); } @BindingAdapter("go") public static void doneAction(EditText editText, Runnable runnable) { editText.setOnEditorActionListener((v, actionId, event) -> { if (actionId == EditorInfo.IME_ACTION_GO) { ViewUtils.hideKeyboard(editText); runnable.run(); return true; } return false; }); } @BindingAdapter(value = "valueAttrChanged") public static void setDateChangeListener(DatePicker datePicker, final InverseBindingListener listener) { if (listener != null) { datePicker.setOnDateChangedListener(newDate -> listener.onChange()); } } @InverseBindingAdapter(attribute = "value") public static String getRealValue(DatePicker datePicker) { return datePicker.getValue().get(); } @BindingAdapter(value = "valueAttrChanged") public static void setTimeListener(TimePicker timePicker, final InverseBindingListener listener) { if (listener != null) { timePicker.setOnDateChangedListener(newDate -> listener.onChange()); } } @InverseBindingAdapter(attribute = "value") public static String getRealValue(TimePicker timePicker) { return timePicker.getValue().get(); } @BindingAdapter("imageOnClick") public static void bindOnImageButtonClickListener(ImageButton imageButton, String url) { imageButton.setOnClickListener(view -> { if (url != null) { Context context = imageButton.getContext(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); if (intent.resolveActivity(context.getPackageManager()) == null) { Toast.makeText(context, "No Web browser found", Toast.LENGTH_SHORT).show(); } else { context.startActivity(intent); } } }); } }
34.674877
134
0.67609
86f2bad20c5c0e16a2c6856105383abaf105b489
1,541
package org.clubrockisen.controller.abstracts; import org.clubrockisen.entities.enums.Gender; import org.clubrockisen.entities.enums.Status; /** * Interface for defining a controller for a member entity. * @author Alex */ public interface MemberController { /** * Change the name of the member in the model. * @param newName * the new name for the member. */ void changeName (final String newName); /** * Change the gender of the member in the model. * @param newGender * the new gender for the member. */ void changeGender (final Gender newGender); /** * Change the entries of the member in the model. * @param newEntries * the new entry number for the member. */ void changeEntries (final int newEntries); /** * Change the number of entries until the next free one in the model. * @param newNextFree * the new value for the next free entry. */ void changeNextFree (final int newNextFree); /** * Change the credit of the member in the model. * @param newCredit * the new credit for the member. */ void changeCredit (final double newCredit); /** * Change the status of the member in the model. * @param newStatus * the new status for the member. */ void changeStatus (final Status newStatus); /** * Persists any changes to the database.<br /> * @return <code>true</code> if the operation succeeded. */ boolean persist (); /** * Reload the models registered from the database.<br /> */ void reload (); }
23.707692
70
0.669046
4334434db9675c9d83e9235a6a33c3733f10a190
2,768
package theForsaken.cards; import com.megacrit.cardcrawl.actions.AbstractGameAction.AttackEffect; import com.megacrit.cardcrawl.actions.animations.VFXAction; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.DamageAllEnemiesAction; import com.megacrit.cardcrawl.actions.utility.SFXAction; import com.megacrit.cardcrawl.actions.utility.WaitAction; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.powers.StrengthPower; import com.megacrit.cardcrawl.vfx.combat.MindblastEffect; import theForsaken.TheForsakenMod; import theForsaken.characters.TheForsaken; import static theForsaken.TheForsakenMod.makeCardPath; public class SolarFlare extends AbstractDynamicCard { // TEXT DECLARATION public static final String ID = TheForsakenMod.makeID(SolarFlare.class.getSimpleName()); public static final String IMG = makeCardPath("SolarFlare.png"); // Must have an image with the same NAME as the card in your image folder!. // /TEXT DECLARATION/ // STAT DECLARATION private static final CardRarity RARITY = CardRarity.UNCOMMON; private static final CardTarget TARGET = CardTarget.ALL_ENEMY; private static final CardType TYPE = CardType.ATTACK; public static final CardColor COLOR = TheForsaken.Enums.COLOR_GOLD; private static final int COST = 3; private static final int DAMAGE = 27; private static final int UPGRADE_PLUS_DMG = 5; private static final int MAGIC = 2; // /STAT DECLARATION/ public SolarFlare() { super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET); baseDamage = DAMAGE; baseMagicNumber = MAGIC; magicNumber = baseMagicNumber; isMultiDamage = true; } // Actions the card should do. @Override public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToBottom(new SFXAction("ATTACK_HEAVY")); AbstractDungeon.actionManager.addToBottom(new VFXAction(p, new MindblastEffect(p.dialogX, p.dialogY, p.flipHorizontal), 0.1F)); AbstractDungeon.actionManager.addToBottom(new DamageAllEnemiesAction(p, multiDamage, damageTypeForTurn, AttackEffect.NONE)); AbstractDungeon.actionManager.addToBottom(new WaitAction(0.1F)); AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new StrengthPower(p, -magicNumber), -magicNumber)); } // Upgraded stats. @Override public void upgrade() { if (!upgraded) { upgradeName(); upgradeDamage(UPGRADE_PLUS_DMG); initializeDescription(); } } }
38.444444
135
0.747832
1848369b5cd4896a9dcf07be61674fe157456642
620
package com.example; import com.example.rest.config.SpringConfig; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! */ public class App { public static void main(String[] args) { //实例化 /*HelloServiceImpl service = new HelloServiceImpl(); RPCProxyServer proxyServer = new RPCProxyServer(); //发布 proxyServer.publisher(service, 8080);*/ ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); //context.start(); } }
29.52381
96
0.716129
6c1156880ec6c026be7eafd4c2e373b25ab8bec8
35,658
package com.example.lyc.vrexplayer.activity; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.lyc.vrexplayer.R; import com.example.lyc.vrexplayer.Utils.RxBus; import com.example.lyc.vrexplayer.Utils.UserEvent; import com.example.lyc.vrexplayer.broadcastreceiver.WifiDerectBroadcastReceiver; import com.example.lyc.vrexplayer.task.FileServerAsyncTask; import com.example.lyc.vrexplayer.view.FlikerProgressBar; import java.io.File; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import rx.Subscription; import rx.functions.Action1; public class WifiP2pRecActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "wifip2precactivity"; private View mLayout; private IntentFilter mFilter; private WifiP2pManager mManager; private WifiP2pManager.Channel mChannel; private WifiDerectBroadcastReceiver mReceiver; private WifiP2pManager.PeerListListener mPeerListListener; private WifiP2pManager.ConnectionInfoListener mConnectionInfoListener; private List<HashMap<String, String>> mPeerLists; private WifiP2pInfo mInfo; private Button mBtn_reset; private TextView mTv_waiting_for_server; private TextView mTv_rec_file; Handler handler = new Handler(); private FileServerAsyncTask mServerTask; private Subscription mSubscription; private Collection<WifiP2pDevice> mDeviceList; private HashMap<String, WifiP2pDevice> mAllDeviceList = new HashMap<>(); private String preTransFileName = null; private String beforeConnectDevice; private static String mAbsolutePath; private String mBeforeConnectName; private FlikerProgressBar mRec_progress; private static final int RESTART_REC = 1; private static final int NOT_FINISHED_RESTART = 2; private static final int MISS_PROGRESS = 3; private static final int FIRST_VIEW_MISS = 4; private static final int PROGRESS_BIANHUA = 5; private int mPretransFileSize; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESTART_REC: if (mServerTask != null) { if (!mServerTask.getIsAccept()) { Log.d(TAG, "startServerTask: 任务还没accept 说明已经启动了任务"); } else if (mServerTask.getStatus() == AsyncTask.Status.FINISHED) { Log.d(TAG, "startServerTask: 任务 finished" + mServerTask.getStatus()); mServerTask = new FileServerAsyncTask(); mServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } else { mServerTask = new FileServerAsyncTask(); mServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } break; case NOT_FINISHED_RESTART: mServerTask = new FileServerAsyncTask(); mServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); break; case MISS_PROGRESS: mRec_progress.setVisibility(View.GONE); break; case FIRST_VIEW_MISS: mFirst_view.setVisibility(View.GONE); mSecond_view.setVisibility(View.VISIBLE); break; case PROGRESS_BIANHUA: float newProgress = mProgress; Log.d(TAG, "startServerTask: "+newProgress + "::" + mBeforeProgress ); if(newProgress == mBeforeProgress){ //说明没动 已经挂掉了 Log.d(TAG, "startServerTask: 已经挂掉了"); mServerTask.closeSocket(); mHandler.sendEmptyMessageDelayed(NOT_FINISHED_RESTART, 100 ); }else{ //说明在动作 } break; } super.handleMessage(msg); } }; private boolean mIsFromServer; private LinearLayout mSecond_view; private LinearLayout mFirst_view; private TextView mTv_ava_space; private Button mBtn_ava_space_confirm; private long mAvailableNum = 0; private float mBeforeProgress; private float mProgress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); getWindow().getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); mLayout = getLayoutInflater().from(this) .inflate(R.layout.activity_wifi_p2p_rec, null); this.getWindow() .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(mLayout); mLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mLayout.getSystemUiVisibility() == View.SYSTEM_UI_FLAG_VISIBLE) { mLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } else { mLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } } }); initView(); initData(); initEvent(); initWifiP2p(); initRxBus(); } private void initRxBus() { mSubscription = RxBus.getInstance() .toObserverable(UserEvent.class) .subscribe(new Action1<UserEvent>() { @Override public void call(final UserEvent userEvent) { long fileLength = 0; switch (userEvent.getName()) { case "disconnect": handler.post(new Runnable() { @Override public void run() { //中文修改 mTv_waiting_for_server.setText( "接收端已经准备好(等待发送端连接):"); // mTv_waiting_for_server.setText("The receiving is ready (waiting for the connecting"); } }); break; case "hasReceived": handler.post(new Runnable() { @Override public void run() { if (mTv_rec_file.getVisibility() == View.GONE) { mTv_rec_file.setVisibility(View.VISIBLE); } if (mRec_progress.getVisibility() == View.VISIBLE) { mRec_progress.reset(); Log.d(TAG, "run: reset之后在gone"); mRec_progress.setVisibility(View.GONE); } if (userEvent.getFileName() != null) { if (userEvent.getFiles_size() == 1) { //中文修改 mTv_rec_file.setText("传输文件的状态:接受文件完成:" + "文件为" + userEvent.getFileName()); // mTv_rec_file.setText("Status of the transport file: accept the file completion:" + "File:" + userEvent.getFileName()); preTransFileName = userEvent.getFileName(); mPretransFileSize = 1; } else { //中文修改 mTv_rec_file.setText( "传输文件的状态:接受文件完成,共接受" + userEvent.getFiles_size() + "个文件"); // mTv_rec_file.setText( "Status of the transmission file: accept the file and accept it" + userEvent.getFiles_size() + "Files"); preTransFileName = userEvent.getFileName(); mPretransFileSize = userEvent.getFiles_size(); } } else { //中文修改 mTv_rec_file.setText("传输文件的状态:接受文件完成。"); // mTv_rec_file.setText("Status of the transport file: accept the file completion。"); } //重新执行一次等待的任务 // // Log.d(TAG, // "run: 任务" + mServerTask.getStatus()); mHandler.sendEmptyMessageDelayed(RESTART_REC, 30); for (int i = 0; i < userEvent.getPathsArr() .size(); i++) { sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File( userEvent.getPathsArr() .get(i))))); } } }); break; case "serverReceiving": handler.post(new Runnable() { @Override public void run() { //中文修改 mTv_rec_file.setText( "传输文件的状态:接受文件中"); // mTv_rec_file.setText( // "Status of the transport file:Receiving"); } }); break; case "waitingConnect": handler.post(new Runnable() { @Override public void run() { if (mTv_rec_file.getVisibility() == View.GONE) { mTv_rec_file.setVisibility( View.VISIBLE); } if (mRec_progress.getVisibility() == View.VISIBLE) { mRec_progress.setVisibility( View.GONE); } if (preTransFileName != null || mPretransFileSize != 0) { if (mPretransFileSize == 1) { mTv_rec_file.setText( "传输文件的状态:等待传输中(上一次接受文件名为:" + preTransFileName + ")"); // mTv_rec_file.setText( // "Status of the transport file:Waiting For Receiving"); } else { mTv_rec_file.setText( "传输文件的状态:等待传输中(上一次共接受" + mPretransFileSize + "个文件)"); // mTv_rec_file.setText( // "Status of the transport file:Waiting For Receiving"); } } else { Log.d(TAG, "run: "+mPretransFileSize +"preTransFileName::" + preTransFileName); mTv_rec_file.setText( "传输文件的状态:等待传输中"); // mTv_rec_file.setText( // "Status of the transport file:Waiting For Receiving"); } } }); break; case "doing": handler.post(new Runnable() { @Override public void run() { if (mTv_rec_file.getVisibility() == View.VISIBLE) { mTv_rec_file.setVisibility( View.GONE); } if (mRec_progress.getVisibility() == View.GONE) { mRec_progress.setVisibility( View.VISIBLE); } mProgress = (userEvent.getProgress() * 100 / userEvent.getFileLengthMB()); Log.d(TAG, "run: " + mProgress + "::" + userEvent.getProgress() + "::" + userEvent.getFileLengthMB()); BigDecimal b = new BigDecimal( mProgress); mProgress = b.setScale(1, BigDecimal.ROUND_HALF_UP) .floatValue(); mRec_progress.setProgress( mProgress); } }); case "WIFI_P2P_PEER_CHANGE": break; case "connect_fail": //中文修改 Toast.makeText( getApplicationContext(), "启动文件传输失败 ,请重新发送文件", Toast.LENGTH_SHORT) .show(); // Toast.makeText( getApplicationContext(), // "Start file transfer failed, please resend the file", // Toast.LENGTH_SHORT) // .show(); break; } } }); if (mAvailableNum != 0) { float available_num = ((float) mAvailableNum) / 1024 / 1024 / 1024; Log.d(TAG, "initRxBus: " + available_num); float biaozhunNum = 1.2f; if (available_num < biaozhunNum) { Log.d(TAG, "initRxBus: 进入到小鱼的里面来了"); mFirst_view.setVisibility(View.VISIBLE); //中文修改 mTv_ava_space.setText("可用空间已经不足1.0G,请注意发送文件的大小"); // mTv_ava_space.setText("The available space is less than 1.0G, please note the size of the file sent"); mHandler.sendEmptyMessageDelayed(FIRST_VIEW_MISS, 5000); } else { mFirst_view.setVisibility(View.GONE); mSecond_view.setVisibility(View.VISIBLE); } } else { mFirst_view.setVisibility(View.GONE); mSecond_view.setVisibility(View.VISIBLE); } } private void initWifiP2p() { mFilter = new IntentFilter(); mFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mFilter.addAction(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION); mFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); mManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); mPeerLists = new ArrayList<HashMap<String, String>>(); //这个是申请到列表后的回调 mPeerListListener = new WifiP2pManager.PeerListListener() { @Override public void onPeersAvailable(WifiP2pDeviceList peers) { Log.d(TAG, "onPeersAvailable: 步骤1 搜索到设备"); //搜索到的设备 if (mPeerLists != null) { mPeerLists.clear(); } mDeviceList = peers.getDeviceList(); if (mIsFromServer) { Log.d(TAG, "onPeersAvailable: 步骤 进入到服务器进入的搜索"); if (mDeviceList == null) { mTv_waiting_for_server.setText("接收端已经准备好(等待发送端连接)"); // mTv_waiting_for_server.setText("The receiving is ready (waiting for the connecting"); } else { for (WifiP2pDevice wifiP2pDevice : mDeviceList) { Log.d("Jareld ", "onConnectionInfoAvailable: " + wifiP2pDevice.status); if (wifiP2pDevice.status == WifiP2pDevice.CONNECTED) { //中文修改 beforeConnectDevice = wifiP2pDevice.deviceName; //说明这个连接到了: mTv_waiting_for_server.setText("连接成功------" + "已经连接到设备:" + wifiP2pDevice.deviceName); // mTv_waiting_for_server.setText("Connect success------" + "The connected device:" + wifiP2pDevice.deviceName); startServerTask(); return; } } //到了这里说明 一个也没有连接上 if (mRec_progress.getVisibility() == View.VISIBLE) { mRec_progress.reset(); mRec_progress.setVisibility(View.GONE); } else if (mTv_rec_file.getVisibility() == View.GONE) { mTv_rec_file.setVisibility(View.VISIBLE); // mTv_rec_file.setText("Waiting for recive files"); mTv_rec_file.setText("等待接受文件"); //中文修改 } mTv_waiting_for_server.setText("接收端已经准备好(等待发送端连接):"); // mTv_waiting_for_server.setText("The receiving is ready (waiting for the connecting"); } mIsFromServer = false; } } }; //这是申请连接后的回调 mConnectionInfoListener = new WifiP2pManager.ConnectionInfoListener() { @Override public void onConnectionInfoAvailable(WifiP2pInfo info) { mInfo = info; ///192.168.49.1info.isGroupOwnertrue if (info.groupFormed && info.isGroupOwner) { Log.d(TAG, "Jareld : 服务端"); mIsFromServer = true; //说明是服务端 mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int i) { } }); if (mDeviceList == null) { //中文修改 mTv_waiting_for_server.setText("接收端已经准备好(等待发送端连接)"); // mTv_waiting_for_server.setText("The receiving is ready (waiting for the connecting"); } else { for (WifiP2pDevice wifiP2pDevice : mDeviceList) { Log.d("Jareld ", "onConnectionInfoAvailable: " + wifiP2pDevice.status); if (wifiP2pDevice.status == WifiP2pDevice.CONNECTED) { beforeConnectDevice = wifiP2pDevice.deviceName; //说明这个连接到了: mTv_waiting_for_server.setText("连接成功------" + "已连接至设备:" + wifiP2pDevice.deviceName); // mTv_waiting_for_server.setText("The connection is successful------" + "Already connected to the device:" + wifiP2pDevice.deviceName); startServerTask(); return; } } //到了这里说明 一个也没有连接上 mTv_waiting_for_server.setText("接收端已经准备好(等待发送端连接):"); // mTv_waiting_for_server.setText("The receiving is ready (waiting for the connecting"); } } else if (info.groupFormed) { //说明是客户端 } } }; mReceiver = new WifiDerectBroadcastReceiver(mManager, mChannel, this, mPeerListListener, mConnectionInfoListener); mManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int reason) { } }); mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int reason) { } }); //创建服务器 mManager.createGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int i) { } }); } private void startServerTask() { Log.d(TAG, "startServerTask: 進入到鏈接后的開始任務"); if (mServerTask == null) { mServerTask = new FileServerAsyncTask(); mServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else if (!mServerTask.getIsAccept()) { //还没开始接受 说明程序在 Log.d(TAG, "startServerTask: 还没开始接受"); } else if (!mServerTask.getIsFinished()) { //重新连接服务器但是还没有完成,那么是不是要 重新启动一下这个服务器 Log.d(TAG, "startServerTask: 重连服务器 但是还没有完成,重新关闭一下server"); Log.d(TAG, "startServerTask: " + mRec_progress.getProgress()); mBeforeProgress = mProgress; mHandler.sendEmptyMessageDelayed(PROGRESS_BIANHUA, 200); } else { Log.d(TAG, "startServerTask: 其他情况"); } } private void initView() { mBtn_reset = (Button) findViewById(R.id.reset_status_btn); mTv_waiting_for_server = (TextView) findViewById(R.id.wating_device_connect); mTv_rec_file = (TextView) findViewById(R.id.file_rec); mRec_progress = (FlikerProgressBar) findViewById(R.id.rec_file_progress); mHandler.sendEmptyMessageDelayed(MISS_PROGRESS, 50); mSecond_view = (LinearLayout) findViewById(R.id.second_view); mFirst_view = (LinearLayout) findViewById(R.id.first_view); mTv_ava_space = (TextView) findViewById(R.id.available_space); mBtn_ava_space_confirm = (Button) findViewById(R.id.available_space_confirm); } private void initData() { String path = Environment.getExternalStorageDirectory() + "/" + "Samson/Wifi-Tranfer/"; File file = new File(path); File[] files = file.listFiles(); long l = System.currentTimeMillis(); String string = getCurrentTime(l); if (files.length == 0) { //说明第一次进入 创建 第一个文件夹 File newFile = new File(path + string + "/"); newFile.mkdirs(); mAbsolutePath = newFile.getAbsolutePath(); } else { //看今天是星期几 String s = DateToWeek(new Date(System.currentTimeMillis())); if (s.equals(WEEK[1])) { Log.d(TAG, "initData: " + WEEK[1]); //说明是星期一 创建一个新的目录 File newFile = new File(path + string + "/"); if (!newFile.exists()) { //如果这个目录不存在 那么久创建 newFile.mkdirs(); } //存在 就直接取地址 mAbsolutePath = newFile.getAbsolutePath(); } else { Log.d(TAG, "initData: " + s); //看今天是星期几 int week_i = 0; for (int i = 0; i < WEEK.length; i++) { if (s.equals(WEEK[i])) { week_i = i; break; } } int i = string.lastIndexOf("_"); String substring = string.substring(i + 1, string.length()); int i1 = Integer.parseInt(substring); if (week_i == 0) { i1 = i1 - 6; } else { i1 = i1 - (week_i - 1); } String substring1 = string.substring(0, i); String newString = substring1 + "_" + i1; Log.d(TAG, "initData: " + newString); //不是星期一 mAbsolutePath = path + newString + "/"; } } //随便添加 Log.d(TAG, "initData: 最终的路径" + mAbsolutePath); // 获得手机内部存储控件的状态 File dataFileDir = Environment.getDataDirectory(); getMemoryInfo(dataFileDir); } private void getMemoryInfo(File path) { // 获得一个磁盘状态对象 StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); // 获得一个扇区的大小 long totalBlocks = stat.getBlockCount(); // 获得扇区的总数 long availableBlocks = stat.getAvailableBlocks(); // 获得可用的扇区数量 Log.d(TAG, "getMemoryInfo: " + availableBlocks + "::" + blockSize); //可用空间 mAvailableNum = availableBlocks * blockSize; } public static String getAbsolutePath() { return mAbsolutePath; } public String getCurrentTime(long date) { SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd"); String str = format.format(new Date(date)); return str; } Calendar c = Calendar.getInstance(); Date date = c.getTime(); String s = DateToWeek(date); public static String[] WEEK = {"星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; public static final int WEEKDAYS = 7; public static String DateToWeek(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int dayIndex = calendar.get(Calendar.DAY_OF_WEEK); if (dayIndex < 1 || dayIndex > WEEKDAYS) { return null; } return WEEK[dayIndex - 1]; } private void initEvent() { mBtn_reset.setOnClickListener(this); mBtn_ava_space_confirm.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); registerReceiver(mReceiver, mFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int i) { } }); if (mServerTask != null) { mServerTask.cancel(false); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.reset_status_btn: // TODO: 2017/3/26 断开连接重新创建服务器 mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d("Jareld", "onSuccess:remove group "); mManager.createGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int i) { } }); } @Override public void onFailure(int i) { Log.d(TAG, "onFailure: 失败了"); } }); if (mServerTask != null) { Log.d(TAG, "onClick: servertask status= " + mServerTask.getStatus()); } break; case R.id.available_space_confirm: if (mHandler.hasMessages(FIRST_VIEW_MISS)) { mHandler.removeMessages(FIRST_VIEW_MISS); mFirst_view.setVisibility(View.GONE); mSecond_view.setVisibility(View.VISIBLE); } break; default: break; } } }
45.891892
190
0.406921
1d6345ce70095f072d7c8aa487865795364f218c
813
package com.caleb.algorithm.review.offerdemo; /** * @author:Caleb * @Date :2021-08-04 16:35:04 */ public class CuttingRope14 { public int cuttingRope(int n) { if (n <= 3) { return n - 1; } if (n % 3 == 1) { int count = n / 3; count--; return (int) Math.pow(3, count) * 4; } if (n % 3 == 2) { int count = n / 3; return (int) Math.pow(3, count) * 2; } else { int count = n / 3; return (int) Math.pow(3, count); } } public int cuttingRope1(int n) { if (n <= 3) { return n - 1; } int a = n / 3; int b = n % 3; long res = 1; while (a > 1) { res = (res * 3) % 1000000007; a--; } if (b == 1) { return (int)((res * 4) % 1000000007); } else if (b == 0) { return (int)((res * 3) % 1000000007); } return (int)((res * 6) % 1000000007); } }
17.673913
45
0.501845
750a2ecb141eea782929105ae39621c8e3e672fa
2,196
package com.lakeel.altla.vision.nearby.presentation.presenter; import android.content.Intent; import com.firebase.ui.auth.AuthUI; import com.google.firebase.auth.FirebaseAuth; import com.lakeel.altla.vision.nearby.R; import com.lakeel.altla.vision.nearby.domain.usecase.SignInUseCase; import com.lakeel.altla.vision.nearby.presentation.analytics.AnalyticsReporter; import com.lakeel.altla.vision.nearby.presentation.view.SignInView; import com.lakeel.altla.vision.nearby.rx.ReusableCompositeSubscription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; public final class SignInPresenter extends BasePresenter<SignInView> { @Inject AnalyticsReporter analyticsReporter; @Inject SignInUseCase signInUseCase; private static final Logger LOGGER = LoggerFactory.getLogger(SignInPresenter.class); private final ReusableCompositeSubscription subscriptions = new ReusableCompositeSubscription(); @Inject SignInPresenter() { } private static final String GOOGLE_TOS_URL = "https://www.google.com/policies/terms/"; public void onActivityCreated() { Intent intent = AuthUI.getInstance() .createSignInIntentBuilder() .setProviders(AuthUI.GOOGLE_PROVIDER) .setTosUrl(GOOGLE_TOS_URL) .setTheme(R.style.AuthUiTheme) .build(); getView().showGoogleSignInActivity(intent); } public void onStop() { subscriptions.unSubscribe(); } public void onSignedIn() { analyticsReporter.signIn(); Subscription subscription = signInUseCase .execute() .observeOn(AndroidSchedulers.mainThread()) .subscribe(deviceToken -> { getView().onSignedIn(); }, e -> { LOGGER.error("Failed to sign in.", e); FirebaseAuth.getInstance().signOut(); getView().showSnackBar(R.string.snackBar_error_not_signed_in); }); subscriptions.add(subscription); } }
30.5
100
0.67623
2aa71e78f00d34888fb31b864e5ddbf472f8f5fb
211
package jquants; /** * * @author Mathias Braeu * @since 1.0 * * @param <T> */ public abstract class BaseQuantity<T extends Quantity<T>> extends Quantity<T> { public abstract UnitOfMeasure baseUnit(); }
17.583333
79
0.682464
9ec4ae691cca85868232ec0eca10cee0bfc44646
3,026
/** * SkillAPI * com.sucy.skill.manager.TitleManager * <p> * The MIT License (MIT) * <p> * Copyright (c) 2014 Steven Sucy * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.sucy.skill.manager; import com.sucy.skill.SkillAPI; import com.sucy.skill.api.util.Title; import com.sucy.skill.data.Settings; import com.sucy.skill.data.TitleType; import mc.promcteam.engine.mccore.config.CustomFilter; import mc.promcteam.engine.mccore.config.FilterType; import org.bukkit.entity.Player; import java.util.List; /** * Handles accessing the Title display resource */ public class TitleManager { private static int fadeIn; private static int duration; private static int fadeOut; /** * Initializes the title object if not done so already */ private static void init() { Settings settings = SkillAPI.getSettings(); fadeIn = settings.getTitleFadeIn(); duration = settings.getTitleDuration(); fadeOut = settings.getTitleFadeOut(); } /** * Shows a message using the Title display * * @param player player to send to * @param type type of message * @param msgKey language config key for the message * @param filters filters to apply to the message */ public static void show(Player player, TitleType type, String msgKey, CustomFilter... filters) { if (SkillAPI.getSettings().useTitle(type) && msgKey != null) { List<String> message = SkillAPI.getLanguage().getMessage(msgKey, true, FilterType.COLOR, filters); if (message != null && message.size() > 0) { init(); String title = message.get(0); String subtitle = message.size() > 1 ? message.get(1) : null; Title.send(player, title, subtitle, fadeIn, duration, fadeOut); } } else if (msgKey != null) SkillAPI.getLanguage().sendMessage(msgKey, player, FilterType.COLOR, filters); } }
38.794872
110
0.689689
4afdfaa774f6e73763f1b72c9520e0965df12caa
5,231
package net.logicsquad.minifier; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.codehaus.plexus.util.DirectoryScanner; import net.logicsquad.minifier.css.CSSMinifier; import net.logicsquad.minifier.js.JSMinifier; /** * Goal for minification of web resources. * * @author paulh */ @Mojo(name = "minify", defaultPhase = LifecyclePhase.PROCESS_RESOURCES) public class MinifierMojo extends AbstractMojo { /** * Source directory */ @Parameter(property = "sourceDir", required = true) private String sourceDir; /** * Target directory */ @Parameter(property = "targetDir", required = true) private String targetDir; /** * List of Javascript includes */ @Parameter(property = "jsIncludes") private List<String> jsIncludes; /** * List of Javascript excludes */ @Parameter(property = "jsExcludes") private List<String> jsExcludes; /** * List of CSS includes */ @Parameter(property = "cssIncludes") private List<String> cssIncludes; /** * List of CSS excludes */ @Parameter(property = "cssExcludes") private List<String> cssExcludes; /** * Resolved list of Javascript filenames to minify */ private List<String> jsFilenames; /** * Resolved list of CSS filenames to minify */ private List<String> cssFilenames; /** * Returns resolved list of Javascript filenames for minification. * * @return Javascript filenames */ private List<String> jsFilenames() { if (jsFilenames == null) { jsFilenames = filenameList(jsIncludes, jsExcludes); } return jsFilenames; } /** * Returns resolved list of CSS filenames for minification. * * @return CSS filenames */ private List<String> cssFilenames() { if (cssFilenames == null) { cssFilenames = filenameList(cssIncludes, cssExcludes); } return cssFilenames; } /** * Returns filename list from includes and excludes. * * @param includes list of include patterns * @param excludes list of exclude patterns * @return filename list */ private List<String> filenameList(List<String> includes, List<String> excludes) { List<String> list = new ArrayList<>(); DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(sourceDir); scanner.setIncludes(includes.toArray(new String[0])); scanner.setExcludes(excludes.toArray(new String[0])); scanner.addDefaultExcludes(); scanner.scan(); for (String s : scanner.getIncludedFiles()) { list.add(s); } return list; } /** * Performs Javascript and CSS minification. */ @Override public void execute() throws MojoExecutionException, MojoFailureException { minify(JSMinifier.class, jsFilenames()); minify(CSSMinifier.class, cssFilenames()); return; } /** * Minifies {@link File}s represented by {@code filenames} using an instance of * {@code minifierClass}. * * @param minifierClass class implementing {@link Minifier} * @param filenames list of filenames * @throws MojoFailureException if any exception is caught during minification */ private void minify(Class<? extends Minifier> minifierClass, List<String> filenames) throws MojoFailureException { for (String s : filenames) { try { File infile = new File(sourceDir, s); File outfile = new File(targetDir, s); Constructor<? extends Minifier> constructor = minifierClass.getConstructor(Reader.class); Minifier minifier = constructor.newInstance( new InputStreamReader(Files.newInputStream(infile.toPath()), StandardCharsets.UTF_8)); // Depending on where or how the plugin is invoked, the parent directories above // the output file may not exist yet. Files.createDirectories(outfile.toPath().getParent()); minifier.minify( new OutputStreamWriter(Files.newOutputStream(outfile.toPath()), StandardCharsets.UTF_8)); logMinificationResult(s, infile, outfile); } catch (MinificationException | IOException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new MojoFailureException("Unable to minify resources.", e); } } return; } /** * Logs minification result. * * @param name filename * @param infile input {@link File} * @param outfile output {@link File} */ private void logMinificationResult(String name, File infile, File outfile) { long pre = infile.length(); long post = outfile.length(); long reduction = (long) (100.0 - (((double) post / (double) pre) * 100.0)); getLog().info("Minified '" + name + "' " + pre + " -> " + post + " (" + reduction + "%)"); return; } }
29.061111
115
0.724336
37c7433093defdba895f418ff413b46d0225ff76
1,172
import java.util.*; public class Solution { public Solution() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); System.out.println("Enter the size of array : "); int n = s.nextInt(); System.out.println("Enter the array elements : "); int arr[] = new int[n]; int jumps[] = new int[n]; int pre[] = new int[n]; for(int i = 0 ; i < n ; i++) { arr[i] = s.nextInt(); } int numberofjumps = get_jumps(arr , jumps , pre); System.out.println(); System.out.println("The min number of jumps = " + numberofjumps); } private static int get_jumps(int[] arr, int[] jumps, int pre[]) { jumps[0] = 0; pre[0] = 0; if(arr[0] == 0) { return -1; } for(int i = 1 ; i < arr.length ; i++) { jumps[i] = Integer.MAX_VALUE; for(int j = 0 ; j <= i ; j++) { if(arr[j] >= i-j) { jumps[i] = Math.min(jumps[i] , jumps[j] + 1); pre[i] = j; break; } } } for(int i = 0 ; i < pre.length; i++) { System.out.print(pre[i] + "\t"); } return jumps[jumps.length-1]; } }
18.903226
67
0.544369