hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0aaccf1057eb699afad19c65f56ce042244020 | 1,769 | java | Java | src/main/java/net/tcpshield/tcpshieldapi/response/BackendSetResponse.java | TCPShield/TCPShield-Java-API-Wrapper | c463534bda7602b51264b754017fae813ae9bf18 | [
"MIT"
] | 10 | 2020-12-13T20:26:05.000Z | 2022-03-30T07:54:09.000Z | src/main/java/net/tcpshield/tcpshieldapi/response/BackendSetResponse.java | TCPShield/TCPShield-Java-API-Wrapper | c463534bda7602b51264b754017fae813ae9bf18 | [
"MIT"
] | 1 | 2021-08-11T10:08:33.000Z | 2021-08-11T10:08:33.000Z | src/main/java/net/tcpshield/tcpshieldapi/response/BackendSetResponse.java | TCPShield/TCPShield-Java-API-Wrapper | c463534bda7602b51264b754017fae813ae9bf18 | [
"MIT"
] | 7 | 2021-01-03T00:02:08.000Z | 2022-02-25T18:14:05.000Z | 21.839506 | 65 | 0.565291 | 4,520 | package net.tcpshield.tcpshieldapi.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.util.Arrays;
import java.util.Date;
public class BackendSetResponse {
@JsonProperty("id")
private int id;
@JsonProperty
private String name;
@JsonProperty
private boolean active;
@JsonProperty("updated_at")
private Date updatedAt;
@JsonProperty("created_at")
private Date createdAt;
@JsonProperty("deleted_at")
private Date deletedAt;
@JsonProperty
private String[] backends;
@JsonProperty
private int status;
@JsonProperty
private String message;
public int getID() {
return id;
}
public String getName() {
return name;
}
public boolean isActive() {
return active;
}
public Date getUpdatedAt() {
return updatedAt;
}
public Date getCreatedAt() {
return createdAt;
}
public Date getDeletedAt() {
return deletedAt;
}
public String[] getBackends() {
return backends;
}
public int getStatus() {
return status;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "BackendSetResponse{" +
"id=" + id +
", name='" + name + '\'' +
", active=" + active +
", updatedAt=" + updatedAt +
", createdAt=" + createdAt +
", deletedAt=" + deletedAt +
", backends=" + Arrays.toString(backends) +
", status=" + status +
", message='" + message + '\'' +
'}';
}
}
|
3e0aacd38aa91d0b86231c04353b266de496bf56 | 1,261 | java | Java | library/src/main/java/cn/zibin/luban/Preconditions.java | pinkApple/SuperLuban | 58fd3b13b1411e003bc6ec84c09a3af9fbc2d912 | [
"MIT"
] | null | null | null | library/src/main/java/cn/zibin/luban/Preconditions.java | pinkApple/SuperLuban | 58fd3b13b1411e003bc6ec84c09a3af9fbc2d912 | [
"MIT"
] | null | null | null | library/src/main/java/cn/zibin/luban/Preconditions.java | pinkApple/SuperLuban | 58fd3b13b1411e003bc6ec84c09a3af9fbc2d912 | [
"MIT"
] | null | null | null | 32.333333 | 98 | 0.647898 | 4,521 | package cn.zibin.luban;
import android.support.annotation.Nullable;
public final class Preconditions {
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
}
|
3e0aade5f9d555c3a1bf4e165ce778228da6da32 | 500 | java | Java | src.save/test/java/g1601_1700/s1672_richest_customer_wealth/SolutionTest.java | jscrdev/LeetCode-in-Java | cb2ec473a6e728e0eafb534518fde41910488d85 | [
"MIT"
] | 2 | 2021-12-21T11:30:12.000Z | 2022-03-04T09:30:33.000Z | src.save/test/java/g1601_1700/s1672_richest_customer_wealth/SolutionTest.java | ThanhNIT/LeetCode-in-Java | d1c1eab40db8ef15d69d78dcc55ebb410b4bb5f5 | [
"MIT"
] | null | null | null | src.save/test/java/g1601_1700/s1672_richest_customer_wealth/SolutionTest.java | ThanhNIT/LeetCode-in-Java | d1c1eab40db8ef15d69d78dcc55ebb410b4bb5f5 | [
"MIT"
] | null | null | null | 26.315789 | 100 | 0.662 | 4,522 | package g1601_1700.s1672_richest_customer_wealth;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void maximumWealth() {
assertThat(new Solution().maximumWealth(new int[][] {{1, 2, 3}, {3, 2, 1}}), equalTo(6));
}
@Test
void maximumWealth2() {
assertThat(new Solution().maximumWealth(new int[][] {{1, 5}, {7, 3}, {3, 5}}), equalTo(10));
}
}
|
3e0aae1117c7c144bfbf7fbc0b205984f6d4bf1b | 940 | java | Java | score-http/score-repo-api/src/main/java/org/oagi/score/repo/api/businesscontext/model/DeleteBusinessContextResponse.java | OAGi/Score | 3094555ea14624fe180e921957a418b0bd33147b | [
"MIT"
] | 5 | 2020-02-03T16:02:12.000Z | 2021-07-29T18:18:52.000Z | score-http/score-repo-api/src/main/java/org/oagi/score/repo/api/businesscontext/model/DeleteBusinessContextResponse.java | OAGi/Score | 3094555ea14624fe180e921957a418b0bd33147b | [
"MIT"
] | 566 | 2019-12-09T17:06:44.000Z | 2022-03-28T14:15:48.000Z | score-http/score-repo-api/src/main/java/org/oagi/score/repo/api/businesscontext/model/DeleteBusinessContextResponse.java | OAGi/Score | 3094555ea14624fe180e921957a418b0bd33147b | [
"MIT"
] | 2 | 2019-12-06T19:33:58.000Z | 2020-10-25T07:20:15.000Z | 28.484848 | 80 | 0.715957 | 4,523 | package org.oagi.score.repo.api.businesscontext.model;
import org.oagi.score.repo.api.base.Response;
import java.math.BigInteger;
import java.util.List;
public class DeleteBusinessContextResponse extends Response {
private final List<BigInteger> contextSchemeIdList;
public DeleteBusinessContextResponse(List<BigInteger> contextSchemeIdList) {
this.contextSchemeIdList = contextSchemeIdList;
}
public List<BigInteger> getContextSchemeIdList() {
return contextSchemeIdList;
}
public boolean contains(BigInteger contextSchemeId) {
return this.contextSchemeIdList.contains(contextSchemeId);
}
public boolean containsAll(List<BigInteger> contextSchemeIdList) {
for (BigInteger contextSchemeId : contextSchemeIdList) {
if (!this.contextSchemeIdList.contains(contextSchemeId)) {
return false;
}
}
return true;
}
}
|
3e0aaf3666952688fb9d9ed37b5f4e41f54b2219 | 543 | java | Java | src/main/java/edu/bu/met/cs665/bev/controller/EspressoBeverage.java | ChristopherCanfield/beverage-machine-simulation | 4d0565338d949896c837963d1f34af167243d8ba | [
"Apache-2.0"
] | 1 | 2019-07-26T01:24:54.000Z | 2019-07-26T01:24:54.000Z | src/main/java/edu/bu/met/cs665/bev/controller/EspressoBeverage.java | ChristopherCanfield/beverage-machine-simulation | 4d0565338d949896c837963d1f34af167243d8ba | [
"Apache-2.0"
] | null | null | null | src/main/java/edu/bu/met/cs665/bev/controller/EspressoBeverage.java | ChristopherCanfield/beverage-machine-simulation | 4d0565338d949896c837963d1f34af167243d8ba | [
"Apache-2.0"
] | 1 | 2019-07-29T13:39:39.000Z | 2019-07-29T13:39:39.000Z | 20.884615 | 54 | 0.6814 | 4,524 | package edu.bu.met.cs665.bev.controller;
/**
* Contains information required to brew an espresso.
*
* @author Christopher D. Canfield
*/
public class EspressoBeverage extends CoffeeBeverage {
private final Recipe recipe;
public EspressoBeverage() {
super("Espresso");
Recipe.Builder rb = new Recipe.Builder();
recipe = rb.setTypeIndicator(typeIndicator())
.setSubtypeIndicator("E")
.setTemperatureFahrenheit(210)
.build();
}
@Override
protected Recipe recipe() {
return recipe;
}
}
|
3e0ab03763a8d17a5b281cbd4c18973a205c16d5 | 2,026 | java | Java | src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/entity/animal/horse/AbstractHorseMixin_Carrier_Inventory_API.java | ApolloNetworkMC/Sponge | 4598e2a149e9cd4b80913921e9122ae3306683cb | [
"MIT"
] | 334 | 2015-01-01T05:38:57.000Z | 2022-03-28T06:35:23.000Z | src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/entity/animal/horse/AbstractHorseMixin_Carrier_Inventory_API.java | Kernelcraft-Network/Server | bb18883b03235a2358b985e9907ea8b81b6d8efb | [
"MIT"
] | 2,683 | 2015-04-20T22:01:47.000Z | 2020-11-27T00:29:35.000Z | src/mixins/java/org/spongepowered/common/mixin/inventory/api/world/entity/animal/horse/AbstractHorseMixin_Carrier_Inventory_API.java | Kernelcraft-Network/Server | bb18883b03235a2358b985e9907ea8b81b6d8efb | [
"MIT"
] | 378 | 2015-04-20T07:21:49.000Z | 2020-11-14T17:02:09.000Z | 44.043478 | 83 | 0.781343 | 4,525 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.inventory.api.world.entity.animal.horse;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.animal.horse.AbstractHorse;
import org.spongepowered.api.item.inventory.Carrier;
import org.spongepowered.api.item.inventory.type.CarriedInventory;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.inventory.util.InventoryUtil;
@Mixin(AbstractHorse.class)
public abstract class AbstractHorseMixin_Carrier_Inventory_API implements Carrier {
@Shadow protected SimpleContainer inventory;
@Override
public CarriedInventory<? extends Carrier> inventory() {
return InventoryUtil.carriedWrapperInventory(this.inventory, this);
}
}
|
3e0ab13ffcf14220f5800ea41c35a4b3c4a055e6 | 216 | java | Java | CoreFeatures/UtilityTools/ClassGeneratorJavaCompileAPI/src/main/java/info/smart_tools/smartactors/utility_tool/class_generator_with_java_compile_api/class_builder/package-info.java | asatuchin/smartactors-core | 35d6cae61144305e80b22db04264c14be8405c3f | [
"Apache-2.0"
] | 21 | 2017-09-29T09:45:37.000Z | 2021-09-21T14:12:54.000Z | CoreFeatures/UtilityTools/ClassGeneratorJavaCompileAPI/src/main/java/info/smart_tools/smartactors/utility_tool/class_generator_with_java_compile_api/class_builder/package-info.java | asatuchin/smartactors-core | 35d6cae61144305e80b22db04264c14be8405c3f | [
"Apache-2.0"
] | 310 | 2019-04-11T16:42:11.000Z | 2021-05-23T08:14:16.000Z | CoreFeatures/UtilityTools/ClassGeneratorJavaCompileAPI/src/main/java/info/smart_tools/smartactors/utility_tool/class_generator_with_java_compile_api/class_builder/package-info.java | asatuchin/smartactors-core | 35d6cae61144305e80b22db04264c14be8405c3f | [
"Apache-2.0"
] | 12 | 2017-09-29T09:50:30.000Z | 2022-02-09T08:08:29.000Z | 43.2 | 102 | 0.833333 | 4,526 | /**
* Package contains special class for build class by given string parameters
* and other support classes
*/
package info.smart_tools.smartactors.utility_tool.class_generator_with_java_compile_api.class_builder; |
3e0ab29a358000716974c6a0feafa299c5ed5b20 | 7,105 | java | Java | packager/src/net/rim/tumbler/processbuffer/ProcessBuffer.java | blackberry/WebWorks-TabletOS | 2315d4969358f12724c0997ee06f7ee4102549e6 | [
"Apache-2.0"
] | 4 | 2015-11-05T21:43:42.000Z | 2018-11-22T05:03:33.000Z | packager/src/net/rim/tumbler/processbuffer/ProcessBuffer.java | blackberry-webworks/WebWorks-TabletOS | 1791f8128d586c1f8c7e49e3e02f35c708599b2b | [
"Apache-2.0"
] | 1 | 2016-11-05T14:06:12.000Z | 2016-11-05T14:06:12.000Z | packager/src/net/rim/tumbler/processbuffer/ProcessBuffer.java | blackberry-webworks/WebWorks-TabletOS | 1791f8128d586c1f8c7e49e3e02f35c708599b2b | [
"Apache-2.0"
] | 2 | 2019-02-15T19:08:47.000Z | 2020-07-12T03:26:06.000Z | 34.323671 | 78 | 0.633498 | 4,527 | /*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.rim.tumbler.processbuffer;
/**
* Provides a common base for classes that facilitate the unimpeded execution
* of subprocesses returned from the <code>exec()</code> methods of class
* <code>Runtime</code>.
* <p>
* Process buffer objects can be constructed with the <code>Process</code>
* object returned from a call to <code>Runtime.exec()</code>:
* <pre>
* String cmd = ...;
* Process p = Runtime.getRuntime().exec(cmd);
*
* //
* // Because some native platforms only provide limited buffer size for
* // standard output streams, we promptly read the output streams using
* // a separate thread so that this thread can proceed without blocking.
* // The ProcessBuffer subclasses hide the implementation details.
* //
* ErrorBuffer stderr = new ErrorBuffer(p);
* OutputBuffer stdout = new OutputBuffer(p);
* ExitBuffer exitValue = new ExitBuffer(p);
* </pre>
* The <code>ErrorBuffer</code> uses a separate thread to read from the
* standard error stream of the subprocess, and is made available upon
* reaching the end of the error stream.
* <p>
* The <code>OutputBuffer</code> uses a separate thread to read from the
* standard output stream of the subprocess, and is made available upon
* reaching the end of the output stream.
* <p>
* The <code>ExitBuffer</code> uses a separate thread to wait for completion
* of the subprocess, at which time the buffer is made available containing
* the exit value of the subprocess.
* <p>
* To block until a buffer is available, use the <code>waitFor()</code>
* method. To test (or "poll") whether a buffer is available, use the
* <code>available()</code> method. Details about accessing the actual
* contents of the buffer are specific to the particular subclass.
*/
public abstract class ProcessBuffer {
/**
* The subclass-specific processing performed within this class is
* intended for a separate thread, allowing the calling thread to
* continue without blocking. This private inner class hides the
* implementation of the Runnable interface.
*/
private class FillerThread implements Runnable {
/**
* Performs subclass-specific processing (via <code>fill()</code>)
* and then notifies all threads that the buffer is available so that
* they can unblock and make use of the result. Details about the
* contents of the buffer are specific to the particular subclass.
*/
public void run() {
fill();
synchronized (_flagSync) {
_available = true;
_flagSync.notifyAll();
}
}
}
/**
* Used for synchroniztion with respect to whether or not the buffer
* has been made available. The contents of a buffer are meaningful
* only after the buffer has been made available.
*/
private Object _flagSync;
/**
* Indicates whether the contents of the buffer are available.
* Access is synchronized via '_flagSync'.
*/
private boolean _available;
/**
* Used for synchronizing access to the process.
*/
private Object _processSync;
/**
* The subprocess being buffered. Access is synchronized via
* '_processSync'.
*/
private Process _process;
/**
* An object made available to subclasses for synchronizing access to
* their specific buffers.
*/
private Object _bufferSync;
/**
* Default constructor, scoped to restrict subclasses to within
* this package due to non-trivial thread considerations.
*/
ProcessBuffer() {
_flagSync = new Object();
_processSync = new Object();
_bufferSync = new Object();
}
/**
* Causes the current thread to wait, if necessary, until the contents
* of this buffer are available. This method returns immediately if the
* buffer contents are already available. If the contents are not
* available, the calling thread will be blocked until they become
* available.
*
* @exception java.lang.InterruptedException
* if the current thread is interrupted by another thread
* while it is waiting.
*/
public void waitFor() throws InterruptedException {
//
// "Never invoke the wait method outside a loop"
// Reference: Effective Java, by Joshua Bloch, Item 50.
//
synchronized (_flagSync) {
while (!_available) {
_flagSync.wait();
}
}
}
/**
* Indicates whether the contents of the buffer are available.
*
* @return <code>true</code> if the contents of the buffer are
* available and ready to be accessed, <code>false</code>
* otherwise. For details about accessing the buffer contents,
* refer to subclass documentation.
*/
public boolean available() {
boolean result;
synchronized (_flagSync) {
result = _available;
}
return result;
}
/**
* Begins a separate thread for filling the buffer, and promptly
* returns. Subclasses of this class should call this method from
* their constructors after initializing their own state, if any.
*
* @param process the subprocess being buffered.
*/
final void activate(Process process) {
synchronized (_processSync) {
_process = process;
}
new Thread(new FillerThread()).start();
}
/**
* Returns the subprocess being buffered.
*
* @return the subprocess being buffered.
*/
final Process getProcess() {
Process result;
synchronized (_processSync) {
result = _process;
}
return result;
}
/**
* Performs subclass-specific processing needed to fill the buffer
* prior to being made available.
*/
abstract void fill();
/**
* Returns the object to be used by subclasses for synchronizing access
* to their specific buffers.
*
* @return the object to be used by subclasses for synchronizing access
* to their specific buffers.
*/
final Object getBufferSync() {
return _bufferSync;
}
}
|
3e0ab332966e4565ebd5f302301c2e6799772dc7 | 2,536 | java | Java | app/src/main/java/com/jadebyte/popularmovies/utils/MyGlide.java | wilburt/Popular-Movies | f607ea0798a4e96ce0bf531ce006bb5c56c763a7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/jadebyte/popularmovies/utils/MyGlide.java | wilburt/Popular-Movies | f607ea0798a4e96ce0bf531ce006bb5c56c763a7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/jadebyte/popularmovies/utils/MyGlide.java | wilburt/Popular-Movies | f607ea0798a4e96ce0bf531ce006bb5c56c763a7 | [
"Apache-2.0"
] | null | null | null | 45.285714 | 158 | 0.595426 | 4,528 | package com.jadebyte.popularmovies.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.jadebyte.popularmovies.R;
import java.lang.ref.WeakReference;
public class MyGlide{
public static void load(Context context, ImageView view, String url, final ProgressBar progressBar) {
// Using WeakReferences to avoid leaking Context and View objects
final Context weakCxt = new WeakReference<>(context).get();
final ImageView weakView = new WeakReference<>(view).get();
final ProgressBar weakProg = new WeakReference<>(progressBar).get();
Glide.with(weakCxt)
.load(url)
.asBitmap()
.error(R.drawable.ic_default_movie_poster)
.placeholder(R.drawable.ic_default_movie_poster)
.skipMemoryCache(true) // Just to be on the save path, don't cache images in memory since many images will be loaded in RecyclerView
// This is to avoid the popular plague: OutOfMemoryException. Disk cache should be enough.
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.listener(new RequestListener<String, Bitmap>() {
@Override
public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
if (weakProg != null) {
int space =(int) MyConvert.dpToPx(10, weakCxt);
weakProg.setVisibility(View.GONE);
weakView.setPadding(space, space, space, space);
weakView.setScaleType(ImageView.ScaleType.CENTER);
}
return false;
}
@Override
public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
if (weakProg != null) {
weakProg.setVisibility(View.GONE);
}
return false;
}
})
.into(weakView);
}
}
|
3e0ab38e7e7432d1e8302368372d1e0969dfdf50 | 4,055 | java | Java | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/CreateProcessingJobResult.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/CreateProcessingJobResult.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/CreateProcessingJobResult.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 31.929134 | 152 | 0.643403 | 4,529 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.sagemaker.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/CreateProcessingJob" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateProcessingJobResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of the processing job.
* </p>
*/
private String processingJobArn;
/**
* <p>
* The Amazon Resource Name (ARN) of the processing job.
* </p>
*
* @param processingJobArn
* The Amazon Resource Name (ARN) of the processing job.
*/
public void setProcessingJobArn(String processingJobArn) {
this.processingJobArn = processingJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the processing job.
* </p>
*
* @return The Amazon Resource Name (ARN) of the processing job.
*/
public String getProcessingJobArn() {
return this.processingJobArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the processing job.
* </p>
*
* @param processingJobArn
* The Amazon Resource Name (ARN) of the processing job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateProcessingJobResult withProcessingJobArn(String processingJobArn) {
setProcessingJobArn(processingJobArn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getProcessingJobArn() != null)
sb.append("ProcessingJobArn: ").append(getProcessingJobArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateProcessingJobResult == false)
return false;
CreateProcessingJobResult other = (CreateProcessingJobResult) obj;
if (other.getProcessingJobArn() == null ^ this.getProcessingJobArn() == null)
return false;
if (other.getProcessingJobArn() != null && other.getProcessingJobArn().equals(this.getProcessingJobArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getProcessingJobArn() == null) ? 0 : getProcessingJobArn().hashCode());
return hashCode;
}
@Override
public CreateProcessingJobResult clone() {
try {
return (CreateProcessingJobResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
3e0ab3b4554205add10c980867875f78faef3868 | 378 | java | Java | src/main/java/io/choerodon/notify/infra/mapper/MessageSettingTargetUserMapper.java | readme1988/notify-service | 2aae0de7a04aacf859fbba9b5dc9f447bcdf0d6a | [
"Apache-2.0"
] | null | null | null | src/main/java/io/choerodon/notify/infra/mapper/MessageSettingTargetUserMapper.java | readme1988/notify-service | 2aae0de7a04aacf859fbba9b5dc9f447bcdf0d6a | [
"Apache-2.0"
] | null | null | null | src/main/java/io/choerodon/notify/infra/mapper/MessageSettingTargetUserMapper.java | readme1988/notify-service | 2aae0de7a04aacf859fbba9b5dc9f447bcdf0d6a | [
"Apache-2.0"
] | null | null | null | 25.2 | 85 | 0.81746 | 4,530 | package io.choerodon.notify.infra.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import io.choerodon.mybatis.common.Mapper;
import io.choerodon.notify.infra.dto.TargetUserDTO;
public interface MessageSettingTargetUserMapper extends Mapper<TargetUserDTO> {
List<TargetUserDTO> listByMsgSettingId(@Param("msgSettingId") Long msgSettingId);
}
|
3e0ab4d8d56f0757bd8ca20831b951eb089488c4 | 1,824 | java | Java | videoCore/src/main/java/com/gpufast/recorder/RecorderEngine.java | xiwenhec/videoCore | 40a35fc82d4b9210477e92458a34edf919e95ffc | [
"Apache-2.0"
] | 3 | 2020-06-11T05:36:17.000Z | 2021-04-28T12:40:08.000Z | videoCore/src/main/java/com/gpufast/recorder/RecorderEngine.java | xiwenhec/videoCore | 40a35fc82d4b9210477e92458a34edf919e95ffc | [
"Apache-2.0"
] | null | null | null | videoCore/src/main/java/com/gpufast/recorder/RecorderEngine.java | xiwenhec/videoCore | 40a35fc82d4b9210477e92458a34edf919e95ffc | [
"Apache-2.0"
] | null | null | null | 21.714286 | 89 | 0.599232 | 4,531 | package com.gpufast.recorder;
import android.opengl.EGLContext;
import com.gpufast.recorder.audio.AudioProcessor;
public class RecorderEngine {
private static IRecorder worker;
private static IRecorder create() {
if (worker == null) {
synchronized (RecorderEngine.class) {
if (worker == null) {
worker = new Worker();
}
}
}
return worker;
}
/**
* 设置录制参数
* @param params 参数
*/
public static void setParams(RecordParams params) {
create().setParams(params);
}
/**
* 如果使用openGL传递信息,这需要传递EGLContext
* @param eglContext EGL上下文
*/
public static void setShareContext(EGLContext eglContext) {
create().setShareContext(eglContext);
}
public static void setAudioProcessor(AudioProcessor callback){
create().setAudioProcessor(callback);
}
/***
* 送入视频数据给录音器
* @param textureId 纹理Id
* @param srcTexWidth 纹理的宽度
* @param srcTexHeight 纹理的高度
*/
public static void sendVideoFrame(int textureId, int srcTexWidth, int srcTexHeight) {
create().sendVideoFrame(textureId,srcTexWidth,srcTexHeight);
}
/**
* 是否正在录制
* @return
*/
public static boolean isRecording() {
return create().isRecording();
}
public static void startRecorder() {
create().startRecorder();
}
public static void jointVideo() {
create().jointVideo();
}
public static void stopRecorder() {
create().stopRecorder();
}
public void setRecorderListener(IRecorder.RecordListener listener) {
create().setRecordListener(listener);
}
public static void release() {
create().release();
worker = null;
}
}
|
3e0ab4ede77374dff7b29590fc3ca8dfde9e166f | 3,830 | java | Java | src/test/java/org/assertj/core/internal/characters/Characters_assertGreaterThan_Test.java | yurloc/assertj-core | 50e64e7634433b57f3095e8ee455830e724cf870 | [
"Apache-2.0"
] | 1 | 2019-04-22T08:49:25.000Z | 2019-04-22T08:49:25.000Z | src/test/java/org/assertj/core/internal/characters/Characters_assertGreaterThan_Test.java | yurloc/assertj-core | 50e64e7634433b57f3095e8ee455830e724cf870 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/assertj/core/internal/characters/Characters_assertGreaterThan_Test.java | yurloc/assertj-core | 50e64e7634433b57f3095e8ee455830e724cf870 | [
"Apache-2.0"
] | null | null | null | 35.462963 | 129 | 0.702872 | 4,532 | /*
* Created on Oct 24, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Copyright @2010-2011 the original author or authors.
*/
package org.assertj.core.internal.characters;
import static org.assertj.core.error.ShouldBeGreater.shouldBeGreater;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Characters;
import org.assertj.core.internal.CharactersBaseTest;
import org.junit.Test;
/**
* Tests for <code>{@link Characters#assertGreaterThan(AssertionInfo, Character, char)}</code>.
*
* @author Alex Ruiz
* @author Joel Costigliola
*/
public class Characters_assertGreaterThan_Test extends CharactersBaseTest {
@Test
public void should_fail_if_actual_is_null() {
thrown.expectAssertionError(actualIsNull());
characters.assertGreaterThan(someInfo(), null, 'a');
}
@Test
public void should_pass_if_actual_is_greater_than_other() {
characters.assertGreaterThan(someInfo(), 'b', 'a');
}
@Test
public void should_fail_if_actual_is_equal_to_other() {
AssertionInfo someInfo = someInfo();
try {
characters.assertGreaterThan(someInfo, 'b', 'b');
} catch (AssertionError e) {
verify(failures).failure(someInfo, shouldBeGreater('b', 'b'));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_less_than_other() {
AssertionInfo info = someInfo();
try {
characters.assertGreaterThan(info, 'a', 'b');
} catch (AssertionError e) {
verify(failures).failure(info, shouldBeGreater('a', 'b'));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
// ------------------------------------------------------------------------------------------------------------------
// tests using a custom comparison strategy
// ------------------------------------------------------------------------------------------------------------------
@Test
public void should_pass_if_actual_is_greater_than_other_according_to_custom_comparison_strategy() {
charactersWithCaseInsensitiveComparisonStrategy.assertGreaterThan(someInfo(), 'B', 'a');
}
@Test
public void should_fail_if_actual_is_equal_to_other_according_to_custom_comparison_strategy() {
AssertionInfo someInfo = someInfo();
try {
charactersWithCaseInsensitiveComparisonStrategy.assertGreaterThan(someInfo, 'B', 'b');
} catch (AssertionError e) {
verify(failures).failure(someInfo, shouldBeGreater('B', 'b', caseInsensitiveComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_less_than_other_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
try {
charactersWithCaseInsensitiveComparisonStrategy.assertGreaterThan(info, 'A', 'b');
} catch (AssertionError e) {
verify(failures).failure(info, shouldBeGreater('A', 'b', caseInsensitiveComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
}
|
3e0ab52a3c9202284b6f7c3fa38eab7bf9aa0480 | 3,972 | java | Java | samples/src/main/java/com/hp/ov/sdk/rest/client/facilities/RackClientSample.java | HewlettPackard/oneview-sdk-java | 6b53b1f30070ade8ae479fe709da992e8f703d52 | [
"Apache-2.0"
] | 18 | 2015-11-18T12:21:50.000Z | 2022-02-21T09:17:46.000Z | samples/src/main/java/com/hp/ov/sdk/rest/client/facilities/RackClientSample.java | HewlettPackard/oneview-sdk-java | 6b53b1f30070ade8ae479fe709da992e8f703d52 | [
"Apache-2.0"
] | 26 | 2016-01-05T18:36:38.000Z | 2022-02-07T11:37:13.000Z | samples/src/main/java/com/hp/ov/sdk/rest/client/facilities/RackClientSample.java | HewlettPackard/oneview-sdk-java | 6b53b1f30070ade8ae479fe709da992e8f703d52 | [
"Apache-2.0"
] | 9 | 2015-11-05T17:16:17.000Z | 2017-06-21T22:33:59.000Z | 32.292683 | 119 | 0.676737 | 4,533 | /*
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* 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.hp.ov.sdk.rest.client.facilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hp.ov.sdk.OneViewClientSample;
import com.hp.ov.sdk.dto.ResourceCollection;
import com.hp.ov.sdk.dto.TaskResource;
import com.hp.ov.sdk.dto.rack.Rack;
import com.hp.ov.sdk.dto.rack.TopologyInformation;
import com.hp.ov.sdk.rest.client.OneViewClient;
import com.hp.ov.sdk.util.JsonPrettyPrinter;
public class RackClientSample {
private static final Logger LOGGER = LoggerFactory.getLogger(RackClientSample.class);
// These are variables to be defined by user
// ================================
private static final String RACK_RESOURCE_ID = "d1778269-9efe-4a5b-be70-c9f556a47685";
private static final String RACK_NAME = "Sample Rack";
// ================================
private final RackClient rackClient;
public RackClientSample() {
OneViewClient oneViewClient = new OneViewClientSample().getOneViewClient();
this.rackClient = oneViewClient.rack();
}
private void getRackById() {
Rack rack = this.rackClient.getById(RACK_RESOURCE_ID);
LOGGER.info("Rack object returned to client : " + rack.toJsonString());
}
private void getAllRacks() {
ResourceCollection<Rack> racks = this.rackClient.getAll();
LOGGER.info("Racks returned to client : " + racks.toJsonString());
}
private void getRackByName() {
Rack rack = this.rackClient.getByName(RACK_NAME).get(0);
LOGGER.info("Rack object returned to client : " + rack.toJsonString());
}
private void addRack() {
Rack rack = new Rack();
rack.setName(RACK_NAME);
Rack addedRack = this.rackClient.add(rack);
LOGGER.info("Rack object returned to client : " + addedRack.toJsonString());
}
private void updateRack() {
Rack rack = this.rackClient.getByName(RACK_NAME).get(0);
String resourceId = rack.getResourceId();
rack.setThermalLimit(Integer.valueOf(1000));
Rack updatedRack = this.rackClient.update(resourceId, rack);
LOGGER.info("Rack object returned to client : " + updatedRack.toJsonString());
}
private void removeRack() {
Rack rack = this.rackClient.getByName(RACK_NAME).get(0);
String response = this.rackClient.remove(rack.getResourceId());
LOGGER.info("Response returned to client : " + response);
}
private void removeRackByFilter() {
String filter = "'name' = '" + RACK_NAME + "'";
TaskResource task = this.rackClient.removeByFilter(filter);
LOGGER.info("Task object returned to client : " + task.toJsonString());
}
private void getDeviceTopology() {
TopologyInformation topologyInformation = this.rackClient.getDeviceTopology(RACK_RESOURCE_ID);
LOGGER.info("TopologyInformation object returned to client : " + JsonPrettyPrinter.print(topologyInformation));
}
public static void main(String[] args) {
RackClientSample sample = new RackClientSample();
sample.getRackById();
sample.getAllRacks();
sample.addRack();
sample.updateRack();
sample.getRackByName();
sample.getDeviceTopology();
sample.removeRack();
sample.addRack();
sample.removeRackByFilter();
}
}
|
3e0ab68f23a98fdc5eeb9a2f56a41ab1809e4b81 | 1,634 | java | Java | mtools/src/main/java/com/mtools/core/plugin/task/ComTaskPlugin.java | zhanggh/mtools | 373f8724ec68e4846fb3a88291df92ddd6ecf39b | [
"Apache-2.0"
] | 9 | 2015-01-20T09:08:02.000Z | 2016-06-23T13:07:27.000Z | mtools/src/main/java/com/mtools/core/plugin/task/ComTaskPlugin.java | zhanggh/mtools | 373f8724ec68e4846fb3a88291df92ddd6ecf39b | [
"Apache-2.0"
] | 7 | 2020-06-30T23:12:00.000Z | 2021-08-25T15:19:27.000Z | mtools/src/main/java/com/mtools/core/plugin/task/ComTaskPlugin.java | zhanggh/mtools | 373f8724ec68e4846fb3a88291df92ddd6ecf39b | [
"Apache-2.0"
] | 11 | 2015-01-20T09:04:42.000Z | 2021-07-30T23:01:56.000Z | 28.172414 | 78 | 0.712362 | 4,534 | /**
* 通联支付-研发中心
* @author zhanggh
* 2014-6-10
* version 1.0
* 说明:
*/
package com.mtools.core.plugin.task;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.mtools.core.plugin.BasePlugin;
import com.mtools.core.plugin.constant.CoreConstans;
import com.mtools.core.plugin.helper.SpringUtil;
import com.mtools.core.plugin.notify.SystemRunningNotify;
/**
* 功能:定时任务
* @date 2014-6-10
*/
@Component("comTask")
public class ComTaskPlugin extends BasePlugin{
@Resource(name="sysRunningNotify")
SystemRunningNotify notify;
// @Scheduled(cron="0 0 9 * * ?")
// @Scheduled(fixedDelay=16000)
public void singing(){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
log.info("定时任务:"+sdf.format(date));
}
// @Scheduled(cron="0 0 1 * * ?")
// @Scheduled(fixedDelay=16000)
public void doSomething(){
log.info("定时任务:正在执行某些业务");
}
// @Scheduled(cron="0 0 0 * * ?")
public void perDayMonitor(){
log.info("系统每日正常运行通知!");
// notify.setSubject(SpringUtil.getCxt().getApplicationName()+"系统每日正常运行通知!");
// notify.setContext(SpringUtil.getCxt().getApplicationName()+"系统每日正常运行通知!");
// notify.setMailType(CoreConstans.EXCEPTON_01);//
// notify.getFileList().add("H:/Repositories/通联代码/aiposp/mtools/readme.txt");
// notify.getFileList().add("H:/Repositories/通联代码/aiposp/mtools/heloo.txt");
// executor.execute(notify);
}
}
|
3e0ab720895d039f49c75cdc63a6a4cdad7640c0 | 3,229 | java | Java | src/main/java/com/adenki/smpp/message/param/ParamDescriptor.java | oranoceallaigh/smppapi | 3d72641b2fe782a0ecf365868c1b473897237f42 | [
"BSD-3-Clause"
] | 8 | 2015-07-17T11:14:50.000Z | 2020-05-06T12:05:57.000Z | src/main/java/com/adenki/smpp/message/param/ParamDescriptor.java | oranoceallaigh/smppapi | 3d72641b2fe782a0ecf365868c1b473897237f42 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/adenki/smpp/message/param/ParamDescriptor.java | oranoceallaigh/smppapi | 3d72641b2fe782a0ecf365868c1b473897237f42 | [
"BSD-3-Clause"
] | 8 | 2015-08-07T07:15:10.000Z | 2020-05-22T20:46:09.000Z | 45.478873 | 80 | 0.713224 | 4,535 | package com.adenki.smpp.message.param;
import java.io.IOException;
import java.io.Serializable;
import com.adenki.smpp.util.PacketDecoder;
import com.adenki.smpp.util.PacketEncoder;
/**
* Parameter descriptor. The parameter descriptor interface provides a way
* for SMPP types to be read from byte arrays and written to output streams.
* Descriptors are used for both mandatory and optional parameters.
* @version $Id$
*/
public interface ParamDescriptor extends Serializable {
/**
* Get the index of another numerical mandatory parameter which specifies
* the length of the parameter this descriptor represents. For example,
* in a submit_sm packet, the length of the short_message parameter is
* specified by the sm_length parameter, a 1-byte integer immediately
* preceding short_message in the mandatory parameter section of the packet.
* Therefore, the parameter descriptor that will be used to decode the
* short_message would return the index of the sm_length parameter in the
* body. This specified length can then be used to decode the correct
* number of bytes for the short message.
* <p>
* As another example, take the submit_multi packet. It has a mandatory
* parameter called dest_address(es) which specify all the destinations
* the message should be submitted to. The number of destinations in the
* destination table is specified by the number_of_dests mandatory
* parameter. In this case, the descriptor used to read the dest_addresses
* would return the index of number_of_dests from this method.
* </p>
* @return The index in the mandatory parameters of where to find the length
* specifier for this descriptor. If this descriptor does not need or
* support a length specifier, <code>-1</code> must be returned.
*/
int getLengthSpecifier();
/**
* Get the encoded byte-size of <code>obj</code>.
* @param obj The object to calculate the encoded size for.
* @return The number of bytes the specified object would be encoded
* to via the {@link #writeObject(Object, OutputStream)} method.
*/
int sizeOf(Object obj);
/**
* Write the specified object to an output stream.
* @param obj The object to encode.
* @param out The output stream to write the object to.
* @throws IOException If there was an error writing to the stream.
*/
void writeObject(Object obj, PacketEncoder encoder) throws IOException;
/**
* Read an object from a byte array.
* @param data The byte data to read (or decode) an object from.
* @param position The position to begin parsing from. This position will
* be updated upon return to point to the first byte after the decoded
* object in the byte array.
* @param length The number of bytes to use in reading the object. If the
* length is unknown and intrinsic to the type being decoded (such as
* a C-String, which is terminated by a nul-byte), then <code>-1</code>
* may be supplied.
* @return The decoded object.
*/
// TODO this should throw something - a runtime exception
Object readObject(PacketDecoder decoder, int length);
}
|
3e0ab7542d588f3b98429eaa6de5576bbc3d8d36 | 573 | java | Java | FileInputStream.java | tonymongare/Java-Practising-Guide | 0b7221e023908a27e9e372bae84d6bf340269d7a | [
"MIT"
] | null | null | null | FileInputStream.java | tonymongare/Java-Practising-Guide | 0b7221e023908a27e9e372bae84d6bf340269d7a | [
"MIT"
] | null | null | null | FileInputStream.java | tonymongare/Java-Practising-Guide | 0b7221e023908a27e9e372bae84d6bf340269d7a | [
"MIT"
] | null | null | null | 21.222222 | 69 | 0.408377 | 4,536 | import java.io.FileInputStream;
class Main {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("input.txt");
System.out.println("Data in the file");
int i = input.read();
while(i != -1) {
System.out.println((char)i);
i = input.read();
}
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
|
3e0ab8517b3102cad4ed2dc2ac145a9d67249113 | 9,291 | java | Java | src/test/java/com/github/alexeylapin/ocp/nio/FilesTest.java | alexey-lapin/java-prep-11 | 9cb6a1fd1df53839ff1b04ecec15ed3e01ac6c10 | [
"MIT"
] | null | null | null | src/test/java/com/github/alexeylapin/ocp/nio/FilesTest.java | alexey-lapin/java-prep-11 | 9cb6a1fd1df53839ff1b04ecec15ed3e01ac6c10 | [
"MIT"
] | null | null | null | src/test/java/com/github/alexeylapin/ocp/nio/FilesTest.java | alexey-lapin/java-prep-11 | 9cb6a1fd1df53839ff1b04ecec15ed3e01ac6c10 | [
"MIT"
] | null | null | null | 35.326996 | 111 | 0.629534 | 4,537 | package com.github.alexeylapin.ocp.nio;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.List;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
public class FilesTest {
@Test
void fileExistenceTest() {
assertThat(Files.exists(Path.of("README.md"))).isTrue();
}
@Test
void should_throwNoSuchFileException_when_testingForSameFileAndFileDoesNotExist() {
try {
Files.isSameFile(Path.of("README.md"), Path.of("fake.txt"));
} catch (IOException e) {
assertThat(e).isNotNull().isExactlyInstanceOf(NoSuchFileException.class);
}
}
@Test
void should_notThrowNoSuchFileException_when_testingForSameFileAndPathIsTheSame() {
try {
assertThat(Files.isSameFile(Path.of("fake.txt"), Path.of("fake.txt"))).isTrue();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
void should_notThrow_when_creatingDirectoryInExistingDirectory(@TempDir Path temp) {
assertThat(Files.exists(temp)).isTrue();
Path sub1 = temp.resolve("sub1");
assertThatCode(() -> Files.createDirectory(sub1)).doesNotThrowAnyException();
}
@Test
void should_throw_when_creatingDirectoryInNonExistingDirectory(@TempDir Path temp) {
assertThat(Files.exists(temp)).isTrue();
assertThat(Files.isRegularFile(temp)).isFalse();
assertThat(Files.isDirectory(temp)).isTrue();
Path sub1 = temp.resolve("sub1");
Path sub2 = sub1.resolve("sub2");
assertThat(Files.isDirectory(sub1)).isFalse();
assertThat(Files.isRegularFile(sub1)).isFalse();
assertThatCode(() -> Files.createDirectory(sub2)).isExactlyInstanceOf(NoSuchFileException.class);
assertThatCode(() -> Files.createDirectories(sub2)).doesNotThrowAnyException();
assertThatCode(() -> Files.createDirectories(sub1)).doesNotThrowAnyException();
assertThat(Files.isDirectory(sub1)).isTrue();
assertThat(Files.isDirectory(sub2)).isTrue();
}
@Test
void copyDirectoryTest(@TempDir Path temp) {
Path sub1 = temp.resolve("sub1");
Path sub2 = temp.resolve("sub2");
assertThat(Files.exists(sub2)).isFalse();
assertThat(Files.isRegularFile(sub2)).isFalse();
assertThat(Files.isDirectory(sub2)).isFalse();
assertThatCode(() -> Files.createDirectory(sub1)).doesNotThrowAnyException();
assertThatCode(() -> Files.copy(sub1, sub2)).doesNotThrowAnyException();
assertThat(Files.exists(sub1)).isTrue();
assertThat(Files.exists(sub2)).isTrue();
assertThat(Files.isRegularFile(sub2)).isFalse();
assertThat(Files.isDirectory(sub2)).isTrue();
}
@Test
void copyRegularFileTest(@TempDir Path temp) {
Path sub1 = temp.resolve("sub1");
Path sub2 = temp.resolve("sub2");
assertThat(Files.exists(sub2)).isFalse();
assertThat(Files.isRegularFile(sub2)).isFalse();
assertThat(Files.isDirectory(sub2)).isFalse();
assertThatCode(() -> Files.write(sub1, List.of("line1", "line2"))).doesNotThrowAnyException();
assertThatCode(() -> Files.copy(sub1, sub2)).doesNotThrowAnyException();
assertThat(Files.exists(sub1)).isTrue();
assertThat(Files.exists(sub2)).isTrue();
assertThat(Files.isRegularFile(sub2)).isTrue();
assertThat(Files.isDirectory(sub2)).isFalse();
}
@Test
void moveDirectoryTest(@TempDir Path temp) {
Path sub1 = temp.resolve("sub1");
Path sub2 = temp.resolve("sub2");
assertThat(Files.exists(sub2)).isFalse();
assertThat(Files.isRegularFile(sub2)).isFalse();
assertThat(Files.isDirectory(sub2)).isFalse();
assertThatCode(() -> Files.createDirectory(sub1)).doesNotThrowAnyException();
assertThatCode(() -> Files.move(sub1, sub2)).doesNotThrowAnyException();
assertThat(Files.exists(sub1)).isFalse();
assertThat(Files.exists(sub2)).isTrue();
assertThat(Files.isRegularFile(sub2)).isFalse();
assertThat(Files.isDirectory(sub2)).isTrue();
}
@Test
void moveRegularFileTest(@TempDir Path temp) {
Path sub1 = temp.resolve("sub1");
Path sub2 = temp.resolve("sub2");
assertThat(Files.exists(sub2)).isFalse();
assertThat(Files.isRegularFile(sub2)).isFalse();
assertThat(Files.isDirectory(sub2)).isFalse();
assertThatCode(() -> Files.write(sub1, List.of("line1", "line2"))).doesNotThrowAnyException();
assertThatCode(() -> Files.move(sub1, sub2)).doesNotThrowAnyException();
assertThat(Files.exists(sub1)).isFalse();
assertThat(Files.exists(sub2)).isTrue();
assertThat(Files.isRegularFile(sub2)).isTrue();
assertThat(Files.isDirectory(sub2)).isFalse();
}
@Test
void deleteRegularFileTest(@TempDir Path temp) {
Path path = temp.resolve("fake.txt");
assertThatCode(() -> Files.delete(path)).isExactlyInstanceOf(NoSuchFileException.class);
assertThatCode(() -> Files.deleteIfExists(path)).doesNotThrowAnyException();
assertThatCode(() -> Files.write(path, List.of("line1", "line2", "line3"))).doesNotThrowAnyException();
assertThatCode(() -> Files.delete(path)).doesNotThrowAnyException();
}
@Test
void writeAndReadTest(@TempDir Path temp) {
Path path = temp.resolve("file.txt");
try (var writer = Files.newBufferedWriter(path)) {
writer.write("string1");
writer.newLine();
writer.write("string2");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
try {
List<String> lines = Files.readAllLines(path);
assertThat(lines).containsExactly("string1", "string2");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
void fileAttributesTest(@TempDir Path temp) {
assertThat(Files.isRegularFile(temp)).isFalse();
assertThat(Files.isDirectory(temp)).isTrue();
assertThat(Files.isSymbolicLink(temp)).isFalse();
try {
assertThat(Files.isHidden(temp)).isFalse();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
assertThat(Files.isWritable(temp)).isTrue();
assertThat(Files.isReadable(temp)).isTrue();
assertThat(Files.isExecutable(temp)).isTrue();
}
@Test
void basicFileAttributesTest(@TempDir Path temp) {
try {
BasicFileAttributes attributes = Files.readAttributes(temp, BasicFileAttributes.class);
assertThat(attributes.isRegularFile()).isFalse();
assertThat(attributes.isDirectory()).isTrue();
assertThat(attributes.isSymbolicLink()).isFalse();
assertThat(attributes.isOther()).isFalse();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
void basicFileAttributeViewTest(@TempDir Path temp) {
BasicFileAttributeView view = Files.getFileAttributeView(temp, BasicFileAttributeView.class);
assertThat(view.name()).isEqualTo("basic");
try {
view.setTimes(FileTime.from(Instant.now()), null, null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
void filesListTest() {
try (Stream<Path> stream = Files.list(Path.of(""))) {
stream.forEach(System.out::println);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private long size(Path path) {
try {
return Files.size(path);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
void filesWalkTest() {
try (Stream<Path> stream = Files.walk(Path.of(""))) {
long sum = stream.peek(System.out::println)
.filter(Files::isRegularFile)
.mapToLong(this::size)
.sum();
System.out.println(sum);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
void filesFindTest() {
try (Stream<Path> stream = Files.find(
Path.of(""),
Integer.MAX_VALUE,
(path, __) -> path.getFileName().toString().endsWith(".java"))) {
long sum = stream.peek(System.out::println)
.filter(Files::isRegularFile)
.mapToLong(this::size)
.sum();
System.out.println(sum);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
|
3e0ab8a4ad9bd97938981b94bde4c69defecbb61 | 426 | java | Java | jOOQ-opensource/jOOQSpringBootSDJDBC/src/main/java/com/classicmodels/repository/ProducLineRepository.java | mcac0006/Up-and-Running-with-jOOQ | 41b6bea8df5e1a07e78a68e0d4b6337132c909c6 | [
"MIT"
] | 28 | 2020-09-18T14:32:24.000Z | 2022-03-22T14:48:19.000Z | jOOQ-opensource/jOOQSpringBootSDJDBC/src/main/java/com/classicmodels/repository/ProducLineRepository.java | mcac0006/Up-and-Running-with-jOOQ | 41b6bea8df5e1a07e78a68e0d4b6337132c909c6 | [
"MIT"
] | 2 | 2021-03-22T12:20:16.000Z | 2022-01-03T12:54:35.000Z | jOOQ-opensource/jOOQSpringBootSDJDBC/src/main/java/com/classicmodels/repository/ProducLineRepository.java | mcac0006/Up-and-Running-with-jOOQ | 41b6bea8df5e1a07e78a68e0d4b6337132c909c6 | [
"MIT"
] | 10 | 2021-03-20T13:30:37.000Z | 2022-03-25T04:23:12.000Z | 32.769231 | 82 | 0.835681 | 4,538 | package com.classicmodels.repository;
import com.classicmodels.model.ProductLine;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional(readOnly = true)
public interface ProducLineRepository
extends CrudRepository<ProductLine, String>, ClassicModelsRepository {
}
|
3e0ab942c8f4c6d4627e59bdc1a80b280c9b2ec1 | 618 | java | Java | src/com/innowhere/jnieasy/core/impl/common/classtype/model/ClassTypeNativeArrayInterface.java | jmarranz/jnieasy | e295b23ee7418c8e412b025b957e64ceaba40fac | [
"Apache-2.0"
] | 8 | 2016-10-26T13:20:20.000Z | 2021-05-12T05:00:56.000Z | src/com/innowhere/jnieasy/core/impl/common/classtype/model/ClassTypeNativeArrayInterface.java | jmarranz/jnieasy | e295b23ee7418c8e412b025b957e64ceaba40fac | [
"Apache-2.0"
] | null | null | null | src/com/innowhere/jnieasy/core/impl/common/classtype/model/ClassTypeNativeArrayInterface.java | jmarranz/jnieasy | e295b23ee7418c8e412b025b957e64ceaba40fac | [
"Apache-2.0"
] | 1 | 2022-01-14T03:18:08.000Z | 2022-01-14T03:18:08.000Z | 26.869565 | 87 | 0.765372 | 4,539 | /*
* ClassTypeNativeArrayInterface.java
*
* Created on 16 de mayo de 2005, 12:12
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package com.innowhere.jnieasy.core.impl.common.classtype.model;
import com.innowhere.jnieasy.core.impl.common.classtype.model.ClassTypeNativeArrayInfo;
/**
*
* @author jmarranz
*/
public interface ClassTypeNativeArrayInterface
{
public ClassTypeNativeArrayInfo getArrayInfo();
}
|
3e0ab99284350cd573518bc03fa83d8dcadf65e3 | 12,372 | java | Java | demo_mace/app/src/main/java/com/example/Etc/MySQLiteOpenHelper.java | HamjASB/Fit-Got-U | eab80a74ccf294de0732d2c0feb84db6d129a485 | [
"Apache-2.0"
] | 1 | 2019-03-18T10:04:16.000Z | 2019-03-18T10:04:16.000Z | demo_mace/app/src/main/java/com/example/Etc/MySQLiteOpenHelper.java | HamjASB/Fit-Got-U | eab80a74ccf294de0732d2c0feb84db6d129a485 | [
"Apache-2.0"
] | null | null | null | demo_mace/app/src/main/java/com/example/Etc/MySQLiteOpenHelper.java | HamjASB/Fit-Got-U | eab80a74ccf294de0732d2c0feb84db6d129a485 | [
"Apache-2.0"
] | 4 | 2019-03-18T10:04:24.000Z | 2019-07-01T18:47:06.000Z | 33.803279 | 181 | 0.533948 | 4,540 | package com.example.Etc;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Pair;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
public class MySQLiteOpenHelper extends SQLiteOpenHelper implements Serializable {
final private String[] bodyPart = {"좌측 팔 하박", "좌측 팔 상박", "좌측 다리 하박", "좌측 다리 상박",
"몸통", "엉덩이", "우측 팔 하박", "우측 팔 상박", "우측 다리 하박", "우측 다리 상박",
"좌측 어깨", "우측 어깨"};
private final int POINT_STANDARD_YELLO_RED = 15; // 노란 또는 빨강 기준
private final int POINT_STANDARD_YELLO_GREEN = 5;
final private String exerciseNames[] = {"'스쿼트'", "'플랭크'", "'런지'", "'사이드런지'", "'와이드스쿼트'"};
private Context context = null;
// 안드로이드에서 SQLite 데이터 베이스를 쉽게 사용할 수 있도록 도와주는 클래스
public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.context = context;
onCreate(openDB());
}
@Override
public void onCreate(SQLiteDatabase sqliteDB) {
// 최초에 데이터베이스가 없을경우, 데이터베이스 생성을 위해 호출됨
// 테이블 생성하는 코드를 작성한다
try {
if (sqliteDB != null) {
String sqlCreateTbl;
sqlCreateTbl = "CREATE TABLE IF NOT EXISTS EXERCISE_RECORD (" +
"Id " + "INTEGER primary key autoincrement," +
"Exercise_name " + "TEXT," +
"Exercise_date " + "TEXT," +
"Exercise_count " + "INTEGER" + ");";
System.out.println(sqlCreateTbl);
sqliteDB.execSQL(sqlCreateTbl);
sqlCreateTbl = "CREATE TABLE IF NOT EXISTS EXERCISE_DESCRIBE (" +
"Id " + "INTEGER primary key autoincrement," +
"Weak_part " + "TEXT," +
"Weak_angle " + "INTEGER," +
"Record_id " + "INTEGER," +
"CONSTRAINT Record_id_fk FOREIGN KEY(Record_id) " +
"REFERENCES EXERCISE_RECORD(Id));";
System.out.println(sqlCreateTbl);
sqliteDB.execSQL(sqlCreateTbl);
}
} catch (Exception e) {
e.printStackTrace();
}
} // 쿼리를 가짐
@Override
public void onUpgrade(SQLiteDatabase sqliteDB, int oldVersion, int newVersion) { //쿼리를 가짐
// 데이터베이스의 버전이 바뀌었을 때 호출되는 콜백 메서드
// 버전 바뀌었을 때 기존데이터베이스를 어떻게 변경할 것인지 작성한다
// 각 버전의 변경 내용들을 버전마다 작성해야함
if (sqliteDB != null) {
String sql = "drop table 'EXERCISE_DESCRIBE';"; // 테이블 드랍
sqliteDB.execSQL(sql);
sql = "drop table 'EXERCISE_RECORD';"; // 테이블 드랍
sqliteDB.execSQL(sql);
onCreate(sqliteDB); // 다시 테이블 생성
}
}
private SQLiteDatabase openDB() {
File file = new File(this.context.getFilesDir(), "jelly.db");
SQLiteDatabase db = null;
System.out.println("PATH : " + file.toString());
try {
db = SQLiteDatabase.openOrCreateDatabase(file, null);
} catch (SQLiteException e) {
e.printStackTrace();
}
return db;
}
// ******
public int insertRecord(String exerciseName, String exerciseDate, int exerciseCount) {
SQLiteDatabase db = openDB();
int recordID = -1;
exerciseName = "'" + exerciseName + "'";
exerciseDate = "'" + exerciseDate + "'";
if (db != null) {
String sql = "INSERT INTO EXERCISE_RECORD ( Exercise_name, Exercise_date, Exercise_count ) VALUES ( " + exerciseName + ", " + exerciseDate + ", " + exerciseCount + ");";
db.execSQL(sql);
sql = "SELECT Id From EXERCISE_RECORD WHERE " +
"Exercise_name = " + exerciseName + " AND " +
"Exercise_date = " + exerciseDate + " AND Exercise_count != 0 ;";
Cursor cursor = null;
cursor = db.rawQuery(sql, null);
if (cursor.moveToNext()) {
recordID = cursor.getInt(0);
}
}
return recordID;
} // 쿼리를 가짐
//******
public void insertDescribe(int recordID, String weakPart, int weakAngle) { // 퀴리를 가짐
SQLiteDatabase db = openDB();
weakPart = "'" + weakPart + "'";
if (db != null) {
String sql;
sql = "insert into EXERCISE_DESCRIBE(Weak_part, Weak_angle, Record_id) values (" +
weakPart + ", " + weakAngle + ", " + recordID + ");";
db.execSQL(sql);
}
}
//*******
public void updateRecordCount(int recordID, int exerciseCount) {
SQLiteDatabase db = openDB();
if (db != null) {
String sql = "UPDATE EXERCISE_RECORD SET Exercise_count = " + exerciseCount +
" WHERE Id = " + recordID + ";";
db.execSQL(sql);
}
}
public int getRecordID(String exerciseName, String exerciseDate) {
SQLiteDatabase db = openDB();
int recordID = -1;
exerciseName = "'" + exerciseName + "'";
exerciseDate = "'" + exerciseDate + "'";
if (db != null) {
String sql;
sql = "select Id from EXERCISE_RECORD where " +
"Exercise_name = " + exerciseName + " AND " +
"Exercise_date = " + exerciseDate + " AND Exercise_count != 0;";
Cursor cursor = null;
cursor = db.rawQuery(sql, null);
if (cursor.moveToNext()) {
recordID = cursor.getInt(0);
}
return recordID;
}
return recordID;
}
//todo TEST
public void insertTest() {
final int TEST_SIZE = 5;
int recordID = insertRecord("스쿼트", "2019-06-03-04-51-25", 0);
for (int i = 0; i < TEST_SIZE; i++) {
insertDescribe(recordID, bodyPart[i], i + 5);
}
updateRecordCount(recordID, 5);
recordID = insertRecord("플랭크", "2019-06-02-04-51-26", 5);
for (int i = 0; i < TEST_SIZE; i++) {
insertDescribe(recordID, bodyPart[i + 3], (i + 5) * -1);
}
}
public int[] getJointValues(String exerciseDate, String exerciseName) {
SQLiteDatabase db = openDB();
int[] jointValues = new int[12];
if (db != null) {
for (int i = 0; i < 12; i++) {
String partName = bodyPart[i];
jointValues[i] = calcJointValue(partName, exerciseDate, exerciseName);
}
}
return jointValues;
}
private int calcJointValue(String partName, String exerciseDate, String exerciseName) {
SQLiteDatabase db = openDB();
int jointValue;
int recordID = -1;
String recordIDCondition = "";
partName = "'" + partName + "'";
if (db != null) {
Cursor cursor = null;
if (exerciseDate != null && exerciseName != null) {
recordID = getRecordID(exerciseName, exerciseDate);
recordIDCondition = " AND Record_id = " + recordID;
}
String sqlSelectP_Angle = "SELECT AVG(Weak_angle) as average FROM EXERCISE_DESCRIBE WHERE Weak_part = " + partName +
recordIDCondition + ";";
cursor = db.rawQuery(sqlSelectP_Angle, null);
if (cursor.moveToNext()) {
jointValue = (int)cursor.getDouble(0);
} else {
jointValue = 0;
}
return jointValue;
}
return 0;
} // 쿼리를 가짐
public int countDayExercise(String exerciseDate) {
SQLiteDatabase db = openDB();
Cursor cursor = null;
int exerciseCount = 0;
exerciseDate = "'" + exerciseDate + "%'";
if (db != null) {
String query = "SELECT Exercise_name FROM EXERCISE_RECORD where Exercise_date LIKE " + exerciseDate + " AND Exercise_count != 0;";
System.out.println(query);
cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
exerciseCount++;
cursor.moveToNext();
}
}
}
return exerciseCount;
} // 쿼리를 가짐
public ArrayList<Pair<Pair<String, String>, Integer>> getDescribe(String exerciseDate) {
SQLiteDatabase db = openDB();
Cursor cursor = null;
exerciseDate = "'" + exerciseDate.substring(0, 10) + "%'";
ArrayList<Pair<Pair<String, String>, Integer>> exerciseNames = new ArrayList<Pair<Pair<String, String>, Integer>>();
if (db != null) {
String query = "SELECT Exercise_name, Exercise_date, Exercise_count FROM EXERCISE_RECORD WHERE Exercise_date like " + exerciseDate + " AND Exercise_count != 0;";
cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
exerciseNames.add(Pair.create(Pair.create(cursor.getString(0), cursor.getString(1)), cursor.getInt(2)));
cursor.moveToNext();
}
}
}
return exerciseNames;
}
public String analysisText(int[] jointValues) {
String analysisText = "";
String up_part = "";
String down_part = "";
for (int i = 0; i < jointValues.length; i++) {
if (jointValues[i] >= POINT_STANDARD_YELLO_GREEN) {
up_part += "[" + bodyPart[i] + "] ";
} else if (jointValues[i] <= -1 * POINT_STANDARD_YELLO_GREEN) {
down_part += "[" + bodyPart[i] + "] ";
}
}
if (up_part.length() > 0) {
analysisText += up_part + "부위가 몸 바깥쪽 방향으로 향하는 경향이 있습니다.\n";
}
if (down_part.length() > 0) {
analysisText += down_part + "부위가 몸 안쪽 방향으로 향하는 경향이 있습니다.\n";
}
if (analysisText.length() < 1) {
analysisText = "운동 자세를 바르게 따라하고 있습니다.";
}
return analysisText;
}
public String getDayAnalysisText(String exerciseDate, String exerciseName) {
return analysisText(getJointValues(exerciseDate, exerciseName));
}
// 달력에 운동 데이터 날림
public HashSet<String> getExerciseData() {
HashSet<String> dates = new HashSet<String>();
SQLiteDatabase db = openDB();
Cursor cursor = null;
if (db != null) {
String query = "SELECT distinct Exercise_date FROM EXERCISE_RECORD WHERE Exercise_date AND Exercise_count != 0 " + ";";
System.out.println(query);
cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String tmp_date = cursor.getString(0);
dates.add(tmp_date.substring(0, 10));
cursor.moveToNext();
}
}
}
return dates;
}
public String getExerciseText(String exerciseDate) {
SQLiteDatabase db = openDB();
Cursor cursor = null;
String result = "";
int result_count=0;
if (db != null) {
String query = "SELECT Exercise_name, Exercise_count FROM EXERCISE_RECORD WHERE Exercise_date like '" + exerciseDate + "%' AND Exercise_count != 0;";
cursor = db.rawQuery(query, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String exerciseName = cursor.getString(0);
int exerciseCount = cursor.getInt(1);
result += exerciseName + " " + exerciseCount + "회 ";
result_count++;
if(result_count%3==0) result+="\n";
cursor.moveToNext();
}
}
}
return result;
}
} |
3e0ab99bcbb50f90d087a2235758723d4824f41a | 5,427 | java | Java | src/main/java/net/minecraft/util/Vec3.java | inklesspen1scripter/ultramine_core | 4a7939114c4b61dd3c603302f087004c093101af | [
"WTFPL"
] | null | null | null | src/main/java/net/minecraft/util/Vec3.java | inklesspen1scripter/ultramine_core | 4a7939114c4b61dd3c603302f087004c093101af | [
"WTFPL"
] | null | null | null | src/main/java/net/minecraft/util/Vec3.java | inklesspen1scripter/ultramine_core | 4a7939114c4b61dd3c603302f087004c093101af | [
"WTFPL"
] | 1 | 2020-02-02T15:45:30.000Z | 2020-02-02T15:45:30.000Z | 29.335135 | 229 | 0.693753 | 4,541 | package net.minecraft.util;
public class Vec3
{
public double xCoord;
public double yCoord;
public double zCoord;
private static final String __OBFID = "CL_00000612";
public static Vec3 createVectorHelper(double p_72443_0_, double p_72443_2_, double p_72443_4_)
{
return new Vec3(p_72443_0_, p_72443_2_, p_72443_4_);
}
protected Vec3(double p_i1108_1_, double p_i1108_3_, double p_i1108_5_)
{
if (p_i1108_1_ == -0.0D)
{
p_i1108_1_ = 0.0D;
}
if (p_i1108_3_ == -0.0D)
{
p_i1108_3_ = 0.0D;
}
if (p_i1108_5_ == -0.0D)
{
p_i1108_5_ = 0.0D;
}
this.xCoord = p_i1108_1_;
this.yCoord = p_i1108_3_;
this.zCoord = p_i1108_5_;
}
protected Vec3 setComponents(double p_72439_1_, double p_72439_3_, double p_72439_5_)
{
this.xCoord = p_72439_1_;
this.yCoord = p_72439_3_;
this.zCoord = p_72439_5_;
return this;
}
public Vec3 subtract(Vec3 p_72444_1_)
{
return createVectorHelper(p_72444_1_.xCoord - this.xCoord, p_72444_1_.yCoord - this.yCoord, p_72444_1_.zCoord - this.zCoord);
}
public Vec3 normalize()
{
double d0 = (double)MathHelper.sqrt_double(this.xCoord * this.xCoord + this.yCoord * this.yCoord + this.zCoord * this.zCoord);
return d0 < 1.0E-4D ? createVectorHelper(0.0D, 0.0D, 0.0D) : createVectorHelper(this.xCoord / d0, this.yCoord / d0, this.zCoord / d0);
}
public double dotProduct(Vec3 p_72430_1_)
{
return this.xCoord * p_72430_1_.xCoord + this.yCoord * p_72430_1_.yCoord + this.zCoord * p_72430_1_.zCoord;
}
public Vec3 crossProduct(Vec3 p_72431_1_)
{
return createVectorHelper(this.yCoord * p_72431_1_.zCoord - this.zCoord * p_72431_1_.yCoord, this.zCoord * p_72431_1_.xCoord - this.xCoord * p_72431_1_.zCoord, this.xCoord * p_72431_1_.yCoord - this.yCoord * p_72431_1_.xCoord);
}
public Vec3 addVector(double p_72441_1_, double p_72441_3_, double p_72441_5_)
{
return createVectorHelper(this.xCoord + p_72441_1_, this.yCoord + p_72441_3_, this.zCoord + p_72441_5_);
}
public double distanceTo(Vec3 p_72438_1_)
{
double d0 = p_72438_1_.xCoord - this.xCoord;
double d1 = p_72438_1_.yCoord - this.yCoord;
double d2 = p_72438_1_.zCoord - this.zCoord;
return (double)MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2);
}
public double squareDistanceTo(Vec3 p_72436_1_)
{
double d0 = p_72436_1_.xCoord - this.xCoord;
double d1 = p_72436_1_.yCoord - this.yCoord;
double d2 = p_72436_1_.zCoord - this.zCoord;
return d0 * d0 + d1 * d1 + d2 * d2;
}
public double squareDistanceTo(double p_72445_1_, double p_72445_3_, double p_72445_5_)
{
double d3 = p_72445_1_ - this.xCoord;
double d4 = p_72445_3_ - this.yCoord;
double d5 = p_72445_5_ - this.zCoord;
return d3 * d3 + d4 * d4 + d5 * d5;
}
public double lengthVector()
{
return (double)MathHelper.sqrt_double(this.xCoord * this.xCoord + this.yCoord * this.yCoord + this.zCoord * this.zCoord);
}
public Vec3 getIntermediateWithXValue(Vec3 p_72429_1_, double p_72429_2_)
{
double d1 = p_72429_1_.xCoord - this.xCoord;
double d2 = p_72429_1_.yCoord - this.yCoord;
double d3 = p_72429_1_.zCoord - this.zCoord;
if (d1 * d1 < 1.0000000116860974E-7D)
{
return null;
}
else
{
double d4 = (p_72429_2_ - this.xCoord) / d1;
return d4 >= 0.0D && d4 <= 1.0D ? createVectorHelper(this.xCoord + d1 * d4, this.yCoord + d2 * d4, this.zCoord + d3 * d4) : null;
}
}
public Vec3 getIntermediateWithYValue(Vec3 p_72435_1_, double p_72435_2_)
{
double d1 = p_72435_1_.xCoord - this.xCoord;
double d2 = p_72435_1_.yCoord - this.yCoord;
double d3 = p_72435_1_.zCoord - this.zCoord;
if (d2 * d2 < 1.0000000116860974E-7D)
{
return null;
}
else
{
double d4 = (p_72435_2_ - this.yCoord) / d2;
return d4 >= 0.0D && d4 <= 1.0D ? createVectorHelper(this.xCoord + d1 * d4, this.yCoord + d2 * d4, this.zCoord + d3 * d4) : null;
}
}
public Vec3 getIntermediateWithZValue(Vec3 p_72434_1_, double p_72434_2_)
{
double d1 = p_72434_1_.xCoord - this.xCoord;
double d2 = p_72434_1_.yCoord - this.yCoord;
double d3 = p_72434_1_.zCoord - this.zCoord;
if (d3 * d3 < 1.0000000116860974E-7D)
{
return null;
}
else
{
double d4 = (p_72434_2_ - this.zCoord) / d3;
return d4 >= 0.0D && d4 <= 1.0D ? createVectorHelper(this.xCoord + d1 * d4, this.yCoord + d2 * d4, this.zCoord + d3 * d4) : null;
}
}
public String toString()
{
return "(" + this.xCoord + ", " + this.yCoord + ", " + this.zCoord + ")";
}
public void rotateAroundX(float p_72440_1_)
{
float f1 = MathHelper.cos(p_72440_1_);
float f2 = MathHelper.sin(p_72440_1_);
double d0 = this.xCoord;
double d1 = this.yCoord * (double)f1 + this.zCoord * (double)f2;
double d2 = this.zCoord * (double)f1 - this.yCoord * (double)f2;
this.setComponents(d0, d1, d2);
}
public void rotateAroundY(float p_72442_1_)
{
float f1 = MathHelper.cos(p_72442_1_);
float f2 = MathHelper.sin(p_72442_1_);
double d0 = this.xCoord * (double)f1 + this.zCoord * (double)f2;
double d1 = this.yCoord;
double d2 = this.zCoord * (double)f1 - this.xCoord * (double)f2;
this.setComponents(d0, d1, d2);
}
public void rotateAroundZ(float p_72446_1_)
{
float f1 = MathHelper.cos(p_72446_1_);
float f2 = MathHelper.sin(p_72446_1_);
double d0 = this.xCoord * (double)f1 + this.yCoord * (double)f2;
double d1 = this.yCoord * (double)f1 - this.xCoord * (double)f2;
double d2 = this.zCoord;
this.setComponents(d0, d1, d2);
}
} |
3e0ab9c491e5b632ef802ca3a42d978c2f220ac7 | 382 | java | Java | springboot_shiro_jwt_demo/src/test/java/com/example/li/springboot_shiro_jwt_demo/SpringbootShiroJwtDemoApplicationTests.java | MiaHeHe/springboot | 3259f267eed402b4751edd7b1020cf42b51434a5 | [
"Apache-2.0"
] | 27 | 2019-08-31T07:08:45.000Z | 2022-03-07T12:11:20.000Z | springboot_shiro_jwt_demo/src/test/java/com/example/li/springboot_shiro_jwt_demo/SpringbootShiroJwtDemoApplicationTests.java | lim960/springboot | c2c08a6700bbabedf58a978d900e20600d747681 | [
"Apache-2.0"
] | 9 | 2020-08-04T00:29:16.000Z | 2021-05-12T03:57:02.000Z | springboot_shiro_jwt_demo/src/test/java/com/example/li/springboot_shiro_jwt_demo/SpringbootShiroJwtDemoApplicationTests.java | lim960/springboot | c2c08a6700bbabedf58a978d900e20600d747681 | [
"Apache-2.0"
] | 26 | 2020-02-23T18:00:07.000Z | 2022-03-11T07:00:35.000Z | 22.470588 | 60 | 0.806283 | 4,542 | package com.example.li.springboot_shiro_jwt_demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootShiroJwtDemoApplicationTests {
@Test
public void contextLoads() {
}
}
|
3e0aba4208bb63e797f5bf716c81b574293d2369 | 897 | java | Java | messaging/src/main/java/org/cloudiator/messaging/kafka/Constants.java | IMU-ICCS/common | 426b21b8f7976617507af62d94329bd64baf27bd | [
"Apache-2.0"
] | null | null | null | messaging/src/main/java/org/cloudiator/messaging/kafka/Constants.java | IMU-ICCS/common | 426b21b8f7976617507af62d94329bd64baf27bd | [
"Apache-2.0"
] | 3 | 2018-05-23T15:10:04.000Z | 2019-10-08T07:46:25.000Z | messaging/src/main/java/org/cloudiator/messaging/kafka/Constants.java | IMU-ICCS/common | 426b21b8f7976617507af62d94329bd64baf27bd | [
"Apache-2.0"
] | 3 | 2017-07-18T06:35:12.000Z | 2019-02-02T17:58:25.000Z | 29.9 | 75 | 0.745819 | 4,543 | /*
* Copyright 2017 University of Ulm
*
* 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.cloudiator.messaging.kafka;
public final class Constants {
public static final String KAFKA_SERVERS = "bootstrapServers";
public static final String KAFKA_GROUP_ID = "groupId";
public static final String RESPONSE_TIMEOUT = "responseTimeout";
private Constants() {
}
}
|
3e0abcb5580665e0aae3874167dade5339c0fa8f | 3,600 | java | Java | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PersistJobAction.java | a137872798/elasticsearch | 293ff2f60eb1fce9af59d23692d783ad040e0654 | [
"Apache-2.0"
] | 3 | 2020-07-09T19:00:34.000Z | 2020-07-09T19:01:20.000Z | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PersistJobAction.java | paulbaudrier/elasticsearch | 16bfdcacc0172264db9b32aa6edfa8b5c327f3b4 | [
"Apache-2.0"
] | 2 | 2019-12-05T10:21:58.000Z | 2020-01-10T09:17:26.000Z | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PersistJobAction.java | paulbaudrier/elasticsearch | 16bfdcacc0172264db9b32aa6edfa8b5c327f3b4 | [
"Apache-2.0"
] | 2 | 2020-02-03T07:05:44.000Z | 2020-02-05T01:51:57.000Z | 30 | 101 | 0.619167 | 4,544 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.ml.action;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.support.tasks.BaseTasksResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import java.io.IOException;
import java.util.Objects;
public class PersistJobAction extends ActionType<PersistJobAction.Response> {
public static final PersistJobAction INSTANCE = new PersistJobAction();
public static final String NAME = "cluster:admin/xpack/ml/job/persist";
private PersistJobAction() {
super(NAME, PersistJobAction.Response::new);
}
public static class Request extends JobTaskRequest<PersistJobAction.Request> {
public Request() {
}
public Request(StreamInput in) throws IOException {
super(in);
// isBackground for fwc
in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
// isBackground for fwc
out.writeBoolean(true);
}
public Request(String jobId) {
super(jobId);
}
public boolean isBackGround() {
return true;
}
public boolean isForeground() {
return !isBackGround();
}
@Override
public int hashCode() {
return Objects.hash(jobId, isBackGround());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
PersistJobAction.Request other = (PersistJobAction.Request) obj;
return Objects.equals(jobId, other.jobId) && this.isBackGround() == other.isBackGround();
}
}
public static class Response extends BaseTasksResponse implements Writeable {
private final boolean persisted;
public Response(boolean persisted) {
super(null, null);
this.persisted = persisted;
}
public Response(StreamInput in) throws IOException {
super(in);
persisted = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(persisted);
}
public boolean isPersisted() {
return persisted;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Response that = (Response) o;
return this.persisted == that.persisted;
}
@Override
public int hashCode() {
return Objects.hash(persisted);
}
}
static class RequestBuilder extends ActionRequestBuilder<Request, Response> {
RequestBuilder(ElasticsearchClient client, PersistJobAction action) {
super(client, action, new PersistJobAction.Request());
}
}
}
|
3e0abcbefe730c1c091c01c9d0a90d624145783c | 7,505 | java | Java | src/test/java/com/group3/AppTest.java | Hein1P/group3 | 225559c753ad61f4adb9f71320db119281bd622c | [
"Apache-2.0"
] | null | null | null | src/test/java/com/group3/AppTest.java | Hein1P/group3 | 225559c753ad61f4adb9f71320db119281bd622c | [
"Apache-2.0"
] | 27 | 2020-11-19T16:40:54.000Z | 2020-12-04T18:00:14.000Z | src/test/java/com/group3/AppTest.java | Hein1P/group3 | 225559c753ad61f4adb9f71320db119281bd622c | [
"Apache-2.0"
] | null | null | null | 28.320755 | 95 | 0.654763 | 4,545 |
package com.group3;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
public class AppTest {
static App app;
@BeforeAll
static void init() {
app = new App();
}
@Test
void displayCountryTestNull() {
app.displayCountry(null);
}
@Test
void displayCountryTestEmpty() {
ArrayList<Country> countries = new ArrayList<Country>();
app.displayCountry(countries);
}
@Test
void displayCountryTestEmptyCoun() {
ArrayList<Country> countries = new ArrayList<Country>();
countries.add(null);
app.displayCountry(countries);
}
@Test
void displayCountryTestNormal() {
ArrayList<Country> countries = new ArrayList<Country>();
Country coun = new Country("MMR", "Myanmar", "Asia", "Southeast Asia", 45611000, 2710);
countries.add(coun);
app.displayCountry(countries);
}
@Test
void displayCityTestNull() {
app.displayCity(null);
}
@Test
void displayCityTestEmpty() {
ArrayList<City> cities = new ArrayList<City>();
app.displayCity(cities);
}
@Test
void displayCityTestEmptyCity() {
ArrayList<City> cities = new ArrayList<City>();
cities.add(null);
app.displayCity(cities);
}
@Test
void displayCityTestNormal() {
String countryname = "Myanmar";
Country coun = new Country(null,countryname,null);
ArrayList<City> cities = new ArrayList<City>();
City city = new City(2710, "Rangoon (Yangon)", 3361700, "Rangoon [Yangon]", coun);
cities.add(city);
app.displayCity(cities);
}
@Test
void displayCityPopuOfPeopleinEachContinentTestNull() {
app.displayCityPopuOfPeopleinEachContinent(null);
}
@Test
void displayCityPopuOfPeopleinEachContinentTestEmpty() {
ArrayList<City> cities = new ArrayList<City>();
app.displayCityPopuOfPeopleinEachContinent(cities);
}
@Test
void displayCityPopuOfPeopleinEachContinentTestEmptyCity() {
ArrayList<City> cities = new ArrayList<City>();
cities.add(null);
app.displayCityPopuOfPeopleinEachContinent(cities);
}
@Test
void displayCityPopuOfPeopleinEachContinentTestNormal() {
String continent = "Asia";
Country coun = new Country(null,continent);
ArrayList<City> cities = new ArrayList<City>();
City city = new City( "0.08%", "99.92%",Long.valueOf(900937599400L),coun);
cities.add(city);
app.displayCityPopuOfPeopleinEachContinent(cities);
}
@Test
void displayCityPopuOfPeopleinEachRegionTestNull() {
app.displayPopuOfPeopleinEachRegion(null);
}
@Test
void displayCityPopuOfPeopleinEachRegionTestEmpty() {
ArrayList<City> cities = new ArrayList<City>();
app.displayPopuOfPeopleinEachRegion(cities);
}
@Test
void displayCityPopuOfPeopleinEachRegionTestEmptyCity() {
ArrayList<City> cities = new ArrayList<City>();
cities.add(null);
app.displayPopuOfPeopleinEachRegion(cities);
}
@Test
void displayCityPopuOfPeopleinEachRegionTestNormal() {
String Region = "Southeast Asia";
Country coun = new Country(null,Region);
ArrayList<City> cities = new ArrayList<City>();
City city = new City( "0.08%", "99.92%",Long.valueOf(10000000L),coun);
cities.add(city);
app.displayPopuOfPeopleinEachRegion(cities);
}
@Test
void displayCityPopuOfPeopleinEachCountryTestNull() {
app.displayPopuOfPeopleinEachCountry(null);
}
@Test
void displayCityPopuOfPeopleinEachCountryTestEmpty() {
ArrayList<City> cities = new ArrayList<City>();
app.displayPopuOfPeopleinEachCountry(cities);
}
@Test
void displayCityPopuOfPeopleinEachCountryTestEmptyCity() {
ArrayList<City> cities = new ArrayList<City>();
cities.add(null);
app.displayPopuOfPeopleinEachCountry(cities);
}
@Test
void displayCityPopuOfPeopleinEachCountryTestNormal() {
String Country = "Myanmar";
Country coun = new Country(null,Country);
ArrayList<City> cities = new ArrayList<City>();
City city = new City( "0.08%", "99.92%",Long.valueOf(10000000L),coun);
cities.add(city);
app.displayPopuOfPeopleinEachCountry(cities);
}
@Test
void displayworldpopulationTestNull() {
app.displayWorldPopulation(null);
}
@Test
void displayworldpopulationTestEmpty() {
ArrayList<Country> countries = new ArrayList<Country>();
app.displayWorldPopulation(countries);
}
@Test
void displayworldpopulationTestEmptyCountry() {
ArrayList<Country> countries = new ArrayList<Country>();
countries.add(null);
app.displayWorldPopulation(countries);
}
@Test
void displayworldpopulationTestNormal() {
ArrayList<Country> countries = new ArrayList<Country>();
Country country = new Country(Long.valueOf(6078749450L),null);
countries.add(country);
app.displayWorldPopulation(countries);
}
@Test
void displaycountrypopulationTestNull() {
app.displayCountryPopulation(null);
}
@Test
void displaycountrypopulationTestEmpty() {
ArrayList<Country> countries = new ArrayList<Country>();
app.displayCountryPopulation(countries);
}
@Test
void displaycountrypopulationTestEmptyCountry() {
ArrayList<Country> countries = new ArrayList<Country>();
countries.add(null);
app.displayCountryPopulation(countries);
}
@Test
void displaycountrypopulationTestNormal() {
ArrayList<Country> countries = new ArrayList<Country>();
Country country = new Country(Long.valueOf(3705025700L), "Asia");
countries.add(country);
app.displayCountryPopulation(countries);
}
@Test
void displayCityPopulationTestNull() {
app.displayCityPopulation(null);
}
@Test
void displayCityPopulationTestEmpty() {
ArrayList<City> cities = new ArrayList<City>();
app.displayCityPopulation(cities);
}
@Test
void displayCityPopulationTestEmptyCity() {
ArrayList<City> cities = new ArrayList<City>();
cities.add(null);
app.displayCityPopulation(cities);
}
@Test
void displayCityPopulationTestNormal() {
ArrayList<City> cities = new ArrayList<City>();
City city = new City("Rangoon [Yangon]", 3361700);
cities.add(city);
app.displayCityPopulation(cities);
}
@Test
void displayLanguageTestNull() {
app.displayLanguage(null);
}
@Test
void displayLanguageTestEmpty() {
ArrayList<CountryLanguage> Languages = new ArrayList<CountryLanguage>();
app.displayLanguage(Languages);
}
@Test
void displayLanguageTestEmptyCountryLanguage() {
ArrayList<CountryLanguage> Languages = new ArrayList<CountryLanguage>();
Languages.add(null);
app.displayLanguage(Languages);
}
@Test
void displayLanguageTestNormal() {
ArrayList<CountryLanguage> languages = new ArrayList<CountryLanguage>();
CountryLanguage language = new CountryLanguage("Chinese", "19.61%", 1191843539);
languages.add(language);
app.displayLanguage(languages);
}
}
|
3e0abcd01033d87bb46f712ac76b994f5726ae58 | 1,204 | java | Java | src/aya/util/ObjToColor.java | aya-lang/aya | 2c125eca2f5fb9b8b4cc2348e8fde8ef2583b5e9 | [
"MIT"
] | 17 | 2021-01-04T04:16:06.000Z | 2022-03-19T21:42:34.000Z | src/aya/util/ObjToColor.java | nick-paul/aya-lang | 2c125eca2f5fb9b8b4cc2348e8fde8ef2583b5e9 | [
"MIT"
] | 44 | 2017-01-01T21:34:42.000Z | 2019-08-09T13:26:12.000Z | src/aya/util/ObjToColor.java | nick-paul/aya-lang | 2c125eca2f5fb9b8b4cc2348e8fde8ef2583b5e9 | [
"MIT"
] | 1 | 2021-12-20T15:32:47.000Z | 2021-12-20T15:32:47.000Z | 24.08 | 93 | 0.638704 | 4,546 | package aya.util;
import java.awt.Color;
import aya.exceptions.runtime.ValueError;
import aya.obj.Obj;
import aya.obj.dict.Dict;
import aya.obj.symbol.SymbolConstants;
public class ObjToColor {
public static Color objToColor(Obj val) {
if ( val.isa(Obj.DICT)) {
DictReader c = new DictReader((Dict)val);
int r = c.getInt(SymbolConstants.R, 0);
int g = c.getInt(SymbolConstants.G, 0);
int b = c.getInt(SymbolConstants.B, 0);
int a = c.getInt(SymbolConstants.A, 255);
try {
return new Color(r,g,b,a);
} catch (IllegalArgumentException e) {
throw new ValueError("Invalid color: " + r + "," + g + "," + b + "," + a);
}
} else if (val.isa(Obj.STR)) {
return ColorFactory.valueOf(val.str());
} else {
return null;
}
}
public static Color objToColorEx(Obj val, String message) {
Color c = objToColor(val);
if (c == null) {
throw new ValueError("Error loading color: " + message + "\nwhen reading: " + val.repr());
} else {
return c;
}
}
public static Color objToColorEx(Obj val) {
Color c = objToColor(val);
if (c == null) {
throw new ValueError("Error loading color when reading: " + val.repr());
} else {
return c;
}
}
}
|
3e0abd40d64893a31de592c14f46dc0c6ad95b47 | 2,642 | java | Java | src/main/java/net/thesimpleteam/simplebot/commands/moderation/UnbanCommand.java | TheSimpleTeam/SimpleBot | 8f95641695a432a5ab414e07baf73558ccdcd166 | [
"MIT"
] | null | null | null | src/main/java/net/thesimpleteam/simplebot/commands/moderation/UnbanCommand.java | TheSimpleTeam/SimpleBot | 8f95641695a432a5ab414e07baf73558ccdcd166 | [
"MIT"
] | 16 | 2021-09-27T13:35:15.000Z | 2022-03-20T10:46:27.000Z | src/main/java/net/thesimpleteam/simplebot/commands/moderation/UnbanCommand.java | TheSimpleTeam/SimpleBot | 8f95641695a432a5ab414e07baf73558ccdcd166 | [
"MIT"
] | null | null | null | 55.041667 | 407 | 0.663891 | 4,547 | package net.thesimpleteam.simplebot.commands.moderation;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import net.thesimpleteam.simplebot.SimpleBot;
import net.thesimpleteam.simplebot.enums.CommandCategories;
import net.thesimpleteam.simplebot.utils.MessageHelper;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.Permission;
public class UnbanCommand extends Command {
public UnbanCommand() {
this.name = "unban";
this.arguments = "arguments.unban";
this.aliases = new String[]{"pardon"};
this.category = CommandCategories.STAFF.category;
this.help = "help.unban";
this.guildOnly = true;
this.example = "285829396009451522 wrong person";
this.userPermissions = new Permission[]{Permission.BAN_MEMBERS};
this.botPermissions = new Permission[]{Permission.BAN_MEMBERS};
}
@Override
protected void execute(CommandEvent event) {
String[] args = event.getArgs().split("\\s+");
if (args.length < 1) {
MessageHelper.syntaxError(event, this, "information.unban");
return;
}
if(args[0].replaceAll("\\D+", "").isEmpty()){
event.reply(new MessageBuilder(MessageHelper.getEmbed(event, "error.commands.IDNull", null, null, null).build()).build());
return;
}
SimpleBot.getJda().retrieveUserById(args[0].replaceAll("\\D+", "")).queue(user -> event.getGuild().retrieveBanList().queue(banList -> {
if(banList.stream().anyMatch(banUser -> user.getId().equals(banUser.getUser().getId()))) {
event.getGuild().unban(user).queue(unused -> {
SimpleBot.getServerConfig().tempBan().remove(new StringBuilder().append(user.getId()).append("-").append(event.getGuild().getId()).toString());
event.reply(new MessageBuilder(MessageHelper.getEmbed(event, "success.unban", null, null, null, user.getName(), args.length == 1 ? MessageHelper.translateMessage(event, "text.commands.reasonNull") : new StringBuilder().append(MessageHelper.translateMessage(event, "text.commands.reason")).append(" ").append(event.getArgs().substring(args[0].length() + 1)).toString()).build()).build());
});
return;
}
event.reply(new MessageBuilder(MessageHelper.getEmbed(event, "error.unban", null, null, null, user.getName()).build()).build());
}), userNull -> event.reply(new MessageBuilder(MessageHelper.getEmbed(event, "error.commands.userNull", null, null, null).build()).build()));
}
}
|
3e0abd7a470e04be58ef5dc5c10ae2509155fb13 | 407 | java | Java | src/main/java/com/caul/modules/user/controller/LoginDispathController.java | sdliang1013/account-import | fb155fbe9877a7f1d32dd214decb252b248da9f1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/caul/modules/user/controller/LoginDispathController.java | sdliang1013/account-import | fb155fbe9877a7f1d32dd214decb252b248da9f1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/caul/modules/user/controller/LoginDispathController.java | sdliang1013/account-import | fb155fbe9877a7f1d32dd214decb252b248da9f1 | [
"Apache-2.0"
] | null | null | null | 21.421053 | 62 | 0.695332 | 4,548 | package com.caul.modules.user.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginDispathController {
@RequestMapping(value = "/login")
public String toManage() {
return "/login";
}
@RequestMapping(value = "/main")
public String toMain() {
return "/main";
}
} |
3e0abda1ebe51f9c1a037f1d264c87b700bf7e04 | 1,861 | java | Java | restclient-core/src/main/java/com/mercadolibre/restclient/cache/CacheCallback.java | mercadolibre/java-restclient | e3204d2d1620d372b56a44204319245776712ee5 | [
"Apache-2.0"
] | 31 | 2017-06-26T17:29:15.000Z | 2022-03-08T12:43:08.000Z | restclient-core/src/main/java/com/mercadolibre/restclient/cache/CacheCallback.java | mercadolibre/java-restclient | e3204d2d1620d372b56a44204319245776712ee5 | [
"Apache-2.0"
] | 3 | 2018-10-16T19:03:03.000Z | 2020-11-06T11:14:28.000Z | restclient-core/src/main/java/com/mercadolibre/restclient/cache/CacheCallback.java | mercadolibre/java-restclient | e3204d2d1620d372b56a44204319245776712ee5 | [
"Apache-2.0"
] | 11 | 2017-06-13T16:01:24.000Z | 2022-02-10T22:30:17.000Z | 26.585714 | 108 | 0.745298 | 4,549 | package com.mercadolibre.restclient.cache;
import com.mercadolibre.restclient.Request;
import com.mercadolibre.restclient.Response;
import com.mercadolibre.restclient.ResponseCallbackFuture;
import com.mercadolibre.restclient.async.*;
import static com.mercadolibre.restclient.log.LogUtil.log;
/**
* @author mlabarinas
*/
public class CacheCallback<T extends Response> implements Callback<T> {
protected Request request;
private ResponseCallbackFuture future;
public CacheCallback(Request request) {
this(request, new ResponseCallbackFuture());
}
protected CacheCallback(Request request, ResponseCallbackFuture future) {
this.request = request;
this.future = future;
}
public void success(T response) {
if (response == null) {
request.byPassCache(true);
Action.resend(request, writeBackAction());
} else if (!response.getCacheControl().isExpired()) {
successAction(response);
} else if (request.getCache().allowStaleResponse() && response.getCacheControl().isFreshForRevalidate()) {
request.byPassCache(true);
StaleRequestQueue.enqueue(request);
successAction(response);
} else {
request.byPassCache(true);
Action.resend(request, errorWriteBackAction(response));
}
}
public void failure(Throwable e) {
log.error("Failure in cache fetch", e);
request.byPassCache(true);
Action.resend(request, writeBackAction());
}
protected void successAction(T response) {
future.setDone(response, null);
}
protected HTTPCallback<T> writeBackAction() {
return new WriteBackHTTPCallback<>(request, future);
}
protected HTTPCallback<T> errorWriteBackAction(T response) {
return new ErrorWriteBackHTTPCallback<>(request, future, response);
}
public void cancel() {
future.setCancelled(true);
}
public final ResponseCallbackFuture getFuture() {
return future;
}
}
|
3e0abe06541513c99b4fff4a17c2718d34d587d8 | 6,451 | java | Java | app/src/main/java/com/netsun/labuy/fragment/OrderManagerFragment.java | yljnet/Labuy | 5c7d7f408c73e1e1b59022da6672a8f665aa26a4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/netsun/labuy/fragment/OrderManagerFragment.java | yljnet/Labuy | 5c7d7f408c73e1e1b59022da6672a8f665aa26a4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/netsun/labuy/fragment/OrderManagerFragment.java | yljnet/Labuy | 5c7d7f408c73e1e1b59022da6672a8f665aa26a4 | [
"Apache-2.0"
] | null | null | null | 37.289017 | 116 | 0.618044 | 4,550 | package com.netsun.labuy.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.netsun.labuy.activity.OrderInfoActivity;
import com.netsun.labuy.activity.OrderManagerActivity;
import com.netsun.labuy.R;
import com.netsun.labuy.adapter.OrderManagerItemAdapter;
import com.netsun.labuy.utils.HttpUtils;
import com.netsun.labuy.utils.MyApplication;
import com.netsun.labuy.utils.OrderInfo;
import com.netsun.labuy.utils.PublicFunc;
import com.netsun.labuy.utils.SpaceItemDecoration;
import com.netsun.labuy.utils.UpRefreshLayout;
import com.netsun.labuy.utils.Utility;
import org.litepal.util.LogUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by Administrator on 2017/3/24.
*/
public class OrderManagerFragment extends Fragment {
View view;
UpRefreshLayout orderManagerRefreshLayout;
RecyclerView orderRecyclerView;
List<OrderInfo> orderInfos;
OrderManagerItemAdapter adapter;
String title;
int mode;
int currentPage = 1;
Handler ItemClickHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
int position = msg.arg1;
if (position < orderInfos.size()) {
OrderInfo info = orderInfos.get(position);
if (info.getOrderId() != null && !info.getOrderId().isEmpty()) {
Intent intent = new Intent(getActivity(), OrderInfoActivity.class);
intent.putExtra("order_id", info.getOrderId());
startActivity(intent);
}
}
}
}
};
public String getTitle() {
return this.title;
}
public static OrderManagerFragment newInstance(String title, int mode) {
Bundle args = new Bundle();
args.putString("title", title);
args.putInt("mode", mode);
OrderManagerFragment fragment = new OrderManagerFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
this.title = bundle.getString("title");
this.mode = bundle.getInt("mode");
}
orderInfos = new ArrayList<OrderInfo>();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.layout_order_list, container, false);
orderManagerRefreshLayout = (UpRefreshLayout) view.findViewById(R.id.order_manager_refresh_layout);
orderRecyclerView = (RecyclerView) view.findViewById(R.id.id_order_recycle);
orderRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new OrderManagerItemAdapter(orderInfos);
adapter.setHandler(ItemClickHandler);
orderRecyclerView.setAdapter(adapter);
int space = getResources().getDimensionPixelSize(R.dimen.verital_space);
orderRecyclerView.addItemDecoration(new SpaceItemDecoration(space));
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getOrderInfos(currentPage);
orderManagerRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
currentPage++;
getOrderInfos(currentPage);
}
});
}
public void getOrderInfos(int page) {
PublicFunc.showProgress(getActivity());
String url = null;
if (mode == OrderManagerActivity.ORDER_ALL) {
url = PublicFunc.host + "app.php/Order?token=" + MyApplication.token + "&page=" + page;
} else if (mode == OrderManagerActivity.ORDER_UNPAY) {
url = PublicFunc.host + "app.php/Order?token=" + MyApplication.token + "&page=" + page + "&payStatus=0";
} else if (mode == OrderManagerActivity.ORDER_PAYED) {
url = PublicFunc.host + "app.php/Order?token=" + MyApplication.token + "&page=" + page + "&payStatus=1";
} else {
url = PublicFunc.host + "app.php/Order?token=" + MyApplication.token + "&page=" + page;
}
LogUtil.d(MyApplication.TAG, url);
HttpUtils.get(url, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
orderManagerRefreshLayout.refreshFinish(UpRefreshLayout.REFRESH_FAIL);
if (currentPage > 1)
currentPage--;
if (getActivity() == null) return;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
PublicFunc.closeProgress();
}
});
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String resStr = response.body().string();
ArrayList<OrderInfo> result = Utility.handleOrderListResponse(resStr);
if (result != null) {
for (OrderInfo orderInfo : result) {
orderInfos.add(orderInfo);
}
} else {
currentPage--;
}
if (getActivity() == null) return;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
PublicFunc.closeProgress();
adapter.notifyDataSetChanged();
}
});
}
});
}
}
|
3e0abe8fac8bd3f154a08d6fc1622e100c8e7692 | 1,132 | java | Java | plugins/jadaptive-ssh-management/src/main/java/com/jadaptive/plugins/ssh/management/commands/users/UserManagementCommandFactory.java | ludup/jadaptive-builder | 4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293 | [
"Apache-2.0"
] | 2 | 2020-11-08T00:41:02.000Z | 2021-08-21T02:40:53.000Z | plugins/jadaptive-ssh-management/src/main/java/com/jadaptive/plugins/ssh/management/commands/users/UserManagementCommandFactory.java | ludup/jadaptive-app-builder | 4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293 | [
"Apache-2.0"
] | null | null | null | plugins/jadaptive-ssh-management/src/main/java/com/jadaptive/plugins/ssh/management/commands/users/UserManagementCommandFactory.java | ludup/jadaptive-app-builder | 4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293 | [
"Apache-2.0"
] | null | null | null | 36.516129 | 115 | 0.832155 | 4,551 | package com.jadaptive.plugins.ssh.management.commands.users;
import org.pf4j.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jadaptive.api.permissions.AccessDeniedException;
import com.jadaptive.api.user.UserService;
import com.jadaptive.plugins.sshd.PluginCommandFactory;
import com.jadaptive.plugins.sshd.commands.AbstractAutowiredCommandFactory;
import com.sshtools.server.vsession.CommandFactory;
import com.sshtools.server.vsession.ShellCommand;
@Extension
public class UserManagementCommandFactory extends AbstractAutowiredCommandFactory implements PluginCommandFactory {
static Logger log = LoggerFactory.getLogger(UserManagementCommandFactory.class);
@Override
public CommandFactory<ShellCommand> buildFactory() throws AccessDeniedException {
tryCommand("users", Users.class, UserService.READ_PERMISSION);
tryCommand("create-user", CreateUser.class, UserService.READ_WRITE_PERMISSION);
tryCommand("update-user", UpdateUser.class, UserService.READ_WRITE_PERMISSION);
tryCommand("delete-user", DeleteUser.class, UserService.READ_WRITE_PERMISSION);
return this;
}
} |
3e0abf6935637fb9d9758601ef7a0814f25c6117 | 19,899 | java | Java | modules/json/src/main/java/org/picketlink/json/jose/JWEBuilder.java | backslash47/picketlink | 37da2e30df13e50d3bd7e4476f947961d8318515 | [
"Apache-2.0"
] | 77 | 2015-01-04T09:34:46.000Z | 2022-02-18T10:53:09.000Z | modules/json/src/main/java/org/picketlink/json/jose/JWEBuilder.java | backslash47/picketlink | 37da2e30df13e50d3bd7e4476f947961d8318515 | [
"Apache-2.0"
] | 47 | 2015-01-05T17:01:28.000Z | 2019-06-10T13:40:51.000Z | modules/json/src/main/java/org/picketlink/json/jose/JWEBuilder.java | backslash47/picketlink | 37da2e30df13e50d3bd7e4476f947961d8318515 | [
"Apache-2.0"
] | 74 | 2015-01-06T13:49:55.000Z | 2022-02-02T09:48:32.000Z | 36.511927 | 128 | 0.661792 | 4,552 | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.picketlink.json.jose;
import static org.picketlink.json.JsonConstants.COMMON.ALG;
import static org.picketlink.json.JsonConstants.COMMON.ENC;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_CONTENT_TYPE;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_JSON_WEB_KEY;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_JWK_SET_URL;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_TYPE;
import static org.picketlink.json.JsonConstants.COMMON.KEY_ID;
import static org.picketlink.json.JsonConstants.JWE.CEK_BITLENGTH;
import static org.picketlink.json.JsonConstants.JWE.COMPRESSION_ALG;
import static org.picketlink.json.JsonConstants.JWK.X509_CERTIFICATE_CHAIN;
import static org.picketlink.json.JsonConstants.JWK.X509_CERTIFICATE_SHA1_THUMBPRINT;
import static org.picketlink.json.JsonConstants.JWK.X509_CERTIFICATE_SHA256_THUMBPRINT;
import static org.picketlink.json.JsonConstants.JWK.X509_URL;
import static org.picketlink.json.JsonMessages.MESSAGES;
import static org.picketlink.json.util.Base64Util.b64Decode;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Constructor;
import java.util.Iterator;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
/**
* JSON Web Encryption (JWE) header Builder.
*
* <p>
* Supports build of all Principal Registered Parameter Names of the JWE specification:
*
* <ul>
* <li>{@link #type(String) alg}</li>
* <li>{@link #contentType(String) typ}</li>
* <li>{@link #algorithm(String) cty}</li>
* <li>{@link #encryptionAlgorithm(String, int) enc}</li>
* <li>{@link #compressionAlgorithm(String) zip}</li>
* <li>{@link #keys(JWKSet) keys}</li>
* <li>{@link #JWKSet(String) jku}</li>
* <li>{@link #X509URL(String) x5u}</li>
* <li>{@link #X509CertificateChain(String...) x5c}</li>
* <li>{@link #X509CertificateSHA1Thumbprint(String) x5t}</li>
* <li>{@link #X509CertificateSHA256Thumbprint(String) x5t#S256}</li>
* </ul>
*
* <p>
* Example header:
*
* <pre>
* {
* "alg":"RSA1_5",
* "kid":"2011-04-29",
* "enc":"A128CBC-HS256",
* "jku":"https://server.example.com/keys.jwks"
* }
* </pre>
*
* @param <T> the generic type
* @param <B> the generic type
* @author Giriraj Sharma
*/
public class JWEBuilder<T extends JWE, B extends JWEBuilder<?, ?>> {
private final JsonObjectBuilder headerBuilder;
private final Class<T> tokenType;
/**
* Instantiates a new JWE builder.
*/
public JWEBuilder() {
this((Class<T>) JWE.class);
}
/**
* Instantiates a new {@link org.picketlink.json.jose.JWE} builder.
*
* @param tokenType the token type
*/
protected JWEBuilder(Class<T> tokenType) {
this.tokenType = tokenType;
this.headerBuilder = Json.createObjectBuilder();
}
/**
* Gets the token type.
*
* @return the token type
*/
protected Class<T> getTokenType() {
return this.tokenType;
}
/**
* Gets the header builder.
*
* @return the header builder
*/
protected JsonObjectBuilder getHeaderBuilder() {
return this.headerBuilder;
}
/**
* Sets the type of JSON Web Encryption
* <p>
* The typ (type) Header Parameter is used by JWS or JWE to declare the MIME Media Type [IANA.MediaTypes] of this complete
* JWS or JWE object. This is intended for use by the application when more than one kind of object could be present in an
* application data structure that can contain a JWS or JWE object; the application can use this value to disambiguate among
* the different kinds of objects that might be present. Use of this Header Parameter is OPTIONAL.
*
* @param type the String type
* @return
*/
public JWEBuilder<T, B> type(String type) {
header(HEADER_TYPE, type);
return this;
}
/**
* Sets the content type of JSON Web Encryption
*
* <p>
* The cty (content type) Header Parameter is used by JWS or JWE applications to declare the MIME Media Type
* [IANA.MediaTypes] of the secured content (the payload) or encrypted plaintext. This is intended for use by the
* application when more than one kind of object could be present in the JWS payload or JWE encrypted plaintext; the
* application can use this value to disambiguate among the different kinds of objects that might be present. Use of this
* Header Parameter is OPTIONAL.
*
* @param contentType the String content type
* @return
*/
public JWEBuilder<T, B> contentType(String contentType) {
header(HEADER_CONTENT_TYPE, contentType);
return this;
}
/**
* Sets the algorithm used to encrypt or determine the value of the Content Encryption Key (CEK).
*
* <p>
* The alg (algorithm) Header Parameter identifies the cryptographic algorithm used to secure the JWS or JWE. The signature,
* MAC, or plaintext value is not valid if the alg value does not represent a supported algorithm, or if there is not a key
* for use with that algorithm associated with the party that digitally signed or MACed the content. alg values should
* either be registered in the IANA JSON Web Signature and Encryption Algorithms registry defined in [JWA] or be a value
* that contains a Collision-Resistant Name. The alg value is a case-sensitive string containing a StringOrURI value.
*
* <ul>
* <li>RSA1_5
* <li>RSA-OAEP
* <li>RSA-OAEP-256
* </ul>
*
* @param algorithm the algorithm as a string
* @return
*/
public JWEBuilder<T, B> algorithm(String algorithm) {
header(ALG, algorithm);
return this;
}
/**
* Sets the encryption algorithm used to encrypt the Plaintext to produce the Ciphertext.
*
* <p>
* The enc (encryption algorithm) Header Parameter identifies the content encryption algorithm used to encrypt the Plaintext
* to produce the Ciphertext. This algorithm MUST be an AEAD algorithm with a specified key length. The recipient MUST
* reject the JWE if the enc value does not represent a supported algorithm. enc values should either be registered in the
* IANA JSON Web Signature and Encryption Algorithms registry defined in [JWA] or be a value that contains a
* Collision-Resistant Name. The enc value is a case-sensitive string containing a StringOrURI value.
*
* <ul>
* <li>ENC_A128CBC_HS256
* <li>ENC_A192CBC_HS384
* <li>ENC_A256CBC_HS512
* <li>ENC_A128GCM
* <li>ENC_A192GCM
* <li>ENC_A256GCM
* </ul>
*
* @param encAlgorithm the encryption algorithm
* @param cekBitLength the content encryption key bit length
* @return
*/
public JWEBuilder<T, B> encryptionAlgorithm(String encAlgorithm, int cekBitLength) {
header(ENC, encAlgorithm);
header(CEK_BITLENGTH, cekBitLength);
return this;
}
/**
* Sets the key identifier used to determine the private key needed to decrypt the JWE.
*
* <p>
* The kid (key ID) member can be used to match a specific key. This can be used, for instance, to choose among a set of
* keys within a JWK Set during key rollover. The structure of the kid value is unspecified. When kid values are used within
* a JWK Set, different keys within the JWK Set SHOULD use distinct kid values. (One example in which different keys might
* use the same kid value is if they have different kty (key type) values but are considered to be equivalent alternatives
* by the application using them.) The kid value is a case-sensitive string. Use of this member is OPTIONAL.
*
* @param keyId the key id
* @return
*/
public JWEBuilder<T, B> keyIdentifier(String keyId) {
header(KEY_ID, keyId);
return this;
}
/**
* Sets the compression algorithm. The zip (compression algorithm) applied to the Plaintext before encryption, if any. The
* zip value defined by this specification is:
*
* <ul>
* <li>DEF - Compression with the DEFLATE [RFC1951] algorithm</li>
* </ul>
*
* <p>
* Other values MAY be used. Compression algorithm values can be registered in the IANA JSON Web Encryption Compression
* Algorithm registry defined in [JWA]. The zip value is a case-sensitive string. If no zip parameter is present, no
* compression is applied to the Plaintext before encryption.
*
* @param zipAlgorithm the zip algorithm
* @return
*/
public JWEBuilder<T, B> compressionAlgorithm(String zipAlgorithm) {
header(COMPRESSION_ALG, zipAlgorithm);
return this;
}
/**
* Sets the JSON Web Key Set.
*
* <p>
* The JWK (JSON Web Key) Header Parameter is the public key that corresponds to the key used to digitally sign the JWS.
* This key is represented as a JSON Web Key [JWK]. Use of this Header Parameter is OPTIONAL.
*
* @param keySet the key set
* @return
*/
public JWEBuilder<T, B> keys(JWKSet keySet) {
header(HEADER_JSON_WEB_KEY, keySet.getJsonObject().getJsonArray(HEADER_JSON_WEB_KEY));
return this;
}
/**
* Returns the JWK Set consisting of JWK Keys.
*
* <p>
* The JWK Keys contains the public key to which the JWE was encrypted; this can be used to determine the private key needed
* to decrypt the JWE.
*
* @param keys the keys
* @return
*/
public JWEBuilder<T, B> keys(JWK... keys) {
JWKSet jwkSet = new JWKSet(keys);
return keys(jwkSet);
}
/**
* Updates the {@link org.picketlink.json.jose.JWE} JSON with the JWKSetURL.
*
* <p>
* The jku (JWK Set URL) Header Parameter is a URI [RFC3986] that refers to a resource for a set of JSON-encoded public
* keys, one of which corresponds to the key used to digitally sign the JWS or encrypt plaintext using JWE. The keys MUST be
* encoded as a JSON Web Key Set (JWK Set) [JWK]. The protocol used to acquire the resource MUST provide integrity
* protection; an HTTP GET request to retrieve the JWK Set MUST use TLS [RFC2818, RFC5246]; the identity of the server MUST
* be validated, as per Section 6 of RFC 6125 [RFC6125]. Use of this Header Parameter is OPTIONAL.
*
* @param jwkSetURL the JWK Set URL
* @return
*/
public JWEBuilder<T, B> JWKSet(String jwkSetURL) {
header(HEADER_JWK_SET_URL, jwkSetURL);
return this;
}
/**
* Sets the x509 URL.
*
* <p>
* The x5u (X.509 URL) member is a URI [RFC3986] that refers to a resource for an X.509 public key certificate or
* certificate chain [RFC5280]. The identified resource MUST provide a representation of the certificate or certificate
* chain that conforms to RFC 5280 [RFC5280] in PEM encoded form [RFC1421]. The key in the first certificate MUST match the
* public key represented by other members of the JWK. The protocol used to acquire the resource MUST provide integrity
* protection; an HTTP GET request to retrieve the certificate MUST use TLS [RFC2818, RFC5246]; the identity of the server
* MUST be validated, as per Section 6 of RFC 6125 [RFC6125]. Use of this member is OPTIONAL.
*
* @param x509URL the x509 url
* @return
*/
public JWEBuilder<T, B> X509URL(String x509URL) {
header(X509_URL, x509URL);
return this;
}
/**
* Sets the x509 certificate chain.
*
* <p>
* The x5c (X.509 Certificate Chain) member contains a chain of one or more PKIX certificates [RFC5280]. The certificate
* chain is represented as a JSON array of certificate value strings. Each string in the array is a base64 encoded
* ([RFC4648] Section 4 -- not base64url encoded) DER [ITU.X690.1994] PKIX certificate value. The PKIX certificate
* containing the key value MUST be the first certificate. This MAY be followed by additional certificates, with each
* subsequent certificate being the one used to certify the previous one. The key in the first certificate MUST match the
* public key represented by other members of the JWK. Use of this member is OPTIONAL.
*
* @param certificates the certificates
* @return
*/
public JWEBuilder<T, B> X509CertificateChain(String... certificates) {
if (certificates.length == 1) {
header(X509_CERTIFICATE_CHAIN, certificates[0]);
} else if (certificates.length > 1) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (String operation : certificates) {
arrayBuilder.add(operation);
}
this.headerBuilder.add(X509_CERTIFICATE_CHAIN, arrayBuilder);
}
return this;
}
/**
* Sets the x509 SHA1 certificate thumbprint.
*
* <p>
* The x5t (X.509 Certificate SHA-1 Thumbprint) member is a base64url encoded SHA-1 thumbprint (a.k.a. digest) of the DER
* encoding of an X.509 certificate [RFC5280]. The key in the certificate MUST match the public key represented by other
* members of the JWK. Use of this member is OPTIONAL.
*
* @param sha1Thumbprint the sha1 thumbprint
* @return
*/
public JWEBuilder<T, B> X509CertificateSHA1Thumbprint(String sha1Thumbprint) {
header(X509_CERTIFICATE_SHA1_THUMBPRINT, sha1Thumbprint);
return this;
}
/**
* Sets the x509 SHA256 certificate thumbprint.
*
* <p>
* The x5t#S256 (X.509 Certificate SHA-256 Thumbprint) member is a base64url encoded SHA-256 thumbprint (a.k.a. digest) of
* the DER encoding of an X.509 certificate [RFC5280]. The key in the certificate MUST match the public key represented by
* other members of the JWK. Use of this member is OPTIONAL.
*
* @param sha256Thumbprint the sha256 thumbprint
* @return
*/
public JWEBuilder<T, B> X509CertificateSHA256Thumbprint(String sha256Thumbprint) {
header(X509_CERTIFICATE_SHA256_THUMBPRINT, sha256Thumbprint);
return this;
}
/**
* Updates {@link org.picketlink.json.jose.JWE} Header with the specified string header and its value(s).
*
* @param name the name
* @param value the value
* @return
*/
public JWEBuilder<T, B> header(String name, String... value) {
setString(this.headerBuilder, name, value);
return this;
}
/**
* Updates {@link org.picketlink.json.jose.JWE} Header with the specified string header and its value(s).
*
* @param name the name
* @param value the value
* @return
*/
public JWEBuilder<T, B> header(String name, int... value) {
setInt(this.headerBuilder, name, value);
return this;
}
/**
* Updates {@link org.picketlink.json.jose.JWE} Header with the specified string header and its value(s).
*
* @param name the name
* @param value the value
* @return
*/
public JWEBuilder<T, B> header(String name, List<JsonObject> value) {
setJsonObject(this.headerBuilder, name, value);
return this;
}
/**
* Updates {@link org.picketlink.json.jose.JWE} Header with the specified string header and its value(s).
*
* @param name the name
* @param value the value
* @return
*/
public JWEBuilder<T, B> header(String name, JsonArray value) {
setJsonObject(this.headerBuilder, name, value);
return this;
}
/**
* Updates the {@link javax.json.JsonObjectBuilder} with specified header parameter and its value(s).
*
* @param builderuilder
* @param name the name
* @param values the values
* @return
*/
private JWEBuilder<T, B> setString(JsonObjectBuilder builder, String name, String... values) {
if (values.length == 1) {
builder.add(name, values[0]);
} else if (values.length > 1) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (String value : values) {
arrayBuilder.add(value.toString());
}
builder.add(name, arrayBuilder);
}
return this;
}
/**
* Updates the {@link javax.json.JsonObjectBuilder} with specified header parameter and its value(s).
*
* @param builderuilder
* @param name the name
* @param values the values
* @return
*/
private JWEBuilder<T, B> setInt(JsonObjectBuilder builder, String name, int... values) {
if (values.length == 1) {
builder.add(name, values[0]);
} else if (values.length > 1) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (int value : values) {
arrayBuilder.add(value);
}
builder.add(name, arrayBuilder);
}
return this;
}
/**
* POpulates the specified header parameter of {@link javax.json.JsonObjectBuilder} with its collection.
*
* @param builderuilder
* @param name the name
* @param values the values
* @return
*/
private JWEBuilder<T, B> setJsonObject(JsonObjectBuilder builder, String name, List<JsonObject> values) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
Iterator<JsonObject> iterator = values.iterator();
while (iterator.hasNext()) {
arrayBuilder.add(iterator.next());
}
builder.add(name, arrayBuilder);
return this;
}
/**
* <p>
* Updates the the specified header of {@link javax.json.JsonObjectBuilder} with the {@link javax.json.JsonArray}.
* </p>
*
* @param builder the builder
* @param name the name of the header or claim
* @param values the values for the header or claim
* @return
*/
private JWEBuilder<T, B> setJsonObject(JsonObjectBuilder builder, String name, JsonArray values) {
builder.add(name, values);
return this;
}
/**
* Builds {@link javax.json.JsonObjectBuilder}.
*
* @return
*/
public T build() {
return build(this.headerBuilder.build());
}
/**
* Builds String JSON.
*
* @param json the json
* @return
*/
public T build(String json) {
byte[] keyParameters = b64Decode(json);
return build(Json.createReader(new ByteArrayInputStream(keyParameters)).readObject());
}
/**
* Builds {@link javax.json.JsonObject}.
*
* @param headersObject the headers object
* @return
*/
protected T build(JsonObject headersObject) {
try {
Constructor<T> constructor = this.tokenType.getDeclaredConstructor(JsonObject.class);
constructor.setAccessible(true);
return constructor.newInstance(headersObject);
} catch (Exception e) {
throw MESSAGES.couldNotCreateToken(this.tokenType, e);
}
}
} |
3e0abfa27e7f02cc57a0c2e72de4d5c4dfb78964 | 2,276 | java | Java | ga/src/main/java/nl/tudelft/serg/evosql/EvoSQLConfiguration.java | SERG-Delft/evosql | 5a90e4d4a360642c160013a049d8532c43962c3c | [
"Apache-2.0"
] | 70 | 2018-02-26T18:24:10.000Z | 2022-03-14T04:09:25.000Z | ga/src/main/java/nl/tudelft/serg/evosql/EvoSQLConfiguration.java | SERG-Delft/evosql | 5a90e4d4a360642c160013a049d8532c43962c3c | [
"Apache-2.0"
] | 40 | 2018-02-06T14:53:46.000Z | 2019-08-23T20:26:02.000Z | ga/src/main/java/nl/tudelft/serg/evosql/EvoSQLConfiguration.java | SERG-Delft/evosql | 5a90e4d4a360642c160013a049d8532c43962c3c | [
"Apache-2.0"
] | 9 | 2018-03-06T18:28:50.000Z | 2020-08-03T06:29:02.000Z | 32.056338 | 108 | 0.742091 | 4,553 | package nl.tudelft.serg.evosql;
public class EvoSQLConfiguration {
public static int MAX_ROW_QTY = 4;
public static int MIN_ROW_QTY = 1;
public static int MAX_STRING_LENGTH = 50;
public static int MIN_CHAR_ORD = (int)' ';
public static int MAX_CHAR_ORD = (int)'~';
public static int ABS_INT_RANGE = 1000;
public static int ABS_DOUBLE_RANGE = 1000;
public static String MIN_DATE = "1980-01-01 00:00:00.000";
public static String MAX_DATE = "2070-01-01 00:00:00.000";
public static double NULL_PROBABIBLITY = 0.1;
public static double MUTATE_NULL_PROBABIBLITY = 0.1;
public static double SEED_INSERT_PROBABIBLITY = 0.5;
public static double SEED_CHANGE_PROBABIBLITY = 0.5;
public static int POPULATION_SIZE = 50;
public static double P_CLONE_POPULATION = 0.6;
/** Probability to insert a new row in a Table **/
public static double P_INSERT_PROBABILITY = 1d/3d;
/** Probability to duplicate a row in a Table **/
public static double P_INSERT_DUPLICATE_PROBABILITY = 1d/3d;
/** Probability to delete a row in a Table **/
public static double P_DELETE_PROBABILITY = 1d/3d;
/** Probability to change a row in a Table **/
public static double P_CHANGE_PROBABILITY = 1d/2d;
/** Probability to crossover **/
public static double P_CROSSOVER = 3d/4d;
/** Probability to mutation **/
public static double P_MUTATION = 3d/4d;
public static enum MutationType {
PERCENTAGE, // in the mutation probability is a user-provided percentage
// (See P_MUTATION)
LENGTH, // in the case the mutation probability is equal to 1/LENGTH
// (where LENGTH either the number of Tables and/or Rows)
};
public static MutationType MUTATION = MutationType.LENGTH;
/** Feature config **/
public static boolean USE_LITERAL_SEEDING = true;
public static boolean USE_DYNAMIC_JOIN_SEEDING = true;
public static boolean USE_USED_COLUMN_EXTRACTION = true;
public static boolean MUTATION_PROBABILITY_FOR_EACH_ROW = false;
public static boolean USE_SEEDED_RANDOM_BASELINE = true;
/** Evaluation time **/
public static long MS_EXECUTION_TIME = 120000; // 2 min = 120000, 5 min = 300000, Half an hour = 1800000 ms
/** Testing, should this be moved to special testing classes? **/
public static int TEST_MAX_ITERATIONS = 5;
}
|
3e0ac020acb997ea79693a4b2c6645658f7bde03 | 372 | java | Java | src/maspack/function/MIMOFunction.java | aaltolab/artisynth_core | ce01443e067f20a3f5874c05e9b97019ca7c7ca7 | [
"Apache-2.0",
"BSD-3-Clause"
] | 30 | 2018-03-14T17:19:31.000Z | 2022-02-08T15:02:38.000Z | src/maspack/function/MIMOFunction.java | aaltolab/artisynth_core | ce01443e067f20a3f5874c05e9b97019ca7c7ca7 | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2018-05-02T21:17:34.000Z | 2021-11-30T04:17:57.000Z | src/maspack/function/MIMOFunction.java | aaltolab/artisynth_core | ce01443e067f20a3f5874c05e9b97019ca7c7ca7 | [
"Apache-2.0",
"BSD-3-Clause"
] | 18 | 2018-04-11T13:37:51.000Z | 2022-02-01T21:17:57.000Z | 26.571429 | 77 | 0.72043 | 4,554 | /**
* Copyright (c) 2014, by the Authors: Antonio Sanchez (UBC)
*
* This software is freely available under a 2-clause BSD license. Please see
* the LICENSE file in the ArtiSynth distribution directory for details.
*/
package maspack.function;
public interface MIMOFunction {
void eval(double[] in, double[] out);
int getInputSize();
int getOutputSize();
}
|
3e0ac09c1222d9d3bd5172c432f4c3cdf6039ad2 | 560 | java | Java | src/main/java/cc/heikafei/test/maxTest.java | ninggucaishen/java50 | dac0ea02f3885accb6c9e73f9bfbb7bfa1e325de | [
"MIT"
] | null | null | null | src/main/java/cc/heikafei/test/maxTest.java | ninggucaishen/java50 | dac0ea02f3885accb6c9e73f9bfbb7bfa1e325de | [
"MIT"
] | null | null | null | src/main/java/cc/heikafei/test/maxTest.java | ninggucaishen/java50 | dac0ea02f3885accb6c9e73f9bfbb7bfa1e325de | [
"MIT"
] | null | null | null | 19.310345 | 52 | 0.551786 | 4,555 | package cc.heikafei.test;
import java.util.Scanner;
/**
* 利用Java中的Math类工具包实现三个数的大小比较
*/
public class maxTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入a:");
int a = sc.nextInt();
System.out.print("请输入b:");
int b = sc.nextInt();
System.out.print("请输入c:");
int c = sc.nextInt();
sc.close();
int max1 = Math.max(a, b);
int max2 = Math.max(max1, c);
System.out.println("a,b,c三个数中最大值为:" + max2);
}
}
|
3e0ac0c870ec363de1c003cd6e8d0dce79801288 | 2,271 | java | Java | src/main/java/com/dotcms/rest/api/v1/system/ConfigurationResource.java | ncodeitbharath/gradle | e1b40495088d0233933756b788bb0ea98a347d70 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/dotcms/rest/api/v1/system/ConfigurationResource.java | ncodeitbharath/gradle | e1b40495088d0233933756b788bb0ea98a347d70 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/dotcms/rest/api/v1/system/ConfigurationResource.java | ncodeitbharath/gradle | e1b40495088d0233933756b788bb0ea98a347d70 | [
"Apache-2.0"
] | null | null | null | 31.541667 | 90 | 0.76266 | 4,556 | package com.dotcms.rest.api.v1.system;
import java.io.Serializable;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.dotcms.repackage.javax.ws.rs.GET;
import com.dotcms.repackage.javax.ws.rs.Path;
import com.dotcms.repackage.javax.ws.rs.Produces;
import com.dotcms.repackage.javax.ws.rs.core.Context;
import com.dotcms.repackage.javax.ws.rs.core.MediaType;
import com.dotcms.repackage.javax.ws.rs.core.Response;
import com.dotcms.repackage.org.glassfish.jersey.server.JSONP;
import com.dotcms.rest.ResponseEntityView;
import com.dotcms.rest.annotation.NoCache;
import com.dotcms.rest.exception.mapper.ExceptionMapperUtil;
import com.liferay.util.LocaleUtil;
/**
* This Jersey end-point provides access to configuration parameters that are
* set through the property files for dotCMS configuration:
* {@code dotmarketing-config.properties}, and
* {@code dotcms-config-cluster.properties}. By default, <b>not all
* configuration properties are available through this end-point</b>, they must
* be programmatically read and returned.
*
* @author Jose Castro
* @version 3.7
* @since Jul 22, 2016
*
*/
@Path("/v1/configuration")
@SuppressWarnings("serial")
public class ConfigurationResource implements Serializable {
private final ConfigurationHelper helper;
/**
* Default constructor.
*/
public ConfigurationResource() {
this.helper = ConfigurationHelper.INSTANCE;
}
/**
* Returns the list of system properties that are set through the dotCMS
* configuration files.
*
* @param request
* - The {@link HttpServletRequest} object.
* @return The JSON representation of configuration parameters.
*/
@GET
@JSONP
@NoCache
@Produces({ MediaType.APPLICATION_JSON, "application/javascript" })
public Response list(@Context final HttpServletRequest request) {
try {
final Locale locale = LocaleUtil.getLocale(request);
final Map<String, Object> configPropsMap = helper.getConfigProperties(request, locale);
return Response.ok(new ResponseEntityView(configPropsMap)).build();
} catch (Exception e) {
// In case of unknown error, so we report it as a 500
return ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
|
3e0ac10fab86c8cabd413d7dd3d18826506b0e15 | 812 | java | Java | ef-sdk-java/src/main/java/mx/emite/sdk/clientes/operaciones/ef/FacturaEmite.java | emitefacturacion-mx/ef-sdk-java | 05dbf11239aa4edfa25ec7bc9a677c9fc652dafa | [
"Apache-2.0"
] | null | null | null | ef-sdk-java/src/main/java/mx/emite/sdk/clientes/operaciones/ef/FacturaEmite.java | emitefacturacion-mx/ef-sdk-java | 05dbf11239aa4edfa25ec7bc9a677c9fc652dafa | [
"Apache-2.0"
] | null | null | null | ef-sdk-java/src/main/java/mx/emite/sdk/clientes/operaciones/ef/FacturaEmite.java | emitefacturacion-mx/ef-sdk-java | 05dbf11239aa4edfa25ec7bc9a677c9fc652dafa | [
"Apache-2.0"
] | null | null | null | 29 | 86 | 0.814039 | 4,557 | package mx.emite.sdk.clientes.operaciones.ef;
import mx.emite.sdk.clientes.ClienteJson;
import mx.emite.sdk.clientes.operaciones.Operacion;
import mx.emite.sdk.ef.request.FacturaEmiteRequest;
import mx.emite.sdk.ef.response.FacturaEmiteResponse;
import mx.emite.sdk.enums.Proveedor;
import mx.emite.sdk.enums.Rutas;
import mx.emite.sdk.errores.ApiException;
public class FacturaEmite extends Operacion<FacturaEmiteRequest,FacturaEmiteResponse>{
@Deprecated
public FacturaEmite(final ClienteJson cliente) {
super(cliente,Proveedor.SCOT,Rutas.FACTURAEMITE);
}
@Override
@Deprecated
public FacturaEmiteResponse ejecuta(FacturaEmiteRequest request) throws ApiException{
final String ruta = creaRuta(request);
return procesa(this.getCliente().post(ruta,request,FacturaEmiteResponse.class));
}
}
|
3e0ac22d34b96c290638982fee51b9b4066da9b4 | 532 | java | Java | project_letsmeet/src/edu/unh/letsmeet/parse/TravelLocationJson.java | kkroboth/Intentional-Concurrent-Programming | 4a01ca42d29155b94f6a8af5928333c6058d1861 | [
"Apache-2.0"
] | null | null | null | project_letsmeet/src/edu/unh/letsmeet/parse/TravelLocationJson.java | kkroboth/Intentional-Concurrent-Programming | 4a01ca42d29155b94f6a8af5928333c6058d1861 | [
"Apache-2.0"
] | null | null | null | project_letsmeet/src/edu/unh/letsmeet/parse/TravelLocationJson.java | kkroboth/Intentional-Concurrent-Programming | 4a01ca42d29155b94f6a8af5928333c6058d1861 | [
"Apache-2.0"
] | null | null | null | 26.6 | 60 | 0.75 | 4,558 | package edu.unh.letsmeet.parse;
import edu.unh.letsmeet.storage.TravelLocation;
public class TravelLocationJson {
public int id;
public String country;
public String city;
public double population;
public float[] latlong;
public TravelLocationJson(TravelLocation travelLocation) {
this.id = travelLocation.getId();
this.country = travelLocation.getCountry();
this.city = travelLocation.getCity();
this.population = travelLocation.getPopulation();
this.latlong = travelLocation.getLatlong();
}
}
|
3e0ac3bb09badaae0aadcf2d48a0fc56eea734c2 | 386 | java | Java | app/src/main/java/com/aichifan/app4myqa/EventHistoricalActivity.java | Aichifan/App4MyQA | 80dee490added6226776e39c5b747c7a2461340f | [
"MIT"
] | 2 | 2016-09-02T01:29:52.000Z | 2017-02-19T14:59:26.000Z | app/src/main/java/com/aichifan/app4myqa/EventHistoricalActivity.java | Aichifan/App4MyQA | 80dee490added6226776e39c5b747c7a2461340f | [
"MIT"
] | null | null | null | app/src/main/java/com/aichifan/app4myqa/EventHistoricalActivity.java | Aichifan/App4MyQA | 80dee490added6226776e39c5b747c7a2461340f | [
"MIT"
] | null | null | null | 25.733333 | 80 | 0.756477 | 4,559 | package com.aichifan.app4myqa;
import android.os.Bundle;
public class EventHistoricalActivity extends UserInfoActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_historical);
setHeader(getString(R.string.EventHistoricalActivityTitle), true, true);
}
}
|
3e0ac3e4191615a27af3d153815da178ee842831 | 758 | java | Java | src/main/java/org/hire/me/vo/ErrorVo.java | alanstos/e-url | fea1a8aa26cff28af69f68e230290c8f2091b964 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/hire/me/vo/ErrorVo.java | alanstos/e-url | fea1a8aa26cff28af69f68e230290c8f2091b964 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/hire/me/vo/ErrorVo.java | alanstos/e-url | fea1a8aa26cff28af69f68e230290c8f2091b964 | [
"Apache-2.0"
] | null | null | null | 18.95 | 72 | 0.733509 | 4,560 | package org.hire.me.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ErrorVo extends BaseVo{
@JsonProperty("err_code")
private String errCode;
@JsonProperty("description")
private String descricao;
public static BaseVo parse(String alias, String code, String message) {
return new ErrorVo(alias, code, message);
}
public ErrorVo(String alias,String errCode, String descricao) {
super(alias);
this.errCode = errCode;
this.descricao = descricao;
}
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
|
3e0ac43b771f7c927598c0909f461331f5281961 | 2,941 | java | Java | CoreCompatibility/Core_1_11_R1/src/main/java/me/deecaad/core/compatibility/v1_11_R1.java | MechanicsMain/MechanicsMain | 71d4642052f9b41d1ef0a5a30da5b5f04850639e | [
"MIT"
] | 11 | 2021-12-26T02:25:09.000Z | 2022-03-27T09:26:57.000Z | CoreCompatibility/Core_1_11_R1/src/main/java/me/deecaad/core/compatibility/v1_11_R1.java | MechanicsMain/MechanicsMain | 71d4642052f9b41d1ef0a5a30da5b5f04850639e | [
"MIT"
] | 57 | 2021-12-25T20:06:27.000Z | 2022-03-29T12:40:50.000Z | CoreCompatibility/Core_1_11_R1/src/main/java/me/deecaad/core/compatibility/v1_11_R1.java | MechanicsMain/MechanicsMain | 71d4642052f9b41d1ef0a5a30da5b5f04850639e | [
"MIT"
] | 1 | 2022-03-27T09:27:01.000Z | 2022-03-27T09:27:01.000Z | 32.677778 | 102 | 0.714043 | 4,561 | package me.deecaad.core.compatibility;
import me.deecaad.core.compatibility.block.BlockCompatibility;
import me.deecaad.core.compatibility.block.Block_1_11_R1;
import me.deecaad.core.compatibility.entity.EntityCompatibility;
import me.deecaad.core.compatibility.entity.Entity_1_11_R1;
import me.deecaad.core.compatibility.nbt.NBTCompatibility;
import me.deecaad.core.compatibility.nbt.NBT_1_11_R1;
import me.deecaad.core.utils.LogLevel;
import me.deecaad.core.utils.ReflectionUtil;
import net.minecraft.server.v1_11_R1.EntityPlayer;
import net.minecraft.server.v1_11_R1.Packet;
import net.minecraft.server.v1_11_R1.PlayerConnection;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_11_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftPlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
public class v1_11_R1 implements ICompatibility {
static {
if (ReflectionUtil.getMCVersion() != 11) {
me.deecaad.core.MechanicsCore.debug.log(
LogLevel.ERROR,
"Loaded " + v1_11_R1.class + " when not using Minecraft 11",
new InternalError()
);
}
}
private final EntityCompatibility entityCompatibility;
private final BlockCompatibility blockCompatibility;
private final NBTCompatibility nbtCompatibility;
public v1_11_R1() {
entityCompatibility = new Entity_1_11_R1();
blockCompatibility = new Block_1_11_R1();
nbtCompatibility = new NBT_1_11_R1();
}
@Override
public int getPing(@NotNull Player player) {
return getEntityPlayer(player).ping;
}
@Override
public Entity getEntityById(@NotNull World world, int entityId) {
net.minecraft.server.v1_11_R1.Entity e = ((CraftWorld) world).getHandle().getEntity(entityId);
return e == null ? null : e.getBukkitEntity();
}
@Override
public void sendPackets(Player player, Object packet) {
getEntityPlayer(player).playerConnection.sendPacket((Packet<?>) packet);
}
@Override
public void sendPackets(Player player, Object... packets) {
PlayerConnection playerConnection = getEntityPlayer(player).playerConnection;
for (Object packet : packets) {
playerConnection.sendPacket((Packet<?>) packet);
}
}
@Override
public @NotNull NBTCompatibility getNBTCompatibility() {
return nbtCompatibility;
}
@Nonnull
@Override
public EntityCompatibility getEntityCompatibility() {
return entityCompatibility;
}
@Nonnull
@Override
public BlockCompatibility getBlockCompatibility() {
return blockCompatibility;
}
@Override
public @NotNull EntityPlayer getEntityPlayer(@NotNull Player player) {
return ((CraftPlayer) player).getHandle();
}
} |
3e0ac49cfab3b7d7fff859af69696825b29ef472 | 574 | java | Java | src/main/java/com/cd/ums/common/supcan/freeform/FreeForm.java | zyanming2002/ums | 99662f8a84641c3a938781984c47bfb758747fdd | [
"Apache-1.1"
] | null | null | null | src/main/java/com/cd/ums/common/supcan/freeform/FreeForm.java | zyanming2002/ums | 99662f8a84641c3a938781984c47bfb758747fdd | [
"Apache-1.1"
] | null | null | null | src/main/java/com/cd/ums/common/supcan/freeform/FreeForm.java | zyanming2002/ums | 99662f8a84641c3a938781984c47bfb758747fdd | [
"Apache-1.1"
] | null | null | null | 20.5 | 94 | 0.721254 | 4,562 | /**
* Copyright © 2012-2016 <a href="https://github.com/cd/ums">Ums</a> All rights reserved.
*/
package com.cd.ums.common.supcan.freeform;
import com.cd.ums.common.supcan.common.Common;
import com.cd.ums.common.supcan.common.properties.Properties;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* 硕正FreeForm
* @author WangZhen
* @version 2013-11-04
*/
@XStreamAlias("FreeForm")
public class FreeForm extends Common {
public FreeForm() {
super();
}
public FreeForm(Properties properties) {
this();
this.properties = properties;
}
}
|
3e0ac5de2d1a2a4e52b635d0767b290aa9553cf8 | 2,017 | java | Java | src/main/java/tech/jhipster/lite/generator/server/springboot/dbmigration/flyway/infrastructure/primary/rest/FlywayResource.java | Hawkurane/jhipster-lite | 3207ac3008f61ea78e55eca076a89986fd00a03f | [
"Apache-2.0"
] | null | null | null | src/main/java/tech/jhipster/lite/generator/server/springboot/dbmigration/flyway/infrastructure/primary/rest/FlywayResource.java | Hawkurane/jhipster-lite | 3207ac3008f61ea78e55eca076a89986fd00a03f | [
"Apache-2.0"
] | 170 | 2022-02-14T12:10:26.000Z | 2022-03-31T20:03:42.000Z | src/main/java/tech/jhipster/lite/generator/server/springboot/dbmigration/flyway/infrastructure/primary/rest/FlywayResource.java | Hawkurane/jhipster-lite | 3207ac3008f61ea78e55eca076a89986fd00a03f | [
"Apache-2.0"
] | null | null | null | 45.840909 | 118 | 0.811601 | 4,564 | package tech.jhipster.lite.generator.server.springboot.dbmigration.flyway.infrastructure.primary.rest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.jhipster.lite.generator.project.domain.Project;
import tech.jhipster.lite.generator.project.infrastructure.primary.dto.ProjectDTO;
import tech.jhipster.lite.generator.server.springboot.dbmigration.flyway.application.FlywayApplicationService;
import tech.jhipster.lite.technical.infrastructure.primary.annotation.GeneratorStep;
@RestController
@RequestMapping("/api/servers/spring-boot/databases/migration/flyway")
@Tag(name = "Spring Boot - Database")
class FlywayResource {
private final FlywayApplicationService flywayApplicationService;
public FlywayResource(FlywayApplicationService flywayApplicationService) {
this.flywayApplicationService = flywayApplicationService;
}
@Operation(summary = "Add Flyway")
@ApiResponse(responseCode = "500", description = "An error occurred while adding Flyway")
@PostMapping("/init")
@GeneratorStep(id = "flyway")
public void init(@RequestBody ProjectDTO projectDTO) {
Project project = ProjectDTO.toProject(projectDTO);
flywayApplicationService.init(project);
}
@Operation(summary = "Add User and Authority changelogs")
@ApiResponse(responseCode = "500", description = "An error occurred while adding changelogs for user and authority")
@PostMapping("/user")
@GeneratorStep(id = "flyway-user-and-authority-changelogs")
public void addUserAndAuthority(@RequestBody ProjectDTO projectDTO) {
Project project = ProjectDTO.toProject(projectDTO);
flywayApplicationService.addUserAuthorityChangelog(project);
}
}
|
3e0ac66fb9a3e3fad726e52bf2b43facd5f12edf | 15,492 | java | Java | app/src/main/java/org/wikipedia/gallery/GalleryItemFragment.java | uniqx/apps-android-wikipedia | bf06da540acc030fa95dbacbb861d38c78f705cf | [
"Apache-2.0"
] | 1 | 2020-02-05T18:51:45.000Z | 2020-02-05T18:51:45.000Z | app/src/main/java/org/wikipedia/gallery/GalleryItemFragment.java | felixyf0124/FandroidsWiki | 059ef7331e5ba07f6d774239380b9992d5b5d173 | [
"Apache-2.0"
] | 3 | 2020-07-16T17:23:26.000Z | 2021-05-08T03:13:29.000Z | app/src/main/java/org/wikipedia/gallery/GalleryItemFragment.java | felixyf0124/FandroidsWiki | 059ef7331e5ba07f6d774239380b9992d5b5d173 | [
"Apache-2.0"
] | 1 | 2020-01-31T08:34:59.000Z | 2020-01-31T08:34:59.000Z | 38.827068 | 124 | 0.633553 | 4,565 | package org.wikipedia.gallery;
import android.graphics.Bitmap;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.VideoView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.samples.zoomable.DoubleTapGestureListener;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.FragmentUtil;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.page.Namespace;
import org.wikipedia.page.PageTitle;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.FileUtil;
import org.wikipedia.util.PermissionUtil;
import org.wikipedia.util.ShareUtil;
import org.wikipedia.util.StringUtil;
import org.wikipedia.util.log.L;
import org.wikipedia.views.ZoomableDraweeViewWithBackground;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import static org.wikipedia.util.PermissionUtil.hasWriteExternalStoragePermission;
import static org.wikipedia.util.PermissionUtil.requestWriteStorageRuntimePermissions;
public class GalleryItemFragment extends Fragment {
public static final String ARG_PAGETITLE = "pageTitle";
public static final String ARG_GALLERY_ITEM = "galleryItem";
public static final String ARG_FEED_FEATURED_IMAGE = "feedFeaturedImage";
public static final String ARG_AGE = "age";
public interface Callback {
void onDownload(@NonNull GalleryItem item);
void onShare(@NonNull GalleryItem item, @Nullable Bitmap bitmap, @NonNull String subject, @NonNull PageTitle title);
}
@BindView(R.id.gallery_item_progress_bar) ProgressBar progressBar;
@BindView(R.id.gallery_video_container) View videoContainer;
@BindView(R.id.gallery_video) VideoView videoView;
@BindView(R.id.gallery_video_thumbnail) SimpleDraweeView videoThumbnail;
@BindView(R.id.gallery_video_play_button) View videoPlayButton;
@BindView(R.id.gallery_image) ZoomableDraweeViewWithBackground imageView;
@Nullable private Unbinder unbinder;
private MediaController mediaController;
private int age;
@NonNull private WikipediaApp app = WikipediaApp.getInstance();
@Nullable private GalleryActivity parentActivity;
@Nullable private PageTitle pageTitle;
@SuppressWarnings("NullableProblems") @NonNull private PageTitle imageTitle;
@Nullable private GalleryItem galleryItem;
@Nullable public GalleryItem getGalleryItem() {
return galleryItem;
}
public static GalleryItemFragment newInstance(@Nullable PageTitle pageTitle, @NonNull GalleryItem galleryItem) {
GalleryItemFragment f = new GalleryItemFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_PAGETITLE, pageTitle);
args.putSerializable(ARG_GALLERY_ITEM, galleryItem);
if (galleryItem instanceof FeaturedImageGalleryItem) {
args.putBoolean(ARG_FEED_FEATURED_IMAGE, true);
args.putInt(ARG_AGE, ((FeaturedImageGalleryItem) galleryItem).getAge());
}
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
galleryItem = (GalleryItem) getArguments().getSerializable(ARG_GALLERY_ITEM);
pageTitle = getArguments().getParcelable(ARG_PAGETITLE);
imageTitle = new PageTitle(Namespace.FILE.toLegacyString(),
StringUtil.removeNamespace(galleryItem.getTitles().getCanonical()),
new WikiSite(galleryItem.getFilePage()));
if (getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE)) {
age = getArguments().getInt(ARG_AGE);
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery_item, container, false);
unbinder = ButterKnife.bind(this, rootView);
imageView.setTapListener(new DoubleTapGestureListener(imageView) {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
parentActivity.toggleControls();
return true;
}
});
GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources())
.setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
.build();
imageView.setHierarchy(hierarchy);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
parentActivity = (GalleryActivity) getActivity();
loadMedia();
}
@Override
public void onDestroyView() {
imageView.setController(null);
imageView.setOnClickListener(null);
videoThumbnail.setController(null);
videoThumbnail.setOnClickListener(null);
unbinder.unbind();
unbinder = null;
super.onDestroyView();
}
private void updateProgressBar(boolean visible, boolean indeterminate, int value) {
progressBar.setIndeterminate(indeterminate);
if (!indeterminate) {
progressBar.setProgress(value);
}
progressBar.setVisibility(visible ? View.VISIBLE : View.GONE);
}
@Override
public void onDestroy() {
super.onDestroy();
app.getRefWatcher().watch(this);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (!isAdded()) {
return;
}
menu.findItem(R.id.menu_gallery_visit_page).setEnabled(galleryItem != null);
menu.findItem(R.id.menu_gallery_share).setEnabled(galleryItem != null
&& !TextUtils.isEmpty(galleryItem.getThumbnailUrl()) && imageView.getDrawable() != null);
menu.findItem(R.id.menu_gallery_save).setEnabled(galleryItem != null
&& !TextUtils.isEmpty(galleryItem.getThumbnailUrl()) && imageView.getDrawable() != null);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_gallery_visit_page:
if (galleryItem != null) {
parentActivity.finishWithPageResult(imageTitle);
}
return true;
case R.id.menu_gallery_save:
handleImageSaveRequest();
return true;
case R.id.menu_gallery_share:
shareImage();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Notifies this fragment that the current position of its containing ViewPager has changed.
*
* @param fragmentPosition This fragment's position in the ViewPager.
* @param pagerPosition The pager's current position that is displayed to the user.
*/
public void onUpdatePosition(int fragmentPosition, int pagerPosition) {
if (fragmentPosition != pagerPosition) {
// update stuff if our position is not "current" within the ViewPager...
if (mediaController != null) {
if (videoView.isPlaying()) {
videoView.pause();
}
mediaController.hide();
}
} else {
// update stuff if our position is "current"
if (mediaController != null) {
if (!videoView.isPlaying()) {
videoView.start();
}
}
}
}
private void handleImageSaveRequest() {
if (!(hasWriteExternalStoragePermission(this.getActivity()))) {
requestWriteExternalStoragePermission();
} else {
saveImage();
}
}
private void requestWriteExternalStoragePermission() {
requestWriteStorageRuntimePermissions(this,
Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION);
}
/**
* Load the actual media associated with our gallery item into the UI.
*/
private void loadMedia() {
if (FileUtil.isVideo(galleryItem.getType())) {
loadVideo();
} else {
loadImage(galleryItem.getPreferredSizedImageUrl());
}
parentActivity.supportInvalidateOptionsMenu();
parentActivity.layOutGalleryDescription();
}
private View.OnClickListener videoThumbnailClickListener = new View.OnClickListener() {
private boolean loading = false;
@Override
public void onClick(View v) {
if (loading) {
return;
}
loading = true;
L.d("Loading video from url: " + galleryItem.getOriginalVideoSource().getOriginalUrl());
videoView.setVisibility(View.VISIBLE);
mediaController = new MediaController(parentActivity);
updateProgressBar(true, true, 0);
videoView.setMediaController(mediaController);
videoView.setOnPreparedListener((mp) -> {
updateProgressBar(false, true, 0);
// ...update the parent activity, which will trigger us to start playing!
parentActivity.layOutGalleryDescription();
// hide the video thumbnail, since we're about to start playback
videoThumbnail.setVisibility(View.GONE);
videoPlayButton.setVisibility(View.GONE);
// and start!
videoView.start();
loading = false;
});
videoView.setOnErrorListener((mp, what, extra) -> {
updateProgressBar(false, true, 0);
FeedbackUtil.showMessage(getActivity(),
R.string.gallery_error_video_failed);
videoView.setVisibility(View.GONE);
videoThumbnail.setVisibility(View.VISIBLE);
videoPlayButton.setVisibility(View.VISIBLE);
loading = false;
return true;
});
videoView.setVideoURI(Uri.parse(galleryItem.getOriginalVideoSource().getOriginalUrl()));
}
};
private void loadVideo() {
videoContainer.setVisibility(View.VISIBLE);
videoPlayButton.setVisibility(View.VISIBLE);
videoView.setVisibility(View.GONE);
if (TextUtils.isEmpty(galleryItem.getThumbnailUrl())) {
videoThumbnail.setVisibility(View.GONE);
} else {
// show the video thumbnail while the video loads...
videoThumbnail.setVisibility(View.VISIBLE);
videoThumbnail.setController(Fresco.newDraweeControllerBuilder()
.setUri(galleryItem.getThumbnail().getSource())
.setAutoPlayAnimations(true)
.setControllerListener(new BaseControllerListener<ImageInfo>() {
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
updateProgressBar(false, true, 0);
}
@Override
public void onFailure(String id, Throwable throwable) {
updateProgressBar(false, true, 0);
}
})
.build());
}
videoThumbnail.setOnClickListener(videoThumbnailClickListener);
}
private void loadImage(String url) {
imageView.setVisibility(View.VISIBLE);
L.v("Loading image from url: " + url);
updateProgressBar(true, true, 0);
imageView.setDrawBackground(false);
imageView.setController(Fresco.newDraweeControllerBuilder()
.setUri(url)
.setAutoPlayAnimations(true)
.setControllerListener(new BaseControllerListener<ImageInfo>() {
@Override
public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
imageView.setDrawBackground(true);
updateProgressBar(false, true, 0);
parentActivity.supportInvalidateOptionsMenu();
}
@Override
public void onFailure(String id, Throwable throwable) {
updateProgressBar(false, true, 0);
FeedbackUtil.showMessage(getActivity(), R.string.gallery_error_draw_failed);
L.d(throwable);
}
})
.build());
}
private void shareImage() {
if (galleryItem == null) {
return;
}
new ImagePipelineBitmapGetter(galleryItem.getPreferredSizedImageUrl()){
@Override
public void onSuccess(@Nullable Bitmap bitmap) {
if (!isAdded()) {
return;
}
if (callback() != null) {
callback().onShare(galleryItem, bitmap, getShareSubject(), imageTitle);
}
}
}.get();
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION:
if (PermissionUtil.isPermitted(grantResults)) {
saveImage();
} else {
L.e("Write permission was denied by user");
FeedbackUtil.showMessage(getActivity(),
R.string.gallery_save_image_write_permission_rationale);
}
break;
default:
throw new RuntimeException("unexpected permission request code " + requestCode);
}
}
@Nullable
private String getShareSubject() {
if (getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE)) {
return ShareUtil.getFeaturedImageShareSubject(requireContext(), age);
}
return pageTitle != null ? pageTitle.getDisplayText() : null;
}
private void saveImage() {
if (galleryItem != null && callback() != null) {
callback().onDownload(galleryItem);
}
}
@Nullable private Callback callback() {
return FragmentUtil.getCallback(this, Callback.class);
}
}
|
3e0ac6db32eba864cb27c335553ade8a1bf5cfc6 | 8,974 | java | Java | src/main/java/net/floodlightcontroller/debugevent/Event.java | gauravsingh0110/CoSEL | 1d065b08495e4734353cf4a17df9287a2a2489c0 | [
"Apache-2.0"
] | 24 | 2015-02-11T22:52:24.000Z | 2021-05-11T02:24:03.000Z | src/main/java/net/floodlightcontroller/debugevent/Event.java | gauravsingh0110/CoSEL | 1d065b08495e4734353cf4a17df9287a2a2489c0 | [
"Apache-2.0"
] | 2 | 2016-08-24T08:17:40.000Z | 2019-09-16T09:02:29.000Z | src/main/java/net/floodlightcontroller/debugevent/Event.java | gauravsingh0110/CoSEL | 1d065b08495e4734353cf4a17df9287a2a2489c0 | [
"Apache-2.0"
] | 11 | 2015-02-24T06:28:36.000Z | 2022-02-23T03:21:35.000Z | 40.423423 | 99 | 0.437709 | 4,566 | package net.floodlightcontroller.debugevent;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.floodlightcontroller.debugevent.IDebugEventService.EventColumn;
import net.floodlightcontroller.devicemanager.SwitchPort;
import net.floodlightcontroller.packet.IPv4;
import org.openflow.protocol.OFFlowMod;
import org.openflow.util.HexString;
public class Event {
long timestamp;
long threadId;
String threadName;
Object eventData;
private Map<String, String> returnMap;
public Event(long timestamp, long threadId, String threadName, Object eventData) {
super();
this.timestamp = timestamp;
this.threadId = threadId;
this.threadName = threadName;
this.eventData = eventData;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public long getThreadId() {
return threadId;
}
public void setThreadId(long threadId) {
this.threadId = threadId;
}
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
public Object geteventData() {
return eventData;
}
public void seteventData(Object eventData) {
this.eventData = eventData;
}
@Override
public String toString() {
return "Event [timestamp=" + timestamp + ", threadId=" + threadId
+ ", eventData=" + eventData.toString() + "]";
}
public Map<String, String> getFormattedEvent(Class<?> eventClass, String moduleEventName) {
if (eventClass == null || !eventClass.equals(eventData.getClass())) {
returnMap = new HashMap<String, String>();
returnMap.put("Error", "null event data or event-class does not match event-data");
return returnMap;
}
// return cached value if there is one
if (returnMap != null)
return returnMap;
returnMap = new HashMap<String, String>();
returnMap.put("Timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.format(timestamp));
returnMap.put("Thread Id", String.valueOf(threadId));
returnMap.put("Thread Name", String.valueOf(threadName));
customFormat(eventClass, eventData, returnMap);
return returnMap;
}
private void customFormat(Class<?> clazz, Object eventData,
Map<String, String> retMap) {
for (Field f : clazz.getDeclaredFields()) {
EventColumn ec = f.getAnnotation(EventColumn.class);
if (ec == null) continue;
f.setAccessible(true);
try {
Object obj = f.get(eventData);
switch(ec.description()) {
case DPID:
retMap.put(ec.name(), HexString.toHexString((Long) obj));
break;
case MAC:
retMap.put(ec.name(), HexString.toHexString((Long) obj, 6));
break;
case IPv4:
retMap.put(ec.name(), IPv4.fromIPv4Address((Integer) obj));
break;
case FLOW_MOD_FLAGS:
int flags = (Integer)obj;
StringBuilder builder = new StringBuilder();
if (flags == 0) {
builder.append("None");
}
else {
if ((flags & OFFlowMod.OFPFF_SEND_FLOW_REM) != 0) {
builder.append("SEND_FLOW_REM ");
}
if ((flags & OFFlowMod.OFPFF_CHECK_OVERLAP) != 0) {
builder.append("CHECK_OVERLAP ");
}
if ((flags & OFFlowMod.OFPFF_EMERG) != 0) {
builder.append("EMERG ");
}
}
retMap.put(ec.name(), builder.toString());
break;
case LIST_IPV4:
@SuppressWarnings("unchecked")
List<Integer> ipv4Addresses = (List<Integer>)obj;
StringBuilder ipv4AddressesStr = new StringBuilder();
if (ipv4Addresses.size() == 0) {
ipv4AddressesStr.append("--");
} else {
for (Integer ipv4Addr : ipv4Addresses) {
ipv4AddressesStr.append(IPv4.fromIPv4Address(ipv4Addr.intValue()));
ipv4AddressesStr.append(" ");
}
}
retMap.put(ec.name(), ipv4AddressesStr.toString());
break;
case LIST_ATTACHMENT_POINT:
@SuppressWarnings("unchecked")
List<SwitchPort> aps = (List<SwitchPort>)obj;
StringBuilder apsStr = new StringBuilder();
if (aps.size() == 0) {
apsStr.append("--");
} else {
for (SwitchPort ap : aps) {
apsStr.append(HexString.toHexString(ap.getSwitchDPID()));
apsStr.append("/");
apsStr.append(ap.getPort());
apsStr.append(" ");
}
}
retMap.put(ec.name(), apsStr.toString());
break;
case LIST_OBJECT:
@SuppressWarnings("unchecked")
List<Object> obl = (List<Object>)obj;
StringBuilder sbldr = new StringBuilder();
if (obl.size() == 0) {
sbldr.append("--");
} else {
for (Object o : obl) {
sbldr.append(o.toString());
sbldr.append(" ");
}
}
retMap.put(ec.name(), sbldr.toString());
break;
case SREF_LIST_OBJECT:
@SuppressWarnings("unchecked")
SoftReference<List<Object>> srefListObj =
(SoftReference<List<Object>>)obj;
List<Object> ol = srefListObj.get();
if (ol != null) {
StringBuilder sb = new StringBuilder();
if (ol.size() == 0) {
sb.append("--");
} else {
for (Object o : ol) {
sb.append(o.toString());
sb.append(" ");
}
}
retMap.put(ec.name(), sb.toString());
} else {
retMap.put(ec.name(), "-- reference not available --");
}
break;
case SREF_OBJECT:
@SuppressWarnings("unchecked")
SoftReference<Object> srefObj = (SoftReference<Object>)obj;
if (srefObj == null) {
retMap.put(ec.name(), "--");
} else {
Object o = srefObj.get();
if (o != null) {
retMap.put(ec.name(), o.toString());
} else {
retMap.put(ec.name(),
"-- reference not available --");
}
}
break;
case STRING:
case OBJECT:
case PRIMITIVE:
default:
retMap.put(ec.name(), obj.toString());
}
} catch (ClassCastException e) {
retMap.put("Error", e.getMessage());
} catch (IllegalArgumentException e) {
retMap.put("Error", e.getMessage());
} catch (IllegalAccessException e) {
retMap.put("Error", e.getMessage());
}
}
}
}
|
3e0ac7329dbaea3b39adafa82b2fa218a30c7371 | 681 | java | Java | src/functions/Rent.java | lanka97/bightstar_enterprise | a308ea5070e6808a7b02169c523a6f35c333ca0d | [
"MIT"
] | null | null | null | src/functions/Rent.java | lanka97/bightstar_enterprise | a308ea5070e6808a7b02169c523a6f35c333ca0d | [
"MIT"
] | null | null | null | src/functions/Rent.java | lanka97/bightstar_enterprise | a308ea5070e6808a7b02169c523a6f35c333ca0d | [
"MIT"
] | null | null | null | 21.28125 | 79 | 0.650514 | 4,567 | /*
* 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 functions;
import DBconnection.DBConnection;
import DBconnection.DBConnection;
import java.sql.*;
//import java.sql.SQLException;
//import java.util.Date;
/**
*
* @author Lanka
*/
public class Rent {
public String rentID;
public String rentType;
public String rentDate;
public String rentDes;
public double payed;
public double total;
public int chequeNum;
public String officer;
}
|
3e0ac8592175858c36735b26472203eab458672c | 6,041 | java | Java | src/main/java/org/b3log/solo/processor/SearchProcessor.java | zxb222278/solo-blog | aad6006cb8c06d1ec33d28d64347ebaccdfbbaf8 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/b3log/solo/processor/SearchProcessor.java | zxb222278/solo-blog | aad6006cb8c06d1ec33d28d64347ebaccdfbbaf8 | [
"Apache-2.0"
] | 1 | 2022-01-21T23:30:41.000Z | 2022-01-21T23:30:41.000Z | src/main/java/org/b3log/solo/processor/SearchProcessor.java | zxb222278/solo-blog | aad6006cb8c06d1ec33d28d64347ebaccdfbbaf8 | [
"Apache-2.0"
] | null | null | null | 36.391566 | 150 | 0.70634 | 4,568 | /*
* Solo - A small and beautiful blogging system written in Java.
* Copyright (c) 2010-present, b3log.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.b3log.solo.processor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Latkes;
import org.b3log.latke.ioc.Inject;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.servlet.HttpMethod;
import org.b3log.latke.servlet.RequestContext;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.AbstractFreeMarkerRenderer;
import org.b3log.latke.servlet.renderer.TextXmlRenderer;
import org.b3log.latke.util.Paginator;
import org.b3log.solo.model.Article;
import org.b3log.solo.model.Common;
import org.b3log.solo.model.Option;
import org.b3log.solo.service.ArticleQueryService;
import org.b3log.solo.service.DataModelService;
import org.b3log.solo.service.OptionQueryService;
import org.b3log.solo.service.UserQueryService;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.owasp.encoder.Encode;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Search processor.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @version 1.1.1.3, Mar 19, 2019
* @since 2.4.0
*/
@RequestProcessor
public class SearchProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(SearchProcessor.class);
/**
* Article query service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Option query service.
*/
@Inject
private OptionQueryService optionQueryService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* DataModelService.
*/
@Inject
private DataModelService dataModelService;
/**
* Shows opensearch.xml.
*
* @param context the specified context
*/
@RequestProcessing(value = "/opensearch.xml", method = HttpMethod.GET)
public void showOpensearchXML(final RequestContext context) {
final TextXmlRenderer renderer = new TextXmlRenderer();
context.setRenderer(renderer);
try {
final InputStream resourceAsStream = SearchProcessor.class.getResourceAsStream("/opensearch.xml");
String content = IOUtils.toString(resourceAsStream, "UTF-8");
final JSONObject preference = optionQueryService.getPreference();
content = StringUtils.replace(content, "${blogTitle}", Jsoup.clean(preference.optString(Option.ID_C_BLOG_TITLE), Whitelist.none()));
content = StringUtils.replace(content, "${blogSubtitle}", Jsoup.clean(preference.optString(Option.ID_C_BLOG_SUBTITLE), Whitelist.none()));
content = StringUtils.replace(content, "${servePath}", Latkes.getServePath());
renderer.setContent(content);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Shows opensearch.xml failed", e);
}
}
/**
* Searches articles.
*
* @param context the specified context
*/
@RequestProcessing(value = "/search", method = HttpMethod.GET)
public void search(final RequestContext context) {
final HttpServletRequest request = context.getRequest();
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "common-template/search.ftl");
final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());
final Map<String, Object> dataModel = renderer.getDataModel();
dataModel.putAll(langs);
final int pageNum = Paginator.getPage(request);
String keyword = context.param(Common.KEYWORD);
if (StringUtils.isBlank(keyword)) {
keyword = "";
}
keyword = Encode.forHtml(keyword);
dataModel.put(Common.KEYWORD, keyword);
final JSONObject result = articleQueryService.searchKeyword(keyword, pageNum, 15);
final List<JSONObject> articles = (List<JSONObject>) result.opt(Article.ARTICLES);
try {
final JSONObject preference = optionQueryService.getPreference();
dataModelService.fillCommon(context, dataModel, preference);
dataModelService.fillFaviconURL(dataModel, preference);
dataModelService.fillUsite(dataModel);
dataModelService.setArticlesExProperties(context, articles, preference);
dataModel.put(Article.ARTICLES, articles);
final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION);
pagination.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION, pagination);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Search articles failed");
dataModel.put(Article.ARTICLES, Collections.emptyList());
}
}
}
|
3e0ac8d1db35f6aec248cbd2ddf45f7586f6cc5c | 617 | java | Java | corn/src/main/java/com/xiazhenyu/corn/coreTec/synchro/synNotExtends/Main.java | chenyusharp/corp | fe86d9d4778ca58cc38655d8ca9e0d1dac0c1b33 | [
"Apache-2.0"
] | null | null | null | corn/src/main/java/com/xiazhenyu/corn/coreTec/synchro/synNotExtends/Main.java | chenyusharp/corp | fe86d9d4778ca58cc38655d8ca9e0d1dac0c1b33 | [
"Apache-2.0"
] | null | null | null | corn/src/main/java/com/xiazhenyu/corn/coreTec/synchro/synNotExtends/Main.java | chenyusharp/corp | fe86d9d4778ca58cc38655d8ca9e0d1dac0c1b33 | [
"Apache-2.0"
] | null | null | null | 24.68 | 137 | 0.614263 | 4,569 | package com.xiazhenyu.corn.coreTec.synchro.synNotExtends;
/**
* Date: 2022/1/2
* <p>
* Description:
*
* @author xiazhenyu
*/
public class Main {
synchronized public void serviceMethod() {
try {
System.out.println("from main,begin threadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis());
Thread.sleep(3000);
System.out.println("from main,end threadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
3e0ac9100488a9b6d43e319fff4fd900f26451d0 | 643 | java | Java | src/test/java/TimeServiceTest.java | Antinomy/Cucumber-Selenium | ee3b3b1dce641ae05c407b338a0242dd7f953e52 | [
"MIT"
] | null | null | null | src/test/java/TimeServiceTest.java | Antinomy/Cucumber-Selenium | ee3b3b1dce641ae05c407b338a0242dd7f953e52 | [
"MIT"
] | null | null | null | src/test/java/TimeServiceTest.java | Antinomy/Cucumber-Selenium | ee3b3b1dce641ae05c407b338a0242dd7f953e52 | [
"MIT"
] | null | null | null | 23.814815 | 75 | 0.712286 | 4,570 | import domian.service.TimeService;
import org.hamcrest.core.StringStartsWith;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringStartsWith.startsWith;
/**
* Created by Antinomy on 15/7/2.
*/
public class TimeServiceTest {
@Test
public void testNow()
{
String now = TimeService.now();
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
assertThat(now, startsWith(today));
assertThat(now.length(), is(14));
}
}
|
3e0ac9abee3d929d1385aa79a8ab8bf598f60ec8 | 3,877 | java | Java | WallPanelApp/src/main/java/org/wallpanelproject/android/BrowserActivityNative.java | 7Cervide/WallTile | a08eb7218404d650e9d816f2554aafec367e55ba | [
"Apache-2.0"
] | 214 | 2017-04-13T12:52:38.000Z | 2022-03-10T21:21:39.000Z | WallPanelApp/src/main/java/org/wallpanelproject/android/BrowserActivityNative.java | quadportnick/homeDash | a08eb7218404d650e9d816f2554aafec367e55ba | [
"Apache-2.0"
] | 66 | 2017-04-17T20:08:50.000Z | 2022-03-27T20:33:49.000Z | WallPanelApp/src/main/java/org/wallpanelproject/android/BrowserActivityNative.java | quadportnick/homeDash | a08eb7218404d650e9d816f2554aafec367e55ba | [
"Apache-2.0"
] | 49 | 2017-04-21T21:05:05.000Z | 2022-02-24T14:46:41.000Z | 31.778689 | 95 | 0.605107 | 4,571 | package org.wallpanelproject.android;
import android.annotation.SuppressLint;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.os.Bundle;
import android.webkit.WebViewClient;
import org.wallpanelproject.android.R;
public class BrowserActivityNative extends BrowserActivity {
private WebView mWebView;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_browser);
mWebView = (WebView) findViewById(R.id.activity_browser_webview_native);
mWebView.setVisibility(View.VISIBLE);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebChromeClient(new WebChromeClient(){
Snackbar snackbar;
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (!displayProgress) return;
if(newProgress == 100 && snackbar != null){
snackbar.dismiss();
pageLoadComplete(view.getUrl());
return;
}
String text = "Loading "+ newProgress+ "% " + view.getUrl();
if(snackbar == null){
snackbar = Snackbar.make(view, text, Snackbar.LENGTH_INDEFINITE);
} else {
snackbar.setText(text);
}
snackbar.show();
}
});
mWebView.setWebViewClient(new WebViewClient(){
//If you will not use this method url links are open in new browser not in webview
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return true;
}
});
mWebView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
resetScreen();
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAppCacheEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
Log.i(TAG, webSettings.getUserAgentString());
super.onCreate(savedInstanceState);
}
@Override
protected void loadUrl(final String url) {
if (zoomLevel != 1.0) { mWebView.setInitialScale((int)(zoomLevel * 100)); }
mWebView.loadUrl(url);
}
@Override
protected void evaluateJavascript(final String js) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mWebView.evaluateJavascript(js, null);
}
}
@Override
protected void clearCache() {
mWebView.clearCache(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().removeAllCookies(null);
}
}
@Override
protected void reload() {
mWebView.reload();
}
}
|
3e0acbbc9dfb99f46ca85bd4f31eeb00e561b96c | 4,770 | java | Java | runescape-client/src/main/java/WorldMapIcon_1.java | GooseG17/runelite | dd8d252f44198372f5ed8573b44f15199a8b7432 | [
"BSD-2-Clause"
] | 5 | 2020-04-15T03:09:25.000Z | 2021-02-27T12:31:31.000Z | runescape-client/src/main/java/WorldMapIcon_1.java | GooseG17/runelite | dd8d252f44198372f5ed8573b44f15199a8b7432 | [
"BSD-2-Clause"
] | 1 | 2019-01-10T05:17:42.000Z | 2019-01-10T05:17:42.000Z | runescape-client/src/main/java/WorldMapIcon_1.java | GooseG17/runelite | dd8d252f44198372f5ed8573b44f15199a8b7432 | [
"BSD-2-Clause"
] | 114 | 2020-03-04T17:48:35.000Z | 2022-03-30T04:39:15.000Z | 24.587629 | 115 | 0.710901 | 4,572 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("g")
@Implements("WorldMapIcon_1")
public class WorldMapIcon_1 extends AbstractWorldMapIcon {
@ObfuscatedName("f")
@ObfuscatedGetter(
intValue = 399748255
)
@Export("objectDefId")
final int objectDefId;
@ObfuscatedName("i")
@ObfuscatedSignature(
signature = "Las;"
)
@Export("region")
final WorldMapRegion region;
@ObfuscatedName("y")
@ObfuscatedGetter(
intValue = 1594551933
)
@Export("element")
int element;
@ObfuscatedName("w")
@ObfuscatedSignature(
signature = "Law;"
)
@Export("label")
WorldMapLabel label;
@ObfuscatedName("p")
@ObfuscatedGetter(
intValue = 2144976415
)
@Export("subWidth")
int subWidth;
@ObfuscatedName("b")
@ObfuscatedGetter(
intValue = 649203899
)
@Export("subHeight")
int subHeight;
@ObfuscatedSignature(
signature = "(Lht;Lht;ILas;)V"
)
WorldMapIcon_1(Coord var1, Coord var2, int var3, WorldMapRegion var4) {
super(var1, var2);
this.objectDefId = var3;
this.region = var4;
this.init();
}
@ObfuscatedName("f")
@ObfuscatedSignature(
signature = "(B)I",
garbageValue = "63"
)
@Export("getElement")
public int getElement() {
return this.element;
}
@ObfuscatedName("i")
@ObfuscatedSignature(
signature = "(I)Law;",
garbageValue = "-1801186977"
)
@Export("getLabel")
WorldMapLabel getLabel() {
return this.label;
}
@ObfuscatedName("y")
@ObfuscatedSignature(
signature = "(I)I",
garbageValue = "-2033351231"
)
@Export("getSubWidth")
int getSubWidth() {
return this.subWidth;
}
@ObfuscatedName("w")
@ObfuscatedSignature(
signature = "(I)I",
garbageValue = "1873129621"
)
@Export("getSubHeight")
int getSubHeight() {
return this.subHeight;
}
@ObfuscatedName("n")
@ObfuscatedSignature(
signature = "(B)V",
garbageValue = "0"
)
@Export("init")
void init() {
this.element = Coord.getObjectDefinition(this.objectDefId).transform().mapIconId;
this.label = this.region.createMapLabel(GrandExchangeOfferUnitPriceComparator.WorldMapElement_get(this.element));
WorldMapElement var1 = GrandExchangeOfferUnitPriceComparator.WorldMapElement_get(this.getElement());
Sprite var2 = var1.getSpriteBool(false);
if (var2 != null) {
this.subWidth = var2.subWidth;
this.subHeight = var2.subHeight;
} else {
this.subWidth = 0;
this.subHeight = 0;
}
}
@ObfuscatedName("f")
@ObfuscatedSignature(
signature = "(II)Lij;",
garbageValue = "-754699522"
)
@Export("getParamDefinition")
public static ParamDefinition getParamDefinition(int var0) {
ParamDefinition var1 = (ParamDefinition)ParamDefinition.ParamDefinition_cached.get((long)var0);
if (var1 != null) {
return var1;
} else {
byte[] var2 = ParamDefinition.ParamDefinition_archive.takeFile(11, var0);
var1 = new ParamDefinition();
if (var2 != null) {
var1.decode(new Buffer(var2));
}
var1.postDecode();
ParamDefinition.ParamDefinition_cached.put(var1, (long)var0);
return var1;
}
}
@ObfuscatedName("f")
@ObfuscatedSignature(
signature = "(I)V",
garbageValue = "-1785574656"
)
static void method277() {
Tiles.Tiles_minPlane = 99;
class14.field88 = new byte[4][104][104];
Tiles.field498 = new byte[4][104][104];
Tiles.field494 = new byte[4][104][104];
Tiles.field493 = new byte[4][104][104];
Tiles.field501 = new int[4][105][105];
Tiles.field496 = new byte[4][105][105];
ArchiveLoader.field512 = new int[105][105];
UrlRequest.Tiles_hue = new int[104];
MenuAction.Tiles_saturation = new int[104];
PacketBufferNode.Tiles_lightness = new int[104];
Tiles.Tiles_hueMultiplier = new int[104];
Varcs.field1244 = new int[104];
}
@ObfuscatedName("gp")
@ObfuscatedSignature(
signature = "(B)V",
garbageValue = "57"
)
static void method296() {
int var0 = Players.Players_count;
int[] var1 = Players.Players_indices;
for (int var2 = 0; var2 < var0; ++var2) {
if (var1[var2] != Client.combatTargetPlayerIndex && var1[var2] != Client.localPlayerIndex) {
class14.addPlayerToScene(Client.players[var1[var2]], true);
}
}
}
@ObfuscatedName("kp")
@ObfuscatedSignature(
signature = "(Ljava/lang/String;B)V",
garbageValue = "75"
)
@Export("clanKickUser")
static final void clanKickUser(String var0) {
if (Calendar.clanChat != null) {
PacketBufferNode var1 = class2.getPacketBufferNode(ClientPacket.field2245, Client.packetWriter.isaacCipher);
var1.packetBuffer.writeByte(ViewportMouse.stringCp1252NullTerminatedByteSize(var0));
var1.packetBuffer.writeStringCp1252NullTerminated(var0);
Client.packetWriter.addNode(var1);
}
}
}
|
3e0accbead1bf06cf1a0d72c59a7a7a9a64b29db | 1,671 | java | Java | openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/XMappingOverride.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 104 | 2015-01-31T01:11:05.000Z | 2022-03-20T05:28:58.000Z | openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/XMappingOverride.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 56 | 2016-09-30T14:04:31.000Z | 2022-02-21T11:23:53.000Z | openjpa-persistence-jdbc/src/main/java/org/apache/openjpa/persistence/jdbc/XMappingOverride.java | marcomarcucci30/openjpa | 4937cfba77895995aef6e7b5374a8b54a914577c | [
"Apache-2.0"
] | 127 | 2015-01-11T14:18:46.000Z | 2022-03-23T13:46:58.000Z | 30.381818 | 79 | 0.737882 | 4,573 | /*
* 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.openjpa.persistence.jdbc;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.persistence.Column;
/**
* <p>Allows override of complex embedded or superclass mappings.</p>
*
* @author Abe White
* @since 0.4.0, 1.1.0
*/
@Target({ TYPE })
@Retention(RUNTIME)
public @interface XMappingOverride {
String name() default "";
Column[] columns() default {};
XJoinColumn[] joinColumns() default {};
ElementColumn[] elementColumns() default {};
ElementJoinColumn[] elementJoinColumns() default {};
KeyColumn[] keyColumns() default {};
KeyJoinColumn[] keyJoinColumns() default {};
ContainerTable containerTable() default @ContainerTable(specified = false);
}
|
3e0accc94f999cacbe4524c75a1fb2f1e7a80f63 | 4,311 | java | Java | maxkey-identitys/maxkey-synchronizers-workweixin/src/main/java/org/maxkey/synchronizer/workweixin/entity/WorkWeixinUsers.java | addstone/MaxKey | 7e4e5a622ee20f595c3c45b7ff86d2929b95f774 | [
"Apache-2.0"
] | 215 | 2021-03-16T04:40:04.000Z | 2022-03-30T23:35:23.000Z | maxkey-identitys/maxkey-synchronizers-workweixin/src/main/java/org/maxkey/synchronizer/workweixin/entity/WorkWeixinUsers.java | addstone/MaxKey | 7e4e5a622ee20f595c3c45b7ff86d2929b95f774 | [
"Apache-2.0"
] | 29 | 2020-07-14T06:22:53.000Z | 2021-01-03T09:42:26.000Z | maxkey-identitys/maxkey-synchronizers-workweixin/src/main/java/org/maxkey/synchronizer/workweixin/entity/WorkWeixinUsers.java | addstone/MaxKey | 7e4e5a622ee20f595c3c45b7ff86d2929b95f774 | [
"Apache-2.0"
] | 51 | 2021-03-16T03:52:57.000Z | 2022-03-11T07:48:52.000Z | 17.52439 | 75 | 0.716771 | 4,574 | /*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top]
*
* 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.maxkey.synchronizer.workweixin.entity;
public class WorkWeixinUsers {
String userid;
String name;
String mobile;
long[] department;
long[] order;
String position;
String gender;
String email;
long[] is_leader_in_dept;
String avatar;
String thumb_avatar;
String telephone;
String alias;
int status;
int isleader;
int enable;
String address;
int hide_mobile;
String english_name;
String open_userid;
long main_department;
String qr_code;
String external_position;
public class ExtAttrs {
String type;
String name;
String text;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public long[] getDepartment() {
return department;
}
public void setDepartment(long[] department) {
this.department = department;
}
public long[] getOrder() {
return order;
}
public void setOrder(long[] order) {
this.order = order;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long[] getIs_leader_in_dept() {
return is_leader_in_dept;
}
public void setIs_leader_in_dept(long[] is_leader_in_dept) {
this.is_leader_in_dept = is_leader_in_dept;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getThumb_avatar() {
return thumb_avatar;
}
public void setThumb_avatar(String thumb_avatar) {
this.thumb_avatar = thumb_avatar;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getHide_mobile() {
return hide_mobile;
}
public void setHide_mobile(int hide_mobile) {
this.hide_mobile = hide_mobile;
}
public String getEnglish_name() {
return english_name;
}
public void setEnglish_name(String english_name) {
this.english_name = english_name;
}
public String getOpen_userid() {
return open_userid;
}
public void setOpen_userid(String open_userid) {
this.open_userid = open_userid;
}
public long getMain_department() {
return main_department;
}
public void setMain_department(long main_department) {
this.main_department = main_department;
}
public String getQr_code() {
return qr_code;
}
public void setQr_code(String qr_code) {
this.qr_code = qr_code;
}
public String getExternal_position() {
return external_position;
}
public void setExternal_position(String external_position) {
this.external_position = external_position;
}
public int getIsleader() {
return isleader;
}
public void setIsleader(int isleader) {
this.isleader = isleader;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public WorkWeixinUsers() {
super();
}
}
|
3e0acfa9f8a8e7391a9eb458dc8383836b971a99 | 6,859 | java | Java | gitiles-servlet/src/main/java/com/google/gitiles/RevisionParser.java | nasser-torabzade/gitiles | c12cd3d361d37c7a4fd3a792be1d04f46877405a | [
"Apache-2.0"
] | 1 | 2015-05-01T20:16:45.000Z | 2015-05-01T20:16:45.000Z | gitiles-servlet/src/main/java/com/google/gitiles/RevisionParser.java | nasser-torabzade/gitiles | c12cd3d361d37c7a4fd3a792be1d04f46877405a | [
"Apache-2.0"
] | null | null | null | gitiles-servlet/src/main/java/com/google/gitiles/RevisionParser.java | nasser-torabzade/gitiles | c12cd3d361d37c7a4fd3a792be1d04f46877405a | [
"Apache-2.0"
] | null | null | null | 31.902326 | 97 | 0.599942 | 4,575 | // Copyright 2012 Google Inc. All Rights Reserved.
//
// 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.google.gitiles;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import java.io.IOException;
/** Object to parse revisions out of Gitiles paths. */
class RevisionParser {
static final Splitter PATH_SPLITTER = Splitter.on('/');
private static final Splitter OPERATOR_SPLITTER = Splitter.on(CharMatcher.anyOf("^~"));
static class Result {
private final Revision revision;
private final Revision oldRevision;
private final int pathStart;
@VisibleForTesting
Result(Revision revision) {
this(revision, null, revision.getName().length());
}
@VisibleForTesting
Result(Revision revision, Revision oldRevision, int pathStart) {
this.revision = revision;
this.oldRevision = oldRevision;
this.pathStart = pathStart;
}
public Revision getRevision() {
return revision;
}
public Revision getOldRevision() {
return oldRevision;
}
@Override
public boolean equals(Object o) {
if (o instanceof Result) {
Result r = (Result) o;
return Objects.equal(revision, r.revision)
&& Objects.equal(oldRevision, r.oldRevision)
&& Objects.equal(pathStart, r.pathStart);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(revision, oldRevision, pathStart);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.omitNullValues()
.add("revision", revision)
.add("oldRevision", oldRevision)
.add("pathStart", pathStart)
.toString();
}
int getPathStart() {
return pathStart;
}
}
private final Repository repo;
private final GitilesAccess access;
private final VisibilityCache cache;
RevisionParser(Repository repo, GitilesAccess access, VisibilityCache cache) {
this.repo = checkNotNull(repo, "repo");
this.access = checkNotNull(access, "access");
this.cache = checkNotNull(cache, "cache");
}
Result parse(String path) throws IOException {
RevWalk walk = new RevWalk(repo);
try {
Revision oldRevision = null;
StringBuilder b = new StringBuilder();
boolean first = true;
for (String part : PATH_SPLITTER.split(path)) {
if (part.isEmpty()) {
return null; // No valid revision contains empty segments.
}
if (!first) {
b.append('/');
}
if (oldRevision == null) {
int dots = part.indexOf("..");
int firstParent = part.indexOf("^!");
if (dots == 0 || firstParent == 0) {
return null;
} else if (dots > 0) {
b.append(part.substring(0, dots));
String oldName = b.toString();
if (!isValidRevision(oldName)) {
return null;
} else {
ObjectId old = repo.resolve(oldName);
if (old == null) {
return null;
}
oldRevision = Revision.peel(oldName, old, walk);
}
part = part.substring(dots + 2);
b = new StringBuilder();
} else if (firstParent > 0) {
if (firstParent != part.length() - 2) {
return null;
}
b.append(part.substring(0, part.length() - 2));
String name = b.toString();
if (!isValidRevision(name)) {
return null;
}
ObjectId id = repo.resolve(name);
if (id == null) {
return null;
}
RevCommit c;
try {
c = walk.parseCommit(id);
} catch (IncorrectObjectTypeException e) {
return null; // Not a commit, ^! is invalid.
}
if (c.getParentCount() > 0) {
oldRevision = Revision.peeled(name + "^", c.getParent(0));
} else {
oldRevision = Revision.NULL;
}
Result result = new Result(Revision.peeled(name, c), oldRevision, name.length() + 2);
return isVisible(walk, result) ? result : null;
}
}
b.append(part);
String name = b.toString();
if (!isValidRevision(name)) {
return null;
}
ObjectId id = repo.resolve(name);
if (id != null) {
int pathStart;
if (oldRevision == null) {
pathStart = name.length(); // foo
} else {
// foo..bar (foo may be empty)
pathStart = oldRevision.getName().length() + 2 + name.length();
}
Result result = new Result(Revision.peel(name, id, walk), oldRevision, pathStart);
return isVisible(walk, result) ? result : null;
}
first = false;
}
return null;
} finally {
walk.release();
}
}
private static boolean isValidRevision(String revision) {
// Disallow some uncommon but valid revision expressions that either we
// don't support or we represent differently in our URLs.
return revision.indexOf(':') < 0
&& revision.indexOf("^{") < 0
&& revision.indexOf('@') < 0;
}
private boolean isVisible(RevWalk walk, Result result) throws IOException {
String maybeRef = OPERATOR_SPLITTER.split(result.getRevision().getName()).iterator().next();
if (repo.getRef(maybeRef) != null) {
// Name contains a visible ref; skip expensive reachability check.
return true;
}
if (!cache.isVisible(repo, walk, access, result.getRevision().getId())) {
return false;
}
if (result.getOldRevision() != null && result.getOldRevision() != Revision.NULL) {
return cache.isVisible(repo, walk, access, result.getOldRevision().getId());
} else {
return true;
}
}
}
|
3e0ad01cb6b147cbdc97a2ffc0fe30b11002a031 | 3,292 | java | Java | patterned-edit-text/src/main/java/com/faradaj/patternededittext/utils/PatternUtils.java | faradaj/PatternedEditText | 56d804c00f8e66501ef033cf1e2bcdd3022c8a10 | [
"Unlicense",
"MIT"
] | 62 | 2015-01-09T20:28:34.000Z | 2021-03-25T00:13:07.000Z | patterned-edit-text/src/main/java/com/faradaj/patternededittext/utils/PatternUtils.java | faradaj/PatternedEditText | 56d804c00f8e66501ef033cf1e2bcdd3022c8a10 | [
"Unlicense",
"MIT"
] | 5 | 2015-06-26T09:49:24.000Z | 2020-02-06T08:21:28.000Z | patterned-edit-text/src/main/java/com/faradaj/patternededittext/utils/PatternUtils.java | faradaj/PatternedEditText | 56d804c00f8e66501ef033cf1e2bcdd3022c8a10 | [
"Unlicense",
"MIT"
] | 8 | 2015-04-07T06:06:42.000Z | 2018-01-20T11:35:12.000Z | 31.056604 | 120 | 0.52096 | 4,576 | package com.faradaj.patternededittext.utils;
import java.util.ArrayList;
public class PatternUtils {
public static String convertTextToPatternedText(String text, String pattern, char specialChar) {
StringBuilder sb = new StringBuilder();
int patternLength = pattern.length();
int textLength = text.length();
int patternAdditionCount = 0;
for (int i = 0; i < textLength + patternAdditionCount; ++i) {
if (patternLength > i && pattern.charAt(i) != specialChar) {
sb.append(pattern.charAt(i));
++patternAdditionCount;
} else {
sb.append(text.charAt(i - patternAdditionCount));
}
if (i + 1 == textLength + patternAdditionCount) {
if (patternLength > i + 1) {
if (pattern.substring(i + 1).indexOf(specialChar) == -1) {
sb.append(pattern.substring(i + 1));
}
}
}
}
return sb.toString();
}
public static int getDifferenceCount(String patternedText, String pattern, char specialChar) {
int patternedTextLength = patternedText.length();
int differenceCounter = 0;
for (int i = 0; i < patternedTextLength; ++i) {
if (pattern.charAt(i) != specialChar) {
++differenceCounter;
}
}
return differenceCounter;
}
public static boolean isTextAppliesPattern(String realText, String pattern, char specialChar) {
int patternLength = pattern.length();
int realTextLength = realText.length();
for (int i = 0; i < patternLength; ++i) {
if (realTextLength > i) {
if (pattern.charAt(i) != specialChar) {
if (realText.charAt(i) != pattern.charAt(i)) {
return false;
}
}
}
}
return true;
}
public static String convertPatternedTextToText(String patternedText, String pattern, char specialChar) {
StringBuilder sb = new StringBuilder();
int patternedTextLength = patternedText.length();
for (int i = 0; i < patternedTextLength; ++i) {
if (pattern.charAt(i) == specialChar) {
sb.append(patternedText.charAt(i));
}
}
return sb.toString();
}
public static ArrayList<Span> generateSpansFromPattern(String specialChar, String pattern) {
ArrayList<Span> spans = new ArrayList<Span>();
int offset = 0;
int length = 0;
int patternLength = pattern.length();
for (int i = 0; i < patternLength; ++i) {
if (pattern.substring(i, i + 1).equals(specialChar)) {
if (length == 0) {
offset = i;
}
++length;
}
if ((i + 1 < patternLength && !pattern.substring(i+1, i+2).equals(specialChar)) || i + 1 == patternLength) {
if (!(offset == 0 && length == 0)) {
spans.add(new Span(offset, length));
}
offset = 0;
length = 0;
}
}
return spans;
}
}
|
3e0ad05ad89a530d11eaa16b249b0b4ec3ff4d79 | 535 | java | Java | account/src/main/java/com/twitapp/account/utils/Beans.java | toshmanuel/twit-app | 5264a2e0703cc0c64cc8315bd3e4fdf0492795b9 | [
"MIT"
] | null | null | null | account/src/main/java/com/twitapp/account/utils/Beans.java | toshmanuel/twit-app | 5264a2e0703cc0c64cc8315bd3e4fdf0492795b9 | [
"MIT"
] | 1 | 2022-02-18T08:28:20.000Z | 2022-02-18T08:28:20.000Z | account/src/main/java/com/twitapp/account/utils/Beans.java | toshmanuel/twit-app | 5264a2e0703cc0c64cc8315bd3e4fdf0492795b9 | [
"MIT"
] | 1 | 2022-02-18T08:20:14.000Z | 2022-02-18T08:20:14.000Z | 26.75 | 81 | 0.762617 | 4,577 | package com.twitapp.account.utils;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class Beans {
@Bean
public ModelMapper getModelMapper() {
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setSkipNullEnabled(true);
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
return mapper;
}
}
|
3e0ad0dd0617b8dd27c9e3e9101f5d59103f169c | 1,563 | java | Java | chapter9/riderautoparts-order/src/main/java/camelinaction/OrderCreateTable.java | smalautomationinc/camelinaction | 24dc51f5e7c985fcad6129bf0134842505eb15d9 | [
"Apache-2.0"
] | 191 | 2015-01-14T08:27:37.000Z | 2022-03-29T00:54:49.000Z | chapter9/riderautoparts-order/src/main/java/camelinaction/OrderCreateTable.java | SteveHarrison82/camelinaction | 1d74f64c4aefd318baee21cb1b53928bc9f45763 | [
"Apache-2.0"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | chapter9/riderautoparts-order/src/main/java/camelinaction/OrderCreateTable.java | SteveHarrison82/camelinaction | 1d74f64c4aefd318baee21cb1b53928bc9f45763 | [
"Apache-2.0"
] | 215 | 2015-01-01T01:52:48.000Z | 2021-08-16T10:51:08.000Z | 36.348837 | 106 | 0.712732 | 4,578 | /**
* 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 camelinaction;
import javax.sql.DataSource;
import org.apache.camel.CamelContext;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @version $Revision$
*/
public class OrderCreateTable {
public OrderCreateTable(CamelContext camelContext) {
DataSource ds = camelContext.getRegistry().lookupByNameAndType("myDataSource", DataSource.class);
JdbcTemplate jdbc = new JdbcTemplate(ds);
try {
jdbc.execute("drop table riders_order");
} catch (Exception e) {
// ignore as the table may not already exists
}
jdbc.execute("create table riders_order "
+ "( customer_id varchar(10), ref_no varchar(10), part_id varchar(10), amount varchar(10) )");
}
}
|
3e0ad0ebb278f54948b7728cc0e0b14535ad0ae2 | 45,926 | java | Java | app/src/main/java/com/akshara/assessment/a3/TelemetryReport/TelemetryRreportActivity.java | klpdotorg/a3 | 1b282c4411637017dc56b865d862471854c4a054 | [
"MIT"
] | 1 | 2018-08-04T23:00:04.000Z | 2018-08-04T23:00:04.000Z | app/src/main/java/com/akshara/assessment/a3/TelemetryReport/TelemetryRreportActivity.java | klpdotorg/a3 | 1b282c4411637017dc56b865d862471854c4a054 | [
"MIT"
] | null | null | null | app/src/main/java/com/akshara/assessment/a3/TelemetryReport/TelemetryRreportActivity.java | klpdotorg/a3 | 1b282c4411637017dc56b865d862471854c4a054 | [
"MIT"
] | null | null | null | 43.042174 | 332 | 0.567064 | 4,579 | package com.akshara.assessment.a3.TelemetryReport;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.akshara.assessment.a3.A3Application;
import com.akshara.assessment.a3.BaseActivity;
import com.akshara.assessment.a3.BuildConfig;
import com.akshara.assessment.a3.NetworkRetrofitPackage.A3NetWorkCalls;
import com.akshara.assessment.a3.NetworkRetrofitPackage.A3Services;
import com.akshara.assessment.a3.NetworkRetrofitPackage.CurrentStateInterface;
import com.akshara.assessment.a3.Pojo.TelemetryPojo;
import com.akshara.assessment.a3.R;
import com.akshara.assessment.a3.UtilsPackage.AppStatus;
import com.akshara.assessment.a3.UtilsPackage.ConstantsA3;
import com.akshara.assessment.a3.UtilsPackage.DailogUtill;
import com.akshara.assessment.a3.UtilsPackage.SchoolStateInterface;
import com.akshara.assessment.a3.UtilsPackage.SessionManager;
import com.akshara.assessment.a3.WebViewActivity;
import com.akshara.assessment.a3.db.KontactDatabase;
import com.akshara.assessment.a3.db.QuestionSetDetailTable;
import com.akshara.assessment.a3.db.QuestionTable;
import com.akshara.assessment.a3.db.StudentTable;
import com.crashlytics.android.Crashlytics;
import com.gka.akshara.assesseasy.deviceDatastoreMgr;
import com.yahoo.squidb.data.SquidCursor;
import com.yahoo.squidb.sql.Query;
import org.apache.commons.lang3.text.WordUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TelemetryRreportActivity extends BaseActivity {
KontactDatabase db;
long A3APP_INSTITUTIONID;
int EASYASSESS_QUESTIONSETID;
int A3APP_GRADEID;
private deviceDatastoreMgr a3dsapiobj;
RecyclerView reportRecyclerView;
TelemetryReportAdapter adapter;
private File pdfFile;
ArrayList<QuestionTable> questionTables;
ArrayList<pojoReportData> dataInternal;
ArrayList<String> mConceptList;
ArrayList<StudentTable> studentIds;
SessionManager sessionManager;
String gradeS = "";
// private static final int STORAGE_PERMISSION_CODE = 123;
ProgressDialog progressDialog;
ArrayList<String> titles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_telemetry_rreport);
try {
db = ((A3Application) getApplicationContext()).getDb();
a3dsapiobj = new deviceDatastoreMgr();
a3dsapiobj.initializeDS(this);
mConceptList = new ArrayList<>();
// mConceptList2nd = new ArrayList<>();
reportRecyclerView = findViewById(R.id.reportRecyclerView);
A3APP_INSTITUTIONID = getIntent().getLongExtra("A3APP_INSTITUTIONID", 0L);
EASYASSESS_QUESTIONSETID = getIntent().getIntExtra("EASYASSESS_QUESTIONSETID", 0);
A3APP_GRADEID = getIntent().getIntExtra("A3APP_GRADEID", 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getResources().getString(R.string.studentScore));
sessionManager = new SessionManager(getApplicationContext());
reportRecyclerView.setLayoutManager(new LinearLayoutManager(this));
reportRecyclerView.setItemAnimator(new DefaultItemAnimator());
studentIds = getStudentIds(A3APP_INSTITUTIONID, A3APP_GRADEID);
gradeS = getResources().getStringArray(R.array.array_grade)[A3APP_GRADEID - 1];
dataInternal = a3dsapiobj.getAllStudentsForReports(EASYASSESS_QUESTIONSETID + "", studentIds, true, ConstantsA3.assessmenttype, true);
Collections.sort(dataInternal);
titles = getAllQuestionSetTitle(EASYASSESS_QUESTIONSETID);
questionTables = getAllQuestions(EASYASSESS_QUESTIONSETID);
adapter = new TelemetryReportAdapter(this, dataInternal, questionTables, titles);
reportRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (Exception e) {
Crashlytics.log("TelemetryRreportActivity report crash:");
// DailogUtill.showDialog("Oops some thing went wrong",getSupportFragmentManager(),getApplicationContext());
DailogUtill.showDialog(getResources().getString(R.string.oops), getSupportFragmentManager(), TelemetryRreportActivity.this);
}
// saveExcelFile(getApplicationContext(),"shreee.xls");
}
private void initPorgresssDialogForSchool() {
progressDialog = new ProgressDialog(TelemetryRreportActivity.this);
progressDialog.setMessage(getResources().getString(R.string.loadingStudent));
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
progressDialog.setCancelable(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.download_menu, menu);
return true;
}
public void downloadStudents(MenuItem item) {
if (item.getItemId() == R.id.action_download) {
try {
// DailogUtill.showDialog("Error while generating report",getSupportFragmentManager(),TelemetryRreportActivity.this);
// requestStoragePermission();
// generatePDFData();
if (AppStatus.isConnected(getApplicationContext())) {
downloadStudentsFirst();
} else {
DailogUtill.showDialog(getResources().getString(R.string.netWorkError), getSupportFragmentManager(), TelemetryRreportActivity.this);
}
} catch (Exception e) {
try {
Crashlytics.log("Error while generating report");
Crashlytics.log("Institution Id:" + A3APP_INSTITUTIONID);
} catch (Exception e1) {
Crashlytics.log("Error while generating report inner try catch block:" + e.getMessage());
}
DailogUtill.showDialog("Error while generating report.Please try again", getSupportFragmentManager(), TelemetryRreportActivity.this);
//Toast.makeText(getApplicationContext(), "Error while generating report", Toast.LENGTH_SHORT).show();
}
}
}
public void downloadStudentsFirst() {
initPorgresssDialogForSchool();
String URL = BuildConfig.HOST + "/api/v1/institutions/" + A3APP_INSTITUTIONID + "/students/";
// String URL = BuildConfig.HOST +"/api/v1/institutestudents/?institution_id="+schoolId;
new A3NetWorkCalls(TelemetryRreportActivity.this).downloadStudent(URL, A3APP_INSTITUTIONID, A3APP_GRADEID, sessionManager.getToken(), new SchoolStateInterface() {
@Override
public void success(String message) {
// finishProgress();
studentIds = getStudentIds(A3APP_INSTITUTIONID, A3APP_GRADEID);
ArrayList<String> childIds = new ArrayList<>();
for (StudentTable child : studentIds) {
childIds.add(child.getId() + "");
}
//Log.d("shri",childIds.toString());
if (childIds.size() > 0) {
// ArrayList<String> temp = new ArrayList<>();
// temp.add("5455736");
TelemetryPojo pojo = new TelemetryPojo(sessionManager.getLanguage(), ConstantsA3.subject, gradeS, sessionManager.getProgramFromSession(), ConstantsA3.assessmenttype, "", "", A3Services.AUTH_KEY, childIds,sessionManager.getStateKey().toUpperCase());
//TelemetryPojo pojo = new TelemetryPojo(sessionManager.getLanguage(), ConstantsA3.subject, gradeS, sessionManager.getProgramFromSession(), ConstantsA3.assessmenttype, "2017:08:01", "2018:08:16", A3Services.AUTH_KEY, temp);
// Log.d("shri", EASYASSESS_QUESTIONSETID + "---" + studentIds.toString() + "----" + ConstantsA3.assessmenttype);
new A3NetWorkCalls(TelemetryRreportActivity.this).getTelmetryData(pojo, new CurrentStateInterface() {
@Override
public void setSuccess(String message) {
finishProgress();
// a3dsapiobj.a3appdb.close();
// a3dsapiobj = new deviceDatastoreMgr();
//a3dsapiobj.initializeDS(TelemetryRreportActivity.this);
// Log.d("shri",dataInternal.size()+"Internal");
dataInternal = a3dsapiobj.getAllStudentsForReports(EASYASSESS_QUESTIONSETID + "", studentIds, true, ConstantsA3.assessmenttype, true);
// Log.d("shri", EASYASSESS_QUESTIONSETID + "---" + studentIds.toString() + "----" + ConstantsA3.assessmenttype);
Collections.sort(dataInternal);
GenerateHtmlString();
// final ArrayList<pojoReportData> data2=data;
// Log.d("shri",data2.size()+"p");
try {
try {
// generatePDFData();
// GenerateHtmlString();
} catch (Exception e) {
DailogUtill.showDialog("Error while generating report.Please try again", getSupportFragmentManager(), TelemetryRreportActivity.this);
}
} catch (Exception e) {
Toast.makeText(TelemetryRreportActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
// dataInternal = a3dsapiobj.getAllStudentsForReports(EASYASSESS_QUESTIONSETID + "", studentIds, true, ConstantsA3.assessmenttype, true);
// Collections.sort(dataInternal);
adapter = new TelemetryReportAdapter(TelemetryRreportActivity.this, dataInternal, questionTables, titles);
reportRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
//DailogUtill.showDialog(message, getSupportFragmentManager(), TelemetryRreportActivity.this);
}
@Override
public void setFailed(String message) {
finishProgress();
DailogUtill.showDialog(message, getSupportFragmentManager(), TelemetryRreportActivity.this);
}
});
} else {
finishProgress();
Toast.makeText(getApplicationContext(), "No Childrens info found", Toast.LENGTH_SHORT).show();
}
}
@Override
public void failed(String message) {
finishProgress();
DailogUtill.showDialog(message, getSupportFragmentManager(), TelemetryRreportActivity.this);
}
@Override
public void update(int message) {
}
});
}
public void GenerateHtmlString() {
int totalAssessmentAttemptedStu = 0;
int totalStudents = 0;
Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
final String thStyle = " ";
final String dataTillBodyTagOpen = "<!DOCTYPE html>\n" +
"<html>\n" +
"<meta charset=\"UTF-8\"/>\n" +
"<head>\n" +
"<style>\n" +
"table, th, td {\n" +
" border: 1px solid black;\n" +
" border-collapse: collapse;\n" +
"}\n" +
"th, td {\n" +
" padding: 5px;\n" +
" text-align: left; style=\"width:100%\" \n" +
"}\n" +
"th span \n" +
"{\n" +
" -ms-writing-mode: tb-rl;\n" +
" -webkit-writing-mode: vertical-rl;\n" +
" writing-mode: vertical-rl;\n" +
" transform: rotate(180deg);\n" +
" white-space: nowrap;\n" +
"}</style>\n" +
"</head>\n" +
"<body>\n";
final String bodyEnd = "</body></html>";
String title = ConstantsA3.subject + " " + "Assessment for " + ConstantsA3.schoolName;
String assessmenttype = getResources().getString(R.string.assessment_type_rep) + " " + ConstantsA3.assessmenttype + " , " + gradeS;
String userName = sessionManager.getUserType() + ": " + sessionManager.getFirstName();
// String language = "Language: " + sessionManager.getLanguage();
String subject = getResources().getString(R.string.subject_rep) + " " + ConstantsA3.subject;
//String grade = "Grade: " +gradeS ;
String headers1 = "<h2><center>" + title + "</center></h2>";
String headers2 = "<h2><center>" + assessmenttype + "</center></h2>";
String Print1 = "<h3>" + userName + "</h3>";
// String Print2 = "<h3>" + grade + "</h3>";
// String Print3 = "<h3>" + language + "</h3>";
String Print4 = "<h3>" + subject + "</h3>";
StringBuilder firstTable = new StringBuilder();
firstTable.append("<table style=\\\"width:100%\\\"> <tr>");
for (int i = 0; i < mConceptList.size(); i++) {
if (i == 0) {
String tableheader1 = " <th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#cccccc';width=\"20%\">" + getResources().getString(R.string.slno) + "</th><th style='font-weight:bold;background-color:#cccccc';width=\\\"80%\\\">" + getResources().getString(R.string.micro) + "</th></tr>";
firstTable.append(tableheader1);
}
String mconcept = mConceptList.get(i).split("@@")[0];
String tableheader1 = "<tr><th style='text-align:center;vertical-align:middle'; width=\"20%\">" + (i + 1) + "</th><th width=\"80%\">" + mconcept + "</th></tr>";
firstTable.append(tableheader1);
if (i == mConceptList.size() - 1) {
// document.add(pdfPTableforContent);
// document.newPage();
firstTable.append("</table><p style=\"page-break-before: always\">");
}
}
final String tableStart = "<table style=\"width:100%\";page-break-before: always> <tr>";
// StringBuilder htmlData = new StringBuilder(dataTillBodyTagOpen+ headers1 + headers2 + Print1 + Print4 +firstTable+tableStart);
StringBuilder htmlData = new StringBuilder();
//StringBuilder htmlData = new StringBuilder(dataTillBodyTagOpen + headers1 + headers2 + Print1 + Print4 +firstTable+tableStart);
String tempSize = (70 / mConceptList.size()) + "%";
for (int m = 0; m < mConceptList.size(); m++) {
if (m == 0) {
String tableheader1 = " <th style='font-weight:bold;background-color:#cccccc';width=\"15%\">" + getResources().getString(R.string.studntName) + "</th>";
String tableheader2 = " <th style='font-weight:bold;background-color:#cccccc';width=\"5%\">" + getResources().getString(R.string.sln) + "</th>";
htmlData.append(tableheader2);
htmlData.append(tableheader1);
}
//0 index mconcept,1 index will have question id,2 will have qtitle& 3 concept
//0 index mconcept,1 index will have question id,2 will have qtitle& 3 concept
//
String concept = mConceptList.get(m).split("@@")[3];
try {
concept = concept.split("-", 2)[1];
} catch (Exception e) {
}
// String tablemconceptsheader="<th style='text-align:center;vertical-align:middle';width="+tempSize+">"+String.valueOf(m + 1)+"</th>";
String tablemconceptsheader = "<th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#cccccc';width=" + tempSize + ">(" + (m + 1) + ")" + concept + "</th>";
htmlData.append(tablemconceptsheader);
//Phrase phrase = new Phrase(String.valueOf(mConceptList.get(m).split("@@")[0]),getFont());
if (m == (mConceptList.size() - 1)) {
String sizetemp = "10%";
htmlData.append("<th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#cccccc' width=" + sizetemp + ">" + getResources().getString(R.string.stscore) + "</th> </tr>");
}
}
//first header completed
for (int j = 0; j < dataInternal.size(); j++) {
StudentTable table = dataInternal.get(j).getTable();
String name = " " + table.getFirstName().toLowerCase();
// Log.d("shri", table.getFirstName() + "--" + table.getId());
try {
if (table.getMiddleName() != null && !table.getMiddleName().equalsIgnoreCase("")) {
name = name + " " + (table.getMiddleName().substring(0, 1)).toLowerCase();
}
} catch (Exception e) {
}
//pdfPTable.addCell(new PdfPCell(new Phrase(name)));
String startDataH = "<tr><th style='text-align:center;vertical-align:middle'>" + (j + 1) + "</th><th>" + WordUtils.capitalize(name) + "</th>";
htmlData.append(startDataH);
for (int k = 0; k < mConceptList.size(); k++) {
if (dataInternal.get(j).getDetailReportsMap().get(table.getId()) != null) {
int size = dataInternal.get(j).getDetailReportsMap().get(table.getId()).size();
//Log.d("shri",size+"---------------------");
int marks = 0;
try {
CombinePojo pojo = dataInternal.get(j).getDetailReportsMap().get(table.getId()).get(size - 1);
marks = getAnswer(mConceptList.get(k), pojo, j, table.getId(), (size - 1));
} catch (Exception e) {
marks = 0;
}
htmlData.append("<th style='text-align:center;vertical-align:middle'>" + marks + "</th>");
// getAnswer(mConceptList.get(k),pojo);
// if(marks!=0) {
Integer count = freq.get(k);
if (count == null) {
freq.put(k, marks);
} else {
freq.put(k, count + marks);
}
// }
} else {
String nodata = "-";
htmlData.append("<th style='text-align:center;vertical-align:middle'>" + nodata + "</th>");
}
if (k == mConceptList.size() - 1) {
if (dataInternal.get(j).getDetailReportsMap().get(table.getId()) != null) {
totalAssessmentAttemptedStu++;
totalStudents++;
// int size = dataInternal.get(j).getDetailReportsMap().get(table.getId()).size();
int score = 0;
/* if(size>0) {
score= dataInternal.get(j).getDetailReportsMap().get(table.getId()).get(size - 1).getPojoAssessment().getScore();
}*/
ArrayList<CombinePojo> combinePojos = dataInternal.get(j).getDetailReportsMap().get(table.getId());
/* for (CombinePojo cd : listData.get(studentTable.getId())) {
//Log.d("shri",cd.getPojoAssessment().getScore()+"!!!!");
}*/
try {
if (combinePojos.size() > 1) {
int size1 = combinePojos.size();
score = combinePojos.get((size1 - 1)).getPojoAssessment().getScore();
} else {
score = combinePojos.get(0).getPojoAssessment().getScore();
}
} catch (Exception e) {
score = dataInternal.get(j).getScore();
}
htmlData.append("<th style='text-align:center;vertical-align:middle'>" + score + "</th></tr>");
//end score
} else {
String score = "-";
totalStudents++;
htmlData.append("<th style='text-align:center;vertical-align:middle'>" + score + "</th></tr>");
}
}
}
if (j == dataInternal.size() - 1) {
String Print5 = "<h3>" + getResources().getString(R.string.attemptedStudents) + "" + totalAssessmentAttemptedStu + "</h3>";
String Print6 = "<h3>" + getResources().getString(R.string.totalStudents) + "" + totalStudents + "</h3>";
StringBuilder htmlData2 = new StringBuilder(dataTillBodyTagOpen + headers1 + headers2 + Print1 + Print4 + Print6 + Print5 + firstTable + tableStart);
htmlData2.append(htmlData);
if (freq != null && freq.size() > 0) {
String lastTotlalString = "<tr><th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#cccccc'> </th><th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#cccccc'>" + getResources().getString(R.string.coorect_answers) + "</th>";
StringBuilder builder = new StringBuilder(lastTotlalString);
for (Integer val : freq.values()) {
// if (val <= 4) {
// builder.append("<th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#F00'><font color=\"#FFDF00\">" + val + "</font></th>");
// } else {
builder.append("<th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#cccccc'>" + val + "</th>");
// }
}
builder.append("<th style='text-align:center;vertical-align:middle;font-weight:bold;background-color:#cccccc'> </th></tr>");
htmlData2.append(builder);
String s = "</table><h4><left>" + getResources().getString(R.string.kitQ) + "</left></h4>";
htmlData2.append(s);
}
htmlData2.append(bodyEnd);
// Log.d("shri",freq.toString());
// genPdfFile(htmlData.toString());
Intent intent = new Intent(getApplicationContext(), WebViewActivity.class);
intent.putExtra("data", htmlData2.toString());
startActivity(intent);
}
}
}
/*
private void generatePDFData() throws DocumentException {
int tableSize = mConceptList.size() + 2;
int[] bytes = new int[tableSize];
int temp = (75 / mConceptList.size());
for (int i = 0; i < tableSize; i++) {
if (i == 0) {
bytes[i] = 15;
continue;
}
bytes[i] = temp;
if (i == tableSize - 1) {
bytes[i] = 10;
}
}
PdfPTable pdfPTable = new PdfPTable(tableSize);
pdfPTable.setWidths(bytes);
pdfPTable.setWidthPercentage(100);
try {
*/
/* File root = Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/downloadAK");
if(!dir.exists())
dir.mkdirs();*//*
Calendar calendar = Calendar.getInstance();
String fileName = getResources().getString(R.string.app_name) + calendar.getTimeInMillis();
// File file = new File(dir, fileName+".pdf");
// File storageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
*/
/* File file = File.createTempFile(
fileName,
".pdf",
storageDir
);*//*
File storageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
fileName, */
/* prefix *//*
".pdf", */
/* suffix *//*
storageDir */
/* directory *//*
);
*/
/* File file = File.createTempFile(
fileName, *//*
*/
/* prefix *//*
*/
/*
".pdf", *//*
*/
/* suffix *//*
*/
/*
dir *//*
*/
/* directory *//*
*/
/*
);*//*
// String mCurrentPhotoPath = "file:" + file.getAbsolutePath();
String imageFilePath = file.getAbsolutePath();
pdfFile = file;
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document(PageSize.A3.rotate());
PdfWriter.getInstance(document, output);
document.open();
Font font = new Font(Font.FontFamily.HELVETICA, 22, Font.BOLD);
Font font2 = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
String title = ConstantsA3.subject + " " + "Assessment for " + ConstantsA3.schoolName;
Paragraph paragraphappName = new Paragraph(title, font);
paragraphappName.setAlignment(Element.ALIGN_CENTER);
paragraphappName.setLeading(0, 1);
paragraphappName.setSpacingAfter(20);
document.add(paragraphappName);
// String FONT = "assets/sample1.ttf";
// Font f = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Paragraph paragraphappName2 = new Paragraph(getResources().getString(R.string.assessment_type_rep) + ConstantsA3.assessmenttype, font);
paragraphappName2.setAlignment(Element.ALIGN_CENTER);
paragraphappName2.setLeading(0, 1);
paragraphappName2.setSpacingAfter(30);
document.add(paragraphappName2);
Paragraph paragraphUserName = new Paragraph(sessionManager.getUserType() + ": " + sessionManager.getFirstName(), font2);
Paragraph gradeParagraph = new Paragraph("Grade: " + gradeS, font2);
// Paragraph paraAsstypetitle = new Paragraph("Assessment type title: " + ConstantsA3.surveyTitle, font2);
// Paragraph paraAsstype = new Paragraph("ASSESSMENT TYPE: " + ConstantsA3.assessmenttype, font2);
// Paragraph paralang = new Paragraph("Language: " + sessionManager.getLanguage(), font2);
Paragraph paraSubjecttype = new Paragraph(getResources().getString(R.string.subject_rep) + ConstantsA3.subject, font2);
paraSubjecttype.setSpacingAfter(15);
document.add(paragraphUserName);
// document.add(paraAsstypetitle);
// document.add(paraAsstype);
document.add(gradeParagraph);
// document.add(paralang);
document.add(paraSubjecttype);
// BidiFormatter myBidiFormatter = BidiFormatter.getInstance();
PdfPTable pdfPTableforContent = new PdfPTable(2);
pdfPTableforContent.setWidths(new float[]{15, 85});
pdfPTableforContent.setWidthPercentage(70);
for (int i = 0; i < mConceptList.size(); i++) {
PdfPCell pdfPCell;
if (i == 0) {
//set headers
pdfPCell = new PdfPCell(new Phrase("Sl.NO"));
pdfPCell.setBackgroundColor(BaseColor.GRAY);
pdfCellStyles(pdfPCell);
// pdfPCell.setColspan(1);
pdfPTableforContent.addCell(pdfPCell);
pdfPCell = new PdfPCell(new Phrase("Concept name"));
pdfPCell.setBackgroundColor(BaseColor.GRAY);
pdfCellStyles1(pdfPCell);
pdfPTableforContent.addCell(pdfPCell);
}
pdfPCell = new PdfPCell(new Phrase(String.valueOf(i + 1)));
// pdfPCell.setColspan(1);
pdfCellStyles(pdfPCell);
pdfPTableforContent.addCell(pdfPCell);
//pdfPCell = new PdfPCell(new Phrase(mConceptList.get(i)));
// pdfPCell = new PdfPCell(new Phrase(mConceptList.get(i).split("@@")[2] + " - " + mConceptList.get(i).split("@@")[0]));
pdfPCell = new PdfPCell(new Phrase(" " + mConceptList.get(i).split("@@")[0]));
// Phrase p=new Phrase("");
pdfPTableforContent.addCell(pdfPCell);
// pdfCellStyles2(pdfPCell)
if (i == mConceptList.size() - 1) {
document.add(pdfPTableforContent);
document.newPage();
}
}
for (int m = 0; m < mConceptList.size(); m++) {
PdfPCell pdfPCell;
if (m == 0) {
Phrase phrase = new Phrase("Concept type/ \nStudent Name");
pdfPCell = new PdfPCell(phrase);
// pdfPCell.setNoWrap(false);
pdfPCell.setBackgroundColor(BaseColor.GRAY);
// pdfPCell.setColspan(1);
pdfCellStylesInside(pdfPCell);
pdfPTable.addCell(pdfPCell);
}
Phrase phrase = new Phrase(String.valueOf(m + 1));
//Phrase phrase = new Phrase(String.valueOf(mConceptList.get(m).split("@@")[0]),getFont());
pdfPCell = new PdfPCell(phrase);
// pdfPCell.setHorizontalAlignment(Element.ALIGN_LEFT);
// pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// pdfPCell.setRotation(90);
pdfCellStyles(pdfPCell);
pdfPCell.setBackgroundColor(BaseColor.GRAY);
pdfPTable.addCell(pdfPCell);
if (m == (mConceptList.size() - 1)) {
Phrase phrase1 = new Phrase("Score");
pdfPCell = new PdfPCell(phrase1);
pdfCellStyles(pdfPCell);
pdfPCell.setBackgroundColor(BaseColor.GRAY);
pdfPTable.addCell(pdfPCell);
}
}
for (int j = 0; j < dataInternal.size(); j++) {
StudentTable table = dataInternal.get(j).getTable();
String name = table.getFirstName();
try {
if (table.getMiddleName() != null && !table.getMiddleName().equalsIgnoreCase("")) {
name = name + " " + (table.getMiddleName().substring(0, 1));
}
*/
/* if (table.getLastName() != null && !table.getLastName().equalsIgnoreCase("")) {
name = name + " " + (table.getLastName().substring(0, 1));
}*//*
} catch (Exception e) {
}
pdfPTable.addCell(new PdfPCell(new Phrase(name)));
for (int k = 0; k < mConceptList.size(); k++) {
if (dataInternal.get(j).getDetailReportsMap().get(table.getId()) != null) {
int size = dataInternal.get(j).getDetailReportsMap().get(table.getId()).size();
CombinePojo pojo = dataInternal.get(j).getDetailReportsMap().get(table.getId()).get(size - 1);
PdfPCell pdfPCell = new PdfPCell(new PdfPCell(new Phrase(getAnswer(mConceptList.get(k), pojo, j, table.getId(), (size - 1)) + "")));
pdfCellStyles(pdfPCell);
pdfPTable.addCell(pdfPCell);
// getAnswer(mConceptList.get(k),pojo);
} else {
PdfPCell pdfPCell = new PdfPCell(new Phrase("-"));
pdfCellStyles(pdfPCell);
pdfPTable.addCell(pdfPCell);
}
if (k == mConceptList.size() - 1) {
if (dataInternal.get(j).getDetailReportsMap().get(table.getId()) != null) {
int size = dataInternal.get(j).getDetailReportsMap().get(table.getId()).size();
int score = dataInternal.get(j).getDetailReportsMap().get(table.getId()).get(size - 1).getPojoAssessment().getScore();
PdfPCell pdfPCell = new PdfPCell(new PdfPCell(new Phrase(String.valueOf(score))));
pdfCellStyles(pdfPCell);
pdfPTable.addCell(pdfPCell);
} else {
PdfPCell pdfPCell = new PdfPCell(new Phrase("-"));
pdfCellStyles(pdfPCell);
pdfPTable.addCell(pdfPCell);
}
}
}
if (j == dataInternal.size() - 1) {
document.add(pdfPTable);
pdfPTable.setHeaderRows(1);
document.close();
// output.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
// set flag to give temporary permission to external app to use your FileProvider
// intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
// Uri uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, pdfFile);
Uri uri = FileProvider.getUriForFile(TelemetryRreportActivity.this, BuildConfig.APPLICATION_ID + ".provider", pdfFile);
// I am opening a PDF file so I give it a valid MIME type
intent.setDataAndType(uri, "application/pdf");
// validate that the device can open your File!
PackageManager pm = getApplicationContext().getPackageManager();
if (intent.resolveActivity(pm) != null) {
try {
startActivity(intent);
} catch (Exception e) {
try {
Crashlytics.log("Institution Id:" + A3APP_INSTITUTIONID);
Crashlytics.log("PDF reader not found");
} catch (Exception e1) {
Crashlytics.log("PDF reader not found inner catch");
}
DailogUtill.showDialog("PDF reader not found", getSupportFragmentManager(), getApplicationContext());
// Toast.makeText(getApplicationContext(), "PDF reader not found", Toast.LENGTH_SHORT).show();
}
}
}
}
} catch (Exception e) {
Crashlytics.log("Error-" + e.getMessage());
DailogUtill.showDialog(getResources().getString(R.string.oops), getSupportFragmentManager(), TelemetryRreportActivity.this);
// Toast.makeText(getApplicationContext(), "Error-" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}*/
private void finishProgress() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
/* private void pdfCellStyles(PdfPCell pdfPCell) {
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
}
private void pdfCellStyles1(PdfPCell pdfPCell) {
// pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
}
private void pdfCellStylesInside(PdfPCell pdfPCell) {
//pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
}*/
public int getAnswer(String mconceptName1, CombinePojo pojo, int j, long stuid, int i) {
int answerCount = 0;
// Log.d("shri","-----------------start ---:"+stuid);
for (int m = 0; m < pojo.getPojoAssessmentDetail().size(); m++) {
pojoAssessmentDetail detail = pojo.getPojoAssessmentDetail().get(m);
/* if(detail.getId_assessment().equalsIgnoreCase("2c54c984e21cc4"))
{
Log.d("shri",detail.toString());
}*/
if (detail != null) {
// Log.d("shri",de)
String mConceptName = getMConceptName(detail.getId_question());
// Log.d("shri",concept+"------"+conceptName+":"+detail.getPass()+"qidAss"+detail.getId_assessment()+"-QID"+detail.getId_question()+"--id--"+detail.getId());
// pojo.getPojoAssessment().id_questionset;
// if (mconceptName1.split("@@")[1].equalsIgnoreCase(detail.getId_question()) && detail.getPass() != null && detail.getPass().equalsIgnoreCase("P")) {
if (mconceptName1.split("@@")[0].equalsIgnoreCase(mConceptName) && detail.getPass() != null
&& detail.getPass().equalsIgnoreCase("P") && detail.isFlag() == false) {
//answerCount = answerCount + 1;
answerCount = 1;
// dataInternal.get(j).getDetailReportsMap().get(stuid).get(i).getPojoAssessmentDetail().remove(m);
// pojo.getPojoAssessmentDetail().remove(m);
dataInternal.get(j).getDetailReportsMap().get(stuid).get(i).getPojoAssessmentDetail().get(m).setFlag(true);
return answerCount;
// m=m-1;
} else if (mconceptName1.split("@@")[0].equalsIgnoreCase(mConceptName) && detail.isFlag() == false) {
dataInternal.get(j).getDetailReportsMap().get(stuid).get(i).getPojoAssessmentDetail().get(m).setFlag(true);
// pojo.getPojoAssessmentDetail().remove(m);
// m=m-1;
return answerCount;
}
}
}
return answerCount;
}
public String getMConceptName(String questionId) {
Query question = Query.select().from(QuestionTable.TABLE)
.where(QuestionTable.ID_QUESTION.eq(questionId));
SquidCursor<QuestionTable> studentCursor = db.query(QuestionTable.class, question);
while (studentCursor.moveToNext()) {
String mconceptName = new QuestionTable(studentCursor).getMconceptName();
if (studentCursor != null) {
studentCursor.close();
}
return mconceptName;
}
return "";
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
navigateBack();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
navigateBack();
}
public void navigateBack() {
overridePendingTransition(R.anim.slide_from_left, R.anim.slide_to_right);
finish();
}
public ArrayList<StudentTable> getStudentIds(long institution, int gradeId) {
ArrayList<StudentTable> studentIds = new ArrayList<>();
Query studentQuery = Query.select().from(StudentTable.TABLE)
.where(StudentTable.INSTITUTION.eq(institution).and(StudentTable.STUDENT_GRADE.eq(gradeId))).orderBy(StudentTable.FIRST_NAME.asc());
SquidCursor<StudentTable> studentCursor = db.query(StudentTable.class, studentQuery);
if (studentCursor != null && studentCursor.getCount() > 0) {
while (studentCursor.moveToNext()) {
StudentTable studentTable = new StudentTable(studentCursor);
studentIds.add(studentTable);
}
}
//Log.d("shri","Student size"+studentIds.size());
return studentIds;
}
public ArrayList<String> getAllQuestioId(int questionsetId) {
ArrayList<String> listQId = new ArrayList<>();
Query QuestionsetQuery = Query.select().from(QuestionSetDetailTable.TABLE)
.where(QuestionSetDetailTable.ID_QUESTIONSET.eq(questionsetId));
SquidCursor<QuestionSetDetailTable> questionsetDetailCursor = db.query(QuestionSetDetailTable.class, QuestionsetQuery);
if (questionsetDetailCursor != null && questionsetDetailCursor.getCount() > 0) {
while (questionsetDetailCursor.moveToNext()) {
QuestionSetDetailTable questionSetDetailTable = new QuestionSetDetailTable(questionsetDetailCursor);
listQId.add(questionSetDetailTable.getIdQuestion());
}
}
return listQId;
}
public ArrayList<QuestionTable> getAllQuestions(int questionsetId) {
ArrayList<String> qIDtemp = new ArrayList<>();
mConceptList = new ArrayList<>();
// mConceptList2nd = new ArrayList<>();
ArrayList<QuestionTable> listAllQuestions = new ArrayList<>();
Query QuestionsetQuery = Query.select().from(QuestionSetDetailTable.TABLE)
.where(QuestionSetDetailTable.ID_QUESTIONSET.eq(questionsetId));
SquidCursor<QuestionSetDetailTable> questionsetDetailCursor = db.query(QuestionSetDetailTable.class, QuestionsetQuery);
if (questionsetDetailCursor != null && questionsetDetailCursor.getCount() > 0) {
while (questionsetDetailCursor.moveToNext()) {
QuestionSetDetailTable questionSetDetailTable = new QuestionSetDetailTable(questionsetDetailCursor);
Query QuestionQuery = Query.select().from(QuestionTable.TABLE)
.where(QuestionTable.ID_QUESTION.eq(questionSetDetailTable.getIdQuestion()));
SquidCursor<QuestionTable> questionCursoe = db.query(QuestionTable.class, QuestionQuery);
while (questionCursoe.moveToNext()) {
QuestionTable questionTable = new QuestionTable(questionCursoe);
if (!qIDtemp.contains(questionTable.getIdQuestion())) {
qIDtemp.add(questionTable.getIdQuestion());
//if (!mConceptList.contains(questionTable.getMconceptName())) {
mConceptList.add(questionTable.getMconceptName() + "@@" + questionTable.getIdQuestion() + "@@" + questionTable.getQuestionTitle() + "@@" + questionTable.getConceptName());
// mConceptList2nd.add(questionTable.getIdQuestion() );
// }
listAllQuestions.add(questionTable);
}
}
}
}
return listAllQuestions;
}
public ArrayList<String> getAllQuestionSetTitle(int questionsetId) {
ArrayList<String> qIDtemp = new ArrayList<>();
ArrayList<String> listQuestionTitle = new ArrayList<>();
Query QuestionsetQuery = Query.select().from(QuestionSetDetailTable.TABLE)
.where(QuestionSetDetailTable.ID_QUESTIONSET.eq(questionsetId));
SquidCursor<QuestionSetDetailTable> questionsetDetailCursor = db.query(QuestionSetDetailTable.class, QuestionsetQuery);
if (questionsetDetailCursor != null && questionsetDetailCursor.getCount() > 0) {
while (questionsetDetailCursor.moveToNext()) {
QuestionSetDetailTable questionSetDetailTable = new QuestionSetDetailTable(questionsetDetailCursor);
Query QuestionQuery = Query.select().from(QuestionTable.TABLE)
.where(QuestionTable.ID_QUESTION.eq(questionSetDetailTable.getIdQuestion()));
SquidCursor<QuestionTable> questionCursoe = db.query(QuestionTable.class, QuestionQuery);
while (questionCursoe.moveToNext()) {
QuestionTable questionTable = new QuestionTable(questionCursoe);
if (!qIDtemp.contains(questionTable.getIdQuestion())) {
qIDtemp.add(questionTable.getIdQuestion());
if (!listQuestionTitle.contains(questionTable.getConceptName())) {
listQuestionTitle.add(questionTable.getConceptName());
}
}
}
}
}
return listQuestionTitle;
}
}
|
3e0ad179251968a023ee4ae5ad1d3dc4fd8944a0 | 5,280 | java | Java | common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mSessionMsgListener.java | andre-aktivconsultancy/thingsboard | 7d5153f52ee4033c8a7ffab0a678950122b982eb | [
"ECL-2.0",
"Apache-2.0"
] | 11,616 | 2016-12-06T11:19:33.000Z | 2022-03-31T16:15:40.000Z | common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mSessionMsgListener.java | andre-aktivconsultancy/thingsboard | 7d5153f52ee4033c8a7ffab0a678950122b982eb | [
"ECL-2.0",
"Apache-2.0"
] | 4,143 | 2016-12-06T16:58:55.000Z | 2022-03-31T19:26:39.000Z | common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/LwM2mSessionMsgListener.java | andre-aktivconsultancy/thingsboard | 7d5153f52ee4033c8a7ffab0a678950122b982eb | [
"ECL-2.0",
"Apache-2.0"
] | 4,144 | 2016-12-06T13:02:55.000Z | 2022-03-31T12:22:41.000Z | 44.745763 | 135 | 0.788447 | 4,580 | /**
* Copyright © 2016-2021 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.transport.lwm2m.server;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.ResourceType;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.transport.SessionMsgListener;
import org.thingsboard.server.common.transport.TransportService;
import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.gen.transport.TransportProtos.AttributeUpdateNotificationMsg;
import org.thingsboard.server.gen.transport.TransportProtos.GetAttributeResponseMsg;
import org.thingsboard.server.gen.transport.TransportProtos.SessionCloseNotificationProto;
import org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcRequestMsg;
import org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcResponseMsg;
import org.thingsboard.server.gen.transport.TransportProtos.ToTransportUpdateCredentialsProto;
import org.thingsboard.server.transport.lwm2m.server.attributes.LwM2MAttributesService;
import org.thingsboard.server.transport.lwm2m.server.rpc.LwM2MRpcRequestHandler;
import org.thingsboard.server.transport.lwm2m.server.uplink.LwM2mUplinkMsgHandler;
import java.util.Optional;
import java.util.UUID;
@Slf4j
@RequiredArgsConstructor
public class LwM2mSessionMsgListener implements GenericFutureListener<Future<? super Void>>, SessionMsgListener {
private final LwM2mUplinkMsgHandler handler;
private final LwM2MAttributesService attributesService;
private final LwM2MRpcRequestHandler rpcHandler;
private final TransportProtos.SessionInfoProto sessionInfo;
private final TransportService transportService;
@Override
public void onGetAttributesResponse(GetAttributeResponseMsg getAttributesResponse) {
this.attributesService.onGetAttributesResponse(getAttributesResponse, this.sessionInfo);
}
@Override
public void onAttributeUpdate(UUID sessionId, AttributeUpdateNotificationMsg attributeUpdateNotification) {
log.trace("[{}] Received attributes update notification to device", sessionId);
this.attributesService.onAttributesUpdate(attributeUpdateNotification, this.sessionInfo);
}
@Override
public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) {
log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage());
}
@Override
public void onToTransportUpdateCredentials(ToTransportUpdateCredentialsProto updateCredentials) {
this.handler.onToTransportUpdateCredentials(sessionInfo, updateCredentials);
}
@Override
public void onDeviceProfileUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceProfile deviceProfile) {
this.handler.onDeviceProfileUpdate(sessionInfo, deviceProfile);
}
@Override
public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) {
this.handler.onDeviceUpdate(sessionInfo, device, deviceProfileOpt);
}
@Override
public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) {
log.trace("[{}] Received RPC command to device", sessionId);
this.rpcHandler.onToDeviceRpcRequest(toDeviceRequest, this.sessionInfo);
}
@Override
public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) {
this.rpcHandler.onToServerRpcResponse(toServerResponse);
}
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
log.info("[{}] operationComplete", future);
}
@Override
public void onResourceUpdate(TransportProtos.ResourceUpdateMsg resourceUpdateMsgOpt) {
if (ResourceType.LWM2M_MODEL.name().equals(resourceUpdateMsgOpt.getResourceType())) {
this.handler.onResourceUpdate(resourceUpdateMsgOpt);
}
}
@Override
public void onResourceDelete(TransportProtos.ResourceDeleteMsg resourceDeleteMsgOpt) {
if (ResourceType.LWM2M_MODEL.name().equals(resourceDeleteMsgOpt.getResourceType())) {
this.handler.onResourceDelete(resourceDeleteMsgOpt);
}
}
@Override
public void onDeviceDeleted(DeviceId deviceId) {
log.trace("[{}] Device on delete", deviceId);
this.handler.onDeviceDelete(deviceId);
}
}
|
3e0ad1b01b08169bdf1becb9dafb019aa92f190a | 2,562 | java | Java | _/Chapter 2/SensorPlay/app/src/main/java/com/sensorplay/SensorCapabilityActivity.java | paullewallencom/android-978-1-7852-8550-9 | 29b8cd0a628613effa7806d314dedb38ce6f99cd | [
"Apache-2.0"
] | 15 | 2016-12-09T07:53:14.000Z | 2021-10-01T22:12:03.000Z | _/Chapter 2/SensorPlay/app/src/main/java/com/sensorplay/SensorCapabilityActivity.java | paullewallencom/android-978-1-7852-8550-9 | 29b8cd0a628613effa7806d314dedb38ce6f99cd | [
"Apache-2.0"
] | 2 | 2016-05-25T21:59:29.000Z | 2018-07-02T08:10:59.000Z | _/Chapter 2/SensorPlay/app/src/main/java/com/sensorplay/SensorCapabilityActivity.java | paullewallencom/android-978-1-7852-8550-9 | 29b8cd0a628613effa7806d314dedb38ce6f99cd | [
"Apache-2.0"
] | 19 | 2016-05-25T22:17:48.000Z | 2022-03-07T18:17:59.000Z | 36.084507 | 93 | 0.803669 | 4,581 | package com.sensorplay;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.View;
import android.widget.TextView;
public class SensorCapabilityActivity extends Activity {
private SensorManager mSensorManager;
private int mSensorType;
private Sensor mSensor;
private TextView mSensorNameTextView;
private TextView mSensorMaximumRangeTextView;
private TextView mSensorMinDelayTextView;
private TextView mSensorPowerTextView;
private TextView mSensorResolutionTextView;
private TextView mSensorVendorTextView;
private TextView mSensorVersionTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.capability_layout);
Intent intent = getIntent();
mSensorType = intent.getIntExtra(getResources().getResourceName(R.string.sensor_type), 0);
mSensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(mSensorType);
mSensorNameTextView = (TextView)findViewById(R.id.sensor_name);
mSensorMaximumRangeTextView = (TextView)findViewById(R.id.sensor_range);
mSensorMinDelayTextView = (TextView)findViewById(R.id.sensor_mindelay);
mSensorPowerTextView = (TextView)findViewById(R.id.sensor_power);
mSensorResolutionTextView = (TextView)findViewById(R.id.sensor_resolution);
mSensorVendorTextView = (TextView)findViewById(R.id.sensor_vendor);
mSensorVersionTextView = (TextView)findViewById(R.id.sensor_version);
mSensorNameTextView.setText(mSensor.getName());
mSensorMaximumRangeTextView.setText(String.valueOf(mSensor.getMaximumRange()));
mSensorMinDelayTextView.setText(String.valueOf(mSensor.getMinDelay()));
mSensorPowerTextView.setText(String.valueOf(mSensor.getPower()));
mSensorResolutionTextView.setText(String.valueOf(mSensor.getResolution()));
mSensorVendorTextView.setText(String.valueOf(mSensor.getVendor()));
mSensorVersionTextView.setText(String.valueOf(mSensor.getVersion()));
}
public void onClickSensorValues(View v)
{
Intent intent = new Intent(getApplicationContext(), SensorValuesActivity.class);
intent.putExtra(getResources().getResourceName(R.string.sensor_type), mSensorType);
startActivity(intent);
}
@Override
public void onBackPressed() {
finish();
NavUtils.navigateUpFromSameTask(this);
}
}
|
3e0ad1b7cd75e7e5146de0bb1d818088629bbb00 | 261 | java | Java | src/main/java/br/com/luciano/npj/repository/filter/AlunoFilter.java | AntonioLimaSilva/Projeto-com-Spring-Framework | 965b634084f855c629ed0ef5dc8d9361c7512d19 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/luciano/npj/repository/filter/AlunoFilter.java | AntonioLimaSilva/Projeto-com-Spring-Framework | 965b634084f855c629ed0ef5dc8d9361c7512d19 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/luciano/npj/repository/filter/AlunoFilter.java | AntonioLimaSilva/Projeto-com-Spring-Framework | 965b634084f855c629ed0ef5dc8d9361c7512d19 | [
"Apache-2.0"
] | null | null | null | 14.5 | 45 | 0.731801 | 4,582 | package br.com.luciano.npj.repository.filter;
import br.com.luciano.npj.model.Pessoa;
public class AlunoFilter {
private Pessoa pessoa;
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
}
|
3e0ad2a58785f2d228f2916eed9649e6371d1c6e | 32,137 | java | Java | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/async/AsyncWaitOperatorTest.java | Shih-Wei-Hsu/flink | 3fed93d62d8f79627d4ded2dd1fae6fae91b36e8 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | 41 | 2018-11-14T04:05:42.000Z | 2022-02-09T10:39:23.000Z | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/async/AsyncWaitOperatorTest.java | Shih-Wei-Hsu/flink | 3fed93d62d8f79627d4ded2dd1fae6fae91b36e8 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | 15 | 2021-06-13T18:06:12.000Z | 2022-02-09T22:40:04.000Z | flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/async/AsyncWaitOperatorTest.java | houmaozheng/flink | ef692d0967daf8f532d9011122e1d3104a07fb39 | [
"Apache-2.0"
] | 16 | 2019-01-04T09:19:03.000Z | 2022-01-10T14:34:31.000Z | 34.742703 | 121 | 0.764539 | 4,583 | /*
* 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.flink.streaming.api.operators.async;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.base.IntSerializer;
import org.apache.flink.api.java.Utils;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.testutils.OneShotLatch;
import org.apache.flink.runtime.checkpoint.CheckpointMetaData;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.io.network.api.CheckpointBarrier;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.operators.testutils.MockEnvironment;
import org.apache.flink.runtime.state.TestTaskStateManager;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.async.AsyncFunction;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
import org.apache.flink.streaming.api.graph.StreamConfig;
import org.apache.flink.streaming.api.operators.ChainingStrategy;
import org.apache.flink.streaming.api.operators.async.queue.StreamElementQueue;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamElement;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.runtime.tasks.OneInputStreamTask;
import org.apache.flink.streaming.runtime.tasks.OneInputStreamTaskTestHarness;
import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness;
import org.apache.flink.streaming.util.TestHarnessUtil;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.TestLogger;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Tests for {@link AsyncWaitOperator}. These test that:
*
* <ul>
* <li>Process StreamRecords and Watermarks in ORDERED mode</li>
* <li>Process StreamRecords and Watermarks in UNORDERED mode</li>
* <li>AsyncWaitOperator in operator chain</li>
* <li>Snapshot state and restore state</li>
* </ul>
*/
public class AsyncWaitOperatorTest extends TestLogger {
private static final long TIMEOUT = 1000L;
@Rule
public Timeout timeoutRule = new Timeout(10, TimeUnit.SECONDS);
private static class MyAsyncFunction extends RichAsyncFunction<Integer, Integer> {
private static final long serialVersionUID = 8522411971886428444L;
private static final long TERMINATION_TIMEOUT = 5000L;
private static final int THREAD_POOL_SIZE = 10;
static ExecutorService executorService;
static int counter = 0;
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
synchronized (MyAsyncFunction.class) {
if (counter == 0) {
executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
++counter;
}
}
@Override
public void close() throws Exception {
super.close();
freeExecutor();
}
private void freeExecutor() {
synchronized (MyAsyncFunction.class) {
--counter;
if (counter == 0) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException interrupted) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
}
@Override
public void asyncInvoke(final Integer input, final ResultFuture<Integer> resultFuture) throws Exception {
executorService.submit(new Runnable() {
@Override
public void run() {
resultFuture.complete(Collections.singletonList(input * 2));
}
});
}
}
/**
* A special {@link AsyncFunction} without issuing
* {@link ResultFuture#complete} until the latch counts to zero.
* {@link ResultFuture#complete} until the latch counts to zero.
* This function is used in the testStateSnapshotAndRestore, ensuring
* that {@link StreamElement} can stay
* in the {@link StreamElementQueue} to be
* snapshotted while checkpointing.
*/
private static class LazyAsyncFunction extends MyAsyncFunction {
private static final long serialVersionUID = 3537791752703154670L;
private static CountDownLatch latch;
public LazyAsyncFunction() {
latch = new CountDownLatch(1);
}
@Override
public void asyncInvoke(final Integer input, final ResultFuture<Integer> resultFuture) throws Exception {
this.executorService.submit(new Runnable() {
@Override
public void run() {
try {
latch.await();
}
catch (InterruptedException e) {
// do nothing
}
resultFuture.complete(Collections.singletonList(input));
}
});
}
public static void countDown() {
latch.countDown();
}
}
/**
* A special {@link LazyAsyncFunction} for timeout handling.
* Complete the result future with 3 times the input when the timeout occurred.
*/
private static class IgnoreTimeoutLazyAsyncFunction extends LazyAsyncFunction {
private static final long serialVersionUID = 1428714561365346128L;
@Override
public void timeout(Integer input, ResultFuture<Integer> resultFuture) throws Exception {
resultFuture.complete(Collections.singletonList(input * 3));
}
}
/**
* A {@link Comparator} to compare {@link StreamRecord} while sorting them.
*/
private class StreamRecordComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Watermark || o2 instanceof Watermark) {
return 0;
} else {
StreamRecord<Integer> sr0 = (StreamRecord<Integer>) o1;
StreamRecord<Integer> sr1 = (StreamRecord<Integer>) o2;
if (sr0.getTimestamp() != sr1.getTimestamp()) {
return (int) (sr0.getTimestamp() - sr1.getTimestamp());
}
int comparison = sr0.getValue().compareTo(sr1.getValue());
if (comparison != 0) {
return comparison;
} else {
return sr0.getValue() - sr1.getValue();
}
}
}
}
/**
* Test the AsyncWaitOperator with ordered mode and event time.
*/
@Test
public void testEventTimeOrdered() throws Exception {
testEventTime(AsyncDataStream.OutputMode.ORDERED);
}
/**
* Test the AsyncWaitOperator with unordered mode and event time.
*/
@Test
public void testWaterMarkUnordered() throws Exception {
testEventTime(AsyncDataStream.OutputMode.UNORDERED);
}
private void testEventTime(AsyncDataStream.OutputMode mode) throws Exception {
final OneInputStreamOperatorTestHarness<Integer, Integer> testHarness =
createTestHarness(new MyAsyncFunction(), TIMEOUT, 2, mode);
final long initialTime = 0L;
final ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
synchronized (testHarness.getCheckpointLock()) {
testHarness.processElement(new StreamRecord<>(1, initialTime + 1));
testHarness.processElement(new StreamRecord<>(2, initialTime + 2));
testHarness.processWatermark(new Watermark(initialTime + 2));
testHarness.processElement(new StreamRecord<>(3, initialTime + 3));
}
// wait until all async collectors in the buffer have been emitted out.
synchronized (testHarness.getCheckpointLock()) {
testHarness.endInput();
testHarness.close();
}
expectedOutput.add(new StreamRecord<>(2, initialTime + 1));
expectedOutput.add(new StreamRecord<>(4, initialTime + 2));
expectedOutput.add(new Watermark(initialTime + 2));
expectedOutput.add(new StreamRecord<>(6, initialTime + 3));
if (AsyncDataStream.OutputMode.ORDERED == mode) {
TestHarnessUtil.assertOutputEquals("Output with watermark was not correct.", expectedOutput, testHarness.getOutput());
}
else {
Object[] jobOutputQueue = testHarness.getOutput().toArray();
Assert.assertEquals("Watermark should be at index 2", new Watermark(initialTime + 2), jobOutputQueue[2]);
Assert.assertEquals("StreamRecord 3 should be at the end", new StreamRecord<>(6, initialTime + 3), jobOutputQueue[3]);
TestHarnessUtil.assertOutputEqualsSorted(
"Output for StreamRecords does not match",
expectedOutput,
testHarness.getOutput(),
new StreamRecordComparator());
}
}
/**
* Test the AsyncWaitOperator with ordered mode and processing time.
*/
@Test
public void testProcessingTimeOrdered() throws Exception {
testProcessingTime(AsyncDataStream.OutputMode.ORDERED);
}
/**
* Test the AsyncWaitOperator with unordered mode and processing time.
*/
@Test
public void testProcessingUnordered() throws Exception {
testProcessingTime(AsyncDataStream.OutputMode.UNORDERED);
}
private void testProcessingTime(AsyncDataStream.OutputMode mode) throws Exception {
final OneInputStreamOperatorTestHarness<Integer, Integer> testHarness =
createTestHarness(new MyAsyncFunction(), TIMEOUT, 6, mode);
final long initialTime = 0L;
final Queue<Object> expectedOutput = new ArrayDeque<>();
testHarness.open();
synchronized (testHarness.getCheckpointLock()) {
testHarness.processElement(new StreamRecord<>(1, initialTime + 1));
testHarness.processElement(new StreamRecord<>(2, initialTime + 2));
testHarness.processElement(new StreamRecord<>(3, initialTime + 3));
testHarness.processElement(new StreamRecord<>(4, initialTime + 4));
testHarness.processElement(new StreamRecord<>(5, initialTime + 5));
testHarness.processElement(new StreamRecord<>(6, initialTime + 6));
testHarness.processElement(new StreamRecord<>(7, initialTime + 7));
testHarness.processElement(new StreamRecord<>(8, initialTime + 8));
}
expectedOutput.add(new StreamRecord<>(2, initialTime + 1));
expectedOutput.add(new StreamRecord<>(4, initialTime + 2));
expectedOutput.add(new StreamRecord<>(6, initialTime + 3));
expectedOutput.add(new StreamRecord<>(8, initialTime + 4));
expectedOutput.add(new StreamRecord<>(10, initialTime + 5));
expectedOutput.add(new StreamRecord<>(12, initialTime + 6));
expectedOutput.add(new StreamRecord<>(14, initialTime + 7));
expectedOutput.add(new StreamRecord<>(16, initialTime + 8));
synchronized (testHarness.getCheckpointLock()) {
testHarness.endInput();
testHarness.close();
}
if (mode == AsyncDataStream.OutputMode.ORDERED) {
TestHarnessUtil.assertOutputEquals("ORDERED Output was not correct.", expectedOutput, testHarness.getOutput());
}
else {
TestHarnessUtil.assertOutputEqualsSorted(
"UNORDERED Output was not correct.",
expectedOutput,
testHarness.getOutput(),
new StreamRecordComparator());
}
}
/**
* Tests that the AsyncWaitOperator works together with chaining.
*/
@Test
public void testOperatorChainWithProcessingTime() throws Exception {
JobVertex chainedVertex = createChainedVertex(new MyAsyncFunction(), new MyAsyncFunction());
final OneInputStreamTaskTestHarness<Integer, Integer> testHarness = new OneInputStreamTaskTestHarness<>(
OneInputStreamTask::new,
1, 1,
BasicTypeInfo.INT_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO);
testHarness.setupOutputForSingletonOperatorChain();
testHarness.taskConfig = chainedVertex.getConfiguration();
final StreamConfig streamConfig = testHarness.getStreamConfig();
final StreamConfig operatorChainStreamConfig = new StreamConfig(chainedVertex.getConfiguration());
streamConfig.setStreamOperatorFactory(
operatorChainStreamConfig.getStreamOperatorFactory(AsyncWaitOperatorTest.class.getClassLoader()));
testHarness.invoke();
testHarness.waitForTaskRunning();
long initialTimestamp = 0L;
testHarness.processElement(new StreamRecord<>(5, initialTimestamp));
testHarness.processElement(new StreamRecord<>(6, initialTimestamp + 1L));
testHarness.processElement(new StreamRecord<>(7, initialTimestamp + 2L));
testHarness.processElement(new StreamRecord<>(8, initialTimestamp + 3L));
testHarness.processElement(new StreamRecord<>(9, initialTimestamp + 4L));
testHarness.endInput();
testHarness.waitForTaskCompletion();
List<Object> expectedOutput = new LinkedList<>();
expectedOutput.add(new StreamRecord<>(22, initialTimestamp));
expectedOutput.add(new StreamRecord<>(26, initialTimestamp + 1L));
expectedOutput.add(new StreamRecord<>(30, initialTimestamp + 2L));
expectedOutput.add(new StreamRecord<>(34, initialTimestamp + 3L));
expectedOutput.add(new StreamRecord<>(38, initialTimestamp + 4L));
TestHarnessUtil.assertOutputEqualsSorted(
"Test for chained operator with AsyncWaitOperator failed",
expectedOutput,
testHarness.getOutput(),
new StreamRecordComparator());
}
private JobVertex createChainedVertex(
AsyncFunction<Integer, Integer> firstFunction,
AsyncFunction<Integer, Integer> secondFunction) {
StreamExecutionEnvironment chainEnv = StreamExecutionEnvironment.getExecutionEnvironment();
// set parallelism to 2 to avoid chaining with source in case when available processors is 1.
chainEnv.setParallelism(2);
// the input is only used to construct a chained operator, and they will not be used in the real tests.
DataStream<Integer> input = chainEnv.fromElements(1, 2, 3);
input = addAsyncOperatorLegacyChained(
input,
firstFunction,
TIMEOUT,
6,
AsyncDataStream.OutputMode.ORDERED);
// the map function is designed to chain after async function. we place an Integer object in it and
// it is initialized in the open() method.
// it is used to verify that operators in the operator chain should be opened from the tail to the head,
// so the result from AsyncWaitOperator can pass down successfully and correctly.
// if not, the test can not be passed.
input = input.map(new RichMapFunction<Integer, Integer>() {
private static final long serialVersionUID = 1L;
private Integer initialValue = null;
@Override
public void open(Configuration parameters) throws Exception {
initialValue = 1;
}
@Override
public Integer map(Integer value) throws Exception {
return initialValue + value;
}
});
input = addAsyncOperatorLegacyChained(
input,
secondFunction,
TIMEOUT,
3,
AsyncDataStream.OutputMode.UNORDERED);
input.map(new MapFunction<Integer, Integer>() {
private static final long serialVersionUID = 5162085254238405527L;
@Override
public Integer map(Integer value) throws Exception {
return value;
}
}).startNewChain().addSink(new DiscardingSink<Integer>());
// be build our own OperatorChain
final JobGraph jobGraph = chainEnv.getStreamGraph().getJobGraph();
Assert.assertEquals(3, jobGraph.getVerticesSortedTopologicallyFromSources().size());
return jobGraph.getVerticesSortedTopologicallyFromSources().get(1);
}
@Test
public void testStateSnapshotAndRestore() throws Exception {
final OneInputStreamTaskTestHarness<Integer, Integer> testHarness = new OneInputStreamTaskTestHarness<>(
OneInputStreamTask::new,
1, 1,
BasicTypeInfo.INT_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO);
testHarness.setupOutputForSingletonOperatorChain();
AsyncWaitOperatorFactory<Integer, Integer> factory = new AsyncWaitOperatorFactory<>(
new LazyAsyncFunction(),
TIMEOUT,
4,
AsyncDataStream.OutputMode.ORDERED);
final StreamConfig streamConfig = testHarness.getStreamConfig();
OperatorID operatorID = new OperatorID(42L, 4711L);
streamConfig.setStreamOperatorFactory(factory);
streamConfig.setOperatorID(operatorID);
final TestTaskStateManager taskStateManagerMock = testHarness.getTaskStateManager();
taskStateManagerMock.setWaitForReportLatch(new OneShotLatch());
testHarness.invoke();
testHarness.waitForTaskRunning();
final OneInputStreamTask<Integer, Integer> task = testHarness.getTask();
final long initialTime = 0L;
testHarness.processElement(new StreamRecord<>(1, initialTime + 1));
testHarness.processElement(new StreamRecord<>(2, initialTime + 2));
testHarness.processElement(new StreamRecord<>(3, initialTime + 3));
testHarness.processElement(new StreamRecord<>(4, initialTime + 4));
testHarness.waitForInputProcessing();
final long checkpointId = 1L;
final long checkpointTimestamp = 1L;
final CheckpointMetaData checkpointMetaData = new CheckpointMetaData(checkpointId, checkpointTimestamp);
task.triggerCheckpointAsync(checkpointMetaData, CheckpointOptions.forCheckpointWithDefaultLocation(), false);
taskStateManagerMock.getWaitForReportLatch().await();
assertEquals(checkpointId, taskStateManagerMock.getReportedCheckpointId());
LazyAsyncFunction.countDown();
testHarness.endInput();
testHarness.waitForTaskCompletion();
// set the operator state from previous attempt into the restored one
TaskStateSnapshot subtaskStates = taskStateManagerMock.getLastJobManagerTaskStateSnapshot();
final OneInputStreamTaskTestHarness<Integer, Integer> restoredTaskHarness =
new OneInputStreamTaskTestHarness<>(
OneInputStreamTask::new,
BasicTypeInfo.INT_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO);
restoredTaskHarness.setTaskStateSnapshot(checkpointId, subtaskStates);
restoredTaskHarness.setupOutputForSingletonOperatorChain();
AsyncWaitOperatorFactory<Integer, Integer> restoredOperator = new AsyncWaitOperatorFactory<>(
new MyAsyncFunction(),
TIMEOUT,
6,
AsyncDataStream.OutputMode.ORDERED);
restoredTaskHarness.getStreamConfig().setStreamOperatorFactory(restoredOperator);
restoredTaskHarness.getStreamConfig().setOperatorID(operatorID);
restoredTaskHarness.invoke();
restoredTaskHarness.waitForTaskRunning();
final OneInputStreamTask<Integer, Integer> restoredTask = restoredTaskHarness.getTask();
restoredTaskHarness.processElement(new StreamRecord<>(5, initialTime + 5));
restoredTaskHarness.processElement(new StreamRecord<>(6, initialTime + 6));
restoredTaskHarness.processElement(new StreamRecord<>(7, initialTime + 7));
// trigger the checkpoint while processing stream elements
restoredTask.triggerCheckpointAsync(
new CheckpointMetaData(checkpointId, checkpointTimestamp),
CheckpointOptions.forCheckpointWithDefaultLocation(),
false)
.get();
restoredTaskHarness.processElement(new StreamRecord<>(8, initialTime + 8));
restoredTaskHarness.endInput();
restoredTaskHarness.waitForTaskCompletion();
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
expectedOutput.add(new StreamRecord<>(2, initialTime + 1));
expectedOutput.add(new StreamRecord<>(4, initialTime + 2));
expectedOutput.add(new StreamRecord<>(6, initialTime + 3));
expectedOutput.add(new StreamRecord<>(8, initialTime + 4));
expectedOutput.add(new StreamRecord<>(10, initialTime + 5));
expectedOutput.add(new StreamRecord<>(12, initialTime + 6));
expectedOutput.add(new StreamRecord<>(14, initialTime + 7));
expectedOutput.add(new StreamRecord<>(16, initialTime + 8));
// remove CheckpointBarrier which is not expected
restoredTaskHarness.getOutput()
.removeIf(record -> record instanceof CheckpointBarrier);
TestHarnessUtil.assertOutputEquals(
"StateAndRestored Test Output was not correct.",
expectedOutput,
restoredTaskHarness.getOutput());
}
@Test
public void testAsyncTimeoutFailure() throws Exception {
testAsyncTimeout(
new LazyAsyncFunction(),
Optional.of(TimeoutException.class),
new StreamRecord<>(2, 5L));
}
@Test
public void testAsyncTimeoutIgnore() throws Exception {
testAsyncTimeout(
new IgnoreTimeoutLazyAsyncFunction(),
Optional.empty(),
new StreamRecord<>(3, 0L),
new StreamRecord<>(2, 5L));
}
private void testAsyncTimeout(
LazyAsyncFunction lazyAsyncFunction,
Optional<Class<? extends Throwable>> expectedException,
StreamRecord<Integer>... expectedRecords) throws Exception {
final long timeout = 10L;
final OneInputStreamOperatorTestHarness<Integer, Integer> testHarness =
createTestHarness(lazyAsyncFunction, timeout, 2, AsyncDataStream.OutputMode.ORDERED);
final MockEnvironment mockEnvironment = testHarness.getEnvironment();
mockEnvironment.setExpectedExternalFailureCause(Throwable.class);
final long initialTime = 0L;
final ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.setProcessingTime(initialTime);
synchronized (testHarness.getCheckpointLock()) {
testHarness.processElement(new StreamRecord<>(1, initialTime));
testHarness.setProcessingTime(initialTime + 5L);
testHarness.processElement(new StreamRecord<>(2, initialTime + 5L));
}
// trigger the timeout of the first stream record
testHarness.setProcessingTime(initialTime + timeout + 1L);
// allow the second async stream record to be processed
lazyAsyncFunction.countDown();
// wait until all async collectors in the buffer have been emitted out.
synchronized (testHarness.getCheckpointLock()) {
testHarness.endInput();
testHarness.close();
}
expectedOutput.addAll(Arrays.asList(expectedRecords));
TestHarnessUtil.assertOutputEquals("Output with watermark was not correct.", expectedOutput, testHarness.getOutput());
if (expectedException.isPresent()) {
assertTrue(mockEnvironment.getActualExternalFailureCause().isPresent());
assertTrue(ExceptionUtils.findThrowable(
mockEnvironment.getActualExternalFailureCause().get(),
expectedException.get()).isPresent());
}
}
/**
* FLINK-5652
* Tests that registered timers are properly canceled upon completion of a
* {@link StreamElement} in order to avoid resource leaks because TriggerTasks hold
* a reference on the StreamRecordQueueEntry.
*/
@Test
public void testTimeoutCleanup() throws Exception {
OneInputStreamOperatorTestHarness<Integer, Integer> harness =
createTestHarness(new MyAsyncFunction(), TIMEOUT, 1, AsyncDataStream.OutputMode.UNORDERED);
harness.open();
synchronized (harness.getCheckpointLock()) {
harness.processElement(42, 1L);
}
synchronized (harness.getCheckpointLock()) {
harness.endInput();
harness.close();
}
// check that we actually outputted the result of the single input
assertEquals(Arrays.asList(new StreamRecord(42 * 2, 1L)), new ArrayList<>(harness.getOutput()));
// check that we have cancelled our registered timeout
assertEquals(0, harness.getProcessingTimeService().getNumActiveTimers());
}
/**
* FLINK-6435
*
* <p>Tests that a user exception triggers the completion of a StreamElementQueueEntry and does not wait to until
* another StreamElementQueueEntry is properly completed before it is collected.
*/
@Test
public void testOrderedWaitUserExceptionHandling() throws Exception {
testUserExceptionHandling(AsyncDataStream.OutputMode.ORDERED);
}
/**
* FLINK-6435
*
* <p>Tests that a user exception triggers the completion of a StreamElementQueueEntry and does not wait to until
* another StreamElementQueueEntry is properly completed before it is collected.
*/
@Test
public void testUnorderedWaitUserExceptionHandling() throws Exception {
testUserExceptionHandling(AsyncDataStream.OutputMode.UNORDERED);
}
private void testUserExceptionHandling(AsyncDataStream.OutputMode outputMode) throws Exception {
OneInputStreamOperatorTestHarness<Integer, Integer> harness =
createTestHarness(new UserExceptionAsyncFunction(), TIMEOUT, 2, outputMode);
harness.getEnvironment().setExpectedExternalFailureCause(Throwable.class);
harness.open();
synchronized (harness.getCheckpointLock()) {
harness.processElement(1, 1L);
}
synchronized (harness.getCheckpointLock()) {
harness.close();
}
assertTrue(harness.getEnvironment().getActualExternalFailureCause().isPresent());
}
/**
* AsyncFunction which completes the result with an {@link Exception}.
*/
private static class UserExceptionAsyncFunction implements AsyncFunction<Integer, Integer> {
private static final long serialVersionUID = 6326568632967110990L;
@Override
public void asyncInvoke(Integer input, ResultFuture<Integer> resultFuture) throws Exception {
resultFuture.completeExceptionally(new Exception("Test exception"));
}
}
/**
* FLINK-6435
*
* <p>Tests that timeout exceptions are properly handled in ordered output mode. The proper handling means that
* a StreamElementQueueEntry is completed in case of a timeout exception.
*/
@Test
public void testOrderedWaitTimeoutHandling() throws Exception {
testTimeoutExceptionHandling(AsyncDataStream.OutputMode.ORDERED);
}
/**
* FLINK-6435
*
* <p>Tests that timeout exceptions are properly handled in ordered output mode. The proper handling means that
* a StreamElementQueueEntry is completed in case of a timeout exception.
*/
@Test
public void testUnorderedWaitTimeoutHandling() throws Exception {
testTimeoutExceptionHandling(AsyncDataStream.OutputMode.UNORDERED);
}
private void testTimeoutExceptionHandling(AsyncDataStream.OutputMode outputMode) throws Exception {
OneInputStreamOperatorTestHarness<Integer, Integer> harness =
createTestHarness(new NoOpAsyncFunction<>(), 10L, 2, outputMode);
harness.getEnvironment().setExpectedExternalFailureCause(Throwable.class);
harness.open();
synchronized (harness.getCheckpointLock()) {
harness.processElement(1, 1L);
}
harness.setProcessingTime(10L);
synchronized (harness.getCheckpointLock()) {
harness.close();
}
}
/**
* Tests that the AysncWaitOperator can restart if checkpointed queue was full.
*
* <p>See FLINK-7949
*/
@Test(timeout = 10000)
public void testRestartWithFullQueue() throws Exception {
final int capacity = 10;
// 1. create the snapshot which contains capacity + 1 elements
final CompletableFuture<Void> trigger = new CompletableFuture<>();
final OneInputStreamOperatorTestHarness<Integer, Integer> snapshotHarness = createTestHarness(
new ControllableAsyncFunction<>(trigger), // the NoOpAsyncFunction is like a blocking function
1000L,
capacity,
AsyncDataStream.OutputMode.ORDERED);
snapshotHarness.open();
final OperatorSubtaskState snapshot;
final ArrayList<Integer> expectedOutput = new ArrayList<>(capacity);
try {
synchronized (snapshotHarness.getCheckpointLock()) {
for (int i = 0; i < capacity; i++) {
snapshotHarness.processElement(i, 0L);
expectedOutput.add(i);
}
}
synchronized (snapshotHarness.getCheckpointLock()) {
// execute the snapshot within the checkpoint lock, because then it is guaranteed
// that the lastElementWriter has written the exceeding element
snapshot = snapshotHarness.snapshot(0L, 0L);
}
// trigger the computation to make the close call finish
trigger.complete(null);
} finally {
synchronized (snapshotHarness.getCheckpointLock()) {
snapshotHarness.close();
}
}
// 2. restore the snapshot and check that we complete
final OneInputStreamOperatorTestHarness<Integer, Integer> recoverHarness = createTestHarness(
new ControllableAsyncFunction<>(CompletableFuture.completedFuture(null)),
1000L,
capacity,
AsyncDataStream.OutputMode.ORDERED);
recoverHarness.initializeState(snapshot);
synchronized (recoverHarness.getCheckpointLock()) {
recoverHarness.open();
}
synchronized (recoverHarness.getCheckpointLock()) {
recoverHarness.endInput();
recoverHarness.close();
}
final ConcurrentLinkedQueue<Object> output = recoverHarness.getOutput();
final List<Integer> outputElements = output.stream()
.map(r -> ((StreamRecord<Integer>) r).getValue())
.collect(Collectors.toList());
assertThat(outputElements, Matchers.equalTo(expectedOutput));
}
private static class ControllableAsyncFunction<IN> implements AsyncFunction<IN, IN> {
private static final long serialVersionUID = -4214078239267288636L;
private transient CompletableFuture<Void> trigger;
private ControllableAsyncFunction(CompletableFuture<Void> trigger) {
this.trigger = Preconditions.checkNotNull(trigger);
}
@Override
public void asyncInvoke(IN input, ResultFuture<IN> resultFuture) throws Exception {
trigger.thenAccept(v -> resultFuture.complete(Collections.singleton(input)));
}
}
private static class NoOpAsyncFunction<IN, OUT> implements AsyncFunction<IN, OUT> {
private static final long serialVersionUID = -3060481953330480694L;
@Override
public void asyncInvoke(IN input, ResultFuture<OUT> resultFuture) throws Exception {
// no op
}
}
/**
* This helper function is needed to check that the temporary fix for FLINK-13063 can be backwards compatible with
* the old chaining behavior by setting the ChainingStrategy manually. TODO: remove after a proper fix for
* FLINK-13063 is in place that allows chaining.
*/
private <IN, OUT> SingleOutputStreamOperator<OUT> addAsyncOperatorLegacyChained(
DataStream<IN> in,
AsyncFunction<IN, OUT> func,
long timeout,
int bufSize,
AsyncDataStream.OutputMode mode) {
TypeInformation<OUT> outTypeInfo = TypeExtractor.getUnaryOperatorReturnType(
func,
AsyncFunction.class,
0,
1,
new int[]{1, 0},
in.getType(),
Utils.getCallLocationName(),
true);
// create transform
AsyncWaitOperatorFactory<IN, OUT> factory = new AsyncWaitOperatorFactory<>(
in.getExecutionEnvironment().clean(func),
timeout,
bufSize,
mode);
factory.setChainingStrategy(ChainingStrategy.ALWAYS);
return in.transform("async wait operator", outTypeInfo, factory);
}
private static <OUT> OneInputStreamOperatorTestHarness<Integer, OUT> createTestHarness(
AsyncFunction<Integer, OUT> function,
long timeout,
int capacity,
AsyncDataStream.OutputMode outputMode) throws Exception {
return new OneInputStreamOperatorTestHarness<>(
new AsyncWaitOperatorFactory<>(function, timeout, capacity, outputMode),
IntSerializer.INSTANCE);
}
}
|
3e0ad3dfd60d795956527c4b16dfa574d581df41 | 1,558 | java | Java | src/main/java/io/solidloop/jetbrains/ide/serverlessframeworkgui/command/InvokeFunctionCommand.java | plamen-paskov/serverless-framework-gui | 36e0ed02aac9264610bd97f17cb9150f4286bab5 | [
"MIT"
] | 2 | 2019-12-26T20:28:03.000Z | 2020-12-17T11:34:03.000Z | src/main/java/io/solidloop/jetbrains/ide/serverlessframeworkgui/command/InvokeFunctionCommand.java | plamen-paskov/serverless-framework-gui | 36e0ed02aac9264610bd97f17cb9150f4286bab5 | [
"MIT"
] | 21 | 2019-04-02T09:31:21.000Z | 2022-03-04T08:35:49.000Z | src/main/java/io/solidloop/jetbrains/ide/serverlessframeworkgui/command/InvokeFunctionCommand.java | plamen-paskov/serverless-framework-gui | 36e0ed02aac9264610bd97f17cb9150f4286bab5 | [
"MIT"
] | null | null | null | 31.16 | 180 | 0.644416 | 4,584 | package io.solidloop.jetbrains.ide.serverlessframeworkgui.command;
import io.solidloop.jetbrains.ide.serverlessframeworkgui.function.Function;
import io.solidloop.jetbrains.ide.serverlessframeworkgui.service.Service;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class InvokeFunctionCommand extends AbstractCommand {
private Function function;
public InvokeFunctionCommand(CommandArguments commandArguments, Function function) {
super(commandArguments);
this.function = function;
}
@Override
public List<String> getCommand() {
Service service = function.getService();
List<String> command = new ArrayList<>();
command.add(commandArguments.getServerlessExecutable());
command.add("invoke");
command.add("-f");
command.add(function.getName());
if (service.getRegion() != null) {
command.add("-r");
command.add(function.getService().getRegion());
}
String dataFile = getDataFile(function);
File file = new File(dataFile);
if (!file.exists()) {
command.add("-d");
command.add("{}");
} else {
command.add("-p");
command.add(dataFile);
}
return command;
}
private String getDataFile(Function function) {
return function.getService().getFile().getParent().getCanonicalPath() + "/serverless-framework-gui/" + function.getService().getName() + "/" + function.getName() + ".json";
}
}
|
3e0ad5200024eaa1fcc2a6aea22a9d837d207818 | 14,958 | java | Java | Components/CommonCore/Source/gov/sandia/cognition/math/matrix/mtj/DiagonalMatrixMTJ.java | Markoy8/Foundry | c3ec00a8efe08a25dd5eae7150b788e4486c0e6e | [
"BSD-3-Clause"
] | 122 | 2015-01-19T17:36:40.000Z | 2022-02-25T20:22:22.000Z | Components/CommonCore/Source/gov/sandia/cognition/math/matrix/mtj/DiagonalMatrixMTJ.java | Markoy8/Foundry | c3ec00a8efe08a25dd5eae7150b788e4486c0e6e | [
"BSD-3-Clause"
] | 45 | 2015-01-23T06:28:33.000Z | 2021-05-18T19:11:29.000Z | Components/CommonCore/Source/gov/sandia/cognition/math/matrix/mtj/DiagonalMatrixMTJ.java | Markoy8/Foundry | c3ec00a8efe08a25dd5eae7150b788e4486c0e6e | [
"BSD-3-Clause"
] | 42 | 2015-01-20T03:07:17.000Z | 2021-08-18T08:51:55.000Z | 25.525597 | 89 | 0.544926 | 4,585 | /*
* File: DiagonalMatrixMTJ.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright Sep 19, 2008, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government.
* Export of this program may require a license from the United States
* Government. See CopyrightHistory.txt for complete details.
*
*/
package gov.sandia.cognition.math.matrix.mtj;
import gov.sandia.cognition.annotation.PublicationReference;
import gov.sandia.cognition.annotation.PublicationType;
import gov.sandia.cognition.math.ComplexNumber;
import gov.sandia.cognition.math.matrix.DiagonalMatrix;
import gov.sandia.cognition.math.matrix.Matrix;
import gov.sandia.cognition.math.matrix.MatrixFactory;
import gov.sandia.cognition.math.matrix.Vector;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.NumberFormat;
/**
* A diagonal matrix that wraps MTJ's BandMatrix class.
* @author Kevin R. Dixon
* @since 2.1
*/
@PublicationReference(
author="Bjorn-Ove Heimsund",
title="Matrix Toolkits for Java BandMatrix",
type=PublicationType.WebPage,
year=2006,
url="http://ressim.berlios.de/doc/no/uib/cipr/matrix/BandMatrix.html",
notes="This class wraps the BandMatrix class from Heimsund's MTJ package"
)
public class DiagonalMatrixMTJ
extends AbstractMTJMatrix
implements DiagonalMatrix
{
/**
* Creates a new instance of DiagonalMatrixMTJ
* @param dim
* Dimensionality of the square diagonal matrix
*/
protected DiagonalMatrixMTJ(
int dim )
{
super( new no.uib.cipr.matrix.BandMatrix( dim, 0, 0 ) );
}
/**
* Copy Constructor
* @param other DiagonalMatrixMTJ to copy
*/
protected DiagonalMatrixMTJ(
DiagonalMatrixMTJ other )
{
super( other.getInternalMatrix().copy() );
}
/**
* Creates a new instance of DiagonalMatrixMTJ
* @param diagonal
* Array of elements to set the diagonal to
*/
protected DiagonalMatrixMTJ(
double[] diagonal )
{
this( diagonal.length );
double[] actual = this.getDiagonal();
System.arraycopy(diagonal, 0, actual, 0, diagonal.length);
}
public int getDimensionality()
{
return this.getNumRows();
}
@Override
public no.uib.cipr.matrix.BandMatrix getInternalMatrix()
{
return (no.uib.cipr.matrix.BandMatrix) super.getInternalMatrix();
}
@Override
protected void setInternalMatrix(
no.uib.cipr.matrix.Matrix internalMatrix )
{
super.setInternalMatrix( (no.uib.cipr.matrix.BandMatrix) internalMatrix );
}
@Override
public AbstractMTJMatrix times(
AbstractMTJMatrix matrix )
{
this.assertMultiplicationDimensions(matrix);
final int M = this.getNumRows();
final int N = matrix.getNumColumns();
DenseMatrix retval = DenseMatrixFactoryMTJ.INSTANCE.createMatrix( M, N );
double[] diagonal = this.getDiagonal();
// The diagonal elements scale each row
for( int i = 0; i < M; i++ )
{
final double di = diagonal[i];
if( di != 0.0 )
{
for( int j = 0; j < N; j++ )
{
double vij = matrix.getElement( i, j );
if( vij != 0.0 )
{
retval.setElement( i, j, di*vij );
}
}
}
}
return retval;
}
@Override
public DiagonalMatrixMTJ times(
DiagonalMatrix matrix)
{
DiagonalMatrixMTJ clone = (DiagonalMatrixMTJ) this.clone();
clone.timesEquals(matrix);
return clone;
}
@Override
public void timesEquals(
DiagonalMatrix matrix)
{
if( !this.checkSameDimensions(matrix) )
{
throw new IllegalArgumentException( "Matrix must be the same size as this" );
}
final int M = this.getDimensionality();
// The diagonal elements scale each row
for( int i = 0; i < M; i++ )
{
final double d1i = this.getElement(i);
final double d2j = matrix.getElement(i);
final double v = d1i * d2j;
this.setElement(i, v);
}
}
@Override
public AbstractMTJVector times(
AbstractMTJVector vector )
{
final int M = this.getDimensionality();
if( M != vector.getDimensionality() )
{
throw new IllegalArgumentException(
"Number of Columns != vector.getDimensionality()" );
}
double[] diagonal = this.getDiagonal();
double[] retval = new double[ diagonal.length ];
for( int i = 0; i < M; i++ )
{
final double v2 = diagonal[i];
if( v2 != 0.0 )
{
final double v1 = vector.getElement( i );
if( v1 != 0.0 )
{
retval[i] = v1*v2;
}
}
}
return DenseVectorFactoryMTJ.INSTANCE.copyArray( retval );
}
@Override
public DiagonalMatrixMTJ dotTimes(
Matrix matrix )
{
DiagonalMatrixMTJ clone = (DiagonalMatrixMTJ) this.clone();
clone.dotTimesEquals( matrix );
return clone;
}
@Override
public void dotTimesEquals(
AbstractMTJMatrix matrix )
{
this.assertSameDimensions( matrix );
int M = this.getDimensionality();
double[] diagonal = this.getDiagonal();
for( int i = 0; i < M; i++ )
{
diagonal[i] *= matrix.getElement( i, i );
}
}
@Override
public boolean isSquare()
{
return true;
}
@Override
public boolean isSymmetric()
{
return true;
}
@Override
public boolean isSymmetric(
double effectiveZero )
{
return true;
}
@Override
public ComplexNumber logDeterminant()
{
// The diagonal elements (for either LU or QR) will be REAL, but
// they may be negative. The logarithm of a negative number is
// the logarithm of the absolute value of the number, with an
// imaginary part of PI. The exponential is all that matters, so
// the log-determinant is equivalent, MODULO PI (3.14...), so
// we just toggle this sign bit.
double logsum = 0.0;
int sign = 1;
double[] diagonal = this.getDiagonal();
for (int i = 0; i < diagonal.length; i++)
{
double eigenvalue = diagonal[i];
if (eigenvalue < 0.0)
{
sign = -sign;
logsum += Math.log(-eigenvalue);
}
else
{
logsum += Math.log(eigenvalue);
}
}
return new ComplexNumber(logsum, (sign < 0) ? Math.PI : 0.0);
}
@Override
public double normFrobenius()
{
double[] diagonal = this.getDiagonal();
double sum = 0.0;
for( int i = 0; i < diagonal.length; i++ )
{
double v = diagonal[i];
sum += v*v;
}
return Math.sqrt( sum );
}
@Override
public int rank(
double effectiveZero )
{
int rank = 0;
double[] diagonal = this.getDiagonal();
int M = diagonal.length;
for( int i = 0; i < M; i++ )
{
if( Math.abs( diagonal[i] ) > effectiveZero )
{
rank++;
}
}
return rank;
}
@Override
public Vector solve(
AbstractMTJVector b )
{
DiagonalMatrixMTJ pinvA = this.pseudoInverse();
return pinvA.times( b );
}
@Override
public Matrix solve(
Matrix B )
{
DiagonalMatrixMTJ pinvA = this.pseudoInverse();
return pinvA.times( B );
}
@Override
public Vector solve(
Vector b )
{
DiagonalMatrixMTJ pinvA = this.pseudoInverse();
return pinvA.times( b );
}
public SparseMatrix getSubMatrix(
int minRow,
int maxRow,
int minColumn,
int maxColumn )
{
int numRows = maxRow - minRow + 1;
if (numRows <= 0)
{
throw new IllegalArgumentException( "minRow " + minRow +
" >= maxRow " + maxRow );
}
int numColumns = maxColumn - minColumn + 1;
if (numColumns <= 0)
{
throw new IllegalArgumentException( "minCol " + minColumn +
" >= maxCol " + maxColumn );
}
SparseMatrix submatrix =
SparseMatrixFactoryMTJ.INSTANCE.createMatrix( numRows, numColumns );
this.getSubMatrixInto(
minRow, maxRow, minColumn, maxColumn, submatrix );
return submatrix;
}
public DiagonalMatrixMTJ transpose()
{
return this;
}
/**
* Gets the data along the diagonal
* @return
* Diagonal data
*/
public double[] getDiagonal()
{
return this.getInternalMatrix().getData();
}
@Override
public DiagonalMatrixMTJ pseudoInverse()
{
return this.pseudoInverse( 0.0 );
}
public DiagonalMatrixMTJ pseudoInverse(
double effectiveZero )
{
double[] diagonal = this.getDiagonal();
int M = diagonal.length;
double[] retval = new double[ M ];
for( int i = 0; i < M; i++ )
{
double di = diagonal[i];
if( Math.abs( di ) <= effectiveZero )
{
retval[i] = 0.0;
}
else
{
retval[i] = 1.0 / di;
}
}
return new DiagonalMatrixMTJ( retval );
}
@Override
public DiagonalMatrixMTJ inverse()
{
return this.pseudoInverse();
}
@Override
public boolean isSparse()
{
return true;
}
@Override
public int getEntryCount()
{
return this.getInternalMatrix().getData().length;
}
public Vector getColumn(
int columnIndex )
{
int M = this.getDimensionality();
Vector column = SparseVectorFactoryMTJ.getDefault().createVector( M );
column.setElement( columnIndex, this.getElement( columnIndex, columnIndex ) );
return column;
}
public Vector getRow(
int rowIndex )
{
int N = this.getDimensionality();
Vector row = SparseVectorFactoryMTJ.getDefault().createVector( N );
row.setElement( rowIndex, this.getElement( rowIndex, rowIndex ) );
return row;
}
@Override
public double getElement(
int rowIndex,
int columnIndex )
{
if( rowIndex != columnIndex )
{
return 0.0;
}
else
{
return this.getElement( rowIndex );
}
}
@Override
public void setElement(
int rowIndex,
int columnIndex,
double value )
{
if( rowIndex != columnIndex )
{
if( value != 0.0 )
{
throw new IllegalArgumentException(
"Can only set diagonal elements in a DiagonalMatrix!" );
}
}
else
{
this.setElement( rowIndex, value );
}
}
public double getElement(
int index )
{
double[] diagonal = this.getDiagonal();
return diagonal[index];
}
public void setElement(
int index,
double value )
{
double[] diagonal = this.getDiagonal();
diagonal[index] = value;
}
@Override
public DenseVector convertToVector()
{
return DenseVectorFactoryMTJ.INSTANCE.copyArray( this.getDiagonal() );
}
@Override
public void convertFromVector(
Vector parameters )
{
if( this.getNumRows() != parameters.getDimensionality() )
{
throw new IllegalArgumentException(
"Wrong number of parameters!" );
}
double[] diagonal = this.getDiagonal();
for( int i = 0; i < diagonal.length; i++ )
{
diagonal[i] = parameters.getElement( i );
}
}
@Override
public String toString()
{
int M = this.getDimensionality();
StringBuilder retval = new StringBuilder( M * 10 );
retval.append( "(" + M + "x" + M + "), diagonal:" );
for( int i = 0; i < M; i++ )
{
retval.append( " " + this.getElement( i ) );
}
return retval.toString();
}
public String toString(
final NumberFormat format)
{
final int d = this.getDimensionality();
final StringBuilder result = new StringBuilder(d * 5);
result.append("(" + d + "x" + d + "), diagonal:");
for (int i = 0; i < d; i++)
{
result.append(" " + format.format(this.getElement(i)));
}
return result.toString();
}
/**
* Writes a DenseMatrix out to a serialized file
* @param out output stream to which the DenseMatrix will be written
* @throws java.io.IOException On bad write
*/
private void writeObject(
ObjectOutputStream out )
throws IOException
{
out.defaultWriteObject();
//manually serialize superclass
int numDiagonal = this.getDimensionality();
double[] diag = new double[numDiagonal];
for( int i = 0; i < numDiagonal; i++ )
{
diag[i] = this.getElement(i);
}
out.writeObject( diag );
}
/**
* Reads in a serialized class from the specified stream
* @param in stream from which to read the DenseMatrix
* @throws java.io.IOException On bad read
* @throws java.lang.ClassNotFoundException if next object isn't DenseMatrix
*/
private void readObject(
ObjectInputStream in )
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
double[] diag = (double[]) in.readObject();
this.setInternalMatrix( new no.uib.cipr.matrix.BandMatrix( diag.length, 0, 0 ) );
System.arraycopy(diag, 0, this.getDiagonal(), 0, diag.length);
}
@Override
public MatrixFactory<?> getMatrixFactory()
{
return SparseMatrixFactoryMTJ.INSTANCE;
}
}
|
3e0ad5384b56a6c06ac706a6437a250bcbc9fbed | 14,860 | java | Java | src/main/java/de/tum/in/www1/artemis/web/rest/TextExerciseImportService.java | muenchdo/ArTEMiS | 8acdae21e9b2527f9a53e5c003302cc742a8284a | [
"MIT"
] | null | null | null | src/main/java/de/tum/in/www1/artemis/web/rest/TextExerciseImportService.java | muenchdo/ArTEMiS | 8acdae21e9b2527f9a53e5c003302cc742a8284a | [
"MIT"
] | null | null | null | src/main/java/de/tum/in/www1/artemis/web/rest/TextExerciseImportService.java | muenchdo/ArTEMiS | 8acdae21e9b2527f9a53e5c003302cc742a8284a | [
"MIT"
] | null | null | null | 52.882562 | 142 | 0.735061 | 4,586 | package de.tum.in.www1.artemis.web.rest;
import java.util.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import de.tum.in.www1.artemis.domain.*;
import de.tum.in.www1.artemis.domain.enumeration.ExerciseMode;
import de.tum.in.www1.artemis.repository.*;
@Repository
public class TextExerciseImportService {
private final Logger log = LoggerFactory.getLogger(TextExerciseImportService.class);
private final TextExerciseRepository textExerciseRepository;
private final ExampleSubmissionRepository exampleSubmissionRepository;
private final SubmissionRepository submissionRepository;
private final ResultRepository resultRepository;
private final TextBlockRepository textBlockRepository;
public TextExerciseImportService(TextExerciseRepository textExerciseRepository, ExampleSubmissionRepository exampleSubmissionRepository,
SubmissionRepository submissionRepository, ResultRepository resultRepository, TextBlockRepository textBlockRepository) {
this.textExerciseRepository = textExerciseRepository;
this.exampleSubmissionRepository = exampleSubmissionRepository;
this.submissionRepository = submissionRepository;
this.resultRepository = resultRepository;
this.textBlockRepository = textBlockRepository;
}
/**
* Imports a text exercise creating a new entity, copying all basic values and saving it in the database.
* All basic include everything except Student-, Tutor participations, and student questions. <br>
* This method calls {@link #copyTextExerciseBasis(TextExercise)} to set up the basis of the exercise
* {@link #copyExampleSubmission(TextExercise, TextExercise)} for a hard copy of the example submissions.
*
* @param templateExercise The template exercise which should get imported
* @param importedExercise The new exercise already containing values which should not get copied, i.e. overwritten
* @return The newly created exercise
*/
@Transactional
public TextExercise importTextExercise(final TextExercise templateExercise, TextExercise importedExercise) {
log.debug("Creating a new Exercise based on exercise {}", templateExercise);
TextExercise newExercise = copyTextExerciseBasis(importedExercise);
textExerciseRepository.save(newExercise);
newExercise.setExampleSubmissions(copyExampleSubmission(templateExercise, newExercise));
return newExercise;
}
/** This helper method copies all attributes of the {@code importedExercise} into the new exercise.
* Here we ignore all external entities as well as the start-, end-, and assemessment due date.
* If the exercise is a team exercise, this method calls {@link #copyTeamAssignmentConfig(TeamAssignmentConfig)}
* to copy the Team assignment configuration
*
* @param importedExercise The exercise from which to copy the basis
* @return the cloned TextExercise basis
*/
@NotNull
private TextExercise copyTextExerciseBasis(TextExercise importedExercise) {
log.debug("Copying the exercise basis from {}", importedExercise);
TextExercise newExercise = new TextExercise();
if (importedExercise.getCourseViaExerciseGroupOrCourseMember() != null) {
newExercise.setCourse(importedExercise.getCourseViaExerciseGroupOrCourseMember());
}
else {
newExercise.setExerciseGroup(importedExercise.getExerciseGroup());
}
newExercise.setSampleSolution(importedExercise.getSampleSolution());
newExercise.setTitle(importedExercise.getTitle());
newExercise.setMaxScore(importedExercise.getMaxScore());
newExercise.setAssessmentType(importedExercise.getAssessmentType());
newExercise.setProblemStatement(importedExercise.getProblemStatement());
newExercise.setReleaseDate(importedExercise.getReleaseDate());
newExercise.setDueDate(importedExercise.getDueDate());
newExercise.setAssessmentDueDate(importedExercise.getAssessmentDueDate());
newExercise.setDifficulty(importedExercise.getDifficulty());
newExercise.setGradingInstructions(importedExercise.getGradingInstructions());
newExercise.setGradingCriteria(copyGradingCriteria(importedExercise));
if (newExercise.getExerciseGroup() != null) {
newExercise.setMode(ExerciseMode.INDIVIDUAL);
}
else {
newExercise.setCategories(importedExercise.getCategories());
newExercise.setMode(importedExercise.getMode());
if (newExercise.getMode() == ExerciseMode.TEAM) {
newExercise.setTeamAssignmentConfig(copyTeamAssignmentConfig(importedExercise.getTeamAssignmentConfig()));
}
}
return newExercise;
}
/** Helper method which does a hard copy of the Grading Criteria
*
* @param originalTextExercise The original exercise which contains the grading criteria to be imported
* @return A clone of the grading criteria list
*/
private List<GradingCriterion> copyGradingCriteria(TextExercise originalTextExercise) {
log.debug("Copying the grading criteria from {}", originalTextExercise);
List<GradingCriterion> newGradingCriteria = new ArrayList<>();
for (GradingCriterion originalGradingCriterion : originalTextExercise.getGradingCriteria()) {
GradingCriterion newGradingCriterion = new GradingCriterion();
newGradingCriterion.setExercise(originalTextExercise);
newGradingCriterion.setTitle(originalGradingCriterion.getTitle());
newGradingCriterion.setStructuredGradingInstructions(copyGradingInstruction(originalGradingCriterion, newGradingCriterion));
newGradingCriteria.add(newGradingCriterion);
}
return newGradingCriteria;
}
/** Helper method which does a hard copy of the Grading Instructions
*
* @param originalGradingCriterion The original grading criterion which contains the grading instructions
* @param newGradingCriterion The cloned grading criterion in which we insert the grading instructions
* @return A clone of the grading instruction list of the grading criterion
*/
private List<GradingInstruction> copyGradingInstruction(GradingCriterion originalGradingCriterion, GradingCriterion newGradingCriterion) {
log.debug("Copying the grading instructions for the following criterion {}", originalGradingCriterion);
List<GradingInstruction> newGradingInstructions = new ArrayList<>();
for (GradingInstruction originalGradingInstruction : originalGradingCriterion.getStructuredGradingInstructions()) {
GradingInstruction newGradingInstruction = new GradingInstruction();
newGradingInstruction.setCredits(originalGradingInstruction.getCredits());
newGradingInstruction.setFeedback(originalGradingInstruction.getFeedback());
newGradingInstruction.setGradingScale(originalGradingInstruction.getGradingScale());
newGradingInstruction.setInstructionDescription(originalGradingInstruction.getInstructionDescription());
newGradingInstruction.setUsageCount(originalGradingInstruction.getUsageCount());
newGradingInstruction.setGradingCriterion(newGradingCriterion);
newGradingInstructions.add(newGradingInstruction);
}
return newGradingInstructions;
}
/** Helper method which does a hard copy of the Team Assignment Configurations.
*
* @param originalConfig the original team assignment configuration to be copied.
* @return The cloned configuration
*/
private TeamAssignmentConfig copyTeamAssignmentConfig(TeamAssignmentConfig originalConfig) {
log.debug("Copying TeamAssignmentConfig");
TeamAssignmentConfig newConfig = new TeamAssignmentConfig();
newConfig.setMinTeamSize(originalConfig.getMinTeamSize());
newConfig.setMaxTeamSize(originalConfig.getMaxTeamSize());
return newConfig;
}
/** This helper method does a hard copy of the result of a submission.
* To copy the feedback, it calls {@link #copyFeedback(List, Result)}
*
* @param originalResult The original result to be copied
* @param newSubmission The submission in which we link the result clone
* @return The cloned result
*/
private Result copyResult(Result originalResult, Submission newSubmission) {
log.debug("Copying the result to new submission: {}", newSubmission);
Result newResult = new Result();
newResult.setAssessmentType(originalResult.getAssessmentType());
newResult.setAssessor(originalResult.getAssessor());
newResult.setCompletionDate(originalResult.getCompletionDate());
newResult.setExampleResult(true);
newResult.setRated(true);
newResult.setResultString(originalResult.getResultString());
newResult.setHasFeedback(originalResult.getHasFeedback());
newResult.setScore(originalResult.getScore());
newResult.setFeedbacks(copyFeedback(originalResult.getFeedbacks(), newResult));
newResult.setSubmission(newSubmission);
resultRepository.save(newResult);
return newResult;
}
/** This helper functions does a hard copy of the feedbacks.
*
* @param originalFeedbacks The original list of feedbacks to be copied
* @param newResult The result in which we link the new feedback
* @return The cloned list of feedback
*/
private List<Feedback> copyFeedback(List<Feedback> originalFeedbacks, Result newResult) {
log.debug("Copying the feedbacks to new result: {}", newResult);
List<Feedback> newFeedbacks = new ArrayList<>();
for (final var originalFeedback : originalFeedbacks) {
Feedback newFeedback = new Feedback();
newFeedback.setCredits(originalFeedback.getCredits());
newFeedback.setDetailText(originalFeedback.getDetailText());
newFeedback.setPositive(originalFeedback.isPositive());
newFeedback.setReference(originalFeedback.getReference());
newFeedback.setType(originalFeedback.getType());
newFeedback.setText(originalFeedback.getText());
newFeedback.setResult(newResult);
newFeedbacks.add(newFeedback);
}
return newFeedbacks;
}
/** This helper functions does a hard copy of the text blocks and inserts them into {@code newSubmission}
*
* @param originalTextBlocks The original text blocks to be copied
* @param newSubmission The submission in which we enter the new text blocks
* @return the cloned list of text blocks
*/
private List<TextBlock> copyTextBlocks(List<TextBlock> originalTextBlocks, TextSubmission newSubmission) {
log.debug("Copying the TextBlocks to new TextSubmission: {}", newSubmission);
List<TextBlock> newTextBlocks = new ArrayList<>();
for (TextBlock originalTextBlock : originalTextBlocks) {
TextBlock newTextBlock = new TextBlock();
newTextBlock.setAddedDistance(originalTextBlock.getAddedDistance());
newTextBlock.setCluster(originalTextBlock.getCluster());
newTextBlock.setEndIndex(originalTextBlock.getEndIndex());
newTextBlock.setStartIndex(originalTextBlock.getStartIndex());
newTextBlock.setSubmission(newSubmission);
newTextBlock.setText(originalTextBlock.getText());
textBlockRepository.save(newTextBlock);
newTextBlocks.add(newTextBlock);
}
return newTextBlocks;
}
/** This functions does a hard copy of the example submissions contained in {@code templateExercise}.
* To copy the corresponding Submission entity this function calls {@link #copySubmission(TextSubmission)}
*
* @param templateExercise {TextExercise} The original exercise from which to fetch the example submissions
* @param newExercise The new exercise in which we will insert the example submissions
* @return The cloned set of example submissions
*/
private Set<ExampleSubmission> copyExampleSubmission(TextExercise templateExercise, TextExercise newExercise) {
log.debug("Copying the ExampleSubmissions to new Exercise: {}", newExercise);
Set<ExampleSubmission> newExampleSubmissions = new HashSet<>();
for (ExampleSubmission originalExampleSubmission : templateExercise.getExampleSubmissions()) {
TextSubmission originalSubmission = (TextSubmission) originalExampleSubmission.getSubmission();
TextSubmission newSubmission = copySubmission(originalSubmission);
ExampleSubmission newExampleSubmission = new ExampleSubmission();
newExampleSubmission.setExercise(newExercise);
newExampleSubmission.setSubmission(newSubmission);
newExampleSubmission.setAssessmentExplanation(originalExampleSubmission.getAssessmentExplanation());
exampleSubmissionRepository.save(newExampleSubmission);
newExampleSubmissions.add(newExampleSubmission);
}
return newExampleSubmissions;
}
/** This helper function does a hard copy of the {@code originalSubmission} and stores the values in {@code newSubmission}.
* To copy the TextBlocks and the submission results this function calls {@link #copyTextBlocks(List, TextSubmission)} and
* {@link #copyResult(Result, Submission)} respectively.
*
* @param originalSubmission The original submission to be copied.
* @return The cloned submission
*/
private TextSubmission copySubmission(TextSubmission originalSubmission) {
TextSubmission newSubmission = new TextSubmission();
if (originalSubmission != null) {
log.debug("Copying the Submission to new ExampleSubmission: {}", newSubmission);
newSubmission.setExampleSubmission(true);
newSubmission.setSubmissionDate(originalSubmission.getSubmissionDate());
newSubmission.setLanguage(originalSubmission.getLanguage());
newSubmission.setType(originalSubmission.getType());
newSubmission.setParticipation(originalSubmission.getParticipation());
newSubmission.setText(originalSubmission.getText());
newSubmission.setBlocks(copyTextBlocks(originalSubmission.getBlocks(), newSubmission));
newSubmission.setResult(copyResult(originalSubmission.getResult(), newSubmission));
submissionRepository.save(newSubmission);
}
return newSubmission;
}
}
|
3e0ad8444bd029e5361c4c72351c522631505e5b | 908 | java | Java | javaJokes/src/main/java/com/udacity/gradle/javajokes/utils/NetworkUtils.java | bazrafkan/Build-It-Bigger | 682792d86a35dccb3d8df9c5853ea0de757a782f | [
"MIT"
] | null | null | null | javaJokes/src/main/java/com/udacity/gradle/javajokes/utils/NetworkUtils.java | bazrafkan/Build-It-Bigger | 682792d86a35dccb3d8df9c5853ea0de757a782f | [
"MIT"
] | null | null | null | javaJokes/src/main/java/com/udacity/gradle/javajokes/utils/NetworkUtils.java | bazrafkan/Build-It-Bigger | 682792d86a35dccb3d8df9c5853ea0de757a782f | [
"MIT"
] | null | null | null | 30.266667 | 83 | 0.632159 | 4,587 | package com.udacity.gradle.javajokes.utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class NetworkUtils {
private static final int CONNECT_TIMEOUT = 3000;
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
}
|
3e0ad85b845324bf023737282780ecfbbd835d05 | 1,566 | java | Java | main/plugins/org.talend.designer.components.libs/libs_src/talend-codegen-utils/src/main/java/org/talend/codegen/enforcer/IndexMapperByIndex.java | coheigea/tdi-studio-se | c4cd4df0fc841c497b51718e623145d29d0bf030 | [
"Apache-2.0"
] | 114 | 2015-03-05T15:34:59.000Z | 2022-02-22T03:48:44.000Z | main/plugins/org.talend.designer.components.libs/libs_src/talend-codegen-utils/src/main/java/org/talend/codegen/enforcer/IndexMapperByIndex.java | coheigea/tdi-studio-se | c4cd4df0fc841c497b51718e623145d29d0bf030 | [
"Apache-2.0"
] | 1,137 | 2015-03-04T01:35:42.000Z | 2022-03-29T06:03:17.000Z | main/plugins/org.talend.designer.components.libs/libs_src/talend-codegen-utils/src/main/java/org/talend/codegen/enforcer/IndexMapperByIndex.java | coheigea/tdi-studio-se | c4cd4df0fc841c497b51718e623145d29d0bf030 | [
"Apache-2.0"
] | 219 | 2015-01-21T10:42:18.000Z | 2022-02-17T07:57:20.000Z | 30.115385 | 126 | 0.600255 | 4,588 | // ============================================================================
//
// Copyright (C) 2006-2021 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.codegen.enforcer;
import org.apache.avro.Schema;
/**
* {@link IndexMapper} implementation, which match fields according their indexes
*/
class IndexMapperByIndex implements IndexMapper {
/**
* Number of fields in design schema. It is also equaled number of fields of POJO class in case there is no dynamic fields
*/
private final int designSchemaSize;
/**
* Constructor sets design schema size
*
* @param designSchema design schema
*/
IndexMapperByIndex(Schema designSchema) {
designSchemaSize = designSchema.getFields().size();
}
/**
* {@inheritDoc}
*
* If there is no dynamic fields runtime indexes equal design indexes
* <code>runtimeSchema</code> parameter is not used here
*/
@Override
public int[] computeIndexMap(Schema runtimeSchema) {
int[] indexMap = new int[designSchemaSize];
for (int i = 0; i < designSchemaSize; i++) {
indexMap[i] = i;
}
return indexMap;
}
}
|
3e0ad897e385c6dced5a97a7b144f0e1ca06cf5e | 2,680 | java | Java | java/client/org/apache/derby/client/am/ParameterMetaData40.java | kavin256/Derby | 1c5fe53ae15064a104e5140311c71b91ded4a7bc | [
"Apache-2.0"
] | null | null | null | java/client/org/apache/derby/client/am/ParameterMetaData40.java | kavin256/Derby | 1c5fe53ae15064a104e5140311c71b91ded4a7bc | [
"Apache-2.0"
] | null | null | null | java/client/org/apache/derby/client/am/ParameterMetaData40.java | kavin256/Derby | 1c5fe53ae15064a104e5140311c71b91ded4a7bc | [
"Apache-2.0"
] | null | null | null | 37.222222 | 87 | 0.646269 | 4,589 | /*
Derby - Class org.apache.derby.client.am.ParameterMetaData40
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.derby.client.am;
import java.sql.SQLException;
import org.apache.derby.shared.common.reference.SQLState;
public class ParameterMetaData40 extends ParameterMetaData {
/**
*
* Calls the superclass constructor to pass the arguments
* @param columnMetaData ColumnMetaData
*
*/
public ParameterMetaData40(ColumnMetaData columnMetaData) {
super(columnMetaData);
}
/**
* Returns false unless <code>interfaces</code> is implemented
*
* @param interfaces a Class defining an interface.
* @return true if this implements the interface or
* directly or indirectly wraps an object
* that does.
* @throws java.sql.SQLException if an error occurs while determining
* whether this is a wrapper for an object
* with the given interface.
*/
public boolean isWrapperFor(Class<?> interfaces) throws SQLException {
return interfaces.isInstance(this);
}
/**
* Returns <code>this</code> if this class implements the interface
*
* @param interfaces a Class defining an interface
* @return an object that implements the interface
* @throws java.sql.SQLExption if no object if found that implements the
* interface
*/
public <T> T unwrap(java.lang.Class<T> interfaces)
throws SQLException {
try {
return interfaces.cast(this);
} catch (ClassCastException cce) {
throw new SqlException(null,new ClientMessageId(SQLState.UNABLE_TO_UNWRAP),
interfaces).getSQLException();
}
}
}
|
3e0ad988716e79fbf6c05748928fcc817bc1d4e4 | 1,588 | java | Java | Programacion II - 2020/JavaMiniCRUD/src/Model/Persona.java | Ismael-UTN/Java-Practicas-UTN | 78b10f3befaba27bcbaed44fdb87315fc7a3c06f | [
"MIT"
] | 1 | 2020-05-25T01:18:16.000Z | 2020-05-25T01:18:16.000Z | Programacion II - 2020/JavaMiniCRUD/src/Model/Persona.java | Ismael-UTN/Java-Practicas-UTN | 78b10f3befaba27bcbaed44fdb87315fc7a3c06f | [
"MIT"
] | null | null | null | Programacion II - 2020/JavaMiniCRUD/src/Model/Persona.java | Ismael-UTN/Java-Practicas-UTN | 78b10f3befaba27bcbaed44fdb87315fc7a3c06f | [
"MIT"
] | 1 | 2020-05-03T18:35:15.000Z | 2020-05-03T18:35:15.000Z | 19.604938 | 147 | 0.56738 | 4,590 | package Model;
/**
*
* @author SkylakeFrost
*/
public class Persona {
private int id_persona;
private String nombre;
private String apellido;
private int dni;
private long cuit;
public Persona(int id_persona, String nombre, String apellido, int dni, long cuit) {
this.id_persona = id_persona;
this.nombre = nombre;
this.apellido = apellido;
this.dni = dni;
this.cuit = cuit;
}
public Persona(String nombre, String apellido, int dni, long cuit) {
this.nombre = nombre;
this.apellido = apellido;
this.dni = dni;
this.cuit = cuit;
}
public Persona() {
}
public int getId_persona() {
return id_persona;
}
public void setId_persona(int id_persona) {
this.id_persona = id_persona;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public int getDni() {
return dni;
}
public void setDni(int dni) {
this.dni = dni;
}
public long getCuit() {
return cuit;
}
public void setCuit(long cuit) {
this.cuit = cuit;
}
@Override
public String toString() {
return "Persona{" + "id_persona=" + id_persona + ", nombre=" + nombre + ", apellido=" + apellido + ", dni=" + dni + ", cuit=" + cuit + '}';
}
}
|
3e0ada1e15d7858b750143c4ccd4db0806f99359 | 1,167 | java | Java | src/das/excpt/EArgumentBreaksRule.java | ibatis-dao/metadict | b0a09611cf39762bfde3772c1c13ac60a2123bd9 | [
"Apache-2.0"
] | null | null | null | src/das/excpt/EArgumentBreaksRule.java | ibatis-dao/metadict | b0a09611cf39762bfde3772c1c13ac60a2123bd9 | [
"Apache-2.0"
] | 1 | 2016-01-03T15:21:36.000Z | 2016-01-03T15:21:36.000Z | src/das/excpt/EArgumentBreaksRule.java | ibatis-dao/metadict | b0a09611cf39762bfde3772c1c13ac60a2123bd9 | [
"Apache-2.0"
] | null | null | null | 32.416667 | 91 | 0.686375 | 4,591 | /*
* Copyright 2015 serg.
*
* 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 das.excpt;
/**
*
* @author StarukhSA
*/
public class EArgumentBreaksRule extends IllegalArgumentException {
/**
*
*/
private static final long serialVersionUID = -6267965401001420333L;
public EArgumentBreaksRule(String methodName, String rule) {
super("Method "+methodName+"() arguments should match rule ("+rule+")");
}
public EArgumentBreaksRule(String methodName, String argName, String rule) {
super("Method "+methodName+"("+argName+") argument should match rule ("+rule+")");
}
}
|
3e0adaf5f912518ae6a5a0e6ba2329eaee8b3156 | 3,102 | java | Java | common/common-rest/src/test/java/io/servicecomb/common/rest/codec/param/TestRawJsonBodyProcessor.java | hawkmenz/ServiceComb-Java-Chassis | e6e94ae2ca02677d025eb63b1f1bf1668463a76a | [
"Apache-2.0"
] | null | null | null | common/common-rest/src/test/java/io/servicecomb/common/rest/codec/param/TestRawJsonBodyProcessor.java | hawkmenz/ServiceComb-Java-Chassis | e6e94ae2ca02677d025eb63b1f1bf1668463a76a | [
"Apache-2.0"
] | null | null | null | common/common-rest/src/test/java/io/servicecomb/common/rest/codec/param/TestRawJsonBodyProcessor.java | hawkmenz/ServiceComb-Java-Chassis | e6e94ae2ca02677d025eb63b1f1bf1668463a76a | [
"Apache-2.0"
] | null | null | null | 34.087912 | 100 | 0.738233 | 4,592 | /*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicecomb.common.rest.codec.param;
import static org.mockito.Mockito.when;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import io.servicecomb.common.rest.codec.RestObjectMapper;
import io.servicecomb.common.rest.codec.RestServerRequest;
import io.servicecomb.foundation.vertx.stream.BufferInputStream;
import io.servicecomb.swagger.generator.core.SwaggerConst;
import io.swagger.models.parameters.BodyParameter;
import io.vertx.core.buffer.Buffer;
public class TestRawJsonBodyProcessor {
private static RestServerRequest request;
private static ParamValueProcessor bodyProcessor;
@Before
public void beforeTest() {
request = Mockito.mock(RestServerRequest.class);
BodyProcessorCreator bodyCreator =
(BodyProcessorCreator) ParamValueProcessorCreatorManager.INSTANCE.getBodyProcessorCreater();
BodyParameter bp = new BodyParameter();
bp.setVendorExtension(SwaggerConst.EXT_RAW_JSON_TYPE, true);
bodyProcessor = bodyCreator.create(bp, String.class);
}
@Test
public void testJsonInt() throws Exception {
Buffer buffer = Buffer.buffer("123");
when(request.getBody()).thenReturn(new BufferInputStream(buffer.getByteBuf()));
String result = (String) bodyProcessor.getValue(request);
Assert.assertEquals("123", result);
}
@Test
public void testJsonString() throws Exception {
Buffer buffer = Buffer.buffer("\"abc\"");
when(request.getBody()).thenReturn(new BufferInputStream(buffer.getByteBuf()));
String result = (String) bodyProcessor.getValue(request);
Assert.assertEquals("\"abc\"", result);
}
@Test
public void testJsonMap() throws Exception {
Buffer buffer = Buffer.buffer("{\"abc\":\"def\"}");
when(request.getBody()).thenReturn(new BufferInputStream(buffer.getByteBuf()));
String result = (String) bodyProcessor.getValue(request);
Assert.assertEquals("{\"abc\":\"def\"}", result);
@SuppressWarnings("unchecked")
Map<String, String> resMap = RestObjectMapper.INSTANCE.readValue(result.getBytes(),
Map.class);
Assert.assertEquals("def", resMap.get("abc"));
}
@Test
public void testJsonList() throws Exception {
Buffer buffer = Buffer.buffer("[\"abc\"]");
when(request.getBody()).thenReturn(new BufferInputStream(buffer.getByteBuf()));
String result = (String) bodyProcessor.getValue(request);
Assert.assertEquals("[\"abc\"]", result);
}
}
|
3e0adbb07123991476d0d689a542f575fedc72ad | 1,754 | java | Java | dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/db/ConvertBigIntegerToBytes.java | luontola/dimdwarf | 5cde790c3bb98fc4a3c3aeee22d49f69ab78b285 | [
"Apache-2.0"
] | 3 | 2019-01-12T13:03:33.000Z | 2019-06-22T07:33:33.000Z | dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/db/ConvertBigIntegerToBytes.java | luontola/dimdwarf | 5cde790c3bb98fc4a3c3aeee22d49f69ab78b285 | [
"Apache-2.0"
] | null | null | null | dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/db/ConvertBigIntegerToBytes.java | luontola/dimdwarf | 5cde790c3bb98fc4a3c3aeee22d49f69ab78b285 | [
"Apache-2.0"
] | 4 | 2019-05-02T22:08:56.000Z | 2020-01-14T08:21:48.000Z | 32.481481 | 92 | 0.628278 | 4,593 | // Copyright © 2008-2010 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://dimdwarf.sourceforge.net/LICENSE
package net.orfjackal.dimdwarf.db;
import javax.annotation.concurrent.Immutable;
import java.math.BigInteger;
@Immutable
public class ConvertBigIntegerToBytes implements Converter<BigInteger, Blob> {
public BigInteger back(Blob value) {
if (value == null || value.length() == 0) {
return null;
}
return new BigInteger(1, unpack(value.toByteArray()));
}
public Blob forth(BigInteger value) {
if (value == null) {
return null;
}
if (value.signum() < 0) {
throw new IllegalArgumentException("Negative values are not allowed: " + value);
}
return Blob.fromBytes(pack(value.toByteArray()));
}
private static byte[] unpack(byte[] packed) {
byte[] bytes = new byte[packed.length - 1];
assert bytes.length == packed[0];
System.arraycopy(packed, 1, bytes, 0, bytes.length);
return bytes;
}
private static byte[] pack(byte[] bytes) {
int leadingNullBytes = getLeadingNullBytes(bytes);
int significantBytes = bytes.length - leadingNullBytes;
byte[] packed = new byte[significantBytes + 1];
packed[0] = (byte) significantBytes;
System.arraycopy(bytes, leadingNullBytes, packed, 1, significantBytes);
return packed;
}
private static int getLeadingNullBytes(byte[] bytes) {
int leadingNullBytes = 0;
for (int i = 0; i < bytes.length && bytes[i] == 0x00; i++) {
leadingNullBytes++;
}
return leadingNullBytes;
}
}
|
3e0adc8be8f6fbdc296eaab2cbed284b07e42cc6 | 1,105 | java | Java | ri/src/main/java/com/github/t1/problemdetailmapper/ProblemDetailXmlMessageBodyWriter.java | t1/problem-details | 2f06dc401de3ea57fee08b7d620393b64ab26a62 | [
"Apache-2.0"
] | 15 | 2019-12-14T04:42:15.000Z | 2022-01-22T14:48:51.000Z | ri/src/main/java/com/github/t1/problemdetailmapper/ProblemDetailXmlMessageBodyWriter.java | t1/problem-details | 2f06dc401de3ea57fee08b7d620393b64ab26a62 | [
"Apache-2.0"
] | 30 | 2019-12-20T05:11:52.000Z | 2021-03-16T04:11:35.000Z | ri/src/main/java/com/github/t1/problemdetailmapper/ProblemDetailXmlMessageBodyWriter.java | t1/problem-details | 2f06dc401de3ea57fee08b7d620393b64ab26a62 | [
"Apache-2.0"
] | 4 | 2019-12-18T14:43:12.000Z | 2020-02-26T18:01:34.000Z | 39.464286 | 138 | 0.771946 | 4,594 | package com.github.t1.problemdetailmapper;
import com.github.t1.problemdetail.ri.lib.ProblemXml;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Map;
import static com.github.t1.problemdetail.Constants.PROBLEM_DETAIL_XML_TYPE;
@Provider
public class ProblemDetailXmlMessageBodyWriter implements MessageBodyWriter<Map<String, Object>> {
@Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return PROBLEM_DETAIL_XML_TYPE.isCompatible(mediaType);
}
@Override public void writeTo(Map<String, Object> map, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
new ProblemXml(map).writeTo(entityStream);
}
}
|
3e0adcdc4427f8b9ffccf017b13b591228f4eee2 | 1,440 | java | Java | src/com/itheima/domain/Cart.java | ssj287/store | 7032e5aa5de07e38d1bffa47e2a3a9aaa4717e36 | [
"Apache-2.0"
] | null | null | null | src/com/itheima/domain/Cart.java | ssj287/store | 7032e5aa5de07e38d1bffa47e2a3a9aaa4717e36 | [
"Apache-2.0"
] | null | null | null | src/com/itheima/domain/Cart.java | ssj287/store | 7032e5aa5de07e38d1bffa47e2a3a9aaa4717e36 | [
"Apache-2.0"
] | null | null | null | 16.363636 | 58 | 0.650694 | 4,595 | package com.itheima.domain;
import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public class Cart implements Serializable{
//存放购物车项的集合 key:商品的id cartitem:购物车项 使用map集合便于删除单个购物车项
private Map<String, CartItem> map=new LinkedHashMap<>();
//总金额
private Double total=0.0;
/**
* 获取所有的购物车项
* @return
*/
public Collection<CartItem> getItmes(){
return map.values();
}
/**
* 添加到购物车
* @param item 购物车项
*/
public void add2Cart(CartItem item){
//1.先判断购物车中有无该商品
//1.1先获取商品的id
String pid = item.getProduct().getPid();
if(map.containsKey(pid)){
//有
//设置购买数量 需要获取该商品之前的购买数量+现在的购买数量(item.getCount)
//获取购物车中购物车项
CartItem oItem = map.get(pid);
oItem.setCount(oItem.getCount()+item.getCount());
}else{
//没有 将购物车项添加进去
map.put(pid, item);
}
//2.添加完成之后 修改金额
total+=item.getSubtotal();
}
/**
* 从购物车删除指定购物车项
* @param pid 商品的id
*/
public void removeFromCart(String pid){
//1.从集合中删除
CartItem item = map.remove(pid);
//2.修改金额
total-=item.getSubtotal();
}
/**
* 清空购物车
*/
public void clearCart(){
//1.map置空
map.clear();
//2.金额归零
total=0.0;
}
public Map<String, CartItem> getMap() {
return map;
}
public void setMap(Map<String, CartItem> map) {
this.map = map;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
}
|
3e0add10c5373deee49acd1016c6dc5a25bfd9ce | 1,120 | java | Java | ruoyi-manager/src/main/java/com/ruoyi/web/controller/audit/AuditController.java | hczzl/manager | 616e825bde838b70f930dba12fae4abcda954a6b | [
"MIT"
] | null | null | null | ruoyi-manager/src/main/java/com/ruoyi/web/controller/audit/AuditController.java | hczzl/manager | 616e825bde838b70f930dba12fae4abcda954a6b | [
"MIT"
] | null | null | null | ruoyi-manager/src/main/java/com/ruoyi/web/controller/audit/AuditController.java | hczzl/manager | 616e825bde838b70f930dba12fae4abcda954a6b | [
"MIT"
] | null | null | null | 32 | 103 | 0.773214 | 4,596 | package com.ruoyi.web.controller.audit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.service.audit.AuditService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author zhongzhilong
* @date 2019/8/10
*/
@RequestMapping("/audit")
@Controller
@Api(value = "auditController", tags = "提交审批相关接口")
public class AuditController {
@Autowired
private AuditService auditService;
@RequestMapping(value = "/commit", method = {RequestMethod.POST})
@ResponseBody
@Log(title = "提交审批", businessType = BusinessType.INSERT)
public AjaxResult audit(String currentId, String memo, Integer type, String userId, String score) {
return auditService.audit(currentId, memo, type, userId, score);
}
}
|
3e0add28b09eb892788a6da152ccc83da3e84e94 | 5,386 | java | Java | demo-MybatisPlus-CodeGenerator/src/main/java/CodeGenerator2.java | Max-Qiu/demo | 3238cb9589a6d29239df353332bd4ee7ec2c7e92 | [
"Apache-2.0"
] | null | null | null | demo-MybatisPlus-CodeGenerator/src/main/java/CodeGenerator2.java | Max-Qiu/demo | 3238cb9589a6d29239df353332bd4ee7ec2c7e92 | [
"Apache-2.0"
] | null | null | null | demo-MybatisPlus-CodeGenerator/src/main/java/CodeGenerator2.java | Max-Qiu/demo | 3238cb9589a6d29239df353332bd4ee7ec2c7e92 | [
"Apache-2.0"
] | null | null | null | 33.6625 | 108 | 0.619755 | 4,597 | import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.TemplateType;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;
/**
* 代码生成器简化版:删除模板中的日期、删除service接口、关闭乐观锁和逻辑删除
*
* 以 MySQL 为例
*
* 1. 修改最重要的设置
*
* 2. 运行 generator
*
* 3. 删除 iservice 文件夹
*
* 4. 拷贝代码至自己的项目
*
* PS 代码生成后推荐格式化一下,毕竟模板中可能有多余的空行或者空格或者import顺序不一样等等
*
* @author Max_Qiu
*/
public class CodeGenerator2 {
/**
* 最重要的配置
*/
// 数据库地址
private static final String URL = "jdbc:mysql://localhost:3306/mpg?useSSL=false&serverTimezone=GMT%2B8";
// 用户名
private static final String USERNAME = "root";
// 密码
private static final String PASSWORD = "123";
// 作者(@author Max_Qiu)
private static final String AUTHOR = "Max_Qiu";
// 父包名
private static final String PARENT = "com.maxqiu.demo";
// 需要排除的表
private static final String[] EXCLUDE = new String[] {"table_a", "table_b"};
// 去除表前缀(smp_user -> User)(若不需要去除,则设置为 "" )
private static final String TABLE_PREFIX = "mpg_";
public static void main(String[] args) {
// 数据源配置
DataSourceConfig dataSourceConfig = new DataSourceConfig
// URL、用户名、密码
.Builder(URL, USERNAME, PASSWORD)
// 数据库查询实现
.dbQuery(new MySqlQuery())
// 类型转换器
.typeConvert(new MySqlTypeConvert())
// 数据库关键字处理器
.keyWordsHandler(new MySqlKeyWordsHandler())
// 构建数据库配置
.build();
// 全局配置
GlobalConfig globalConfig = new GlobalConfig.Builder()
// 覆盖已有文件(默认false)
.fileOverride()
// 关闭生成后自动打开文件夹(默认true)
.disableOpenDir()
// 文件输出目录(默认D:\\tmp)
.outputDir("demo-MybatisPlus-CodeGenerator\\src\\main\\java")
// 作者
.author(AUTHOR)
// 实体时间类型(使用Java8时间类,其他类型进入DateType枚举查看详细)
.dateType(DateType.TIME_PACK)
// 生成文件中的注释的日期(指定格式)
.commentDate("yyyy-MM-dd")
// 构建全局配置
.build();
// 包相关的配置项
PackageConfig packageConfig = new PackageConfig.Builder()
// 包名
.parent(PARENT)
// service实现类包名(默认service.impl)
.serviceImpl("service")
// 构建包配置对象
.build();
// 模板路径配置
TemplateConfig templateConfig = new TemplateConfig.Builder()
// 禁用service
.disable(TemplateType.SERVICE)
// 实体模板路径(JAVA)
.entity("mybatis2/entity.java")
// serviceImpl模板路径
.serviceImpl("mybatis2/serviceImpl.java")
// mapper模板路径
.mapper("mybatis2/mapper.java")
// mapperXml模板路径
.mapperXml("mybatis2/mapper.xml")
// 控制器模板路径
.controller("mybatis2/controller.java")
// 构建模板配置对象
.build();
// 策略配置
StrategyConfig.Builder strategyConfigBuilder = new StrategyConfig.Builder()
// 开启跳过视图
.enableSkipView()
// 精确匹配排除表,生成表,模糊匹配排查表,生成表
.addExclude(EXCLUDE)
// 设置需要移除的表前缀
.addTablePrefix(TABLE_PREFIX);
// 实体策略配置
strategyConfigBuilder.entityBuilder()
// 开启链式模型,即实体可以连续set,例:.setXxx().setXxx();
.enableChainModel()
// 开启lombok模型
.enableLombok()
// 开启Boolean类型字段移除is前缀,即 is_deleted -> deleted
.enableRemoveIsPrefix()
// 开启生成实体时生成字段注解,即每个字段都设置 @TableId/@TableField
.enableTableFieldAnnotation()
// 数据库表映射到实体的命名策略(不做任何改变,原样输出)(设置为:下划线转驼峰)
.naming(NamingStrategy.underline_to_camel)
// 数据库表字段映射到实体的命名策略(未指定按照 naming 执行)
.columnNaming(NamingStrategy.underline_to_camel)
// 开启 ActiveRecord 模式
.enableActiveRecord();
strategyConfigBuilder.serviceBuilder()
// 格式化文件名
.convertServiceImplFileName((entityName -> entityName + ConstVal.SERVICE));
// 控制器属性配置构建
strategyConfigBuilder.controllerBuilder()
// 开启驼峰转连字符 autoFill -> auto-fill
.enableHyphenStyle()
// 开启生成@RestController控制器
.enableRestStyle();
StrategyConfig strategyConfig = strategyConfigBuilder.build();
AutoGenerator autoGenerator = new AutoGenerator(dataSourceConfig);
autoGenerator.global(globalConfig);
autoGenerator.packageInfo(packageConfig);
autoGenerator.strategy(strategyConfig);
autoGenerator.template(templateConfig);
autoGenerator.execute();
}
}
|
3e0add386d430b6638e65bb9f11fb28566eb4eee | 3,893 | java | Java | debezium-core/src/main/java/io/debezium/heartbeat/HeartbeatImpl.java | mduhan/debezium | 033db6659de6a027d54b662cd51f03279212f89d | [
"Apache-2.0"
] | 1 | 2019-06-12T04:20:29.000Z | 2019-06-12T04:20:29.000Z | debezium-core/src/main/java/io/debezium/heartbeat/HeartbeatImpl.java | mduhan/debezium | 033db6659de6a027d54b662cd51f03279212f89d | [
"Apache-2.0"
] | null | null | null | debezium-core/src/main/java/io/debezium/heartbeat/HeartbeatImpl.java | mduhan/debezium | 033db6659de6a027d54b662cd51f03279212f89d | [
"Apache-2.0"
] | 1 | 2020-10-22T07:23:28.000Z | 2020-10-22T07:23:28.000Z | 33.560345 | 129 | 0.687644 | 4,598 | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.heartbeat;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.config.Configuration;
import io.debezium.function.BlockingConsumer;
import io.debezium.util.Clock;
import io.debezium.util.Threads;
import io.debezium.util.Threads.Timer;
import io.debezium.util.SchemaNameAdjuster;
/**
* Default implementation of Heartbeat
*
* @author Jiri Pechanec
*
*/
class HeartbeatImpl implements Heartbeat {
private static final Logger LOGGER = LoggerFactory.getLogger(HeartbeatImpl.class);
private static final SchemaNameAdjuster schemaNameAdjuster = SchemaNameAdjuster.create(LOGGER);
/**
* Default length of interval in which connector generates periodically
* heartbeat messages. A size of 0 disables heartbeat.
*/
static final int DEFAULT_HEARTBEAT_INTERVAL = 0;
/**
* Default prefix for names of heartbeat topics
*/
static final String DEFAULT_HEARTBEAT_TOPICS_PREFIX = "__debezium-heartbeat";
private static final String SERVER_NAME_KEY = "serverName";
private static Schema KEY_SCHEMA = SchemaBuilder.struct()
.name(schemaNameAdjuster.adjust("io.debezium.connector.mysql.ServerNameKey"))
.field(SERVER_NAME_KEY,Schema.STRING_SCHEMA)
.build();
private final String topicName;
private final Supplier<OffsetPosition> positionSupplier;
private final Duration heartbeatInterval;
private final String key;
private volatile Timer heartbeatTimeout;
HeartbeatImpl(Configuration configuration, String topicName,
String key, Supplier<OffsetPosition> positionSupplier) {
this.topicName = topicName;
this.positionSupplier = positionSupplier;
this.key = key;
heartbeatInterval = configuration.getDuration(HeartbeatImpl.HEARTBEAT_INTERVAL, ChronoUnit.MILLIS);
heartbeatTimeout = resetHeartbeat();
}
@Override
public void heartbeat(Consumer<SourceRecord> consumer) {
if (heartbeatTimeout.expired()) {
LOGGER.debug("Generating heartbeat event");
consumer.accept(heartbeatRecord());
heartbeatTimeout = resetHeartbeat();
}
}
@Override
public void heartbeat(BlockingConsumer<SourceRecord> consumer) throws InterruptedException {
if (heartbeatTimeout.expired()) {
LOGGER.debug("Generating heartbeat event");
consumer.accept(heartbeatRecord());
heartbeatTimeout = resetHeartbeat();
}
}
/**
* Produce a key struct based on the server name and KEY_SCHEMA
*
*/
private Struct serverNameKey(String serverName){
Struct result = new Struct(KEY_SCHEMA);
result.put(SERVER_NAME_KEY, serverName);
return result;
}
/**
* Produce an empty record to the heartbeat topic.
*
*/
private SourceRecord heartbeatRecord() {
final Integer partition = 0;
OffsetPosition position = positionSupplier.get();
return new SourceRecord(position.partition(), position.offset(),
topicName, partition, KEY_SCHEMA, serverNameKey(key), null, null);
}
private Timer resetHeartbeat() {
return Threads.timer(Clock.SYSTEM, heartbeatInterval);
}
}
|
3e0adee48507bcec01f75ff3d38913a9a4ee8ec3 | 1,808 | java | Java | sdk/outboundmailer/src/main/java/com/fincloud/outboundmailer/models/FileUploadResponseFilesItem.java | samjegal/fincloud-sdk-for-java | 3fbc0078be2aa6ef9981044ca911d86afa0fef8f | [
"MIT"
] | null | null | null | sdk/outboundmailer/src/main/java/com/fincloud/outboundmailer/models/FileUploadResponseFilesItem.java | samjegal/fincloud-sdk-for-java | 3fbc0078be2aa6ef9981044ca911d86afa0fef8f | [
"MIT"
] | null | null | null | sdk/outboundmailer/src/main/java/com/fincloud/outboundmailer/models/FileUploadResponseFilesItem.java | samjegal/fincloud-sdk-for-java | 3fbc0078be2aa6ef9981044ca911d86afa0fef8f | [
"MIT"
] | null | null | null | 19.652174 | 70 | 0.589049 | 4,599 | /**
* FINCLOUD_APACHE_NO_VERSION
*/
package com.fincloud.outboundmailer.models;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The FileUploadResponseFilesItem model.
*/
public class FileUploadResponseFilesItem {
/**
* File ID.
*/
@JsonProperty(value = "fileId")
private String fileId;
/**
* File name.
*/
@JsonProperty(value = "fileName")
private String fileName;
/**
* File 크기.
*/
@JsonProperty(value = "fileSize")
private Long fileSize;
/**
* Get file ID.
*
* @return the fileId value
*/
public String fileId() {
return this.fileId;
}
/**
* Set file ID.
*
* @param fileId the fileId value to set
* @return the FileUploadResponseFilesItem object itself.
*/
public FileUploadResponseFilesItem withFileId(String fileId) {
this.fileId = fileId;
return this;
}
/**
* Get file name.
*
* @return the fileName value
*/
public String fileName() {
return this.fileName;
}
/**
* Set file name.
*
* @param fileName the fileName value to set
* @return the FileUploadResponseFilesItem object itself.
*/
public FileUploadResponseFilesItem withFileName(String fileName) {
this.fileName = fileName;
return this;
}
/**
* Get file 크기.
*
* @return the fileSize value
*/
public Long fileSize() {
return this.fileSize;
}
/**
* Set file 크기.
*
* @param fileSize the fileSize value to set
* @return the FileUploadResponseFilesItem object itself.
*/
public FileUploadResponseFilesItem withFileSize(Long fileSize) {
this.fileSize = fileSize;
return this;
}
}
|
3e0ae09f2dc0d139ec235091ab851a10a0a85628 | 17,137 | java | Java | library/src/main/java/com/dream/library/widgets/swipeback/SwipeBackLayout.java | susong0618/EasyFrame | b6593cf2bd8f0ded1d3e92ceed5d55b5087844f1 | [
"Apache-2.0"
] | 5 | 2015-10-12T01:11:46.000Z | 2016-09-19T08:55:48.000Z | library/src/main/java/com/dream/library/widgets/swipeback/SwipeBackLayout.java | susong/EasyFrame | b6593cf2bd8f0ded1d3e92ceed5d55b5087844f1 | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/dream/library/widgets/swipeback/SwipeBackLayout.java | susong/EasyFrame | b6593cf2bd8f0ded1d3e92ceed5d55b5087844f1 | [
"Apache-2.0"
] | null | null | null | 32.641905 | 114 | 0.60028 | 4,600 | package com.dream.library.widgets.swipeback;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import com.dream.library.R;
import java.util.ArrayList;
import java.util.List;
public class SwipeBackLayout extends FrameLayout {
/**
* Minimum velocity that will be detected as a fling
*/
private static final int MIN_FLING_VELOCITY = 400; // dips per second
private static final int DEFAULT_SCRIM_COLOR = 0x99000000;
private static final int FULL_ALPHA = 255;
/**
* Edge flag indicating that the left edge should be affected.
*/
public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT;
/**
* Edge flag indicating that the right edge should be affected.
*/
public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT;
/**
* Edge flag indicating that the bottom edge should be affected.
*/
public static final int EDGE_BOTTOM = ViewDragHelper.EDGE_BOTTOM;
/**
* Edge flag set indicating all edges should be affected.
*/
public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT | EDGE_BOTTOM;
/**
* A view is not currently being dragged or animating as a result of a
* fling/snap.
*/
public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;
/**
* A view is currently being dragged. The position is currently changing as
* a result of user input or simulated user input.
*/
public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;
/**
* A view is currently settling into place as a result of a fling or
* predefined non-interactive motion.
*/
public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;
/**
* Default threshold of scroll
*/
private static final float DEFAULT_SCROLL_THRESHOLD = 0.3f;
private static final int OVERSCROLL_DISTANCE = 10;
private static final int[] EDGE_FLAGS = {
EDGE_LEFT, EDGE_RIGHT, EDGE_BOTTOM, EDGE_ALL
};
private int mEdgeFlag;
/**
* Threshold of scroll, we will close the activity, when scrollPercent over
* this value;
*/
private float mScrollThreshold = DEFAULT_SCROLL_THRESHOLD;
private Activity mActivity;
private boolean mEnable = true;
private View mContentView;
private ViewDragHelper mDragHelper;
private float mScrollPercent;
private int mContentLeft;
private int mContentTop;
/**
* The set of listeners to be sent events through.
*/
private List<SwipeListener> mListeners;
private float mScrimOpacity;
private int mScrimColor = DEFAULT_SCRIM_COLOR;
private boolean mInLayout;
private Rect mTmpRect = new Rect();
/**
* Edge being dragged
*/
private int mTrackingEdge;
public SwipeBackLayout(Context context) {
this(context, null);
}
public SwipeBackLayout(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.SwipeBackLayoutStyle);
}
public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
mDragHelper = ViewDragHelper.create(this, new ViewDragCallback());
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeBackLayout, defStyle,
R.style.SwipeBackLayout);
int edgeSize = a.getDimensionPixelSize(R.styleable.SwipeBackLayout_edge_size, -1);
if (edgeSize > 0)
setEdgeSize(edgeSize);
int mode = EDGE_FLAGS[a.getInt(R.styleable.SwipeBackLayout_edge_flag, 0)];
setEdgeTrackingEnabled(mode);
a.recycle();
final float density = getResources().getDisplayMetrics().density;
final float minVel = MIN_FLING_VELOCITY * density;
mDragHelper.setMinVelocity(minVel);
mDragHelper.setMaxVelocity(minVel * 2f);
}
/**
* Sets the sensitivity of the NavigationLayout.
*
* @param context The application context.
* @param sensitivity value between 0 and 1, the final value for touchSlop =
* ViewConfiguration.getScaledTouchSlop * (1 / s);
*/
public void setSensitivity(Context context, float sensitivity) {
mDragHelper.setSensitivity(context, sensitivity);
}
/**
* Set up contentView which will be moved by user gesture
*
* @param view
*/
private void setContentView(View view) {
mContentView = view;
}
public void setEnableGesture(boolean enable) {
mEnable = enable;
}
/**
* Enable edge tracking for the selected edges of the parent view. The
* callback's
* {@link com.github.obsessive.library.swipeback.ViewDragHelper.Callback#onEdgeTouched(int, int)}
* and
* {@link com.github.obsessive.library.swipeback.ViewDragHelper.Callback#onEdgeDragStarted(int, int)}
* methods will only be invoked for edges for which edge tracking has been
* enabled.
*
* @param edgeFlags Combination of edge flags describing the edges to watch
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setEdgeTrackingEnabled(int edgeFlags) {
mEdgeFlag = edgeFlags;
mDragHelper.setEdgeTrackingEnabled(mEdgeFlag);
}
/**
* Set a color to use for the scrim that obscures primary content while a
* drawer is open.
*
* @param color Color to use in 0xAARRGGBB format.
*/
public void setScrimColor(int color) {
mScrimColor = color;
invalidate();
}
/**
* Set the size of an edge. This is the range in pixels along the edges of
* this view that will actively detect edge touches or drags if edge
* tracking is enabled.
*
* @param size The size of an edge in pixels
*/
public void setEdgeSize(int size) {
mDragHelper.setEdgeSize(size);
}
/**
* Register a callback to be invoked when a swipe event is sent to this
* view.
*
* @param listener the swipe listener to attach to this view
* @deprecated use {@link #addSwipeListener} instead
*/
@Deprecated
public void setSwipeListener(SwipeListener listener) {
addSwipeListener(listener);
}
/**
* Add a callback to be invoked when a swipe event is sent to this view.
*
* @param listener the swipe listener to attach to this view
*/
public void addSwipeListener(SwipeListener listener) {
if (mListeners == null) {
mListeners = new ArrayList<SwipeListener>();
}
mListeners.add(listener);
}
/**
* Removes a listener from the set of listeners
*
* @param listener
*/
public void removeSwipeListener(SwipeListener listener) {
if (mListeners == null) {
return;
}
mListeners.remove(listener);
}
public static interface SwipeListener {
/**
* Invoke when state change
*
* @param state flag to describe scroll state
* @param scrollPercent scroll percent of this view
* @see #STATE_IDLE
* @see #STATE_DRAGGING
* @see #STATE_SETTLING
*/
public void onScrollStateChange(int state, float scrollPercent);
/**
* Invoke when edge touched
*
* @param edgeFlag edge flag describing the edge being touched
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void onEdgeTouch(int edgeFlag);
/**
* Invoke when scroll percent over the threshold for the first time
*/
public void onScrollOverThreshold();
}
/**
* Set scroll threshold, we will close the activity, when scrollPercent over
* this value
*
* @param threshold
*/
public void setScrollThresHold(float threshold) {
if (threshold >= 1.0f || threshold <= 0) {
throw new IllegalArgumentException("Threshold value should be between 0 and 1.0");
}
mScrollThreshold = threshold;
}
/**
* Scroll out contentView and finish the activity
*/
public void scrollToFinishActivity() {
final int childWidth = mContentView.getWidth();
final int childHeight = mContentView.getHeight();
int left = 0, top = 0;
if ((mEdgeFlag & EDGE_LEFT) != 0) {
left = childWidth + OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_LEFT;
} else if ((mEdgeFlag & EDGE_RIGHT) != 0) {
left = -childWidth - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_RIGHT;
} else if ((mEdgeFlag & EDGE_BOTTOM) != 0) {
top = -childHeight - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_BOTTOM;
}
mDragHelper.smoothSlideViewTo(mContentView, left, top);
invalidate();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
try {
return mDragHelper.shouldInterceptTouchEvent(event);
} catch (ArrayIndexOutOfBoundsException e) {
// FIXME: handle exception
// issues #9
return false;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
mDragHelper.processTouchEvent(event);
return true;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mInLayout = true;
if (mContentView != null)
mContentView.layout(mContentLeft, mContentTop,
mContentLeft + mContentView.getMeasuredWidth(),
mContentTop + mContentView.getMeasuredHeight());
mInLayout = false;
}
@Override
public void requestLayout() {
if (!mInLayout) {
super.requestLayout();
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final boolean drawContent = child == mContentView;
boolean ret = super.drawChild(canvas, child, drawingTime);
if (mScrimOpacity > 0 && drawContent
&& mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) {
drawScrim(canvas, child);
}
return ret;
}
private void drawScrim(Canvas canvas, View child) {
final int baseAlpha = (mScrimColor & 0xff000000) >>> 24;
final int alpha = (int) (baseAlpha * mScrimOpacity);
final int color = alpha << 24 | (mScrimColor & 0xffffff);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
canvas.clipRect(0, 0, child.getLeft(), getHeight());
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight());
}
canvas.drawColor(color);
}
public void attachToActivity(Activity activity) {
mActivity = activity;
TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{
android.R.attr.windowBackground
});
int background = a.getResourceId(0, 0);
a.recycle();
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView().findViewById(Window.ID_ANDROID_CONTENT);
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
decorChild.setBackgroundResource(background);
decor.removeView(decorChild);
addView(decorChild);
setContentView(decorChild);
decor.addView(this);
}
@Override
public void computeScroll() {
mScrimOpacity = 1 - mScrollPercent;
if (mDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private class ViewDragCallback extends ViewDragHelper.Callback {
private boolean mIsScrollOverValid;
@Override
public boolean tryCaptureView(View view, int i) {
boolean ret = mDragHelper.isEdgeTouched(mEdgeFlag, i);
if (ret) {
if (mDragHelper.isEdgeTouched(EDGE_LEFT, i)) {
mTrackingEdge = EDGE_LEFT;
} else if (mDragHelper.isEdgeTouched(EDGE_RIGHT, i)) {
mTrackingEdge = EDGE_RIGHT;
} else if (mDragHelper.isEdgeTouched(EDGE_BOTTOM, i)) {
mTrackingEdge = EDGE_BOTTOM;
}
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onEdgeTouch(mTrackingEdge);
}
}
mIsScrollOverValid = true;
}
return ret;
}
@Override
public int getViewHorizontalDragRange(View child) {
return mEdgeFlag & (EDGE_LEFT | EDGE_RIGHT);
}
@Override
public int getViewVerticalDragRange(View child) {
return mEdgeFlag & EDGE_BOTTOM;
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
super.onViewPositionChanged(changedView, left, top, dx, dy);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth()));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth()));
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
mScrollPercent = Math.abs((float) top
/ (mContentView.getHeight()));
}
mContentLeft = left;
mContentTop = top;
invalidate();
if (mScrollPercent < mScrollThreshold && !mIsScrollOverValid) {
mIsScrollOverValid = true;
}
if (mListeners != null && !mListeners.isEmpty()
&& mDragHelper.getViewDragState() == STATE_DRAGGING
&& mScrollPercent >= mScrollThreshold && mIsScrollOverValid) {
mIsScrollOverValid = false;
for (SwipeListener listener : mListeners) {
listener.onScrollOverThreshold();
}
}
if (mScrollPercent >= 1) {
if (!mActivity.isFinishing())
mActivity.finish();
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final int childWidth = releasedChild.getWidth();
final int childHeight = releasedChild.getHeight();
int left = 0, top = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? childWidth
+ OVERSCROLL_DISTANCE : 0;
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? -(childWidth
+ OVERSCROLL_DISTANCE) : 0;
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
top = yvel < 0 || yvel == 0 && mScrollPercent > mScrollThreshold ? -(childHeight
+ OVERSCROLL_DISTANCE) : 0;
}
mDragHelper.settleCapturedViewAt(left, top);
invalidate();
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
int ret = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
ret = Math.min(child.getWidth(), Math.max(left, 0));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
ret = Math.min(0, Math.max(left, -child.getWidth()));
}
return ret;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
int ret = 0;
if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
ret = Math.min(0, Math.max(top, -child.getHeight()));
}
return ret;
}
@Override
public void onViewDragStateChanged(int state) {
super.onViewDragStateChanged(state);
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onScrollStateChange(state, mScrollPercent);
}
}
}
}
}
|
3e0ae0c2644db416cb85487748635acb1928a460 | 13,756 | java | Java | react-native-pytorch-core/android/src/main/java/org/pytorch/rn/core/camera/CameraView.java | pytorch/live | a41764355b74b5948275dae680ea82cb1e9a4b38 | [
"MIT"
] | 270 | 2021-12-01T17:09:16.000Z | 2022-03-28T08:34:38.000Z | react-native-pytorch-core/android/src/main/java/org/pytorch/rn/core/camera/CameraView.java | liuyinglao/live | 95bad00f42ec34f14d75115db2b9edcc61c6b688 | [
"MIT"
] | 51 | 2021-12-01T17:32:02.000Z | 2022-03-29T10:57:21.000Z | react-native-pytorch-core/android/src/main/java/org/pytorch/rn/core/camera/CameraView.java | liuyinglao/live | 95bad00f42ec34f14d75115db2b9edcc61c6b688 | [
"MIT"
] | 29 | 2021-12-01T17:31:03.000Z | 2022-02-20T07:23:41.000Z | 35.637306 | 98 | 0.692062 | 4,601 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package org.pytorch.rn.core.camera;
import android.Manifest;
import android.animation.ValueAnimator;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.Log;
import android.util.Size;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraInfoUnavailableException;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.pytorch.rn.core.R;
import org.pytorch.rn.core.image.IImage;
import org.pytorch.rn.core.image.Image;
import org.pytorch.rn.core.javascript.JSContext;
public class CameraView extends ConstraintLayout {
public static final String TAG = "PTLCameraView";
public static final String REACT_CLASS = "PyTorchCameraView";
private final String[] REQUIRED_PERMISSIONS = new String[] {Manifest.permission.CAMERA};
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private PreviewView mPreviewView;
private Button mCaptureButton;
private Button mFlipButton;
private ImageCapture mImageCapture;
private ValueAnimator pressAnimation, releaseAnimation;
private LayerDrawable mCaptureButtonLayerDrawable;
private GradientDrawable mCaptureButtonInnerCircle;
private CameraSelector mPreferredCameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
private final int DURATION = 100;
private final float SCALE_BUTTON_BY = 1.15f;
private boolean mIsDirty = false;
private boolean mIsDirtyForCameraRestart = false;
private boolean mHideCaptureButton = false;
private boolean mHideFlipButton = false;
private Size mTargetResolution = new Size(480, 640);
private Camera mCamera;
/** Blocking camera operations are performed using this executor */
private ExecutorService cameraExecutor;
private final ReactApplicationContext mReactContext;
public CameraView(ReactApplicationContext context) {
super(context);
mReactContext = context;
init();
}
private void init() {
cameraProviderFuture = ProcessCameraProvider.getInstance(mReactContext.getCurrentActivity());
// Initialize our background executor
cameraExecutor = Executors.newSingleThreadExecutor();
View mLayout = inflate(mReactContext, R.layout.activity_camera, this);
mPreviewView = mLayout.findViewById(R.id.preview_view);
mCaptureButton = mLayout.findViewById(R.id.capture_button);
mFlipButton = mLayout.findViewById(R.id.flip_button);
// Initialize drawables to change (inner circle stroke)
mCaptureButtonLayerDrawable =
(LayerDrawable)
mReactContext
.getResources()
.getDrawable(R.drawable.camera_button, mReactContext.getTheme())
.mutate();
mCaptureButtonInnerCircle =
(GradientDrawable)
mCaptureButtonLayerDrawable.findDrawableByLayerId(R.id.camera_button_inner_circle);
// Calculate pixel values of borders
float density = mReactContext.getResources().getDisplayMetrics().density;
int cameraButtonInnerBorderNormal = (int) (density * 18);
int cameraButtonInnerBorderPressed = (int) (density * 24);
// Initialize Value Animators and Listeners
// grow means grow border so the circle shrinks
pressAnimation =
ValueAnimator.ofInt(cameraButtonInnerBorderNormal, cameraButtonInnerBorderPressed)
.setDuration(DURATION);
releaseAnimation =
ValueAnimator.ofInt(cameraButtonInnerBorderPressed, cameraButtonInnerBorderNormal)
.setDuration(DURATION);
ValueAnimator.AnimatorUpdateListener animatorUpdateListener =
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator updatedAnimation) {
int animatedValue = (int) updatedAnimation.getAnimatedValue();
mCaptureButtonInnerCircle.setStroke(animatedValue, Color.TRANSPARENT);
mCaptureButton.setBackground(mCaptureButtonLayerDrawable);
}
};
pressAnimation.addUpdateListener(animatorUpdateListener);
releaseAnimation.addUpdateListener(animatorUpdateListener);
mCaptureButton.setOnTouchListener(
(v, e) -> {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
pressAnimation.start();
mCaptureButton.animate().scaleX(SCALE_BUTTON_BY).setDuration(DURATION);
mCaptureButton.animate().scaleY(SCALE_BUTTON_BY).setDuration(DURATION);
takePicture();
break;
case MotionEvent.ACTION_UP:
releaseAnimation.start();
mCaptureButton.animate().scaleX(1f).setDuration(DURATION);
mCaptureButton.animate().scaleY(1f).setDuration(DURATION);
}
return false;
});
mFlipButton.setOnTouchListener(
(v, e) -> {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
flipCamera();
}
return false;
});
// The PreviewView has a width/height of 0/0. This was reported as an issue in the CameraX
// issue tracker and is supposedly a bug in how React Native calculates children dimension.
// A manual remeasure of the layout fixes this.
// Link to issue: https://issuetracker.google.com/issues/177245493#comment8
mPreviewView.setOnHierarchyChangeListener(new CameraView.ReactNativeCameraPreviewRemeasure());
if (allPermissionsGranted()) {
startCamera(); // start camera if permission has been granted by user
} else {
int REQUEST_CODE_PERMISSIONS = 200;
ActivityCompat.requestPermissions(
mReactContext.getCurrentActivity(), REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
}
private void startCamera() {
cameraProviderFuture.addListener(
() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future.
// This should never be reached.
Log.e(TAG, e.getMessage());
}
},
ContextCompat.getMainExecutor(mReactContext));
}
protected void takePicture() {
if (mImageCapture != null) {
mImageCapture.takePicture(
ContextCompat.getMainExecutor(mReactContext),
new ImageCapture.OnImageCapturedCallback() {
@Override
public void onCaptureSuccess(@NonNull ImageProxy imageProxy) {
super.onCaptureSuccess(imageProxy);
IImage image = new Image(imageProxy, mReactContext.getApplicationContext());
JSContext.NativeJSRef ref = JSContext.wrapObject(image);
mReactContext
.getJSModule(RCTEventEmitter.class)
.receiveEvent(CameraView.this.getId(), "onCapture", ref.getJSRef());
}
@Override
public void onError(@NonNull ImageCaptureException exception) {
super.onError(exception);
Log.e(TAG, exception.getLocalizedMessage(), exception);
}
});
}
}
protected void flipCamera() {
if (mPreferredCameraSelector == CameraSelector.DEFAULT_BACK_CAMERA) {
mPreferredCameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA;
} else {
mPreferredCameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
}
startCamera();
}
void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
// Unbind previous use cases. Without this, on unmounting and mounting CameraView again, the
// app will crash.
cameraProvider.unbindAll();
Preview preview = new Preview.Builder().build();
// Some devices do not have front and back camera, like the emulator on a laptop.
CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
try {
if (cameraProvider.hasCamera(mPreferredCameraSelector)) {
cameraSelector = mPreferredCameraSelector;
}
} catch (CameraInfoUnavailableException e) {
}
ImageAnalysis imageAnalysis =
new ImageAnalysis.Builder()
.setTargetResolution(mTargetResolution)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build();
imageAnalysis.setAnalyzer(
cameraExecutor,
imageProxy -> {
IImage image = new Image(imageProxy, mReactContext.getApplicationContext());
JSContext.NativeJSRef ref = JSContext.wrapObject(image);
mReactContext
.getJSModule(RCTEventEmitter.class)
.receiveEvent(CameraView.this.getId(), "onFrame", ref.getJSRef());
});
mImageCapture = new ImageCapture.Builder().setTargetResolution(mTargetResolution).build();
OrientationEventListener orientationEventListener =
new OrientationEventListener(mReactContext.getApplicationContext()) {
@Override
public void onOrientationChanged(int orientation) {
int rotation;
// Monitors orientation values to determine the target rotation value
if (orientation >= 45 && orientation < 135) {
rotation = Surface.ROTATION_270;
} else if (orientation >= 135 && orientation < 225) {
rotation = Surface.ROTATION_180;
} else if (orientation >= 225 && orientation < 315) {
rotation = Surface.ROTATION_90;
} else {
rotation = Surface.ROTATION_0;
}
mImageCapture.setTargetRotation(rotation);
imageAnalysis.setTargetRotation(rotation);
}
};
orientationEventListener.enable();
mCamera =
cameraProvider.bindToLifecycle(
(LifecycleOwner) mReactContext.getCurrentActivity(),
cameraSelector,
preview,
imageAnalysis,
mImageCapture);
preview.setSurfaceProvider(
ContextCompat.getMainExecutor(mReactContext), mPreviewView.getSurfaceProvider());
}
private boolean allPermissionsGranted() {
for (String permission : REQUIRED_PERMISSIONS) {
if (ContextCompat.checkSelfPermission(mReactContext, permission)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
public void setHideCaptureButton(boolean hideCaptureButton) {
if (mHideCaptureButton != hideCaptureButton) {
mHideCaptureButton = hideCaptureButton;
mIsDirty = true;
}
}
public void setHideFlipButton(boolean hideFlipButton) {
if (mHideFlipButton != hideFlipButton) {
mHideFlipButton = hideFlipButton;
mIsDirty = true;
}
}
public void setCameraSelector(CameraSelector cameraSelector) {
if (!mPreferredCameraSelector.equals(cameraSelector)) {
mPreferredCameraSelector = cameraSelector;
mIsDirty = true;
mIsDirtyForCameraRestart = true;
}
}
public void setTargetResolution(Size size) {
if (!mTargetResolution.equals(size)) {
mTargetResolution = size;
mIsDirty = true;
mIsDirtyForCameraRestart = true;
}
}
public void maybeUpdateView() {
if (!mIsDirty) {
return;
}
mCaptureButton.post(
() -> {
mCaptureButton.setVisibility(mHideCaptureButton ? View.INVISIBLE : View.VISIBLE);
});
mFlipButton.post(
() -> {
mFlipButton.setVisibility(mHideFlipButton ? View.INVISIBLE : View.VISIBLE);
});
if (mIsDirtyForCameraRestart) {
startCamera();
}
}
private static class ReactNativeCameraPreviewRemeasure
implements ViewGroup.OnHierarchyChangeListener {
@Override
public void onChildViewAdded(View parent, View child) {
parent.post(
() -> {
parent.measure(
View.MeasureSpec.makeMeasureSpec(
parent.getMeasuredWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(
parent.getMeasuredHeight(), View.MeasureSpec.EXACTLY));
parent.layout(0, 0, parent.getMeasuredWidth(), parent.getMeasuredHeight());
Log.d(
TAG,
String.format(
"Measured width=%s, height=%s",
parent.getMeasuredWidth(), parent.getMeasuredHeight()));
});
}
@Override
public void onChildViewRemoved(View parent, View child) {
// empty
}
}
}
|
3e0ae2957ceaea9257024a5726bd759432b9f1a7 | 4,993 | java | Java | src/main/java/com/lailaps/ui/DownloadScreenController.java | theovier/lernplattform-crawler | 46d1a6afed56983da63841e79d96337693651a57 | [
"MIT"
] | 7 | 2017-07-07T20:24:13.000Z | 2018-10-24T13:30:06.000Z | src/main/java/com/lailaps/ui/DownloadScreenController.java | theovier/lernplattform-crawler | 46d1a6afed56983da63841e79d96337693651a57 | [
"MIT"
] | 2 | 2017-10-29T18:53:12.000Z | 2019-10-31T10:27:36.000Z | src/main/java/com/lailaps/ui/DownloadScreenController.java | theovier/lernplattform-crawler | 46d1a6afed56983da63841e79d96337693651a57 | [
"MIT"
] | null | null | null | 34.916084 | 111 | 0.727418 | 4,602 | package com.lailaps.ui;
import com.lailaps.download.DownloadObserver;
import com.lailaps.download.DownloadStatistics;
import com.lailaps.download.DownloadableDocument;
import com.lailaps.ui.DownloadIndicator.FailedDownloadIndicator;
import com.lailaps.ui.DownloadIndicator.ProgressDownloadIndicator;
import com.lailaps.ui.DownloadIndicator.SkippedDownloadIndicator;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.net.URL;
import java.util.ResourceBundle;
public class DownloadScreenController implements Initializable, Controllable, AutoResizable, DownloadObserver {
private ScreenContainer parent;
private ObservableList<ProgressDownloadIndicator> downloadIndicators = FXCollections.observableArrayList();
private ResourceBundle bundle;
@FXML
private BorderPane pane;
@FXML
private Label headline;
@FXML
private ProgressIndicator throbber;
@FXML
private ListView<ProgressDownloadIndicator> listView;
@Override
public void initialize(URL location, ResourceBundle resources) {
this.bundle = resources;
headline.setText(bundle.getString("downloadScreen.headline"));
determineTimeToBindSizes();
listView.setItems(downloadIndicators);
}
@Override
public void setParentScreen(ScreenContainer parent) {
this.parent = parent;
}
@Override
public ScreenContainer getParentScreen() {
return parent;
}
@Override
public void bindComponentsToStageSize() {
Stage stage = (Stage) pane.getScene().getWindow();
pane.prefWidthProperty().bind(stage.widthProperty());
listView.prefWidthProperty().bind(stage.widthProperty());
pane.prefHeightProperty().bind(stage.heightProperty().subtract(50));
for (ProgressDownloadIndicator line : downloadIndicators) {
line.bindProgressBarWidthProperty(listView);
}
}
@Override
public void determineTimeToBindSizes() {
pane.sceneProperty().addListener((observableScene, oldScene, newScene) -> {
if (oldScene == null && newScene != null) {
bindComponentsToStageSize();
}
});
}
private boolean updateDownloadIndicatorForDocument(DownloadableDocument document, double currentProgress) {
for (ProgressDownloadIndicator indicator : downloadIndicators) {
if (indicator.isReferringToSameDocument(document)) {
indicator.setProgress(currentProgress);
return true;
}
}
return false;
}
private boolean removeDownloadIndicatorForDocument(DownloadableDocument document) {
for (ProgressDownloadIndicator indicator : downloadIndicators) {
if (indicator.isReferringToSameDocument(document)) {
downloadIndicators.remove(indicator);
return true;
}
}
return false;
}
@Override
public void onDownloadStarted(DownloadableDocument document) {
ProgressDownloadIndicator newIndicator = new ProgressDownloadIndicator(document);
downloadIndicators.add(newIndicator);
newIndicator.bindProgressBarWidthProperty(listView);
}
@Override
public void onDownloadProgress(DownloadableDocument document, double currentProgress) {
updateDownloadIndicatorForDocument(document, currentProgress);
}
@Override
public void onDownloadSkipped(DownloadableDocument skippedDocument) {
SkippedDownloadIndicator skippingIndicator = new SkippedDownloadIndicator(skippedDocument, bundle);
skippingIndicator.bindProgressBarWidthProperty(listView);
downloadIndicators.add(skippingIndicator);
}
@Override
public void onDownloadFailed(DownloadableDocument failedDocument, Exception cause) {
removeDownloadIndicatorForDocument(failedDocument);
FailedDownloadIndicator failingIndicator = new FailedDownloadIndicator(failedDocument, cause);
failingIndicator.bindProgressBarWidthProperty(listView);
downloadIndicators.add(failingIndicator);
}
@Override
public void onDownloadSuccess(DownloadableDocument downloadedDocument) {
//empty
}
@Override
public void onFinishedDownloading(DownloadStatistics statistics) {
throbber.setVisible(false);
headline.setText(bundle.getString("downloadScreen.finished"));
FinishedDownloadAlert alert = new FinishedDownloadAlert(statistics, bundle);
alert.initContent();
alert.initModality(Modality.APPLICATION_MODAL);
alert.initOwner(parent.getCurrentWindow());
alert.displayAndWait();
}
}
|
3e0ae3ee9332d8b8e3cc28398244f2401909141b | 3,508 | java | Java | src/main/java/lkd/namsic/cnkb/domain/game/quest/Quest.java | CNKB/Server | 450ffb9e7210123be5500fe692c86da6fc9c6649 | [
"MIT"
] | 1 | 2021-09-28T12:50:19.000Z | 2021-09-28T12:50:19.000Z | src/main/java/lkd/namsic/cnkb/domain/game/quest/Quest.java | CNKB/Server | 450ffb9e7210123be5500fe692c86da6fc9c6649 | [
"MIT"
] | null | null | null | src/main/java/lkd/namsic/cnkb/domain/game/quest/Quest.java | CNKB/Server | 450ffb9e7210123be5500fe692c86da6fc9c6649 | [
"MIT"
] | null | null | null | 32.481481 | 84 | 0.70268 | 4,604 | package lkd.namsic.cnkb.domain.game.quest;
import lkd.namsic.cnkb.domain.game.chat.Chat;
import lkd.namsic.cnkb.domain.game.map.GameMapLimitQuest;
import lkd.namsic.cnkb.domain.game.npc.Npc;
import lkd.namsic.cnkb.domain.game.npc.NpcChatLimitCurrentQuest;
import lkd.namsic.cnkb.domain.game.npc.NpcChatLimitIntimacy;
import lkd.namsic.cnkb.domain.game.npc.NpcChatLimitQuest;
import lombok.*;
import javax.persistence.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Quest {
@Id
@Column
Long id;
@Builder.Default
@Column
Integer minLv = 1;
@Builder.Default
@Column(columnDefinition = "BIGINT UNSIGNED NOT NULL")
BigInteger needMoney = new BigInteger("0");
@Builder.Default
@Column(columnDefinition = "BIGINT UNSIGNED NOT NULL")
BigInteger rewardMoney = new BigInteger("0");
@Builder.Default
@Column(nullable = false)
Long rewardExp = 0L;
@Builder.Default
@Column(columnDefinition = "SMALLINT UNSIGNED NOT NULL")
Integer rewardAdv = 0;
@ManyToOne
@JoinColumn(name = "clear_npc_id", nullable = false)
Npc npc;
@Builder.Default
@OneToMany(mappedBy = "quest", cascade = CascadeType.ALL)
List<Chat> chatList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<GameMapLimitQuest> gameMapLimitQuestList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<NpcChatLimitCurrentQuest> npcChatLimitCurrentQuestList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<NpcChatLimitIntimacy> npcChatLimitIntimacyList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<NpcChatLimitQuest> npcChatLimitQuestList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "quest", cascade = CascadeType.ALL)
List<QuestNeedEquip> questNeedEquipList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestNeedItem> questNeedItemList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestNeedIntimacy> questNeedIntimacyList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestRewardEquip> questRewardEquipList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestRewardEquipRecipe> questRewardEquipRecipeList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestRewardIntimacy> questRewardIntimacyList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestRewardItem> questRewardItemList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestRewardItemRecipe> questRewardItemRecipeList = new ArrayList<>();
@Builder.Default
@OneToMany(mappedBy = "pk.quest", cascade = CascadeType.ALL)
List<QuestRewardStat> questRewardStatList = new ArrayList<>();
} |
3e0ae42635732d314d75f42735700ff067ad18cc | 1,586 | java | Java | src/main/java/com/arjim/webserver/user/model/ImFriendUserInfoData.java | pymxb1991/arjim-dis-server | e6b019b14d0e100165dc71f70eff8a49b220aebc | [
"Apache-2.0"
] | null | null | null | src/main/java/com/arjim/webserver/user/model/ImFriendUserInfoData.java | pymxb1991/arjim-dis-server | e6b019b14d0e100165dc71f70eff8a49b220aebc | [
"Apache-2.0"
] | null | null | null | src/main/java/com/arjim/webserver/user/model/ImFriendUserInfoData.java | pymxb1991/arjim-dis-server | e6b019b14d0e100165dc71f70eff8a49b220aebc | [
"Apache-2.0"
] | null | null | null | 18.022727 | 82 | 0.717528 | 4,605 | package com.arjim.webserver.user.model;
import org.apache.commons.lang.StringUtils;
public class ImFriendUserInfoData {
private String id;// 好友ID
private String username;// 好友昵称
private String avatar;// 好友头像
private String sign;// 签名
private String groupname;
private String status;
private Integer statusNo;
private Long sipUserName; // SIP帐号
private String sipPassword; // SIP密码
public Long getSipUserName() {
return sipUserName;
}
public void setSipUserName(Long sipUserName) {
this.sipUserName = sipUserName;
}
public String getSipPassword() {
return sipPassword;
}
public void setSipPassword(String sipPassword) {
this.sipPassword = sipPassword;
}
public String getGroupname() {
return groupname;
}
public void setGroupname(String groupname) {
this.groupname = groupname;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAvatar() {
return StringUtils.isNotEmpty(avatar) ? avatar : "layui/images/0.jpg";// avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getStatusNo() {
return statusNo;
}
public void setStatusNo(Integer statusNo) {
this.statusNo = statusNo;
}
}
|
3e0ae472e1fa36168e8308a26eb52a52dc046c5c | 4,734 | java | Java | kerberos-test/src/test/java/org/apache/directory/server/kerberos/kdc/KerberosTcpITest.java | motoponk/directory-server | 2a7dc89e3e905fd7ea3ace9a04fac561af594f56 | [
"Apache-2.0"
] | null | null | null | kerberos-test/src/test/java/org/apache/directory/server/kerberos/kdc/KerberosTcpITest.java | motoponk/directory-server | 2a7dc89e3e905fd7ea3ace9a04fac561af594f56 | [
"Apache-2.0"
] | 1 | 2021-02-23T13:28:38.000Z | 2021-02-23T13:28:38.000Z | kerberos-test/src/test/java/org/apache/directory/server/kerberos/kdc/KerberosTcpITest.java | motoponk/directory-server | 2a7dc89e3e905fd7ea3ace9a04fac561af594f56 | [
"Apache-2.0"
] | null | null | null | 38.233871 | 130 | 0.731702 | 4,606 | /*
* 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.directory.server.kerberos.kdc;
import org.apache.directory.server.annotations.CreateKdcServer;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifFiles;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.shared.kerberos.codec.types.EncryptionType;
import org.apache.directory.shared.kerberos.crypto.checksum.ChecksumType;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests to obtain TGTs and Service Tickets from KDCs via TCP.
*
* We use some internal knowledge of the Sun/Oracle implementation here to force
* the usage of TCP and checksum:
* <li>In sun.security.krb5.KrbKdcReq the static field udpPrefLimit is set to 1
* which means that TCP is always used.
* <li>In sun.security.krb5.Checksum the static field CKSUMTYPE_DEFAULT is set
* to the appropriate checksum value.
*
* @author <a href="mailto:kenaa@example.com">Apache Directory
Project</a>
*/
@RunWith(FrameworkRunner.class)
@CreateDS(name = "KerberosTcpIT-class",
partitions =
{
@CreatePartition(
name = "example",
suffix = "dc=example,dc=com")
},
additionalInterceptors =
{
KeyDerivationInterceptor.class
})
@CreateLdapServer(
transports =
{
@CreateTransport(protocol = "LDAP")
})
@CreateKdcServer(
transports =
{
@CreateTransport(protocol = "TCP", port = 6086)
})
@ApplyLdifFiles("org/apache/directory/server/kerberos/kdc/KerberosIT.ldif")
public class KerberosTcpITest extends AbstractKerberosITest
{
// TODO: fix failing tests
// TODO: add tests for other encryption types
// TODO: add tests for different options
@Test
public void testObtainTickets_DES3_CBC_SHA1_KD() throws Exception
{
// RFC3961, Section 6.3: des3-cbc-hmac-sha1-kd + hmac-sha1-des3-kd
ObtainTicketParameters parameters = new ObtainTicketParameters( TcpTransport.class,
EncryptionType.DES3_CBC_SHA1_KD, ChecksumType.HMAC_SHA1_DES3_KD );
testObtainTickets( parameters );
}
@Test
@Ignore("Fails with KrbException: Integrity check on decrypted field failed (31) - Integrity check on decrypted field failed")
public void testObtainTickets_RC4_HMAC() throws Exception
{
// TODO: RFC4757: rc4-hmac + hmac-md5
ObtainTicketParameters parameters = new ObtainTicketParameters( TcpTransport.class,
EncryptionType.RC4_HMAC, ChecksumType.HMAC_MD5 );
testObtainTickets( parameters );
}
@Test
public void testObtainTickets_AES128() throws Exception
{
// RFC3962, Section 7: aes128-cts-hmac-sha1-96 + hmac-sha1-96-aes128
ObtainTicketParameters parameters = new ObtainTicketParameters( TcpTransport.class,
EncryptionType.AES128_CTS_HMAC_SHA1_96, ChecksumType.HMAC_SHA1_96_AES128 );
testObtainTickets( parameters );
}
@Test
@Ignore("Fails with javax.security.auth.login.LoginException: No supported encryption types listed in default_tkt_enctypes")
public void testObtainTickets_AES256() throws Exception
{
// RFC3962, Section 7: aes256-cts-hmac-sha1-96 + hmac-sha1-96-aes256
ObtainTicketParameters parameters = new ObtainTicketParameters( TcpTransport.class,
EncryptionType.AES256_CTS_HMAC_SHA1_96, ChecksumType.HMAC_SHA1_96_AES256 );
testObtainTickets( parameters );
}
}
|
3e0ae495ed56a533b3ea321a2d8a5d0120948e8f | 361 | java | Java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/enums/MonthOfYearEnumOrBuilder.java | giger85/google-ads-java | e91f6aba2638d172baf302dbc3ff1dceb80c70fe | [
"Apache-2.0"
] | 1 | 2022-02-22T08:10:07.000Z | 2022-02-22T08:10:07.000Z | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/enums/MonthOfYearEnumOrBuilder.java | giger85/google-ads-java | e91f6aba2638d172baf302dbc3ff1dceb80c70fe | [
"Apache-2.0"
] | null | null | null | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/enums/MonthOfYearEnumOrBuilder.java | giger85/google-ads-java | e91f6aba2638d172baf302dbc3ff1dceb80c70fe | [
"Apache-2.0"
] | null | null | null | 36.1 | 97 | 0.803324 | 4,607 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/enums/month_of_year.proto
package com.google.ads.googleads.v10.enums;
public interface MonthOfYearEnumOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.enums.MonthOfYearEnum)
com.google.protobuf.MessageOrBuilder {
}
|
3e0ae53d0cda041e65973a3796687bdf55ca09ea | 9,076 | java | Java | com.io7m.smfj.cmdline/src/main/java/com/io7m/smfj/cmdline/CommandFilter.java | io7m/smf | a7f9adb53cceb41555e42e0bd9e89d4539ae2e7c | [
"0BSD"
] | null | null | null | com.io7m.smfj.cmdline/src/main/java/com/io7m/smfj/cmdline/CommandFilter.java | io7m/smf | a7f9adb53cceb41555e42e0bd9e89d4539ae2e7c | [
"0BSD"
] | 56 | 2016-11-20T22:43:11.000Z | 2019-12-22T20:54:35.000Z | com.io7m.smfj.cmdline/src/main/java/com/io7m/smfj/cmdline/CommandFilter.java | io7m/smf | a7f9adb53cceb41555e42e0bd9e89d4539ae2e7c | [
"0BSD"
] | null | null | null | 30.039735 | 81 | 0.667438 | 4,608 | /*
* Copyright © 2019 Mark Raynsford <efpyi@example.com> https://www.io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
* BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
package com.io7m.smfj.cmdline;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.io7m.smfj.core.SMFPartialLogged;
import com.io7m.smfj.frontend.SMFFilterCommandFile;
import com.io7m.smfj.frontend.SMFParserProviders;
import com.io7m.smfj.frontend.SMFSerializerProviders;
import com.io7m.smfj.parser.api.SMFParserProviderType;
import com.io7m.smfj.processing.api.SMFFilterCommandContext;
import com.io7m.smfj.processing.api.SMFFilterCommandModuleResolver;
import com.io7m.smfj.processing.api.SMFFilterCommandModuleResolverType;
import com.io7m.smfj.processing.api.SMFMemoryMesh;
import com.io7m.smfj.processing.api.SMFMemoryMeshFilterType;
import com.io7m.smfj.processing.api.SMFMemoryMeshProducer;
import com.io7m.smfj.processing.api.SMFMemoryMeshProducerType;
import com.io7m.smfj.processing.api.SMFMemoryMeshSerializer;
import com.io7m.smfj.serializer.api.SMFSerializerProviderType;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The filter command.
*/
@Parameters(commandDescription = "Filter mesh data")
public final class CommandFilter extends CommandRoot
{
private static final Logger LOG = LoggerFactory.getLogger(CommandFilter.class);
private int exitCode;
@Parameter(
names = "--input-file",
required = true,
description = "The input file")
private Path fileIn;
@Parameter(
names = "--input-format",
description = "The input file format")
private String formatIn;
@Parameter(
names = "--output-file",
description = "The output file")
private Path fileOut;
@Parameter(
names = "--output-format",
description = "The output file format")
private String formatOut;
@Parameter(
names = "--commands",
required = true,
description = "The filter commands")
private Path fileCommands;
@Parameter(
names = "--source-directory",
description = "The source directory")
private Path sourceDirectory = Paths.get("");
CommandFilter()
{
this.exitCode = 0;
}
@Override
public Integer call()
throws Exception
{
super.call();
final Optional<List<SMFMemoryMeshFilterType>> filtersOpt =
this.parseFilterCommands();
if (filtersOpt.isEmpty()) {
return this.fail();
}
final List<SMFMemoryMeshFilterType> filters = filtersOpt.get();
final Optional<SMFParserProviderType> providerParserOpt =
SMFParserProviders.findParserProvider(
Optional.ofNullable(this.formatIn),
this.fileIn.toString());
if (providerParserOpt.isEmpty()) {
return this.fail();
}
final SMFParserProviderType providerParser = providerParserOpt.get();
final Optional<SMFMemoryMesh> meshOpt =
this.loadMemoryMesh(providerParser, this.fileIn);
if (meshOpt.isEmpty()) {
return this.fail();
}
final SMFFilterCommandContext context =
SMFFilterCommandContext.of(
this.sourceDirectory.toAbsolutePath(),
this.fileCommands.toAbsolutePath());
final Optional<SMFMemoryMesh> filteredOpt =
this.runFilters(context, filters, meshOpt.get());
if (filteredOpt.isEmpty()) {
return this.fail();
}
this.serializeMesh(filteredOpt.get());
return Integer.valueOf(this.exitCode);
}
private void serializeMesh(
final SMFMemoryMesh filtered)
{
if (this.fileOut != null) {
final Optional<SMFSerializerProviderType> providerSerializerOpt =
SMFSerializerProviders.findSerializerProvider(
Optional.ofNullable(this.formatOut),
this.fileOut.toString());
if (providerSerializerOpt.isEmpty()) {
this.fail();
return;
}
final SMFSerializerProviderType serializers =
providerSerializerOpt.get();
LOG.debug("serializing to {}", this.fileOut);
final var timeThen = LocalDateTime.now();
try (var os = Files.newOutputStream(this.fileOut)) {
try (var serializer =
serializers.serializerCreate(
serializers.serializerSupportedVersions().last(),
this.fileOut.toUri(),
os)) {
SMFMemoryMeshSerializer.serialize(filtered, serializer);
}
} catch (final IOException e) {
LOG.error("could not serialize mesh: {}", e.getMessage());
LOG.debug("i/o error: ", e);
this.fail();
return;
}
final var timeNow = LocalDateTime.now();
LOG.debug("serialized in {}", Duration.between(timeThen, timeNow));
}
}
private Integer fail()
{
this.exitCode = 1;
return Integer.valueOf(this.exitCode);
}
private Optional<SMFMemoryMesh> runFilters(
final SMFFilterCommandContext context,
final List<SMFMemoryMeshFilterType> filters,
final SMFMemoryMesh mesh)
{
SMFMemoryMesh meshCurrent = mesh;
for (int index = 0; index < filters.size(); ++index) {
final SMFMemoryMeshFilterType filter = filters.get(index);
LOG.debug("evaluating filter: {}", filter.name());
final SMFPartialLogged<SMFMemoryMesh> result =
filter.filter(context, meshCurrent);
result.warnings().forEach(e -> {
LOG.warn("{}", e.fullMessage());
final Optional<Exception> exceptionOpt = e.exception();
if (exceptionOpt.isPresent()) {
LOG.error("exception: ", exceptionOpt.get());
}
});
result.errors().forEach(e -> {
LOG.error("{}", e.fullMessage());
final Optional<Exception> exceptionOpt = e.exception();
if (exceptionOpt.isPresent()) {
LOG.error("exception: ", exceptionOpt.get());
}
});
if (result.isSucceeded()) {
meshCurrent = result.get();
} else {
this.exitCode = 1;
return Optional.empty();
}
}
return Optional.of(meshCurrent);
}
private Optional<SMFMemoryMesh> loadMemoryMesh(
final SMFParserProviderType parsers,
final Path path)
throws IOException
{
final SMFMemoryMeshProducerType loader =
SMFMemoryMeshProducer.create();
LOG.debug("open {}", path);
try (var stream = Files.newInputStream(path)) {
try (var parser = parsers.parserCreateSequential(
loader, path.toUri(), stream)) {
parser.parse();
}
loader.warnings().forEach(e -> {
LOG.warn("{}", e.fullMessage());
final Optional<Exception> exceptionOpt = e.exception();
if (exceptionOpt.isPresent()) {
LOG.error("exception: ", exceptionOpt.get());
}
});
loader.errors().forEach(e -> {
LOG.error("{}", e.fullMessage());
final Optional<Exception> exceptionOpt = e.exception();
if (exceptionOpt.isPresent()) {
LOG.error("exception: ", exceptionOpt.get());
}
});
if (!loader.errors().isEmpty()) {
this.exitCode = 1;
return Optional.empty();
}
}
return Optional.of(loader.mesh());
}
private Optional<List<SMFMemoryMeshFilterType>> parseFilterCommands()
throws IOException
{
final SMFFilterCommandModuleResolverType resolver =
SMFFilterCommandModuleResolver.create();
try (var stream = Files.newInputStream(this.fileCommands)) {
final SMFPartialLogged<List<SMFMemoryMeshFilterType>> result =
SMFFilterCommandFile.parseFromStream(
resolver, Optional.of(this.fileCommands.toUri()), stream);
result.warnings().forEach(e -> {
LOG.warn("{}", e.fullMessage());
final Optional<Exception> exceptionOpt = e.exception();
if (exceptionOpt.isPresent()) {
LOG.error("exception: ", exceptionOpt.get());
}
});
result.errors().forEach(e -> {
LOG.error("{}", e.fullMessage());
final Optional<Exception> exceptionOpt = e.exception();
if (exceptionOpt.isPresent()) {
LOG.error("exception: ", exceptionOpt.get());
}
});
if (result.isSucceeded()) {
return Optional.of(result.get());
}
return Optional.empty();
}
}
}
|
3e0ae54b5b11ae31131b89c92c82791b057e579c | 4,756 | java | Java | java/nutshell/ShellUtils.java | fmidev/nutshell | 6b4a42670db8fc043dbe6a1687e59f3b77381b88 | [
"MIT"
] | 1 | 2021-07-26T02:40:38.000Z | 2021-07-26T02:40:38.000Z | java/nutshell/ShellUtils.java | fmidev/nutshell | 6b4a42670db8fc043dbe6a1687e59f3b77381b88 | [
"MIT"
] | null | null | null | java/nutshell/ShellUtils.java | fmidev/nutshell | 6b4a42670db8fc043dbe6a1687e59f3b77381b88 | [
"MIT"
] | 1 | 2020-05-12T12:50:21.000Z | 2020-05-12T12:50:21.000Z | 23.899497 | 125 | 0.66127 | 4,609 | package nutshell;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ShellUtils {
static public Process run(String[] cmdArray, String[] env, File directory) throws IOException, InterruptedException{
final Process child = Runtime.getRuntime().exec(cmdArray, env, directory);
// SP: Lisäsin waitFor-kutsun. Nyt ei ainakaan varmasti aloita uutta säiettä/prosessia.
// child.waitFor(); // NO! Sync'd read will pend!
return child;
}
static public Process run(String cmdLine, String[] env, File directory) throws IOException, InterruptedException{
return ShellUtils.run(cmdLine.split(" "), env, directory);
}
static public Process run(String cmd, String[] args, String[] env, File directory) throws IOException, InterruptedException{
if (args == null)
args = new String[0];
String[] cmdArray = new String[1+ args.length];
cmdArray[0] = cmd;
for (int i = 0; i < args.length; i++) {
cmdArray[1+i] = args[i];
}
return ShellUtils.run(cmdArray, env, directory);
}
/*
static public String[] mapToArray(Map<String, Object> map){
Set<String> set = new HashSet<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
set.add(entry.toString());
}
//return set.toArray(new String[set.size()]);
return set.toArray(new String[0]);
}
*/
/** Create a directory in which all the components are writable.
*
* @param root - starting point
* @param subdir - subdirectory
* @return - resulting directory (root and path concatenated)
* @throws IOException
static public Path makeWritableDir(Path root, Path subdir) throws IOException{
if (subdir == null)
return root;
if (subdir.getNameCount() == 0)
return root;
// recursion
if (makeWritableDir(root, subdir.getParent()) == null)
return null;
Path dirPath = root.resolve(subdir);
File dir = dirPath.toFile();
if (!dir.exists()){
//log.note("Creating dir: ").append(root);
if (!dir.mkdirs()){
throw new IOException("Creating dir failed: " + dirPath.toString());
//log.warn("Creating dir failed: ").append(root);
//return false;
}
}
if (! dir.setWritable(true, false)){
if (! dir.canWrite()){
throw new IOException("Could not set dir writable: " + dirPath.toString());
}
}
return dirPath;
}
*/
interface ProcessReader {
void handleStdOut(String line);
void handleStdErr(String line);
}
/**
*
* @param process - Process created with run etc.
* @return exit value
* @throws InterruptedException
*/
static public int read(Process process, ProcessReader reader) throws InterruptedException{
// Consider two separate processed, if timing is not issue.
InputStream inputStream = process.getInputStream();
InputStream errorStream = process.getErrorStream();
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
String inputLine = null;
String errorLine = null;
while (true){
while ((inputLine = inputReader.readLine()) != null)
reader.handleStdOut(inputLine);
while ((errorLine = errorReader.readLine()) != null)
reader.handleStdErr(errorLine);
if ((inputLine == null) && (errorLine == null))
break;
}
inputReader.close();
errorReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//check child.waitFor();
process.waitFor();
return process.exitValue();
}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length == 0){
System.out.println("Usage: <command> [<params>]");
System.out.println("Example: ls . foo.bar");
return;
}
String[] env = {"A=1", "B=2"};
File directory = new File(".");
try {
if (args.length == 1)
args = args[0].split(" ");
Process process = ShellUtils.run(args, env, directory);
ProcessReader handler = new ProcessReader() {
@Override
public void handleStdOut(String line) {
System.out.println("STDOUT:" + line);
}
@Override
public void handleStdErr(String line) {
System.err.println("STDERR:" + line);
}
};
read(process, handler);
System.out.println("exit value: " + process.exitValue());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
3e0ae5a953a125dd3dd9382eaf83305021b981c6 | 6,032 | java | Java | server/src/main/java/com/blocklang/core/git/GitCommit.java | blocklang/blocklang.com | 939074c9df037c0780e01e9a73ee724b3dcc1dc0 | [
"MIT"
] | 38 | 2019-01-28T10:32:24.000Z | 2022-03-14T15:17:35.000Z | server/src/main/java/com/blocklang/core/git/GitCommit.java | blocklang/blocklang-release | 939074c9df037c0780e01e9a73ee724b3dcc1dc0 | [
"MIT"
] | 515 | 2019-02-08T14:26:27.000Z | 2022-01-15T01:23:22.000Z | server/src/main/java/com/blocklang/core/git/GitCommit.java | blocklang/blocklang-release | 939074c9df037c0780e01e9a73ee724b3dcc1dc0 | [
"MIT"
] | 16 | 2019-04-08T08:07:08.000Z | 2022-03-10T07:03:26.000Z | 33.325967 | 127 | 0.712036 | 4,610 | package com.blocklang.core.git;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.EmptyCommitException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.blocklang.core.git.exception.FileCreateOrUpdateFailedException;
import com.blocklang.core.git.exception.GitCommitFailedException;
import com.blocklang.core.git.exception.GitEmptyCommitException;
import com.blocklang.core.git.exception.GitRepoNotFoundException;
public class GitCommit {
private static final Logger logger = LoggerFactory.getLogger(GitCommit.class);
/**
* git commit操作
*
* @param gitRepoPath git仓库根目录
* @param relativePath 相对git仓库根目录的文件夹路径,支持使用 / 分割的路径
* @param fileName 文件名
* @param fileContent 内容
* @param authorName 作者名称
* @param authorMail 作者邮箱
* @param commitMessage 提交信息
* @return 返回 commit id
*/
public String execute(
Path gitRepoPath,
String relativePath,
String fileName,
String fileContent,
String authorName,
String authorMail,
String commitMessage){
File folder = gitRepoPath.resolve(Constants.DOT_GIT).toFile();
try(Repository repo = FileRepositoryBuilder.create(folder);
Git git = new Git(repo)){
saveOrUpdateFile(gitRepoPath, relativePath, fileName, fileContent);
// 注意 Filepattern 一定是相对仓库根目录的路径,如果是目录,则不能以/或\开头,分隔符只能是 /
String filePattern = fileName;
if(StringUtils.isNotBlank(relativePath)) {
filePattern = relativePath + "/" + filePattern;
}
if(filePattern.startsWith("/")) {
filePattern = filePattern.substring(1);
}
git.add().addFilepattern(filePattern).call();
RevCommit commit = git.commit().setAuthor(authorName, authorMail).setMessage(commitMessage).call();
return commit.getName();
} catch (GitAPIException e) {
throw new GitCommitFailedException(e);
}catch (IOException e) {
throw new GitRepoNotFoundException(gitRepoPath.toString(), e);
}
}
private void saveOrUpdateFile(Path gitRepoPath,
String relativePath,
String fileName,
String fileContent){
try{
Path folder = null;
if(StringUtils.isBlank(relativePath)) {
folder = gitRepoPath;
}else {
folder = gitRepoPath.resolve(Paths.get("", relativePath.split("/")));
}
if(Files.notExists(folder)){
Files.createDirectories(folder);
}
Path file = folder.resolve(fileName);
if(Files.notExists(file)){
Files.createFile(file);
}
Files.writeString(file, fileContent);
}catch(IOException e){
throw new FileCreateOrUpdateFailedException(e);
}
}
public RevCommit getLatestCommit(Path gitRepoPath) {
File gitDir = gitRepoPath.resolve(Constants.DOT_GIT).toFile();
String branch = Constants.MASTER;
try (Repository repository = FileRepositoryBuilder.create(gitDir);
RevWalk walk = new RevWalk(repository)) {
Ref head = repository.findRef(branch);
RevCommit commit = walk.parseCommit(head.getObjectId());
walk.dispose();
return commit;
} catch (IOException e) {
logger.error("获取最新提交信息失败", e);
}
return null;
}
public RevCommit getLatestCommit(Path gitRepoPath, String relativeFilePath) {
File gitDir = gitRepoPath.resolve(Constants.DOT_GIT).toFile();
String branch = Constants.MASTER;
try (Repository repository = FileRepositoryBuilder.create(gitDir);
RevWalk walk = new RevWalk(repository);
Git git = new Git(repository)) {
Ref head = repository.findRef(branch);
if(StringUtils.isBlank(relativeFilePath)) {
RevCommit commit = walk.parseCommit(head.getObjectId());
walk.dispose();
return commit;
}
ObjectId objectId = null;
if(head == null){
objectId = repository.resolve(branch);
}else{
objectId = head.getObjectId();
}
RevCommit commit = walk.parseCommit(objectId);
Iterable<RevCommit> csIterable = git.log().add(commit.getId()).addPath(relativeFilePath).setMaxCount(1).call();
return csIterable.iterator().next();
} catch (IOException | GitAPIException e) {
logger.error("获取最新提交信息失败", e);
}
return null;
}
public String execute(Path gitRepoPath,
String authorName,
String authorMail,
String commitMessage) {
File folder = gitRepoPath.resolve(Constants.DOT_GIT).toFile();
try(Repository repo = FileRepositoryBuilder.create(folder);
Git git = new Git(repo)){
RevCommit commit = git.commit().setAllowEmpty(false).setCommitter(authorName, authorMail).setMessage(commitMessage).call();
return commit.getName();
} catch(EmptyCommitException e) {
logger.error("没有暂存的文件,不能空提交", e);
throw new GitEmptyCommitException(e);
} catch (GitAPIException e) {
throw new GitCommitFailedException(e);
}catch (IOException e) {
throw new GitRepoNotFoundException(gitRepoPath.toString(), e);
}
}
public String addAllAndCommit(Path gitRepoPath, String authorName, String authorMail, String commitMessage) {
File folder = gitRepoPath.resolve(Constants.DOT_GIT).toFile();
try(Repository repo = FileRepositoryBuilder.create(folder);
Git git = new Git(repo)){
git.add().addFilepattern(".").call();
RevCommit commit = git.commit().setAuthor(authorName, authorMail).setMessage(commitMessage).call();
return commit.getName();
} catch (GitAPIException e) {
throw new GitCommitFailedException(e);
}catch (IOException e) {
throw new GitRepoNotFoundException(gitRepoPath.toString(), e);
}
}
}
|
3e0ae5abfa7b1cc0de36ac2ae2ec984c5c0b82b1 | 777 | java | Java | src/main/java/controller/Cookieservlet.java | lizhenlizhenlizhen/ebank-app | d2b712525cfd2e2e8e208ca0b0d1ff412ae4e4ed | [
"Apache-2.0"
] | null | null | null | src/main/java/controller/Cookieservlet.java | lizhenlizhenlizhen/ebank-app | d2b712525cfd2e2e8e208ca0b0d1ff412ae4e4ed | [
"Apache-2.0"
] | null | null | null | src/main/java/controller/Cookieservlet.java | lizhenlizhenlizhen/ebank-app | d2b712525cfd2e2e8e208ca0b0d1ff412ae4e4ed | [
"Apache-2.0"
] | null | null | null | 24.28125 | 120 | 0.785071 | 4,611 | package controller;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Cookie Servlet
* @author ZhenLi
*
*/
@WebServlet(urlPatterns="/cookie")
public class Cookieservlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext ctxt = request.getServletContext();
System.out.println(ctxt);
Cookie c=new Cookie("k", "lizhen");
c.setMaxAge(60*60);
response.addCookie(c);
}
}
|
3e0ae5f9f0d5862c726892bb682913dbeb734dba | 6,261 | java | Java | solr-hadoop-core/src/test/java/com/lucidworks/hadoop/ingest/RegexIngestMapperTest.java | hortonworks/hadoop-solr | f2523e0fd945b105842a81b0db0cb5332d70102f | [
"Apache-2.0"
] | 48 | 2016-05-06T01:32:13.000Z | 2021-09-13T18:12:04.000Z | solr-hadoop-core/src/test/java/com/lucidworks/hadoop/ingest/RegexIngestMapperTest.java | hortonworks/hadoop-solr | f2523e0fd945b105842a81b0db0cb5332d70102f | [
"Apache-2.0"
] | 13 | 2016-05-01T18:20:22.000Z | 2020-02-16T19:29:33.000Z | solr-hadoop-core/src/test/java/com/lucidworks/hadoop/ingest/RegexIngestMapperTest.java | zvtrung/hadoop-solr | f2523e0fd945b105842a81b0db0cb5332d70102f | [
"Apache-2.0"
] | 36 | 2016-03-08T09:15:55.000Z | 2021-06-01T10:15:57.000Z | 44.091549 | 158 | 0.707235 | 4,612 | package com.lucidworks.hadoop.ingest;
import com.lucidworks.hadoop.io.LWDocument;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.mahout.common.Pair;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileIterator;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.lucidworks.hadoop.utils.ConfigurationKeys.COLLECTION;
import static com.lucidworks.hadoop.utils.ConfigurationKeys.ZK_CONNECT;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class RegexIngestMapperTest extends BaseMiniClusterTestCase {
@Test
public void test() throws Exception {
Configuration conf = getDefaultRegexIngestMapperConfiguration();
loadFrankensteinDataFromSequenceFile(conf); // Input is stored in 'sample.txt'
Job job = createJobBasedOnConfiguration(conf, RegexIngestMapper.class);
List<String> results = runJobSuccessfully(job, jobInput, 776);
assertNumDocsProcessed(job, 776);
assertTrue("Expected to parse ID for first input file", results.get(0).contains("sample.txt"));
}
@Test
public void testMatch() throws Exception {
jobInput.add("text 1 text 2");
Configuration conf = getDefaultRegexIngestMapperConfiguration();
conf.set(RegexIngestMapper.REGEX, "(\\w+)\\s+(\\d+)\\s+(\\w+)\\s+(\\d+)");
conf.set(RegexIngestMapper.GROUPS_TO_FIELDS, "0=body,1=text,2=number");
conf.setBoolean(RegexIngestMapper.REGEX_MATCH, true);
Job job = createJobBasedOnConfiguration(conf, RegexIngestMapper.class);
List<String> results = runJobSuccessfully(job, jobInput, 1);
assertNumDocsProcessed(job, 1);
assertNotNull("document is null", results.get(0));
}
@Test
public void testSimple() throws Exception {
jobInput.add("text 1 text 2");
Configuration conf = getDefaultRegexIngestMapperConfiguration();
conf.set(RegexIngestMapper.REGEX, "(\\w+)\\s+(\\d+)");
conf.set(RegexIngestMapper.GROUPS_TO_FIELDS, "0=body,1=text,2=number");
Job job = createJobBasedOnConfiguration(conf, RegexIngestMapper.class);
List<String> results = runJobSuccessfully(job, jobInput, 1);
assertNumDocsProcessed(job, 1);
assertNotNull("document is null", results.get(0));
}
@Test
public void testBad() throws Exception {
Configuration conf = getDefaultRegexIngestMapperConfiguration();
conf.unset(RegexIngestMapper.REGEX);
assertMapperConfigurationFailsWithMessage(conf, "com.lucidworks.hadoop.ingest.RegexIngestMapper.regex property must not be null or empty");
conf.set(RegexIngestMapper.REGEX, "");
assertMapperConfigurationFailsWithMessage(conf, "com.lucidworks.hadoop.ingest.RegexIngestMapper.regex property must not be null or empty");
conf.set(RegexIngestMapper.REGEX, "\\w+");// good regex, bad group mapping
conf.set(RegexIngestMapper.GROUPS_TO_FIELDS, "");
assertMapperConfigurationFailsWithMessage(conf, "com.lucidworks.hadoop.ingest.RegexIngestMapper.groups_to_fields property must not be null or empty");
conf.set(RegexIngestMapper.REGEX, "\\w+");// good regex, bad group mapping
conf.set(RegexIngestMapper.GROUPS_TO_FIELDS, "0");
assertMapperConfigurationFailsWithMessage(conf, "Malformed com.lucidworks.hadoop.ingest.RegexIngestMapper.groups_to_fields");
conf.set(RegexIngestMapper.GROUPS_TO_FIELDS, "0=foo,1");
assertMapperConfigurationFailsWithMessage(conf, "Malformed com.lucidworks.hadoop.ingest.RegexIngestMapper.groups_to_fields");
RegexIngestMapper mapper = new RegexIngestMapper();
LWDocument[] docs = mapper.toDocuments(null, null, null, null);
Assert.assertNull(docs);
}
@Test
public void testPathField() throws Exception {
jobInput.add("text 1 text 2");
Configuration conf = getDefaultRegexIngestMapperConfiguration();
conf.set(RegexIngestMapper.REGEX, "\\w+");
conf.set(RegexIngestMapper.GROUPS_TO_FIELDS, "0=body");
useAlternativeInputPath("testing/data/altInput");
Job job = createJobBasedOnConfiguration(conf, RegexIngestMapper.class);
List<String> results = runJobSuccessfully(job, jobInput, 1);
assertNumDocsProcessed(job, 1);
assertNotNull("document is null", results.get(0));
}
private void loadFrankensteinDataFromSequenceFile(Configuration conf) throws Exception {
final String sequenceFilePathSubstring = "sequence" + File.separator + "frankenstein_text_text.seq";
final URI fullSeqFileUri = RegexIngestMapperTest.class.getClassLoader().getResource(sequenceFilePathSubstring).toURI();
Path seqFilePath = new Path(fullSeqFileUri);
SequenceFileIterator<Text, Text> iterator = new SequenceFileIterator<Text, Text>(seqFilePath, true, conf);
Set<String> ids = new HashSet<String>();
while (iterator.hasNext()) {
Pair<Text, Text> pair = iterator.next();
jobInput.add(pair.getSecond().toString());
}
}
private Configuration getDefaultRegexIngestMapperConfiguration() {
Configuration conf = getBaseConfiguration();
conf.set(COLLECTION, "collection");
conf.set(ZK_CONNECT, "localhost:0000");
conf.set("idField", "id");
conf.set(RegexIngestMapper.REGEX, "\\w+");
conf.set(RegexIngestMapper.GROUPS_TO_FIELDS, "0=body");
return conf;
}
private void assertMapperConfigurationFailsWithMessage(Configuration conf, String expectedMessage) {
try {
new RegexIngestMapper().configure(new JobConf(conf));
Assert.fail();
} catch (RuntimeException e) {
Assert.assertTrue("Actual exception message ["+e.getMessage()+"] did not match expected message ["
+ expectedMessage+"].",
e.getMessage().startsWith(expectedMessage));
}
}
}
|
3e0ae6088516e21aa44531b8c8afbdc29822089a | 1,726 | java | Java | spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ActiveProfilesInterfaceTests.java | ZevGit/spring-framework | 9ca8681f79cad3a0c3c6ab1497575eaa9232441c | [
"Apache-2.0"
] | 442 | 2019-06-17T07:05:10.000Z | 2022-03-29T03:21:21.000Z | spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ActiveProfilesInterfaceTests.java | ZevGit/spring-framework | 9ca8681f79cad3a0c3c6ab1497575eaa9232441c | [
"Apache-2.0"
] | 4 | 2019-08-12T03:41:05.000Z | 2022-03-21T00:47:29.000Z | spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/ActiveProfilesInterfaceTests.java | ZevGit/spring-framework | 9ca8681f79cad3a0c3c6ab1497575eaa9232441c | [
"Apache-2.0"
] | 168 | 2019-06-24T05:06:12.000Z | 2022-03-30T05:54:15.000Z | 25.761194 | 82 | 0.761877 | 4,613 | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.configuration.interfaces;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.tests.sample.beans.Employee;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Sam Brannen
* @since 4.3
*/
@RunWith(SpringRunner.class)
public class ActiveProfilesInterfaceTests implements ActiveProfilesTestInterface {
@Autowired
Employee employee;
@Test
public void profileFromTestInterface() {
assertNotNull(employee);
assertEquals("dev", employee.getName());
}
@Configuration
static class Config {
@Bean
@Profile("dev")
Employee employee1() {
return new Employee("dev");
}
@Bean
@Profile("prod")
Employee employee2() {
return new Employee("prod");
}
}
}
|
3e0ae7290dfeaf18b8e75dd6f67d3d82a30854da | 471 | java | Java | warship-core/src/main/java/com/hy/zhan/warship/core/exception/WarshipExceptionHandlerSelector.java | hyzhan43/spring-boot-warship | 88ea864080a9cd193d07560dda7c7ed77940444f | [
"Apache-2.0"
] | null | null | null | warship-core/src/main/java/com/hy/zhan/warship/core/exception/WarshipExceptionHandlerSelector.java | hyzhan43/spring-boot-warship | 88ea864080a9cd193d07560dda7c7ed77940444f | [
"Apache-2.0"
] | null | null | null | warship-core/src/main/java/com/hy/zhan/warship/core/exception/WarshipExceptionHandlerSelector.java | hyzhan43/spring-boot-warship | 88ea864080a9cd193d07560dda7c7ed77940444f | [
"Apache-2.0"
] | null | null | null | 26.166667 | 74 | 0.762208 | 4,614 | package com.hy.zhan.warship.core.exception;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
/**
* author: HyJame
* date: 2020/5/3
* desc: 异常处理选择器
*/
public class WarshipExceptionHandlerSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{WarshipExceptionHandler.class.getName()};
}
}
|
3e0ae8bb69263f0e955e1d6d6cf76e3b23a1afb1 | 951 | java | Java | framework/src/main/java/com/suredy/formbuilder/eav/model/FormEntry.java | ynbz/framework | 65effc284952e9f8ab99bfffb627d7e0d10cd79f | [
"MIT"
] | null | null | null | framework/src/main/java/com/suredy/formbuilder/eav/model/FormEntry.java | ynbz/framework | 65effc284952e9f8ab99bfffb627d7e0d10cd79f | [
"MIT"
] | null | null | null | framework/src/main/java/com/suredy/formbuilder/eav/model/FormEntry.java | ynbz/framework | 65effc284952e9f8ab99bfffb627d7e0d10cd79f | [
"MIT"
] | null | null | null | 22.642857 | 67 | 0.774974 | 4,615 | package com.suredy.formbuilder.eav.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.suredy.eav.model.EAVEntry;
import com.suredy.formbuilder.design.model.FormDefine;
/**
* 表单实体
*
* @author VIVID.G
* @since 2017-3-1
* @version v0.1
*/
@Entity
@Table(name = "tb_form_entry")
public class FormEntry extends EAVEntry<FormAttributeValue> {
private static final long serialVersionUID = 1L;
/* 对应的表单定义对象 */
@JsonIgnore
@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinColumn(name = "form_define_id")
private FormDefine formDefine;
public FormDefine getFormDefine() {
return formDefine;
}
public void setFormDefine(FormDefine formDefine) {
this.formDefine = formDefine;
}
}
|
3e0ae95046b55ce0b803f54e9dafde85095f3947 | 3,584 | java | Java | src/game/stages/pregame/VideoOptionsMenu.java | XBigTK13X/Munchoid | 218be08ced7b7af23767a4f711055654b4c6f507 | [
"MIT"
] | null | null | null | src/game/stages/pregame/VideoOptionsMenu.java | XBigTK13X/Munchoid | 218be08ced7b7af23767a4f711055654b4c6f507 | [
"MIT"
] | 16 | 2016-06-27T02:19:56.000Z | 2017-05-10T07:11:39.000Z | src/game/stages/pregame/VideoOptionsMenu.java | XBigTK13X/Munchoid | 218be08ced7b7af23767a4f711055654b4c6f507 | [
"MIT"
] | null | null | null | 30.632479 | 107 | 0.570313 | 4,616 | package game.stages.pregame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import game.app.core.SettingsDetector;
import game.app.save.Options;
import sps.bridge.Commands;
import sps.display.Screen;
import sps.entities.HitTest;
import sps.states.StateManager;
import sps.text.TextPool;
import sps.ui.ButtonStyle;
import sps.ui.Tooltips;
import sps.ui.UIButton;
import sps.ui.UISlider;
public class VideoOptionsMenu extends OptionsState {
private UISlider _brightness;
public VideoOptionsMenu(Sprite background) {
super(background);
}
@Override
public void create() {
final UIButton back = new UIButton("Back", Commands.get("Menu6")) {
@Override
public void click() {
StateManager.get().pop();
}
};
final UIButton settingsDetection = new UIButton("Detect Optimal Settings", Commands.get("Menu3")) {
@Override
public void click() {
StateManager.reset().push(new SettingsDetector());
}
};
final UIButton fullScreen = new UIButton("Toggle Full Screen", Commands.get("Menu2")) {
@Override
public void click() {
Options.get().FullScreen = !Gdx.graphics.isFullscreen();
Options.get().save();
Options.get().apply();
}
};
final UIButton graphicsMode = new UIButton(qualityMessage(Options.get()), Commands.get("Menu1")) {
@Override
public void click() {
Options.get().GraphicsLowQuality = !Options.get().GraphicsLowQuality;
Options.get().save();
Options.get().apply();
setMessage(qualityMessage(Options.get()));
layout();
}
};
ButtonStyle style = new ButtonStyle(10, 20, 80, 10, 10);
style.apply(back, 0, 0);
style.apply(graphicsMode, 0, 3);
style.apply(fullScreen, 0, 2);
style.apply(settingsDetection, 0, 1);
_brightness = new UISlider(80, 10, (int) Screen.width(10), (int) Screen.height(70)) {
@Override
public void onSlide() {
setBrightnessPercent(getSliderPercent(), true);
}
};
setBrightnessPercent(Options.get().Brightness, false);
final UIButton brightnessReset = new UIButton("") {
@Override
public void click() {
setBrightnessPercent(100, true);
}
};
TextPool.get().write("Brightness", Screen.pos(15, 77));
brightnessReset.setSize(5, 5);
brightnessReset.setScreenPercent(3, 73);
Tooltips.get().add(new Tooltips.User() {
@Override
public boolean isActive() {
return HitTest.mouseInside(brightnessReset.getSprite());
}
@Override
public String message() {
return "Reset brightness.";
}
});
}
private void setBrightnessPercent(int brightness, boolean persist) {
_brightness.setSliderPercent(brightness);
if (persist) {
Options.get().Brightness = brightness;
Options.get().apply();
Options.get().save();
}
}
private String qualityMessage(Options options) {
return "Graphics Mode: " + (options.GraphicsLowQuality ? "Fast" : "Pretty");
}
@Override
public void draw() {
super.draw();
_brightness.draw();
}
}
|
3e0ae9fa2ac85a4b7072914009c6bfb91fb9f5e8 | 6,331 | java | Java | src/main/java/edu/wisc/my/portlets/bookmarks/dao/file/FileSystemBookmarkStore.java | markmclaren/BookmarksPortlet | 388bfe3e296940045766119ae6fe44735e2d8a99 | [
"Apache-2.0"
] | 2 | 2015-08-20T02:54:51.000Z | 2020-09-20T09:29:11.000Z | src/main/java/edu/wisc/my/portlets/bookmarks/dao/file/FileSystemBookmarkStore.java | markmclaren/BookmarksPortlet | 388bfe3e296940045766119ae6fe44735e2d8a99 | [
"Apache-2.0"
] | 27 | 2015-01-07T15:09:23.000Z | 2021-01-21T14:43:18.000Z | src/main/java/edu/wisc/my/portlets/bookmarks/dao/file/FileSystemBookmarkStore.java | markmclaren/BookmarksPortlet | 388bfe3e296940045766119ae6fe44735e2d8a99 | [
"Apache-2.0"
] | 10 | 2015-03-04T19:51:33.000Z | 2019-06-21T21:08:04.000Z | 34.543478 | 141 | 0.638767 | 4,617 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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 edu.wisc.my.portlets.bookmarks.dao.file;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import edu.wisc.my.portlets.bookmarks.dao.BookmarkStore;
import edu.wisc.my.portlets.bookmarks.domain.BookmarkSet;
/**
* <p>FileSystemBookmarkStore class.</p>
*
* @author Eric Dalquist <a href="mailto:anpch@example.com@doit.wisc.edu</a>
* @version $Revision: 12150 $
*/
public class FileSystemBookmarkStore implements BookmarkStore {
protected final Log logger = LogFactory.getLog(this.getClass());
private String baseStorePath = null;
/**
* <p>Getter for the field <code>baseStorePath</code>.</p>
*
* @return Returns the baseStorePath.
*/
public String getBaseStorePath() {
return this.baseStorePath;
}
/**
* <p>Setter for the field <code>baseStorePath</code>.</p>
*
* @param baseStorePath The baseStorePath to set.
*/
public void setBaseStorePath(String baseStorePath) {
this.baseStorePath = baseStorePath;
}
/** {@inheritDoc} */
public BookmarkSet getBookmarkSet(String owner, String name) {
final File storeFile = this.getStoreFile(owner, name);
//Ok if the file doesn't exist, the user hasn't stored one yet.
if (!storeFile.exists()) {
return null;
}
try {
final FileInputStream fis = new FileInputStream(storeFile);
final BufferedInputStream bis = new BufferedInputStream(fis);
final XMLDecoder d = new XMLDecoder(bis);
try {
final BookmarkSet bs = (BookmarkSet)d.readObject();
return bs;
}
finally {
d.close();
}
}
catch (FileNotFoundException fnfe) {
final String errorMsg = "Error reading BookmarkSet for owner='" + owner + "', name='" + name + "' from file='" + storeFile + "'";
logger.error(errorMsg, fnfe);
throw new DataAccessResourceFailureException(errorMsg);
}
}
/** {@inheritDoc} */
public void storeBookmarkSet(BookmarkSet bookmarkSet) {
if (bookmarkSet == null) {
throw new IllegalArgumentException("AddressBook may not be null");
}
final File storeFile = this.getStoreFile(bookmarkSet.getOwner(), bookmarkSet.getName());
try {
final FileOutputStream fos = new FileOutputStream(storeFile);
final BufferedOutputStream bos = new BufferedOutputStream(fos);
final XMLEncoder e = new XMLEncoder(bos);
try {
e.writeObject(bookmarkSet);
}
finally {
e.close();
}
}
catch (FileNotFoundException fnfe) {
final String errorMsg = "Error storing BookmarkSet='" + bookmarkSet + "' to file='" + storeFile + "'";
logger.error(errorMsg, fnfe);
throw new DataAccessResourceFailureException(errorMsg, fnfe);
}
}
/** {@inheritDoc} */
public void removeBookmarkSet(String owner, String name) {
final File storeFile = this.getStoreFile(owner, name);
storeFile.delete();
}
/** {@inheritDoc} */
public BookmarkSet createBookmarkSet(String owner, String name) {
final BookmarkSet bookmarkSet = new BookmarkSet();
bookmarkSet.setOwner(owner);
bookmarkSet.setName(name);
bookmarkSet.setCreated(new Date());
bookmarkSet.setModified(bookmarkSet.getCreated());
this.storeBookmarkSet(bookmarkSet);
return bookmarkSet;
}
/**
* Generates the file name String for an owner and book name.
*
* @param owner The owner of the bookmark set.
* @param name The name of the bookmark set.
* @return The file name for the owner and name.
*/
protected String getStoreFileName(String owner, String name) {
final StringBuilder fileNameBuff = new StringBuilder();
fileNameBuff.append(owner != null ? "_" + owner : "null");
fileNameBuff.append("_");
fileNameBuff.append(name != null ? "_" + name : "null");
fileNameBuff.append(".bms.xml");
return fileNameBuff.toString();
}
/**
* Generates the {@link java.io.File} object to use for storing, retrieving
* and deleting the bookmark set.
*
* @param owner The owner of the bookmark set.
* @param name The name of the bookmark set.
* @return The File for the owner and name.
*/
protected File getStoreFile(String owner, String name) {
final String fileStoreName = this.getStoreFileName(owner, name);
final File basePath = this.getStoreDirectory();
final File storeFile = new File(basePath, fileStoreName);
return storeFile;
}
/**
* <p>getStoreDirectory.</p>
*
* @return The directory to store AddressBooks in.
*/
protected File getStoreDirectory() {
return (this.baseStorePath == null ? new File(".") : new File(this.baseStorePath));
}
}
|
3e0aebf080c0756e0110a345c44b062f42e42b0f | 3,967 | java | Java | src/main/java/com/linecorp/armeria/server/docs/Specification.java | bazzani/armeria | 138109d39fc336358e125c74e9f70d99b771848b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/linecorp/armeria/server/docs/Specification.java | bazzani/armeria | 138109d39fc336358e125c74e9f70d99b771848b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/linecorp/armeria/server/docs/Specification.java | bazzani/armeria | 138109d39fc336358e125c74e9f70d99b771848b | [
"Apache-2.0"
] | 1 | 2020-08-19T22:47:36.000Z | 2020-08-19T22:47:36.000Z | 37.074766 | 109 | 0.634737 | 4,618 | /*
* Copyright 2015 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.server.docs;
import static java.util.Objects.requireNonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.thrift.TBase;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.linecorp.armeria.server.ServiceConfig;
import com.linecorp.armeria.server.thrift.ThriftService;
class Specification {
static Specification forServiceConfigs(Iterable<ServiceConfig> serviceConfigs,
Map<Class<?>, ? extends TBase<?, ?>> sampleRequests) {
final Map<Class<?>, Iterable<EndpointInfo>> map = new LinkedHashMap<>();
for (ServiceConfig c : serviceConfigs) {
c.service().as(ThriftService.class).ifPresent(service -> {
for (Class<?> iface : service.interfaces()) {
final Class<?> serviceClass = iface.getEnclosingClass();
final List<EndpointInfo> endpoints =
(List<EndpointInfo>) map.computeIfAbsent(serviceClass, cls -> new ArrayList<>());
c.pathMapping().exactPath().ifPresent(
p -> endpoints.add(EndpointInfo.of(
c.virtualHost().hostnamePattern(),
p, service.defaultSerializationFormat(),
service.allowedSerializationFormats())));
}
});
}
return forServiceClasses(map, sampleRequests);
}
static Specification forServiceClasses(Map<Class<?>, Iterable<EndpointInfo>> map,
Map<Class<?>, ? extends TBase<?, ?>> sampleRequests) {
requireNonNull(map, "map");
final List<ServiceInfo> services = new ArrayList<>(map.size());
final Set<ClassInfo> classes = new HashSet<>();
map.forEach((serviceClass, endpoints) -> {
try {
final ServiceInfo service = ServiceInfo.of(serviceClass, endpoints, sampleRequests);
services.add(service);
classes.addAll(service.classes().values());
} catch (ClassNotFoundException e) {
throw new RuntimeException("unable to initialize Specification", e);
}
});
return new Specification(services, classes);
}
private final Map<String, ServiceInfo> services;
private final Map<String, ClassInfo> classes;
private Specification(Collection<ServiceInfo> services, Collection<ClassInfo> classes) {
final Map<String, ServiceInfo> serviceMap = new TreeMap<>();
final Map<String, ClassInfo> classMap = new TreeMap<>();
services.stream().forEach(s -> serviceMap.put(s.name(), s));
classes.stream().forEach(c -> classMap.put(c.name(), c));
this.services = Collections.unmodifiableMap(serviceMap);
this.classes = Collections.unmodifiableMap(classMap);
}
@JsonProperty
public Map<String, ServiceInfo> services() {
return services;
}
@JsonProperty
public Map<String, ClassInfo> classes() {
return classes;
}
}
|
3e0aed0309f6031dde9612718d012443b30d2303 | 5,638 | java | Java | flea-frame-db/src/test/java/com/huazie/frame/db/common/sql/SqlTemplateConfigTest.java | Huazie/flea-frame | cffc890ac55a6fc80b9f90dc4df04b17e59e08a6 | [
"BSD-3-Clause"
] | 10 | 2019-06-17T15:41:34.000Z | 2021-09-02T01:51:19.000Z | flea-frame-db/src/test/java/com/huazie/frame/db/common/sql/SqlTemplateConfigTest.java | Huazie/flea-frame | cffc890ac55a6fc80b9f90dc4df04b17e59e08a6 | [
"BSD-3-Clause"
] | 24 | 2019-11-10T14:49:54.000Z | 2021-07-28T07:15:08.000Z | flea-frame-db/src/test/java/com/huazie/frame/db/common/sql/SqlTemplateConfigTest.java | Huazie/flea-frame | cffc890ac55a6fc80b9f90dc4df04b17e59e08a6 | [
"BSD-3-Clause"
] | 1 | 2021-01-19T03:26:12.000Z | 2021-01-19T03:26:12.000Z | 35.683544 | 148 | 0.623448 | 4,619 | package com.huazie.frame.db.common.sql;
import com.huazie.frame.common.slf4j.FleaLogger;
import com.huazie.frame.common.slf4j.impl.FleaLoggerProxy;
import com.huazie.frame.common.util.PatternMatcherUtils;
import com.huazie.frame.db.common.sql.template.SqlTemplateEnum;
import com.huazie.frame.db.common.sql.template.config.Property;
import com.huazie.frame.db.common.sql.template.config.Rule;
import com.huazie.frame.db.common.sql.template.config.SqlTemplateConfig;
import org.junit.Test;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p> SQL模板配置自测 </p>
*
* @author huazie
* @version 1.0.0
* @since 1.0.0
*/
public class SqlTemplateConfigTest {
private static final FleaLogger LOGGER = FleaLoggerProxy.getProxyInstance(SqlTemplateConfigTest.class);
@Test
public void testSqlTemplate() {
LOGGER.debug(SqlTemplateConfig.getConfig().getSql().toString());
LOGGER.debug(SqlTemplateConfig.getConfig().getSql().getTemplates().toString());
LOGGER.debug(SqlTemplateConfig.getConfig().getSql().getParams().toString());
LOGGER.debug(SqlTemplateConfig.getConfig().getSql().getRelations().toString());
}
@Test
public void testRules() {
LOGGER.debug(SqlTemplateConfig.getConfig().getRule("insert").toString());
LOGGER.debug(SqlTemplateConfig.getConfig().getRule("update").toString());
LOGGER.debug(SqlTemplateConfig.getConfig().getRule("delete").toString());
LOGGER.debug(SqlTemplateConfig.getConfig().getRule("select").toString());
}
@Test
public void testInsertTemplateRule() {
// String template = " INSERT INTO ##table## ( ##columns## ) VALUES ( ##values## )";
String template = " Insert into ##table## ( ##columns## ) values ( ##values## )";
LOGGER.debug("======INSERT规则校验开始======");
Rule rule = SqlTemplateConfig.getConfig().getRule("insert");
Map<String, Property> propMap = rule.toPropMap();// 获取其属性值
Property prop = propMap.get(SqlTemplateEnum.SQL.getKey());// 获取指定的校验规则配置
String regExp = prop.getValue();
Pattern p = Pattern.compile(regExp, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(template);
if (matcher.matches()) {// SQL模板满足校验规则配置
LOGGER.debug("INSERT规则校验通过");
} else {
LOGGER.debug("INSERT规则校验失败");
}
LOGGER.debug("======INSERT规则校验结束======");
}
@Test
public void testUpdateTemplateRule() {
// String template = " UPDATE ##table## SET ##sets## WHERE ##conditions## ";
String template = " update ##table## set ##sets## where ##conditions## ";
LOGGER.debug("======UPDATE规则校验开始======");
Rule rule = SqlTemplateConfig.getConfig().getRule("update");
Map<String, Property> propMap = rule.toPropMap();// 获取其属性值
Property prop = propMap.get(SqlTemplateEnum.SQL.getKey());// 获取指定的校验规则配置
String regExp = prop.getValue();
Pattern p = Pattern.compile(regExp, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(template);
if (matcher.matches()) {// SQL模板满足校验规则配置
LOGGER.debug("UPDATE规则校验通过");
} else {
LOGGER.debug("UPDATE规则校验失败");
}
LOGGER.debug("======UPDATE规则校验结束======");
}
@Test
public void testSelectTemplateRule() {
// String template = " SELECT ##columns## FROM ##table## WHERE ##conditions## ";
String template = " select ##columns## from ##table## where ##conditions## ";
LOGGER.debug("======SELECT规则校验开始======");
Rule rule = SqlTemplateConfig.getConfig().getRule("select");
Map<String, Property> propMap = rule.toPropMap();// 获取其属性值
Property prop = propMap.get(SqlTemplateEnum.SQL.getKey());// 获取指定的校验规则配置
String regExp = prop.getValue();
Pattern p = Pattern.compile(regExp, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(template);
if (matcher.matches()) {// SQL模板满足校验规则配置
LOGGER.debug("SELECT规则校验通过");
} else {
LOGGER.debug("SELECT规则校验失败");
}
LOGGER.debug("======SELECT规则校验结束======");
}
@Test
public void testDeleteTemplateRule() {
String template = " DELETE FROM ##table## WHERE ##conditions## ";
// String template = " delete from ##table## where ##conditions## ";
LOGGER.debug("======DELETE规则校验开始======");
Rule rule = SqlTemplateConfig.getConfig().getRule("delete");
Map<String, Property> propMap = rule.toPropMap();// 获取其属性值
Property prop = propMap.get(SqlTemplateEnum.SQL.getKey());// 获取指定的校验规则配置
String regExp = prop.getValue();
Pattern p = Pattern.compile(regExp, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(template);
if (matcher.matches()) {// SQL模板满足校验规则配置
LOGGER.debug("DELETE规则校验通过");
} else {
LOGGER.debug("DELETE规则校验失败");
}
LOGGER.debug("======DELETE规则校验结束======");
}
@Test
public void testPattern() throws Exception {
String regExp = "AVG\\([([\\s\\S]*)]*\\)|COUNT\\([([\\s\\S]*)]*\\)|SUM\\([([\\s\\S]*)]*\\)|MAX\\([([\\s\\S]*)]*\\)|MIN\\([([\\s\\S]*)]*\\)";
String input = "avg(stu_id)";
LOGGER.debug("RESULT = {}", PatternMatcherUtils.matches(regExp, input, Pattern.CASE_INSENSITIVE));
}
@Test
public void testPattern1() throws Exception {
String regExp = "[ ]*1[ ]*=[ ]*1[ ]*";
String input = " 1= 1 ";
LOGGER.debug("RESULT = {}", PatternMatcherUtils.matches(regExp, input, Pattern.CASE_INSENSITIVE));
}
}
|
3e0aed55c31d45cad9516dfe58e070ec23bc0e55 | 2,891 | java | Java | server/src/main/java/com/lickhunter/web/services/impl/SentimentsServiceImpl.java | ebaloaloa/lick-hunter-web | 8cebc61e415a650e2fb131d5381a61c489441712 | [
"FTL"
] | 10 | 2021-03-29T13:35:28.000Z | 2022-01-22T18:22:11.000Z | server/src/main/java/com/lickhunter/web/services/impl/SentimentsServiceImpl.java | ebaloaloa/lick-hunter-web | 8cebc61e415a650e2fb131d5381a61c489441712 | [
"FTL"
] | 15 | 2021-04-27T06:22:43.000Z | 2022-01-23T07:32:56.000Z | server/src/main/java/com/lickhunter/web/services/impl/SentimentsServiceImpl.java | ebaloaloa/lick-hunter-web | 8cebc61e415a650e2fb131d5381a61c489441712 | [
"FTL"
] | 14 | 2021-05-08T04:51:53.000Z | 2022-02-05T23:19:47.000Z | 45.888889 | 143 | 0.723625 | 4,620 | package com.lickhunter.web.services.impl;
import com.lickhunter.web.configs.ApplicationConfig;
import com.lickhunter.web.models.sentiments.SentimentsAsset;
import com.lickhunter.web.repositories.SymbolRepository;
import com.lickhunter.web.services.SentimentsService;
import com.lickhunter.web.to.SentimentsTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service
@Slf4j
@RequiredArgsConstructor
public class SentimentsServiceImpl implements SentimentsService {
private final ApplicationConfig applicationConfig;
private final SymbolRepository symbolRepository;
@Value("${sentiments.key}")
private String key;
public SentimentsAsset getSentiments(SentimentsTO sentimentsTO) {
SentimentsAsset result = null;
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("user-agent", "PostmanRuntime/7.26.8");
HttpEntity<String> entity = new HttpEntity<>(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(applicationConfig.getSentimentsApi())
.queryParam("data", sentimentsTO.getEndpoint())
.queryParam("key", key)
.queryParam("symbol", sentimentsTO.getSymbol())
.queryParam("data_points", sentimentsTO.getDataPoints())
.queryParam("change", sentimentsTO.getChange())
.queryParam("interval", sentimentsTO.getInterval());
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
ResponseEntity<SentimentsAsset> res = restTemplate.exchange(builder.toUriString(), HttpMethod.GET , entity, SentimentsAsset.class);
symbolRepository.update(res.getBody());
result = res.getBody();
} catch (Exception e) {
log.warn(String.format("Failed to receive %s sentiments: %s", sentimentsTO.getSymbol(), e.getMessage()));
}
return result;
}
}
|
3e0aede198583dd815caf95ddb53c4d4158bcafa | 108 | java | Java | tech-stack/framework/spring-boot/reactive/src/main/java/com/atul/scaler/reactive/domain/enums/Status.java | atulanand206/scaler-learnings | 5365327568ab42949ebc5c20271b7bea7a26f2ff | [
"MIT"
] | null | null | null | tech-stack/framework/spring-boot/reactive/src/main/java/com/atul/scaler/reactive/domain/enums/Status.java | atulanand206/scaler-learnings | 5365327568ab42949ebc5c20271b7bea7a26f2ff | [
"MIT"
] | null | null | null | tech-stack/framework/spring-boot/reactive/src/main/java/com/atul/scaler/reactive/domain/enums/Status.java | atulanand206/scaler-learnings | 5365327568ab42949ebc5c20271b7bea7a26f2ff | [
"MIT"
] | null | null | null | 13.5 | 46 | 0.740741 | 4,621 | package com.atul.scaler.reactive.domain.enums;
public enum Status {
SUGGESTED,
APPROVED,
ARCHIVED;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.