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
|
|---|---|---|---|---|---|
7f6d7a6d049a92d1c2dd2ee4d7ab23e2db702a94
| 915
|
package com.schlimm.java7.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class CallGraph_Default_AsynchronousFileChannel {
private static AsynchronousFileChannel fileChannel;
public static void main(String[] args) throws InterruptedException, IOException, ExecutionException {
try {
fileChannel = AsynchronousFileChannel.open(Paths.get("E:/temp/afile.out"), StandardOpenOption.READ,
StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
Future<Integer> future = fileChannel.write(ByteBuffer.wrap("Hello".getBytes()), 0L);
future.get();
} catch (Exception e) {
e.printStackTrace();
} finally {
fileChannel.close();
}
}
}
| 32.678571
| 102
| 0.785792
|
ab0863bbffcf3ef8de77409d0af1aa81d86c1b97
| 423
|
package com.wayki.wallet.dialog;
import android.content.Context;
import android.support.annotation.NonNull;
public class ActiveDialog extends WalletDailog {
public ActiveDialog(@NonNull Context context, int theme, int layoutid) {
super(context, theme, layoutid);
}
@Override
public void initUI() {
}
public String getPwd() {
return editText.getText().toString().trim();
}
}
| 21.15
| 76
| 0.687943
|
0e2be721a6e5c2027568008a9ebdfcaf6cc086af
| 1,066
|
package glitch.kraken.services.request;
import glitch.api.http.HttpClient;
import glitch.api.http.Routes;
import glitch.kraken.object.json.Team;
import glitch.kraken.object.json.collections.Teams;
import glitch.service.AbstractRequest;
import reactor.core.publisher.Mono;
public class TeamsRequest extends AbstractRequest<Team, Teams> {
private Integer limit;
private Integer offset;
public TeamsRequest(HttpClient httpClient) {
super(httpClient, Routes.get("/teams").newRequest());
}
public TeamsRequest setLimit(Integer limit) {
this.limit = limit;
return this;
}
public TeamsRequest setOffset(Integer offset) {
this.offset = offset;
return this;
}
@Override
public Mono<Teams> get() {
if (limit != null && limit > 0 && limit <= 100) {
request.queryParam("limit", limit);
}
if (offset != null && offset >= 0) {
request.queryParam("offset", offset);
}
return httpClient.exchangeAs(request, Teams.class);
}
}
| 25.380952
| 64
| 0.65197
|
3951c08ad88392a708d882741baae88dee00fedb
| 484
|
package com.vidolima.doco.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is applied to the entity class. Specifies that other annotations can also be found in super class.
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentIndexSubClass {
}
| 30.25
| 117
| 0.816116
|
76a24cf39678441076d564f5ff1ea7ec64d0a408
| 7,025
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import org.apache.jasper.compiler.Localizer;
/**
* A simple ASCII byte reader. This is an optimized reader for reading
* byte streams that only contain 7-bit ASCII characters.
*
* @author Andy Clark, IBM
*
* @version $Id$
*/
public class ASCIIReader extends Reader {
//
// Data
//
/** Input stream. */
private final InputStream fInputStream;
/** Byte buffer. */
private final byte[] fBuffer;
//
// Constructors
//
/**
* Constructs an ASCII reader from the specified input stream
* and buffer size.
*
* @param inputStream The input stream.
* @param size The initial buffer size.
*/
public ASCIIReader(InputStream inputStream, int size) {
fInputStream = inputStream;
fBuffer = new byte[size];
}
//
// Reader methods
//
/**
* Read a single character. This method will block until a character is
* available, an I/O error occurs, or the end of the stream is reached.
*
* <p> Subclasses that intend to support efficient single-character input
* should override this method.
*
* @return The character read, as an integer in the range 0 to 127
* (<tt>0x00-0x7f</tt>), or -1 if the end of the stream has
* been reached
*
* @exception IOException If an I/O error occurs
*/
@Override
public int read() throws IOException {
int b0 = fInputStream.read();
if (b0 > 0x80) {
throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII",
Integer.toString(b0)));
}
return b0;
} // read():int
/**
* Read characters into a portion of an array. This method will block
* until some input is available, an I/O error occurs, or the end of the
* stream is reached.
*
* @param ch Destination buffer
* @param offset Offset at which to start storing characters
* @param length Maximum number of characters to read
*
* @return The number of characters read, or -1 if the end of the
* stream has been reached
*
* @exception IOException If an I/O error occurs
*/
@Override
public int read(char ch[], int offset, int length) throws IOException {
if (length > fBuffer.length) {
length = fBuffer.length;
}
int count = fInputStream.read(fBuffer, 0, length);
for (int i = 0; i < count; i++) {
int b0 = (0xff & fBuffer[i]); // Convert to unsigned
if (b0 > 0x80) {
throw new IOException(Localizer.getMessage("jsp.error.xml.invalidASCII",
Integer.toString(b0)));
}
ch[offset + i] = (char)b0;
}
return count;
} // read(char[],int,int)
/**
* Skip characters. This method will block until some characters are
* available, an I/O error occurs, or the end of the stream is reached.
*
* @param n The number of characters to skip
*
* @return The number of characters actually skipped
*
* @exception IOException If an I/O error occurs
*/
@Override
public long skip(long n) throws IOException {
return fInputStream.skip(n);
} // skip(long):long
/**
* Tell whether this stream is ready to be read.
*
* @return True if the next read() is guaranteed not to block for input,
* false otherwise. Note that returning false does not guarantee that the
* next read will block.
*
* @exception IOException If an I/O error occurs
*/
@Override
public boolean ready() throws IOException {
return false;
} // ready()
/**
* Tell whether this stream supports the mark() operation.
*/
@Override
public boolean markSupported() {
return fInputStream.markSupported();
} // markSupported()
/**
* Mark the present position in the stream. Subsequent calls to reset()
* will attempt to reposition the stream to this point. Not all
* character-input streams support the mark() operation.
*
* @param readAheadLimit Limit on the number of characters that may be
* read while still preserving the mark. After
* reading this many characters, attempting to
* reset the stream may fail.
*
* @exception IOException If the stream does not support mark(),
* or if some other I/O error occurs
*/
@Override
public void mark(int readAheadLimit) throws IOException {
fInputStream.mark(readAheadLimit);
} // mark(int)
/**
* Reset the stream. If the stream has been marked, then attempt to
* reposition it at the mark. If the stream has not been marked, then
* attempt to reset it in some way appropriate to the particular stream,
* for example by repositioning it to its starting point. Not all
* character-input streams support the reset() operation, and some support
* reset() without supporting mark().
*
* @exception IOException If the stream has not been marked,
* or if the mark has been invalidated,
* or if the stream does not support reset(),
* or if some other I/O error occurs
*/
@Override
public void reset() throws IOException {
fInputStream.reset();
} // reset()
/**
* Close the stream. Once a stream has been closed, further read(),
* ready(), mark(), or reset() invocations will throw an IOException.
* Closing a previously-closed stream, however, has no effect.
*
* @exception IOException If an I/O error occurs
*/
@Override
public void close() throws IOException {
fInputStream.close();
} // close()
} // class ASCIIReader
| 34.101942
| 88
| 0.606406
|
e69567e1528fa452ce3f184095698792b79d8138
| 1,458
|
package base.service.impl;
import java.util.List;
import java.util.function.Predicate;
import base.data.Gender;
import base.data.Person;
import base.service.Task;
import base.service.util.PersonLambda;
public class ProcessPersons implements Task {
@Override
public void execute() throws Exception {
System.out.println("=====Process persons Test=======");
List<Person> personList = Person.createShortList();
PersonLambda pLamb = new PersonLambda();
for(Person p:personList) {
p.printName();
}
// Predicates
Predicate<Person> allPeople = ppl -> ppl.getAge() >= 16;
Predicate<Person> allYounger = ppl -> ppl.getAge() >= 18 && ppl.getAge() <= 29 && ppl.getGender() == Gender.MALE;
Predicate<Person> allOlder = p -> p.getAge() >= 28 && p.getAge() <=65;
// Execute the task
System.out.println("============Processing the generation=============");
pLamb.reachYoungerContacts(personList, allYounger);
System.out.println("=============Finished processing the generation==========");
System.out.println("============Processing the generation=============");
pLamb.reachMiddleAgeContacts(personList, allPeople);
System.out.println("=============Finished processing the generation==========");
System.out.println("============Processing the generation=============");
pLamb.reachOlderContacts(personList, allOlder);
System.out.println("=============Finished processing the generation==========");
}
}
| 34.714286
| 115
| 0.64952
|
80a3910dd2e540ef7b96713322e0e6122ea848b8
| 5,696
|
/**
* Copyright 2011-2019 Asakusa Framework Team.
*
* 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.asakusafw.utils.gradle;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a command path.
* @since 0.9.2
*/
public class CommandPath {
static final Logger LOG = LoggerFactory.getLogger(CommandPath.class);
static final boolean WINDOWS = System.getProperty("os.name", "")
.toLowerCase(Locale.ENGLISH)
.startsWith("windows");
static final String ENV_PATH = "PATH";
static final String ENV_PATHEXT = "PATHEXT";
static final List<String> WINDOWS_PATH_EXTENSIONS;
static {
List<String> extensions = new ArrayList<>();
if (WINDOWS) {
Optional.ofNullable(System.getenv(ENV_PATHEXT))
.map(it -> Arrays.stream(it.split(Pattern.quote(File.pathSeparator))))
.orElseGet(Stream::empty)
.sequential()
.map(String::trim)
.filter(it -> it.isEmpty() == false)
.map(it -> it.toLowerCase(Locale.ENGLISH))
.forEach(extensions::add);
}
WINDOWS_PATH_EXTENSIONS = extensions;
}
private final List<Path> directories;
/**
* Creates a new instance.
* @param directories the path directories
*/
public CommandPath(List<? extends Path> directories) {
this.directories = new ArrayList<>(directories);
}
/**
* Returns an appended path.
* @param other to be appended in the tail of this path
* @return the appended path
*/
public CommandPath append(CommandPath other) {
List<Path> results = new ArrayList<>();
results.addAll(directories);
results.addAll(other.directories);
return new CommandPath(results);
}
/**
* Creates a new instance from environment variables.
* @return the created instance
*/
public static CommandPath system() {
return CommandPath.of(System.getenv(ENV_PATH));
}
/**
* Creates a new instance.
* @param pathString the path string
* @return the created instance
*/
public static CommandPath of(String pathString) {
if (pathString == null) {
return new CommandPath(Collections.emptyList());
}
List<Path> directories = Stream.of(pathString.split(Pattern.quote(File.pathSeparator)))
.map(String::trim)
.filter(s -> s.isEmpty() == false)
.map(Paths::get)
.collect(Collectors.toList());
return new CommandPath(directories);
}
/**
* Returns a resolved file path of the specified command.
* @param command the target command name
* @return the command file path, or {@code empty} if there is no such a command
*/
public Optional<Path> find(String command) {
return Stream.concat(
Stream.of(Paths.get(command)).filter(Path::isAbsolute),
directories.stream().map(d -> d.resolve(command)))
.flatMap(CommandPath::expand)
.filter(Files::isRegularFile)
.filter(Files::isExecutable)
.findFirst();
}
private static Stream<Path> expand(Path path) {
if (WINDOWS) {
String name = Optional.ofNullable(path.getFileName())
.map(Path::toString)
.orElse(null);
if (name == null || name.lastIndexOf('.') >= 0) {
// if already has extension, we don't add any extensions.
return Stream.of(path);
}
// otherwise, we append each %PathExt% value.
return WINDOWS_PATH_EXTENSIONS.stream()
.map(name::concat)
.map(path::resolveSibling);
} else {
return Stream.of(path);
}
}
/**
* Returns the path string.
* @return the path string
*/
public String asPathString() {
return directories.stream()
.map(Path::toAbsolutePath)
.map(Path::toString)
.collect(Collectors.joining(File.pathSeparator));
}
/**
* Launches the command.
* @param command the command location
* @param arguments the command arguments
* @param workingDir the working directory
* @param env the environment variables
* @return the exit status
*/
public static int launch(Path command, List<String> arguments, Path workingDir, Map<String, String> env) {
return new BasicCommandLauncher(workingDir, env).launch(command, arguments);
}
@Override
public String toString() {
return directories.toString();
}
}
| 32.363636
| 110
| 0.614642
|
355a115babb88698c82c8b077e8285efc9092468
| 6,667
|
package com.pushtorefresh.storio3.sqlite.operations.put;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.pushtorefresh.storio3.StorIOException;
import com.pushtorefresh.storio3.operations.PreparedOperation;
import com.pushtorefresh.storio3.sqlite.Changes;
import com.pushtorefresh.storio3.Interceptor;
import com.pushtorefresh.storio3.sqlite.SQLiteTypeMapping;
import com.pushtorefresh.storio3.sqlite.StorIOSQLite;
import com.pushtorefresh.storio3.sqlite.operations.internal.RxJavaUtils;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Single;
/**
* Prepared Put Operation for {@link StorIOSQLite}.
*
* @param <T> type of object to put.
*/
public class PreparedPutObject<T> extends PreparedPut<PutResult, T> {
@NonNull
private final T object;
@Nullable
private final PutResolver<T> explicitPutResolver;
PreparedPutObject(@NonNull StorIOSQLite storIOSQLite,
@NonNull T object,
@Nullable PutResolver<T> explicitPutResolver) {
super(storIOSQLite);
this.object = object;
this.explicitPutResolver = explicitPutResolver;
}
/**
* Creates {@link Flowable} which will perform Put Operation and send result to observer.
* <p>
* Returned {@link Flowable} will be "Cold Flowable", which means that it performs
* put only after subscribing to it. Also, it emits the result once.
* <p>
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>Operates on {@link StorIOSQLite#defaultRxScheduler()} if not {@code null}.</dd>
* </dl>
*
* @return non-null {@link Flowable} which will perform Put Operation.
* and send result to observer.
*/
@NonNull
@CheckResult
@Override
public Flowable<PutResult> asRxFlowable(@NonNull BackpressureStrategy backpressureStrategy) {
return RxJavaUtils.createFlowable(storIOSQLite, this, backpressureStrategy);
}
/**
* Creates {@link Single} which will perform Put Operation lazily when somebody subscribes to it and send result to observer.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>Operates on {@link StorIOSQLite#defaultRxScheduler()} if not {@code null}.</dd>
* </dl>
*
* @return non-null {@link Single} which will perform Put Operation.
* And send result to observer.
*/
@NonNull
@CheckResult
@Override
public Single<PutResult> asRxSingle() {
return RxJavaUtils.createSingle(storIOSQLite, this);
}
/**
* Creates {@link Completable} which will perform Put Operation lazily when somebody subscribes to it.
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>Operates on {@link StorIOSQLite#defaultRxScheduler()} if not {@code null}.</dd>
* </dl>
*
* @return non-null {@link Completable} which will perform Put Operation.
*/
@NonNull
@CheckResult
@Override
public Completable asRxCompletable() {
return RxJavaUtils.createCompletable(storIOSQLite, this);
}
@NonNull
@Override
protected Interceptor getRealCallInterceptor() {
return new RealCallInterceptor();
}
@NonNull
@Override
public T getData() {
return object;
}
private class RealCallInterceptor implements Interceptor {
@NonNull
@Override
public <Result, WrappedResult, Data> Result intercept(@NonNull PreparedOperation<Result, WrappedResult, Data> operation, @NonNull Chain chain) {
try {
final StorIOSQLite.LowLevel lowLevel = storIOSQLite.lowLevel();
final PutResolver<T> putResolver;
if (explicitPutResolver != null) {
putResolver = explicitPutResolver;
} else {
final SQLiteTypeMapping<T> typeMapping = lowLevel.typeMapping((Class<T>) object.getClass());
if (typeMapping == null) {
throw new IllegalStateException("Object does not have type mapping: " +
"object = " + object + ", object.class = " + object.getClass() + ", " +
"db was not affected by this operation, please add type mapping for this type");
}
putResolver = typeMapping.putResolver();
}
final PutResult putResult = putResolver.performPut(storIOSQLite, object);
if (putResult.wasInserted() || putResult.wasUpdated()) {
final Changes changes = Changes.newInstance(
putResult.affectedTables(),
putResult.affectedTags()
);
lowLevel.notifyAboutChanges(changes);
}
//noinspection unchecked
return (Result) putResult;
} catch (Exception exception) {
throw new StorIOException("Error has occurred during Put operation. object = " + object, exception);
}
}
}
/**
* Builder for {@link PreparedPutObject}.
*
* @param <T> type of object to put.
*/
public static class Builder<T> {
@NonNull
private final StorIOSQLite storIOSQLite;
@NonNull
private final T object;
private PutResolver<T> putResolver;
Builder(@NonNull StorIOSQLite storIOSQLite, @NonNull T object) {
this.storIOSQLite = storIOSQLite;
this.object = object;
}
/**
* Optional: Specifies {@link PutResolver} for Put Operation
* which allows you to customize behavior of Put Operation.
* <p>
* Can be set via {@link SQLiteTypeMapping}
* If it's not set via {@link SQLiteTypeMapping} or explicitly — exception will be thrown.
*
* @param putResolver put resolver.
* @return builder.
* @see DefaultPutResolver
*/
@NonNull
public Builder<T> withPutResolver(@NonNull PutResolver<T> putResolver) {
this.putResolver = putResolver;
return this;
}
/**
* Prepares Put Operation.
*
* @return {@link PreparedPutObject} instance.
*/
@NonNull
public PreparedPutObject<T> prepare() {
return new PreparedPutObject<T>(
storIOSQLite,
object,
putResolver
);
}
}
}
| 33.335
| 152
| 0.60987
|
dfe8501466fd3068b37cd5c0ec113c4ec434a60e
| 471
|
package com.geektcp.alpha.console.mps.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.geektcp.alpha.console.mps.model.entity.RolePermission;
/**
* <p>
* 角色权限表 服务类
* </p>
*/
public interface RolePermissionService extends IService<RolePermission> {
/**
* 更新角色权限
*
*
* @param roleId 角色
* @param permissionIds 权限列表
* @return
*/
void authPermissions(String roleId, String[] permissionIds);
}
| 19.625
| 73
| 0.677282
|
4af3e9607a8f6d9fab31f5aebe46ec89126cd5e6
| 966
|
package com.kristijangeorgiev.softdelete.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.kristijangeorgiev.softdelete.service.RoleService;
@RestController
@RepositoryRestController
@RequestMapping("/roles")
public class RoleController {
@Autowired
private RoleService roleService;
@ResponseStatus(code = HttpStatus.NO_CONTENT)
@RequestMapping(value = "/softDelete/{id}", method = RequestMethod.DELETE)
public void softDelete(@PathVariable("id") Long id) {
roleService.softDelete(id);
}
}
| 33.310345
| 75
| 0.833333
|
b119a40d1ebbd7a7a1eb165df22020a76fa9d09d
| 158
|
package models.shape;
// shapes
public abstract sealed class Shape permits Circle, Rectangle, Square {
public double getArea() {
return 0.0;
}
}
| 17.555556
| 70
| 0.689873
|
1045a2929c0975c61a00c6738a8b9804c7a464cf
| 20,868
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.s3a.commit.integration;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import com.google.common.collect.Sets;
import org.assertj.core.api.Assertions;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.s3a.S3AFileSystem;
import org.apache.hadoop.fs.s3a.S3AUtils;
import org.apache.hadoop.fs.s3a.commit.AbstractYarnClusterITest;
import org.apache.hadoop.fs.s3a.commit.CommitConstants;
import org.apache.hadoop.fs.s3a.commit.LoggingTextOutputFormat;
import org.apache.hadoop.fs.s3a.commit.files.SuccessData;
import org.apache.hadoop.fs.s3a.commit.magic.MagicS3GuardCommitter;
import org.apache.hadoop.fs.s3a.commit.staging.DirectoryStagingCommitter;
import org.apache.hadoop.fs.s3a.commit.staging.PartitionedStagingCommitter;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobStatus;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.DurationInfo;
import static org.apache.hadoop.fs.s3a.S3ATestUtils.disableFilesystemCaching;
import static org.apache.hadoop.fs.s3a.S3ATestUtils.lsR;
import static org.apache.hadoop.fs.s3a.S3AUtils.applyLocatedFiles;
import static org.apache.hadoop.fs.s3a.commit.CommitConstants.FS_S3A_COMMITTER_STAGING_TMP_PATH;
import static org.apache.hadoop.fs.s3a.commit.CommitConstants.MAGIC;
import static org.apache.hadoop.fs.s3a.commit.CommitConstants._SUCCESS;
import static org.apache.hadoop.fs.s3a.commit.InternalCommitterConstants.FS_S3A_COMMITTER_STAGING_UUID;
import static org.apache.hadoop.fs.s3a.commit.staging.Paths.getMultipartUploadCommitsDirectory;
import static org.apache.hadoop.fs.s3a.commit.staging.StagingCommitterConstants.STAGING_UPLOADS;
import static org.apache.hadoop.test.LambdaTestUtils.intercept;
/**
* Test an MR Job with all the different committers.
* <p>
* This is a fairly complex parameterization: it is designed to
* avoid the overhead of starting a Yarn cluster for
* individual committer types, so speed up operations.
* <p>
* It also implicitly guarantees that there is never more than one of these
* MR jobs active at a time, so avoids overloading the test machine with too
* many processes.
* How the binding works:
* <ol>
* <li>
* Each parameterized suite is configured through its own
* {@link CommitterTestBinding} subclass.
* </li>
* <li>
* JUnit runs these test suites one parameterized binding at a time.
* </li>
* <li>
* The test suites are declared to be executed in ascending order, so
* that for a specific binding, the order is {@link #test_000()},
* {@link #test_100()} {@link #test_200_execute()} and finally
* {@link #test_500()}.
* </li>
* <li>
* {@link #test_000()} calls {@link CommitterTestBinding#validate()} to
* as to validate the state of the committer. This is primarily to
* verify that the binding setup mechanism is working.
* </li>
* <li>
* {@link #test_100()} is relayed to
* {@link CommitterTestBinding#test_100()},
* for any preflight tests.
* </li>
* <li>
* The {@link #test_200_execute()} test runs the MR job for that
* particular binding with standard reporting and verification of the
* outcome.
* </li>
* <li>
* {@link #test_500()} test is relayed to
* {@link CommitterTestBinding#test_500()}, for any post-MR-job tests.
* </ol>
*
* A new S3A FileSystem instance is created for each test_ method, so the
* pre-execute and post-execute validators cannot inspect the state of the
* FS as part of their tests.
* However, as the MR workers and AM all run in their own processes, there's
* generally no useful information about the job in the local S3AFileSystem
* instance.
*/
@RunWith(Parameterized.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ITestS3ACommitterMRJob extends AbstractYarnClusterITest {
private static final Logger LOG =
LoggerFactory.getLogger(ITestS3ACommitterMRJob.class);
/**
* Test array for parameterized test runs.
*
* @return the committer binding for this run.
*/
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> params() {
return Arrays.asList(new Object[][]{
{new DirectoryCommitterTestBinding()},
{new PartitionCommitterTestBinding()},
{new MagicCommitterTestBinding()},
});
}
/**
* The committer binding for this instance.
*/
private final CommitterTestBinding committerTestBinding;
/**
* Parameterized constructor.
* @param committerTestBinding binding for the test.
*/
public ITestS3ACommitterMRJob(
final CommitterTestBinding committerTestBinding) {
this.committerTestBinding = committerTestBinding;
}
@Override
public void setup() throws Exception {
super.setup();
// configure the test binding for this specific test case.
committerTestBinding.setup(getClusterBinding(), getFileSystem());
}
@Override
protected Configuration createConfiguration() {
Configuration conf = super.createConfiguration();
disableFilesystemCaching(conf);
return conf;
}
@Rule
public final TemporaryFolder localFilesDir = new TemporaryFolder();
@Override
protected String committerName() {
return committerTestBinding.getCommitterName();
}
@Override
public boolean useInconsistentClient() {
return committerTestBinding.useInconsistentClient();
}
/**
* Verify that the committer binding is happy.
*/
@Test
public void test_000() throws Throwable {
committerTestBinding.validate();
}
@Test
public void test_100() throws Throwable {
committerTestBinding.test_100();
}
@Test
public void test_200_execute() throws Exception {
describe("Run an MR with committer %s", committerName());
S3AFileSystem fs = getFileSystem();
// final dest is in S3A
// we can't use the method name as the template places square braces into
// that and URI creation fails.
Path outputPath = path("ITestS3ACommitterMRJob-execute-"+ committerName());
// create and delete to force in a tombstone marker -see HADOOP-16207
fs.mkdirs(outputPath);
fs.delete(outputPath, true);
String commitUUID = UUID.randomUUID().toString();
String suffix = isUniqueFilenames() ? ("-" + commitUUID) : "";
int numFiles = getTestFileCount();
// create all the input files on the local FS.
List<String> expectedFiles = new ArrayList<>(numFiles);
Set<String> expectedKeys = Sets.newHashSet();
for (int i = 0; i < numFiles; i += 1) {
File file = localFilesDir.newFile(i + ".text");
try (FileOutputStream out = new FileOutputStream(file)) {
out.write(("file " + i).getBytes(StandardCharsets.UTF_8));
}
String filename = String.format("part-m-%05d%s", i, suffix);
Path path = new Path(outputPath, filename);
expectedFiles.add(path.toString());
expectedKeys.add("/" + fs.pathToKey(path));
}
Collections.sort(expectedFiles);
Job mrJob = createJob(newJobConf());
JobConf jobConf = (JobConf) mrJob.getConfiguration();
mrJob.setOutputFormatClass(LoggingTextOutputFormat.class);
FileOutputFormat.setOutputPath(mrJob, outputPath);
File mockResultsFile = localFilesDir.newFile("committer.bin");
mockResultsFile.delete();
String committerPath = "file:" + mockResultsFile;
jobConf.set("mock-results-file", committerPath);
// setting up staging options is harmless for other committers
jobConf.set(FS_S3A_COMMITTER_STAGING_UUID, commitUUID);
mrJob.setInputFormatClass(TextInputFormat.class);
FileInputFormat.addInputPath(mrJob,
new Path(localFilesDir.getRoot().toURI()));
mrJob.setMapperClass(MapClass.class);
mrJob.setNumReduceTasks(0);
// an attempt to set up log4j properly, which clearly doesn't work
URL log4j = getClass().getClassLoader().getResource("log4j.properties");
if (log4j != null && "file".equals(log4j.getProtocol())) {
Path log4jPath = new Path(log4j.toURI());
LOG.debug("Using log4j path {}", log4jPath);
mrJob.addFileToClassPath(log4jPath);
String sysprops = String.format("-Xmx128m -Dlog4j.configuration=%s",
log4j);
jobConf.set(JobConf.MAPRED_MAP_TASK_JAVA_OPTS, sysprops);
jobConf.set(JobConf.MAPRED_REDUCE_TASK_JAVA_OPTS, sysprops);
jobConf.set("yarn.app.mapreduce.am.command-opts", sysprops);
}
applyCustomConfigOptions(jobConf);
// fail fast if anything goes wrong
mrJob.setMaxMapAttempts(1);
try (DurationInfo ignore = new DurationInfo(LOG, "Job Submit")) {
mrJob.submit();
}
String jobID = mrJob.getJobID().toString();
String logLocation = "logs under "
+ getYarn().getTestWorkDir().getAbsolutePath();
try (DurationInfo ignore = new DurationInfo(LOG, "Job Execution")) {
mrJob.waitForCompletion(true);
}
JobStatus status = mrJob.getStatus();
if (!mrJob.isSuccessful()) {
// failure of job.
// be as meaningful as possible.
String message =
String.format("Job %s failed in state %s with cause %s.\n"
+ "Consult %s",
jobID,
status.getState(),
status.getFailureInfo(),
logLocation);
LOG.error(message);
fail(message);
}
waitForConsistency();
Path successPath = new Path(outputPath, _SUCCESS);
SuccessData successData = validateSuccessFile(outputPath,
committerName(),
fs,
"MR job " + jobID,
1);
String commitData = successData.toString();
FileStatus[] results = fs.listStatus(outputPath,
S3AUtils.HIDDEN_FILE_FILTER);
int fileCount = results.length;
Assertions.assertThat(fileCount)
.describedAs("No files from job %s in output directory %s; see %s",
jobID,
outputPath,
logLocation)
.isNotEqualTo(0);
List<String> actualFiles = Arrays.stream(results)
.map(s -> s.getPath().toString())
.sorted()
.collect(Collectors.toList());
Assertions.assertThat(actualFiles)
.describedAs("Files found in %s", outputPath)
.isEqualTo(expectedFiles);
Assertions.assertThat(successData.getFilenames())
.describedAs("Success files listed in %s:%s",
successPath, commitData)
.isNotEmpty()
.containsExactlyInAnyOrderElementsOf(expectedKeys);
assertPathDoesNotExist("temporary dir should only be from"
+ " classic file committers",
new Path(outputPath, CommitConstants.TEMPORARY));
customPostExecutionValidation(outputPath, successData);
}
@Override
protected void applyCustomConfigOptions(final JobConf jobConf)
throws IOException {
committerTestBinding.applyCustomConfigOptions(jobConf);
}
@Override
protected void customPostExecutionValidation(final Path destPath,
final SuccessData successData) throws Exception {
committerTestBinding.validateResult(destPath, successData);
}
/**
* This is the extra test which committer test bindings can add.
*/
@Test
public void test_500() throws Throwable {
committerTestBinding.test_500();
}
/**
* Test Mapper.
* This is executed in separate process, and must not make any assumptions
* about external state.
*/
public static class MapClass
extends Mapper<LongWritable, Text, LongWritable, Text> {
private int operations;
private String id = "";
private LongWritable l = new LongWritable();
private Text t = new Text();
@Override
protected void setup(Context context)
throws IOException, InterruptedException {
super.setup(context);
// force in Log4J logging
org.apache.log4j.BasicConfigurator.configure();
// and pick up scale test flag as passed down
boolean scaleMap = context.getConfiguration()
.getBoolean(KEY_SCALE_TESTS_ENABLED, false);
operations = scaleMap ? SCALE_TEST_KEYS : BASE_TEST_KEYS;
id = context.getTaskAttemptID().toString();
}
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
for (int i = 0; i < operations; i++) {
l.set(i);
t.set(String.format("%s:%05d", id, i));
context.write(l, t);
}
}
}
/**
* A binding class for committer tests.
* Subclasses of this will be instantiated and drive the parameterized
* test suite.
*
* These classes will be instantiated in a static array of the suite, and
* not bound to a cluster binding or filesystem.
*
* The per-method test {@link #setup()} method will call
* {@link #setup(ClusterBinding, S3AFileSystem)}, to link the instance
* to the specific test cluster <i>and test filesystem</i> in use
* in that test.
*/
private abstract static class CommitterTestBinding {
/**
* Name.
*/
private final String committerName;
/**
* Cluster binding.
*/
private ClusterBinding binding;
/**
* The S3A filesystem.
*/
private S3AFileSystem remoteFS;
/**
* Constructor.
* @param committerName name of the committer for messages.
*/
protected CommitterTestBinding(final String committerName) {
this.committerName = committerName;
}
/**
* Set up the test binding: this is called during test setup.
* @param cluster the active test cluster.
* @param fs the S3A Filesystem used as a destination.
*/
private void setup(
ClusterBinding cluster,
S3AFileSystem fs) {
this.binding = cluster;
this.remoteFS = fs;
}
protected String getCommitterName() {
return committerName;
}
protected ClusterBinding getBinding() {
return binding;
}
protected S3AFileSystem getRemoteFS() {
return remoteFS;
}
protected FileSystem getClusterFS() throws IOException {
return getBinding().getClusterFS();
}
@Override
public String toString() {
return committerName;
}
/**
* Override point to let implementations tune the MR Job conf.
* @param jobConf configuration
*/
protected void applyCustomConfigOptions(JobConf jobConf)
throws IOException {
}
/**
* Should the inconsistent S3A client be used?
* @return true for inconsistent listing
*/
public abstract boolean useInconsistentClient();
/**
* Override point for any committer specific validation operations;
* called after the base assertions have all passed.
* @param destPath destination of work
* @param successData loaded success data
* @throws Exception failure
*/
protected void validateResult(Path destPath,
SuccessData successData)
throws Exception {
}
/**
* A test to run before the main {@link #test_200_execute()} test is
* invoked.
* @throws Throwable failure.
*/
void test_100() throws Throwable {
}
/**
* A test to run after the main {@link #test_200_execute()} test is
* invoked.
* @throws Throwable failure.
*/
void test_500() throws Throwable {
}
/**
* Validate the state of the binding.
* This is called in {@link #test_000()} so will
* fail independently of the other tests.
* @throws Throwable failure.
*/
public void validate() throws Throwable {
assertNotNull("Not bound to a cluster", binding);
assertNotNull("No cluster filesystem", getClusterFS());
assertNotNull("No yarn cluster", binding.getYarn());
}
}
/**
* The directory staging committer.
*/
private static final class DirectoryCommitterTestBinding
extends CommitterTestBinding {
private DirectoryCommitterTestBinding() {
super(DirectoryStagingCommitter.NAME);
}
/**
* @return true for inconsistent listing
*/
public boolean useInconsistentClient() {
return true;
}
/**
* Verify that staging commit dirs are made absolute under the user's
* home directory, so, in a secure cluster, private.
*/
@Override
void test_100() throws Throwable {
FileSystem fs = getClusterFS();
Configuration conf = fs.getConf();
String pri = "private";
conf.set(FS_S3A_COMMITTER_STAGING_TMP_PATH, pri);
Path dir = getMultipartUploadCommitsDirectory(conf, "uuid");
Assertions.assertThat(dir.isAbsolute())
.describedAs("non-absolute path")
.isTrue();
String stagingTempDir = dir.toString().toLowerCase(Locale.ENGLISH);
String self = UserGroupInformation.getCurrentUser()
.getShortUserName().toLowerCase(Locale.ENGLISH);
Assertions.assertThat(stagingTempDir)
.describedAs("Staging committer temp path in cluster")
.contains(pri + "/" + self)
.endsWith("uuid/" + STAGING_UPLOADS);
}
}
/**
* The partition committer test binding.
*/
private static final class PartitionCommitterTestBinding
extends CommitterTestBinding {
private PartitionCommitterTestBinding() {
super(PartitionedStagingCommitter.NAME);
}
/**
* @return true for inconsistent listing
*/
public boolean useInconsistentClient() {
return true;
}
}
/**
* The magic committer test binding.
* This includes extra result validation.
*/
private static final class MagicCommitterTestBinding
extends CommitterTestBinding {
private MagicCommitterTestBinding() {
super(MagicS3GuardCommitter.NAME);
}
/**
* @return we need a consistent store.
*/
public boolean useInconsistentClient() {
return false;
}
/**
* The result validation here is that there isn't a __magic directory
* any more.
* @param destPath destination of work
* @param successData loaded success data
* @throws Exception failure
*/
@Override
protected void validateResult(final Path destPath,
final SuccessData successData)
throws Exception {
Path magicDir = new Path(destPath, MAGIC);
// if an FNFE isn't raised on getFileStatus, list out the directory
// tree
S3AFileSystem fs = getRemoteFS();
// log the contents
lsR(fs, destPath, true);
intercept(FileNotFoundException.class, () -> {
final FileStatus st = fs.getFileStatus(magicDir);
StringBuilder result = new StringBuilder("Found magic dir which should"
+ " have been deleted at ").append(st).append('\n');
result.append(" [");
applyLocatedFiles(fs.listFiles(magicDir, true),
(status) -> result.append(" ").append(status.getPath()).append('\n'));
result.append("]");
return result.toString();
});
}
}
}
| 32.353488
| 103
| 0.690004
|
bfdddf0f8dd9566d84f4a75f6004cc530bcf52f8
| 1,047
|
/*
* Copyright (C) 2015 Karumi.
*
* 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.karumi.rosie.domain.usecase.error;
/**
* Callback invoked when an error happens inside of a use case.
*/
public interface OnErrorCallback<T extends Error> {
/**
* Method called when an error has occurred while executing a use case.
*
* @param error Error thrown by the use case
* @return true if the error has been consumed, meaning it won't be notified to
* other registered callbacks
*/
boolean onError(T error);
}
| 31.727273
| 81
| 0.725883
|
33da2bb0bd5c735540097c86aa6d80a50252537f
| 511
|
package org.shkim.codility.sorting;
import java.util.HashSet;
/**
* https://codility.com/demo/results/trainingE437UV-PU6/ 41% not allow 0
* https://codility.com/demo/results/trainingB2WS6U-TKT/ 75% timeout
* last this code is 100 use hashset.
*
* @author parad
*
*/
public class Distinct
{
public static int solution(int A[])
{
int N = A.length;
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < N; i++)
{
set.add(A[i]);
}
int cnt = set.size();
return cnt;
}
}
| 16.483871
| 72
| 0.630137
|
a0cf071e81eb6efff61650b56eb2d1a7914a99aa
| 2,615
|
package ch.sebastianhaeni.semantic.web;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
class Helper {
static void executeQueryOnModel(String modelFile, String queryFile) {
Model model = Helper.loadModel(modelFile);
Query query = Helper.loadQuery(queryFile);
QueryExecution queryExecution = QueryExecutionFactory.create(query, model);
execute(query, queryExecution);
}
private static void execute(Query query, QueryExecution queryExecution) {
switch (query.getQueryType()) {
case Query.QueryTypeAsk:
System.out.print(queryExecution.execAsk());
break;
case Query.QueryTypeSelect:
ResultSet results = queryExecution.execSelect();
ResultSetFormatter.out(System.out, results, query);
break;
case Query.QueryTypeConstruct:
Model constructedModel = queryExecution.execConstruct();
constructedModel.write(System.out, "TTL");
break;
default:
System.out.println("Query type not supported");
System.exit(1);
}
}
private static Model loadModel(String file) {
String inputFile = "src/test/resources/" + file;
// create an empty model
Model model = ModelFactory.createDefaultModel();
// use the FileManager to find the input file
InputStream in = FileManager.get().open(inputFile);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFile + " not found");
}
// read the RDF/XML file
model.read(in, null, Converter.parseInputFormat(file));
return model;
}
private static Query loadQuery(String file) {
byte[] encoded = new byte[0];
try {
encoded = Files.readAllBytes(Paths.get("src/test/resources/" + file));
} catch (IOException e) {
e.printStackTrace();
}
String queryString = new String(encoded);
return QueryFactory.create(queryString);
}
static void executeQueryOnEndpoint(String endpointUrl, String queryFile) {
Query query = Helper.loadQuery(queryFile);
QueryExecution queryExecution = QueryExecutionFactory.sparqlService(endpointUrl, query);
execute(query, queryExecution);
}
}
| 31.890244
| 96
| 0.634417
|
8e28a9b0850311ddb6305d6fb31b0e9533d7e699
| 667
|
package com.purgeteam.log.trace.service.a.demo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* @author purgeyao
* @since 1.0
*/
@Slf4j
@Aspect
@Component
public class TestAspect {
@Around("execution(public * com.purgeteam.log.trace.service.a.demo.TestService.test())")
public Object fun1(ProceedingJoinPoint point) throws Throwable {
// ...(方法执行前的逻辑)
Object result = point.proceed();
// ...(方法执行后的逻辑)
log.info("切面");
return result;
}
}
| 24.703704
| 92
| 0.70015
|
56b21719ae100babc2648492efa3b62a04b4696e
| 1,402
|
package com.bombo.cheatbot.images;
import com.bombo.cheatbot.CheatApplication;
import com.bombo.cheatbot.ScreenCapture;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ImageAnalyze {
@Getter@Setter
private int x, y, width, height;
private double limitRatio;
@JsonIgnore@Getter
private BufferedImage reference;
@JsonIgnore@Getter
private BufferedImage currentImage;
@JsonIgnore
private long lastImageChanged;
@JsonIgnore@Getter
private boolean triggered;
public ImageAnalyze(double limitRatio, Rectangle rect) {
this.limitRatio = limitRatio;
this.x = rect.x;
this.y = rect.y;
this.width = rect.width;
this.height = rect.height;
this.triggered = false;
}
public boolean computeTriggered(BufferedImage image) {
triggered = false;
currentImage = image;
if (reference != null) {
double diff = ImageComparator.getDifferencePercent(reference, currentImage);
if (diff > limitRatio) triggered = true;
}
return triggered;
}
public void saveReference() {
reference = ScreenCapture.capture(CheatApplication.getInstance().getSelectedApplication().getPointer(), new Rectangle(x, y, width, height));
}
}
| 28.04
| 148
| 0.686876
|
c74070bd5595f4a93209ad6da8b1241b02a03537
| 2,374
|
import jgh.javagraph.geometry.voronoi.CircleEvent;
import jgh.javagraph.geometry.voronoi.TreeItem;
import jgh.javagraph.geometry.voronoi.Node2d;
import org.junit.Assert;
import org.junit.Test;
public class VoronoiTest {
@Test
public void CircleEventTest1(){
Node2d n1 = new Node2d(0, 10);
Node2d n2 = new Node2d(5, 10);
Node2d n3 = new Node2d(10, 0);
CircleEvent ce = new CircleEvent(new TreeItem(n1), new TreeItem(n2), new TreeItem(n3));
ce.calculateCircle();
Assert.assertTrue(Math.abs(ce.getR() - 7.9) < 0.1f);
}
@Test
public void CircleEventTest2(){
Node2d n1 = new Node2d(0, 10);
Node2d n2 = new Node2d(0, 11);
Node2d n3 = new Node2d(16, 34);
CircleEvent ce = new CircleEvent(new TreeItem(n1), new TreeItem(n2), new TreeItem(n3));
ce.calculateCircle();
Assert.assertTrue(Math.abs(ce.getR() - 25.25495) < 0.1f);
}
@Test
public void CircleEventTest3(){
//all points are collinear and x values are all equal
Node2d n1 = new Node2d(0, 10);
Node2d n2 = new Node2d(0, 10);
Node2d n3 = new Node2d(0, 10);
CircleEvent ce = new CircleEvent(new TreeItem(n1), new TreeItem(n2), new TreeItem(n3));
boolean canCalculate = ce.calculateCircle();
Assert.assertTrue(canCalculate == false);
}
@Test
public void CircleEventTest4(){
// all points are collinear
Node2d n1 = new Node2d(2, 10);
Node2d n2 = new Node2d(10, 50);
Node2d n3 = new Node2d(26, 130);
CircleEvent ce = new CircleEvent(new TreeItem(n1), new TreeItem(n2), new TreeItem(n3));
boolean canCalculate = ce.calculateCircle();
Assert.assertTrue(canCalculate == false);
}
@Test
public void CircleEventTest5(){
// all points are ALMOST collinear, but not quite. This should
// give a huge circle with a radius very far from all points.
Node2d n1 = new Node2d(2, 10);
Node2d n2 = new Node2d(10.1f, 50);
Node2d n3 = new Node2d(26.2f, 130.05f);
CircleEvent ce = new CircleEvent(new TreeItem(n1), new TreeItem(n2), new TreeItem(n3));
boolean canCalculate = ce.calculateCircle();
Assert.assertTrue(canCalculate == true);
Assert.assertTrue(Math.abs(ce.getR() - 46322.7) < 1f);
}
}
| 33.43662
| 95
| 0.625527
|
22bdab44c07fe51e60a19d984e2575ba879a1293
| 8,505
|
package com.github.unidbg.hook.hookzz;
import com.github.unidbg.Emulator;
import com.github.unidbg.Family;
import com.github.unidbg.Svc;
import com.github.unidbg.Symbol;
import com.github.unidbg.arm.Arm64Svc;
import com.github.unidbg.arm.ArmSvc;
import com.github.unidbg.arm.context.RegisterContext;
import com.github.unidbg.hook.BaseHook;
import com.github.unidbg.hook.ReplaceCallback;
import com.github.unidbg.memory.SvcMemory;
import com.github.unidbg.pointer.UnidbgPointer;
import com.sun.jna.Pointer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Stack;
/**
* 对32位支持比较好
*/
public final class HookZz extends BaseHook implements IHookZz {
private static final Log log = LogFactory.getLog(HookZz.class);
public static HookZz getInstance(Emulator<?> emulator) {
HookZz hookZz = emulator.get(HookZz.class.getName());
if (hookZz == null) {
hookZz = new HookZz(emulator);
emulator.set(HookZz.class.getName(), hookZz);
}
return hookZz;
}
private static final int RS_SUCCESS = 1;
private final Symbol zz_enable_arm_arm64_b_branch, zz_disable_arm_arm64_b_branch;
private final Symbol zzReplace;
private final Symbol zzWrap;
private final Symbol zzDynamicBinaryInstrumentation;
private HookZz(Emulator<?> emulator) {
super(emulator, "libhookzz");
boolean isIOS = emulator.getFamily() == Family.iOS;
zz_enable_arm_arm64_b_branch = module.findSymbolByName(isIOS ? "_zz_enable_arm_arm64_b_branch" : "zz_enable_arm_arm64_b_branch", false);
zz_disable_arm_arm64_b_branch = module.findSymbolByName(isIOS ? "_zz_disable_arm_arm64_b_branch" : "zz_disable_arm_arm64_b_branch", false);
zzReplace = module.findSymbolByName(isIOS ? "_ZzReplace" : "ZzReplace", false);
zzWrap = module.findSymbolByName(isIOS ? "_ZzWrap" : "ZzWrap", false);
zzDynamicBinaryInstrumentation = module.findSymbolByName(isIOS ? "_ZzDynamicBinaryInstrumentation" : "ZzDynamicBinaryInstrumentation", false);
if (log.isDebugEnabled()) {
log.debug("zzReplace=" + zzReplace + ", zzWrap=" + zzWrap);
}
if (zz_enable_arm_arm64_b_branch == null) {
throw new IllegalStateException("zz_enable_arm_arm64_b_branch is null");
}
if (zz_disable_arm_arm64_b_branch == null) {
throw new IllegalStateException("zz_disable_arm_arm64_b_branch is null");
}
if (zzReplace == null) {
throw new IllegalStateException("zzReplace is null");
}
if (zzWrap == null) {
throw new IllegalStateException("zzWrap is null");
}
if (zzDynamicBinaryInstrumentation == null) {
throw new IllegalStateException("zzDynamicBinaryInstrumentation is null");
}
}
@Override
public void enable_arm_arm64_b_branch() {
int ret = zz_enable_arm_arm64_b_branch.call(emulator)[0].intValue();
if (ret != RS_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
}
@Override
public void disable_arm_arm64_b_branch() {
int ret = zz_disable_arm_arm64_b_branch.call(emulator)[0].intValue();
if (ret != RS_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
}
@Override
public void replace(long functionAddress, final ReplaceCallback callback) {
replace(functionAddress, callback, false);
}
@Override
public void replace(Symbol symbol, ReplaceCallback callback) {
replace(symbol, callback, false);
}
@Override
public void replace(long functionAddress, Svc svc) {
if (svc == null) {
throw new NullPointerException();
}
final Pointer originCall = emulator.getMemory().malloc(emulator.getPointerSize(), false).getPointer();
Pointer callback = emulator.getSvcMemory().registerSvc(svc);
int ret = zzReplace.call(emulator, UnidbgPointer.pointer(emulator, functionAddress), callback, originCall)[0].intValue();
if (ret != RS_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
}
@Override
public void replace(Symbol symbol, Svc svc) {
replace(symbol.getAddress(), svc);
}
@Override
public void replace(long functionAddress, ReplaceCallback callback, boolean enablePostCall) {
final Pointer originCall = emulator.getMemory().malloc(emulator.getPointerSize(), false).getPointer();
Pointer replaceCall = createReplacePointer(callback, originCall, enablePostCall);
int ret = zzReplace.call(emulator, UnidbgPointer.pointer(emulator, functionAddress), replaceCall, originCall)[0].intValue();
if (ret != RS_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
}
@Override
public void replace(Symbol symbol, ReplaceCallback callback, boolean enablePostCall) {
replace(symbol.getAddress(), callback, enablePostCall);
}
@Override
public <T extends RegisterContext> void wrap(Symbol symbol, WrapCallback<T> callback) {
wrap(symbol.getAddress(), callback);
}
@SuppressWarnings("unchecked")
@Override
public <T extends RegisterContext> void wrap(long functionAddress, final WrapCallback<T> callback) {
SvcMemory svcMemory = emulator.getSvcMemory();
final Stack<Object> context = new Stack<>();
Pointer preCall = svcMemory.registerSvc(emulator.is32Bit() ? new ArmSvc() {
@Override
public long handle(Emulator<?> emulator) {
callback.preCall(emulator, (T) new HookZzArm32RegisterContextImpl(emulator, context), new ArmHookEntryInfo(emulator));
return 0;
}
} : new Arm64Svc() {
@Override
public long handle(Emulator<?> emulator) {
callback.preCall(emulator, (T) new HookZzArm64RegisterContextImpl(emulator, context), new Arm64HookEntryInfo(emulator));
return 0;
}
});
Pointer postCall = svcMemory.registerSvc(emulator.is32Bit() ? new ArmSvc() {
@Override
public long handle(Emulator<?> emulator) {
callback.postCall(emulator, (T) new HookZzArm32RegisterContextImpl(emulator, context), new ArmHookEntryInfo(emulator));
return 0;
}
} : new Arm64Svc() {
@Override
public long handle(Emulator<?> emulator) {
callback.postCall(emulator, (T) new HookZzArm64RegisterContextImpl(emulator, context), new Arm64HookEntryInfo(emulator));
return 0;
}
});
int ret = zzWrap.call(emulator, UnidbgPointer.pointer(emulator, functionAddress), preCall, postCall)[0].intValue();
if (ret != RS_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
}
@Override
public <T extends RegisterContext> void instrument(Symbol symbol, InstrumentCallback<T> callback) {
instrument(symbol.getAddress(), callback);
}
@SuppressWarnings("unchecked")
@Override
public <T extends RegisterContext> void instrument(long functionAddress, final InstrumentCallback<T> callback) {
SvcMemory svcMemory = emulator.getSvcMemory();
Pointer dbiCall = svcMemory.registerSvc(emulator.is32Bit() ? new ArmSvc() {
private final Stack<Object> context = new Stack<>();
@Override
public long handle(Emulator<?> emulator) {
callback.dbiCall(emulator, (T) new HookZzArm32RegisterContextImpl(emulator, context), new ArmHookEntryInfo(emulator));
return 0;
}
} : new Arm64Svc() {
private final Stack<Object> context = new Stack<>();
@Override
public long handle(Emulator<?> emulator) {
callback.dbiCall(emulator, (T) new HookZzArm64RegisterContextImpl(emulator, context), new Arm64HookEntryInfo(emulator));
return 0;
}
});
int ret = zzDynamicBinaryInstrumentation.call(emulator, UnidbgPointer.pointer(emulator, functionAddress), dbiCall)[0].intValue();
if (ret != RS_SUCCESS) {
throw new IllegalStateException("ret=" + ret);
}
}
@Override
public void switch_to_file_log(String path) {
throw new UnsupportedOperationException();
}
}
| 40.5
| 150
| 0.657496
|
60e9ee337a8fe8d483e9717c4493cb0b20597812
| 3,507
|
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ratpack.stream.internal;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import ratpack.func.Action;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
public class GatedPublisher<T> implements Publisher<T> {
private final Publisher<T> upstream;
private final Action<? super Runnable> releaseReceiver;
public GatedPublisher(Publisher<T> upstream, Action<? super Runnable> releaseReceiver) {
this.upstream = upstream;
this.releaseReceiver = releaseReceiver;
}
@Override
public void subscribe(final Subscriber<? super T> downstream) {
final GatedSubscriber<? super T> gatedSubscriber = new GatedSubscriber<>(downstream);
try {
releaseReceiver.execute((Runnable) gatedSubscriber::open);
} catch (final Throwable e) {
downstream.onSubscribe(new Subscription() {
@Override
public void request(long n) {
downstream.onError(e);
}
@Override
public void cancel() {
}
});
}
upstream.subscribe(gatedSubscriber);
}
private static class GatedSubscriber<T> implements Subscriber<T> {
private Subscription upstreamSubscription;
private final Subscriber<T> downstream;
private final AtomicBoolean open = new AtomicBoolean();
private final AtomicBoolean done = new AtomicBoolean();
private final AtomicBoolean draining = new AtomicBoolean();
private final AtomicLong waiting = new AtomicLong();
public GatedSubscriber(Subscriber<T> downstream) {
this.downstream = downstream;
}
private void open() {
open.set(true);
drain();
}
private void drain() {
if (draining.compareAndSet(false, true)) {
try {
if (open.get()) {
long requested = waiting.getAndSet(0);
upstreamSubscription.request(requested);
}
} finally {
draining.set(false);
}
}
if (open.get() && waiting.get() > 0) {
drain();
}
}
@Override
public void onSubscribe(Subscription s) {
upstreamSubscription = s;
downstream.onSubscribe(new DownstreamSubscription());
}
@Override
public void onNext(T t) {
downstream.onNext(t);
}
@Override
public void onError(Throwable t) {
downstream.onError(t);
}
@Override
public void onComplete() {
downstream.onComplete();
}
private class DownstreamSubscription implements Subscription {
@Override
public void request(long n) {
if (open.get() && !done.get()) {
upstreamSubscription.request(n);
} else {
waiting.addAndGet(n);
}
}
@Override
public void cancel() {
upstreamSubscription.cancel();
}
}
}
}
| 26.568182
| 90
| 0.659253
|
cb9f9643d0ca946771b92c97739dbabeae8af93c
| 386
|
package com.java3y.austin.pipeline;
import java.util.List;
/**
* 业务执行模板(把责任链的逻辑串起来)
* @author 3y
*/
public class ProcessTemplate {
private List<BusinessProcess> processList;
public List<BusinessProcess> getProcessList() {
return processList;
}
public void setProcessList(List<BusinessProcess> processList) {
this.processList = processList;
}
}
| 20.315789
| 67
| 0.702073
|
5d68b780ffa24d920af6a8c5a1d76550d3426900
| 2,118
|
package de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.database;
import com.vaadin.data.util.sqlcontainer.query.generator.filter.QueryBuilder;
import de.unioninvestment.eai.portal.portlet.crud.domain.model.DatabaseQueryContainer;
import de.unioninvestment.eai.portal.portlet.crud.domain.model.Table;
import de.unioninvestment.eai.portal.portlet.crud.scripting.model.ScriptRow;
import groovy.lang.GString;
import org.codehaus.groovy.runtime.GStringImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Created by cmj on 13.07.14.
*/
public class QueryDeleteStatementGenerator implements QueryStatementGenerator {
private final Table table;
private String tablename;
private List<String> idColumns;
public QueryDeleteStatementGenerator(Table table) {
this.table = table;
}
private void updateConfig() {
if (tablename == null) {
DatabaseQueryContainer container = (DatabaseQueryContainer) table.getContainer();
tablename = container.getTablename();
idColumns = table.getColumns().getPrimaryKeyNames();
checkArgument(tablename != null, "Cannot generate DELETE statements - Table name needed");
checkArgument(idColumns.size() >= 1, "Cannot generate DELETE statements - at least one primary key column must exist");
}
}
public GString generateStatement(ScriptRow row) {
updateConfig();
Object[] values = new Object[idColumns.size()];
ArrayList<String> strings = new ArrayList<String>(values.length + 1);
String head = "DELETE FROM " + QueryBuilder.quote(tablename) + " WHERE ";
int idx = 0;
Map<String,Object> idValues = row.getId();
for (String idName : idColumns) {
values[idx++] = idValues.get(idName);
strings.add(head + QueryBuilder.quote(idName) + "=");
head = " AND ";
}
return new GStringImpl(values, strings.toArray(new String[strings.size()]));
}
}
| 34.721311
| 131
| 0.694995
|
5e29ac1f5ec6c0470885bf1198c611c901ad107f
| 4,209
|
package com.ximalaya.ting.android.opensdk.model.banner;
import com.google.gson.annotations.SerializedName;
import com.ximalaya.ting.android.opensdk.datatrasfer.XimalayaResponse;
public class Banner extends XimalayaResponse
{
@SerializedName("album_id")
private long albumId;
@SerializedName("banner_content_type")
private int bannerContentType;
@SerializedName("id")
private long bannerId;
@SerializedName("banner_redirect_url")
private String bannerRedirectUrl;
@SerializedName("banner_short_title")
private String bannerShortTitle;
@SerializedName("banner_title")
private String bannerTitle;
@SerializedName("banner_uid")
private int bannerUid;
@SerializedName("banner_url")
private String bannerUrl;
@SerializedName("can_share")
private boolean canShare;
@SerializedName("column_content_type")
private String columnContentType;
@SerializedName("column_id")
private int columnId;
@SerializedName("is_external_url")
private String isExternalUrl;
@SerializedName("third_party_url")
private String thirdPartyUrl;
@SerializedName("track_id")
private int trackId;
public long getAlbumId()
{
return this.albumId;
}
public int getBannerContentType()
{
return this.bannerContentType;
}
public long getBannerId()
{
return this.bannerId;
}
public String getBannerRedirectUrl()
{
return this.bannerRedirectUrl;
}
public String getBannerShortTitle()
{
return this.bannerShortTitle;
}
public String getBannerTitle()
{
return this.bannerTitle;
}
public int getBannerUid()
{
return this.bannerUid;
}
public String getBannerUrl()
{
return this.bannerUrl;
}
public String getColumnContentType()
{
return this.columnContentType;
}
public int getColumnId()
{
return this.columnId;
}
public String getIsExternalUrl()
{
return this.isExternalUrl;
}
public String getThirdPartyUrl()
{
return this.thirdPartyUrl;
}
public int getTrackId()
{
return this.trackId;
}
public boolean isCanShare()
{
return this.canShare;
}
public void setAlbumId(long paramLong)
{
this.albumId = paramLong;
}
public void setBannerContentType(int paramInt)
{
this.bannerContentType = paramInt;
}
public void setBannerId(long paramLong)
{
this.bannerId = paramLong;
}
public void setBannerRedirectUrl(String paramString)
{
this.bannerRedirectUrl = paramString;
}
public void setBannerShortTitle(String paramString)
{
this.bannerShortTitle = paramString;
}
public void setBannerTitle(String paramString)
{
this.bannerTitle = paramString;
}
public void setBannerUid(int paramInt)
{
this.bannerUid = paramInt;
}
public void setBannerUrl(String paramString)
{
this.bannerUrl = paramString;
}
public void setCanShare(boolean paramBoolean)
{
this.canShare = paramBoolean;
}
public void setColumnContentType(String paramString)
{
this.columnContentType = paramString;
}
public void setColumnId(int paramInt)
{
this.columnId = paramInt;
}
public void setIsExternalUrl(String paramString)
{
this.isExternalUrl = paramString;
}
public void setThirdPartyUrl(String paramString)
{
this.thirdPartyUrl = paramString;
}
public void setTrackId(int paramInt)
{
this.trackId = paramInt;
}
public String toString()
{
return "RankBanners [bannerId=" + this.bannerId + ", bannerTitle=" + this.bannerTitle + ", bannerShortTitle=" + this.bannerShortTitle + ", bannerUrl=" + this.bannerUrl + ", bannerRedirectUrl=" + this.bannerRedirectUrl + ", canShare=" + this.canShare + ", bannerContentType=" + this.bannerContentType + ", bannerUid=" + this.bannerUid + ", trackId=" + this.trackId + ", columnId=" + this.columnId + ", columnContentType=" + this.columnContentType + ", albumId=" + this.albumId + ", thirdPartyUrl=" + this.thirdPartyUrl + ", isExternalUrl=" + this.isExternalUrl + "]";
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ximalaya.ting.android.opensdk.model.banner.Banner
* JD-Core Version: 0.6.0
*/
| 21.045
| 570
| 0.711333
|
82cc931daee001f3527c8d3c7bcdfd1cf54c040b
| 2,479
|
package org.apache.nifi.graphml.scripts;
import java.io.File;
import java.net.URL;
import java.util.Objects;
public class Bundle {
private final File workingDirectory;
private final BundleDescriptor bundleDescriptor;
private final BundleDescriptor dependencyDescriptor;
private final ClassLoader classLoader;
private final URL[] bundleJars;
public Bundle(Bundle.Builder builder) {
this.workingDirectory = builder.workingDirectory;
this.bundleDescriptor = builder.bundleDescriptor;
this.dependencyDescriptor = builder.dependencyDescriptor;
this.classLoader = builder.classLoader;
this.bundleJars = builder.bundleJars;
}
public File getWorkingDirectory() {
return workingDirectory;
}
public BundleDescriptor getBundleDescriptor() {
return bundleDescriptor;
}
public BundleDescriptor getDependencyDescriptor() {
return dependencyDescriptor;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public URL[] getBundleJars() {
return bundleJars;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bundle bundle = (Bundle) o;
return workingDirectory.equals(bundle.workingDirectory) &&
bundleDescriptor.equals(bundle.bundleDescriptor) &&
Objects.equals(dependencyDescriptor, bundle.dependencyDescriptor);
}
@Override
public int hashCode() {
return Objects.hash(workingDirectory, bundleDescriptor, dependencyDescriptor);
}
@Override
public String toString() {
return "Bundle{" + bundleDescriptor + "}";
}
public static class Builder {
public File workingDirectory;
public BundleDescriptor bundleDescriptor;
public BundleDescriptor dependencyDescriptor;
public ClassLoader classLoader;
public URL[] bundleJars;
public Bundle build() {
return new Bundle(this);
}
}
public Builder with() {
Builder builder = new Builder();
builder.workingDirectory = this.workingDirectory;
builder.bundleDescriptor = this.bundleDescriptor;
builder.dependencyDescriptor = this.dependencyDescriptor;
builder.classLoader = this.classLoader;
builder.bundleJars = this.bundleJars;
return builder;
}
}
| 28.825581
| 86
| 0.672449
|
700cc558aea8b9498ca38e6041f11a8ce117279e
| 2,127
|
package org.jboss.resteasy.test.resource.patch;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PATCH;
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.core.MediaType;
@Path("/students")
public class StudentResource
{
private static Map<Long, Student> studentsMap = new java.util.concurrent.ConcurrentHashMap<Long, Student>();
public StudentResource()
{
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Student getStudent(@PathParam("id") long id)
{
Student student = studentsMap.get(id);
if (student == null)
{
throw new NotFoundException();
}
return student;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Student addStudent(Student student)
{
studentsMap.put(student.getId(), student);
return student;
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Student updateStudent(@PathParam("id") long id, Student student)
{
if (studentsMap.get(id) == null)
{
throw new NotFoundException();
}
studentsMap.put(id, student);
return student;
}
@PATCH
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON_PATCH_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Student patchStudent(@PathParam("id") long id, Student student)
{
if (studentsMap.get(id) == null)
{
throw new NotFoundException();
}
studentsMap.put(id, student);
return student;
}
@PATCH
@Path("/{id}")
@Consumes("application/merge-patch+json")
@Produces(MediaType.APPLICATION_JSON)
public Student mergePatchStudent(@PathParam("id") long id, Student student)
{
if (studentsMap.get(id) == null)
{
throw new NotFoundException();
}
studentsMap.put(id, student);
return student;
}
}
| 23.633333
| 111
| 0.661025
|
1c27ddd0cb185cd91f10b013e41b7a01ace4ad2a
| 1,520
|
package main.io;
import main.utils.Constants;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class AuthFile {
private static File authFile = new File(Constants.CONFIG_FILE);
private static File authPath = new File(Constants.CONFIG_PATH);
private static Scanner sc = null;
public static boolean createDirectory(){
boolean result = authPath.exists();
if (!result) authPath.mkdirs();
return result;
}
public static boolean createFile(){
try {
return !authFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void updateFile(String apiKey, String authToken, String rootSyncPath){
try {
PrintWriter pw = new PrintWriter(Constants.CONFIG_FILE);
pw.append(apiKey).append("\r\n");
pw.append(authToken).append("\r\n");
pw.append(rootSyncPath).append("\r\n");
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String nextLine() {
try {
if (sc == null) refreshScanner();
return sc.nextLine();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static void refreshScanner() {
try {
sc = new Scanner(authFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 27.142857
| 88
| 0.568421
|
e463f601446248237d3c6de341af2f4001b67c36
| 961
|
import java.util.Arrays;
import java.util.Scanner;
class Bubble {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
System.out.print("Length: ");
int length = in.nextInt();
int[] array = new int[length];
for (int i = 0; i < length; i++) {
System.out.printf("Item %d: ", i);
array[i] = in.nextInt();
}
System.out.println("Source array " + Arrays.toString(array));
boolean loop = true;
while (loop) {
loop = false;
for (int i = 0; i < length - 1; i++) {
if (array[i] > array[i + 1]) {
loop = true;
int tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
}
}
}
System.out.println("Sorted array " + Arrays.toString(array));
in.close();
}
}
| 23.439024
| 69
| 0.443288
|
ce2eaf76af1015ae770e440a4f457e000d4bce1c
| 63,259
|
/*
* 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 calculations;
import java.awt.event.KeyEvent;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
*
* @author kasuni
*/
public class interface_cal extends javax.swing.JFrame {
double n1;
double n2;
double result;
String opr;
private Object math;
double memorydisplay;
boolean isEquelClicked;
boolean isBtnClicked=false;
boolean isNumBtnClicked=false;
double temp;
double memory=0;
public interface_cal() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton2 = new javax.swing.JButton();
jbRAD = new javax.swing.JButton();
tfDisplay = new javax.swing.JTextField();
jbMOD = new javax.swing.JButton();
jb4 = new javax.swing.JButton();
jb5 = new javax.swing.JButton();
jb7 = new javax.swing.JButton();
jb8 = new javax.swing.JButton();
jb9 = new javax.swing.JButton();
jb6 = new javax.swing.JButton();
jb2 = new javax.swing.JButton();
jbMUL = new javax.swing.JButton();
jb3 = new javax.swing.JButton();
jb1 = new javax.swing.JButton();
jbADD = new javax.swing.JButton();
jbpoint = new javax.swing.JButton();
jbPLUSMINUS = new javax.swing.JButton();
jb0 = new javax.swing.JButton();
jbDIV = new javax.swing.JButton();
jbEQL = new javax.swing.JButton();
jbSUB = new javax.swing.JButton();
jbPOW = new javax.swing.JButton();
jbBACKS = new javax.swing.JButton();
jbTAN = new javax.swing.JButton();
jbCOS = new javax.swing.JButton();
jbSIN = new javax.swing.JButton();
jbLOG = new javax.swing.JButton();
jbSQR = new javax.swing.JButton();
jbCOSEC = new javax.swing.JButton();
jbCLEAR = new javax.swing.JButton();
jbCOT = new javax.swing.JButton();
jbSEC = new javax.swing.JButton();
jbPI = new javax.swing.JButton();
jbROUND = new javax.swing.JButton();
jbPOW2 = new javax.swing.JButton();
jbPOW3 = new javax.swing.JButton();
jbCBRT = new javax.swing.JButton();
jbBINARY = new javax.swing.JButton();
jbHEXADECIMAL = new javax.swing.JButton();
jbOCT = new javax.swing.JButton();
jbCOSH = new javax.swing.JButton();
jbSINH = new javax.swing.JButton();
jbTANH = new javax.swing.JButton();
jbMS = new javax.swing.JButton();
jbMR = new javax.swing.JButton();
jbMC = new javax.swing.JButton();
jbDEGREE = new javax.swing.JButton();
jbINV = new javax.swing.JButton();
jbLn = new javax.swing.JButton();
jbE = new javax.swing.JButton();
jbEx = new javax.swing.JButton();
jbOpnBracket = new javax.swing.JButton();
jbCloseBracket = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jButton2.setText("jButton2");
jbRAD.setText("RAD");
jbRAD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbRADActionPerformed(evt);
}
});
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Calculator");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
tfDisplay.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
tfDisplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfDisplayActionPerformed(evt);
}
});
tfDisplay.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
tfDisplayKeyTyped(evt);
}
});
jbMOD.setText("%");
jbMOD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbMODActionPerformed(evt);
}
});
jb4.setText("4");
jb4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb4ActionPerformed(evt);
}
});
jb5.setText("5");
jb5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb5ActionPerformed(evt);
}
});
jb7.setText("7");
jb7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb7ActionPerformed(evt);
}
});
jb8.setText("8");
jb8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb8ActionPerformed(evt);
}
});
jb9.setText("9");
jb9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb9ActionPerformed(evt);
}
});
jb6.setText("6");
jb6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb6ActionPerformed(evt);
}
});
jb2.setText("2");
jb2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb2ActionPerformed(evt);
}
});
jbMUL.setText("*");
jbMUL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbMULActionPerformed(evt);
}
});
jb3.setText("3");
jb3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb3ActionPerformed(evt);
}
});
jb1.setText("1");
jb1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb1ActionPerformed(evt);
}
});
jbADD.setText("+");
jbADD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbADDActionPerformed(evt);
}
});
jbpoint.setText(".");
jbpoint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbpointActionPerformed(evt);
}
});
jbPLUSMINUS.setText("+/-");
jbPLUSMINUS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbPLUSMINUSActionPerformed(evt);
}
});
jb0.setText("0");
jb0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jb0ActionPerformed(evt);
}
});
jbDIV.setText("/");
jbDIV.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbDIVActionPerformed(evt);
}
});
jbEQL.setText("=");
jbEQL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbEQLActionPerformed(evt);
}
});
jbSUB.setText("-");
jbSUB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbSUBActionPerformed(evt);
}
});
jbPOW.setText("x^y");
jbPOW.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbPOWActionPerformed(evt);
}
});
jbBACKS.setText("←");
jbBACKS.setToolTipText("");
jbBACKS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbBACKSActionPerformed(evt);
}
});
jbTAN.setText("tan");
jbTAN.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbTANActionPerformed(evt);
}
});
jbCOS.setText("cos");
jbCOS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCOSActionPerformed(evt);
}
});
jbSIN.setText("sin");
jbSIN.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbSINActionPerformed(evt);
}
});
jbLOG.setText("log");
jbLOG.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbLOGActionPerformed(evt);
}
});
jbSQR.setText("√");
jbSQR.setToolTipText("");
jbSQR.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbSQRActionPerformed(evt);
}
});
jbCOSEC.setText("cosec");
jbCOSEC.setToolTipText("");
jbCOSEC.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCOSECActionPerformed(evt);
}
});
jbCLEAR.setText("C");
jbCLEAR.setToolTipText("");
jbCLEAR.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCLEARActionPerformed(evt);
}
});
jbCOT.setText("cot");
jbCOT.setToolTipText("");
jbCOT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCOTActionPerformed(evt);
}
});
jbSEC.setText("sec");
jbSEC.setToolTipText("");
jbSEC.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbSECActionPerformed(evt);
}
});
jbPI.setText("pi");
jbPI.setToolTipText("");
jbPI.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbPIActionPerformed(evt);
}
});
jbROUND.setText("RND");
jbROUND.setToolTipText("");
jbROUND.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbROUNDActionPerformed(evt);
}
});
jbPOW2.setText("x^2");
jbPOW2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbPOW2ActionPerformed(evt);
}
});
jbPOW3.setText("x^3");
jbPOW3.setToolTipText("");
jbPOW3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbPOW3ActionPerformed(evt);
}
});
jbCBRT.setText("cbrt");
jbCBRT.setToolTipText("");
jbCBRT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCBRTActionPerformed(evt);
}
});
jbBINARY.setText("bin");
jbBINARY.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbBINARYActionPerformed(evt);
}
});
jbHEXADECIMAL.setText("hex");
jbHEXADECIMAL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbHEXADECIMALActionPerformed(evt);
}
});
jbOCT.setText("oct");
jbOCT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbOCTActionPerformed(evt);
}
});
jbCOSH.setText("cosh");
jbCOSH.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCOSHActionPerformed(evt);
}
});
jbSINH.setText("sinh");
jbSINH.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbSINHActionPerformed(evt);
}
});
jbTANH.setText("tanh");
jbTANH.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbTANHActionPerformed(evt);
}
});
jbMS.setText("MS");
jbMS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbMSActionPerformed(evt);
}
});
jbMR.setText("MR");
jbMR.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbMRActionPerformed(evt);
}
});
jbMC.setText("MC");
jbMC.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbMCActionPerformed(evt);
}
});
jbDEGREE.setText("degree");
jbDEGREE.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbDEGREEActionPerformed(evt);
}
});
jbINV.setText("1/x");
jbINV.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbINVActionPerformed(evt);
}
});
jbLn.setText("ln");
jbLn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbLnActionPerformed(evt);
}
});
jbE.setText("e");
jbE.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbEActionPerformed(evt);
}
});
jbEx.setText("e^x");
jbEx.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbExActionPerformed(evt);
}
});
jbOpnBracket.setText("(");
jbOpnBracket.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbOpnBracketActionPerformed(evt);
}
});
jbCloseBracket.setText(")");
jbCloseBracket.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbCloseBracketActionPerformed(evt);
}
});
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("general");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setText("scientific");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jbEQL, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jbMOD, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbCloseBracket, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jbCOSEC, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbSEC, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jb1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jb2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jb3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbMUL, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbINV, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jbSIN, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbCOS, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jb0, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbPLUSMINUS, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jbpoint, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbDIV, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbOpnBracket, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jbSINH, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbCOSH, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(4, 4, 4)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jbTANH, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbCOT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jbTAN, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbLOG, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(231, 231, 231))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(tfDisplay, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jb4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jb5, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jb6, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbADD, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbSQR, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jb7, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jb8, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jb9, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbSUB, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbPI, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jbMS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbMR, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbMC, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbCLEAR, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbBACKS, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jbPOW, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbPOW2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbPOW3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbEx, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jbBINARY, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbHEXADECIMAL, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbOCT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbE, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jbCBRT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbROUND, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbDEGREE, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jbLn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(tfDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbMS, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbMR, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbMC, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbCLEAR, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbBACKS, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbBINARY, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbHEXADECIMAL, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbOCT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbE, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jb7, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb8, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb9, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbSUB, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbPI, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbPOW, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbPOW2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbPOW3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbEx, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jb4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb5, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb6, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbADD, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbSQR, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbCBRT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbROUND, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbDEGREE, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbLn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jb1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbMUL, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbINV, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbSIN, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbCOS, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbTAN, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbLOG, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbpoint, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbPLUSMINUS, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbDIV, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbSINH, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbCOSH, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbTANH, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbOpnBracket, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb0, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbCOSEC, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbCOT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbSEC, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbMOD, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbEQL, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jbCloseBracket, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(30, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jb7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb7ActionPerformed
if(isEquelClicked==true){
tfDisplay.setText("");
isEquelClicked=false;
}
String n=tfDisplay.getText() + jb7.getText();
tfDisplay.setText(n);
isNumBtnClicked=true;
}//GEN-LAST:event_jb7ActionPerformed
private void jb8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb8ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb8.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb8ActionPerformed
private void jbDIVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDIVActionPerformed
if(isNumBtnClicked==true){
tfDisplay.setText(tfDisplay.getText()+"/");
isNumBtnClicked = false;
opr="/";
}
}//GEN-LAST:event_jbDIVActionPerformed
private void jbEQLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEQLActionPerformed
if(opr=="^"){
n2=Double.parseDouble(tfDisplay.getText());
result=Math.pow(n1,n2);
tfDisplay.setText(String.valueOf(result));
}else{
ScriptEngineManager mgr = new ScriptEngineManager();
String shortName;
ScriptEngine engine = mgr.getEngineByName("javascript");
String foo = tfDisplay.getText();
try {
tfDisplay.setText(engine.eval(foo).toString());
} catch (ScriptException e) {
e.printStackTrace();
}
}
n1=0;
n2=0;
}//GEN-LAST:event_jbEQLActionPerformed
private void jbSUBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSUBActionPerformed
if(isNumBtnClicked==true){
tfDisplay.setText(tfDisplay.getText()+"-");
isNumBtnClicked=false;
opr="-";
}
}//GEN-LAST:event_jbSUBActionPerformed
private void jbPOWActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPOWActionPerformed
if (isBtnClicked == true) {
n2 = Double.parseDouble(tfDisplay.getText());
tfDisplay.setText("");
n1 =Math.pow(n1, n2);
opr = ("^");
} else {
n1 = Double.parseDouble(tfDisplay.getText());
tfDisplay.setText("");
opr = ("^");
isBtnClicked = true;
}
}//GEN-LAST:event_jbPOWActionPerformed
private void jbBACKSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBACKSActionPerformed
String backspce=null;
if(tfDisplay.getText().length()>0){
StringBuilder strb= new StringBuilder(tfDisplay.getText());
strb.deleteCharAt(tfDisplay.getText().length()-1);
backspce=strb.toString();
tfDisplay.setText(backspce);
}
}//GEN-LAST:event_jbBACKSActionPerformed
private void jbTANActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbTANActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num=Math.toRadians(num);
num = Math.tan(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbTANActionPerformed
private void jbCOSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCOSActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num=Math.toRadians(num);
num = Math.cos(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbCOSActionPerformed
private void jbSINActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSINActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num=Math.toRadians(num);
num = Math.sin(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbSINActionPerformed
private void jbLOGActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbLOGActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.log10(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbLOGActionPerformed
private void jb5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb5ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb5.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb5ActionPerformed
private void tfDisplayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfDisplayActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tfDisplayActionPerformed
private void jbADDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbADDActionPerformed
if(isNumBtnClicked==true){
tfDisplay.setText(tfDisplay.getText() + "+");
isNumBtnClicked = false;
opr="+";
}
}//GEN-LAST:event_jbADDActionPerformed
private void jbSQRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSQRActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.sqrt(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbSQRActionPerformed
private void jb9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb9ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb9.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb9ActionPerformed
private void jb4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb4ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb4.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb4ActionPerformed
private void jb6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb6ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb6.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb6ActionPerformed
private void jb1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb1ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb1.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb1ActionPerformed
private void jb2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb2ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb2.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb2ActionPerformed
private void jb3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb3ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n=tfDisplay.getText() + jb3.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb3ActionPerformed
private void jbCOSECActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCOSECActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.toRadians(num);
num = Math.sin(num);
num=1/num;
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbCOSECActionPerformed
private void jbCLEARActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCLEARActionPerformed
tfDisplay.setText("");
n1=0;
n2=0;
memory=0;
}//GEN-LAST:event_jbCLEARActionPerformed
private void jbCOTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCOTActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.toRadians(num);
num = Math.tan(num);
num=1/num;
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbCOTActionPerformed
private void jb0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb0ActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n = tfDisplay.getText() + jb0.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jb0ActionPerformed
private void jbpointActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbpointActionPerformed
if(!tfDisplay.getText().contains(".")){
tfDisplay.setText(tfDisplay.getText()+jbpoint.getText());
}
}//GEN-LAST:event_jbpointActionPerformed
private void jbPLUSMINUSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPLUSMINUSActionPerformed
double num=Double.parseDouble(String.valueOf(tfDisplay.getText()));
num=(-1)*num;
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbPLUSMINUSActionPerformed
private void jbMULActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbMULActionPerformed
if(isNumBtnClicked==true){
tfDisplay.setText(tfDisplay.getText()+"*");
isNumBtnClicked = false;
opr="*";
}
}//GEN-LAST:event_jbMULActionPerformed
private void jbSECActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSECActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num=Math.toRadians(num);
num = Math.cos(num);
num=1/num;
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbSECActionPerformed
private void jbPIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPIActionPerformed
double num= 3.1415926535897932384626433832795;
tfDisplay.setText(tfDisplay.getText()+String.valueOf(num));
}//GEN-LAST:event_jbPIActionPerformed
private void jbROUNDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbROUNDActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.round(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbROUNDActionPerformed
private void jbPOW2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPOW2ActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.pow(num, 2);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbPOW2ActionPerformed
private void jbPOW3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbPOW3ActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.pow(num, 3);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbPOW3ActionPerformed
private void jbCBRTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCBRTActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.cbrt(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbCBRTActionPerformed
private void jbBINARYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBINARYActionPerformed
int num = Integer.parseInt(tfDisplay.getText());
tfDisplay.setText(Integer.toString(num,2));
}//GEN-LAST:event_jbBINARYActionPerformed
private void jbHEXADECIMALActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbHEXADECIMALActionPerformed
int num = Integer.parseInt(tfDisplay.getText());
tfDisplay.setText(Integer.toString(num, 16));
}//GEN-LAST:event_jbHEXADECIMALActionPerformed
private void jbOCTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbOCTActionPerformed
int num = Integer.parseInt(tfDisplay.getText());
tfDisplay.setText(Integer.toString(num, 8));
}//GEN-LAST:event_jbOCTActionPerformed
private void tfDisplayKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfDisplayKeyTyped
char ch=evt.getKeyChar();
if(!(Character.isDigit(ch)|| (ch==KeyEvent.VK_BACK_SPACE) || (ch== KeyEvent.VK_DELETE))){
evt.consume();
}
}//GEN-LAST:event_tfDisplayKeyTyped
private void jbMODActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbMODActionPerformed
if(isNumBtnClicked==true){
tfDisplay.setText(tfDisplay.getText()+"%");
isNumBtnClicked = false;
opr="%";
}
}//GEN-LAST:event_jbMODActionPerformed
private void jbTANHActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbTANHActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num=Math.toRadians(num);
num = Math.tanh(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbTANHActionPerformed
private void jbCOSHActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCOSHActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num=Math.toRadians(num);
num = Math.cosh(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbCOSHActionPerformed
private void jbSINHActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSINHActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num =Math.toRadians(num);
num=Math.sinh(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbSINHActionPerformed
private void jbMSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbMSActionPerformed
// tfDisplay.setText(String.valueOf(tfDisplay.getText()));
memory=Double.parseDouble(String.valueOf(tfDisplay.getText()));
tfDisplay.setText("");
}//GEN-LAST:event_jbMSActionPerformed
private void jbRADActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRADActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.toRadians(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbRADActionPerformed
private void jbDEGREEActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDEGREEActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.toDegrees(num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbDEGREEActionPerformed
private void jbINVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbINVActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = (1 / num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbINVActionPerformed
private void jbMRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbMRActionPerformed
//tfDisplay.setText(String.valueOf(tfDisplay.getText()));
n1=memory;
tfDisplay.setText(tfDisplay.getText()+memory);
isBtnClicked=true;
}//GEN-LAST:event_jbMRActionPerformed
private void jbMCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbMCActionPerformed
memory=0;
}//GEN-LAST:event_jbMCActionPerformed
private void jbLnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbLnActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
result=Math.log(num);
tfDisplay.setText(String.valueOf(result));
/* if (isNumBtnClicked ==false) {
tfDisplay.setText(tfDisplay.getText() + "ln");
isNumBtnClicked = true;
opr = "ln";
}*/
}//GEN-LAST:event_jbLnActionPerformed
private void jbEActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEActionPerformed
double num = 2.71828183;
tfDisplay.setText(tfDisplay.getText()+String.valueOf(num));
}//GEN-LAST:event_jbEActionPerformed
private void jbExActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExActionPerformed
double num = Double.parseDouble(String.valueOf(tfDisplay.getText()));
num = Math.pow(2.71828183,num);
tfDisplay.setText(String.valueOf(num));
}//GEN-LAST:event_jbExActionPerformed
private void jbOpnBracketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbOpnBracketActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n = tfDisplay.getText() + jbOpnBracket.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jbOpnBracketActionPerformed
private void jbCloseBracketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCloseBracketActionPerformed
if (isEquelClicked == true) {
tfDisplay.setText("");
isEquelClicked = false;
}
String n = tfDisplay.getText() + jbCloseBracket.getText();
tfDisplay.setText(n);
isNumBtnClicked = true;
}//GEN-LAST:event_jbCloseBracketActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
this.setResizable(true);
this.setSize(335,535);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
this.setResizable(true);
this.setSize(335,535);
}//GEN-LAST:event_formWindowActivated
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
this.setResizable(true);
this.setSize(648, 535);
tfDisplay.setSize(594, 44);
}//GEN-LAST:event_jMenuItem2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(interface_cal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(interface_cal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(interface_cal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(interface_cal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new interface_cal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JButton jb0;
private javax.swing.JButton jb1;
private javax.swing.JButton jb2;
private javax.swing.JButton jb3;
private javax.swing.JButton jb4;
private javax.swing.JButton jb5;
private javax.swing.JButton jb6;
private javax.swing.JButton jb7;
private javax.swing.JButton jb8;
private javax.swing.JButton jb9;
private javax.swing.JButton jbADD;
private javax.swing.JButton jbBACKS;
private javax.swing.JButton jbBINARY;
private javax.swing.JButton jbCBRT;
private javax.swing.JButton jbCLEAR;
private javax.swing.JButton jbCOS;
private javax.swing.JButton jbCOSEC;
private javax.swing.JButton jbCOSH;
private javax.swing.JButton jbCOT;
private javax.swing.JButton jbCloseBracket;
private javax.swing.JButton jbDEGREE;
private javax.swing.JButton jbDIV;
private javax.swing.JButton jbE;
private javax.swing.JButton jbEQL;
private javax.swing.JButton jbEx;
private javax.swing.JButton jbHEXADECIMAL;
private javax.swing.JButton jbINV;
private javax.swing.JButton jbLOG;
private javax.swing.JButton jbLn;
private javax.swing.JButton jbMC;
private javax.swing.JButton jbMOD;
private javax.swing.JButton jbMR;
private javax.swing.JButton jbMS;
private javax.swing.JButton jbMUL;
private javax.swing.JButton jbOCT;
private javax.swing.JButton jbOpnBracket;
private javax.swing.JButton jbPI;
private javax.swing.JButton jbPLUSMINUS;
private javax.swing.JButton jbPOW;
private javax.swing.JButton jbPOW2;
private javax.swing.JButton jbPOW3;
private javax.swing.JButton jbRAD;
private javax.swing.JButton jbROUND;
private javax.swing.JButton jbSEC;
private javax.swing.JButton jbSIN;
private javax.swing.JButton jbSINH;
private javax.swing.JButton jbSQR;
private javax.swing.JButton jbSUB;
private javax.swing.JButton jbTAN;
private javax.swing.JButton jbTANH;
private javax.swing.JButton jbpoint;
private javax.swing.JTextField tfDisplay;
// End of variables declaration//GEN-END:variables
private String tfDisplay(String text) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 49.771046
| 163
| 0.642754
|
031c63fe168924074767447100b0ec4ea92f4403
| 2,887
|
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc4240.troTek2019.subsystems;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
import org.usfirst.frc4240.troTek2019.Robot;
import org.usfirst.frc4240.troTek2019.commands.*;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDSource;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
/**
*
*/
public class arm1 extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public arm1() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
@Override
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
@Override
public void periodic() {
// Put code here to be run every loop
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CMDPIDGETTERS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CMDPIDGETTERS
// Put methods for controlling this subsystem
// here. Call these from Commands.
/*
public void armUp () {
Robot.arm1.armSpeedController.set(-.35);
}
public void armDown () {
Robot.arm1.armSpeedController.set(.1);
}
public void armStop () {
Robot.arm1.armSpeedController.stopMotor();
}
*/
//Place encoder stuff here
public double getRate () {
return Robot.arm1PID.getRate();
}
/*
public void resetBigEncoder() {
armQuad1.reset();
}
public void spinForward (double forward) {
Robot.arm1.armSpeedController.set(forward);
}
public void armHold () {
Robot.arm1.armSpeedController.set(-.25);
}
public double driveWithTrigger () {
return Robot.oi.xboxController.getRawAxis(2);
}
*/
}
| 27.759615
| 75
| 0.701767
|
554240d1c72dc0c327b05b002999e47899e2341f
| 1,323
|
package controllers;
import models.ConnectionRequest;
import models.User;
import play.mvc.Controller;
import play.mvc.Result;
/**
* Created by lubuntu on 10/23/16.
*/
public class RequestController extends Controller {
public Result sendRequest(Long senderid, Long recieverid)
{
if(senderid==null || recieverid==null || User.find.byId(senderid)==null || User.find.byId(recieverid)==null)
return ok();
else{
ConnectionRequest c= new ConnectionRequest();
c.sender= User.find.byId(senderid);
c.receiver= User.find.byId(recieverid);
c.status= ConnectionRequest.Status.WAITING;
ConnectionRequest.db().save(c);
return ok();
}
}
public Result acceptRequest(Long requestid)
{
if(requestid==null || ConnectionRequest.find.byId(requestid)==null)
return ok();
else{
ConnectionRequest c = ConnectionRequest.find.byId(requestid);
c.sender.connections.add(c.receiver);
c.receiver.connections.add(c.sender);
c.status = ConnectionRequest.Status.ACCEPTED;
ConnectionRequest.db().update(c);
c.sender.update();
c.receiver.update();
User.db().update(c.sender);
User.db().update(c.receiver);
return ok();
}
}
}
| 30.767442
| 112
| 0.62963
|
76d48b0a1e8042c77d69469204d55dbfa149ae8a
| 3,108
|
package net.sf.odinms.provider;
import java.awt.Point;
import java.awt.image.BufferedImage;
import net.sf.odinms.provider.wz.MapleDataType;
public class MapleDataTool {
private MapleDataTool() {
}
public static String getString(MapleData data) {
return ((String) data.getData());
}
public static String getString(MapleData data, String def) {
if (data == null || data.getData() == null) {
return def;
} else {
return ((String) data.getData());
}
}
public static String getString(String path, MapleData data) {
return getString(data.getChildByPath(path));
}
public static String getString(String path, MapleData data, String def) {
return getString(data.getChildByPath(path), def);
}
public static double getDouble(MapleData data) {
return ((Double) data.getData()).doubleValue();
}
public static float getFloat(MapleData data) {
return ((Float) data.getData()).floatValue();
}
public static int getInt(MapleData data) {
return ((Integer) data.getData()).intValue();
}
public static int getInt(MapleData data, int def) {
if (data == null || data.getData() == null) {
return def;
} else {
if (data.getType() == MapleDataType.STRING) {
return Integer.parseInt(getString(data));
} else {
return ((Integer) data.getData()).intValue();
}
}
}
public static int getInt(String path, MapleData data) {
return getInt(data.getChildByPath(path));
}
public static int getIntConvert(MapleData data) {
if (data.getType() == MapleDataType.STRING) {
return Integer.parseInt(getString(data));
} else {
return getInt(data);
}
}
public static int getIntConvert(String path, MapleData data) {
MapleData d = data.getChildByPath(path);
if (d.getType() == MapleDataType.STRING) {
return Integer.parseInt(getString(d));
} else {
return getInt(d);
}
}
public static int getInt(String path, MapleData data, int def) {
return getInt(data.getChildByPath(path), def);
}
public static int getIntConvert(String path, MapleData data, int def) {
MapleData d = data.getChildByPath(path);
if (d == null) {
return def;
}
if (d.getType() == MapleDataType.STRING) {
try {
return Integer.parseInt(getString(d));
} catch (NumberFormatException nfe) {
return def;
}
} else {
return getInt(d, def);
}
}
public static BufferedImage getImage(MapleData data) {
return ((MapleCanvas) data.getData()).getImage();
}
public static Point getPoint(MapleData data) {
return ((Point) data.getData());
}
public static Point getPoint(String path, MapleData data) {
return getPoint(data.getChildByPath(path));
}
public static Point getPoint(String path, MapleData data, Point def) {
final MapleData pointData = data.getChildByPath(path);
if (pointData == null) {
return def;
}
return getPoint(pointData);
}
public static String getFullDataPath(MapleData data) {
String path = "";
MapleDataEntity myData = data;
while (myData != null) {
path = myData.getName() + "/" + path;
myData = myData.getParent();
}
return path.substring(0, path.length() - 1);
}
}
| 24.472441
| 74
| 0.685006
|
d79faca6a907d7a79fe27423afd37b22674076ee
| 2,382
|
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples;
import com.elex_project.abraxas.Console;
import lombok.extern.slf4j.Slf4j;
import javax.sound.sampled.*;
import java.io.IOException;
import java.util.Objects;
@Slf4j
public class SignalProcessing {
public static void main(String... args)
throws UnsupportedAudioFileException, IOException, LineUnavailableException {
for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) {
Mixer mixer = AudioSystem.getMixer(mixerInfo);
Console.writeLine("MIXER: {}", mixerInfo);
for (Control control : mixer.getControls()){
Console.writeLine("CONTROL: {}", control.toString());
}
for (Line.Info info : mixer.getSourceLineInfo()) {
Console.writeLine("SOURCE LINE: {}" , info);
Line line = mixer.getLine(info);
for (Control control : line.getControls()){
Console.writeLine("CONTROL: {}", control.toString());
}
}
for (Line.Info info : mixer.getTargetLineInfo()) {
Console.writeLine("TARGET LINE: {}" , info);
Line line = mixer.getLine(info);
for (Control control : line.getControls()){
Console.writeLine("CONTROL: {}", control.toString());
}
}
}
/*AudioInputStream inputStream = AudioSystem.getAudioInputStream(Objects.requireNonNull(ClassLoader.
getSystemResourceAsStream("alarm_gentle.wav")));
SourceDataLine src = AudioSystem.getSourceDataLine(inputStream.getFormat());
src.open();
src.start();
Mixer mixer = AudioSystem.getMixer(AudioSystem.getMixerInfo()[1]);
Console.writeLine(mixer.getLineInfo());
Port line = (Port) mixer.getLine(Port.Info.LINE_IN);
line.open();
for (Control ctrl : line.getControls()) {
Console.writeLine(ctrl);
}
FloatControl volumeCtrl = (FloatControl) mixer.getControl(FloatControl.Type.VOLUME);
volumeCtrl.setValue(0);
byte[] buffer = new byte[64];
int numRead = 0;
float dVol = 0.f;
while ((numRead = inputStream.read(buffer, 0, buffer.length)) > 0) {
log.debug("vol: {}", volumeCtrl.getValue());
src.write(buffer, 0, numRead);
if (volumeCtrl.getValue()<=volumeCtrl.getMinimum()) {
dVol = 0.01f;
} else if (volumeCtrl.getValue()>=volumeCtrl.getMaximum()){
dVol = -0.01f;
}
volumeCtrl.setValue(volumeCtrl.getValue()+dVol);
}
inputStream.close();
src.close();*/
}
}
| 29.775
| 102
| 0.690596
|
13464eb53e762c890ce23aa87fcfcc83da6512e8
| 9,904
|
/*******************************************************************************
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.editors;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.IJavaPartitions;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.quickassist.IQuickAssistAssistant;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.source.DefaultAnnotationHover;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.core.builder.KotlinPsiManager;
import org.jetbrains.kotlin.core.log.KotlinLogger;
import org.jetbrains.kotlin.eclipse.ui.utils.EditorUtil;
import org.jetbrains.kotlin.ui.editors.highlighting.KotlinTokenScanner;
import org.jetbrains.kotlin.ui.editors.hover.KotlinInformationProvider;
import org.jetbrains.kotlin.ui.editors.hover.KotlinTextHover;
import org.jetbrains.kotlin.ui.editors.outline.KotlinOutlinePopup;
public class Configuration extends JavaSourceViewerConfiguration {
private KotlinTokenScanner scanner;
private final KotlinEditor editor;
public Configuration(@NotNull IColorManager colorManager, @NotNull KotlinEditor editor, IPreferenceStore preferenceStore) {
super(colorManager, preferenceStore, editor.getJavaEditor(), IJavaPartitions.JAVA_PARTITIONING);
this.editor = editor;
}
@Override
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER
};
}
@Override
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter = new InformationPresenter(new IInformationControlCreator() {
@Override
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new KotlinOutlinePopup(editor, parent, shellStyle, treeStyle);
}
});
presenter.setInformationProvider(new OutlineInformationProvider(editor.getJavaEditor()), IDocument.DEFAULT_CONTENT_TYPE);
presenter.setSizeConstraints(45, 15, true, false);
return presenter;
}
@Override
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter= new InformationPresenter(new IInformationControlCreator() {
@Override
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, true);
}
});
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IInformationProvider provider = new KotlinInformationProvider(editor);
for (String contentType : getConfiguredContentTypes(sourceViewer)) {
presenter.setInformationProvider(provider, contentType);
}
presenter.setSizeConstraints(100, 12, false, true);
return presenter;
}
@Override
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new DefaultAnnotationHover();
}
@Override
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
return getTextHover(sourceViewer, contentType);
}
@Override
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return new KotlinTextHover(editor);
}
@Override
public IQuickAssistAssistant getQuickAssistAssistant(ISourceViewer sourceViewer) {
return null;
}
@Override
public IReconciler getReconciler(ISourceViewer sourceViewer) {
return null;
}
@Nullable
public KotlinTokenScanner getScanner() {
if (scanner == null) {
scanner = KotlinTokenScanner.createScanner(fPreferenceStore, getColorManager(), editor);
}
return scanner;
}
@Override
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { "//", "" };
}
@Override
public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
return null;
}
@Override
public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
return JavaPartitionScanner.JAVA_PARTITIONING;
}
@Override
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
KotlinTokenScanner scanner = getScanner();
return scanner != null ? getKotlinPresentaionReconciler(scanner) : null;
}
@Override
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
return null;
}
private static class OutlineInformationProvider implements IInformationProvider, IInformationProviderExtension {
private final AbstractTextEditor editor;
public OutlineInformationProvider(AbstractTextEditor editor) {
this.editor = editor;
}
@Override
public IRegion getSubject(ITextViewer textViewer, int offset) {
return new Region(offset, 0);
}
@Override
public String getInformation(ITextViewer textViewer, IRegion subject) {
Object result = getInformation2(textViewer, subject);
return result != null ? result.toString() : null;
}
@Override
public Object getInformation2(ITextViewer textViewer, IRegion subject) {
IFile file = EditorUtil.getFile(editor);
if (file != null) {
return KotlinPsiManager.INSTANCE.getParsedFile(file);
}
KotlinLogger.logError("Failed to retrieve IFile from editor " + editor, null);
return null;
}
}
@Override
protected Map<String, IAdaptable> getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
Map<String, IAdaptable> targets = super.getHyperlinkDetectorTargets(sourceViewer);
targets.remove("org.eclipse.jdt.ui.javaCode");
targets.put("org.jetbrains.kotlin.ui.editors.kotlinCode", getEditor());
return targets;
}
public static KotlinPresentationReconciler getKotlinPresentaionReconciler(@NotNull KotlinTokenScanner scanner) {
DefaultDamagerRepairer kotlinDamagerRepairer = new DefaultDamagerRepairer(scanner);
KotlinPresentationReconciler reconciler = new KotlinPresentationReconciler();
reconciler.setDamager(kotlinDamagerRepairer, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(kotlinDamagerRepairer, IDocument.DEFAULT_CONTENT_TYPE);
return reconciler;
}
public static class KotlinPresentationReconciler extends PresentationReconciler {
private volatile IDocument lastDocument = null;
public TextPresentation createRepairDescription(IRegion damage, IDocument document) {
if (document != lastDocument) {
setDocumentToDamagers(document);
setDocumentToRepairers(document);
lastDocument = document;
}
return createPresentation(damage, document);
}
}
}
| 40.590164
| 129
| 0.712338
|
69baf10ab9cd68ba9566e1c3fdaba07cea99b614
| 398
|
/**
* The scraping package contains all scraping code used by asvc.
* An overview of what is scraped per site is given in their respective files.
*
* @author dbarenholz
* @version 1.0
* @since 13
*
* @see com.dbarenholz.asvc.scraping.ForvoScraper
* @see com.dbarenholz.asvc.scraping.JishoScraper
* @see com.dbarenholz.asvc.scraping.TatoebaScraper
*/
package com.dbarenholz.asvc.scraping;
| 30.615385
| 78
| 0.748744
|
a1dc27f6a2c95b8ec8a72c082f8e359324fe8bbc
| 338
|
package com.zhangyf.bidirectio.net.exception;
/**
* Created on 2018-03-09 09:33.
* App异常
*
* @author zyf
*/
public class AppException extends RuntimeException {
public int code;
public String msg;
public AppException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
}
| 17.789474
| 52
| 0.627219
|
c671f42cdaaadf79c3018c0b4ee96921c5e0f7a3
| 6,020
|
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Copyright (c) 2019, Eldar Timraleev (aka CRaFT4ik).
+
+ 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 ru.er_log.components;
import java.io.Serializable;
public class eTCPConfig implements IConfig, Serializable
{
private int srcPort;
private int dstPort;
private long seqNum;
private long askNum;
private short offset = (short) AUTO_VALUE;
private reserved reserved;
private flags flags;
private int windowSize;
private int checksum = (int) AUTO_VALUE;
private int urgent;
private long options;
private String data;
public eTCPConfig() {}
public int getSrcPort()
{
return srcPort;
}
public eTCPConfig setSrcPort(int srcPort)
{
this.srcPort = srcPort;
return this;
}
public int getDstPort()
{
return dstPort;
}
public eTCPConfig setDstPort(int dstPort)
{
this.dstPort = dstPort;
return this;
}
public long getSeqNum()
{
return seqNum;
}
public eTCPConfig setSeqNum(long seqNum)
{
this.seqNum = seqNum;
return this;
}
public long getAskNum()
{
return askNum;
}
public eTCPConfig setAskNum(long askNum)
{
this.askNum = askNum;
return this;
}
public short getOffset()
{
return offset;
}
public eTCPConfig setOffset(short offset)
{
this.offset = offset;
return this;
}
public boolean correctOffsetAuto()
{
return offset == (short) AUTO_VALUE;
}
public eTCPConfig.reserved getReserved()
{
return reserved;
}
public eTCPConfig setReserved(eTCPConfig.reserved reserved)
{
this.reserved = reserved;
return this;
}
public eTCPConfig.flags getFlags()
{
return flags;
}
public eTCPConfig setFlags(eTCPConfig.flags flags)
{
this.flags = flags;
return this;
}
public int getWindowSize()
{
return windowSize;
}
public eTCPConfig setWindowSize(int windowSize)
{
this.windowSize = windowSize;
return this;
}
public int getChecksum()
{
return checksum;
}
public eTCPConfig setChecksum(int checksum)
{
this.checksum = checksum;
return this;
}
public boolean correctChecksumAuto()
{
return checksum == (int) AUTO_VALUE;
}
public int getUrgent()
{
return urgent;
}
public eTCPConfig setUrgent(int urgent)
{
this.urgent = urgent;
return this;
}
public long getOptions()
{
return options;
}
public eTCPConfig setOptions(long options)
{
this.options = options;
return this;
}
public String getData()
{
return data;
}
public eTCPConfig setData(String data)
{
this.data = data;
return this;
}
public static class reserved implements Serializable
{
private final boolean bit0;
private final boolean bit1;
private final boolean bit2;
private final boolean bit3;
private final boolean bit4;
private final boolean bit5;
public reserved(boolean bit_0, boolean bit_1, boolean bit_2, boolean bit_3, boolean bit_4, boolean bit_5)
{
this.bit0 = bit_0;
this.bit1 = bit_1;
this.bit2 = bit_2;
this.bit3 = bit_3;
this.bit4 = bit_4;
this.bit5 = bit_5;
}
public byte toByte()
{
byte value = 0x0;
value |= (isBit0() ? 1 : 0) << 5;
value |= (isBit1() ? 1 : 0) << 4;
value |= (isBit2() ? 1 : 0) << 3;
value |= (isBit3() ? 1 : 0) << 2;
value |= (isBit4() ? 1 : 0) << 1;
value |= (isBit5() ? 1 : 0);
return value;
}
public boolean isBit0()
{
return bit0;
}
public boolean isBit1()
{
return bit1;
}
public boolean isBit2()
{
return bit2;
}
public boolean isBit3()
{
return bit3;
}
public boolean isBit4()
{
return bit4;
}
public boolean isBit5()
{
return bit5;
}
}
public static class flags implements Serializable
{
private final boolean u;
private final boolean a;
private final boolean p;
private final boolean r;
private final boolean s;
private final boolean f;
public flags(boolean U, boolean A, boolean P, boolean R, boolean S, boolean F)
{
u = U;
a = A;
p = P;
r = R;
s = S;
f = F;
}
public boolean isU()
{
return u;
}
public boolean isA()
{
return a;
}
public boolean isP()
{
return p;
}
public boolean isR()
{
return r;
}
public boolean isS()
{
return s;
}
public boolean isF()
{
return f;
}
}
}
| 20.47619
| 113
| 0.522425
|
6ec6092b63472043a9d5215fc69febb95a786279
| 7,795
|
/*
* Copyright (C) 2017 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.idea.tests.gui.debugger;
import com.android.tools.idea.tests.gui.framework.fixture.*;
import com.android.tools.idea.tests.gui.framework.matcher.Matchers;
import com.google.common.collect.Lists;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.impl.content.BaseLabel;
import com.intellij.openapi.wm.impl.content.ContentTabLabelFixture;
import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode;
import org.fest.swing.core.Robot;
import org.fest.swing.fixture.DialogFixture;
import org.fest.swing.fixture.JButtonFixture;
import org.fest.swing.timing.Wait;
import org.fest.swing.util.PatternTextMatcher;
import org.jetbrains.annotations.NotNull;
import javax.swing.tree.TreeNode;
import java.util.List;
import java.util.regex.Pattern;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.fest.swing.core.matcher.DialogMatcher.withTitle;
import static org.fest.swing.core.matcher.JButtonMatcher.withText;
import static org.fest.swing.finder.WindowFinder.findDialog;
public class DebuggerTestBase {
protected static final String DEBUG_CONFIG_NAME = "app";
protected static final Pattern DEBUGGER_ATTACHED_PATTERN = Pattern.compile(".*Debugger attached to process.*", Pattern.DOTALL);
protected static final long EMULATOR_LAUNCH_WAIT_SECONDS = 120;
/**
* Toggles breakpoints at {@code lines} of the source file {@code fileName}.
*/
void openAndToggleBreakPoints(IdeFrameFixture ideFrame, String fileName, String... lines) {
toggleBreakpoints(ideFrame.getEditor().open(fileName), lines);
}
void openAndToggleBreakPoints(@NotNull IdeFrameFixture ideFrameFixture, @NotNull VirtualFile file, @NotNull String... lines) {
toggleBreakpoints(
ideFrameFixture.getEditor().open(file, EditorFixture.Tab.DEFAULT),
lines);
}
private void toggleBreakpoints(@NotNull EditorFixture editor, @NotNull String[] lines) {
for (String line : lines) {
editor.moveBetween("", line);
editor.invokeAction(EditorFixture.EditorAction.TOGGLE_LINE_BREAKPOINT);
}
editor.close();
}
void waitForSessionStart(DebugToolWindowFixture debugToolWindowFixture) {
// Wait for "Debugger attached to process.*" to be printed on the app-native debug console.
final ExecutionToolWindowFixture.ContentFixture contentFixture = debugToolWindowFixture.findContent(DEBUG_CONFIG_NAME);
contentFixture.waitForOutput(new PatternTextMatcher(DEBUGGER_ATTACHED_PATTERN), EMULATOR_LAUNCH_WAIT_SECONDS);
}
public static void checkAppIsPaused(IdeFrameFixture ideFrame, String[] expectedPattern) {
checkAppIsPaused(ideFrame, expectedPattern, DEBUG_CONFIG_NAME);
}
public static void checkAppIsPaused(@NotNull IdeFrameFixture ideFrame, @NotNull String[] expectedPattern, @NotNull String debugConfigName) {
ContentTabLabelFixture tabLabel = ContentTabLabelFixture.find(ideFrame.robot(), Matchers.byText(BaseLabel.class, debugConfigName));
Wait.seconds(5).expecting("ContentTabLabel " + debugConfigName + " to become active")
.until(() -> tabLabel.isSelected());
Wait.seconds(5).expecting("variable patterns to match")
.until(() -> verifyVariablesAtBreakpoint(ideFrame, expectedPattern, debugConfigName));
}
protected static void resume(@NotNull String debugConfigName, IdeFrameFixture ideFrame) {
DebugToolWindowFixture debugToolWindowFixture = new DebugToolWindowFixture(ideFrame);
final ExecutionToolWindowFixture.ContentFixture contentFixture = debugToolWindowFixture.findContent(debugConfigName);
contentFixture.clickResumeButton();
}
private static boolean verifyVariablesAtBreakpoint(IdeFrameFixture ideFrame, String[] expectedVariablePatterns, String debugConfigName) {
DebugToolWindowFixture debugToolWindowFixture = new DebugToolWindowFixture(ideFrame);
final ExecutionToolWindowFixture.ContentFixture contentFixture = debugToolWindowFixture.findContent(debugConfigName);
Ref<XDebuggerTreeNode> debuggerTreeRoot = new Ref<>();
Wait.seconds(5).expecting("debugger tree to appear").until(() -> {
XDebuggerTreeNode root = contentFixture.getDebuggerTreeRoot();
if (root != null) {
debuggerTreeRoot.set(root);
return true;
} else {
return false;
}
});
List<String> unmatchedPatterns = getUnmatchedTerminalVariableValues(expectedVariablePatterns, debuggerTreeRoot.get());
return unmatchedPatterns.isEmpty();
}
@NotNull
public static String variableToSearchPattern(String name, String type, String value) {
return String.format("%s = \\{%s\\} %s", name, type, value);
}
/**
* Returns the appropriate pattern to look for a variable named {@code name} with the type {@code type} and value {@code value} appearing
* in the Variables window in Android Studio.
*/
@NotNull
public static String variableToSearchPattern(String name, String value) {
return String.format("%s = %s", name, value);
}
protected static void finishInstallUninstallProcess(@NotNull Robot robot) {
MessagesFixture.findByTitle(robot, "Confirm Change").clickOk();
DialogFixture downloadDialog = findDialog(withTitle("SDK Quickfix Installation"))
.withTimeout(SECONDS.toMillis(30)).using(robot);
JButtonFixture finish = downloadDialog.button(withText("Finish"));
Wait.seconds(120)
.expecting("Android source to be installed").until(finish::isEnabled);
finish.click();
}
public static void stopDebugSession(DebugToolWindowFixture debugToolWindowFixture) {
stopDebugSession(debugToolWindowFixture, DEBUG_CONFIG_NAME);
}
public static void stopDebugSession(DebugToolWindowFixture debugToolWindowFixture, String debugConfigName) {
final ExecutionToolWindowFixture.ContentFixture contentFixture = debugToolWindowFixture.findContent(debugConfigName);
contentFixture.waitForStopClick();
contentFixture.waitForExecutionToFinish();
}
/**
* Returns the subset of {@code expectedPatterns} which do not match any of the children (just the first level children, not recursive) of
* {@code treeRoot} .
*/
@NotNull
private static List<String> getUnmatchedTerminalVariableValues(String[] expectedPatterns, XDebuggerTreeNode treeRoot) {
String[] childrenTexts = debuggerTreeRootToChildrenTexts(treeRoot);
List<String> unmatchedPatterns = Lists.newArrayList();
for (String expectedPattern : expectedPatterns) {
boolean matched = false;
for (String childText : childrenTexts) {
if (childText.matches(expectedPattern)) {
matched = true;
break;
}
}
if (!matched) {
unmatchedPatterns.add(expectedPattern);
}
}
return unmatchedPatterns;
}
@NotNull
private static String[] debuggerTreeRootToChildrenTexts(XDebuggerTreeNode treeRoot) {
List<? extends TreeNode> children = treeRoot.getChildren();
String[] childrenTexts = new String[children.size()];
int i = 0;
for (TreeNode child : children) {
childrenTexts[i] = ((XDebuggerTreeNode)child).getText().toString();
++i;
}
return childrenTexts;
}
}
| 42.82967
| 142
| 0.757152
|
912978eb0a32bf64ecd68f006a2dacfdab989b56
| 4,577
|
package com.digistratum.microhost.RestServer;
import com.digistratum.microhost.RestServer.Controller.Controller;
import com.digistratum.microhost.Exception.MHException;
import com.digistratum.Config.Config;
import com.digistratum.microhost.RestServer.Controller.ControllerBaseMicroHostImpl;
import com.digistratum.microhost.RestServer.Controller.ControllerDefaultImpl;
import com.digistratum.microhost.RestServer.Http.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
import org.apache.log4j.Logger;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
public class RestServerImpl implements RestServer {
protected final static Logger log = Logger.getLogger(RestServerImpl.class);
protected final static Integer DEFAULT_PORT = 54321;
protected final static Integer DEFAULT_THREADS = 10;
protected final static String MICROHOST_ENDPOINTS = "off";
protected final static String MICROHOST_CONTEXT = "/microhost";
protected final static String DEFAULT_CONTEXT = "/";
protected HttpServer server;
protected Map<String, Controller> controllerMap;
/**
* Configuration-injected constructor
*
* Use this to automatically configure the service by way of configuration data.
*
* @param config Config instance (DI)
* @param serverFactory an HttpServerFactory instance we can use to get a new HttpServer instance
*/
@Inject
public RestServerImpl(Config config, HttpServerFactory serverFactory) {
this(
config.get("microhost.port",DEFAULT_PORT),
config.get("microhost.threads",DEFAULT_THREADS),
serverFactory
);
// Add our own default controllers as needed
// Set up default controller for microhost context endpoints
if ("on".equals(config.get("microhost.context.microhost", MICROHOST_ENDPOINTS))) {
try {
addControllerContext(new ControllerBaseMicroHostImpl(), MICROHOST_CONTEXT);
} catch (MHException e) {
// Swallow it - no exceptions are permitted from our Constructors (thanks Dagger!)
}
}
// Add a default context for / to handle 404s's
try {
addControllerContext(new ControllerDefaultImpl(), DEFAULT_CONTEXT);
} catch (MHException e) {
// Swallow it - no exceptions are permitted from our Constructors (thanks Dagger!)
}
}
/**
* Parametric constructor
*
* Use this to programmatically configure the service rather than using configuration data.
*
* @param port Listening port for our MicroHost HTTP service
* @param threadPoolSize Count of threads for our pool (concurrency limit)
*/
public RestServerImpl(int port, int threadPoolSize, HttpServerFactory serverFactory) {
try {
server = serverFactory.getInstance(port);
// ref: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)
server.setExecutor(Executors.newFixedThreadPool(threadPoolSize));
controllerMap = new HashMap<>();
// Start the MicroHost HttpServer; Note that we can still add/remove
// controller contexts on-the-fly while the server is running
server.start();
} catch (MHException e) {
// No exceptions from constructors (thanks, Daggger!)
log.error("Failed to create new HttpServer", e);
}
}
@Override
public void addControllerContext(Controller ctrl, String ctx) throws MHException {
// If the controller or context are bogus...
if ((null == ctrl) || (null == ctx) || ctx.isEmpty()) {
String msg = "Failed to add context for invalid controller: '" + ctx + "'";
log.error(msg);
throw new MHException(msg);
}
// If the context is already defined, it must be removed before we attempt to replace it
if (hasContext(ctx)) {
String msg = "Failed to add duplicate controller for context: '" + ctx + "'";
log.error(msg);
throw new MHException(msg);
}
// Initialize it...
ctrl.setContext(ctx);
ctrl.mapEndpoints();
// ... and add it!
log.info("Adding context: '" + ctx +"'");
controllerMap.put(ctx, ctrl);
server.createContext(ctx, ctrl);
}
@Override
public void removeContext(String ctx) throws MHException {
if (! hasContext(ctx)) {
throw new MHException("Failed to remove undefined context: '" + ctx + "'");
}
server.removeContext(ctx);
controllerMap.remove(ctx);
}
@Override
public boolean hasContext(String ctx) throws MHException {
if ((null == ctx) || ctx.isEmpty()) {
String msg = "Failed to check invalid context";
log.error(msg);
throw new MHException(msg);
}
return controllerMap.containsKey(ctx);
}
@Override
public void stop() {
server.stop(0);
}
}
| 32.460993
| 115
| 0.735853
|
261a0d698dc68097efa663be00acba5d065c6ec4
| 1,973
|
package android.os;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* 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%
*/
@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class Power
{
// Fields
public static final int PARTIAL_WAKE_LOCK = 1;
public static final int FULL_WAKE_LOCK = 2;
public static final int BRIGHTNESS_OFF = 0;
public static final int BRIGHTNESS_DIM = 20;
public static final int BRIGHTNESS_ON = 255;
public static final int BRIGHTNESS_LOW_BATTERY = 10;
public static final int LOW_BATTERY_THRESHOLD = 10;
// Constructors
private Power(){
}
// Methods
@com.francetelecom.rd.stubs.annotation.UseRule(value = "Power.shutdown", report = "-")
public static void shutdown(){
}
@com.francetelecom.rd.stubs.annotation.UseRule(value = "Power.reboot", report = "-")
public static void reboot(java.lang.String arg1) throws java.io.IOException{
}
@com.francetelecom.rd.stubs.annotation.ArgsRule(value = "Power.releaseWakeLock", pos = 1, report = "-")
public static void releaseWakeLock(java.lang.String arg1){
}
@com.francetelecom.rd.stubs.annotation.ArgsRule(value = "Power.acquireWakeLock", pos = 2, report = "-")
public static void acquireWakeLock(int arg1, java.lang.String arg2){
}
public static int setLastUserActivityTimeout(long arg1){
return 0;
}
public static int setScreenState(boolean arg1){
return 0;
}
}
| 28.185714
| 105
| 0.714648
|
231a0d45340edfb950c510f0306df85f8dc92905
| 2,044
|
/*
* 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.employees.utils;
import java.util.prefs.Preferences;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
*
* @author Salim Said Hemed
*/
public class NetConfig {
private String host;
private int port;
private Preferences PREFERENCES;
final String HOST = "HOST";
final String PORT = "PORT";
StringProperty hostProperty = new SimpleStringProperty();
IntegerProperty portProperty = new SimpleIntegerProperty();
public StringProperty getHostProperty() {
return hostProperty;
}
public IntegerProperty getPortProperty() {
return portProperty;
}
public NetConfig(){
this.PREFERENCES = Preferences.userRoot().node(this.getClass().getName());
this.hostProperty.set(this.PREFERENCES.get(HOST, "127.0.0.1"));
this.portProperty.set(this.PREFERENCES.getInt(PORT, 80));
}
public String getNetworkConfig(){
StringBuilder Address = new StringBuilder();
Address.append("http://");
Address.append(PREFERENCES.get(HOST, "127.0.0.1"));
Address.append(":");
Address.append(PREFERENCES.get(PORT, "80"));
return Address.toString();
}
public void setNetWorkConfig(String host,int port){
this.PREFERENCES.put(HOST, host);
this.PREFERENCES.putInt(PORT, port);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
this.hostProperty.set(host);
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
this.portProperty.set(port);
}
}
| 28.788732
| 80
| 0.650685
|
7497862c5ec13093c1f76a71f2245c3f0c319567
| 2,169
|
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.query.aggregation.histogram;
import io.druid.query.aggregation.TestFloatColumnSelector;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class ApproximateHistogramPostAggregatorTest
{
static final float[] VALUES = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
protected ApproximateHistogram buildHistogram(int size, float[] values)
{
ApproximateHistogram h = new ApproximateHistogram(size);
for (float v : values) {
h.offer(v);
}
return h;
}
@Test
public void testCompute()
{
ApproximateHistogram ah = buildHistogram(10, VALUES);
final TestFloatColumnSelector selector = new TestFloatColumnSelector(VALUES);
ApproximateHistogramAggregator agg = new ApproximateHistogramAggregator("price", selector, 10, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY);
for (int i = 0; i < VALUES.length; i++) {
agg.aggregate();
selector.increment();
}
Map<String, Object> metricValues = new HashMap<String, Object>();
metricValues.put(agg.getName(), agg.get());
ApproximateHistogramPostAggregator approximateHistogramPostAggregator = new EqualBucketsPostAggregator(
"approxHist",
"price",
5
);
Assert.assertEquals(ah.toHistogram(5), approximateHistogramPostAggregator.compute(metricValues));
}
}
| 32.863636
| 149
| 0.733057
|
0d13e0b0ec7b1afbc1c59c9ecbc7456fc82c3095
| 3,277
|
package com.nitkarsh.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.nitkarsh.navdrawerrecycler.R;
import java.util.List;
public class AdapterData extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<Object> list;
private DrawerLayout drawerLayout;
private RecyclerView.LayoutManager layoutManager;
private final int head=0,tag=1;
public AdapterData(Context context, List<Object> list, DrawerLayout drawerLayout, RecyclerView.LayoutManager layoutManager){
this.context=context;
this.list=list;
this.drawerLayout=drawerLayout;
this.layoutManager=layoutManager;
}
private List<Object> objectList;
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
switch (viewType){
case tag:
View v1=inflater.inflate(R.layout.recycler_menu_item,parent,false);
viewHolder=new ViewTags(context,v1,drawerLayout,layoutManager);
break;
case head:
View v2=inflater.inflate(R.layout.recycler_menu_head,parent,false);
viewHolder= new ViewHead(v2);
break;
default:
View v3=inflater.inflate(R.layout.recycler_menu_item,parent,false);
viewHolder = new ViewTags(context,v3,drawerLayout,layoutManager);
break;
}
return viewHolder;
}
@Override
public int getItemViewType(int position) {
if(list.get(position) instanceof TagData) {
return tag;
}
else{
return head;
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
switch(holder.getItemViewType()){
case tag:
ViewTags tags=(ViewTags)holder;
TagData dataTag=(TagData)list.get(position);
tags.getImageTag().setImageDrawable(ContextCompat.getDrawable(context,dataTag.getImage()));
tags.getTextTag().setText(dataTag.getText());
break;
case head:
ViewHead head=(ViewHead)holder;
HeadData dataHead=(HeadData)list.get(position);
head.getTvHead().setText(dataHead.getHead());
break;
default:
ViewTags defaultTag=(ViewTags)holder;
TagData dataDefault=(TagData)list.get(position);
defaultTag.getImageTag().setImageDrawable(ContextCompat.getDrawable(context,dataDefault.getImage()));
defaultTag.getTextTag().setText(dataDefault.getText());
break;
}
}
@Override
public int getItemCount() {
return list.size();
}
}
| 34.861702
| 128
| 0.647543
|
7cadfedd6ea285e1ebfab7c57c8ca6d02d0178ef
| 918
|
package com.gildedrose.test;
public class ItemBackstagePasses extends Item implements IStrategy {
public ItemBackstagePasses(String name, int sellIn, int quality) {
super(name, sellIn, quality);
}
public void updateQuality() {
if (this.sellIn <= Constants.LIMIT.EXPIRED.day) {
this.quality = Constants.LOWER_QUALITY_LIMIT;
} else if (this.sellIn <= Constants.LIMIT.DAYS5.day) {
this.quality += Constants.TRIPLE_INCREASE;
} else if (this.sellIn <= Constants.LIMIT.DAYS10.day) {
this.quality += Constants.DOUBLE_INCREASE;
} else if (this.sellIn > Constants.LIMIT.DAYS10.day) {
this.quality += Constants.STANDARD_INCREASE;
}
if(this.quality >= Constants.UPPER_QUALITY_LIMIT){
this.quality = Constants.UPPER_QUALITY_LIMIT;
}
this.sellIn -= Constants.DAY_INCREASE;
}
}
| 32.785714
| 70
| 0.64488
|
050e71f3a3ef76d07fa560da9ea30422a58822eb
| 1,000
|
package com.megait.mymall.service;
import com.megait.mymall.domain.Member;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class EmailService {
private final MailSender consoleMailSender;
@Transactional
public void sendEmail(Member member) {
member.generateEmailCheckToken();
String url = "http://127.0.0.1:8080/email-check-token?token="
+ member.getEmailCheckToken() + "&email=" + member.getEmail();
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(member.getEmail());
message.setFrom("admin@mymall.com");
message.setSubject("[mymall] 회원가입 이메일 인증 링크입니다.");
message.setText("다음 링크를 클릭해주세요. =>" + url);
consoleMailSender.send(message);
}
}
| 30.30303
| 78
| 0.721
|
61133fc122baf0dede28c66e2c4de8e80087402a
| 1,449
|
package com.universign.javaclient.signature;
/**
* Describes a requester of a transaction.
* InitiatorInfo is used as a return value only.
*
*/
public class InitiatorInfo
{
private String email;
private String firstname;
private String lastname;
/**
* The InitiatorInfo Constructor.
*/
InitiatorInfo()
{
// package constructor
}
/**
* Return the requester email.
*
* @return The requester email.
*/
public String getEmail()
{
return email;
}
/**
* Sets a requester email.
*
* @param email The requester email.
* @return The current object instance
*/
public InitiatorInfo setEmail(String email)
{
this.email = email;
return this;
}
/**
* Return the requester first name.
*
* @return The requester firstname.
*/
public String getFirstname()
{
return firstname;
}
/**
* Sets the requester first name.
*
* @param firstname The requester first name.
* @return The current object instance
*/
public InitiatorInfo setFirstname(String firstname)
{
this.firstname = firstname;
return this;
}
/**
* Return the requester last name.
*
* @return The requester lastname.
*/
public String getLastname()
{
return lastname;
}
/**
* Sets the requester last name.
*
* @param lastname The requester last name.
* @return The current object instance
*/
public InitiatorInfo setLastname(String lastname)
{
this.lastname = lastname;
return this;
}
}
| 16.280899
| 52
| 0.674948
|
cf444316b62ce332145a32c522ebf1fe24bb0d17
| 1,439
|
package me.zhehua.uilibrary.range;
import android.content.Context;
import android.support.annotation.ColorInt;
import android.text.SpannableString;
import android.text.Spanned;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by Zhehua on 2016/10/27.
*/
public class RangedTextView extends TextView {
RangeSpan mRangeSpan;
public RangedTextView(Context context) {
this(context, null);
}
public RangedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mRangeSpan = new RangeSpan();
}
public void setRangedText(String text, int start, int end) {
SpannableString spannable = new SpannableString(text);
spannable.setSpan(mRangeSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
super.setText(spannable);
}
public RangedTextView setRange(float percentage) {
mRangeSpan.setRange(percentage);
return this;
}
public RangedTextView setNormalColor(int color) {
super.setTextColor(color);
return this;
}
public RangedTextView setRangedColor(@ColorInt int highlightColor) {
mRangeSpan.setHighlightColor(highlightColor);
return this;
}
public RangedTextView setRangedBackColor(@ColorInt int normalColor) {
mRangeSpan.setTextColor(normalColor);
return this;
}
public void show() {
invalidate();
}
}
| 25.696429
| 84
| 0.694927
|
2f8c002fe540d9a95eda845bb56913bdb59f2a60
| 2,065
|
package com.excilys.db.page;
import java.util.List;
import java.util.Scanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.excilys.db.exception.CompaniesInexistantException;
import com.excilys.db.model.Computer;
import com.excilys.db.service.IComputerService;
@Component
public class PageComputerCLI {
List<Computer> computers;
int index;
private Scanner sc;
protected int pageSize;
protected int pageNumber;
@Autowired
IComputerService computerService;
/**
*
*/
public PageComputerCLI() {
super();
}
/**
*
* @param list des ordinateurs
* @param sc le scanner
*/
public PageComputerCLI(List<Computer> list, Scanner sc) {
computers = list;
index = 0;
this.sc = sc;
}
/**
*
* @param n le nombre d'element a afficher
*/
public void afficherNElements(int n) {
int end = index + n;
for (int i = index; i < Math.min(end, computers.size()); i++) {
System.out.println("Ordinateur " + (i + 1) + computers.get(i).toString());
index++;
}
}
/**
*
*/
public void afficher() {
while (index < computers.size()) {
String exit = sc.nextLine();
if (exit.equals("Q") || exit.equals("q")) {
index = computers.size();
}
afficherNElements(this.pageSize);
}
}
/**
*
* @param offset l'offset
* @param limit la limit
* @param sortBy sortBy
* @param orderBy l'ordre
* @return la liste des ordinateurs
* @throws CompaniesInexistantException
*/
public List<Computer> getPage(int offset, int limit, String sortBy, String orderBy) {
return computerService.listComputer(offset, limit, sortBy, orderBy);
}
/**
*
*/
public void updateComputer() {
computers = computerService.listComputer(this.pageNumber, this.pageSize);
}
}
| 22.944444
| 89
| 0.59322
|
8e84f10ae6a28ad67bfa129c4a41de47bc33e9c3
| 6,082
|
/**
* "First, solve the problem. Then, write the code. -John Johnson"
* "Or use Vangav M"
* www.vangav.com
* */
/**
* MIT License
*
* Copyright (c) 2016 Vangav
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
* */
/**
* Community
* Facebook Group: Vangav Open Source - Backend
* fb.com/groups/575834775932682/
* Facebook Page: Vangav
* fb.com/vangav.f
*
* Third party communities for Vangav Backend
* - play framework
* - cassandra
* - datastax
*
* Tag your question online (e.g.: stack overflow, etc ...) with
* #vangav_backend
* to easier find questions/answers online
* */
package com.vangav.backend.play_framework.controllers_generator.json;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author mustapha
* fb.com/mustapha.abdallah
*/
/**
* ControllersJson represents all controllers of a backend
* */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ControllersJson {
/**
* java_package is usually the reverse of the project's domain name
* (e.g.: com.vangav is the reverse of vangav.com)
* it serves as a unique identifier for the set of projects related to that
* domain name in order to avoid conflicts with other libraries
*/
@JsonProperty
public String java_package;
/**
* check_source is used to check the request source for device-specific
* operations (e.g.: if a mobile app backend wants to reject requests
* coming from computers to potentially try to cause some harm)
* also used for specific-client applications (like mobile apps) to verify
* client (using request hashing with a secret phrase or else)
*/
@JsonProperty
public boolean check_source;
/**
* throttle is a common need for mobile applications and websites to ban
* behavior like spam, DOS, etc ...
*/
@JsonProperty
public boolean throttle;
/**
* validate_param is used to validate a request (e.g.: validate e-mail
* format, photo size, etc ...)
*/
@JsonProperty
public boolean validate_param;
/**
* authenticate is used to authenticate a request (e.g.: OAuth 2,
* Facebook Login, etc ...)
*/
@JsonProperty
public boolean authenticate;
/**
* after_response is used to switch on/off all after response operations
* (each of those operation has a switch property whose value only matters
* if this property's value is true)
*/
@JsonProperty
public boolean after_response;
/**
* after_processing is used to enable doing further processing for a request
* after a response is sent. (e.g.: let's say someone shared a public post
* on Facebook, before a response is sent this post must be made to appear
* for that user's friends which is critical for a successful post; then
* in after processing the post gets assigned to more non-friend users
* which if failed doesn't affect the success of the request from the
* user-experience point of view)
*/
@JsonProperty
public boolean after_processing;
/**
* default_operations are used to execute operations that happen after each
* request regardless of the type of that request (e.g.: in a mobile app
* default operations can be used to update the user's notifications'
* badge number; for example to reset it on the backend side since
* a request means that the user opened the app)
*/
@JsonProperty
public boolean default_operations;
/**
* notifications is used to enable sending push notifications
*/
@JsonProperty
public boolean notifications;
/**
* analysis is used to enable doing analysis after requests
*/
@JsonProperty
public boolean analysis;
/**
* logging is used to enable logging requests, responses, exceptions, etc ...
*/
@JsonProperty
public boolean logging;
/**
* controllers reprsents all backend controllers
*/
@JsonProperty
public ControllerJson[] controllers;
/**
* fromJsonString
* @param json
* @return ControllersJson Object reflecting param json String
* @throws Exception
*/
@JsonIgnore
public static ControllersJson fromJsonString (String json) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, ControllersJson.class);
}
/**
* getAsString
* @return String representation of this JSON Object
* @throws Exception
*/
@JsonIgnore
public String getAsString () throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
return
objectMapper.writerWithDefaultPrettyPrinter(
).writeValueAsString(this);
}
@Override
@JsonIgnore
public String toString () {
try {
return
"ControllersJson:\n"
+ this.getAsString();
} catch (Exception e) {
return
"ControllersJson: threw and Exception!";
}
}
}
| 31.512953
| 79
| 0.706018
|
7de7442efaf6e7ece0bc2816e0a1b2282a2e4064
| 4,142
|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.failurehandler.value;
import java.util.HashMap;
import java.util.Map;
public class DefaultParser implements ValueParser {
private static final Map<Class<?>, BasicParser> PARSERS = new HashMap<>();
static {
BasicParser.init();
}
@Override
public Object parse(Class<?> type, String value, String s) {
if (type.isArray()) {
return new ArrayParser(this).parse(type, value, s);
}
ValueParser parser = PARSERS.get(type);
if (parser == null) {
throw new IllegalArgumentException("can't find parser for "
+ type.getName());
}
return parser.parse(type, value, s);
}
private static enum BasicParser implements ValueParser {
BOOL(boolean.class, Boolean.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return Boolean.valueOf(value);
}
},
BYTE(byte.class, Byte.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return Byte.decode(value);
}
},
CHAR(char.class, Character.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
if (value.length() != 1) {
throw new IllegalArgumentException(
String.format("can't cast %s to char", value));
}
return value.charAt(0);
}
},
SHORT(short.class, Short.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return Short.decode(value);
}
},
INT(int.class, Integer.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return Integer.decode(value);
}
},
LONG(long.class, Long.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return Long.decode(value);
}
},
FLOAT(float.class, Float.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return Float.parseFloat(value);
}
},
DOUBLE(double.class, Double.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return Double.parseDouble(value);
}
},
STRING(String.class, Object.class) {
@Override
public Object parse(Class<?> type, String value, String s) {
return value;
}
};
private BasicParser(Class<?>... classes) {
for (Class<?> aClass : classes) {
DefaultParser.PARSERS.put(aClass, this);
}
}
private static void init() {
// no-op used to provoke <cinit>
}
}
}
| 34.231405
| 78
| 0.56929
|
b49eee62d53f61be499b7f3c33ed711811116ec5
| 346
|
package com.akash.showoffapp.modules.jobs;
import com.akash.showoffapp.base.BasePresenter;
import com.akash.showoffapp.modules.jobs.view.IJobsView;
public class JobsPresenter extends BasePresenter<IJobsView> {
@Override
protected void setupDataObservers() {
}
@Override
protected void createViewSubscriptions() {
}
}
| 20.352941
| 61
| 0.754335
|
c7811ecae70c202f736f4f665139d249ae2834cf
| 3,524
|
package it.unive.golisa.cfg.expression.literal;
import it.unive.golisa.cfg.statement.assignment.GoShortVariableDeclaration.NumericalTyper;
import it.unive.golisa.cfg.type.composite.GoTypesTuple;
import it.unive.golisa.cfg.type.numeric.signed.GoIntType;
import it.unive.lisa.analysis.AbstractState;
import it.unive.lisa.analysis.AnalysisState;
import it.unive.lisa.analysis.SemanticException;
import it.unive.lisa.analysis.heap.HeapDomain;
import it.unive.lisa.analysis.lattices.ExpressionSet;
import it.unive.lisa.analysis.value.ValueDomain;
import it.unive.lisa.caches.Caches;
import it.unive.lisa.interprocedural.InterproceduralAnalysis;
import it.unive.lisa.program.cfg.CFG;
import it.unive.lisa.program.cfg.CodeLocation;
import it.unive.lisa.program.cfg.Parameter;
import it.unive.lisa.program.cfg.statement.Expression;
import it.unive.lisa.program.cfg.statement.call.NativeCall;
import it.unive.lisa.symbolic.SymbolicExpression;
import it.unive.lisa.symbolic.heap.AccessChild;
import it.unive.lisa.symbolic.heap.HeapAllocation;
import it.unive.lisa.symbolic.heap.HeapDereference;
import it.unive.lisa.symbolic.heap.HeapReference;
import it.unive.lisa.symbolic.value.Constant;
public class GoExpressionsTuple extends NativeCall {
public GoExpressionsTuple(CFG cfg, CodeLocation location, Expression[] expressions) {
super(cfg, location, "(tuple)", expressions);
}
@Override
public <A extends AbstractState<A, H, V>,
H extends HeapDomain<H>,
V extends ValueDomain<V>> AnalysisState<A, H, V> callSemantics(
AnalysisState<A, H, V> entryState, InterproceduralAnalysis<A, H, V> interprocedural,
AnalysisState<A, H, V>[] computedStates, ExpressionSet<SymbolicExpression>[] params)
throws SemanticException {
AnalysisState<A, H,
V> lastPostState = computedStates.length == 0 ? entryState : computedStates[computedStates.length - 1];
// Length of the expression tuple
int len = getParameters().length;
Parameter[] types = new Parameter[len];
for (int i = 0; i < types.length; i++) {
Expression p = getParameters()[i];
types[i] = new Parameter(p.getLocation(), "_", p.getDynamicType());
}
GoTypesTuple tupleType = new GoTypesTuple(types);
HeapAllocation created = new HeapAllocation(Caches.types().mkSingletonSet(tupleType), getLocation());
// Allocates the new heap allocation
AnalysisState<A, H, V> containerState = lastPostState.smallStepSemantics(created, this);
ExpressionSet<SymbolicExpression> containerExps = containerState.getComputedExpressions();
AnalysisState<A, H, V> result = entryState.bottom();
for (SymbolicExpression containerExp : containerExps) {
HeapReference reference = new HeapReference(Caches.types().mkSingletonSet(getStaticType()), containerExp,
getLocation());
HeapDereference dereference = new HeapDereference(Caches.types().mkSingletonSet(getStaticType()), reference,
getLocation());
AnalysisState<A, H, V> tmp = containerState;
for (int i = 0; i < len; i++) {
AccessChild access = new AccessChild(Caches.types().mkSingletonSet(tupleType.getTypeAt(i)), dereference,
new Constant(GoIntType.INSTANCE, i, getLocation()), getLocation());
AnalysisState<A, H, V> accessState = tmp.smallStepSemantics(access, this);
for (SymbolicExpression index : accessState.getComputedExpressions())
for (SymbolicExpression v : params[i])
tmp = tmp.assign(index, NumericalTyper.type(v), this);
}
result = result.lub(tmp.smallStepSemantics(reference, this));
}
return result;
}
}
| 41.458824
| 111
| 0.764472
|
60f831593607010facdfa40f4e915342198e6653
| 3,469
|
/*
* Copyright 2019 YugaByte, Inc. and Contributors
*
* Licensed under the Polyform Free Trial License 1.0.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://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt
*/
package com.yugabyte.yw.commissioner.tasks.subtasks;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableList;
import com.yugabyte.yw.commissioner.AbstractTaskBase;
import com.yugabyte.yw.common.ShellResponse;
import com.yugabyte.yw.common.TableManager;
import com.yugabyte.yw.forms.AbstractTaskParams;
import com.yugabyte.yw.forms.BackupTableParams;
import com.yugabyte.yw.forms.ITaskParams;
import com.yugabyte.yw.models.Backup;
import play.api.Play;
import play.libs.Json;
import java.util.List;
import java.util.UUID;
public class DeleteBackup extends AbstractTaskBase {
public static class Params extends AbstractTaskParams {
public UUID customerUUID;
public UUID backupUUID;
}
public Params params() {
return (Params) taskParams;
}
private TableManager tableManager;
@Override
public void initialize(ITaskParams params) {
super.initialize(params);
tableManager = Play.current().injector().instanceOf(TableManager.class);
}
@Override
public void run() {
Backup backup = Backup.get(params().customerUUID, params().backupUUID);
if (backup.state != Backup.BackupState.Completed) {
// TODO: Allow deletion of InProgress backups. But not sure if backend supports it
// and may not be worth the effort.
LOG.error("Cannot delete backup in any other state other than completed.");
return;
}
try {
BackupTableParams backupParams = backup.getBackupInfo();
List<BackupTableParams> backupList =
backupParams.backupList == null ? ImmutableList.of(backupParams) : backupParams.backupList;
if (deleteAllBackups(backupList)) {
transitionState(backup, Backup.BackupState.Deleted);
return;
}
} catch (Exception ex) {
LOG.error("Unexpected error in DeleteBackup {}. We will ignore the error and Mark the " +
"backup as failed to be deleted and remove it from scheduled cleanup.",
params().backupUUID, ex);
}
transitionState(backup, Backup.BackupState.FailedToDelete);
}
private static void transitionState(Backup backup, Backup.BackupState newState) {
if (backup != null) {
backup.transitionState(newState);
}
}
private boolean deleteAllBackups(List<BackupTableParams> backupList) {
boolean success = true;
for (BackupTableParams childBackupParams : backupList) {
if (!deleteBackup(childBackupParams)) {
success = false;
}
}
return success;
}
private boolean deleteBackup(BackupTableParams backupTableParams) {
backupTableParams.actionType = BackupTableParams.ActionType.DELETE;
ShellResponse response = tableManager.deleteBackup(backupTableParams);
JsonNode jsonNode = Json.parse(response.message);
if (response.code != 0 || jsonNode.has("error")) {
LOG.error("Delete Backup failed for {}. Response code={}, hasError={}.",
backupTableParams.storageLocation, response.code, jsonNode.has("error"));
return false;
} else {
LOG.info("[" + getName() + "] STDOUT: " + response.message);
return true;
}
}
}
| 33.679612
| 100
| 0.715768
|
5f696498d2996bd5cee5fbfbcb620081cd1f8a9f
| 385
|
package com.ullink.slack.simpleslackapi.events;
import com.ullink.slack.simpleslackapi.SlackChannel;
import lombok.Data;
@Data
public class SlackChannelRenamed implements SlackEvent {
private final SlackChannel slackChannel;
private final String newName;
@Override
public SlackEventType getEventType() {
return SlackEventType.SLACK_CHANNEL_RENAMED;
}
}
| 22.647059
| 56
| 0.776623
|
86b1e14238ebcdeef13f8a630090800fd9cfe19c
| 2,229
|
/*
Copyright 2001 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.flex.forks.batik.ext.awt.image.rendered;
import java.awt.image.Raster;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
/**
* This is a useful class that wraps a Raster for patricipation in
* an LRU Cache. When this object drops out of the LRU cache it
* removes it's hard reference to the tile, but retains it's soft
* reference allowing for the recovery of the tile when the JVM is
* not under memory pressure
*/
public class TileLRUMember implements LRUCache.LRUObj {
private static final boolean DEBUG = false;
protected LRUCache.LRUNode myNode = null;
protected Reference wRaster = null;
protected Raster hRaster = null;
public TileLRUMember() { }
public TileLRUMember(Raster ras) {
setRaster(ras);
}
public void setRaster(Raster ras) {
hRaster = ras;
wRaster = new SoftReference(ras);
}
public boolean checkRaster() {
if (hRaster != null) return true;
if ((wRaster != null) &&
(wRaster.get() != null)) return true;
return false;
}
public Raster retrieveRaster() {
if (hRaster != null) return hRaster;
if (wRaster == null) return null;
hRaster = (Raster)wRaster.get();
if (hRaster == null) // didn't manage to retrieve it...
wRaster = null;
return hRaster;
}
public LRUCache.LRUNode lruGet() { return myNode; }
public void lruSet(LRUCache.LRUNode nde) { myNode = nde; }
public void lruRemove() {
myNode = null;
hRaster = null;
if (DEBUG) System.out.println("Removing");
}
}
| 28.21519
| 75
| 0.676537
|
8459d0491073f934a5f5e10d5604c77fcbf08205
| 1,172
|
package com.bumptech.glide.supportapp.stackoverflow._35107329_rounded_drawable;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.graphics.drawable.*;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.transcode.ResourceTranscoder;
public class RoundedDrawableTranscoder implements ResourceTranscoder<Bitmap, RoundedBitmapDrawable> {
private final Context context;
private final BitmapPool bitmapPool;
public RoundedDrawableTranscoder(Context context) {
this.context = context;
this.bitmapPool = Glide.get(context).getBitmapPool();
}
@Override public Resource<RoundedBitmapDrawable> transcode(Resource<Bitmap> toTranscode) {
Bitmap resource = toTranscode.get();
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);
drawable.setCircular(true);
return new RoundedBitmapDrawableResource(drawable, bitmapPool);
}
@Override public String getId() {
return getClass().getName() + "." + getClass().getPackage().getName();
}
}
| 36.625
| 105
| 0.80802
|
f1e71e76197f8c4a085e48389fd0e76819edbef9
| 1,459
|
package com.education.common;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: haojie
* @qq :1422471205
* @CreateTime: 2021-07-29-09-27
*/
@Data
public class Result {
/**
* 是否成功
*/
private Boolean success;
/**
* 返回码
*/
private Integer code;
/**
* 返回信息
*/
private String message;
/**
* 返回数据
*/
private Map<String, Object> data = new HashMap<String, Object>();
public static Result success(){
Result result = new Result();
result.setSuccess(true);
result.setCode(ResultCode.SUCCESS_CODE.getCode());
result.setMessage("请求成功");
return result;
}
public static Result fail(){
Result result = new Result();
result.setSuccess(false);
result.setCode(ResultCode.FAILER_CODE.getCode());
result.setMessage("请求失败");
return result;
}
public Result success(Boolean success){
this.setSuccess(success);
return this;
}
public Result code(Integer code) {
this.setCode(code);
return this;
}
public Result message(String message){
this.setMessage(message);
return this;
}
public Result data(Map<String,Object> map){
this.setData(map);
return this;
}
public Result data(String key,Object value){
this.data.put(key, value);
return this;
}
}
| 18.705128
| 69
| 0.580535
|
6c250aac81ffb17815229022808b60194e37a8a1
| 524
|
/*
* Copyright (C) Byte-Store.DE, Inc - All Rights Reserved
*
* Unauthorized copying of this file, via any medium is strictly prohibited.
*/
package de.packet.mailbox.core;
import net.dv8tion.jda.api.entities.User;
import java.util.ArrayList;
public class CacheHandler {
public static String TOKEN = "YOUR_TOKEN";
public static boolean MAILBOX_STATUS = false;
public static ArrayList<User> MAILBOX_TEXT = new ArrayList<User>();
public static ArrayList<User> MAILBOX_VOICE = new ArrayList<User>();
}
| 26.2
| 76
| 0.736641
|
6471c4f3dc70a45a5048e5b2fc2950df33c04128
| 958
|
package tools.balok;
import balok.causality.AccessMode;
import balok.causality.Epoch;
import balok.causality.Event;
public class ExclusiveState implements BalokShadowLocation {
private Event<Epoch> event;
private AccessMode mode;
private final int lastTid;
public ExclusiveState(Event<Epoch> event, AccessMode mode, int lastTid) {
this.event = event;
this.mode = mode;
this.lastTid = lastTid;
}
public boolean isEmpty() {
return event == null;
}
public boolean isExclusive(int tid) {
if (lastTid == tid) {
return true;
} else {
return false;
}
}
public Event<Epoch> getEvent() {
return event;
}
public AccessMode getMode() {
return mode;
}
public void setEvent(Event<Epoch> event) {
this.event = event;
}
public void setMode(AccessMode mode) {
this.mode = mode;
}
}
| 19.55102
| 77
| 0.604384
|
6f0b2a57a3c180ac7b5574bf298f1fc75f061720
| 895
|
package net.consensys.eventeum.config;
import net.consensys.eventeum.annotation.ConditionalOnRocketRequired;
import net.consensys.eventeum.dto.message.EventeumMessage;
import net.consensys.eventeum.integration.RocketSettings;
import net.consensys.eventeum.utils.RocketTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Spring configuration for RocketMQ related beans.
*
* @author quhuanwen
*/
@Configuration("eventeumRocketConfiguration")
@ConditionalOnRocketRequired
public class RocketConfiguration {
@Autowired
private RocketSettings settings;
@Bean(initMethod = "init", destroyMethod = "destroy")
public RocketTemplate<String, EventeumMessage> eventeumRocketTemplate() {
return new RocketTemplate<>(settings);
}
}
| 31.964286
| 77
| 0.805587
|
5d9c04a9b1d64aefa155aaa08be95707ba441e96
| 164
|
package com.benefire.framework.repository.query;
/**
* @param <T> the domain type the repository manages
* @author jiang
*/
public interface Repository<T> {
}
| 16.4
| 52
| 0.719512
|
987962478b0110f78d47a28984d7a918fc3f4360
| 21,823
|
package kbasesearchengine.test.parse;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import kbasesearchengine.common.GUID;
import kbasesearchengine.common.ObjectJsonPath;
import kbasesearchengine.events.handler.SourceData;
import kbasesearchengine.events.handler.SourceData.Builder;
import kbasesearchengine.parse.IdMapper;
import kbasesearchengine.parse.ObjectParser;
import kbasesearchengine.parse.SimpleIdConsumer;
import kbasesearchengine.parse.SimpleSubObjectConsumer;
import kbasesearchengine.parse.SubObjectConsumer;
import kbasesearchengine.system.ObjectTypeParsingRules;
import kbasesearchengine.system.ObjectTypeParsingRulesFileParser;
import kbasesearchengine.test.common.TestCommon;
import us.kbase.common.service.UObject;
public class ObjectParserTest {
private static Path scratch;
@BeforeClass
public static void prepare() throws Exception {
scratch = Paths.get(TestCommon.getTempDir(), "test_object_parser");
}
@AfterClass
public static void teardown() throws Exception {
final boolean deleteTempFiles = TestCommon.getDeleteTempFiles();
if (scratch != null && scratch.toFile().exists() && deleteTempFiles) {
FileUtils.deleteDirectory(scratch.toFile());
}
}
/**
* Testing object with 'from-parent' attributes
*
* @throws Exception
*/
@Test
public void extractParentFragmentGenomeFeatureTest() throws Exception {
final String jsonResource = "genome01";
final String type = "GenomeFeature";
final String parentJson = extractParentFragment(type, jsonResource);
final String expectedParentJson = "{\"domain\":\"B\",\"scientific_name\":\"Shewanella\","
+ "\"assembly_ref\":\"1/2/1\"}";
assertEquals(parentJson, expectedParentJson);
}
/**
* Testing object with no 'from-parent' attributes
*
* @throws Exception
*/
@Test
public void extractParentFragmentGenomeTest() throws Exception {
final String jsonResource = "assembly01";
final String type = "Assembly";
final String parentJson = extractParentFragment(type, jsonResource);
assertNull(parentJson); // Assembly.yaml doesn't have "from-parent" path
}
/**
* Helper method for ObjectParser.extractParentFragment tests
*
* @param type
* @param jsonResource
* @return
* @throws Exception
*/
public static String extractParentFragment(String type, String jsonResource) throws Exception {
final File rulesFile = new File("resources/types/" + type + ".yaml");
final ObjectTypeParsingRules parsingRules = ObjectTypeParsingRulesFileParser
.fromFile(rulesFile).get(0);
try (JsonParser jts = SubObjectExtractorTest.getParsedJsonResource(jsonResource)) {
final String parentJson = ObjectParser.extractParentFragment(parsingRules, jts);
return parentJson;
}
}
/**
* Testing preparing a genome feature GUID
*
* @throws Exception
*/
@Test
public void prepareGUIDGenomeFeatureTest() throws Exception {
final String jsonResource = "genome01";
final String type = "GenomeFeature";
final ArrayList<GUID> idList = prepareGUID(type, jsonResource, new GUID("WS:1/1/1"));
assertThat(idList.size(), is(3));
final List<String> expectedIds = Arrays.asList("NewGenome.CDS.6211", "NewGenome.CDS.6210",
"NewGenome.CDS.6209");
for (GUID guid : idList) {
assertThat(guid.getSubObjectId(), is(expectedIds.get(idList.indexOf(guid))));
assertThat(guid.getSubObjectType(), is("feature"));
assertThat(guid.getStorageCode(), is("WS"));
assertThat(guid.getVersion(), is(1));
assertThat(guid.getAccessGroupId(), is(1));
assertThat(guid.getAccessGroupObjectId(), is("1"));
}
}
/**
* Helper method for ObjectParser.prepareGUID tests
*
* @param type
* @param jsonResource
* @param ref
* @return
* @throws Exception
*/
public static ArrayList<GUID> prepareGUID(String type, String jsonResource, GUID ref)
throws Exception {
final ArrayList<GUID> idList = new ArrayList<GUID>();
final File rulesFile = new File("resources/types/" + type + ".yaml");
final ObjectTypeParsingRules parsingRules = ObjectTypeParsingRulesFileParser
.fromFile(rulesFile).get(0);
final Map<ObjectJsonPath, String> pathToJson = new LinkedHashMap<>();
final SubObjectConsumer subObjConsumer = new SimpleSubObjectConsumer(pathToJson);
try (JsonParser jts = SubObjectExtractorTest.getParsedJsonResource(jsonResource)) {
ObjectParser.extractSubObjects(parsingRules, subObjConsumer, jts);
}
for (ObjectJsonPath path : pathToJson.keySet()) {
final String subJson = pathToJson.get(path);
final SimpleIdConsumer idConsumer = new SimpleIdConsumer();
if (parsingRules.getSubObjectIDPath().isPresent()) {
try (JsonParser subJts = UObject.getMapper().getFactory().createParser(subJson)) {
IdMapper.mapKeys(parsingRules.getSubObjectIDPath().get(), subJts, idConsumer);
}
}
final GUID id = ObjectParser.prepareGUID(parsingRules, ref, path, idConsumer);
idList.add(id);
}
return idList;
}
/**
* Testing parsing Assembly object
*
* @throws Exception
*/
@Test
public void parseSubObjectsGenomeTest() throws Exception {
final String jsonResource = "assembly01";
final String type = "Assembly";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(1));
final String jsonString = guidToJson.values().iterator().next();
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, HashMap.class);
HashMap<String, Object> expectedResult = new HashMap<String, Object>();
expectedResult.put("dna_size", 4706287);
expectedResult.put("external_source_id", "NC_008321.fna");
expectedResult.put("contigs", 1);
expectedResult.put("name", "test_asmb.1");
expectedResult.put("gc_content", 0.478944654246543);
assertThat(expectedResult, is(result));
}
/**
* Testing parsing GenomeFeature object
*
* @throws Exception
*/
@Test
public void parseSubObjectsGenomeFeatureTest() throws Exception {
final String jsonResource = "genome01";
final String type = "GenomeFeature";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(3));
final List<String> expectedIds = Arrays.asList("NewGenome.CDS.6211", "NewGenome.CDS.6210",
"NewGenome.CDS.6209");
int key_index = 0;
for (GUID guidKey : guidToJson.keySet()) {
assertThat(guidKey.getSubObjectId(), is(expectedIds.get(key_index)));
assertThat(guidKey.getSubObjectType(), is("feature"));
assertThat(guidKey.getStorageCode(), is("WS"));
assertThat(guidKey.getVersion(), is(1));
assertThat(guidKey.getAccessGroupId(), is(1));
assertThat(guidKey.getAccessGroupObjectId(), is("1"));
key_index++;
}
final List<String> expectedKeys = Arrays.asList("ontology_terms", "function",
"protein_translation", "location", "id", "type");
final List<String> expectedFunctions = Arrays.asList("Polysaccharide biosynthesis protein",
"Transcriptional activator RfaH", "Di-tripeptide/cation symporter");
final String expectedType = "CDS";
int value_index = 0;
for (String jsonString : guidToJson.values()) {
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString,
HashMap.class);
assertThat(expectedKeys.containsAll(result.keySet()), is(true));
assertThat(result.get("id"), is(expectedIds.get(value_index)));
assertThat(result.get("function"), is(expectedFunctions.get(value_index)));
assertThat(result.get("type"), is(expectedType));
value_index++;
}
}
/**
* Testing parsing MediaCompound object
*
* @throws Exception
*/
@Test
public void parseSubObjectsMediaCompoundTest() throws Exception {
final String jsonResource = "media01";
final String type = "MediaCompound";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(3));
final List<String> expectedIds = Arrays.asList(
"48/1/1/compounds/id/cpd00027",
"48/1/1/compounds/id/cpd00013",
"48/1/1/compounds/id/cpd00009");
int key_index = 0;
for (GUID guidKey : guidToJson.keySet()) {
assertThat(guidKey.getSubObjectId(), is(expectedIds.get(key_index)));
assertThat(guidKey.getSubObjectType(), is("MediaCompound"));
assertThat(guidKey.getStorageCode(), is("WS"));
assertThat(guidKey.getVersion(), is(1));
assertThat(guidKey.getAccessGroupId(), is(1));
assertThat(guidKey.getAccessGroupObjectId(), is("1"));
key_index++;
}
final List<String> expectedKeys = Arrays.asList("inchikey", "concentration",
"minFlux", "maxFlux", "id", "name", "compound_ref");
final List<Double> expectedFlux = Arrays.asList( 100.0, 10.0, 50.0);
final List<String> names = Arrays.asList( "cpd00027", "cpd00013", "cpd00009");
final Double expectedConcentration = 0.001;
final String inchikey = "WQZGKKKJIJFFOK-VFUOTHLCSA-N";
int value_index = 0;
for (String jsonString : guidToJson.values()) {
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString,
HashMap.class);
assertThat(result.keySet().size(), is(expectedKeys.size()));
assertThat(expectedKeys.containsAll(result.keySet()), is(true));
assertThat(result.get("compound_ref"), is(expectedIds.get(value_index)));
assertThat(result.get("id"), is(names.get(value_index)));
assertThat(result.get("name"), is(names.get(value_index)));
assertThat(result.get("maxFlux"), is(expectedFlux.get(value_index)));
assertThat(result.get("minFlux"), is(-expectedFlux.get(value_index)));
assertThat(result.get("concentration"), is(expectedConcentration));
assertThat(result.get("inchikey"), is(inchikey));
value_index++;
}
}
/**
* Testing parsing RNASeqSampleSet object
*
* @throws Exception
*/
@Test
public void parseObjectsRNASeqSampleSetTest() throws Exception {
final String jsonResource = "rnaseqsampleset01";
final String type = "RNASeqSampleSet";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(1));
final String jsonString = guidToJson.values().iterator().next();
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, HashMap.class);
HashMap<String, Object> expectedResult = new HashMap<String, Object>();
expectedResult.put("sampleset_desc", "Arabidopsis thaliana wild type and hy5-215 seedlings grown under white light.");
expectedResult.put("source", "NCBI SRP003951");
expectedResult.put("num_samples", 4);
expectedResult.put("num_replicates", 3);
assertThat(result, is(expectedResult));
}
/**
* Testing parsing FBAModel object
*
* @throws Exception
*/
@Test
public void parseObjectsModelTest() throws Exception {
final String jsonResource = "fbamodel01";
final String type = "FBAModel";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(1));
final String jsonString = guidToJson.values().iterator().next();
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, HashMap.class);
HashMap<String, Object> expectedResult = new HashMap<String, Object>();
expectedResult.put("id", "rast_test");
expectedResult.put("source", "KBase");
expectedResult.put("modelcompartments", 2);
expectedResult.put("modelcompounds", 3);
expectedResult.put("modelreactions", 3);
expectedResult.put("name", "E. coli");
expectedResult.put("type", "GenomeScale");
expectedResult.put("genome_ref", "1/2/1");
assertThat(result, is(expectedResult));
}
/**
* Testing parsing ModelCompound object
*
* @throws Exception
*/
@Test
public void parseSubObjectsModelCompoundTest() throws Exception {
final String jsonResource = "fbamodel01";
final String type = "ModelCompound";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(3));
final List<String> expectedIds = Arrays.asList("cpd00001_c0", "cpd02154_c0",
"cpd00013_c0");
int key_index = 0;
for (GUID guidKey : guidToJson.keySet()) {
assertThat(guidKey.getSubObjectId(), is(expectedIds.get(key_index)));
assertThat(guidKey.getSubObjectType(), is("ModelCompound"));
assertThat(guidKey.getStorageCode(), is("WS"));
assertThat(guidKey.getVersion(), is(1));
assertThat(guidKey.getAccessGroupId(), is(1));
assertThat(guidKey.getAccessGroupObjectId(), is("1"));
key_index++;
}
final List<String> expectedKeys = Arrays.asList("inchikey", "formula",
"aliases", "id", "name");
final List<String> expectedFormula = Arrays.asList("H2O", "C5H7N2O4", "H4N");
int value_index = 0;
for (String jsonString : guidToJson.values()) {
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString,
HashMap.class);
assertThat(expectedKeys.containsAll(result.keySet()), is(true));
assertThat(result.get("id"), is(expectedIds.get(value_index)));
assertThat(result.get("formula"), is(expectedFormula.get(value_index)));
value_index++;
}
}
/**
* Testing parsing ModelReaction object
*
* @throws Exception
*/
@Test
public void parseSubObjectsModelReactionTest() throws Exception {
final String jsonResource = "fbamodel01";
final String type = "ModelReaction";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(3));
final List<String> expectedIds = Arrays.asList("rxn02282_c0", "rxn02201_c0",
"rxn00351_c0");
int key_index = 0;
for (GUID guidKey : guidToJson.keySet()) {
assertThat(guidKey.getSubObjectId(), is(expectedIds.get(key_index)));
assertThat(guidKey.getSubObjectType(), is("ModelReaction"));
assertThat(guidKey.getStorageCode(), is("WS"));
assertThat(guidKey.getVersion(), is(1));
assertThat(guidKey.getAccessGroupId(), is(1));
assertThat(guidKey.getAccessGroupObjectId(), is("1"));
key_index++;
}
final List<String> expectedKeys = Arrays.asList("pathway", "aliases", "id",
"name");
final List<String> expectedName = Arrays.asList("N-Formimino-L-aspartate iminohydrolase_c0",
"2-amino-4-hydroxy-6-hydroxymethyl-7,8-dihydropteridine-diphosphate:4-aminobenzoate 2-amino-4-hydroxydihydropteridine-6-methenyltransferase_c0",
"gamma-L-glutamyl-L-cysteine:glycine ligase (ADP-forming)_c0");
int value_index = 0;
for (String jsonString : guidToJson.values()) {
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString,
HashMap.class);
assertThat(expectedKeys.containsAll(result.keySet()), is(true));
assertThat(result.get("id"), is(expectedIds.get(value_index)));
assertThat(result.get("name"), is(expectedName.get(value_index)));
value_index++;
}
}
/**
* Testing parsing ModelReactionProteinSubunit object
*
* @throws Exception
*/
@Test
public void parseSubObjectsModelReactionProteinSubunitTest() throws Exception {
final String jsonResource = "fbamodel01";
final String type = "ModelReactionProteinSubunit";
final String guid = "WS:1/1/1";
final Map<GUID, String> guidToJson = parseSubObjects(type, jsonResource, guid);
assertThat(guidToJson.size(), is(3));
final List<String> expectedIds = Arrays.asList("allantoate deiminase (EC 3.5.3.9)",
"Dihydropteroate synthase (EC 2.5.1.15)",
"Glutathione synthetase (EC 6.3.2.3)");
int key_index = 0;
for (GUID guidKey : guidToJson.keySet()) {
assertThat(guidKey.getSubObjectId(), is(expectedIds.get(key_index)));
assertThat(guidKey.getSubObjectType(), is("ModelReactionProteinSubunit"));
assertThat(guidKey.getStorageCode(), is("WS"));
assertThat(guidKey.getVersion(), is(1));
assertThat(guidKey.getAccessGroupId(), is(1));
assertThat(guidKey.getAccessGroupObjectId(), is("1"));
key_index++;
}
final List<String> expectedKeys = Arrays.asList("role", "feature_refs");
final List<List<String>> expectedName = Arrays.asList(
Arrays.asList("~/genome/features/id/eco_from_assembly.CDS.522"),
Arrays.asList("~/genome/features/id/eco_from_assembly.CDS.3263"),
Arrays.asList("~/genome/features/id/eco_from_assembly.CDS.3031"));
int value_index = 0;
for (String jsonString : guidToJson.values()) {
@SuppressWarnings("unchecked")
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString,
HashMap.class);
assertThat(expectedKeys.containsAll(result.keySet()), is(true));
assertThat(result.get("role"), is(expectedIds.get(value_index)));
assertThat(result.get("feature_refs"), is(expectedName.get(value_index)));
value_index++;
}
}
/**
* Helper method for ObjectParser.parseSubObjects tests
*
* @param type
* @param jsonResource
* @param guidString
* @param rule_version
* @return
* @throws Exception
*/
public static Map<GUID, String> parseSubObjects(String type, String jsonResource,
String guidString, int rule_version, String... keys) throws Exception {
final GUID guid = new GUID(guidString);
final InputStream inputStream = ObjectParserTest.class
.getResourceAsStream("data/"+jsonResource + ".json.properties");
final Reader reader = new InputStreamReader(inputStream);
final UObject data = UObject.fromJsonString(CharStreams.toString(reader));
final String name = "TestObj" + "_" + type;
final String creator = "creator";
final SourceData obj = SourceData.getBuilder(data, name, creator).build();
final File rulesFile = new File("resources/types/" + type + ".yaml");
final ObjectTypeParsingRules parsingRules = ObjectTypeParsingRulesFileParser
.fromFile(rulesFile).get(rule_version);
final Map<GUID, String> guidToJson = ObjectParser.parseSubObjects(obj, guid, parsingRules);
return guidToJson;
}
/**
* Helper method for ObjectParser.parseSubObjects tests
*
* @param type
* @param jsonResource
* @param guidString
* @return
* @throws Exception
*/
public static Map<GUID, String> parseSubObjects(String type, String jsonResource,
String guidString) throws Exception {
return parseSubObjects(type, jsonResource, guidString, 0);
}
}
| 39.320721
| 161
| 0.640379
|
10edb990e8a51f465657c165ce0566169318a7a1
| 5,256
|
package com.adshow.ad.entity;
import java.util.Date;
import com.adshow.core.common.entity.BaseEntity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.annotations.Version;
import org.springframework.format.annotation.DateTimeFormat;
/**
* <p>
*
* </p>
*
* @author wmz
* @since 2018-08-13
*/
@TableName("ad_player_program")
public class PlayerProgram extends BaseEntity<PlayerProgram> {
private static final long serialVersionUID = 1L;
/**
* 播放端ID
*/
@TableField("player_id")
private String playerId;
/**
* 播放端名称
*/
@TableField("player_name")
private String playerName;
/**
* 节目ID
*/
@TableField("program_id")
private String programId;
/**
* 节目名称
*/
@TableField("program_name")
private String programName;
/**
* 节目分辨率
*/
@TableField("resolution")
private String resolution;
/**
* 终端的节目状态 0-未下载 1-正在下载 2-下载完成 3-节目删除
*/
@TableField("status")
private Integer status;
/**
* 节目时长
*/
@TableField("program_duration")
private Integer programDuration;
/**
* 过期时间
*/
@TableField("start_date")
private Integer startDate;
/**
* 创建时间
*/
@TableField("end_date")
private Integer endDate;
/**
* 开始时段(0~24)
*/
@TableField("start_time")
private String startTime;
/**
* 结束时段(0~24)
*/
@TableField("end_time")
private String endTime;
/**
* 优先级
*/
@TableField("priority")
private Integer priority;
/**
* 节目大小
*/
@TableField("size")
private Long size;
/**
* 节目当前下载的大小
*/
@TableField("download_size")
private Long downloadSize;
public String getPlayerId() {
return playerId;
}
public PlayerProgram setPlayerId(String playerId) {
this.playerId = playerId;
return this;
}
public String getPlayerName() {
return playerName;
}
public PlayerProgram setPlayerName(String playerName) {
this.playerName = playerName;
return this;
}
public String getProgramId() {
return programId;
}
public PlayerProgram setProgramId(String programId) {
this.programId = programId;
return this;
}
public String getProgramName() {
return programName;
}
public PlayerProgram setProgramName(String programName) {
this.programName = programName;
return this;
}
public String getResolution() {
return resolution;
}
public PlayerProgram setResolution(String resolution) {
this.resolution = resolution;
return this;
}
public Integer getStatus() {
return status;
}
public PlayerProgram setStatus(Integer status) {
this.status = status;
return this;
}
public Integer getProgramDuration() {
return programDuration;
}
public PlayerProgram setProgramDuration(Integer programDuration) {
this.programDuration = programDuration;
return this;
}
public Integer getStartDate() {
return startDate;
}
public PlayerProgram setStartDate(Integer startDate) {
this.startDate = startDate;
return this;
}
public Integer getEndDate() {
return endDate;
}
public PlayerProgram setEndDate(Integer endDate) {
this.endDate = endDate;
return this;
}
public String getStartTime() {
return startTime;
}
public PlayerProgram setStartTime(String startTime) {
this.startTime = startTime;
return this;
}
public String getEndTime() {
return endTime;
}
public PlayerProgram setEndTime(String endTime) {
this.endTime = endTime;
return this;
}
public Integer getPriority() {
return priority;
}
public PlayerProgram setPriority(Integer priority) {
this.priority = priority;
return this;
}
public Long getSize() {
return size;
}
public PlayerProgram setSize(Long size) {
this.size = size;
return this;
}
public Long getDownloadSize() {
return downloadSize;
}
public PlayerProgram setDownloadSize(Long downloadSize) {
this.downloadSize = downloadSize;
return this;
}
@Override
public String toString() {
return "PlayerProgram{" +
"playerId=" + playerId +
", playerName=" + playerName +
", programId=" + programId +
", programName=" + programName +
", resolution=" + resolution +
", status=" + status +
", programDuration=" + programDuration +
", startDate=" + startDate +
", endDate=" + endDate +
", startTime=" + startTime +
", endTime=" + endTime +
", priority=" + priority +
", size=" + size +
", downloadSize=" + downloadSize +
"}";
}
}
| 21.365854
| 70
| 0.60293
|
4442aaddf94f2519e51a79a80d1d9126e4c73aa3
| 4,450
|
package org.jax.phenopacketgenerator.model;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A POJO class that contains all of the data we need to export a Phenopacket
*/
public class PgModel {
private final static String EMPTY_STRING = "";
private String hpoVersion = EMPTY_STRING;
private String ecoVersion = EMPTY_STRING;
private final TreeSet<PgOntologyClass> phenotypes;
private String vcfPath = null;
private String genomeAssembly;
private String biocurator = EMPTY_STRING;
private String probandId = EMPTY_STRING;
private String phenopacketId = EMPTY_STRING;
private String phenopacketVersion = EMPTY_STRING;
private String isoAge = EMPTY_STRING;
private String sex = EMPTY_STRING;
private final String iso8601 = "^P(?=\\d|T\\d)(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)([DW]))?";
private final Pattern pattern = Pattern.compile(iso8601);
public PgModel(List<PgOntologyClass> phenotypes) {
this.phenotypes = new TreeSet<>(phenotypes);
}
public String getIsoAge() {
return isoAge;
}
public void setIsoAge(String isoAge) {
this.isoAge = isoAge;
}
public boolean hasSexData() {
return ! sex.equals(EMPTY_STRING);
}
public boolean hasAgeData() {
return isoAge != null && ! isoAge.equals(EMPTY_STRING);
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public boolean hasVcf() {
return this.vcfPath != null;
}
public String getHpoVersion() {
return hpoVersion;
}
public String getPhenopacketVersion() {
return phenopacketVersion;
}
public void setPhenopacketVersion(String phenopacketVersion) {
this.phenopacketVersion = phenopacketVersion;
}
public void setHpoVersion(String hpoVersion) {
this.hpoVersion = hpoVersion;
}
public String getEcoVersion() {
return ecoVersion;
}
public void setEcoVersion(String ecoVersion) {
this.ecoVersion = ecoVersion;
}
public List<PgOntologyClass> getPhenotypes() {
ImmutableList.Builder<PgOntologyClass> builder = new ImmutableList.Builder<>();
for (PgOntologyClass pgoc : this.phenotypes) {
builder.add(pgoc);
}
return builder.build();
}
public String getVcfPath() {
return vcfPath;
}
public void setVcfPath(String vcfPath) {
this.vcfPath = vcfPath;
}
public String getGenomeAssembly() {
return genomeAssembly;
}
public void setGenomeAssembly(String genomeAssembly) {
this.genomeAssembly = genomeAssembly;
}
public String getBiocurator() {
return biocurator;
}
public void setBiocurator(String biocurator) {
this.biocurator = biocurator;
}
public String getProbandId() {
return probandId;
}
public void setProbandId(String probandId) {
this.probandId = probandId;
}
public String getPhenopacketId() {
return phenopacketId;
}
public void setPhenopacketId(String phenopacketId) {
this.phenopacketId = phenopacketId;
}
public void qc() throws PGException {
if (this.phenopacketId.equals(EMPTY_STRING) || phenopacketId.isEmpty()) {
throw new PGException("Phenopacket ID is not initialized");
} else {
System.out.println("phenopacket id is "+phenopacketId);
}
if (this.probandId.equals(EMPTY_STRING) || probandId.isEmpty()) {
throw new PGException("Proband ID is not initialized");
}
if (this.isoAge == null || this.isoAge.equals(EMPTY_STRING) || this.isoAge.isEmpty()) {
// OK, not required
} else {
Matcher m = pattern.matcher(isoAge);
if (! m.find()) {
throw new PGException("Invalid age string: " + isoAge);
}
}
if (this.phenotypes.isEmpty()) {
throw new PGException("At least one phenotype term required!");
}
if (biocurator == null || biocurator.equals(EMPTY_STRING) || biocurator.isEmpty()) {
throw new PGException("Biocurator ID not unitialized (use Edit menu)");
}
}
}
| 26.646707
| 95
| 0.634382
|
b4b2950a0f311b17ae0ae0ecf4331b2f0c635d56
| 2,895
|
/**
* Copyright (c) 2008-2010 Andrey Somov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.scanner;
import java.io.IOException;
import java.util.LinkedList;
import junit.framework.TestCase;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.Mark;
import org.yaml.snakeyaml.reader.StreamReader;
import org.yaml.snakeyaml.tokens.BlockEndToken;
import org.yaml.snakeyaml.tokens.BlockMappingStartToken;
import org.yaml.snakeyaml.tokens.KeyToken;
import org.yaml.snakeyaml.tokens.ScalarToken;
import org.yaml.snakeyaml.tokens.StreamEndToken;
import org.yaml.snakeyaml.tokens.StreamStartToken;
import org.yaml.snakeyaml.tokens.Token;
import org.yaml.snakeyaml.tokens.ValueToken;
public class ScannerImplTest extends TestCase {
public void testGetToken() {
String data = "string: abcd";
StreamReader reader = new StreamReader(data);
Scanner scanner = new ScannerImpl(reader);
Mark dummy = new Mark("dummy", 0, 0, 0, "", 0);
LinkedList<Token> etalonTokens = new LinkedList<Token>();
etalonTokens.add(new StreamStartToken(dummy, dummy));
etalonTokens.add(new BlockMappingStartToken(dummy, dummy));
etalonTokens.add(new KeyToken(dummy, dummy));
etalonTokens.add(new ScalarToken("string", true, dummy, dummy, (char) 0));
etalonTokens.add(new ValueToken(dummy, dummy));
etalonTokens.add(new ScalarToken("abcd", true, dummy, dummy, (char) 0));
etalonTokens.add(new BlockEndToken(dummy, dummy));
etalonTokens.add(new StreamEndToken(dummy, dummy));
while (!etalonTokens.isEmpty() && scanner.checkToken(etalonTokens.get(0).getTokenId())) {
assertEquals(etalonTokens.removeFirst(), scanner.getToken());
}
assertFalse("Must contain no more tokens: " + scanner.getToken(), scanner
.checkToken(new Token.ID[0]));
}
public void testWrongTab() throws IOException {
Yaml yaml = new Yaml();
try {
yaml.load("\t data: 1");
fail("TAB cannot start a token.");
} catch (Exception e) {
assertEquals(
"while scanning for the next token; found character \t'\\t' that cannot start any token",
e.getMessage());
}
}
}
| 41.357143
| 110
| 0.671848
|
3f81384f1c03e37296553308ca0dc8af937fa5f9
| 513
|
package interpreter.bytecode;
import interpreter.VirtualMachine;
public class FalseBranchCode extends JumpCode {
private String label;
public void init(String a, String b) {
label = a;
}
public void execute(VirtualMachine vm) {
if (vm.popStack() == 0) {
vm.programCounter(getJump() -1);
}
}
public String toString() {
StringBuffer s = new StringBuffer();
s.append("FALSEBRANCH " + getLabel());
return s.toString();
}
}
| 20.52
| 47
| 0.602339
|
882934bc13614f37e5be601465c841f4d3021457
| 9,993
|
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.oopath;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.assertj.core.api.Assertions;
import org.drools.compiler.oopath.model.Child;
import org.drools.compiler.oopath.model.Man;
import org.drools.compiler.oopath.model.Toy;
import org.drools.compiler.oopath.model.Woman;
import org.junit.Test;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
public class OOPathBindTest {
@Test
public void testBindIntegerFireAllRules() throws InterruptedException, ExecutionException {
testBindInteger(false);
}
@Test(timeout = 1000)
public void testBindIntegerFireUntilHalt() throws InterruptedException, ExecutionException {
testBindInteger(true);
}
public void testBindInteger(final boolean fireUntilHalt) throws InterruptedException, ExecutionException {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Adult( $age: /age )\n" +
"then\n" +
" list.add( $age );\n" +
"end\n";
final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
.build()
.newKieSession();
Future fireUntilHaltFuture = null;
final ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
if (fireUntilHalt) {
fireUntilHaltFuture = executorService.submit((Runnable) ksession::fireUntilHalt);
}
final List<Integer> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Man bob = new Man( "Bob", 40 );
ksession.insert(bob);
if (fireUntilHalt) {
waitForResultAndStopFireUntilHalt(list, ksession, fireUntilHaltFuture);
} else {
ksession.fireAllRules();
Assertions.assertThat(list).hasSize(1);
}
Assertions.assertThat(list).contains(40);
} finally {
executorService.shutdownNow();
ksession.dispose();
}
}
private void waitForResultAndStopFireUntilHalt(final List<Integer> resultList, final KieSession kieSession,
final Future fireUntilHaltFuture) throws InterruptedException, ExecutionException {
try {
while (resultList.size() < 1) {
Thread.sleep(100);
}
} finally {
kieSession.halt();
fireUntilHaltFuture.get();
}
}
@Test
public void testBindString() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Adult( $name: /name )\n" +
"then\n" +
" list.add( $name );\n" +
"end\n";
testScenarioBindString(drl, "Bob", "Alice");
}
@Test
public void testBindStringWithConstraint() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Adult( $name: /name[this == \"Bob\"] )\n" +
"then\n" +
" list.add( $name );\n" +
"end\n";
testScenarioBindString(drl, "Bob");
}
@Test
public void testBindStringWithAlphaConstraint() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Adult( $name: /name[this.length == 3, this != \"George\"] )\n" +
"then\n" +
" list.add( $name );\n" +
"end\n";
testScenarioBindString(drl, "Bob");
}
@Test
public void testBindStringWithBetaConstraint() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" $alice: Adult(name == \"Alice\") \n" +
" Adult( $name: /name[this.length == 3, this != $alice.name] )\n" +
"then\n" +
" list.add( $name );\n" +
"end\n";
testScenarioBindString(drl, "Bob");
}
private void testScenarioBindString(final String drl, final String... expectedResults) {
final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
.build()
.newKieSession();
final List<String> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Man bob = new Man( "Bob", 40 );
final Woman alice = new Woman( "Alice", 38 );
ksession.insert(bob);
ksession.insert(alice);
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder(expectedResults);
}
@Test
public void testBindObjectFromList() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Adult( $child: /children )\n" +
"then\n" +
" list.add( $child.getName() );\n" +
"end\n";
final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
.build()
.newKieSession();
final List<String> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Man bob = new Man( "Bob", 40 );
bob.addChild( new Child( "Charles", 12 ) );
bob.addChild( new Child( "Debbie", 8 ) );
ksession.insert( bob );
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder("Charles", "Debbie");
}
@Test
public void testBindList() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Man( $toys: /wife/children.toys )\n" +
"then\n" +
" list.add( $toys.size() );\n" +
"end\n";
final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
.build()
.newKieSession();
final List<Integer> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Woman alice = new Woman( "Alice", 38 );
final Man bob = new Man( "Bob", 40 );
bob.setWife( alice );
final Child charlie = new Child( "Charles", 12 );
final Child debbie = new Child( "Debbie", 8 );
alice.addChild( charlie );
alice.addChild( debbie );
charlie.addToy( new Toy( "car" ) );
charlie.addToy( new Toy( "ball" ) );
debbie.addToy( new Toy( "doll" ) );
ksession.insert( bob );
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder(1, 2);
}
@Test
public void testBindListWithConstraint() {
final String drl =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Man( $toys: /wife/children[age > 10].toys )\n" +
"then\n" +
" list.add( $toys.size() );\n" +
"end\n";
final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
.build()
.newKieSession();
final List<Integer> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Woman alice = new Woman( "Alice", 38 );
final Man bob = new Man( "Bob", 40 );
bob.setWife( alice );
final Child charlie = new Child( "Charles", 12 );
final Child debbie = new Child( "Debbie", 8 );
alice.addChild( charlie );
alice.addChild( debbie );
charlie.addToy( new Toy( "car" ) );
charlie.addToy( new Toy( "ball" ) );
debbie.addToy( new Toy( "doll" ) );
ksession.insert( bob );
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder(2);
}
}
| 35.18662
| 111
| 0.520064
|
4827b2c4a22f5b463f13f8ff32964580f730db89
| 2,110
|
package com.mina_mikhail.fixed_solutions_task.di.module;
import com.mina_mikhail.fixed_solutions_task.BuildConfig;
import dagger.Module;
import dagger.Provides;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
@Module
public class OkHttpClientModule {
private static final long REQUEST_TIMEOUT = 60;
private static final String API_KEY = "bf6840f7825e215d725f507d56d176c0";
/**
* @return a singleton instance of OkHttpClient
*/
@Provides
@Singleton
public OkHttpClient okHttpClient(Interceptor headerInterceptor,
HttpLoggingInterceptor httpLoggingInterceptor) {
return new OkHttpClient()
.newBuilder()
.readTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.connectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.addNetworkInterceptor(headerInterceptor)
.addNetworkInterceptor(httpLoggingInterceptor)
.retryOnConnectionFailure(false)
.build();
}
/**
* @return a logger instance to log all network requests and its responses
*/
@Provides
public HttpLoggingInterceptor httpLoggingInterceptor() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.level(
BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.BASIC);
return httpLoggingInterceptor;
}
/**
* @return a header Interceptor used to add custom header with all network requests
*/
@Provides
@Singleton
public Interceptor provideInterceptor() {
return chain -> {
Request newRequest = chain.request();
HttpUrl url = newRequest
.url()
.newBuilder()
.addQueryParameter("api_key", API_KEY)
.build();
newRequest = newRequest
.newBuilder()
.url(url)
.build();
return chain.proceed(newRequest);
};
}
}
| 29.305556
| 101
| 0.697156
|
4c512931f85902f7d907a1f2589ff8f97c961100
| 2,084
|
package org.funnycoin.transactions;
import org.funnycoin.wallet.SignageUtils;
import java.security.*;
import java.security.spec.EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import static java.nio.charset.StandardCharsets.UTF_8;
public class Transaction {
String ownerKey;
String outputKey;
float amount;
public String transactionId;
public String signature;
public String token;
public Transaction(String ownerKey, String outputKey, float amount, String signature, String token) {
this.token = token;
this.signature = signature;
this.outputKey = outputKey;
this.ownerKey = ownerKey;
this.amount = amount;
}
public String getOwnerKey() {
return ownerKey;
}
public String getOutputKey() {
return outputKey;
}
public String getToken() {
return token;
}
public float getAmount() {
return amount;
}
public boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA");
ecdsaVerify.initVerify(publicKey);
ecdsaVerify.update(plainText.getBytes(UTF_8));
return ecdsaVerify.verify(Base64.getDecoder().decode(signature));
}
public String getHash() {
return applySha256(ownerKey + outputKey + amount + signature + token);
}
public String applySha256(String input){
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
}
| 27.786667
| 105
| 0.636276
|
d47bcd63d8038d81deb0d0c3486f6a8561ff5b08
| 3,225
|
/*
*
*/
package net.community.chest.spring.test.listener;
import java.io.IOException;
import java.util.Set;
import javax.annotation.Resource;
import net.community.chest.io.EOLStyle;
import org.hibernate.HibernateException;
import org.hibernate.event.DeleteEvent;
import org.hibernate.event.def.DefaultDeleteEventListener;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Required;
/**
* @author Lyor G.
* @since Jul 22, 2010 2:50:31 PM
*/
public class EntitiesDeleteEventListener extends DefaultDeleteEventListener
implements BeanNameAware {
/**
*
*/
private static final long serialVersionUID = -2557864448779173038L;
public EntitiesDeleteEventListener ()
{
super();
}
/**
* The actual {@link Appendable} instance implementing the API
*/
private Appendable _out;
public Appendable getOutput ()
{
return _out;
}
/* NOTE: relies on type-based bean resolution - i.e., there
* is only ONE bean that matches the setter-s argument type
*/
@Resource // see section 3.9.3 tip in Spring documentation
@Required
public void setOutput (Appendable out)
{
_out = out;
}
private String _beanName;
public String getBeanName ()
{
return _beanName;
}
/*
* @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String)
*/
@Override
public void setBeanName (String name)
{
_beanName = name;
}
protected void finalizeDeletion (DeleteEvent event) throws HibernateException
{
final Appendable out=getOutput();
if (null == out)
throw new HibernateException("No " + Appendable.class.getSimpleName() + " instance provided");
final Object o=(null == event) ? null : event.getObject();
if (o != null)
{
try
{
out.append("\t++> ")
.append(getBeanName())
.append("#finalizeDeletion(): ")
.append(o.toString())
.append(EOLStyle.LOCAL.getStyleString())
;
EntitiesContext.marshalObject(o, out)
.append(EOLStyle.LOCAL.getStyleString())
;
}
catch(IOException e)
{
throw new HibernateException("Failed to generated object message", e);
}
}
}
/*
* @see org.hibernate.event.def.DefaultDeleteEventListener#onDelete(org.hibernate.event.DeleteEvent)
*/
@Override
public void onDelete (DeleteEvent event) throws HibernateException
{
super.onDelete(event);
finalizeDeletion(event);
}
/*
* @see org.hibernate.event.def.DefaultDeleteEventListener#onDelete(org.hibernate.event.DeleteEvent, java.util.Set)
*/
@Override
public void onDelete (DeleteEvent event, @SuppressWarnings("rawtypes") Set transientEntities)
throws HibernateException
{
super.onDelete(event, transientEntities);
finalizeDeletion(event);
}
}
| 28.794643
| 119
| 0.611783
|
012f469250bc6278d8af5c06819b4aa616964b89
| 27,193
|
/*
* This file is part of ReplayStudio, licensed under the MIT License (MIT).
* It is partially derived from MCProtocolLib <https://github.com/ReplayMod/MCProtocolLib>, under the same license.
*
* Copyright (c) 2020 johni0702 <https://github.com/johni0702>
* Copyright (c) ReplayStudio contributors (see git)
* Copyright (c) 2013-2019 Steveice10
* Copyright (c) MCProtocolLib contributors (see git at 34352c1, linked above)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.replaymod.replaystudio.protocol.packets;
import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import com.github.steveice10.packetlib.io.stream.StreamNetInput;
import com.github.steveice10.packetlib.io.stream.StreamNetOutput;
import com.replaymod.replaystudio.protocol.Packet;
import com.replaymod.replaystudio.protocol.PacketType;
import com.replaymod.replaystudio.protocol.PacketTypeRegistry;
import com.replaymod.replaystudio.us.myles.ViaVersion.api.Pair;
import com.replaymod.replaystudio.us.myles.ViaVersion.api.protocol.ProtocolVersion;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class PacketChunkData {
private Column column;
private boolean isUnload;
private int unloadX;
private int unloadZ;
public static PacketChunkData read(Packet packet) throws IOException {
PacketChunkData chunkData = new PacketChunkData();
try (Packet.Reader reader = packet.reader()) {
if (packet.atLeast(ProtocolVersion.v1_9)) {
if (packet.getType() == PacketType.UnloadChunk) {
chunkData.readUnload(reader);
} else {
chunkData.readLoad(packet, reader);
}
} else {
chunkData.readLoad(packet, reader);
}
}
return chunkData;
}
public Packet write(PacketTypeRegistry registry) throws IOException {
PacketType packetType;
boolean atLeastV1_9 = ProtocolVersion.getIndex(registry.getVersion()) >= ProtocolVersion.getIndex(ProtocolVersion.v1_9);
if (atLeastV1_9) {
packetType = isUnload ? PacketType.UnloadChunk : PacketType.ChunkData;
} else {
packetType = PacketType.ChunkData;
}
Packet packet = new Packet(registry, packetType);
try (Packet.Writer writer = packet.overwrite()) {
if (atLeastV1_9) {
if (isUnload) {
writeUnload(writer);
} else {
writeLoad(packet, writer);
}
} else {
writeLoad(packet, writer);
}
}
return packet;
}
public static List<Column> readBulk(Packet packet) throws IOException {
try (Packet.Reader in = packet.reader()) {
if (packet.atLeast(ProtocolVersion.v1_8)) {
return readBulkV1_8(packet, in);
} else {
return readBulkV1_7(packet, in);
}
}
}
private static List<Column> readBulkV1_8(Packet packet, Packet.Reader in) throws IOException {
List<Column> result = new ArrayList<>();
boolean skylight = in.readBoolean();
int columns = in.readVarInt();
int[] xs = new int[columns];
int[] zs = new int[columns];
int[] masks = new int[columns];
int[] lengths = new int[columns];
for (int column = 0; column < columns; column++) {
xs[column] = in.readInt();
zs[column] = in.readInt();
masks[column] = in.readUnsignedShort();
int nChunks = Integer.bitCount(masks[column]);
int length = (nChunks * ((4096 * 2) + 2048)) + (skylight ? nChunks * 2048 : 0) + 256;
lengths[column] = length;
}
for (int column = 0; column < columns; column++) {
byte[] buf = new byte[lengths[column]];
in.readBytes(buf);
result.add(readColumn(packet, buf, xs[column], zs[column], true, skylight, masks[column], 0, null, null, null));
}
return result;
}
private static List<Column> readBulkV1_7(Packet packet, Packet.Reader in) throws IOException {
List<Column> result = new ArrayList<>();
// Read packet base data.
short columns = in.readShort();
int deflatedLength = in.readInt();
boolean skylight = in.readBoolean();
byte[] deflatedBytes = in.readBytes(deflatedLength);
// Inflate chunk data.
byte[] inflated = new byte[196864 * columns];
Inflater inflater = new Inflater();
inflater.setInput(deflatedBytes, 0, deflatedLength);
try {
inflater.inflate(inflated);
} catch(DataFormatException e) {
throw new IOException("Bad compressed data format");
} finally {
inflater.end();
}
// Cycle through and read all columns.
int pos = 0;
for(int count = 0; count < columns; count++) {
// Read column-specific data.
int x = in.readInt();
int z = in.readInt();
int chunkMask = in.readShort();
int extendedChunkMask = in.readShort();
// Determine column data length.
int chunks = 0;
int extended = 0;
for(int ch = 0; ch < 16; ch++) {
chunks += chunkMask >> ch & 1;
extended += extendedChunkMask >> ch & 1;
}
int length = (8192 * chunks + 256) + (2048 * extended);
if(skylight) {
length += 2048 * chunks;
}
// Copy column data into a new array.
byte[] buf = new byte[length];
System.arraycopy(inflated, pos, buf, 0, length);
// Read data into chunks and biome data.
result.add(readColumn(packet, buf, x, z, true, skylight, chunkMask, extendedChunkMask, null, null, null));
pos += length;
}
return result;
}
public static PacketChunkData load(Column column) {
PacketChunkData chunkData = new PacketChunkData();
chunkData.column = column;
return chunkData;
}
public static PacketChunkData unload(int chunkX, int chunkZ) {
PacketChunkData chunkData = new PacketChunkData();
chunkData.isUnload = true;
// Post 1.9
chunkData.unloadX = chunkX;
chunkData.unloadZ = chunkZ;
// Pre 1.9
chunkData.column = new Column(chunkX, chunkZ, new Chunk[16], new byte[256], null, null, null);
return chunkData;
}
private PacketChunkData() {
}
public Column getColumn() {
return column;
}
public boolean isUnload() {
return isUnload;
}
public int getUnloadX() {
return unloadX;
}
public int getUnloadZ() {
return unloadZ;
}
private void readUnload(NetInput in) throws IOException {
this.isUnload = true;
this.unloadX = in.readInt();
this.unloadZ = in.readInt();
}
private void writeUnload(NetOutput out) throws IOException {
out.writeInt(this.unloadX);
out.writeInt(this.unloadZ);
}
private void readLoad(Packet packet, Packet.Reader in) throws IOException {
int x = in.readInt();
int z = in.readInt();
boolean fullChunk = in.readBoolean();
int chunkMask = packet.atLeast(ProtocolVersion.v1_9) ? in.readVarInt() : in.readUnsignedShort();
int extendedChunkMask = 0;
if (!packet.atLeast(ProtocolVersion.v1_8)) {
extendedChunkMask = in.readUnsignedShort();
}
CompoundTag heightmaps = null;
if (packet.atLeast(ProtocolVersion.v1_14)) {
heightmaps = in.readNBT();
}
int[] biomes = null;
if (packet.atLeast(ProtocolVersion.v1_15) && fullChunk) {
biomes = in.readInts(1024);
}
byte[] data;
if (packet.atLeast(ProtocolVersion.v1_8)) {
data = in.readBytes(in.readVarInt());
} else {
byte[] deflated = in.readBytes(in.readInt());
// Determine inflated data length.
int len = 12288 * Integer.bitCount(chunkMask);
if (fullChunk) {
len += 256;
}
data = new byte[len];
// Inflate chunk data.
Inflater inflater = new Inflater();
inflater.setInput(deflated, 0, deflated.length);
try {
inflater.inflate(data);
} catch (DataFormatException e) {
throw new IOException("Bad compressed data format");
} finally {
inflater.end();
}
}
CompoundTag[] tileEntities = null;
if (packet.atLeast(ProtocolVersion.v1_9_3)) {
tileEntities = new CompoundTag[in.readVarInt()];
for (int i = 0; i < tileEntities.length; i++) {
tileEntities[i] = in.readNBT();
}
}
this.column = readColumn(packet, data, x, z, fullChunk, false, chunkMask, extendedChunkMask, tileEntities, heightmaps, biomes);
if (packet.atMost(ProtocolVersion.v1_8) && fullChunk && chunkMask == 0) {
isUnload = true;
unloadX = x;
unloadZ = z;
}
}
private void writeLoad(Packet packet, Packet.Writer out) throws IOException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
NetOutput netOut = new StreamNetOutput(byteOut);
Pair<Integer, Integer> masks = writeColumn(packet, netOut, this.column, this.column.isFull());
int mask = masks.getKey();
int extendedMask = masks.getValue();
out.writeInt(this.column.x);
out.writeInt(this.column.z);
out.writeBoolean(this.column.isFull());
if (packet.atLeast(ProtocolVersion.v1_9)) {
out.writeVarInt(mask);
} else {
out.writeShort(mask);
}
if (!packet.atLeast(ProtocolVersion.v1_8)) {
out.writeShort(extendedMask);
}
if (packet.atLeast(ProtocolVersion.v1_14)) {
out.writeNBT(this.column.heightMaps);
}
if (packet.atLeast(ProtocolVersion.v1_15) && this.column.biomes != null) {
out.writeInts(this.column.biomes);
}
int len;
byte[] data;
if (packet.atLeast(ProtocolVersion.v1_8)) {
len = byteOut.size();
data = byteOut.toByteArray();
} else {
Deflater deflater = new Deflater(-1);
len = byteOut.size();
data = new byte[len];
try {
deflater.setInput(byteOut.toByteArray(), 0, len);
deflater.finish();
len = deflater.deflate(data);
} finally {
deflater.end();
}
}
out.writeVarInt(len);
out.writeBytes(data, len);
if (packet.atLeast(ProtocolVersion.v1_9_3)) {
out.writeVarInt(this.column.tileEntities.length);
for (CompoundTag tag : this.column.tileEntities) {
out.writeNBT(tag);
}
}
}
private static Column readColumn(Packet packet, byte[] data, int x, int z, boolean fullChunk, boolean hasSkylight, int mask, int extendedMask, CompoundTag[] tileEntities, CompoundTag heightmaps, int[] biomes) throws IOException {
NetInput in = new StreamNetInput(new ByteArrayInputStream(data));
Throwable ex = null;
Column column = null;
try {
Chunk[] chunks = new Chunk[16];
for(int index = 0; index < chunks.length; index++) {
if((mask & (1 << index)) != 0) {
Chunk chunk = new Chunk();
if (packet.atLeast(ProtocolVersion.v1_9)) {
chunk.blocks = new BlockStorage(packet, in);
if (packet.atMost(ProtocolVersion.v1_13_2)) {
chunk.blockLight = in.readBytes(2048);
chunk.skyLight = hasSkylight ? in.readBytes(2048) : null;
}
} else {
chunk.blocks = new BlockStorage(packet);
}
chunks[index] = chunk;
}
}
if (!packet.atLeast(ProtocolVersion.v1_9)) {
if (packet.atLeast(ProtocolVersion.v1_8)) {
for (Chunk chunk : chunks) {
if (chunk != null) chunk.blocks.storage = new FlexibleStorage(0, in.readLongs(1024));
}
} else {
for (Chunk chunk : chunks) {
if (chunk != null) chunk.blocks.storage = new FlexibleStorage(0, in.readLongs(512));
}
for (Chunk chunk : chunks) {
if (chunk != null) chunk.blocks.metadata = in.readLongs(256);
}
}
for (Chunk chunk : chunks) {
if (chunk != null) chunk.blockLight = in.readBytes(2048);
}
if (hasSkylight) {
for (Chunk chunk : chunks) {
if (chunk != null) chunk.skyLight = in.readBytes(2048);
}
}
// extendedMask should be 0 for 1.8+
for (int index = 0; index < chunks.length; index++) {
if ((extendedMask & (1 << index)) != 0) {
if (chunks[index] == null) {
in.readLongs(256);
} else {
chunks[index].blocks.extended = in.readLongs(256);
}
}
}
}
byte[] biomeData = null;
if (fullChunk && !packet.atLeast(ProtocolVersion.v1_15)) {
biomeData = in.readBytes(packet.atLeast(ProtocolVersion.v1_13) ? 1024 : 256);
}
column = new Column(x, z, chunks, biomeData, tileEntities, heightmaps, biomes);
} catch(Throwable e) {
ex = e;
}
// Unfortunately, this is needed to detect whether the chunks contain skylight or not.
if((in.available() > 0 || ex != null) && !hasSkylight) {
return readColumn(packet, data, x, z, fullChunk, true, mask, extendedMask, tileEntities, heightmaps, biomes);
} else if(ex != null) {
throw new IOException("Failed to read chunk data.", ex);
}
return column;
}
private static Pair<Integer, Integer> writeColumn(Packet packet, NetOutput out, Column column, boolean fullChunk) throws IOException {
int mask = 0;
int extendedMask = 0;
Chunk[] chunks = column.chunks;
for (int index = 0; index < chunks.length; index++) {
Chunk chunk = chunks[index];
if (chunk != null) {
mask |= 1 << index;
if (packet.atLeast(ProtocolVersion.v1_9)) {
chunk.blocks.write(packet, out);
if (packet.atMost(ProtocolVersion.v1_13_2)) {
out.writeBytes(chunk.blockLight);
if (chunk.skyLight != null) {
out.writeBytes(chunk.skyLight);
}
}
}
}
}
if (!packet.atLeast(ProtocolVersion.v1_9)) {
if (packet.atLeast(ProtocolVersion.v1_8)) {
for (Chunk chunk : chunks) {
if (chunk != null) out.writeLongs(chunk.blocks.storage.data);
}
} else {
for (Chunk chunk : chunks) {
if (chunk != null) out.writeLongs(chunk.blocks.storage.data);
}
for (Chunk chunk : chunks) {
if (chunk != null) out.writeLongs(chunk.blocks.metadata);
}
}
for (Chunk chunk : chunks) {
if (chunk != null) out.writeBytes(chunk.blockLight);
}
for (Chunk chunk : chunks) {
if (chunk != null && chunk.skyLight != null) out.writeBytes(chunk.skyLight);
}
// extended should be null for 1.8+
for (int index = 0; index < chunks.length; index++) {
if (chunks[index] != null && chunks[index].blocks.extended != null) {
extendedMask |= 1 << index;
out.writeLongs(chunks[index].blocks.extended);
}
}
}
if (fullChunk && !packet.atLeast(ProtocolVersion.v1_15)) {
out.writeBytes(column.biomeData);
}
return new Pair<>(mask, extendedMask);
}
public static class Column {
public int x;
public int z;
public Chunk[] chunks;
public byte[] biomeData; // pre 1.15
public CompoundTag[] tileEntities;
public CompoundTag heightMaps;
public int[] biomes; // 1.15+
public Column(int x, int z, Chunk[] chunks, byte[] biomeData, CompoundTag[] tileEntities, CompoundTag heightmaps, int[] biomes) {
this.x = x;
this.z = z;
this.chunks = chunks;
this.biomeData = biomeData;
this.tileEntities = tileEntities;
this.heightMaps = heightmaps;
this.biomes = biomes;
}
public boolean isFull() {
return this.biomeData != null || this.biomes != null;
}
}
public static class Chunk {
public BlockStorage blocks;
public byte[] blockLight;
public byte[] skyLight;
public Chunk copy() {
Chunk copy = new Chunk();
copy.blocks = this.blocks != null ? this.blocks.copy() : null;
copy.blockLight = this.blockLight != null ? this.blockLight.clone() : null;
copy.skyLight = this.skyLight != null ? this.skyLight.clone() : null;
return copy;
}
}
public static class BlockStorage {
private int blockCount;
private int bitsPerEntry;
private List<Integer> states;
private FlexibleStorage storage;
private long[] metadata; // 1.7 only
private long[] extended; // 1.7 only
private BlockStorage(BlockStorage from) {
this.blockCount = from.blockCount;
this.bitsPerEntry = from.bitsPerEntry;
if (from.states != null) {
this.states = new ArrayList<>(from.states);
}
if (from.storage != null) {
this.storage = new FlexibleStorage(bitsPerEntry, from.storage.data.clone());
}
if (from.metadata != null) {
this.metadata = from.metadata.clone();
}
if (from.extended != null) {
this.extended = from.extended.clone();
}
}
/**
* 1.9+
*/
public BlockStorage() {
this.blockCount = 0;
this.bitsPerEntry = 4;
this.states = new ArrayList<>();
this.states.add(0);
this.storage = new FlexibleStorage(bitsPerEntry, 4096);
}
// 1.7-1.8
BlockStorage(Packet packet) {
}
// 1.9+
BlockStorage(Packet packet, NetInput in) throws IOException {
if (packet.atLeast(ProtocolVersion.v1_14)) {
this.blockCount = in.readShort();
}
this.bitsPerEntry = in.readUnsignedByte();
this.states = new ArrayList<>();
int stateCount = this.bitsPerEntry > 8 && packet.atLeast(ProtocolVersion.v1_13) ? 0 : in.readVarInt();
for(int i = 0; i < stateCount; ++i) {
this.states.add(in.readVarInt());
}
this.storage = new FlexibleStorage(bitsPerEntry, in.readLongs(in.readVarInt()));
}
// 1.9+
void write(Packet packet, NetOutput out) throws IOException {
if (packet.atLeast(ProtocolVersion.v1_14)) {
out.writeShort(this.blockCount);
}
out.writeByte(this.bitsPerEntry);
if (this.bitsPerEntry <= 8 || !packet.atLeast(ProtocolVersion.v1_13)) {
out.writeVarInt(this.states.size());
for (Integer state : this.states) {
out.writeVarInt(state);
}
}
out.writeVarInt(storage.data.length);
out.writeLongs(storage.data);
}
private static int index(int x, int y, int z) {
return y << 8 | z << 4 | x;
}
/**
* Only 1.9+
*/
public int get(int x, int y, int z) {
int id = this.storage.get(index(x, y, z));
return this.bitsPerEntry <= 8 ? (id >= 0 && id < this.states.size() ? this.states.get(id) : 0) : id;
}
/**
* Only 1.9+
*/
public void set(int x, int y, int z, int state) {
int id = this.bitsPerEntry <= 8 ? this.states.indexOf(state) : state;
if(id == -1) {
this.states.add(state);
if(this.states.size() > 1 << this.bitsPerEntry) {
this.bitsPerEntry++;
List<Integer> oldStates = this.states;
if(this.bitsPerEntry > 8) {
oldStates = new ArrayList<Integer>(this.states);
this.states.clear();
this.bitsPerEntry = 13;
}
FlexibleStorage oldStorage = this.storage;
this.storage = new FlexibleStorage(this.bitsPerEntry, this.storage.getSize());
for(int index = 0; index < this.storage.getSize(); index++) {
this.storage.set(index, this.bitsPerEntry <= 8 ? oldStorage.get(index) : oldStates.get(index));
}
}
id = this.bitsPerEntry <= 8 ? this.states.indexOf(state) : state;
}
int ind = index(x, y, z);
int curr = this.storage.get(ind);
if(state != 0 && curr == 0) {
this.blockCount++;
} else if(state == 0 && curr != 0) {
this.blockCount--;
}
this.storage.set(ind, id);
}
public BlockStorage copy() {
return new BlockStorage(this);
}
}
private static class FlexibleStorage {
private final long[] data;
private final int bitsPerEntry;
private final int size;
private final long maxEntryValue;
public FlexibleStorage(int bitsPerEntry, int size) {
this(bitsPerEntry, new long[roundToNearest(size * bitsPerEntry, 64) / 64]);
}
public FlexibleStorage(int bitsPerEntry, long[] data) {
if(bitsPerEntry < 4) {
bitsPerEntry = 4;
}
this.bitsPerEntry = bitsPerEntry;
this.data = data;
this.size = this.data.length * 64 / this.bitsPerEntry;
this.maxEntryValue = (1L << this.bitsPerEntry) - 1;
}
private static int roundToNearest(int value, int roundTo) {
if(roundTo == 0) {
return 0;
} else if(value == 0) {
return roundTo;
} else {
if(value < 0) {
roundTo *= -1;
}
int remainder = value % roundTo;
return remainder != 0 ? value + roundTo - remainder : value;
}
}
public long[] getData() {
return this.data;
}
public int getBitsPerEntry() {
return this.bitsPerEntry;
}
public int getSize() {
return this.size;
}
public int get(int index) {
if(index < 0 || index > this.size - 1) {
throw new IndexOutOfBoundsException();
}
int bitIndex = index * this.bitsPerEntry;
int startIndex = bitIndex / 64;
int endIndex = ((index + 1) * this.bitsPerEntry - 1) / 64;
int startBitSubIndex = bitIndex % 64;
if(startIndex == endIndex) {
return (int) (this.data[startIndex] >>> startBitSubIndex & this.maxEntryValue);
} else {
int endBitSubIndex = 64 - startBitSubIndex;
return (int) ((this.data[startIndex] >>> startBitSubIndex | this.data[endIndex] << endBitSubIndex) & this.maxEntryValue);
}
}
public void set(int index, int value) {
if(index < 0 || index > this.size - 1) {
throw new IndexOutOfBoundsException();
}
if(value < 0 || value > this.maxEntryValue) {
throw new IllegalArgumentException("Value cannot be outside of accepted range.");
}
int bitIndex = index * this.bitsPerEntry;
int startIndex = bitIndex / 64;
int endIndex = ((index + 1) * this.bitsPerEntry - 1) / 64;
int startBitSubIndex = bitIndex % 64;
this.data[startIndex] = this.data[startIndex] & ~(this.maxEntryValue << startBitSubIndex) | ((long) value & this.maxEntryValue) << startBitSubIndex;
if(startIndex != endIndex) {
int endBitSubIndex = 64 - startBitSubIndex;
this.data[endIndex] = this.data[endIndex] >>> endBitSubIndex << endBitSubIndex | ((long) value & this.maxEntryValue) >> endBitSubIndex;
}
}
}
}
| 37.455923
| 233
| 0.543154
|
ddf5aa793ee766742f2e890e69a5c9df96e62103
| 5,788
|
/**
* Copyright 2015 Daniel Götten
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.maci.photography.eyebeam.library.storage.persistent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import de.maci.photography.eyebeam.library.Photo;
import de.maci.photography.eyebeam.library.metadata.Metadata;
import de.maci.photography.eyebeam.library.storage.InMemoryDataStore;
import de.maci.photography.eyebeam.library.storage.LibraryDataStore;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.compress.utils.Charsets;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.xml.bind.JAXBException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Stream;
import static java.util.Objects.requireNonNull;
/**
* @author Daniel Götten <daniel.goetten@googlemail.com>
* @since 20.10.15
*/
public class FileDataStore implements LibraryDataStore, Persistable {
private static final Type STORABLE_MAP_TYPE = new TypeToken<Map<StorablePhoto, StorableMetadata>>() {}.getType();
private static final String dbFileName = "photos.dat";
private final Logger logger = LoggerFactory.getLogger(getClass());
private final LibraryDataStore delegate;
private final Path dataDirectory;
public FileDataStore(@Nonnull Path dataDirectory) {
requireNonNull(dataDirectory, "Data directory path must not be null!");
this.delegate = InMemoryDataStore.empty();
this.dataDirectory = dataDirectory;
}
@Override
public boolean metadataExists(@Nonnull Photo photo) {
return delegate.metadataExists(photo);
}
@Nonnull
@Override
public Optional<Metadata> metadataOf(@Nonnull Photo photo) {
return delegate.metadataOf(photo);
}
@Override
public Stream<Photo> photos() {
return delegate.photos();
}
@Override
public boolean contains(@Nullable Photo photo) {
return delegate.contains(photo);
}
@Override
public long size() {
return delegate.size();
}
@Override
public boolean remove(@Nullable Photo photo) {
return delegate.remove(photo);
}
@Override
public boolean store(@Nonnull Photo photo) {
return delegate.store(photo);
}
@Override
public void replaceMetadata(@Nonnull Photo photo, @Nonnull Metadata metadata) {
delegate.replaceMetadata(photo, metadata);
}
@Override
public void clear() {
delegate.clear();
}
@Override
public void flush() throws IOException {
try (OutputStream os = createCompressedFileOutputStream()) {
try {
os.write(createGson().toJson(mapDataToStorables()).getBytes(Charsets.UTF_8));
} catch (JAXBException e) {
logger.error("Failed to serialize data.", e);
}
os.flush();
}
}
private Map<StorablePhoto, StorableMetadata> mapDataToStorables() throws JAXBException {
Map<StorablePhoto, StorableMetadata> result = new TreeMap<>();
photos().forEach(photo -> {
Optional<Metadata> metadata = metadataOf(photo);
result.put(StorablePhoto.of(photo), metadata.isPresent() ? StorableMetadata.of(metadata.get()) : null);
});
return result;
}
@Override
public void restore() throws IOException {
try (InputStream is = createCompressedFileInputStream()) {
setDataFromStorables(createGson().fromJson(IOUtils.toString(is, Charsets.UTF_8), STORABLE_MAP_TYPE));
}
}
private void setDataFromStorables(Map<StorablePhoto, StorableMetadata> data) {
clear();
for (Map.Entry<StorablePhoto, StorableMetadata> entry : data.entrySet()) {
Photo photo = entry.getKey().unbox();
store(photo);
Optional<Metadata> metadata = Storables.unboxNullSafe(entry.getValue());
if (metadata.isPresent()) {
replaceMetadata(photo, metadata.get());
}
}
}
private static Gson createGson() {
return new GsonBuilder().enableComplexMapKeySerialization().create();
}
private InputStream createCompressedFileInputStream() {
try {
return new GzipCompressorInputStream(new FileInputStream(dataDirectory.resolve(dbFileName).toFile()));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private OutputStream createCompressedFileOutputStream() {
try {
return new GzipCompressorOutputStream(new FileOutputStream(dataDirectory.resolve(dbFileName).toFile()));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
| 31.977901
| 117
| 0.691776
|
38273c1a6696d0a30e3304b0a53ef5fc0353456e
| 657
|
package picard.util;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class MiscTest {
@Test
public void canWriteToDevNull() throws IOException {
File f = new File("/dev/null");
Assert.assertTrue(f.canRead());
final OutputStream stream = new FileOutputStream(f);
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream));
writer.write("Just a test");
writer.close();
}
}
| 24.333333
| 89
| 0.712329
|
6dedd90bcf09ca212a07da0c601d2cdd8ec00003
| 694
|
package leetCode;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;
public class LeetCode202Test {
@Test
public void isHappy() {
LeetCode202 l = new LeetCode202();
assertTrue(l.isHappy(1));
assertTrue(l.isHappy(7));
assertTrue(l.isHappy(10));
assertTrue(l.isHappy(13));
assertTrue(l.isHappy(19));
assertTrue(l.isHappy(23));
assertTrue(l.isHappy(91));
assertTrue(l.isHappy(94));
assertTrue(l.isHappy(97));
assertFalse(l.isHappy(11));
assertFalse(l.isHappy(12));
assertFalse(l.isHappy(14));
assertFalse(l.isHappy(95));
assertFalse(l.isHappy(96));
}
}
| 23.931034
| 44
| 0.685879
|
caf72def8ff6b9d007344f693cccd3f3404d0962
| 2,041
|
package com.eltechs.axs.xconnectors.epoll.impl;
import com.eltechs.axs.annotations.UsedByNativeCode;
import com.eltechs.axs.helpers.Assert;
import com.eltechs.axs.xconnectors.impl.SocketReader;
import com.eltechs.axs.xconnectors.impl.SocketWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
public class SocketWrapper implements SocketReader, SocketWriter {
@UsedByNativeCode
private final int fd;
private native void closeImpl();
private static native boolean initialiseNativeParts();
private native int readImpl(ByteBuffer byteBuffer, int i, int i2);
private native int writeImpl(ByteBuffer byteBuffer, int i, int i2);
static {
System.loadLibrary("xconnector-fairepoll");
Assert.state(initialiseNativeParts(), "Managed and native parts of EpollProcessorThread do not match one another.");
}
public SocketWrapper(int i) {
this.fd = i;
}
public int getFd() {
return this.fd;
}
public int read(ByteBuffer byteBuffer) throws IOException {
int position = byteBuffer.position();
int readImpl = readImpl(byteBuffer, position, byteBuffer.remaining());
if (readImpl > 0) {
byteBuffer.position(position + readImpl);
return readImpl;
} else if (readImpl >= 0) {
return -1;
} else {
throw new IOException(String.format("recvmsg() has failed; errno = %d\n", new Object[]{Integer.valueOf(-readImpl)}));
}
}
public int write(ByteBuffer byteBuffer) throws IOException {
int position = byteBuffer.position();
int writeImpl = writeImpl(byteBuffer, 0, byteBuffer.remaining());
if (writeImpl > 0) {
byteBuffer.position(position + writeImpl);
}
if (writeImpl >= 0) {
return writeImpl;
}
throw new IOException(String.format("sendmsg() has failed; errno = %d\n", new Object[]{Integer.valueOf(-writeImpl)}));
}
public void close() {
closeImpl();
}
}
| 31.890625
| 129
| 0.656541
|
ce3951bcd8a55101121f3ff5e764fd814f2d2734
| 872
|
package com.yueny.fw.practice.design.single;
import java.lang.reflect.Constructor;
/**
* @Author yueny09 <deep_blue_yang@126.com>
* @Date 2019-11-25 10:36
*/
public class LazyHolderTest {
public static void main(String[] args) {
try{
// 第一次。 因为没有被初始化过,所以允许初始化了
Object object = LazyHolderSingle.getInstance();
System.out.println(object); // sout
Class<?> clazz = LazyHolderSingle.class;
// 通过反射拿到私有的构造方法
Constructor c = clazz.getDeclaredConstructor(null);
// 强制访问, 第二次,不再允许初始化了
c.setAccessible(true);
Object object1 = c.newInstance();
System.out.println(object1);
Object object2 = c.newInstance();
System.out.println(object2);
}catch (Exception e){
e.printStackTrace();
}
}
}
| 26.424242
| 63
| 0.582569
|
226e928e768b7958895e750accda1e5b293c71b4
| 1,097
|
/*
* Java
*
* Copyright 2014 IS2T. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be found at http://www.is2t.com/open-source-bsd-license/.
*/
package com.is2t.transition;
import ej.flow.mwt.MWTFlowManager;
import ej.flow.mwt.TransitionManager;
/**
* Defines a vertical translation transition. Both panels move: the old one goes out, the new one comes in.
*/
public class VerticalTransitionManager extends TranslationTransitionManager implements TransitionManager {
@Override
public int getBound(MWTFlowManager<?, ?> flowManager, boolean forward) {
int desktopHeight = flowManager.getDesktop().getHeight();
return isReversed() ? -desktopHeight : desktopHeight;
}
@Override
public void step(MWTFlowManager<?, ?> flowManager, int value) {
int yOldPanel;
int yNewPanel;
int yPreviousPanel = isOver() ? 0 : value + getShift();
if (isForward()) {
yOldPanel = yPreviousPanel;
yNewPanel = value;
} else {
yOldPanel = value;
yNewPanel = yPreviousPanel;
}
move(flowManager, 0, yOldPanel, 0, yNewPanel, value);
}
}
| 28.128205
| 128
| 0.727438
|
9f1a0aefb61c756ed056b0948a184acc07c05004
| 810
|
package org.sb.libevl;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JsonHelper
{
public static String json(String name, Object val)
{
return quote(name) + " : " + quote(String.valueOf(val));
}
public static String obj(String... pairs)
{
return Arrays.stream(pairs).collect(Collectors.joining(",\n", "{\n", "}\n"));
}
private static String quote(String str)
{
return "\"" + str.replace("\"", "\\\"") + "\"";
}
public static String array(Object... objs)
{
return array(Arrays.stream(objs));
}
public static <T> String array(Stream<T> objs)
{
return objs.map(o -> String.valueOf(o)).collect(Collectors.joining(", ", "[ ", " ]"));
}
}
| 23.823529
| 94
| 0.580247
|
71eb45d0981900b963728b1e74339f700d060f0c
| 589
|
package ru.stqa.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
public class GroupDeletionTests extends TestBase {
@Test
public void testGroupDeletion() {
app.getNavigationHelper().gotoGroupPage();
int before = app.getGroupHelper().getGroupCount();
app.getGroupHelper().selectGroup(before -1);
app.getGroupHelper().deleteSelectedGroups();
app.getGroupHelper().returntoGroupPage();
int after = app.getGroupHelper().getGroupCount();
Assert.assertEquals(after,before -1);
}
}
| 25.608696
| 58
| 0.689304
|
76d4ed89c47aa1cf6954461b471c7d4145597845
| 3,889
|
// Copyright 2009-2022 Information & Computational Sciences, JHI. All rights
// reserved. Use is subject to the accompanying licence terms.
package jhi.curlywhirly.gui;
import scri.commons.gui.*;
import javax.swing.*;
import java.awt.event.*;
public class Actions
{
private final WinMain winMain;
public static AbstractAction fileOpen;
public static AbstractAction fileSample;
public static AbstractAction dataExport;
public static AbstractAction reset;
public static AbstractAction spin;
public static AbstractAction screenshot;
public static AbstractAction captureMovie;
public static AbstractAction showPrefs;
public static AbstractAction showAbout;
public static AbstractAction showHelp;
Actions(WinMain winMain)
{
this.winMain = winMain;
createActions();
// Set initial states for actions that shouldn't be enabled at the start
openedNoData();
}
public static ImageIcon getIcon(String name)
{
ImageIcon icon = Icons.getIcon(name);
return SystemUtils.isMacOS() ? null : icon;
}
private void createActions()
{
fileOpen = new AbstractAction(RB.getString("gui.WinMainToolBar.open"), getIcon("OPEN"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().open();
}
};
fileSample = new AbstractAction("", getIcon("SAMPLE"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().openSample();
}
};
dataExport = new AbstractAction(RB.getString("gui.WinMainToolBar.export"), getIcon("EXPORT"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().exportDataSet();
}
};
reset = new AbstractAction(RB.getString("gui.WinMainToolBar.reset"), getIcon("RESET"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().reset();
}
};
spin = new AbstractAction(RB.getString("gui.WinMainToolBar.spin"), getIcon("SPIN"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().spin();
}
};
screenshot = new AbstractAction(RB.getString("gui.WinMainToolBar.screenshot"), getIcon("SCREENSHOT"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().screenshot();
}
};
captureMovie = new AbstractAction(RB.getString("gui.WinMainToolBar.movie"), getIcon("MOVIE"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().captureMovie();
}
};
showPrefs = new AbstractAction(RB.getString("gui.WinMainToolBar.prefs"), getIcon("PREFS"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().showPrefs();
}
};
showAbout = new AbstractAction("", getIcon("INFO"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().showAbout();
}
};
showHelp = new AbstractAction("", getIcon("HELP"))
{
@Override
public void actionPerformed(ActionEvent e)
{
winMain.getCommands().showHelp();
}
};
}
public static void openedNoData()
{
fileOpen.setEnabled(true);
fileSample.setEnabled(true);
dataExport.setEnabled(false);
reset.setEnabled(false);
spin.setEnabled(false);
screenshot.setEnabled(false);
captureMovie.setEnabled(false);
showPrefs.setEnabled(true);
showAbout.setEnabled(true);
showHelp.setEnabled(true);
}
public static void openedData()
{
fileOpen.setEnabled(true);
fileSample.setEnabled(true);
dataExport.setEnabled(true);
reset.setEnabled(true);
spin.setEnabled(true);
screenshot.setEnabled(true);
captureMovie.setEnabled(true);
showPrefs.setEnabled(true);
showAbout.setEnabled(true);
showHelp.setEnabled(true);
}
}
| 23.858896
| 104
| 0.683209
|
19b32ed1ea03a52877984fe976b77cd15eaf2db9
| 1,306
|
/**
* Copyright (c) 2008 Perforce Software. All rights reserved.
*/
package com.perforce.team.ui.labels;
import org.eclipse.swt.widgets.Table;
import com.perforce.team.core.p4java.IP4Label;
import com.perforce.team.ui.BaseTableSorter;
/**
* @author Kevin Sawicki (ksawicki@perforce.com)
*/
public class LabelSorter extends BaseTableSorter {
/**
* @param table
* @param sortCol
*/
public LabelSorter(Table table, String sortCol) {
super(table, sortCol);
}
/**
* @see com.perforce.team.ui.BaseTableSorter#getField(java.lang.Object,
* java.lang.String)
*/
@Override
protected Object getField(Object field, String column) {
if (field instanceof IP4Label) {
IP4Label label = (IP4Label) field;
if (LabelsViewer.LABEL_COLUMN.equals(column)) {
return label.getName();
} else if (LabelsViewer.DESCRIPTION_COLUMN.equals(column)) {
return label.getDescription();
} else if (LabelsViewer.ACCESS_COLUMN.equals(column)) {
return label.getAccessTime();
} else if (LabelsViewer.OWNER_COLUMN.equals(column)) {
return label.getOwner();
}
}
return super.getField(field, column);
}
}
| 28.391304
| 75
| 0.618683
|
28cf992f2584dbd770bd96bb9e9966f487e06e44
| 306
|
package com.jackie.wowjava.design.pattern.proxy.staticproxy;
/**
* @Author: Jackie
* @Date: 2018/10/10
*/
public class StaticProxyDemo {
public static void main(String[] args) {
User user = new RealUser();
User proxyUser = new ProxyUser(user);
proxyUser.request();
}
}
| 20.4
| 60
| 0.640523
|
71f47e91ee873bd35330c0797a05e96f454deaa9
| 3,900
|
// Copyright 2015-2021 Nkisi 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 nkisi.http;
import nkisi.codec.Debug;
import nkisi.codec.Format;
import nkisi.codec.Output;
import nkisi.codec.Writer;
import nkisi.collections.FingerTrieSeq;
import nkisi.util.Murmur3;
public final class Product extends HttpPart implements Debug {
final String name;
final String version;
final FingerTrieSeq<String> comments;
Product(String name, String version, FingerTrieSeq<String> comments) {
this.name = name;
this.version = version;
this.comments = comments;
}
Product(String name, String version) {
this(name, version, FingerTrieSeq.<String>empty());
}
Product(String name) {
this(name, null, FingerTrieSeq.<String>empty());
}
public String name() {
return this.name;
}
public String version() {
return this.version;
}
public FingerTrieSeq<String> comments() {
return this.comments;
}
public Product comments(FingerTrieSeq<String> comments) {
return new Product(this.name, this.version, comments);
}
public Product comment(String comment) {
return new Product(this.name, this.version, this.comments.appended(comment));
}
@Override
public Writer<?, ?> httpWriter(HttpWriter http) {
return http.productWriter(this.name, this.version, this.comments.iterator());
}
@Override
public Writer<?, ?> writeHttp(Output<?> output, HttpWriter http) {
return http.writeProduct(this.name, this.version, this.comments.iterator(), output);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Product) {
final Product that = (Product) other;
return this.name.equals(that.name)
&& (this.version == null ? that.version == null : this.version.equals(that.version))
&& this.comments.equals(that.comments);
}
return false;
}
private static int hashSeed;
@Override
public int hashCode() {
if (Product.hashSeed == 0) {
Product.hashSeed = Murmur3.seed(Product.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Product.hashSeed,
this.name.hashCode()), Murmur3.hash(this.version)), this.comments.hashCode()));
}
@Override
public <T> Output<T> debug(Output<T> output) {
output = output.write("Product").write('.').write("create").write('(').debug(this.name);
if (this.version != null) {
output = output.write(", ").debug(this.version);
}
output = output.write(')');
for (String comment : this.comments) {
output = output.write('.').write("comment").write('(').debug(comment).write(')');
}
return output;
}
@Override
public String toString() {
return Format.debug(this);
}
public static Product create(String name, String version, FingerTrieSeq<String> comments) {
return new Product(name, version, comments);
}
public static Product create(String name, String version, String... comments) {
return new Product(name, version, FingerTrieSeq.of(comments));
}
public static Product create(String name, String version) {
return new Product(name, version);
}
public static Product create(String name) {
return new Product(name);
}
public static Product parse(String string) {
return Http.standardParser().parseProductString(string);
}
}
| 28.467153
| 94
| 0.688974
|
4d640b7614ed8d01b541533389d50d3966231202
| 252
|
package com.griddynamics.msd365fp.manualreview.queues.model;
import lombok.Data;
@Data
public class NameApiResponse {
private DisposabilityStatus disposable;
public enum DisposabilityStatus {
YES,
NO,
UNKNOWN
}
}
| 16.8
| 60
| 0.698413
|
83b36a9e2eca2781c0f1095010efcae994cd5ac4
| 6,180
|
package com.axway.apim.apiimport.actions.tasks;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import com.axway.apim.api.IAPI;
import com.axway.apim.apiimport.actions.tasks.props.PropertyHandler;
import com.axway.apim.lib.APIPropertyAnnotation;
import com.axway.apim.lib.errorHandling.AppException;
import com.axway.apim.lib.errorHandling.ErrorCode;
import com.axway.apim.lib.utils.rest.PUTRequest;
import com.axway.apim.lib.utils.rest.RestAPICall;
import com.axway.apim.lib.utils.rest.Transaction;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class UpdateAPIProxy extends AbstractAPIMTask implements IResponseParser {
public UpdateAPIProxy(IAPI desiredState, IAPI actualState) {
super(desiredState, actualState);
}
public void execute(List<String> changedProps) throws AppException {
LOG.debug("Updating API-Proxy");
URI uri;
HttpEntity entity;
ObjectMapper objectMapper = new ObjectMapper();
Transaction context = Transaction.getInstance();
try {
JsonNode lastJsonReponse = (JsonNode)context.get("lastResponse");
if(lastJsonReponse==null) { // This class is called as the first, so, first load the API
lastJsonReponse = initActualAPIContext(this.actualState);
}
lastJsonReponse = handledChangedProps(lastJsonReponse, this.desiredState, this.actualState, changedProps);
if(lastJsonReponse == null) return; // No changes required for the API-Proxy
uri = new URIBuilder(cmd.getAPIManagerURL()).setPath(RestAPICall.API_VERSION+"/proxies/"+context.get("virtualAPIId")).build();
entity = new StringEntity(objectMapper.writeValueAsString(lastJsonReponse), StandardCharsets.UTF_8);
RestAPICall updateAPIProxy = new PUTRequest(entity, uri, this);
updateAPIProxy.execute();
} catch (Exception e) {
throw new AppException("Cannot update API-Proxy.", ErrorCode.CANT_UPDATE_API_PROXY, e);
}
}
@Override
public JsonNode parseResponse(HttpResponse httpResponse) throws AppException {
ObjectMapper objectMapper = new ObjectMapper();
String response = null;
try {
response = EntityUtils.toString(httpResponse.getEntity());
if(httpResponse.getStatusLine().getStatusCode()!=200) {
throw new AppException("Error updating API-Proxy. "
+ "[Return-Code: " + httpResponse.getStatusLine().getStatusCode() + ", Response: '"+response+"'", ErrorCode.CANT_UPDATE_API_PROXY);
}
JsonNode jsonNode = objectMapper.readTree(response);
String backendAPIId = jsonNode.findPath("id").asText();
Transaction.getInstance().put("backendAPIId", backendAPIId);
} catch (Exception e) {
try {
Transaction context = Transaction.getInstance();
Object lastRequest = context.get("lastRequest");
LOG.error("Last request: " + EntityUtils.toString(((HttpEntityEnclosingRequestBase)lastRequest).getEntity()));
LOG.error("Unable to parse received response from API-Manager: '" + response + "'");
throw new AppException("Unable to parse received response from API-Manager", ErrorCode.UNXPECTED_ERROR, e);
} catch (Exception e1) {
throw new AppException("Unable to parse response", ErrorCode.UNXPECTED_ERROR, e1);
}
} finally {
try {
((CloseableHttpResponse)httpResponse).close();
} catch (Exception ignore) { }
}
return null;
}
private static JsonNode handledChangedProps(JsonNode lastJsonReponse, IAPI desired, IAPI actual, List<String> changedProps) throws AppException {
Field field = null;
if(changedProps!=null && changedProps.size()!=0) {
boolean propsChangedInProxy = false;
String logMessage = "Updating Frontend-API (Proxy) for the following properties: ";
for(String fieldName : changedProps) {
try {
field = desired.getClass().getSuperclass().getDeclaredField(fieldName);
if (field.isAnnotationPresent(APIPropertyAnnotation.class)) {
LOG.debug("Going to update property: " + field.getName());
APIPropertyAnnotation property = field.getAnnotation(APIPropertyAnnotation.class);
if(void.class != property.propHandler()) { // Properties going this way, must be migrated
Class clazz = property.propHandler();
LOG.trace("Calling property handler: " + clazz.getCanonicalName());
PropertyHandler propHandler = (PropertyHandler) clazz.newInstance();
lastJsonReponse = propHandler.handleProperty(desired, actual, lastJsonReponse);
logMessage = logMessage + field.getName() + " ";
propsChangedInProxy = true;
} else {
try {
String getterMethodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
Method method = desired.getClass().getSuperclass().getMethod(getterMethodName, null);
Object handler = method.invoke(desired, null);
if(handler instanceof PropertyHandler) { // This is NEW/Preferred way
LOG.trace("Calling property handler: " + handler.getClass());
((PropertyHandler)handler).handleProperty(desired, actual, lastJsonReponse);
logMessage = logMessage + field.getName() + " ";
propsChangedInProxy = true;
} else {
LOG.debug("Property: " + field.getName() + " has no handler configured and is not a propertyHandler");
}
} catch (Exception e) {
LOG.debug("Property: " + field.getName() + " has no handler configured and is not a propertyHandler");
}
}
}
} catch (Exception e) {
throw new AppException("Can't handle property: "+field+" to update API-Proxy.", ErrorCode.CANT_UPDATE_API_PROXY, e);
}
}
if(propsChangedInProxy) {
LOG.info(logMessage);
} else {
LOG.debug("API-Proxy requires no updates");
return null;
}
}
return lastJsonReponse;
}
}
| 43.829787
| 146
| 0.728479
|
d1816e5aa26d4659c27da631e5197d7b247f55b3
| 2,051
|
package com.nuclearfurnace.oscilloscope.discovery;
public class ClusterInstance {
public enum Status {
UP, DOWN
}
private final String hostname;
private final int port;
private final String cluster;
private final Status status;
public ClusterInstance(String hostname, int port, String cluster, Status status) {
this.hostname = hostname;
this.port = port;
this.cluster = cluster;
this.status = status;
}
public String getHostname() {
return hostname;
}
public int getPort() {
return port;
}
public String getCluster() {
return cluster;
}
public Status getStatus() {
return status;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getHostname() == null) ? 0 : getHostname().hashCode());
result = prime * result + ((getPort() == 0) ? 0 : String.valueOf(getPort()).hashCode());
result = prime * result + ((getCluster() == null) ? 0 : getCluster().hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClusterInstance other = (ClusterInstance) obj;
if (getHostname() == null) {
if (other.getHostname() != null)
return false;
} else if (!getHostname().equals(other.getHostname()))
return false;
if (getPort() != other.getPort())
return false;
if (getCluster() == null) {
if (other.getCluster() != null)
return false;
} else if (!getCluster().equals(other.getCluster()))
return false;
if (status != other.status)
return false;
return true;
}
}
| 25.6375
| 96
| 0.548025
|
23563421f88e92138c42b7ec245524ebc5b2c7fa
| 331
|
package pa.edu.uip;
public class Vector1 implements Vectores {
@Override
public double[] sumar(int[] vectores) {
return new double[0];
}
@Override
public double[] restar(int[] vectores) {
return new double[0];
}
@Override
public double productoPunto() {
return 0;
}
}
| 17.421053
| 44
| 0.592145
|
8cefcfe345a6d542cab130404ce354e794965960
| 1,172
|
package net.andreho.haxxor.spi.impl.visitors;
import net.andreho.asm.org.objectweb.asm.MethodVisitor;
import net.andreho.haxxor.Hx;
import net.andreho.haxxor.api.HxLazyType;
import net.andreho.haxxor.api.HxMethod;
import net.andreho.haxxor.api.HxType;
import net.andreho.haxxor.cgen.impl.AsmExecutableMethodVisitor;
import java.util.Objects;
/**
* <br/>Created by a.hofmann on 16.03.2016.<br/>
*/
public class HxMethodVisitor
extends AsmExecutableMethodVisitor {
protected final HxType declaringType;
public HxMethodVisitor(final Hx haxxor,
final HxType declaringType,
final HxMethod method) {
this(haxxor, declaringType, method, null);
}
public HxMethodVisitor(final Hx haxxor,
final HxType declaringType,
final HxMethod method,
final MethodVisitor mv) {
super(haxxor, method, mv);
this.declaringType = Objects.requireNonNull(declaringType, "Declaring type can't be null.");
}
@Override
public void visitEnd() {
super.visitEnd();
((HxLazyType) this.declaringType).addMethodInternally(method);
}
}
| 29.3
| 96
| 0.681741
|
3f0fa55138ad3df3bfaef3fe3c41437cc7d9a9a6
| 11,929
|
package lk.dinuka.translate;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.ibm.cloud.sdk.core.security.IamAuthenticator;
import com.ibm.watson.language_translator.v3.LanguageTranslator;
import com.ibm.watson.language_translator.v3.model.IdentifiableLanguages;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lk.dinuka.translate.databases.entities.ForeignLanguage;
import lk.dinuka.translate.databases.repositories.ForeignRepository;
import lk.dinuka.translate.services.MyLanguageAdapter;
import static lk.dinuka.translate.MainActivity.foreignLanguageSubs;
import static lk.dinuka.translate.MainActivity.languageCodes;
public class LanguageSubscription extends AppCompatActivity {
private SlidrInterface slidr;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
private LanguageTranslator translationService; // translation service
public static HashMap<String, Boolean> foreignSubChanges = new HashMap<>(); // holds changes in Foreign subscriptions (languages that have been clicked by the user)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_language_subscription);
slidr = Slidr.attach(this);
// get and display all foreign languages stored in a separate entity of the db (ForeignLanguage)
// with boolean value of subscribed
if (isNetworkAvailable()) {
// Receive all translatable languages using Watson Translator - [Needs to be done only if there was a change/addition in translatable languages]
translationService = initLanguageTranslatorService(); // connect & initiate to the cloud translation service
new LanguageSubscription.ReceiveIdentifiableLanguagesFromAPI().execute();
} else {
displayToast("An internet connection is required to import the languages.");
}
// ---------------------------------
// ---------------------------------
if (savedInstanceState != null) {
ArrayList<String> foreignLangs = new ArrayList<>();
boolean[] foreignSubs = new boolean[foreignSubChanges.size()];
foreignLangs = savedInstanceState.getStringArrayList("lang_changes");
foreignSubs = savedInstanceState.getBooleanArray("subs_changes");
if (foreignLangs != null) {
if (foreignSubs != null) { // avoiding null pointer exceptions
for (int i = 0; i < foreignLangs.size(); i++) {
foreignSubChanges.put(foreignLangs.get(i), foreignSubs[i]);
}
}
}
// System.out.println(foreignSubChanges);
mAdapter.notifyDataSetChanged();
// pass in this arraylist into the constructor of the adapter as well>>>>>???
}
}
@Override
protected void onStart() {
super.onStart();
recyclerView = findViewById(R.id.language_sub_recycler_view);
recyclerView.setHasFixedSize(true); // change in content won't change the layout size of the RecyclerView
// Use a linear layout within the recycler view
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
List<String> allForeignLanguages = new ArrayList<>();
for (Map.Entry<String, String> entry : languageCodes.entrySet()) { //checking for all HashMap entries
allForeignLanguages.add(entry.getKey()); //adding language name into allForeignLanguages arrayList
}
Collections.sort(allForeignLanguages); // sort all languages in alphabetical order (because HashMap has no order)
// specify the adapter (a bridge between a UI component and a data source)
mAdapter = new MyLanguageAdapter(allForeignLanguages); // insert list of languages
recyclerView.setAdapter(mAdapter);
}
public void updateLanguages(View view) { // update database with new subscription status
// save boolean statuses of all changed languages
// take new changes into a HashMap and change only those in the db
// System.out.println(foreignSubChanges); // records the languages that the user has clicked in language adapter
if (foreignSubChanges.size() > 0) {
for (Map.Entry<String, Boolean> entry : foreignLanguageSubs.entrySet()) { //checking for all HashMap entries
if (foreignSubChanges.containsKey(entry.getKey())) { // if a language name is in the changes arrayList, subscription has been changed
final Boolean subscription = foreignSubChanges.get(entry.getKey());
// if (subscription != (entry.getValue())) { // update only if the subscription status is different.
// get this record from the db ---
final ForeignRepository foreignRepository = new ForeignRepository(getApplicationContext());
final LiveData<ForeignLanguage> foreignResultObservable = foreignRepository.getLangByName(entry.getKey());
foreignResultObservable.observe(this, new Observer<ForeignLanguage>() {
@Override
public void onChanged(ForeignLanguage foreignLanguage) {
// System.out.println(foreignLanguage.getLang_id()); // to check whether all the data was received
// System.out.println(foreignLanguage.getLanguage());
// System.out.println(foreignLanguage.getLanguageCode());
// System.out.println(foreignLanguage.getSubscriptionStatus());
// System.out.println(foreignLanguage.getCreatedAt());
// System.out.println(foreignLanguage.getUpdatedAt());
foreignLanguage.setSubscriptionStatus(subscription); // update subscription status
foreignRepository.updateTask(foreignLanguage); // update foreign language subscription status
foreignLanguageSubs.put(foreignLanguage.getLanguage(), subscription); // update HashMap storing subscription statuses
foreignResultObservable.removeObserver(this); // to stop retrieving the result repeatedly after getting it once
}
});
// }
}
}
displayToast("The new subscriptions have been saved.");
} else {
displayToast("No changes have been made to subscriptions.");
}
}
// --------------------------------------------------------------------
public void displayToast(String message) {
Toast toast = Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT);
View view = toast.getView();
//Gets the actual oval background of the Toast then sets the colour filter
view.getBackground().setColorFilter(Color.parseColor("#56ccf2"), PorterDuff.Mode.SRC_IN);
toast.show();
}
private class ReceiveIdentifiableLanguagesFromAPI extends AsyncTask<String, Void, String> { // get all available languages form the API at the beginning
@Override
protected String doInBackground(String... strings) {
IdentifiableLanguages languages = translationService.listIdentifiableLanguages()
.execute().getResult();
// System.out.println(languages); // to check whether all languages were received
for (int i = 0; i < languages.getLanguages().size(); i++) { // get each language code & name separately
String langName = languages.getLanguages().get(i).getName(); // language name
String langCode = languages.getLanguages().get(i).getLanguage(); // language code
// System.out.println(langName+": "+langCode); // to check
if (!languageCodes.containsKey(langName)) {
// add each of these into the entity ForeignLanguage of the database
ForeignRepository foreignRepository = new ForeignRepository(getApplicationContext());
foreignRepository.insertTask(langName, langCode);
languageCodes.put(langName, langCode); // saving lang names and codes in HashMap
foreignLanguageSubs.put(langName, false); // needed only for the first time
}
// extra modification---
// store all the language names/ codes in an arrayList -> check if the language exists in the system db and add the languages
// only if not available in the db
}
return null;
}
}
private LanguageTranslator initLanguageTranslatorService() { // connect & initiate to the cloud translation service
IamAuthenticator authenticator = new IamAuthenticator("2daMreRDE8V5zPRO3enCVHGUCH1sQJs-Kdq8ryPn4-ij");
translationService = new LanguageTranslator("2018-05-01", authenticator);
translationService.setServiceUrl("https://api.us-south.language-translator.watson.cloud.ibm.com/instances/caf1b5bc-ff11-4271-96cf-93372088290d");
return translationService;
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList<String> foreignLangs = new ArrayList<>();
boolean[] foreignSubs = new boolean[foreignSubChanges.size()];
// create 2 ArrayLists with foreignSubChanges HashMap values in same order
for (Map.Entry<String, Boolean> entry : foreignSubChanges.entrySet()) { //checking for all HashMap entries
foreignLangs.add(entry.getKey());
foreignSubs[foreignLangs.indexOf(entry.getKey())] = entry.getValue();
}
outState.putStringArrayList("lang_changes", foreignLangs);
outState.putBooleanArray("subs_changes", foreignSubs);
// System.out.println(foreignSubChanges);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
/*
References:
room adding multiple entities into the db
https://stackoverflow.com/questions/48743239/how-to-add-new-tables-in-library-with-room
https://stackoverflow.com/questions/44322178/room-schema-export-directory-is-not-provided-to-the-annotation-processor-so-we/44424908#44424908
https://cloud.ibm.com/apidocs/language-translator/language-translator
Sliding animations
https://github.com/r0adkll/Slidr
https://codinginflow.com/tutorials/android/slidr
*/
| 43.695971
| 175
| 0.657641
|
9566c09f8392310f858b873868f52a6707564701
| 1,780
|
package models;
import java.util.ArrayList;
import java.util.List;
import com.et.ar.ActiveRecordBase;
import com.et.ar.annotations.Column;
import com.et.ar.annotations.Id;
import com.et.ar.annotations.Table;
import com.et.ar.exception.ActiveRecordException;
@Table(name="intercourseTypes")
public class IntercourseType extends ActiveRecordBase{
@Id private Integer id;
@Column private Integer parentId;
@Column private String code;
@Column private String name;
@Column private String remark;
@Column private Integer sort;
public void beforeDestroy() throws ActiveRecordException{
for(IntercourseType type: findAll(IntercourseType.class, "parentId=?", new Object[]{id})){
type.destroy();
}
}
public String findChildIds() throws Exception{
String s = "";
List<Integer> ids = new ArrayList<Integer>();
ids.add(id);
while(!ids.isEmpty()){
int id = ids.remove(0);
s += id + ",";
for(IntercourseType type: findAll(IntercourseType.class, "parentId=?", new Object[]{id})){
ids.add(type.getId());
}
}
if (!s.equals("")){
s = s.substring(0, s.length() - 1);
}
return s;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
}
| 21.707317
| 93
| 0.692135
|
bbffb3c3da015a71e9930bb8c4898a0695f7ee41
| 12,246
|
package org.knowm.xchange.lgo;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.meta.CurrencyMetaData;
import org.knowm.xchange.dto.meta.ExchangeMetaData;
import org.knowm.xchange.dto.meta.RateLimit;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.lgo.dto.WithCursor;
import org.knowm.xchange.lgo.dto.currency.LgoCurrencies;
import org.knowm.xchange.lgo.dto.currency.LgoCurrency;
import org.knowm.xchange.lgo.dto.key.LgoKey;
import org.knowm.xchange.lgo.dto.marketdata.LgoOrderbook;
import org.knowm.xchange.lgo.dto.order.LgoPlaceLimitOrder;
import org.knowm.xchange.lgo.dto.order.LgoPlaceMarketOrder;
import org.knowm.xchange.lgo.dto.order.LgoPlaceOrder;
import org.knowm.xchange.lgo.dto.order.LgoUnencryptedOrder;
import org.knowm.xchange.lgo.dto.product.LgoLimit;
import org.knowm.xchange.lgo.dto.product.LgoProduct;
import org.knowm.xchange.lgo.dto.product.LgoProductCurrency;
import org.knowm.xchange.lgo.dto.product.LgoProductTotal;
import org.knowm.xchange.lgo.dto.product.LgoProducts;
import org.knowm.xchange.lgo.dto.product.LgoProductsTest;
import org.knowm.xchange.lgo.dto.trade.LgoUserTrade;
import org.knowm.xchange.lgo.dto.trade.LgoUserTrades;
public class LgoAdaptersTest {
private SimpleDateFormat dateFormat;
@Before
public void setUp() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@Test
public void adaptsMetadata() {
ExchangeMetaData metaData = LgoAdapters.adaptMetadata(emptyMeta(), products(), currencies());
assertThat(metaData).isNotNull();
assertThat(metaData.getCurrencies()).hasSize(2).containsKeys(Currency.BTC, Currency.USD);
assertThat(metaData.getCurrencies().get(Currency.BTC))
.isEqualToComparingFieldByField(new CurrencyMetaData(8, null));
assertThat(metaData.getCurrencies().get(Currency.USD))
.isEqualToComparingFieldByField(new CurrencyMetaData(4, null));
assertThat(metaData.getCurrencyPairs()).hasSize(1).containsKeys(CurrencyPair.BTC_USD);
}
@Test
public void adaptsKeysIndex() throws IOException, URISyntaxException {
String indexFile =
new String(
Files.readAllBytes(
Paths.get(getClass().getResource("/org/knowm/xchange/lgo/key/index.txt").toURI())),
StandardCharsets.US_ASCII);
List<LgoKey> keys = LgoAdapters.adaptKeysIndex(indexFile).collect(Collectors.toList());
assertThat(keys).hasSize(2);
assertThat(keys.get(0))
.isEqualToComparingFieldByField(
new LgoKey(
"7b5dd30f-47cc-4c72-938b-199b13bc6f72",
Instant.parse("2019-07-16T09:13:54Z"),
Instant.parse("2019-07-16T10:13:54Z")));
assertThat(keys.get(1))
.isEqualToComparingFieldByField(
new LgoKey(
"684700ae-8bc7-4315-8aec-b69ca778339a",
Instant.parse("2019-07-16T10:03:54Z"),
Instant.parse("2019-07-16T11:03:54Z")));
}
@Test
public void adaptsBidLimitOrder() {
Date now = new Date();
LimitOrder limitOrder =
new LimitOrder(
OrderType.BID,
new BigDecimal("1"),
CurrencyPair.BTC_USD,
null,
now,
new BigDecimal("6000"));
LgoPlaceOrder bidOrder = LgoAdapters.adaptLimitOrder(limitOrder);
assertThat(bidOrder)
.isEqualToComparingFieldByField(
new LgoPlaceLimitOrder(
0, "B", "BTC-USD", new BigDecimal("1"), new BigDecimal("6000"), now.toInstant()));
}
@Test
public void adaptsAskLimitOrder() {
Date timestamp = new Date();
LimitOrder limitOrder =
new LimitOrder(
OrderType.ASK,
new BigDecimal("1"),
CurrencyPair.BTC_USD,
null,
timestamp,
new BigDecimal("6000"));
LgoPlaceOrder bidOrder = LgoAdapters.adaptLimitOrder(limitOrder);
assertThat(bidOrder)
.isEqualToComparingFieldByField(
new LgoPlaceLimitOrder(
0,
"S",
"BTC-USD",
new BigDecimal("1"),
new BigDecimal("6000"),
timestamp.toInstant()));
}
@Test
public void adaptsBidMarketOrder() {
Date now = new Date();
MarketOrder marketOrder =
new MarketOrder(OrderType.BID, new BigDecimal("1"), CurrencyPair.BTC_USD, null, now);
LgoPlaceOrder bidOrder = LgoAdapters.adaptEncryptedMarketOrder(marketOrder);
assertThat(bidOrder)
.isEqualToComparingFieldByField(
new LgoPlaceMarketOrder(0, "B", "BTC-USD", new BigDecimal("1"), now.toInstant()));
}
@Test
public void adaptsAskMarketOrder() {
Date timestamp = new Date();
MarketOrder marketOrder =
new MarketOrder(OrderType.ASK, new BigDecimal("1"), CurrencyPair.BTC_USD, null, timestamp);
LgoPlaceOrder bidOrder = LgoAdapters.adaptEncryptedMarketOrder(marketOrder);
assertThat(bidOrder)
.isEqualToComparingFieldByField(
new LgoPlaceMarketOrder(0, "S", "BTC-USD", new BigDecimal("1"), timestamp.toInstant()));
}
@Test
public void adaptsUnencryptedOrder() {
Date timestamp = new Date();
LimitOrder limitOrder =
new LimitOrder(
OrderType.ASK,
new BigDecimal("1"),
CurrencyPair.BTC_USD,
null,
timestamp,
new BigDecimal("6000"));
LgoUnencryptedOrder lgoUnencryptedOrder = LgoAdapters.adaptUnencryptedLimitOrder(limitOrder);
assertThat(lgoUnencryptedOrder.price).isEqualTo("6000");
assertThat(lgoUnencryptedOrder.quantity).isEqualTo("1");
assertThat(lgoUnencryptedOrder.productId).isEqualTo("BTC-USD");
assertThat(lgoUnencryptedOrder.side).isEqualTo("S");
assertThat(lgoUnencryptedOrder.timestamp).isEqualTo(timestamp.getTime());
assertThat(lgoUnencryptedOrder.type).isEqualTo("L");
}
@Test
public void adaptsTradeType() {
assertThat(LgoAdapters.adaptUserTradeType(lgoTrade("B", "T"))).isEqualTo(OrderType.BID);
assertThat(LgoAdapters.adaptUserTradeType(lgoTrade("B", "M"))).isEqualTo(OrderType.ASK);
assertThat(LgoAdapters.adaptUserTradeType(lgoTrade("S", "T"))).isEqualTo(OrderType.ASK);
assertThat(LgoAdapters.adaptUserTradeType(lgoTrade("S", "M"))).isEqualTo(OrderType.BID);
}
@Test
public void adaptsProductId() {
assertThat(LgoAdapters.adaptProductId("BTC-USD")).isEqualTo(CurrencyPair.BTC_USD);
}
@Test
public void adaptsUserTrades() throws IOException, ParseException {
WithCursor<LgoUserTrades> lastTrades =
readResourceAs(
"/org/knowm/xchange/lgo/trade/example-trades-data.json",
new TypeReference<WithCursor<LgoUserTrades>>() {});
UserTrades userTrades = LgoAdapters.adaptUserTrades(lastTrades);
assertThat(userTrades.getNextPageCursor()).isEqualTo("aGVsbG8=");
assertThat(userTrades.getUserTrades()).hasSize(2);
assertThat(userTrades.getUserTrades().get(0))
.isEqualToComparingFieldByField(
new UserTrade.Builder()
.type(OrderType.ASK)
.originalAmount(new BigDecimal("0.00500000"))
.currencyPair(CurrencyPair.BTC_USD)
.price(new BigDecimal("3854.0000"))
.timestamp(dateFormat.parse("2019-03-05T16:37:17.220Z"))
.id("2")
.orderId("155180383648300001")
.feeAmount(new BigDecimal("0.0096"))
.feeCurrency(Currency.USD)
.build());
assertThat(userTrades.getUserTrades().get(1))
.isEqualToComparingFieldByField(
new UserTrade.Builder()
.type(OrderType.BID)
.originalAmount(new BigDecimal("0.00829566"))
.currencyPair(CurrencyPair.BTC_USD)
.price(new BigDecimal("2410.9000"))
.timestamp(dateFormat.parse("2019-06-20T15:37:21.855Z"))
.id("2477363")
.orderId("156104504046400001")
.feeAmount(new BigDecimal("0.0100"))
.feeCurrency(Currency.USD)
.build());
}
@Test
public void adaptsOrderBook() throws IOException {
LgoOrderbook lgoOrderbook =
readResourceAs(
"/org/knowm/xchange/lgo/marketdata/example-orderbook-data.json",
new TypeReference<LgoOrderbook>() {});
OrderBook orderBook = LgoAdapters.adaptOrderBook(lgoOrderbook, CurrencyPair.BTC_USD);
assertThat(orderBook).isNotNull();
assertThat(orderBook.getAsks()).hasSize(2);
assertThat(orderBook.getBids()).hasSize(2);
assertThat(orderBook.getAsks().get(0))
.isEqualTo(
new LimitOrder(
OrderType.ASK,
new BigDecimal("4.44440000"),
CurrencyPair.BTC_USD,
null,
null,
new BigDecimal("2921.9000")));
assertThat(orderBook.getAsks().get(1))
.isEqualTo(
new LimitOrder(
OrderType.ASK,
new BigDecimal("8.38460000"),
CurrencyPair.BTC_USD,
null,
null,
new BigDecimal("2926.5000")));
assertThat(orderBook.getBids().get(0))
.isEqualTo(
new LimitOrder(
OrderType.BID,
new BigDecimal("8.35030000"),
CurrencyPair.BTC_USD,
null,
null,
new BigDecimal("2896.6000")));
assertThat(orderBook.getBids().get(1))
.isEqualTo(
new LimitOrder(
OrderType.BID,
new BigDecimal("931.83050000"),
CurrencyPair.BTC_USD,
null,
null,
new BigDecimal("1850.0000")));
}
private <T> T readResourceAs(String path, TypeReference<T> type) throws IOException {
InputStream is = LgoProductsTest.class.getResourceAsStream(path);
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(is, type);
}
private LgoUserTrade lgoTrade(String side, String liquidity) {
return new LgoUserTrade(
"1",
"2",
"BTC-USD",
new BigDecimal("1"),
new BigDecimal("1"),
null,
new BigDecimal("1"),
side,
liquidity);
}
private ExchangeMetaData emptyMeta() {
return new ExchangeMetaData(
new HashMap<>(), new HashMap<>(), new RateLimit[0], new RateLimit[0], true);
}
private LgoCurrencies currencies() {
return new LgoCurrencies(
Lists.newArrayList(
new LgoCurrency("Bitcoin", "BTC", 8), new LgoCurrency("Dollar", "USD", 4)));
}
private LgoProducts products() {
return new LgoProducts(
Lists.newArrayList(
new LgoProduct(
"BTC-USD",
new LgoProductTotal(limit("10", "50000000")),
new LgoProductCurrency("BTC", null, limit("0.001", "1000")),
new LgoProductCurrency("USD", new BigDecimal("0.10"), limit("10", "1000000")))));
}
private LgoLimit limit(String min, String max) {
return new LgoLimit(new BigDecimal(min), new BigDecimal(max));
}
}
| 35.912023
| 100
| 0.65352
|
c411fb159631a68eb390d223dde6b9fcc83c2be6
| 725
|
package org.medimob.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Index definition.
*/
@Documented
@Target(value = {ElementType.FIELD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Index {
/**
* Index's name (by default field(s) name is used).
*/
String name() default "";
/**
* The index columns.
*/
String[] columns();
/**
* Set to true if it's a unique index.
*/
boolean unique() default false;
/**
* The index's where condition.
*/
String where() default "";
}
| 19.594595
| 54
| 0.684138
|
00f375511fc3f9602f5b1997652de6af17555cf1
| 3,409
|
package org.mpilone.hazelcastmq.example.jms;
import static java.util.Arrays.asList;
import javax.jms.*;
import org.mpilone.hazelcastmq.core.HazelcastMQ;
import org.mpilone.hazelcastmq.core.HazelcastMQConfig;
import org.mpilone.hazelcastmq.core.HazelcastMQInstance;
import org.mpilone.hazelcastmq.example.Assert;
import org.mpilone.hazelcastmq.jms.HazelcastMQJmsConfig;
import org.mpilone.hazelcastmq.jms.HazelcastMQJmsConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.HazelcastInstance;
/**
* Example of sending a request/reply message to a remote Hazelcast instance
* assuming some other application will be consuming the message and sending the
* reply. This is useful as a simple integration test with existing endpoints.
*/
public class ProducerRequestReplyWithExternalHazelcast {
private final Logger log = LoggerFactory.getLogger(getClass());
public static void main(String[] args) throws Exception {
new ProducerRequestReplyWithExternalHazelcast();
}
/**
* Constructs the example.
*
* @throws JMSException
*/
public ProducerRequestReplyWithExternalHazelcast() throws JMSException {
// Create a Hazelcast instance client.
ClientConfig config = new ClientConfig();
config.setAddresses(asList("127.0.0.1"));
HazelcastInstance hazelcast = HazelcastClient.newHazelcastClient(config);
try {
// HazelcastMQ Instance
HazelcastMQConfig mqConfig = new HazelcastMQConfig();
mqConfig.setHazelcastInstance(hazelcast);
HazelcastMQInstance mqInstance = HazelcastMQ
.newHazelcastMQInstance(mqConfig);
// HazelcastMQJms Instance
HazelcastMQJmsConfig mqJmsConfig = new HazelcastMQJmsConfig();
mqJmsConfig.setHazelcastMQInstance(mqInstance);
HazelcastMQJmsConnectionFactory connectionFactory = new HazelcastMQJmsConnectionFactory(
mqJmsConfig);
// Create a connection, session, and destinations.
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination requestDest = session.createQueue("foo.bar");
Destination replyDest = session.createTemporaryQueue();
// Create a request producer and reply consumer.
MessageProducer producer1 = session.createProducer(requestDest);
MessageConsumer consumer1 = session.createConsumer(replyDest);
// Send the request.
sendRequest(session, producer1, replyDest);
// Process the reply.
handleReply(session, consumer1);
// Cleanup.
session.close();
connection.close();
}
finally {
hazelcast.getLifecycleService().shutdown();
}
}
private void handleReply(Session session, MessageConsumer consumer)
throws JMSException {
TextMessage msg = (TextMessage) consumer.receive(5000);
Assert.notNull(msg, "Did not get required request.");
log.info("Got reply: " + msg.getText());
}
private void sendRequest(Session session, MessageProducer producer,
Destination replyDest) throws JMSException {
TextMessage msg = session.createTextMessage();
msg.setJMSReplyTo(replyDest);
msg.setText("Hello World");
producer.send(msg);
}
}
| 32.778846
| 94
| 0.743326
|
86d71d072c79243553b4228fff2fb4df01402f98
| 5,880
|
/*
* Copyright 2017 Axway Software
*
* 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.axway.ats.uiengine.elements.html.realbrowser;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import com.axway.ats.common.PublicAtsApi;
import com.axway.ats.uiengine.UiDriver;
import com.axway.ats.uiengine.elements.UiElementProperties;
import com.axway.ats.uiengine.elements.html.HtmlElementLocatorBuilder;
import com.axway.ats.uiengine.elements.html.HtmlSingleSelectList;
import com.axway.ats.uiengine.exceptions.SeleniumOperationException;
import com.axway.ats.uiengine.exceptions.VerifyEqualityException;
import com.axway.ats.uiengine.exceptions.VerifyNotEqualityException;
import com.axway.ats.uiengine.utilities.UiEngineUtilities;
import com.axway.ats.uiengine.utilities.realbrowser.html.RealHtmlElementState;
/**
* A Single Selection HTML list
* @see RealHtmlElement
*/
@PublicAtsApi
public class RealHtmlSingleSelectList extends HtmlSingleSelectList {
//private WebDriver webDriver;
public RealHtmlSingleSelectList( UiDriver uiDriver,
UiElementProperties properties ) {
super(uiDriver, properties);
String[] matchingRules = properties.checkTypeAndRules(this.getClass().getSimpleName(),
"RealHtml",
RealHtmlElement.RULES_DUMMY);
// generate the XPath of this HTML element
String xpath = HtmlElementLocatorBuilder.buildXpathLocator(matchingRules,
properties,
new String[]{ "select" },
"select");
properties.addInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR, xpath);
//webDriver = ( WebDriver ) ( ( AbstractRealBrowserDriver ) super.getUiDriver() ).getInternalObject( InternalObjectsEnum.WebDriver.name() );
}
/**
* set the single selection value
*
* @param value the value to select
*/
@Override
@PublicAtsApi
public void setValue(
String value ) {
new RealHtmlElementState(this).waitToBecomeExisting();
try {
WebElement element = RealHtmlElementLocator.findElement(this);
Select select = new Select(element);
select.selectByVisibleText(value);
} catch (NoSuchElementException nsee) {
throw new SeleniumOperationException("Option with label '" + value + "' not found. ("
+ this.toString() + ")");
}
UiEngineUtilities.sleep();
}
/**
* @return the single selection value
*/
@Override
@PublicAtsApi
public String getValue() {
new RealHtmlElementState(this).waitToBecomeExisting();
WebElement element = RealHtmlElementLocator.findElement(this);
Select select = new Select(element);
if (!select.getAllSelectedOptions().isEmpty()) {
return select.getFirstSelectedOption().getText();
}
throw new SeleniumOperationException("There is no selected 'option' in " + this.toString());
}
/**
* @return a list with all possible selection values
*/
@Override
@PublicAtsApi
public List<String> getAllPossibleValues() {
List<String> values = new ArrayList<String>();
new RealHtmlElementState(this).waitToBecomeExisting();
WebElement element = RealHtmlElementLocator.findElement(this);
Select select = new Select(element);
Iterator<WebElement> iterator = select.getOptions().iterator();
if (!select.getAllSelectedOptions().isEmpty()) {
while (iterator.hasNext()) {
values.add(iterator.next().getText());
}
return values;
}
throw new SeleniumOperationException("There is no selectable 'option' in " + this.toString());
}
/**
* Verify the selected value is as specified
*
* @param expectedValue
*/
@Override
@PublicAtsApi
public void verifyValue(
String expectedValue ) {
expectedValue = expectedValue.trim();
String actualText = getValue().trim();
if (!actualText.equals(expectedValue)) {
throw new VerifyEqualityException(expectedValue, actualText, this);
}
}
/**
* Verify the selected value is NOT as specified
*
* @param notExpectedValue
*/
@Override
@PublicAtsApi
public void verifyNotValue(
String notExpectedValue ) {
notExpectedValue = notExpectedValue.trim();
String actualText = getValue().trim();
if (actualText.equals(notExpectedValue)) {
throw new VerifyNotEqualityException(notExpectedValue, this);
}
}
}
| 36.07362
| 149
| 0.616667
|
a487b6cb6478afa67fb1dfdf6911087786794c91
| 5,397
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.siyeh.ig.psiutils;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* @author Bas Leijdekkers
*/
class DefiniteAssignment {
@NotNull
private final PsiVariable variable;
private final Map<PsiElement, Boolean> definitelyAssignedBeforeBreak = new HashMap();
private final Map<PsiElement, Boolean> definitelyUnassignedBeforeBreak = new HashMap();
private final Map<PsiElement, Boolean> definitelyAssignedBeforeContinue = new HashMap();
private final Map<PsiElement, Boolean> definitelyUnassignedBeforeContinue = new HashMap();
private final Map<PsiElement, Boolean> definitelyAssignedBeforeReturn = new HashMap();
private final Map<PsiElement, Boolean> definitelyUnassignedBeforeReturn = new HashMap();
private boolean definitelyAssigned = false;
private boolean definitelyUnassigned = true;
public DefiniteAssignment(@NotNull PsiVariable variable) {
this.variable = variable;
}
public void and(boolean definitelyAssigned, boolean definitelyUnassigned) {
this.definitelyAssigned &= definitelyAssigned;
this.definitelyUnassigned &= definitelyUnassigned;
}
public void assign(@NotNull PsiReferenceExpression expression, boolean definiteAssignment) {
if (definiteAssignment) {
definitelyAssigned = true;
}
else {
valueAccess(expression);
}
definitelyUnassigned = false;
}
public void andDefiniteAssignmentBeforeBreak(PsiStatement statement) {
definitelyAssigned &= removeValue(statement, definitelyAssignedBeforeBreak);
definitelyUnassigned &= removeValue(statement, definitelyUnassignedBeforeBreak);
}
public void andDefiniteAssignmentBeforeContinue(PsiStatement statement) {
definitelyAssigned &= removeValue(statement, definitelyAssignedBeforeContinue);
definitelyUnassigned &= removeValue(statement, definitelyUnassignedBeforeContinue);
}
public void andDefiniteAssignmentBeforeReturn(PsiMethod method) {
definitelyAssigned &= removeValue(method, definitelyAssignedBeforeReturn);
definitelyUnassigned &= removeValue(method, definitelyUnassignedBeforeReturn);
}
private static boolean removeValue(PsiElement statement, Map<PsiElement, Boolean> map) {
final Boolean aBoolean = map.remove(statement);
return aBoolean == null || aBoolean.booleanValue();
}
@NotNull
public final PsiVariable getVariable() {
return variable;
}
public boolean isDefinitelyAssigned() {
return definitelyAssigned;
}
public boolean isDefinitelyUnassigned() {
return definitelyUnassigned;
}
public void set(boolean definitelyAssigned, boolean definitelyUnassigned) {
this.definitelyAssigned = definitelyAssigned;
this.definitelyUnassigned = definitelyUnassigned;
}
public boolean stop() {
return false;
}
public void storeBeforeBreakStatement(PsiBreakStatement breakStatement) {
final PsiStatement statement = breakStatement.findExitedStatement();
if (statement == null) {
return;
}
storeFor(statement, definitelyAssignedBeforeBreak, definitelyUnassignedBeforeBreak);
}
public void storeBeforeContinueStatement(PsiContinueStatement continueStatement) {
final PsiStatement statement = continueStatement.findContinuedStatement();
if (statement == null) {
return;
}
storeFor(statement, definitelyAssignedBeforeContinue, definitelyUnassignedBeforeContinue);
}
public void storeBeforeReturn(PsiReturnStatement returnStatement) {
final PsiMethod method = PsiTreeUtil.getParentOfType(returnStatement, PsiMethod.class, true, PsiClass.class, PsiLambdaExpression.class);
if (method == null || !method.isConstructor()) {
return;
}
storeFor(method, definitelyAssignedBeforeReturn, definitelyUnassignedBeforeReturn);
}
private void storeFor(PsiElement element,
Map<PsiElement, Boolean> definitelyAssignedMap,
Map<PsiElement, Boolean> definitelyUnassignedMap) {
final Boolean existingDa = definitelyAssignedMap.get(element);
final Boolean existingDu = definitelyUnassignedMap.get(element);
definitelyAssignedMap.put(element, Boolean.valueOf(definitelyAssigned && (existingDa == null || existingDa.booleanValue())));
definitelyUnassignedMap.put(element, Boolean.valueOf(definitelyUnassigned && (existingDu == null || existingDu.booleanValue())));
}
@Override @NonNls
public String toString() {
return "DefiniteAssignment{ variable=" + variable + ", definitelyAssigned=" + definitelyAssigned +
", definitelyUnassigned=" + definitelyUnassigned + '}';
}
public void valueAccess(PsiReferenceExpression expression) {}
}
| 37.479167
| 140
| 0.761719
|
2f7645012d41222aa3d6afcf27f203d1ec36e047
| 373
|
package io.spring.dataflow.sample.usagedetailsenderkafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UsageDetailSenderKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(UsageDetailSenderKafkaApplication.class, args);
}
}
| 26.642857
| 71
| 0.844504
|
ce953df926d59d86a57ebea431f4a524fb5841d5
| 2,452
|
package ru.swayfarer.swl2.resource.rlink.types;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import ru.swayfarer.swl2.collections.CollectionsSWL;
import ru.swayfarer.swl2.collections.extended.IExtendedList;
import ru.swayfarer.swl2.functions.GeneratedFunctions.IFunction1;
import ru.swayfarer.swl2.functions.GeneratedFunctions.IFunction3;
import ru.swayfarer.swl2.resource.rlink.RLUtils;
import ru.swayfarer.swl2.resource.rlink.ResourceLink;
/**
* Искалка соседних URL для Zip-архивов
* @author swayfarer
*
*/
public class ZipAdjacentFinder implements IFunction3<URL, IFunction1<ResourceLink, Boolean>, Boolean, IExtendedList<ResourceLink>>{
@Override
public IExtendedList<ResourceLink> apply(URL url, IFunction1<ResourceLink, Boolean> filter, Boolean isDeep)
{
try
{
if (url.getProtocol().equals("jar"))
{
IExtendedList<ResourceLink> ret = CollectionsSWL.createExtendedList();
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = jarURLConnection.getJarFile();
String resourcePath = url.getPath();
int resStartIndex = resourcePath.indexOf("!/") + 2;
if (resStartIndex >= resourcePath.length())
return null;
String filePath = resourcePath.substring(0, resStartIndex);
resourcePath = resourcePath.substring(resStartIndex);
int slashIndex = resourcePath.lastIndexOf("/");
if (slashIndex > 0)
resourcePath = resourcePath.substring(0, slashIndex);
else
return null;
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith(resourcePath))
{
entryName = entryName.replace(resourcePath + "/", "");
slashIndex = entryName.indexOf("/");
if (isDeep || slashIndex < 0)
{
ResourceLink rlink = RLUtils.createLink("u:"+"jar:"+filePath+"!/"+entry.getName());
if (filter.apply(rlink))
{
ret.add(rlink);
}
}
}
}
if (!ret.isEmpty())
return ret;
}
}
catch (Throwable e)
{
System.err.println("Error while getting children for " + url);
e.printStackTrace();
}
return null;
}
}
| 25.541667
| 131
| 0.674959
|
8bccbf29502894ad60cdd434df8e70ef2ca85c93
| 1,674
|
package mage.cards.s;
import mage.MageInt;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.cost.SpellsCostReductionControllerEffect;
import mage.abilities.keyword.EncoreAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.FilterCard;
import mage.filter.predicate.Predicates;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class SpellbindingSoprano extends CardImpl {
private static final FilterCard filter = new FilterCard("Instant and sorcery spells");
static {
filter.add(Predicates.or(
CardType.INSTANT.getPredicate(),
CardType.SORCERY.getPredicate()
));
}
public SpellbindingSoprano(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.BARD);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Whenever Spellbinding Soprano attacks, instant and sorcery spells you cast this turn cost {1} less to cast.
this.addAbility(new AttacksTriggeredAbility(new SpellsCostReductionControllerEffect(filter, 1)));
// Encore {3}{R}
this.addAbility(new EncoreAbility(new ManaCostsImpl<>("{3}{R}")));
}
private SpellbindingSoprano(final SpellbindingSoprano card) {
super(card);
}
@Override
public SpellbindingSoprano copy() {
return new SpellbindingSoprano(this);
}
}
| 30.436364
| 118
| 0.70908
|
fe15ab6c4536788b36ab57c4f37518983982cef6
| 6,981
|
/**
* Copyright 2017-2020 Philip Helger, pgcc@helger.com
*
* Copyright 2011 Google Inc. All Rights Reserved.
* Author: sreeni@google.com (Sreeni Viswanadha)
*
* Copyright (c) 2006, Sun Microsystems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Generated By:JavaCC: Do not edit this line. JJTreeParserVisitor.java Version 4.1d1 */
package com.helger.pgcc.jjtree;
public class DefaultJJTreeVisitor implements JJTreeParserVisitor
{
public Object defaultVisit (final SimpleNode node, final Object data)
{
return node.childrenAccept (this, data);
}
public Object visit (final SimpleNode node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTGrammar node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTCompilationUnit node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTProductions node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTOptions node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTOptionBinding node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTJavacode node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTJavacodeBody node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNF node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFDeclaration node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFNodeScope node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTRE node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTTokenDecls node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTRESpec node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFChoice node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFSequence node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFLookahead node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTExpansionNodeScope node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFAction node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFZeroOrOne node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFTryBlock node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFNonTerminal node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFAssignment node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFOneOrMore node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFZeroOrMore node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTBNFParenthesized node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREStringLiteral node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTRENamed node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREReference node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREEOF node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREChoice node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTRESequence node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREOneOrMore node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREZeroOrMore node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREZeroOrOne node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTRRepetitionRange node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTREParenthesized node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTRECharList node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTCharDescriptor node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTNodeDescriptor node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTNodeDescriptorExpression node, final Object data)
{
return defaultVisit (node, data);
}
public Object visit (final ASTPrimaryExpression node, final Object data)
{
return defaultVisit (node, data);
}
}
| 27.484252
| 88
| 0.7158
|
c8ccca8ecb8fcea7ec840d49e12059142d72b4f5
| 1,057
|
package pinacolada.stances.pcl;
import com.badlogic.gdx.graphics.Color;
import pinacolada.cards.base.PCLAffinity;
import pinacolada.powers.affinity.EndurancePower;
import pinacolada.stances.PCLStance;
import pinacolada.stances.PCLStanceHelper;
import pinacolada.utilities.PCLGameUtilities;
public class EnduranceStance extends PCLStance
{
public static final PCLAffinity AFFINITY = EndurancePower.AFFINITY_TYPE;
public static final String STANCE_ID = CreateFullID(EnduranceStance.class);
public static boolean IsActive()
{
return PCLGameUtilities.InStance(STANCE_ID);
}
public EnduranceStance()
{
super(PCLStanceHelper.EnduranceStance);
}
@Override
protected Color GetParticleColor()
{
return CreateColor(0.8f, 0.9f, 0.5f, 0.6f, 0.2f, 0.3f);
}
@Override
protected Color GetAuraColor()
{
return CreateColor(0.8f, 0.9f, 0.5f, 0.6f, 0.2f, 0.3f);
}
@Override
protected Color GetMainColor()
{
return new Color(1f, 0.6f, 0.2f, 1f);
}
}
| 24.581395
| 79
| 0.701987
|
251689718ad83ac95fded11de882269f4e46d660
| 36
|
//class
final class Comparable<T> {}
| 18
| 28
| 0.722222
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.