repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
shaotao/Leetcode | algorithm/regular_expression_matching/IsMatch.java | 3237 | import java.io.*;
import java.util.*;
class IsMatch
{
public static void main(String[] args)
{
System.out.println("=== welcome to IsMatch! ===");
Solution solution = new Solution();
String s = "aaaaaaaaaaaaab";
String p = "a*a*a*a*a*a*a*a*a*a*c";
boolean match = solution.isMatch(s, p);
System.out.println("s = "+s);
System.out.println("p = "+p);
System.out.println("match = "+match);
}
}
class Solution
{
public Solution()
{
}
public String trim_p(String p)
{
// combine a*a*a* to a*
StringBuffer buf_p = new StringBuffer("");
for(int i = 0; i < p.length(); i++)
{
char ch = p.charAt(i);
int buf_size = buf_p.length();
if(ch == '*' && buf_size >= 3 &&
buf_p.charAt(buf_size-1) == buf_p.charAt(buf_size-3) &&
buf_p.charAt(buf_size-2) == '*')
{
buf_p.deleteCharAt(buf_size-1);
}
else
{
buf_p.append(ch);
}
}
return buf_p.toString();
}
boolean isMatch(String s, String p)
{
String p2 = trim_p(p);
return isMatch_recur(s, p2);
}
boolean isMatch_recur(String s, String p)
{
String next_s = "";
String next_p = "";
if(s.length() > 1)
{
next_s = s.substring(1);
}
if(p.length() > 1)
{
next_p = p.substring(1);
}
if(p.length() == 0)
{
if(s.length() == 0)
{
return true;
}
else
{
return false;
}
}
// ok, p length is not 0, we still have pattern to match
if(p.charAt(0) == '.')
{
// need to check if p[1] is *
if(p.length() > 1 && p.charAt(1) == '*')
{
// must check for 0 or n occurrance
next_p = "";
if(p.length() > 2)
{
next_p = p.substring(2);
}
boolean ret = isMatch(s, next_p);
if(ret == true)
{
return true;
}
int i = 0;
for(i = 0; i < s.length(); i++)
{
ret = isMatch(s.substring(i), next_p);
if(ret == true)
{
return true;
}
}
// if s is all matched ""
if(i == s.length())
{
ret = isMatch("", next_p);
if(ret == true)
{
return true;
}
}
return false;
}
else
{
// any character
if(s.length() == 0)
{
return false;
}
return isMatch(next_s, next_p);
}
}
else
{
// p[0] is normal character
// need to check if p[1] is *
if(p.length() > 1 && p.charAt(1) == '*')
{
// must check for 0 or n occurrance
next_p = "";
if(p.length() > 2)
{
next_p = p.substring(2);
}
// if s is ""
boolean ret = isMatch(s, next_p);
if(ret == true)
{
return true;
}
int i = 0;
for(i = 0; i < s.length(); i++)
{
ret = isMatch(s.substring(i), next_p);
if(ret == true)
{
return true;
}
if(s.charAt(i) != p.charAt(0))
{
break;
}
}
// if s is all matched ""
if(i == s.length())
{
ret = isMatch("", next_p);
if(ret == true)
{
return true;
}
}
return false;
}
else
{
// need an exact match of a chacter
if(s.length() == 0)
{
return false;
}
if(s.charAt(0) != p.charAt(0))
{
return false;
}
return isMatch(next_s, next_p);
}
}
// we should not get here
//return false;
}
}
| mit |
levibostian/wa2do | app/src/main/java/co/wa2do_app/wa2do/mock/MockEvents.java | 582 | package co.wa2do_app.wa2do.mock;
import co.wa2do_app.wa2do.InterestTypes;
import co.wa2do_app.wa2do.vo.EventVo;
import java.util.ArrayList;
public class MockEvents {
public static ArrayList<EventVo> getEvents() {
ArrayList<EventVo> events = new ArrayList<EventVo>();
events.add(new EventVo(InterestTypes.SPORTS, "Racketball", "Levi Bostian", "123 ABC St", "Miami", "FL", 3, 5, 32, 5, 32));
events.add(new EventVo(InterestTypes.ARTS, "Nickelback", "Trevor Carlson", "456 D St", "Chicago", "IL", 999, 1000, 5, 12, 3));
return events;
}
}
| mit |
tmarsteel/kotlin-prolog | jvm-playground/src/main/java/com/github/prologdb/runtime/playground/jvm/persistence/WindowState.java | 1416 | package com.github.prologdb.runtime.playground.jvm.persistence;
import com.fasterxml.jackson.annotation.JsonProperty;
public class WindowState
{
private Integer locationX;
private Integer locationY;
private Integer width;
private Integer height;
/**
* The graphics device last shown on (multi-monitor support)
*/
private String graphicsDeviceID;
@JsonProperty
public Integer getLocationX()
{
return locationX;
}
@JsonProperty
public void setLocationX(Integer locationX)
{
this.locationX = locationX;
}
@JsonProperty
public Integer getLocationY()
{
return locationY;
}
@JsonProperty
public void setLocationY(Integer locationY)
{
this.locationY = locationY;
}
@JsonProperty
public Integer getWidth()
{
return width;
}
@JsonProperty
public void setWidth(Integer width)
{
this.width = width;
}
@JsonProperty
public Integer getHeight()
{
return height;
}
@JsonProperty
public void setHeight(Integer height)
{
this.height = height;
}
@JsonProperty
public String getGraphicsDeviceID()
{
return graphicsDeviceID;
}
@JsonProperty
public void setGraphicsDeviceID(String graphicsDeviceID)
{
this.graphicsDeviceID = graphicsDeviceID;
}
}
| mit |
fpravica/fizzbuzz | src/main/java/com/prottone/fizzbuzz/Buzzers.java | 791 | package com.prottone.fizzbuzz;
public final class Buzzers {
/**
* Disabled instantiation
*/
private Buzzers() { }
/**
* Returns "Fizz" if index divisible by 3
*/
public static final Buzzer FIZZ = new Buzzer() {
public String execute(final int index) {
return (index % 3 == 0) ? toString() : "";
}
@Override
public String toString() {
return "Fizz";
}
};
/**
* Returns "Buzz" if index divisible by 5
*/
public static final Buzzer BUZZ = new Buzzer() {
public String execute(final int index) {
return (index % 5 == 0) ? toString() : "";
}
@Override
public String toString() {
return "Buzz";
}
};
}
| mit |
Reticality/Flow-of-Time | src/java/reticality/flowoftime/items/BasicItem.java | 314 | package reticality.flowoftime.items;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class BasicItem extends Item {
public BasicItem(String unlocalizedName) {
super();
this.setUnlocalizedName(unlocalizedName);
this.setCreativeTab(CreativeTabs.tabMaterials);
}
}
| mit |
dgonyeo/cshnews2 | CSH News 2/src/main/java/edu/rit/csh/cshnews2/NetworkStuff.java | 6208 | package edu.rit.csh.cshnews2;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
/**
* Created by derek on 12/23/13.
*/
public class NetworkStuff {
public static int returnStatus;
private static String apiKey;
private static CshNewsService mService;
public static void init(String api_key, CshNewsService service)
{
apiKey = api_key;
mService = service;
}
public static boolean isNetworkAvailable() {
if(mService == null)
return false;
ConnectivityManager connectivityManager
= (ConnectivityManager) mService.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static boolean isNetworkAvailable(Activity act) {
ConnectivityManager connectivityManager
= (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
//Makes a get request to page with no additional parameters
public static String makeGetRequest(String page)
{
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
return makeGetRequest(page, params);
}
//Makes a get request to page with the specified additional parameters
public static String makeGetRequest(String page, ArrayList<NameValuePair> params)
{
params.add(new BasicNameValuePair("api_key", apiKey));
params.add(new BasicNameValuePair("api_agent", "Android_Webnews"));
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
URI target = URIUtils.createURI("https", "webnews.csh.rit.edu", -1, "/" + page,
URLEncodedUtils.format(params, "UTF-8"), null);
HttpGet request = new HttpGet(target);
request.addHeader("Accept", "application/json");
response = client.execute(request);
if(response.getStatusLine().getStatusCode() != 200)
Log.d("Hi", "Status: " + response.getStatusLine().getStatusCode());
// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
returnStatus = response.getStatusLine().getStatusCode();
return sb.toString();
} catch (IOException e) {
if(response != null && response.getStatusLine() != null)
returnStatus = response.getStatusLine().getStatusCode();
Log.e("Hi", "IOException on the get request to " + page);
params.remove(params.size() - 1);
params.remove(params.size() - 1);
if(isNetworkAvailable())
return makeGetRequest(page, params);
} catch (URISyntaxException e) {
if(response != null && response.getStatusLine() != null)
returnStatus = response.getStatusLine().getStatusCode();
Log.e("Hi", "URISyntaxException on the get request to " + page);
return null;
}
return null;
}
//Makes a get request to page with the specified additional parameters
public static String makePutRequest(String page, ArrayList<NameValuePair> params)
{
params.add(new BasicNameValuePair("api_key", apiKey));
params.add(new BasicNameValuePair("api_agent", "Android_Webnews"));
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
URI target = URIUtils.createURI("https", "webnews.csh.rit.edu", -1, "/" + page,
URLEncodedUtils.format(params, "UTF-8"), null);
HttpPut request = new HttpPut(target);
request.addHeader("Accept", "application/json");
response = client.execute(request);
if(response.getStatusLine().getStatusCode() != 200)
Log.d("Hi", "Status: " + response.getStatusLine().getStatusCode());
// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
returnStatus = response.getStatusLine().getStatusCode();
return sb.toString();
} catch (IOException e) {
if(response != null && response.getStatusLine() != null)
returnStatus = response.getStatusLine().getStatusCode();
Log.e("Hi", "IOException on the get request to " + page);
return "Error!";
} catch (URISyntaxException e) {
if(response != null && response.getStatusLine() != null)
returnStatus = response.getStatusLine().getStatusCode();
Log.e("Hi", "URISyntaxException on the get request to " + page);
return "Error!";
}
}
}
| mit |
andrzejtrzaska/rsi2-ps2 | CalculatorApp/src/java/org/rsi2/calculator/util/SleepUtil.java | 532 | package org.rsi2.calculator.util;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* SleepUtil
*/
public class SleepUtil {
/**
* randomSleep
*/
public static void randomSleep() {
Random random = new Random();
int delay = (random.nextInt(8) + 3) * 1000;
try {
Thread.sleep(delay);
} catch (InterruptedException ex) {
Logger.getLogger(SleepUtil.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| mit |
ValQuev/TEC | mobile/src/main/java/fr/valquev/tec/Utils.java | 293 | package fr.valquev.tec;
import java.text.Normalizer;
public class Utils {
public static String stringNormalizer(String string) {
string = Normalizer.normalize(string, Normalizer.Form.NFD);
string = string.replaceAll("[^\\p{ASCII}]", "");
return string;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/implementation/BastionHostsInner.java | 53514 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_11_01.implementation;
import com.microsoft.azure.arm.collection.InnerSupportsGet;
import com.microsoft.azure.arm.collection.InnerSupportsDelete;
import com.microsoft.azure.arm.collection.InnerSupportsListing;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.Path;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in BastionHosts.
*/
public class BastionHostsInner implements InnerSupportsGet<BastionHostInner>, InnerSupportsDelete<Void>, InnerSupportsListing<BastionHostInner> {
/** The Retrofit service to perform REST calls. */
private BastionHostsService service;
/** The service client containing this operation class. */
private NetworkManagementClientImpl client;
/**
* Initializes an instance of BastionHostsInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public BastionHostsInner(Retrofit retrofit, NetworkManagementClientImpl client) {
this.service = retrofit.create(BastionHostsService.class);
this.client = client;
}
/**
* The interface defining all the services for BastionHosts to be
* used by Retrofit to perform actually REST calls.
*/
interface BastionHostsService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts delete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("bastionHostName") String bastionHostName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts beginDelete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> beginDelete(@Path("resourceGroupName") String resourceGroupName, @Path("bastionHostName") String bastionHostName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts getByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}")
Observable<Response<ResponseBody>> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("bastionHostName") String bastionHostName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts createOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}")
Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("bastionHostName") String bastionHostName, @Path("subscriptionId") String subscriptionId, @Body BastionHostInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts beginCreateOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts/{bastionHostName}")
Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("bastionHostName") String bastionHostName, @Path("subscriptionId") String subscriptionId, @Body BastionHostInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts list" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Network/bastionHosts")
Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts listByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/bastionHosts")
Observable<Response<ResponseBody>> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts listNext" })
@GET
Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.BastionHosts listByResourceGroupNext" })
@GET
Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void delete(String resourceGroupName, String bastionHostName) {
deleteWithServiceResponseAsync(resourceGroupName, bastionHostName).toBlocking().last().body();
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> deleteAsync(String resourceGroupName, String bastionHostName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, bastionHostName), serviceCallback);
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<Void> deleteAsync(String resourceGroupName, String bastionHostName) {
return deleteWithServiceResponseAsync(resourceGroupName, bastionHostName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String bastionHostName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (bastionHostName == null) {
throw new IllegalArgumentException("Parameter bastionHostName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
Observable<Response<ResponseBody>> observable = service.delete(resourceGroupName, bastionHostName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void beginDelete(String resourceGroupName, String bastionHostName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, bastionHostName).toBlocking().single().body();
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String bastionHostName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, bastionHostName), serviceCallback);
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<Void> beginDeleteAsync(String resourceGroupName, String bastionHostName) {
return beginDeleteWithServiceResponseAsync(resourceGroupName, bastionHostName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String bastionHostName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (bastionHostName == null) {
throw new IllegalArgumentException("Parameter bastionHostName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.beginDelete(resourceGroupName, bastionHostName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.register(204, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the BastionHostInner object if successful.
*/
public BastionHostInner getByResourceGroup(String resourceGroupName, String bastionHostName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, bastionHostName).toBlocking().single().body();
}
/**
* Gets the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<BastionHostInner> getByResourceGroupAsync(String resourceGroupName, String bastionHostName, final ServiceCallback<BastionHostInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, bastionHostName), serviceCallback);
}
/**
* Gets the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the BastionHostInner object
*/
public Observable<BastionHostInner> getByResourceGroupAsync(String resourceGroupName, String bastionHostName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, bastionHostName).map(new Func1<ServiceResponse<BastionHostInner>, BastionHostInner>() {
@Override
public BastionHostInner call(ServiceResponse<BastionHostInner> response) {
return response.body();
}
});
}
/**
* Gets the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the BastionHostInner object
*/
public Observable<ServiceResponse<BastionHostInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String bastionHostName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (bastionHostName == null) {
throw new IllegalArgumentException("Parameter bastionHostName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.getByResourceGroup(resourceGroupName, bastionHostName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<BastionHostInner>>>() {
@Override
public Observable<ServiceResponse<BastionHostInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<BastionHostInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<BastionHostInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<BastionHostInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<BastionHostInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the BastionHostInner object if successful.
*/
public BastionHostInner createOrUpdate(String resourceGroupName, String bastionHostName, BastionHostInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, bastionHostName, parameters).toBlocking().last().body();
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<BastionHostInner> createOrUpdateAsync(String resourceGroupName, String bastionHostName, BastionHostInner parameters, final ServiceCallback<BastionHostInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, bastionHostName, parameters), serviceCallback);
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<BastionHostInner> createOrUpdateAsync(String resourceGroupName, String bastionHostName, BastionHostInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, bastionHostName, parameters).map(new Func1<ServiceResponse<BastionHostInner>, BastionHostInner>() {
@Override
public BastionHostInner call(ServiceResponse<BastionHostInner> response) {
return response.body();
}
});
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<BastionHostInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String bastionHostName, BastionHostInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (bastionHostName == null) {
throw new IllegalArgumentException("Parameter bastionHostName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-11-01";
Observable<Response<ResponseBody>> observable = service.createOrUpdate(resourceGroupName, bastionHostName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<BastionHostInner>() { }.getType());
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the BastionHostInner object if successful.
*/
public BastionHostInner beginCreateOrUpdate(String resourceGroupName, String bastionHostName, BastionHostInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, bastionHostName, parameters).toBlocking().single().body();
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<BastionHostInner> beginCreateOrUpdateAsync(String resourceGroupName, String bastionHostName, BastionHostInner parameters, final ServiceCallback<BastionHostInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, bastionHostName, parameters), serviceCallback);
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the BastionHostInner object
*/
public Observable<BastionHostInner> beginCreateOrUpdateAsync(String resourceGroupName, String bastionHostName, BastionHostInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, bastionHostName, parameters).map(new Func1<ServiceResponse<BastionHostInner>, BastionHostInner>() {
@Override
public BastionHostInner call(ServiceResponse<BastionHostInner> response) {
return response.body();
}
});
}
/**
* Creates or updates the specified Bastion Host.
*
* @param resourceGroupName The name of the resource group.
* @param bastionHostName The name of the Bastion Host.
* @param parameters Parameters supplied to the create or update Bastion Host operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the BastionHostInner object
*/
public Observable<ServiceResponse<BastionHostInner>> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String bastionHostName, BastionHostInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (bastionHostName == null) {
throw new IllegalArgumentException("Parameter bastionHostName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-11-01";
return service.beginCreateOrUpdate(resourceGroupName, bastionHostName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<BastionHostInner>>>() {
@Override
public Observable<ServiceResponse<BastionHostInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<BastionHostInner> clientResponse = beginCreateOrUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<BastionHostInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<BastionHostInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<BastionHostInner>() { }.getType())
.register(201, new TypeToken<BastionHostInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<BastionHostInner> object if successful.
*/
public PagedList<BastionHostInner> list() {
ServiceResponse<Page<BastionHostInner>> response = listSinglePageAsync().toBlocking().single();
return new PagedList<BastionHostInner>(response.body()) {
@Override
public Page<BastionHostInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<BastionHostInner>> listAsync(final ListOperationCallback<BastionHostInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listSinglePageAsync(),
new Func1<String, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<Page<BastionHostInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<BastionHostInner>>, Page<BastionHostInner>>() {
@Override
public Page<BastionHostInner> call(ServiceResponse<Page<BastionHostInner>> response) {
return response.body();
}
});
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listWithServiceResponseAsync() {
return listSinglePageAsync()
.concatMap(new Func1<ServiceResponse<Page<BastionHostInner>>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(ServiceResponse<Page<BastionHostInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<BastionHostInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listSinglePageAsync() {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.list(this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<BastionHostInner>> result = listDelegate(response);
return Observable.just(new ServiceResponse<Page<BastionHostInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<BastionHostInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<BastionHostInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<BastionHostInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<BastionHostInner> object if successful.
*/
public PagedList<BastionHostInner> listByResourceGroup(final String resourceGroupName) {
ServiceResponse<Page<BastionHostInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single();
return new PagedList<BastionHostInner>(response.body()) {
@Override
public Page<BastionHostInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<BastionHostInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<BastionHostInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupSinglePageAsync(resourceGroupName),
new Func1<String, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<Page<BastionHostInner>> listByResourceGroupAsync(final String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
.map(new Func1<ServiceResponse<Page<BastionHostInner>>, Page<BastionHostInner>>() {
@Override
public Page<BastionHostInner> call(ServiceResponse<Page<BastionHostInner>> response) {
return response.body();
}
});
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) {
return listByResourceGroupSinglePageAsync(resourceGroupName)
.concatMap(new Func1<ServiceResponse<Page<BastionHostInner>>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(ServiceResponse<Page<BastionHostInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all Bastion Hosts in a resource group.
*
ServiceResponse<PageImpl<BastionHostInner>> * @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<BastionHostInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<BastionHostInner>> result = listByResourceGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<BastionHostInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<BastionHostInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<BastionHostInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<BastionHostInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<BastionHostInner> object if successful.
*/
public PagedList<BastionHostInner> listNext(final String nextPageLink) {
ServiceResponse<Page<BastionHostInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<BastionHostInner>(response.body()) {
@Override
public Page<BastionHostInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<BastionHostInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<BastionHostInner>> serviceFuture, final ListOperationCallback<BastionHostInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<Page<BastionHostInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<BastionHostInner>>, Page<BastionHostInner>>() {
@Override
public Page<BastionHostInner> call(ServiceResponse<Page<BastionHostInner>> response) {
return response.body();
}
});
}
/**
* Lists all Bastion Hosts in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
return listNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<BastionHostInner>>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(ServiceResponse<Page<BastionHostInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all Bastion Hosts in a subscription.
*
ServiceResponse<PageImpl<BastionHostInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<BastionHostInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<BastionHostInner>> result = listNextDelegate(response);
return Observable.just(new ServiceResponse<Page<BastionHostInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<BastionHostInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<BastionHostInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<BastionHostInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<BastionHostInner> object if successful.
*/
public PagedList<BastionHostInner> listByResourceGroupNext(final String nextPageLink) {
ServiceResponse<Page<BastionHostInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<BastionHostInner>(response.body()) {
@Override
public Page<BastionHostInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<BastionHostInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<BastionHostInner>> serviceFuture, final ListOperationCallback<BastionHostInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<Page<BastionHostInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<BastionHostInner>>, Page<BastionHostInner>>() {
@Override
public Page<BastionHostInner> call(ServiceResponse<Page<BastionHostInner>> response) {
return response.body();
}
});
}
/**
* Lists all Bastion Hosts in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<BastionHostInner> object
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<BastionHostInner>>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(ServiceResponse<Page<BastionHostInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all Bastion Hosts in a resource group.
*
ServiceResponse<PageImpl<BastionHostInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<BastionHostInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<BastionHostInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BastionHostInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BastionHostInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<BastionHostInner>> result = listByResourceGroupNextDelegate(response);
return Observable.just(new ServiceResponse<Page<BastionHostInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<BastionHostInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<BastionHostInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<BastionHostInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
kylebalnave/selenium | interpreter/src/common/io/ResourceReader.java | 1131 | package common.io;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
*
* @author balnave
*/
public class ResourceReader extends StringReader {
public ResourceReader(String fileOrUrl) {
super(fileOrUrl);
}
@Override
public String load() {
BufferedReader br;
InputStream stream = getClass().getResourceAsStream(fileOrUrl);
StringBuilder content = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(stream));
String line = br.readLine();
while (line != null) {
content.append(String.format("\n%s", line));
line = br.readLine();
}
br.close();
success = true;
} catch (FileNotFoundException ex) {
errorMsg = ex.getMessage();
success = false;
} catch (IOException ex) {
errorMsg = ex.getMessage();
success = false;
}
return content.substring(0);
}
}
| mit |
mgilangjanuar/GoSCELE | app/src/main/java/com/mgilangjanuar/dev/goscele/modules/main/presenter/MainPresenter.java | 2245 | package com.mgilangjanuar.dev.goscele.modules.main.presenter;
import android.app.ProgressDialog;
import com.mgilangjanuar.dev.goscele.R;
import com.mgilangjanuar.dev.goscele.base.BasePresenter;
import com.mgilangjanuar.dev.goscele.modules.auth.listener.AuthListener;
import com.mgilangjanuar.dev.goscele.modules.auth.provider.AuthProvider;
import com.mgilangjanuar.dev.goscele.modules.auth.view.AuthActivity;
import com.mgilangjanuar.dev.goscele.modules.common.listener.CheckLoginListener;
import com.mgilangjanuar.dev.goscele.modules.common.model.UserModel;
import com.mgilangjanuar.dev.goscele.modules.common.provider.CheckLoginProvider;
import com.mgilangjanuar.dev.goscele.modules.main.view.MainActivity;
/**
* Created by mgilangjanuar (mgilangjanuar@gmail.com)
*
* @since 2017
*/
public class MainPresenter extends BasePresenter {
private MainActivity activity;
private CheckLoginListener checkLoginListener;
public MainPresenter(MainActivity activity, CheckLoginListener checkLoginListener) {
this.activity = activity;
this.checkLoginListener = checkLoginListener;
}
public void checkLogin() {
new CheckLoginProvider(checkLoginListener).run();
}
public void login() {
final UserModel model = getUserModel();
new AuthProvider(new AuthListener() {
@Override
public ProgressDialog getProgressDialog() {
return null;
}
@Override
public void onUsernameOrPasswordEmpty() {
activity.redirect(AuthActivity.class, true);
}
@Override
public void onConnectionFailed() {
activity.showSnackbar(R.string.connection_problem);
}
@Override
public void onWrongCredential(String error) {
activity.showSnackbar(error);
activity.redirect(AuthActivity.class, true);
}
@Override
public void onSuccess() {
activity.onAuthenticate(model.name);
}
}, model.username, model.password).run();
}
public UserModel getUserModel() {
return new UserModel().find().executeSingle();
}
}
| mit |
CS451Tau/Checkers | src/main/java/edu/drexel/tau/checkers/input/Menu.java | 1279 | package edu.drexel.tau.checkers.input;
import edu.drexel.tau.checkers.entities.IDrawable;
import edu.drexel.tau.checkers.events.IButtonFunc;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import java.util.ArrayList;
/**
* A vertical list of buttons.
*/
public class Menu implements IDrawable {
private ArrayList<Button> menuButtons = new ArrayList<>();
public Menu(float x, float y, Action... actions) {
for(Action action : actions) {
this.menuButtons.add(new Button(action.item, x, y, action.func));
y += Button.height + Button.padding * 2;
}
}
public void update(GameContainer gc, StateBasedGame game) throws SlickException {
menuButtons.forEach(button -> button.update(gc, game));
}
public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException {
menuButtons.forEach(button -> button.render(gc, game, g));
}
public static class Action {
private String item;
private IButtonFunc func;
public Action(String item, IButtonFunc func){
this.item = item;
this.func = func;
}
}
}
| mit |
Mr-Holmes/Jogo-da-Memoria | app/src/main/java/com/example/god/jogodamemoria/GameState.java | 367 | package com.example.god.jogodamemoria;
import android.app.Application;
/**
* Created by god on 04/05/17.
*/
public class GameState extends Application {
private CardInfo[] cards = new CardInfo[8];
// public GameState(){
// for(int i = 0; i < this.cards.length;i++){
// cards[i] = new CardInfo(null,null);
//
// }
// }
}
| mit |
artembatutin/champlain-comp-science | java/src/game/asteroid_applet/Ship.java | 530 | package game.asteroid_applet;
import java.awt.*;
//Ship class - polygonal shape of the player's ship
public class Ship extends BaseVectorShape {
//define the ship polygon
private int[] shipx = {-6, -3, 0, 3, 6, 0};
private int[] shipy = {6, 7, 7, 7, 6, -7};
//bounding rectangle
public Rectangle getBounds() {
Rectangle r;
r = new Rectangle((int) getX() - 6, (int) getY() - 6, 12, 12);
return r;
}
Ship() {
setShape(new Polygon(shipx, shipy, shipx.length));
setAlive(true);
}
}
| mit |
jwiesel/sfdcCommander | sfdcCommander/src/main/java/com/sforce/soap/_2006/_04/metadata/QuoteSettings.java | 3704 | /**
* QuoteSettings.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.sforce.soap._2006._04.metadata;
public class QuoteSettings extends com.sforce.soap._2006._04.metadata.Metadata implements java.io.Serializable {
private boolean enableQuote;
public QuoteSettings() {
}
public QuoteSettings(
java.lang.String fullName,
boolean enableQuote) {
super(
fullName);
this.enableQuote = enableQuote;
}
/**
* Gets the enableQuote value for this QuoteSettings.
*
* @return enableQuote
*/
public boolean isEnableQuote() {
return enableQuote;
}
/**
* Sets the enableQuote value for this QuoteSettings.
*
* @param enableQuote
*/
public void setEnableQuote(boolean enableQuote) {
this.enableQuote = enableQuote;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof QuoteSettings)) return false;
QuoteSettings other = (QuoteSettings) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
this.enableQuote == other.isEnableQuote();
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
_hashCode += (isEnableQuote() ? Boolean.TRUE : Boolean.FALSE).hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(QuoteSettings.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "QuoteSettings"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("enableQuote");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "enableQuote"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| mit |
zalando/nakadi | core-common/src/main/java/org/zalando/nakadi/repository/kafka/KafkaTopicConfigFactory.java | 4924 | package org.zalando.nakadi.repository.kafka;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.zalando.nakadi.domain.CleanupPolicy;
import org.zalando.nakadi.exceptions.runtime.TopicConfigException;
import org.zalando.nakadi.repository.NakadiTopicConfig;
import org.zalando.nakadi.util.UUIDGenerator;
import java.util.HashMap;
import java.util.Map;
@Component
public class KafkaTopicConfigFactory {
private final UUIDGenerator uuidGenerator;
private final int defaultTopicReplicaFactor;
private final long defaultTopicRotationMs;
private final long compactedTopicRotationMs;
private final long compactedTopicSegmentBytes;
private final long compactedTopicCompactionLagMs;
@Autowired
public KafkaTopicConfigFactory(
final UUIDGenerator uuidGenerator,
@Value("${nakadi.topic.default.replicaFactor}") final int defaultTopicReplicaFactor,
@Value("${nakadi.topic.default.rotationMs}") final long defaultTopicRotationMs,
@Value("${nakadi.topic.compacted.rotationMs}") final long compactedTopicRotationMs,
@Value("${nakadi.topic.compacted.segmentBytes}") final long compactedTopicSegmentBytes,
@Value("${nakadi.topic.compacted.compactionLagMs}") final long compactedTopicCompactionLagMs) {
this.uuidGenerator = uuidGenerator;
this.defaultTopicReplicaFactor = defaultTopicReplicaFactor;
this.defaultTopicRotationMs = defaultTopicRotationMs;
this.compactedTopicRotationMs = compactedTopicRotationMs;
this.compactedTopicSegmentBytes = compactedTopicSegmentBytes;
this.compactedTopicCompactionLagMs = compactedTopicCompactionLagMs;
}
public void configureCleanupPolicy(final KafkaTopicConfigBuilder builder, final CleanupPolicy cleanupPolicy) {
switch (cleanupPolicy) {
case COMPACT_AND_DELETE:
builder.withCleanupPolicy("compact,delete");
configureCompactionParameters(builder);
break;
case COMPACT:
builder.withCleanupPolicy("compact");
configureCompactionParameters(builder);
break;
case DELETE:
builder
.withCleanupPolicy("delete")
.withSegmentMs(defaultTopicRotationMs);
break;
default:
throw new IllegalStateException("Cleanup Policy not implemented " + cleanupPolicy.toString());
}
}
public KafkaTopicConfig createKafkaTopicConfig(final NakadiTopicConfig topicConfig) throws TopicConfigException {
// set common values
final KafkaTopicConfigBuilder configBuilder = KafkaTopicConfigBuilder.builder()
.withTopicName(uuidGenerator.randomUUID().toString())
.withPartitionCount(topicConfig.getPartitionCount())
.withReplicaFactor(defaultTopicReplicaFactor);
configureCleanupPolicy(configBuilder, topicConfig.getCleanupPolicy());
if (topicConfig.getCleanupPolicy() != CleanupPolicy.COMPACT) {
configureDeletionRetentionMs(topicConfig, configBuilder);
}
return configBuilder.build();
}
private void configureDeletionRetentionMs(final NakadiTopicConfig topicConfig,
final KafkaTopicConfigBuilder configBuilder) {
configBuilder
.withRetentionMs(topicConfig.getRetentionTimeMs()
.orElseThrow(() -> new TopicConfigException("retention time should be specified " +
"for topic with cleanup policy 'delete' or 'compact_and_delete'")));
}
private void configureCompactionParameters(final KafkaTopicConfigBuilder configBuilder) {
configBuilder
.withSegmentMs(compactedTopicRotationMs)
.withSegmentBytes(compactedTopicSegmentBytes)
.withMinCompactionLagMs(compactedTopicCompactionLagMs);
}
public Map<String, String> createKafkaTopicLevelProperties(final KafkaTopicConfig kafkaTopicConfig) {
final Map<String, String> topicConfig = new HashMap<>();
topicConfig.put("segment.ms", Long.toString(kafkaTopicConfig.getSegmentMs()));
topicConfig.put("cleanup.policy", kafkaTopicConfig.getCleanupPolicy());
kafkaTopicConfig.getRetentionMs()
.ifPresent(v -> topicConfig.put("retention.ms", Long.toString(v)));
kafkaTopicConfig.getSegmentBytes()
.ifPresent(v -> topicConfig.put("segment.bytes", Long.toString(v)));
kafkaTopicConfig.getMinCompactionLagMs()
.ifPresent(v -> topicConfig.put("min.compaction.lag.ms", Long.toString(v)));
return topicConfig;
}
}
| mit |
QuikMod/QuikCore | src/test/java/com/github/quikmod/quikcore/config/DummyConfig.java | 1323 | /*
*/
package com.github.quikmod.quikcore.config;
import com.github.quikmod.quikcore.core.QuikCore;
import java.lang.reflect.Field;
/**
*
* @author RlonRyan
*/
public class DummyConfig {
@QuikConfigurable(
category = "Core",
comment = "Is it true?",
key = "is_true"
)
public static boolean isTrue = false;
@QuikConfigurable(
category = "Core",
comment = "Give me an integer!",
key = "the_int"
)
public static int theInt = 10;
@QuikConfigurable(
category = "Core",
comment = "Float my boat!",
key = "the_float"
)
public static float theFloat = -1.25f;
@QuikConfigurable(
category = "Core",
comment = "1 <3 π!",
key = "the_double"
)
public static double theDouble = Math.PI;
@QuikConfigurable(
category = "Core",
comment = "Random String.",
key = "the_string"
)
public static String theString = "The quick brown fox jumps over the lazy dog.";
public static String asString() {
final StringBuilder sb = new StringBuilder().append("Dummy Config:\n");
for (Field f : DummyConfig.class.getFields()) {
try {
sb.append("\t- ").append(f.getName()).append(": ").append(f.get(null)).append("\n");
} catch (IllegalAccessException | IllegalArgumentException e) {
QuikCore.getCoreLogger().trace(e);
}
}
return sb.toString();
}
}
| mit |
simokhov/schemas44 | src/main/java/ru/gov/zakupki/oos/types/_1/ZfcsRepOnlySupplier.java | 3491 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.07.19 at 11:02:43 AM MSK
//
package ru.gov.zakupki.oos.types._1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Информация о единственном поставщике из Реестра единственных поставщиков (РЕП)
*
* <p>Java class for zfcs_repOnlySupplier complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="zfcs_repOnlySupplier">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="commonInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repCommonInfo"/>
* <element name="products" type="{http://zakupki.gov.ru/oos/types/1}zfcs_repProductsType"/>
* <element name="attachments" type="{http://zakupki.gov.ru/oos/types/1}zfcs_attachmentListType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "zfcs_repOnlySupplier", propOrder = {
"commonInfo",
"products",
"attachments"
})
public class ZfcsRepOnlySupplier {
@XmlElement(required = true)
protected ZfcsRepCommonInfo commonInfo;
@XmlElement(required = true)
protected ZfcsRepProductsType products;
protected ZfcsAttachmentListType attachments;
/**
* Gets the value of the commonInfo property.
*
* @return
* possible object is
* {@link ZfcsRepCommonInfo }
*
*/
public ZfcsRepCommonInfo getCommonInfo() {
return commonInfo;
}
/**
* Sets the value of the commonInfo property.
*
* @param value
* allowed object is
* {@link ZfcsRepCommonInfo }
*
*/
public void setCommonInfo(ZfcsRepCommonInfo value) {
this.commonInfo = value;
}
/**
* Gets the value of the products property.
*
* @return
* possible object is
* {@link ZfcsRepProductsType }
*
*/
public ZfcsRepProductsType getProducts() {
return products;
}
/**
* Sets the value of the products property.
*
* @param value
* allowed object is
* {@link ZfcsRepProductsType }
*
*/
public void setProducts(ZfcsRepProductsType value) {
this.products = value;
}
/**
* Gets the value of the attachments property.
*
* @return
* possible object is
* {@link ZfcsAttachmentListType }
*
*/
public ZfcsAttachmentListType getAttachments() {
return attachments;
}
/**
* Sets the value of the attachments property.
*
* @param value
* allowed object is
* {@link ZfcsAttachmentListType }
*
*/
public void setAttachments(ZfcsAttachmentListType value) {
this.attachments = value;
}
}
| mit |
pgervaise/patternfly-webapp | src/main/java/fr/pgervaise/patternfly/datatable/core/DataTableFilterValue.java | 499 | package fr.pgervaise.patternfly.datatable.core;
/**
*
* @author Philippe Gervaise
*
*/
public class DataTableFilterValue {
private String value;
private String label;
public DataTableFilterValue(String valueAndLabel) {
this.value = valueAndLabel;
this.label = valueAndLabel;
}
public DataTableFilterValue(String value, String label) {
this.value = value;
this.label = label;
}
public String getValue() {
return value;
}
public String getLabel() {
return label;
}
}
| mit |
sparber/CComprehensiveDatatypes | src/tree/symbols/TSOrAssign.java | 235 | package tree.symbols;
import tree.DefaultTreeNodeSymbol;
public class TSOrAssign extends DefaultTreeNodeSymbol {
public static int id = OR_ASSIGN;
public static String text = "|=";
public TSOrAssign() {
super(text, id);
}
}
| mit |
kwasiak/tjazi.com | webapp/src/main/java/com/tjazi/webapp/controller/chatroom/ChatroomsForCurrentUserController.java | 2448 | package com.tjazi.webapp.controller.chatroom;
import com.tjazi.chatroom.service.ChatroomService;
import com.tjazi.chatroom.service.SingleChatroomDriver;
import com.tjazi.security.service.SecurityService;
import com.tjazi.webapp.messages.chatroominfo.GetChatroomsForCurrentUserResponseMeesage;
import com.tjazi.webapp.messages.chatroominfo.GetChatroomsForCurrentUserResult;
import com.tjazi.webapp.messages.chatroominfo.SingleChatroomDataForCurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by kwasiak on 05/08/15.
*/
@RestController
@RequestMapping(value = "/chatroom")
public class ChatroomsForCurrentUserController {
@Autowired
private SecurityService securityService;
@Autowired
private ChatroomService chatroomService;
private static final Logger log = LoggerFactory.getLogger(ChatroomsForCurrentUserController.class);
@RequestMapping(value = "/listforuser", method = RequestMethod.POST)
public GetChatroomsForCurrentUserResponseMeesage getChatroomsForCurrentUser() {
String currentUserName = securityService.getCurrentUserName();
if (currentUserName == null || currentUserName.isEmpty()) {
log.error("There's no active logged-in user, so no chatrooms can be returned.");
return new GetChatroomsForCurrentUserResponseMeesage(GetChatroomsForCurrentUserResult.PERMISSION_DENIED, null);
}
List<SingleChatroomDriver> chatroomsForUser = chatroomService.getChatroomsForUser(currentUserName);
log.debug("Extracted {} chatrooms for user {}", chatroomsForUser.size(), currentUserName);
return new GetChatroomsForCurrentUserResponseMeesage(GetChatroomsForCurrentUserResult.OK,
mapToSingleChatroomDataForCurrentUser(chatroomsForUser));
}
private List<SingleChatroomDataForCurrentUser> mapToSingleChatroomDataForCurrentUser(
List<SingleChatroomDriver> entryList) {
return entryList.stream()
.map(x -> new SingleChatroomDataForCurrentUser(x.getChatroomName(), x.getChatroomUuid()))
.collect(Collectors.toList());
}
}
| mit |
mmithril/XChange | xchange-coinbaseex/src/main/java/org/knowm/xchange/coinbaseex/dto/marketdata/CoinbaseExTrade.java | 1436 | package org.knowm.xchange.coinbaseex.dto.marketdata;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CoinbaseExTrade {
private final String timestamp;
private final long tradeId;
private final BigDecimal price;
private final BigDecimal size;
private final String side;
public CoinbaseExTrade(@JsonProperty("time") String timestamp, @JsonProperty("trade_id") long tradeId, @JsonProperty("price") BigDecimal price,
@JsonProperty("size") BigDecimal size, @JsonProperty("side") String side) {
this.timestamp = timestamp;
this.tradeId = tradeId;
this.price = price;
this.size = size;
this.side = side;
}
public String getTimestamp() {
return timestamp;
}
public long getTradeId() {
return tradeId;
}
public BigDecimal getPrice() {
return price;
}
public BigDecimal getSize() {
return size;
}
public String getSide() {
return side;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CoinbaseExTrade [timestamp=");
builder.append(timestamp);
builder.append(", tradeId=");
builder.append(tradeId);
builder.append(", price=");
builder.append(price);
builder.append(", size=");
builder.append(size);
builder.append(", side=");
builder.append(side);
builder.append("]");
return builder.toString();
}
}
| mit |
jcuda/jcudnn | JCudnnJava/src/main/java/jcuda/jcudnn/cudnnMultiHeadAttnWeightKind.java | 3331 | /*
* JCudnn - Java bindings for cuDNN, the NVIDIA CUDA
* Deep Neural Network library, to be used with JCuda
*
* Copyright (c) 2015-2018 Marco Hutter - http://www.jcuda.org
*
* 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 jcuda.jcudnn;
public class cudnnMultiHeadAttnWeightKind
{
/**
* input projection weights for 'queries'
*/
public static final int CUDNN_MH_ATTN_Q_WEIGHTS = 0;
/**
* input projection weights for 'keys'
*/
public static final int CUDNN_MH_ATTN_K_WEIGHTS = 1;
/**
* input projection weights for 'values'
*/
public static final int CUDNN_MH_ATTN_V_WEIGHTS = 2;
/**
* output projection weights
*/
public static final int CUDNN_MH_ATTN_O_WEIGHTS = 3;
/**
* input projection bias tensor for 'queries'
*/
public static final int CUDNN_MH_ATTN_Q_BIASES = 4;
/**
* input projection bias for 'keys'
*/
public static final int CUDNN_MH_ATTN_K_BIASES = 5;
/**
* input projection bias for 'values'
*/
public static final int CUDNN_MH_ATTN_V_BIASES = 6;
/**
* output projection biases
*/
public static final int CUDNN_MH_ATTN_O_BIASES = 7;
/**
* Private constructor to prevent instantiation
*/
private cudnnMultiHeadAttnWeightKind()
{
// Private constructor to prevent instantiation
}
/**
* Returns a string representation of the given constant
*
* @return A string representation of the given constant
*/
public static String stringFor(int n)
{
switch (n)
{
case CUDNN_MH_ATTN_Q_WEIGHTS: return "CUDNN_MH_ATTN_Q_WEIGHTS";
case CUDNN_MH_ATTN_K_WEIGHTS: return "CUDNN_MH_ATTN_K_WEIGHTS";
case CUDNN_MH_ATTN_V_WEIGHTS: return "CUDNN_MH_ATTN_V_WEIGHTS";
case CUDNN_MH_ATTN_O_WEIGHTS: return "CUDNN_MH_ATTN_O_WEIGHTS";
case CUDNN_MH_ATTN_Q_BIASES: return "CUDNN_MH_ATTN_Q_BIASES";
case CUDNN_MH_ATTN_K_BIASES: return "CUDNN_MH_ATTN_K_BIASES";
case CUDNN_MH_ATTN_V_BIASES: return "CUDNN_MH_ATTN_V_BIASES";
case CUDNN_MH_ATTN_O_BIASES: return "CUDNN_MH_ATTN_O_BIASES";
}
return "INVALID cudnnMultiHeadAttnWeightKind: "+n;
}
}
| mit |
tbepler/JProbe | src/jprobe/services/function/components/DataSelectionPanel.java | 3871 | package jprobe.services.function.components;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Collection;
import java.util.HashSet;
import javax.swing.JButton;
import javax.swing.JPanel;
import util.Observer;
import util.Subject;
import jprobe.Constants;
import jprobe.services.JProbeCore;
import jprobe.services.data.Data;
public class DataSelectionPanel<D extends Data> extends JPanel implements ItemListener, ActionListener, Subject<D>{
private static final long serialVersionUID = 1L;
public static interface OnClose{
public void close();
}
private final Collection<Observer<D>> m_Obs = new HashSet<Observer<D>>();
private final DataComboBox<D> m_DataBox;
private final JButton m_CloseButton;
private final boolean m_Optional;
private OnClose m_CloseAction = new OnClose(){
@Override
public void close() {
//do nothing
}
};
public DataSelectionPanel(JProbeCore core, boolean optional){
super(new GridBagLayout());
m_Optional = optional;
m_DataBox = this.createdDataComboBox(core);
m_DataBox.addItemListener(this);
this.add(m_DataBox, this.createDataComboBoxConstraints());
m_CloseButton = this.createCloseButton();
m_CloseButton.addActionListener(this);
m_CloseButton.setEnabled(optional);
this.add(m_CloseButton, this.createCloseButtonConstraints());
if(optional){
m_DataBox.addData(null);
}
}
protected DataComboBox<D> createdDataComboBox(JProbeCore core){
return new DataComboBox<D>(core);
}
protected GridBagConstraints createDataComboBoxConstraints(){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.insets = new Insets(0,0,2,2);
return gbc;
}
protected JButton createCloseButton(){
return new IconButton(Constants.X_ICON, Constants.X_HIGHLIGHTED_ICON, Constants.X_CLICKED_ICON);
}
protected GridBagConstraints createCloseButtonConstraints(){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.insets = new Insets(0,2,2,0);
return gbc;
}
public JProbeCore getCore(){
return m_DataBox.getCore();
}
@Override
public void setEnabled(boolean enabled){
m_DataBox.setEnabled(enabled);
m_CloseButton.setEnabled(enabled && m_Optional);
super.setEnabled(enabled);
}
public void setCloseAction(OnClose closeAction){
m_CloseAction = closeAction;
}
public void addData(D d){
m_DataBox.addData(d);
}
public void removeData(D d){
m_DataBox.removeData(d);
}
public void renameData(String oldName, String newName){
m_DataBox.rename(oldName, newName);
}
public boolean isOptional(){
return m_CloseButton.isEnabled();
}
public void setOptional(boolean optional){
if(this.isOptional() != optional){
if(optional){
m_DataBox.addData(null);
}else{
m_DataBox.removeData(null);
}
m_CloseButton.setEnabled(optional);
}
}
public D getSelectedData(){
return m_DataBox.getSelectedData();
}
protected void close(){
m_CloseAction.close();
}
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() == m_DataBox){
//System.out.println("Item changed");
D selected = m_DataBox.getSelectedData();
this.notifyObservers(selected);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == m_CloseButton){
this.close();
}
}
protected void notifyObservers(D d){
for(Observer<D> obs : m_Obs){
obs.update(this, d);
}
}
@Override
public void register(Observer<D> obs) {
m_Obs.add(obs);
}
@Override
public void unregister(Observer<D> obs) {
m_Obs.remove(obs);
}
}
| mit |
github-api-test-org/jenkins | test/src/test/java/hudson/model/UserTest.java | 20563 | /*
* The MIT License
*
* Copyright (c) 2004-2012, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt,
* Vincent Latombe
*
* 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 hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebAssert;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.security.AccessDeniedException2;
import hudson.security.GlobalMatrixAuthorizationStrategy;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.security.Permission;
import hudson.tasks.MailAddressResolver;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collections;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.FakeChangeLogSCM;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
public class UserTest {
@Rule public JenkinsRule j = new JenkinsRule();
public static class UserPropertyImpl extends UserProperty implements Action {
private final String testString;
private UserPropertyDescriptor descriptorImpl = new UserPropertyDescriptorImpl();
public UserPropertyImpl(String testString) {
this.testString = testString;
}
public String getTestString() {
return testString;
}
@Override
public UserPropertyDescriptor getDescriptor() {
return descriptorImpl;
}
public String getIconFileName() {
return "/images/24x24/gear.png";
}
public String getDisplayName() {
return "UserPropertyImpl";
}
public String getUrlName() {
return "userpropertyimpl";
}
public static class UserPropertyDescriptorImpl extends UserPropertyDescriptor {
@Override
public UserProperty newInstance(User user) {
return null;
}
@Override
public String getDisplayName() {
return "Property";
}
}
}
@Bug(2331)
@Test public void userPropertySummaryAndActionAreShownInUserPage() throws Exception {
UserProperty property = new UserPropertyImpl("NeedleInPage");
UserProperty.all().add(property.getDescriptor());
User user = User.get("user-test-case");
user.addProperty(property);
HtmlPage page = j.createWebClient().goTo("user/user-test-case");
WebAssert.assertTextPresentInElement(page, "NeedleInPage", "main-panel");
WebAssert.assertTextPresentInElement(page, ((Action) property).getDisplayName(), "side-panel");
}
/**
* Asserts that the default user avatar can be fetched (ie no 404)
*/
@Bug(7494)
@Test public void defaultUserAvatarCanBeFetched() throws Exception {
User user = User.get("avatar-user", true);
HtmlPage page = j.createWebClient().goTo("user/" + user.getDisplayName());
j.assertAllImageLoadSuccessfully(page);
}
@Test public void getAuthorities() throws Exception {
JenkinsRule.DummySecurityRealm realm = j.createDummySecurityRealm();
realm.addGroups("administrator", "admins");
realm.addGroups("alice", "users");
realm.addGroups("bob", "users", "lpadmin", "bob");
j.jenkins.setSecurityRealm(realm);
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
auth.add(Jenkins.ADMINISTER, "admins");
auth.add(Permission.READ, "users");
j.jenkins.setAuthorizationStrategy(auth);
SecurityContext seccon = SecurityContextHolder.getContext();
Authentication orig = seccon.getAuthentication();
try {
seccon.setAuthentication(User.get("administrator").impersonate());
assertEquals("[admins]", User.get("administrator").getAuthorities().toString());
assertEquals("[users]", User.get("alice").getAuthorities().toString());
assertEquals("[lpadmin, users]", User.get("bob").getAuthorities().toString());
assertEquals("[]", User.get("MasterOfXaos").getAuthorities().toString());
seccon.setAuthentication(User.get("alice").impersonate());
assertEquals("[]", User.get("alice").getAuthorities().toString());
assertEquals("[]", User.get("bob").getAuthorities().toString());
} finally {
seccon.setAuthentication(orig);
}
}
@Test
public void testGetUser() {
User user = User.get("John Smith");
User user2 = User.get("John Smith2");
user2.setFullName("John Smith");
assertNotSame("Users should not have the same id.", user.getId(), user2.getId());
User.clear();
User user3 = User.get("John Smith");
user3.setFullName("Alice Smith");
assertEquals("Users should not have the same id.", user.getId(), user3.getId());
User user4 = User.get("Marie",false, Collections.EMPTY_MAP);
assertNull("User should not be created because Marie does not exists.", user4);
}
@Test
public void testAddAndGetProperty() throws IOException {
User user = User.get("John Smith");
UserProperty prop = new SomeUserProperty();
user.addProperty(prop);
assertNotNull("User should have SomeUserProperty property.", user.getProperty(SomeUserProperty.class));
assertEquals("UserProperty1 should be assigned to its descriptor", prop, user.getProperties().get(prop.getDescriptor()));
assertTrue("User should should contains SomeUserProperty.", user.getAllProperties().contains(prop));
User.reload();
assertNotNull("User should have SomeUserProperty property.", user.getProperty(SomeUserProperty.class));
}
@Test
public void testImpersonateAndCurrent() {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
User user = User.get("John Smith");
assertNotSame("User John Smith should not be the current user.", User.current().getId(), user.getId());
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
assertEquals("User John Smith should be the current user.", user.getId(), User.current().getId());
}
@Test
public void testGetUnknown() {
User user = User.get("John Smith");
assertNotNull("User should not be null.", user);
}
@Test
public void testGetAndGetAll() {
User user = User.get("John Smith", false, Collections.emptyMap());
assertNull("User John Smith should not be created.", user);
assertFalse("Jenkins should not contain user John Smith.", User.getAll().contains(user));
User user2 = User.get("John Smith2", true, Collections.emptyMap());
assertNotNull("User John Smith2 should be created.", user2);
assertTrue("Jenkins should contain user John Smith2.", User.getAll().contains(user2));
user = User.get("John Smith2", false, Collections.emptyMap());
assertNotNull("User John Smith should be created.", user);
assertTrue("Jenkins should contain user John Smith.", User.getAll().contains(user));
}
@Test
public void testReload() throws IOException{
User user = User.get("John Smith", true, Collections.emptyMap());
user.save();
String config = user.getConfigFile().asString();
config = config.replace("John Smith", "Alice Smith");
PrintStream st = new PrintStream(user.getConfigFile().getFile());
st.print(config);
User.clear();
assertEquals("User should have full name John Smith.", "John Smith", user.getFullName());
User.reload();
user = User.get(user.getId(), false, Collections.emptyMap());
assertEquals("User should have full name Alice Smith.", "Alice Smith", user.getFullName());
}
@Test
public void testClear() {
User user = User.get("John Smith", true, Collections.emptyMap());
assertNotNull("User should not be null.", user);
user.clear();
user = User.get("John Smith", false, Collections.emptyMap());
assertNull("User shoudl be null", user);
}
@Test
public void testGetBuildsAndGetProjects() throws Exception {
User user = User.get("John Smith", true, Collections.emptyMap());
FreeStyleProject project = j.createFreeStyleProject("free");
FreeStyleProject project2 = j.createFreeStyleProject("free2");
project.save();
FakeChangeLogSCM scm = new FakeChangeLogSCM();
scm.addChange().withAuthor(user.getId());
project.setScm(scm);
j.buildAndAssertSuccess(project);
j.buildAndAssertSuccess(project2);
Build build = project.getLastBuild();
Build build2 = project2.getLastBuild();
assertTrue("User should participate in the last build of project free.", user.getBuilds().contains(build));
assertFalse("User should not participate in the last build of project free2.", user.getBuilds().contains(build2));
assertTrue("User should participate in the project free.", user.getProjects().contains(project));
assertFalse("User should not participate in the project free2.", user.getProjects().contains(project2));
//JENKINS-16178: build should include also builds scheduled by user
build2.replaceAction(new CauseAction(new Cause.UserIdCause()));
assertFalse("User should not participate in the last build of project free2.", user.getBuilds().contains(build2));
assertFalse("Current user should not participate in the last build of project free.", User.current().getBuilds().contains(build));
assertTrue("Current user should participate in the last build of project free2.", User.current().getBuilds().contains(build2));
}
@Test
public void testSave() throws IOException {
User user = User.get("John Smith", true, Collections.emptyMap());
User.clear();
User.reload();
user = User.get("John Smith", false, Collections.emptyMap());
assertNull("User should be null.", user);
user = User.get("John Smithl", true, Collections.emptyMap());
user.addProperty(new SomeUserProperty());
user.save();
User.clear();
User.reload();
user = User.get("John Smithl", false, Collections.emptyMap());
assertNotNull("User should not be null.", user);
assertNotNull("User should be saved with all changes.", user.getProperty(SomeUserProperty.class));
}
@Bug(16332)
@Test public void unrecoverableFullName() throws Throwable {
User u = User.get("John Smith <jsmith@nowhere.net>");
assertEquals("jsmith@nowhere.net", MailAddressResolver.resolve(u));
String id = u.getId();
User.clear(); // simulate Jenkins restart
u = User.get(id);
assertEquals("jsmith@nowhere.net", MailAddressResolver.resolve(u));
}
@Test
public void testDelete() throws IOException {
User user = User.get("John Smith", true, Collections.emptyMap());
user.save();
user.delete();
assertFalse("User should be deleted with his persistent data.", user.getConfigFile().exists());
assertFalse("User should be deleted from memory.", User.getAll().contains(user));
user = User.get("John Smith", false, Collections.emptyMap());
assertNull("User should be deleted from memory.", user);
User.reload();
boolean contained = false;
for(User u: User.getAll()){
if(u.getId().equals(user.getId())){
contained = true;
break;
}
}
assertFalse("User should not be loaded.", contained);
}
@Test
public void testDoConfigSubmit() throws Exception {
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
j.jenkins.setCrumbIssuer(null);
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
j.jenkins.setSecurityRealm(realm);
User user = realm.createAccount("John Smith", "password");
User user2 = realm.createAccount("John Smith2", "password");
user2.save();
auth.add(Jenkins.ADMINISTER, user.getId());
auth.add(Jenkins.READ, user2.getId());
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
HtmlForm form = j.createWebClient().login(user.getId(), "password").goTo(user2.getUrl() + "/configure").getFormByName("config");
form.getInputByName("fullName").setValueAttribute("Alice Smith");
j.submit(form);
assertEquals("User should have full name Alice Smith.", "Alice Smith", user2.getFullName());
SecurityContextHolder.getContext().setAuthentication(user2.impersonate());
try{
user.doConfigSubmit(null, null);
fail("User should not have permission to configure antoher user.");
}
catch(Exception e){
if(!(e.getClass().isAssignableFrom(AccessDeniedException2.class))){
fail("AccessDeniedException should be thrown.");
}
}
form = j.createWebClient().login(user2.getId(), "password").goTo(user2.getUrl() + "/configure").getFormByName("config");
form.getInputByName("fullName").setValueAttribute("John");
j.submit(form);
assertEquals("User should be albe to configure himself.", "John", user2.getFullName());
}
@Test
public void testDoDoDelete() throws Exception {
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
j.jenkins.setCrumbIssuer(null);
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
j.jenkins.setSecurityRealm(realm);
User user = realm.createAccount("John Smith", "password");
User user2 = realm.createAccount("John Smith2", "password");
user2.save();
auth.add(Jenkins.ADMINISTER, user.getId());
auth.add(Jenkins.READ, user2.getId());
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
HtmlForm form = j.createWebClient().login(user.getId(), "password").goTo(user2.getUrl() + "/delete").getFormByName("delete");
j.submit(form);
assertFalse("User should be deleted from memory.", User.getAll().contains(user2));
assertFalse("User should be deleted with his persistent data.", user2.getConfigFile().exists());
User.reload();
assertNull("Deleted user should not be loaded.", User.get(user2.getId(),false, Collections.EMPTY_MAP));
user2 = realm.createAccount("John Smith2", "password");
SecurityContextHolder.getContext().setAuthentication(user2.impersonate());
try{
user.doDoDelete(null, null);
fail("User should not have permission to delete antoher user.");
}
catch(Exception e){
if(!(e.getClass().isAssignableFrom(AccessDeniedException2.class))){
fail("AccessDeniedException should be thrown.");
}
}
user.save();
JenkinsRule.WebClient client = j.createWebClient();
form = client.login(user.getId(), "password").goTo(user.getUrl() + "/delete").getFormByName("delete");
try{
j.submit(form);
fail("User should not be able to delete himself");
}
catch(FailingHttpStatusCodeException e){
//ok exception should be thrown
}
assertTrue("User should not delete himself from memory.", User.getAll().contains(user));
assertTrue("User should not delete his persistent data.", user.getConfigFile().exists());
User.reload();
assertNotNull("Deleted user should be loaded.",User.get(user.getId(),false, Collections.EMPTY_MAP));
}
@Test
public void testHasPermission() throws IOException {
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
j.jenkins.setCrumbIssuer(null);
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
j.jenkins.setSecurityRealm(realm);
User user = realm.createAccount("John Smith","password");
User user2 = realm.createAccount("John Smith2", "password");
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
assertFalse("Current user should not have permission read.", user2.hasPermission(Permission.READ));
assertTrue("Current user should always have permission read to himself.", user.hasPermission(Permission.READ));
auth.add(Jenkins.ADMINISTER, user.getId());
assertTrue("Current user should have permission read, because he has permission administer.", user2.hasPermission(Permission.READ));
SecurityContextHolder.getContext().setAuthentication(Jenkins.ANONYMOUS);
user2 = User.get("anonymous");
assertFalse("Current user should not have permission read, because does not have global permission read and authentication is anonymous.", user2.hasPermission(Permission.READ));
}
@Test
public void testCanDelete() throws IOException {
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
j.jenkins.setAuthorizationStrategy(auth);
j.jenkins.setCrumbIssuer(null);
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
j.jenkins.setSecurityRealm(realm);
User user = realm.createAccount("John Smith","password");
User user2 = realm.createAccount("John Smith2","password");
user2.save();
SecurityContextHolder.getContext().setAuthentication(user.impersonate());
assertFalse("Ordinary user cannot delete somebody else", user2.canDelete());
auth.add(Jenkins.ADMINISTER, user.getId());
assertTrue("Administrator can delete anybody else", user2.canDelete());
assertFalse("User (even admin) cannot delete himself", user.canDelete());
SecurityContextHolder.getContext().setAuthentication(user2.impersonate());
auth.add(Jenkins.ADMINISTER, user2.getId());
User user3 = User.get("Random Somebody");
assertFalse("Storage-less temporary user cannot be deleted", user3.canDelete());
user3.save();
assertTrue("But once storage is allocated, he can be deleted", user3.canDelete());
}
@Test
public void testGetDynamic() {
}
public static class SomeUserProperty extends UserProperty {
@TestExtension
public static class DescriptorImpl extends UserPropertyDescriptor {
public String getDisplayName() {
return "UserProperty1";
}
@Override
public UserProperty newInstance(User user) {
return new SomeUserProperty();
}
}
}
}
| mit |
jikuindia/ona | src/main/java/com/insync/dao/AdminEditDaoImpl.java | 8350 | package com.insync.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.insync.constant.CommonMethods;
import com.insync.constant.QueryConstant;
import com.insync.model.CurrUpdateCommand;
import com.insync.model.IftharCommand;
import com.insync.model.NewsAddCommand;
public class AdminEditDaoImpl extends JdbcDaoSupport implements AdminEditDao {
public int storeImage(List<String> imageNames) {
int flag=0;
for (String imageName : imageNames) {
// Date date=getJdbcTemplate().queryForObject("select sysdate from dual",Date.class);
// System.out.println(date);
flag=getJdbcTemplate().update(QueryConstant.imageSql,
new Object[] {imageName});
}
return flag;
}
public int iftharAdd(IftharCommand iftharCommand) {
int flag = getJdbcTemplate().update(
QueryConstant.storePrayer,
new Object[] { iftharCommand.getPrayer1(),
iftharCommand.getPrayer2(), iftharCommand.getPrayer3(),
iftharCommand.getPrayer4(), iftharCommand.getPrayer5(),
iftharCommand.getDate() });
return flag;
}
public int newsAdd(NewsAddCommand newsAddCommand) {
int flag = 0;
String language = newsAddCommand.getNewsLang();
if ("A".equals(language)) {
flag = getJdbcTemplate().update(
QueryConstant.newsArbian,
new Object[] { newsAddCommand.getTitle(),
newsAddCommand.getStatus(),
newsAddCommand.getNewsHomePage(),
CommonMethods.convertStringToHex(newsAddCommand.getNewsDesHom()),
CommonMethods.convertStringToHex(newsAddCommand.getNewsDesMan()),
newsAddCommand.getDate(),
newsAddCommand.getNewsCat() });
} else {
flag = getJdbcTemplate().update(
QueryConstant.newsEnglish,
new Object[] { newsAddCommand.getTitle(),
newsAddCommand.getStatus(),
newsAddCommand.getNewsHomePage(),
CommonMethods.convertStringToHex(newsAddCommand.getNewsDesHom()),
CommonMethods.convertStringToHex(newsAddCommand.getNewsDesMan()),
newsAddCommand.getDate(),
newsAddCommand.getNewsCat() });
}
return flag;
}
public CurrUpdateCommand getCurrencyData(String t_lang, String t_type) {
CurrUpdateCommand curr1 = (CurrUpdateCommand) getJdbcTemplate().query(
QueryConstant.curEng, new Object[] { t_lang, t_type },
new ResultSetExtractor() {
public CurrUpdateCommand extractData(ResultSet rs)
throws SQLException, DataAccessException {
CurrUpdateCommand curr = null;
while (rs.next()) {
curr = new CurrUpdateCommand();
curr.setHomedesc(rs.getString("HOME_DESC"));
curr.setMaindesc(rs.getString("MAIN_DESC"));
}
return curr;
}
});
return curr1;
}
public int updateCurrency(CurrUpdateCommand currUpdateCommand,
String t_type, String t_lang) {
getJdbcTemplate().update(
QueryConstant.curUpdate,
new Object[] { currUpdateCommand.getHomedesc(),
currUpdateCommand.getMaindesc(), t_type, t_lang });
int flag = getJdbcTemplate().update(
QueryConstant.curHisInsert,
new Object[] { currUpdateCommand.getHomedesc(),
currUpdateCommand.getMaindesc(), t_type, t_lang });
return flag;
}
public int changePass(String password) {
return getJdbcTemplate().update(QueryConstant.changePass,
new Object[] { password });
}
@Override
public List<NewsAddCommand> showTitle(String language) {
String sql=QueryConstant.displayTitleAra;
if("E".equals(language)){
sql=QueryConstant.displayTitleEng;
}
List<NewsAddCommand> lists = (List<NewsAddCommand>) getJdbcTemplate().query(
sql,
new ResultSetExtractor<List<NewsAddCommand>>() {
public List<NewsAddCommand> extractData(ResultSet rs)
throws SQLException {
NewsAddCommand newsTitle = null;
List<NewsAddCommand> list = new ArrayList<NewsAddCommand>();
while (rs.next()) {
newsTitle =new NewsAddCommand();
newsTitle.setTitle(rs.getString("TITLE"));
newsTitle.setSrno(rs.getInt("SR_NO"));
list.add(newsTitle);
}
return list;
}
});
return lists;
}
@Override
public IftharCommand showPrayerTime(Date minDate,Date maxDate) {
IftharCommand prayer= getJdbcTemplate().query(QueryConstant.prayerTime,new Object[]{minDate,maxDate},
new ResultSetExtractor<IftharCommand>() {
public IftharCommand extractData(ResultSet rs)
throws SQLException, DataAccessException {
IftharCommand pyrtime = null;
while (rs.next()) {
pyrtime =new IftharCommand();
pyrtime.setPrayer1(rs.getString("TIME1"));
pyrtime.setPrayer2(rs.getString("TIME2"));
pyrtime.setPrayer3(rs.getString("TIME3"));
pyrtime.setPrayer4(rs.getString("TIME4"));
pyrtime.setPrayer5(rs.getString("TIME5"));
}
return pyrtime;
}
});
return prayer;
}
@Override
public List<String> showImageFile(String dt) {
//sFileUploadCommand imagefile=getJdbcTemplate().query(QueryConstant.imageFile, )
// TODO Auto-generated method stub
List<String> imagelist = getJdbcTemplate().query(QueryConstant.imageFile,new Object[]{dt},
new ResultSetExtractor<List<String>>(){
public List<String> extractData(ResultSet rs)throws SQLException, DataAccessException {
List<String> list=new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString("IMG_URL"));
}
return list;
}
});
return imagelist;
}
@Override
public List<String> serchImages(String date1,String date2) {
// TODO Auto-generated method stub
List<String> imagelist = getJdbcTemplate().query(QueryConstant.serchPhoto,new Object[]{date1,date2},
new ResultSetExtractor<List<String>>(){
public List<String> extractData(ResultSet rs)throws SQLException, DataAccessException {
List<String> list=new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString("IMG_URL"));
}
return list;
}
});
return imagelist;
}
@Override
public NewsAddCommand retriveNews(Integer tnews,String lang) {
String sql=QueryConstant.retrieveNewsARB;
if("E".equals(lang)){
sql=QueryConstant.retrieveNewsENG;
}
NewsAddCommand newsAddCommand=getJdbcTemplate().query(sql,new Object[]{tnews},new ResultSetExtractor<NewsAddCommand>() {
public NewsAddCommand extractData(ResultSet rs)
throws SQLException {
NewsAddCommand newsTitle = null;
while (rs.next()) {
newsTitle =new NewsAddCommand();
newsTitle.setSrno(rs.getInt("SR_NO"));
newsTitle.setTitle(rs.getString("TITLE"));
newsTitle.setStatus(rs.getString("NEWS_STATUS").trim());
newsTitle.setNewsHomePage(rs.getString("HOME_DISPLAY").trim());
newsTitle.setNewsDesHom(CommonMethods.convertHexToString(rs.getString("HOME_DESC")));
newsTitle.setNewsDesMan(CommonMethods.convertHexToString(rs.getString("MAIN_DESC")));
DateFormat df=new SimpleDateFormat("yyyy-mm-dd");
Date today = rs.getDate("NEWS_DATE");
String date=today.toString();
Date today1 =null;
try{
today1 = df.parse(date);
}catch(Exception e){
e.printStackTrace();
}
newsTitle.setDate(today1);
newsTitle.setNewsCat(rs.getString("NEWS_CAT").trim());
}
return newsTitle;
}
});
return newsAddCommand;
}
@Override
public int newsUpdate(NewsAddCommand newsAddCommand) {
String sql=QueryConstant.updateNewARB;
if("E".equals(newsAddCommand.getNewsLang())){
sql=QueryConstant.updateNewENG;
}
int flag=getJdbcTemplate().update(sql, new Object[]{newsAddCommand.getTitle(),newsAddCommand.getStatus(),newsAddCommand.getNewsHomePage(),CommonMethods.convertStringToHex(newsAddCommand.getNewsDesHom()),CommonMethods.convertStringToHex(newsAddCommand.getNewsDesMan()),newsAddCommand.getDate(),newsAddCommand.getNewsCat(),newsAddCommand.getSrno()});
return flag;
}
@Override
public int newsArchive(Integer id,String lang) {
String sql=QueryConstant.changeStatusARB;
if("E".equals(lang)){
sql=QueryConstant.changeStatusENG;
}
return getJdbcTemplate().update(sql,new Object[]{id});
}
}
| mit |
btc4j/btc4j-core | src/main/java/org/btc4j/core/BtcInput.java | 1870 | /*
The MIT License (MIT)
Copyright (c) 2013, 2014 by ggbusto@gmx.com
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.btc4j.core;
public class BtcInput extends BtcOutputPart {
private static final long serialVersionUID = 8501404760721594831L;
private long sequence = 0;
public long getSequence() {
return sequence;
}
public void setSequence(long sequence) {
this.sequence = sequence;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BtcInput [transaction=");
builder.append(getTransaction());
builder.append(", output=");
builder.append(getOutput());
builder.append(", script=");
builder.append(getScript());
builder.append(", sequence=");
builder.append(sequence);
builder.append("]");
return builder.toString();
}
} | mit |
codeestX/ECardFlow | ecardflow/src/main/java/moe/codeest/ecardflow/util/RSBlur.java | 1389 | package moe.codeest.ecardflow.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RSRuntimeException;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
/**
* Created by codeest on 2017/1/18.
*/
public class RSBlur {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static Bitmap blur(Context context, Bitmap bitmap, int radius) throws RSRuntimeException {
RenderScript rs = null;
try {
rs = RenderScript.create(context);
rs.setMessageHandler(new RenderScript.RSMessageHandler());
Allocation input =
Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE,
Allocation.USAGE_SCRIPT);
Allocation output = Allocation.createTyped(rs, input.getType());
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
blur.setInput(input);
blur.setRadius(radius);
blur.forEach(output);
output.copyTo(bitmap);
} finally {
if (rs != null) {
rs.destroy();
}
}
return bitmap;
}
} | mit |
sadikovi/spark-gpu | src/main/java/squared/CPU.java | 1510 | package com.wyn.research.squared;
import com.amd.aparapi.Kernel;
import com.amd.aparapi.Range;
public class CPU {
public static class TestKernel extends Kernel {
// values
private float values[];
// squared values holder
private float squared[];
public TestKernel(int size) {
values = new float[size];
squared = new float[size];
for (int i = 0; i < size; i++) {
values[i] = i;
}
}
@Override public void run() {
int gid = getGlobalId();
squared[gid] = values[gid] * values[gid];
}
}
public static void main(String[] _args) {
System.out.println("Start: " + System.currentTimeMillis());
int size = Const.SIZE;
int iterations = Const.ITERATIONS;
Range range = Range.create(size);
System.out.println("Size: " + size);
System.out.println("Iterations: " + iterations);
TestKernel kernel = new TestKernel(size);
kernel.setExecutionMode(Kernel.EXECUTION_MODE.JTP);
kernel.execute(range, iterations);
System.out.println("Average execution time: " + kernel.getAccumulatedExecutionTime() / iterations);
System.out.println("Execution mode: " + kernel.getExecutionMode());
//kernel.showResults(10);
System.out.println("Finish: " + System.currentTimeMillis());
kernel.dispose();
}
}
| mit |
Loomie/KinoSim | staff/src/main/java/de/outstare/kinosim/staff/JobAssignment.java | 2070 | package de.outstare.kinosim.staff;
import de.outstare.kinosim.util.TimeRange;
/**
* A jobassignment is the definition when a specific employee does a specific job. I.e. Mark works at the counter from 6 to 9 pm.
*
* @author Baret
*
*/
public class JobAssignment implements Comparable<JobAssignment> {
private final TimeRange time;
private final Staff staff;
private final Job job;
/**
* @param time
* @param staff
* @param job
*/
public JobAssignment(final TimeRange time, final Staff staff, final Job job) {
super();
this.time = time;
this.staff = staff;
this.job = job;
}
@Override
public int compareTo(final JobAssignment o) {
return time.getStart().compareTo(o.time.getStart());
}
/**
* @return the time
*/
public TimeRange getTime() {
return time;
}
/**
* @return the staff
*/
public Staff getStaff() {
return staff;
}
/**
* @return the job
*/
public Job getJob() {
return job;
}
public double getProductivity() {
return job.calculateQualification(staff.getSkills());
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode() */
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((job == null) ? 0 : job.hashCode());
result = prime * result + ((staff == null) ? 0 : staff.hashCode());
result = prime * result + ((time == null) ? 0 : time.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object) */
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final JobAssignment other = (JobAssignment) obj;
if (job != other.job) {
return false;
}
if (staff == null) {
if (other.staff != null) {
return false;
}
} else if (!staff.equals(other.staff)) {
return false;
}
if (time == null) {
if (other.time != null) {
return false;
}
} else if (!time.equals(other.time)) {
return false;
}
return true;
}
}
| mit |
azam/acme4j | src/main/java/io/azam/acme4j/AcmeUtil.java | 4763 | package io.azam.acme4j;
import static io.azam.acme4j.AcmeConstants.UTF8;
import static io.azam.acme4j.AcmeConstants.UTF8_UNSUPPORTED;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class AcmeUtil {
public static String toBase64(String s) {
try {
// return Base64.encodeBase64URLSafeString(s.getBytes(UTF8));
return javax.xml.bind.DatatypeConverter.printBase64Binary(
s.getBytes(UTF8)).replaceAll("=", "");
} catch (UnsupportedEncodingException e) {
// We should not get here
throw new UnsupportedOperationException(UTF8_UNSUPPORTED);
}
}
public static String toBase64(byte[] b) {
return javax.xml.bind.DatatypeConverter.printBase64Binary(b)
.replaceAll("=", "");
}
public static String fromBase64(String s) {
try {
return new String(
javax.xml.bind.DatatypeConverter.parseBase64Binary(s), UTF8);
} catch (UnsupportedEncodingException e) {
// We should not get here
throw new UnsupportedOperationException(UTF8_UNSUPPORTED);
}
}
public static String toJson(Map<String, Object> map)
throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(map);
}
@SuppressWarnings("unchecked")
public static Map<String, Object> fromJson(String json) throws IOException {
return new ObjectMapper().readValue(json, Map.class);
}
private static synchronized void loadProvider() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
private static Object readPem(File file) throws IOException {
loadProvider();
BufferedReader r = null;
PEMParser p = null;
try {
r = new BufferedReader(new FileReader(file));
p = new PEMParser(r);
return p.readObject();
} finally {
if (p != null) {
try {
p.close();
} catch (IOException e) {
}
}
if (r != null) {
try {
r.close();
} catch (IOException e) {
}
}
}
}
public static KeyPair readKeyFile(File file) throws IOException {
Object o = readPem(file);
if (o != null && o instanceof PEMKeyPair) {
return new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) o);
}
return null;
}
public static PKCS10CertificationRequest readCsrFile(File file)
throws IOException {
Object o = readPem(file);
if (o != null && o instanceof PKCS10CertificationRequest) {
return (PKCS10CertificationRequest) o;
}
return null;
}
public static Certificate readCert(File file) throws IOException,
CertificateException {
Object o = readPem(file);
if (o != null && o instanceof X509CertificateHolder) {
return new JcaX509CertificateConverter()
.getCertificate((X509CertificateHolder) o);
}
return null;
}
public static Set<String> getSubjectAltNames(PKCS10CertificationRequest csr) {
Set<String> s = new HashSet<String>();
for (Attribute attr : csr.getAttributes()) {
System.out.println(attr.getAttrType());
// 1.2.840.113549.1.9.14
if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr
.getAttrType())) {
for (ASN1Encodable asn1 : attr.getAttributeValues()) {
System.out.println(Extensions.getInstance(asn1)
.getExtensionOIDs());
Extensions exts = Extensions.getInstance(asn1);
GeneralNames gns = GeneralNames.fromExtensions(exts,
Extension.subjectAlternativeName); // 2.5.29.17
for (GeneralName gn : gns.getNames()) {
if (GeneralName.dNSName == gn.getTagNo()) {
s.add(gn.getName().toString());
}
if (GeneralName.iPAddress == gn.getTagNo()) {
// FIXME: ip address is encoded
}
}
}
}
}
return s;
}
}
| mit |
JCThePants/PV-Star | src/com/jcwhatever/pvs/commands/admin/modules/ListSubCommand.java | 3137 | /*
* This file is part of PV-Star for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.jcwhatever.pvs.commands.admin.modules;
import com.jcwhatever.nucleus.managed.commands.CommandInfo;
import com.jcwhatever.nucleus.managed.commands.arguments.ICommandArguments;
import com.jcwhatever.nucleus.managed.commands.exceptions.CommandException;
import com.jcwhatever.nucleus.managed.commands.mixins.IExecutableCommand;
import com.jcwhatever.nucleus.managed.language.Localizable;
import com.jcwhatever.nucleus.managed.messaging.ChatPaginator;
import com.jcwhatever.nucleus.utils.text.TextUtils.FormatTemplate;
import com.jcwhatever.pvs.Lang;
import com.jcwhatever.pvs.api.PVStarAPI;
import com.jcwhatever.pvs.api.commands.AbstractPVCommand;
import com.jcwhatever.pvs.api.modules.PVStarModule;
import org.bukkit.command.CommandSender;
import java.util.List;
@CommandInfo(
parent="modules",
command="list",
staticParams={"page=1"},
floatingParams={"search="},
description="Shows list of loaded modules.",
paramDescriptions = {
"page= {PAGE}",
"search= Optional. Specify a search filter."
})
public class ListSubCommand extends AbstractPVCommand implements IExecutableCommand {
@Localizable static final String _PAGINATOR_TITLE =
"PV-Star Modules";
@Override
public void execute(CommandSender sender, ICommandArguments args) throws CommandException {
int page = args.getInteger("page");
ChatPaginator pagin = createPagin(args, 7, Lang.get(_PAGINATOR_TITLE));
List<PVStarModule> modules = PVStarAPI.getPlugin().getModules();
for (PVStarModule module : modules) {
pagin.add(module.getName() + ' ' + module.getVersion(), module.getDescription());
}
if (!args.isDefaultValue("search"))
pagin.setSearchTerm(args.getString("search"));
pagin.show(sender, page, FormatTemplate.LIST_ITEM_DESCRIPTION);
}
}
| mit |
domisum/ExZiff | src/test/java/de/domisum/exziff/Prototype.java | 272 | package de.domisum.exziff;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Prototype
{
private final Logger logger = LoggerFactory.getLogger(getClass());
public static void start()
{
new Prototype().run();
}
private void run()
{
}
}
| mit |
gardncl/elements-of-programming-interviews | arrays/src/main/java/SudokuChecker.java | 189 | import java.util.List;
public class SudokuChecker {
/*
6.16
*/
public static boolean isValidSudoku(List<List<Integer>> partialAssignment) {
return true;
}
}
| mit |
kplatfoot/android-content-provider-sample | src/com/example/people/EditPersonActivity.java | 2953 | package com.example.people;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
public class EditPersonActivity extends Activity {
private Person mPerson;
private EditText mFirstEditText;
private EditText mLastEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPerson = initializePerson();
if (mPerson == null) {
Toast.makeText(this, "Could not load person", Toast.LENGTH_SHORT).show();
finish();
return;
}
setContentView(R.layout.edit_person);
mFirstEditText = (EditText) findViewById(R.id.first);
mLastEditText = (EditText) findViewById(R.id.last);
populateForm(mPerson);
}
private Person initializePerson() {
Intent intent = getIntent();
if (Intent.ACTION_INSERT.equals(intent.getAction())) {
return new Person();
} else {
// Load existing person from content provider
long id;
try {
id = ContentUris.parseId(intent.getData());
} catch (NumberFormatException e) {
return null;
}
Uri uri = ContentUris.withAppendedId(PeopleProvider.PEOPLE_ID_URI_BASE, id);
Cursor cursor = getContentResolver().query(uri, Person.Columns.ALL, null, null, null);
if (cursor == null || !cursor.moveToFirst()) {
return null;
}
return new Person(cursor);
}
}
private void populateForm(Person person) {
mFirstEditText.setText(person.first);
mLastEditText.setText(person.last);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.edit_person, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
save();
break;
case R.id.menu_discard:
discard();
break;
}
return super.onOptionsItemSelected(item);
}
private void save() {
mPerson.first = mFirstEditText.getText().toString();
mPerson.last = mLastEditText.getText().toString();
ContentValues values = new ContentValues();
mPerson.populateValues(values);
if (mPerson.id == -1) {
getContentResolver().insert(PeopleProvider.PEOPLE_URI, values);
} else {
Uri uri = ContentUris.withAppendedId(PeopleProvider.PEOPLE_ID_URI_BASE, mPerson.id);
getContentResolver().update(uri, values, null, null);
}
setResult(Activity.RESULT_OK);
finish();
}
private void discard() {
setResult(Activity.RESULT_CANCELED);
finish();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/machinelearningservices/azure-resourcemanager-machinelearningservices/src/main/java/com/azure/resourcemanager/machinelearningservices/models/VirtualMachineSshCredentials.java | 3422 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.machinelearningservices.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Admin credentials for virtual machine. */
@Fluent
public final class VirtualMachineSshCredentials {
@JsonIgnore private final ClientLogger logger = new ClientLogger(VirtualMachineSshCredentials.class);
/*
* Username of admin account
*/
@JsonProperty(value = "username")
private String username;
/*
* Password of admin account
*/
@JsonProperty(value = "password")
private String password;
/*
* Public key data
*/
@JsonProperty(value = "publicKeyData")
private String publicKeyData;
/*
* Private key data
*/
@JsonProperty(value = "privateKeyData")
private String privateKeyData;
/**
* Get the username property: Username of admin account.
*
* @return the username value.
*/
public String username() {
return this.username;
}
/**
* Set the username property: Username of admin account.
*
* @param username the username value to set.
* @return the VirtualMachineSshCredentials object itself.
*/
public VirtualMachineSshCredentials withUsername(String username) {
this.username = username;
return this;
}
/**
* Get the password property: Password of admin account.
*
* @return the password value.
*/
public String password() {
return this.password;
}
/**
* Set the password property: Password of admin account.
*
* @param password the password value to set.
* @return the VirtualMachineSshCredentials object itself.
*/
public VirtualMachineSshCredentials withPassword(String password) {
this.password = password;
return this;
}
/**
* Get the publicKeyData property: Public key data.
*
* @return the publicKeyData value.
*/
public String publicKeyData() {
return this.publicKeyData;
}
/**
* Set the publicKeyData property: Public key data.
*
* @param publicKeyData the publicKeyData value to set.
* @return the VirtualMachineSshCredentials object itself.
*/
public VirtualMachineSshCredentials withPublicKeyData(String publicKeyData) {
this.publicKeyData = publicKeyData;
return this;
}
/**
* Get the privateKeyData property: Private key data.
*
* @return the privateKeyData value.
*/
public String privateKeyData() {
return this.privateKeyData;
}
/**
* Set the privateKeyData property: Private key data.
*
* @param privateKeyData the privateKeyData value to set.
* @return the VirtualMachineSshCredentials object itself.
*/
public VirtualMachineSshCredentials withPrivateKeyData(String privateKeyData) {
this.privateKeyData = privateKeyData;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| mit |
marcelmika/lims | docroot/WEB-INF/src/com/marcelmika/lims/persistence/generated/model/impl/PanelImpl.java | 1418 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.marcelmika.lims.persistence.generated.model.impl;
/**
* The extended model implementation for the Panel service. Represents a row in the "lims_Panel" database table, with each column mapped to a property of this class.
*
* <p>
* Helper methods and all application logic should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link com.marcelmika.lims.persistence.generated.model.Panel} interface.
* </p>
*
* @author Brian Wing Shun Chan
*/
public class PanelImpl extends PanelBaseImpl {
/*
* NOTE FOR DEVELOPERS:
*
* Never reference this class directly. All methods that expect a panel model instance should use the {@link com.marcelmika.lims.persistence.generated.model.Panel} interface instead.
*/
public PanelImpl() {
}
} | mit |
batazor/MyExampleAndExperiments | JAVA/Android/startandroid/p0821handleradvmessage/src/main/java/ru/p0651startandroid/handleradvmessage/MainActivity.java | 5286 | package ru.p0651startandroid.handleradvmessage;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
final String LOG_TAG = "myLogs";
final int STATUS_NONE = 0;
final int STATUS_CONNECTING = 1;
final int STATUS_CONNECTED = 2;
final int STATUS_DOWNLOAD_START = 3;
final int STATUS_DOWNLOAD_FILE = 4;
final int STATUS_DOWNLOAD_END = 5;
final int STATUS_DOWNLOAD_NONE = 6;
Handler h;
TextView tvStatus;
ProgressBar pbDownload;
Button btnConnect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = (TextView) findViewById(R.id.tvStatus);
pbDownload = (ProgressBar) findViewById(R.id.pbDownload);
btnConnect = (Button) findViewById(R.id.btnConnect);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case STATUS_NONE:
btnConnect.setEnabled(true);
tvStatus.setText("Not connected");
pbDownload.setVisibility(View.GONE);
break;
case STATUS_CONNECTING:
btnConnect.setEnabled(false);
tvStatus.setText("Connecting");
break;
case STATUS_CONNECTED:
tvStatus.setText("Connected");
break;
case STATUS_DOWNLOAD_START:
tvStatus.setText("Start download " + msg.arg1 + " files");
pbDownload.setMax(msg.arg1);
pbDownload.setProgress(0);
pbDownload.setVisibility(View.VISIBLE);
break;
case STATUS_DOWNLOAD_FILE:
tvStatus.setText("Downloading. Left " + msg.arg2 + " files");
pbDownload.setProgress(msg.arg1);
saveFile((byte[]) msg.obj);
break;
case STATUS_DOWNLOAD_END:
tvStatus.setText("Download complete!");
break;
case STATUS_DOWNLOAD_NONE:
tvStatus.setText("No files for download");
break;
}
};
};
h.sendEmptyMessage(STATUS_NONE);
}
public void onclick(View v) {
Thread t = new Thread(new Runnable() {
Message msg;
byte[] file;
Random rand = new Random();
public void run() {
try {
h.sendEmptyMessage(STATUS_CONNECTING);
TimeUnit.SECONDS.sleep(1);
h.sendEmptyMessage(STATUS_CONNECTED);
TimeUnit.SECONDS.sleep(1);
int filesCount = rand.nextInt(5);
if (filesCount == 0) {
h.sendEmptyMessage(STATUS_DOWNLOAD_NONE);
TimeUnit.MILLISECONDS.sleep(1500);
h.sendEmptyMessage(STATUS_NONE);
return;
}
msg = h.obtainMessage(STATUS_DOWNLOAD_START, filesCount, 0);
h.sendMessage(msg);
for (int i = 1; i <= filesCount; i++) {
file = downloadFile();
msg = h.obtainMessage(STATUS_DOWNLOAD_FILE, i, filesCount - i, file);
h.sendMessage(msg);
}
h.sendEmptyMessage(STATUS_DOWNLOAD_END);
TimeUnit.MILLISECONDS.sleep(1500);
h.sendEmptyMessage(STATUS_NONE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
byte[] downloadFile() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
return new byte[1024];
}
void saveFile(byte[] file) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| mit |
meefik/java-examples | JavaExceptions/src/javaexceptions/JavaExceptions.java | 3904 | package javaexceptions;
// собственное исключение
class SimpleException extends Exception {
public SimpleException() {}
}
class MyException extends Exception {
public MyException() {}
// определения конструктора с параметрами
public MyException(String msg) { super(msg); }
}
public class JavaExceptions {
// сообщаем об исключениях, возбуждаемых методом,
// с помощью ключевого слова throws
public static void f() throws SimpleException {
if (Math.random() > 0.5) {
System.out.println("Возбуждаем SimpleException из f()");
throw new SimpleException();
}
}
public static void g() throws MyException {
throw new MyException("Возбуждаем SimpleException из g()");
}
public static void h() throws Exception {
try {
g();
} catch(Exception e) {
System.out.println("Перехват исключения g() в h()");
e.printStackTrace(System.out);
// повторное возбуждение исключения
throw e;
}
}
public static void r() {
throw new RuntimeException("Возбуждено из r()");
}
public static void main(String[] args) {
// Throwable - корневой класс иерархии исключений (включает подклассы Exception and Error)
// Exception - базовый класс для практически всех классов
// программно восстановимых исключений
// Error - базовых класс для неисправимых ошибок, типа OutOfMemoryError,
// InternalError или StackOverflowError
// Вызов исключения:
// throw new NullPointerException("без паники, это просто проверка исключений :)");
// Перехват исключений:
try {
f();
g();
} catch(SimpleException e) {
e.printStackTrace(System.err);
} catch(MyException e) {
e.printStackTrace(System.err);
}
try {
throw new Exception("Мое исключение");
} catch(Exception e) {
System.out.println("Перехвачено");
System.out.println("getMessage(): " + e.getMessage());
System.out.println("getLocalizedMessage(): " + e.getLocalizedMessage());
System.out.println("toString: " + e);
System.out.println("printStackTrace(): ");
e.printStackTrace(System.out);
}
// Повторное возбуждение исключения
try {
h();
} catch(Exception e) {
System.out.println("main: printStackTrace()");
e.printStackTrace(System.out);
}
// h; // нельзя вызвать без обработчика исключений
// Исключения, унаследованные от RuntimeException, перехватываются автоматически
r();
// Завершение с помощью finally
String t = null;
try {
long l = t.length();
System.out.println("Результат: " + l);
} catch (NullPointerException e) {
System.out.println("Исключение null-ссылка:");
e.printStackTrace(System.out);
} finally {
// finally выполняется всегда
t = "текст";
System.out.println("Исправленный результат: " + t);
}
}
}
| mit |
recena/jenkins | core/src/main/java/hudson/model/CheckPoint.java | 6877 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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 hudson.model;
import hudson.tasks.BuildStep;
import hudson.tasks.Recorder;
import hudson.tasks.Builder;
import hudson.scm.SCM;
import javax.annotation.Nonnull;
/**
* Provides a mechanism for synchronizing build executions in the face of concurrent builds.
*
* <p>
* At certain points of a build, {@link BuildStep}s and other extension points often need
* to refer to what happened in its earlier build. For example, a {@link SCM} check out
* can run concurrently, but the changelog computation requires that the check out of the
* earlier build has completed. Or if Hudson is sending out an e-mail, he needs to know
* the result of the previous build, so that he can decide an e-mail is necessary or not.
*
* <p>
* Check pointing is a primitive mechanism to provide this sort of synchronization.
* These methods can be only invoked from {@link Executor} threads.
*
* <p>
* Each {@link CheckPoint} instance represents unique check points. {@link CheckPoint}
* instances are normally created as a static instance, because two builds of the same project
* needs to refer to the same check point instance for synchronization to happen properly.
*
* <p>
* This class defines a few well-known check point instances. plugins can define
* their additional check points for their own use.
*
* <p>Note that not all job types support checkpoints.
*
* <h2>Example</h2>
* <p>
* {@code JUnitResultArchiver} provides a good example of how a {@link Recorder} can
* depend on its earlier result.
*
* @author Kohsuke Kawaguchi
* @see BuildStep#getRequiredMonitorService()
* @since 1.319
*/
public final class CheckPoint {
private final Object identity;
private final String internalName;
/**
* For advanced uses. Creates a check point that uses the given object as its identity.
*/
public CheckPoint(String internalName, Object identity) {
this.internalName = internalName;
this.identity = identity;
}
/**
* @param internalName
* Name of this check point that's used in the logging, stack traces, debug messages, and so on.
* This is not displayed to users. No need for i18n.
*/
public CheckPoint(String internalName) {
this(internalName, new Object());
}
@Override
public boolean equals(Object that) {
if (that == null || getClass() != that.getClass()) return false;
return identity== ((CheckPoint) that).identity;
}
@Override
public int hashCode() {
return identity.hashCode();
}
@Override
public String toString() {
return "Check point "+internalName;
}
/**
* Records that the execution of the build has reached to a check point, identified
* by the given identifier.
*
* <p>
* If the successive builds are {@linkplain #block() waiting for this check point},
* they'll be released.
*
* <p>
* This method can be only called from an {@link Executor} thread.
*/
public void report() {
Run.reportCheckpoint(this);
}
/**
* Waits until the previous build in progress reaches a check point, identified
* by the given identifier, or until the current executor becomes the youngest build in progress.
*
* <p>
* Note that "previous build in progress" should be interpreted as "previous (build in progress)" instead of
* "(previous build) if it's in progress". This makes a difference around builds that are aborted or
* failed very early without reporting the check points. Imagine the following time sequence:
*
* <ol>
* <li>Build #1, #2, and #3 happens around the same time
* <li>Build #3 waits for check point {@code JUnitResultArchiver}
* <li>Build #2 aborts before getting to that check point
* <li>Build #1 finally checks in {@code JUnitResultArchiver}
* </ol>
*
* <p>
* Using this method, build #3 correctly waits until the step 4. Because of this behavior,
* the {@link #report()}/{@link #block()} pair can normally
* be used without a try/finally block.
*
* <p>
* This method can be only called from an {@link Executor} thread.
*
* @throws InterruptedException
* If the build (represented by the calling executor thread) is aborted while it's waiting.
*/
public void block() throws InterruptedException {
Run.waitForCheckpoint(this, null, null);
}
/**
* Like {@link #block()} but allows for richer logging.
* @param listener an optional listener to which
* @param waiter a description of what component is requesting the wait, such as {@link Descriptor#getDisplayName}
* @throws InterruptedException if the build is aborted while waiting
* @since 1.528
*/
public void block(@Nonnull BuildListener listener, @Nonnull String waiter) throws InterruptedException {
Run.waitForCheckpoint(this, listener, waiter);
}
/**
* {@link CheckPoint} that indicates that {@link AbstractBuild#getCulprits()} is computed.
*/
public static final CheckPoint CULPRITS_DETERMINED = new CheckPoint("CULPRITS_DETERMINED");
/**
* {@link CheckPoint} that indicates that the build is completed.
* ({@link AbstractBuild#isBuilding()}==false)
*/
public static final CheckPoint COMPLETED = new CheckPoint("COMPLETED");
/**
* {@link CheckPoint} that indicates that the build has finished executing the "main" portion
* ({@link Builder}s in case of {@link FreeStyleProject}) and now moving on to the post-build
* steps.
*/
public static final CheckPoint MAIN_COMPLETED = new CheckPoint("MAIN_COMPLETED");
}
| mit |
frib-high-level-controls/save-set-restore | plugins/org.csstudio.saverestore.ui.browser/src/org/csstudio/saverestore/ui/browser/DefaultBaseLevelBrowser.java | 8865 | /*
* This software is Copyright by the Board of Trustees of Michigan
* State University (c) Copyright 2016.
*
* Contact Information:
* Facility for Rare Isotope Beam
* Michigan State University
* East Lansing, MI 48824-1321
* http://frib.msu.edu
*/
package org.csstudio.saverestore.ui.browser;
import static org.csstudio.ui.fx.util.FXUtilities.setGridConstraints;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.csstudio.saverestore.data.BaseLevel;
import org.csstudio.saverestore.ui.Selector;
import org.csstudio.saverestore.ui.SnapshotViewerEditor;
import org.csstudio.ui.fx.util.FXMessageDialog;
import org.csstudio.ui.fx.util.UnfocusableButton;
import org.eclipse.ui.IWorkbenchSite;
import javafx.animation.Animation.Status;
import javafx.animation.FadeTransition;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.util.Duration;
/**
*
* <code>DefaultBaseLevelBrowser</code> is an implementation of the base level browser, which uses a list to select the
* base level from. It also provides an input text, where a non existing base level can be selected.
*
* @author <a href="mailto:jaka.bobnar@cosylab.com">Jaka Bobnar</a>
*
*/
public class DefaultBaseLevelBrowser extends GridPane implements BaseLevelBrowser<BaseLevel> {
private static final String ANIMATED_STYLE = SnapshotViewerEditor.ANIMATED_STYLE + "-fx-font-weight: bold; ";
private final ListView<BaseLevel> baseLevelsList;
private final Button okButton;
private final TextField textField;
private final FadeTransition animation;
private ObjectProperty<BaseLevel> selectedBaseLevelProperty;
private ObjectProperty<BaseLevel> internalBaseLevelProperty;
private ObjectProperty<List<BaseLevel>> availableBaseLevelsProperty;
private final IWorkbenchSite parent;
/**
* Constructs a new default base level browser for the given view.
*
* @param view the parent view (needed only to obtain the shell)
*/
public DefaultBaseLevelBrowser(IWorkbenchSite view) {
this.parent = view;
setVgap(5);
setHgap(5);
baseLevelsList = new ListView<>();
baseLevelsList.selectionModelProperty().get().setSelectionMode(SelectionMode.SINGLE);
baseLevelsList.selectionModelProperty().get().selectedItemProperty()
.addListener((a, o, n) -> baseSelected(true));
baseLevelsList.setOnMouseClicked(e -> {
if (e.getClickCount() == 2) {
confirmSelectBaseLevel();
}
});
baseLevelsList.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
okButton = new UnfocusableButton("Select");
okButton.setOnAction(e -> confirmSelectBaseLevel());
textField = new TextField();
textField.textProperty().addListener((a, o, n) -> baseSelected(false));
textField.setMaxWidth(Double.MAX_VALUE);
setGridConstraints(textField, true, false, Priority.ALWAYS, Priority.NEVER);
setGridConstraints(okButton, false, false, HPos.RIGHT, VPos.CENTER, Priority.NEVER, Priority.NEVER);
setGridConstraints(textField, true, true, Priority.ALWAYS, Priority.ALWAYS);
add(baseLevelsList, 0, 0, 2, 1);
add(textField, 0, 1, 1, 1);
add(okButton, 1, 1, 1, 1);
animation = new FadeTransition(Duration.seconds(0.15), okButton);
animation.setAutoReverse(true);
animation.setFromValue(1.0);
animation.setToValue(0.4);
animation.setCycleCount(6);
setMinHeight(200);
}
private void baseSelected(boolean fromList) {
BaseLevel n = baseLevelsList.selectionModelProperty().get().getSelectedItem();
if (fromList) {
if (n == null) {
textField.setText("");
} else {
textField.setText(n.getStorageName());
}
} else {
String s = textField.getText();
n = new BaseLevel(n == null ? null : n.getBranch(), s, s);
}
internalBaseLevelProperty().setValue(n);
}
private void confirmSelectBaseLevel() {
BaseLevel bl = internalBaseLevelProperty().getValue();
if (bl != null && !availableBaseLevelsProperty.get().contains(bl)) {
String message = Selector.validateBaseLevelName(bl.getStorageName());
if (message != null && !FXMessageDialog.openQuestion(parent.getShell(), "Invalid Name",
message + "\n Do you still want to continue?")) {
return;
}
}
selectedBaseLevelProperty().setValue(bl);
}
/*
* (non-Javadoc)
*
* @see org.csstudio.saverestore.ui.browser.BaseLevelBrowser#getFXContent()
*/
@Override
public Node getFXContent() {
return this;
}
/*
* (non-Javadoc)
*
* @see org.csstudio.saverestore.ui.browser.BaseLevelBrowser#setShowOnlyAvailable(boolean)
*/
@Override
public void setShowOnlyAvailable(boolean onlyAvailable) {
textField.setDisable(onlyAvailable);
}
/*
* (non-Javadoc)
*
* @see org.csstudio.saverestore.ui.browser.BaseLevelBrowser#availableBaseLevelsProperty()
*/
@Override
public ObjectProperty<List<BaseLevel>> availableBaseLevelsProperty() {
if (availableBaseLevelsProperty == null) {
availableBaseLevelsProperty = new SimpleObjectProperty<>(new ArrayList<>());
availableBaseLevelsProperty
.addListener((a, o, n) -> baseLevelsList.getItems().setAll(availableBaseLevelsProperty.get()));
}
return availableBaseLevelsProperty;
}
/*
* (non-Javadoc)
*
* @see org.csstudio.saverestore.ui.browser.BaseLevelBrowser#transform(java.util.List)
*/
@Override
public List<BaseLevel> transform(List<? extends BaseLevel> list) {
return Collections.unmodifiableList(new ArrayList<>(list));
}
/*
* (non-Javadoc)
*
* @see org.csstudio.saverestore.ui.browser.BaseLevelBrowser#selectedBaseLevelProperty()
*/
@Override
public Property<BaseLevel> selectedBaseLevelProperty() {
if (selectedBaseLevelProperty == null) {
selectedBaseLevelProperty = new SimpleObjectProperty<>(this, "selectedBaseLevel", null);
selectedBaseLevelProperty.addListener((a, o, n) -> {
baseLevelsList.selectionModelProperty().get().select(n);
animation.pause();
animation.jumpTo(Duration.seconds(0));
animation.stop();
okButton.setStyle(null);
});
}
return selectedBaseLevelProperty;
}
private Property<BaseLevel> internalBaseLevelProperty() {
if (internalBaseLevelProperty == null) {
internalBaseLevelProperty = new SimpleObjectProperty<>(this, "internalSelectedBaseLevel", null);
internalBaseLevelProperty.addListener((a, o, n) -> {
if (n != null) {
BaseLevel iso = selectedBaseLevelProperty().getValue();
if (!n.equals(iso) && animation.getStatus() != Status.RUNNING) {
okButton.setStyle(ANIMATED_STYLE);
animation.play();
} else if (n.equals(iso)) {
animation.pause();
animation.jumpTo(Duration.seconds(0));
animation.stop();
okButton.setStyle(null);
}
}
});
}
return internalBaseLevelProperty;
}
/*
* (non-Javadoc)
*
* @see org.csstudio.saverestore.ui.browser.BaseLevelBrowser#getTitleFor(java.util.Optional, java.util.Optional)
*/
@Override
public String getTitleFor(Optional<BaseLevel> baseLevel, Optional<String> branch) {
if (baseLevel.isPresent()) {
if (branch.isPresent()) {
return baseLevel.get().getPresentationName() + " (" + branch.get() + ")";
} else {
return baseLevel.get().getPresentationName();
}
} else {
return "";
}
}
/*
* (non-Javadoc)
*
* @see org.csstudio.saverestore.ui.browser.BaseLevelBrowser#getReadableName()
*/
@Override
public String getReadableName() {
return "Default Browser";
}
}
| mit |
ShreyaChippagiri/Advanced-Java-Lab-Programs | MultiThreading/ThreadDemo.java | 2584 | import java.util.*;
class ThreadDemo
{
public static void main(String args[])
{
Display d1=new Display();
Thread1 ob1=new Thread1(d1,"t1");
Thread2 ob2=new Thread2(d1,"t2");
Thread3 ob3=new Thread3(d1,"t3");
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("exception occured");
}
System.out.println("main thread is exiting");
}
}
class Display
{
void disp(int value)
{
System.out.println(" " + value);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(" interrupted.");
}
}
}
//finds factorial
class Thread1 implements Runnable
{
String name;
Thread t;
Display objd;
Thread1(Display d,String threadname)
{
objd=d;
name=threadname;
t=new Thread(this,name);
System.out.println("new thread"+t);
t.start();
}
public void run()
{
synchronized(objd)
{
int number=5;
int fact=1;
for (int i=2;i<=number;i++)
{
fact=fact*i;
}
System.out.println("the factorial of" + number +" is");
objd.disp(fact);
System.out.println("exiting" + name);
}
}
}
class Thread2 implements Runnable
{
String name;
Thread t;
Display objd;
int a[]=new int[20];
Thread2(Display d,String threadname)
{
objd=d;
name=threadname;
t=new Thread(this,name);
System.out.println("new thread"+t);
t.start();
}
public void run()
{
synchronized(objd)
{
int number=5;
a[0]=0;
a[1]=1;
for(int i=2;i<number;i++)
{
a[i]=a[i-1]+a[i-2];
}
System.out.println("the " +number+" th fibonacci number is" );
objd.disp(a[number-1]);
System.out.println("exiting" + name);
}
}
}
class Thread3 implements Runnable
{
String name;
Thread t;
Display objd;
int a[]=new int[5];
Thread3(Display d,String threadname)
{
objd=d;
name=threadname;
t=new Thread(this,name);
System.out.println("new thread"+t);
a[0]=3;
a[1]=6;
a[2]=1;
a[3]=2;
a[4]=8;
t.start();
}
public void run()
{
synchronized(objd)
{
int temp=0;
int n=5;
System.out.print("the unsorted array is");
for(int k=0;k<n;k++)
{
objd.disp(a[k]);
}
for(int i=0;i<n-1;i++)
{
for(int j=0; j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("the sorted array is");
for(int k=0;k<n;k++)
{
objd.disp(a[k]);
}
System.out.println("exiting" + name);
}
}
}
| mit |
r0adkll/Hardwired | app/src/main/java/com/r0adkll/hardwired/data/model/GPU.java | 3187 | package com.r0adkll.hardwired.data.model;
import java.util.ArrayList;
import java.util.List;
/**
* Project: Hardwired
* Package: com.r0adkll.hardwired.data.model
* Created by drew.heavner on 1/12/16.
*/
public class GPU extends Component {
public Load getLoad(){
if(components != null && !components.isEmpty()){
for (Component component : components) {
if(component.title.equalsIgnoreCase("load")){
if(component.components != null && !component.components.isEmpty()){
Component cmp = component.components.get(0);
return cmp.getComponent(Load.class);
}
break;
}
}
}
return null;
}
public Clock getCoreClock(){
if(components != null && !components.isEmpty()){
for (Component component : components) {
if(component.title.equalsIgnoreCase("clocks")){
if(component.components != null && !component.components.isEmpty()){
for (Component clockCmp : component.components) {
if(clockCmp.title.toLowerCase().contains("core")){
return clockCmp.getComponent(Clock.class);
}
}
}
}
}
}
return null;
}
public Clock getMemoryClock(){
if(components != null && !components.isEmpty()){
for (Component component : components) {
if(component.title.equalsIgnoreCase("clocks")){
if(component.components != null && !component.components.isEmpty()){
for (Component clockCmp : component.components) {
if(clockCmp.title.toLowerCase().contains("memory")){
return clockCmp.getComponent(Clock.class);
}
}
}
}
}
}
return null;
}
public Temperature getTemperature(){
if(components != null && !components.isEmpty()){
for (Component component : components) {
if(component.title.equalsIgnoreCase("temperatures")){
if(component.components != null && !component.components.isEmpty()){
Component cmp = component.components.get(0);
return cmp.getComponent(Temperature.class);
}
}
}
}
return null;
}
public Fan getFan(){
if(components != null && !components.isEmpty()){
for (Component component : components) {
if(component.title.equalsIgnoreCase("fans")){
if(component.components != null && !component.components.isEmpty()){
Component cmp = component.components.get(0);
return cmp.getComponent(Fan.class);
}
}
}
}
return null;
}
}
| mit |
mdb255/wedding | wedding-domain/src/main/java/com/mdb255/wedding/domain/viewmodel/RegistryItemViewModel.java | 1851 | package com.mdb255.wedding.domain.viewmodel;
import java.util.List;
public class RegistryItemViewModel {
private int registryItemId;
private String category;
private Boolean isPurchasable;
private Integer qtyRemaining;
private List<Integer> prices;
private String priceRange;
private String description;
private String imageUrl;
public int getRegistryItemId() {
return registryItemId;
}
public void setRegistryItemId(int registryItemId) {
this.registryItemId = registryItemId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Boolean getIsPurchasable() {
return isPurchasable;
}
public void setIsPurchasable(Boolean isPurchasable) {
this.isPurchasable = isPurchasable;
}
public Integer getQtyRemaining() {
return qtyRemaining;
}
public void setQtyRemaining(Integer qtyRemaining) {
this.qtyRemaining = qtyRemaining;
}
public List<Integer> getPrices() {
return prices;
}
public void setPrices(List<Integer> prices) {
this.prices = prices;
}
public String getPriceRange() {
return priceRange;
}
public void setPriceRange(String priceRange) {
this.priceRange = priceRange;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
public String toString() {
return "RegistryItemViewModel [registryItemId=" + registryItemId
+ ", category=" + category + ", isPurchasable=" + isPurchasable
+ ", qtyRemaining=" + qtyRemaining + ", prices=" + prices
+ ", priceRange=" + priceRange + ", description=" + description
+ ", imageUrl=" + imageUrl + "]";
}
}
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/SiteCollectionRequest.java | 5493 | // Template Source: BaseEntityCollectionRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.Site;
import com.microsoft.graph.models.ItemActivityStat;
import com.microsoft.graph.models.ContentType;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.options.QueryOption;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseEntityCollectionRequest;
import com.microsoft.graph.requests.SiteCollectionResponse;
import com.microsoft.graph.requests.SiteCollectionRequestBuilder;
import com.microsoft.graph.requests.SiteCollectionRequest;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Site Collection Request.
*/
public class SiteCollectionRequest extends BaseEntityCollectionRequest<Site, SiteCollectionResponse, SiteCollectionPage> {
/**
* The request builder for this collection of Site
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public SiteCollectionRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, SiteCollectionResponse.class, SiteCollectionPage.class, SiteCollectionRequestBuilder.class);
}
/**
* Creates a new Site
* @param newSite the Site to create
* @return a future with the created object
*/
@Nonnull
public java.util.concurrent.CompletableFuture<Site> postAsync(@Nonnull final Site newSite) {
final String requestUrl = getBaseRequest().getRequestUrl().toString();
return new SiteRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
.buildRequest(getBaseRequest().getHeaders())
.postAsync(newSite);
}
/**
* Creates a new Site
* @param newSite the Site to create
* @return the newly created object
*/
@Nonnull
public Site post(@Nonnull final Site newSite) throws ClientException {
final String requestUrl = getBaseRequest().getRequestUrl().toString();
return new SiteRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
.buildRequest(getBaseRequest().getHeaders())
.post(newSite);
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
/**
* Sets the filter clause for the request
*
* @param value the filter clause
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest filter(@Nonnull final String value) {
addFilterOption(value);
return this;
}
/**
* Sets the order by clause for the request
*
* @param value the order by clause
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest orderBy(@Nonnull final String value) {
addOrderByOption(value);
return this;
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the top value for the request
*
* @param value the max number of items to return
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest top(final int value) {
addTopOption(value);
return this;
}
/**
* Sets the count value for the request
*
* @param value whether or not to return the count of objects with the request
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest count(final boolean value) {
addCountOption(value);
return this;
}
/**
* Sets the count value to true for the request
*
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest count() {
addCountOption(true);
return this;
}
/**
* Sets the skip value for the request
*
* @param value of the number of items to skip
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest skip(final int value) {
addSkipOption(value);
return this;
}
/**
* Add Skip token for pagination
* @param skipToken - Token for pagination
* @return the updated request
*/
@Nonnull
public SiteCollectionRequest skipToken(@Nonnull final String skipToken) {
addSkipTokenOption(skipToken);
return this;
}
}
| mit |
cegiraud/test-spring | src/main/java/com/soprasteria/initiatives/config/properties/ApiProperties.java | 2270 | package com.soprasteria.initiatives.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Swagger API properties
*
* @author jntakpe
*/
@Component
@ConfigurationProperties(prefix = "api")
public class ApiProperties {
private String title;
private String description;
private String version;
private String termsOfServiceUrl;
private String license;
private String licenseUrl;
private Contact contact = new Contact();
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getTermsOfServiceUrl() {
return termsOfServiceUrl;
}
public void setTermsOfServiceUrl(String termsOfServiceUrl) {
this.termsOfServiceUrl = termsOfServiceUrl;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getLicenseUrl() {
return licenseUrl;
}
public void setLicenseUrl(String licenseUrl) {
this.licenseUrl = licenseUrl;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public static class Contact {
private String name;
private String url;
private String mail;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
}
| mit |
chenyiming/learn | dubbo-app/dubbo-app-web/src/main/java/com/wangsong/activiti/controller/BPMController.java | 3925 | package com.wangsong.activiti.controller;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wangsong.activiti.model.Leave;
import com.wangsong.activiti.service.ActivitiService;
import com.wangsong.activiti.service.LeaveService;
import com.wangsong.common.controller.BaseController;
import com.wangsong.common.model.Page;
import com.wangsong.common.util.ByteToInputStream;
import com.wangsong.common.util.UserUtil;
import com.wangsong.system.model.User;
/**
* 字典controller
* @author ty
* @date 2015年1月13日
*/
@Controller
@RequestMapping("activiti/bpm")
public class BPMController extends BaseController{
@Autowired
private ActivitiService workflowService;
/**
* 默认页面
*/
@RequestMapping(value="/toList")
public String list() {
return "activiti/bpm/list";
}
/**
* 获取字典json
*/
@RequestMapping(value="/list")
@ResponseBody
public Map<String, Object> dictList(HttpServletRequest request) {
Page<Map<String, Object>> page = getPage(request);
page= workflowService.findTaskListByUserId(page,((User)UserUtil.getUser()).getId().toString());
return getEasyUIData(page);
}
@RequestMapping(value="/commentList")
@ResponseBody
public Map<String, Object> list(HttpServletRequest request,String businessKey) {
Page<Map<String, Object>> page = getPage(request);
List<Map<String, Object>> commentList =workflowService.findCommentByBusinessKey(businessKey);
page.setResult(commentList);
page.setTotalCount(commentList.size());
return getEasyUIData(page);
}
/**
* 修改字典跳转
*
* @param id
* @param model
* @return
*/
@RequestMapping(value = "/toUpdate")
public String updateForm(String id, Model model) {
String url = workflowService.findTaskFormKeyByTaskId(id);
String sid = workflowService.findIdByTaskId(id);
return "redirect:"+url+"?id="+sid+"&display=yes";
}
@RequestMapping(value = "/toViewImage")
public String toViewImage(String taskId,Model model) {
ProcessDefinition pd = workflowService.findProcessDefinitionByTaskId(taskId);
model.addAttribute("deploymentId", pd.getDeploymentId());
model.addAttribute("diagramResourceName",pd.getDiagramResourceName());
Map<String, Object> map = workflowService.findCoordingByTaskId(taskId);
model.addAttribute("acs", map);
return "activiti/bpm/viewImage";
}
@RequestMapping(value="/viewImage")
public void viewImage(String deploymentId,String diagramResourceName,HttpServletResponse response) throws Exception{
//2:获取资源文件表(act_ge_bytearray)中资源图片输入流InputStream
byte[] bt= workflowService.findImageInputStream(deploymentId,diagramResourceName);
InputStream in = ByteToInputStream.byte2Input(bt);
//3:从response对象获取输出流
OutputStream out = response.getOutputStream();
//4:将输入流中的数据读取出来,写到输出流中
for(int b=-1;(b=in.read())!=-1;){
out.write(b);
}
out.close();
in.close();
//将图写到页面上,用输出流写
}
}
| mit |
pkdtheking/AI-aima-java-code | src/aima/probability/BayesNetNode.java | 2778 | /*
* Created on Jan 31, 2005
*
*/
package aima.probability;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* @author Ravi Mohan
*
*/
public class BayesNetNode {
private String variable;
List<BayesNetNode> parents, children;
ProbabilityDistribution distribution;
public BayesNetNode(String variable) {
this.variable = variable;
parents = new ArrayList<BayesNetNode>();
children = new ArrayList<BayesNetNode>();
distribution = new ProbabilityDistribution(variable);
}
private void addParent(BayesNetNode node) {
if (!(parents.contains(node))) {
parents.add(node);
}
}
private void addChild(BayesNetNode node) {
if (!(children.contains(node))) {
children.add(node);
}
}
public void influencedBy(BayesNetNode parent1) {
addParent(parent1);
parent1.addChild(this);
distribution = new ProbabilityDistribution(parent1.getVariable());
}
public void influencedBy(BayesNetNode parent1, BayesNetNode parent2) {
influencedBy(parent1);
influencedBy(parent2);
distribution = new ProbabilityDistribution(parent1.getVariable(),
parent2.getVariable());
}
public void setProbability(boolean b, double d) {
distribution.set(b, d);
if (isRoot()) {
distribution.set(!b, 1.0 - d);
}
}
private boolean isRoot() {
return (parents.size() == 0);
}
public void setProbability(boolean b, boolean c, double d) {
distribution.set(b, c, d);
}
public String getVariable() {
return variable;
}
public List<BayesNetNode> getChildren() {
return children;
}
public List<BayesNetNode> getParents() {
return parents;
}
@Override
public String toString() {
return variable;
}
public double probabilityOf(Hashtable conditions) {
return distribution.probabilityOf(conditions);
}
public Boolean isTrueFor(double probability,
Hashtable<String, Boolean> modelBuiltUpSoFar) {
Hashtable<String, Boolean> conditions = new Hashtable<String, Boolean>();
if (isRoot()) {
conditions.put(getVariable(), Boolean.TRUE);
} else {
for (int i = 0; i < parents.size(); i++) {
BayesNetNode parent = parents.get(i);
conditions.put(parent.getVariable(), modelBuiltUpSoFar
.get(parent.getVariable()));
}
}
double trueProbability = probabilityOf(conditions);
if (probability <= trueProbability) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (this.getClass() != o.getClass())) {
return false;
}
BayesNetNode another = (BayesNetNode) o;
return variable.equals(another.variable);
}
} | mit |
kbudisantoso/wcd-workinghours | wh.server/src/main/java/de/budisantoso/wcd/wh/persistence/repos/AccountRepository.java | 300 | package de.budisantoso.wcd.wh.persistence.repos;
import org.springframework.data.mongodb.repository.MongoRepository;
import de.budisantoso.wcd.wh.persistence.model.Account;
public interface AccountRepository extends MongoRepository<Account, String> {
Account findByUsername(String username);
}
| mit |
alv-ch/alv-ch-java | components-webapi/src/main/java/ch/alv/components/web/api/config/FormParameter.java | 390 | package ch.alv.components.web.api.config;
/**
* Parameter of a form description.
*
* @since 1.0.0
*/
public class FormParameter extends BaseParameter {
private static final long serialVersionUID = -3136563635062704105L;
public FormParameter() {
}
public FormParameter(String name, ParameterType type, boolean required) {
super(name, type, required);
}
}
| mit |
MiteshSharma/ContentApi | app/services/impl/UserService.java | 4570 | package services.impl;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.inject.Inject;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.DirectDecrypter;
import com.nimbusds.jose.crypto.MACSigner;
import controllers.CoreController;
import dispatcher.EventDispatcher;
import event_handler.EventName;
import exceptions.UserAuthException;
import exceptions.UserLoginFailedException;
import model.TeamMember;
import model.User;
import org.mindrot.jbcrypt.BCrypt;
import play.libs.Json;
import pojo.TeamObject;
import repository.IUserRepository;
import services.IJwtService;
import services.ITeamService;
import services.IUserService;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Created by mitesh on 16/11/16.
*/
public class UserService implements IUserService {
@Inject
IUserRepository userRepository;
@Inject
IJwtService jwtService;
@Inject
ITeamService teamService;
public User create(User user) {
user = userRepository.save(user);
Map<String, String> eventParam = CoreController.getBasicAnalyticsParam();
eventParam.put("userId", user.getId().toString());
eventParam.put("user_name", user.getName());
eventParam.put("email", user.getEmail());
eventParam.put("creation_time", (System.currentTimeMillis()/1000)+"");
EventDispatcher.dispatch(EventName.USER_CREATE, eventParam);
return user;
}
public User update(User user) {
user = userRepository.save(user);
Map<String, String> eventParam = CoreController.getBasicAnalyticsParam();
eventParam.put("userId", user.getId().toString());
eventParam.put("user_name", user.getName());
eventParam.put("email", user.getEmail());
EventDispatcher.dispatch(EventName.USER_UPDATE, eventParam);
return user;
}
public User get(String userId) {
return userRepository.getById(userId);
}
@Override
public User getByEmail(String email) {
return userRepository.get(email);
}
public User resetPassword(User user) {
user.setSupersedePassword(UUID.randomUUID().toString());
user = userRepository.save(user);
Map<String, String> eventParam = CoreController.getBasicAnalyticsParam();
eventParam.put("userId", user.getId().toString());
eventParam.put("email", user.getEmail());
EventDispatcher.dispatch(EventName.USER_PASSWORD_RESET, eventParam);
return user;
}
public boolean isUserExist(User user) {
return userRepository.get(user.getEmail(), user.getProjectId()) != null;
}
public User isValidLogin(User currentUser) {
User user = userRepository.get(currentUser.getEmail());
if (user == null) {
return null;
} else {
if ("Normal".equals(user.getType()) || user.getType() == null) {
if (user.getPasswordHash().equals(BCrypt.hashpw(currentUser.getPassword(), user.getSaltApplied()))) {
return user;
} else if (user.getSupersedePassword() != null && user.getSupersedePassword().equals(currentUser.getSupersedePassword())) {
return user;
}
} else {
if (user.getExternalId() != null && user.getExternalId().equals(currentUser.getExternalId())) {
return user;
}
}
}
return null;
}
@Override
public String login(User user) throws UserLoginFailedException {
ObjectNode jsonNode = Json.newObject();
jsonNode.put("userId", user.getId().toString());
List<TeamObject> teamObjects = this.teamService.getByUser(user.getId().toString());
ObjectNode projectNode = Json.newObject();
for (TeamObject teamObject : teamObjects) {
TeamMember teamMember = teamObject.getTeamMembers().stream().filter(tMember -> tMember.getUserId().equals(user.getId().toString())).findFirst().get();
projectNode.put(teamObject.getProjectId(), teamMember.getRole().toString());
}
jsonNode.put("project", projectNode.toString());
String jwt = jwtService.getJwtWithMessage(jsonNode.toString());
EventDispatcher.dispatch(EventName.USER_LOGIN, CoreController.getBasicAnalyticsParam());
return jwt;
}
@Override
public void logout() {
EventDispatcher.dispatch(EventName.USER_LOGOUT, CoreController.getBasicAnalyticsParam());
}
}
| mit |
vortexwolf/2ch-Browser | app/src/main/java/ua/in/quireg/chan/boards/makaba/MakabaUrlBuilder.java | 4467 | package ua.in.quireg.chan.boards.makaba;
import android.net.Uri;
import javax.inject.Inject;
import ua.in.quireg.chan.common.MainApplication;
import ua.in.quireg.chan.common.utils.StringUtils;
import ua.in.quireg.chan.interfaces.IUrlBuilder;
import ua.in.quireg.chan.settings.ApplicationSettings;
public class MakabaUrlBuilder implements IUrlBuilder {
@Inject protected ApplicationSettings mSettings;
private static final String[] CATALOG_FILTERS = { "catalog", "catalog_num" };
public MakabaUrlBuilder() {
MainApplication.getAppComponent().inject(this);
}
public String getBoardsUrl(){
return this.createRootUri("makaba/mobile.fcgi?task=get_boards").toString();
}
public String getPageUrlApi(String board, int pageNumber) {
String path = pageNumber == 0
? String.format("%s/index.json", board)
: String.format("%s/%s.json", board, String.valueOf(pageNumber));
return this.createRootUri(path).toString();
}
public String getPageUrlHtml(String board, int pageNumber) {
return this.createBoardUri(board, pageNumber == 0 ? null : pageNumber + ".html").toString();
}
public String getThreadUrlApi(String board, String number) {
String path = String.format("%s/res/%s.json", board, number);
return this.createRootUri(path).toString();
}
public String getThreadUrlExtendedApi(String board, String number, String from) {
String path = String.format("makaba/mobile.fcgi?task=get_thread&board=%s&thread=%s&num=%s&json=1", board, number, !StringUtils.isEmpty(from) ? from : number);
return this.createRootUri(path).toString();
}
public String getThreadUrlHtml(String board, String threadNumber) {
return this.createBoardUri(board, "res/" + threadNumber + ".html").toString();
}
public String getPostUrlHtml(String board, String threadNumber, String postNumber) {
return this.getThreadUrlHtml(board, threadNumber) + "#" + postNumber;
}
public String getCatalogUrlApi(String board, int filter) {
return this.createBoardUri(board, CATALOG_FILTERS[filter] + ".json").toString();
}
public String getCatalogUrlHtml(String board, int filter) {
return this.createBoardUri(board, CATALOG_FILTERS[filter] + ".html").toString();
}
public String getSearchUrlApi() {
return this.createRootUri("makaba/makaba.fcgi").toString();
}
public String getIconUrl(String path) {
return this.createRootUri(path).toString();
}
public String getThumbnailUrl(String board, String path) {
return this.createRootUri(path).toString();
}
public String getImageUrl(String board, String path) {
return this.createRootUri(path).toString();
}
public String getPostingUrlApi() {
return this.createRootUri("makaba/posting.fcgi?json=1").toString();
}
public String getPostingUrlHtml() {
return this.createRootUri("makaba/posting.fcgi").toString();
}
public String getCloudflareCheckUrl(String challenge, String response) {
return this.createRootUri("cdn-cgi/l/chk_captcha" + "?recaptcha_challenge_field=" + challenge + "&recaptcha_response_field=" + response).toString();
}
public String getPasscodeCheckUrl() {
return this.createRootUri("makaba/makaba.fcgi").toString();
}
@Override
public String getPasscodeCookieCheckUrl(String boardName, String threadNumber) {
Uri uri = this.createRootUri(
"/api/captcha/2chaptcha/id?board=" + boardName + "&thread=" + threadNumber);
return uri.toString();
}
@Override
public String getAppCaptchaCheckUrl(String publicKey) {
Uri uri = this.createRootUri("/api/captcha/app/id/" + publicKey);
return uri.toString();
}
public String makeAbsolute(String url) {
Uri uri = Uri.parse(url);
uri = uri.isRelative() ? this.createRootUri(url) : uri;
return uri.toString();
}
private Uri createBoardUri(String board, String path) {
return this.appendPath(this.createRootUri(board), path);
}
private Uri createRootUri(String path) {
return this.appendPath(this.mSettings.getDomainUri(), path);
}
private Uri appendPath(Uri baseUri, String path) {
path = path == null ? "" : path.replaceFirst("^/*", "");
return Uri.withAppendedPath(baseUri, path);
}
}
| mit |
cliffano/swaggy-jenkins | clients/jaxrs-resteasy-eap/generated/src/main/java/org/openapitools/api/impl/QueueApiServiceImpl.java | 754 | package org.openapitools.api.impl;
import org.openapitools.api.*;
import org.openapitools.model.*;
import org.openapitools.model.Queue;
import java.util.List;
import java.io.InputStream;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen", date = "2022-02-13T02:21:55.978017Z[Etc/UTC]")
public class QueueApiServiceImpl implements QueueApi {
public Response getQueue(SecurityContext securityContext) {
// do some magic!
return Response.ok().build();
}
public Response getQueueItem(String number,SecurityContext securityContext) {
// do some magic!
return Response.ok().build();
}
}
| mit |
asiaon123/examples | examples-distributed-system/distributed-system-compute/src/main/java/gyz/examples/distributedsystem/compute/package-info.java | 47 | package gyz.examples.distributedsystem.compute; | mit |
limpoxe/Android-Plugin-Framework | Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/e/a/A0.java | 8249 | package com.example.plugintest.manymethods.e.a;
public class A0 {
public static void a0(String msg) { System.out.println("msg=" + msg + 0); }
public static void a1(String msg) { System.out.println("msg=" + msg + 1); }
public static void a2(String msg) { System.out.println("msg=" + msg + 2); }
public static void a3(String msg) { System.out.println("msg=" + msg + 3); }
public static void a4(String msg) { System.out.println("msg=" + msg + 4); }
public static void a5(String msg) { System.out.println("msg=" + msg + 5); }
public static void a6(String msg) { System.out.println("msg=" + msg + 6); }
public static void a7(String msg) { System.out.println("msg=" + msg + 7); }
public static void a8(String msg) { System.out.println("msg=" + msg + 8); }
public static void a9(String msg) { System.out.println("msg=" + msg + 9); }
public static void a10(String msg) { System.out.println("msg=" + msg + 10); }
public static void a11(String msg) { System.out.println("msg=" + msg + 11); }
public static void a12(String msg) { System.out.println("msg=" + msg + 12); }
public static void a13(String msg) { System.out.println("msg=" + msg + 13); }
public static void a14(String msg) { System.out.println("msg=" + msg + 14); }
public static void a15(String msg) { System.out.println("msg=" + msg + 15); }
public static void a16(String msg) { System.out.println("msg=" + msg + 16); }
public static void a17(String msg) { System.out.println("msg=" + msg + 17); }
public static void a18(String msg) { System.out.println("msg=" + msg + 18); }
public static void a19(String msg) { System.out.println("msg=" + msg + 19); }
public static void a20(String msg) { System.out.println("msg=" + msg + 20); }
public static void a21(String msg) { System.out.println("msg=" + msg + 21); }
public static void a22(String msg) { System.out.println("msg=" + msg + 22); }
public static void a23(String msg) { System.out.println("msg=" + msg + 23); }
public static void a24(String msg) { System.out.println("msg=" + msg + 24); }
public static void a25(String msg) { System.out.println("msg=" + msg + 25); }
public static void a26(String msg) { System.out.println("msg=" + msg + 26); }
public static void a27(String msg) { System.out.println("msg=" + msg + 27); }
public static void a28(String msg) { System.out.println("msg=" + msg + 28); }
public static void a29(String msg) { System.out.println("msg=" + msg + 29); }
public static void a30(String msg) { System.out.println("msg=" + msg + 30); }
public static void a31(String msg) { System.out.println("msg=" + msg + 31); }
public static void a32(String msg) { System.out.println("msg=" + msg + 32); }
public static void a33(String msg) { System.out.println("msg=" + msg + 33); }
public static void a34(String msg) { System.out.println("msg=" + msg + 34); }
public static void a35(String msg) { System.out.println("msg=" + msg + 35); }
public static void a36(String msg) { System.out.println("msg=" + msg + 36); }
public static void a37(String msg) { System.out.println("msg=" + msg + 37); }
public static void a38(String msg) { System.out.println("msg=" + msg + 38); }
public static void a39(String msg) { System.out.println("msg=" + msg + 39); }
public static void a40(String msg) { System.out.println("msg=" + msg + 40); }
public static void a41(String msg) { System.out.println("msg=" + msg + 41); }
public static void a42(String msg) { System.out.println("msg=" + msg + 42); }
public static void a43(String msg) { System.out.println("msg=" + msg + 43); }
public static void a44(String msg) { System.out.println("msg=" + msg + 44); }
public static void a45(String msg) { System.out.println("msg=" + msg + 45); }
public static void a46(String msg) { System.out.println("msg=" + msg + 46); }
public static void a47(String msg) { System.out.println("msg=" + msg + 47); }
public static void a48(String msg) { System.out.println("msg=" + msg + 48); }
public static void a49(String msg) { System.out.println("msg=" + msg + 49); }
public static void a50(String msg) { System.out.println("msg=" + msg + 50); }
public static void a51(String msg) { System.out.println("msg=" + msg + 51); }
public static void a52(String msg) { System.out.println("msg=" + msg + 52); }
public static void a53(String msg) { System.out.println("msg=" + msg + 53); }
public static void a54(String msg) { System.out.println("msg=" + msg + 54); }
public static void a55(String msg) { System.out.println("msg=" + msg + 55); }
public static void a56(String msg) { System.out.println("msg=" + msg + 56); }
public static void a57(String msg) { System.out.println("msg=" + msg + 57); }
public static void a58(String msg) { System.out.println("msg=" + msg + 58); }
public static void a59(String msg) { System.out.println("msg=" + msg + 59); }
public static void a60(String msg) { System.out.println("msg=" + msg + 60); }
public static void a61(String msg) { System.out.println("msg=" + msg + 61); }
public static void a62(String msg) { System.out.println("msg=" + msg + 62); }
public static void a63(String msg) { System.out.println("msg=" + msg + 63); }
public static void a64(String msg) { System.out.println("msg=" + msg + 64); }
public static void a65(String msg) { System.out.println("msg=" + msg + 65); }
public static void a66(String msg) { System.out.println("msg=" + msg + 66); }
public static void a67(String msg) { System.out.println("msg=" + msg + 67); }
public static void a68(String msg) { System.out.println("msg=" + msg + 68); }
public static void a69(String msg) { System.out.println("msg=" + msg + 69); }
public static void a70(String msg) { System.out.println("msg=" + msg + 70); }
public static void a71(String msg) { System.out.println("msg=" + msg + 71); }
public static void a72(String msg) { System.out.println("msg=" + msg + 72); }
public static void a73(String msg) { System.out.println("msg=" + msg + 73); }
public static void a74(String msg) { System.out.println("msg=" + msg + 74); }
public static void a75(String msg) { System.out.println("msg=" + msg + 75); }
public static void a76(String msg) { System.out.println("msg=" + msg + 76); }
public static void a77(String msg) { System.out.println("msg=" + msg + 77); }
public static void a78(String msg) { System.out.println("msg=" + msg + 78); }
public static void a79(String msg) { System.out.println("msg=" + msg + 79); }
public static void a80(String msg) { System.out.println("msg=" + msg + 80); }
public static void a81(String msg) { System.out.println("msg=" + msg + 81); }
public static void a82(String msg) { System.out.println("msg=" + msg + 82); }
public static void a83(String msg) { System.out.println("msg=" + msg + 83); }
public static void a84(String msg) { System.out.println("msg=" + msg + 84); }
public static void a85(String msg) { System.out.println("msg=" + msg + 85); }
public static void a86(String msg) { System.out.println("msg=" + msg + 86); }
public static void a87(String msg) { System.out.println("msg=" + msg + 87); }
public static void a88(String msg) { System.out.println("msg=" + msg + 88); }
public static void a89(String msg) { System.out.println("msg=" + msg + 89); }
public static void a90(String msg) { System.out.println("msg=" + msg + 90); }
public static void a91(String msg) { System.out.println("msg=" + msg + 91); }
public static void a92(String msg) { System.out.println("msg=" + msg + 92); }
public static void a93(String msg) { System.out.println("msg=" + msg + 93); }
public static void a94(String msg) { System.out.println("msg=" + msg + 94); }
public static void a95(String msg) { System.out.println("msg=" + msg + 95); }
public static void a96(String msg) { System.out.println("msg=" + msg + 96); }
public static void a97(String msg) { System.out.println("msg=" + msg + 97); }
public static void a98(String msg) { System.out.println("msg=" + msg + 98); }
public static void a99(String msg) { System.out.println("msg=" + msg + 99); }
}
| mit |
koushik963/movieflix | server/movieflix/src/main/java/com/koushik/movieflix/repositry/TitleRepositry.java | 650 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.koushik.movieflix.repositry;
import com.koushik.movieflix.entity.Title;
import java.util.List;
/**
*
* @author koushik
*/
public interface TitleRepositry {
public void create(Title title);
public void edit(Title title);
public void destroy(Title title) ;
public List<Title> findTitleEntities();
public List<Title> findTitleEntities(boolean all, int maxResults, int firstResult);
public Title findTitle(Integer id);
}
| mit |
wubbleworld/wubble-world | src/edu/isi/wubble/jgn/message/WorldUpdateMessage.java | 6873 | package edu.isi.wubble.jgn.message;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;
import com.captiveimagination.jgn.message.Message;
import com.captiveimagination.jgn.message.type.PlayerMessage;
import edu.isi.wubble.jgn.db.DatabaseManager;
import edu.isi.wubble.jgn.sheep.SheepPhysicsState;
import edu.isi.wubble.jgn.sheep.Utils;
import edu.isi.wubble.jgn.sheep.entity.SDynamicEntity;
import edu.isi.wubble.jgn.sheep.entity.SEntity;
public class WorldUpdateMessage extends Message implements PlayerMessage {
// Quick and dirty stuff to decide when to write to DB.
public static int UPDATES_BEFORE_LOG = 30;
public static int _updateCount = 0;
public static int GetUpdateCount() { return _updateCount; }
public WorldUpdateMessage() {
_updateCount++;
// Create the hash of logged entities if it hasn't been created yet.
if (_logHash == null) {
_logHash = new HashMap<String, Boolean>();
}
}
private ArrayList<String> _names;
private ArrayList<String> _types;
private ArrayList<Long> _flags;
private ArrayList<Float> _x;
private ArrayList<Float> _y;
private ArrayList<Float> _z;
private ArrayList<Float> _rotX;
private ArrayList<Float> _rotY;
private ArrayList<Float> _rotZ;
private ArrayList<Float> _rotW;
public int getNumItems() {
int numItems = 0;
if (_names != null) {
numItems = _names.size();
}
return numItems;
}
public ArrayList<String> getNames() { return _names; }
public String getName(int i) { return _names.get(i); }
public void setNames(ArrayList<String> names) {
this._names = names;
}
public ArrayList<String> getTypes() { return _types; }
public String getType(int i) { return _types.get(i); }
public void setTypes(ArrayList<String> types) {
this._types = types;
}
public ArrayList<Long> getFlags() { return _flags; }
public Long getFlag(int i) { return _flags.get(i); }
public void setFlags(ArrayList<Long> flags) {
this._flags = flags;
}
public ArrayList<Float> getX() { return _x; }
public Float getX(int i) { return _x.get(i); }
public void setX(ArrayList<Float> x) {
this._x = x;
}
public ArrayList<Float> getY() { return _y; }
public Float getY(int i) { return _y.get(i); }
public void setY(ArrayList<Float> y) {
this._y = y;
}
public ArrayList<Float> getZ() { return _z; }
public Float getZ(int i) { return _z.get(i); }
public void setZ(ArrayList<Float> z) {
this._z = z;
}
public ArrayList<Float> getRotX() { return _rotX; }
public Float getRotX(int i) { return _rotX.get(i); }
public void setRotX(ArrayList<Float> rotX) {
this._rotX = rotX;
}
public ArrayList<Float> getRotY() { return _rotY; }
public Float getRotY(int i) { return _rotY.get(i); }
public void setRotY(ArrayList<Float> rotY) {
this._rotY = rotY;
}
public ArrayList<Float> getRotZ() { return _rotZ; }
public Float getRotZ(int i) { return _rotZ.get(i); }
public void setRotZ(ArrayList<Float> rotZ) {
this._rotZ = rotZ;
}
public ArrayList<Float> getRotW() { return _rotW; }
public Float getRotW(int i) { return _rotW.get(i); }
public void setRotW(ArrayList<Float> rotW) {
this._rotW = rotW;
}
public static HashMap<String, Boolean> _logHash;
public boolean isLogged(String name) {
boolean retVal = _logHash.containsKey(name);
return retVal;
}
// Indicate to the log that this entity has been removed from the world.
public static long REMOVE = 1;
public static void LogRemove(SEntity e) {
long time = System.currentTimeMillis();
String name = e.getName();
long flags = REMOVE;
SheepPhysicsState sps = Utils.GetSps();
// DatabaseManager dbm = sps.getSheepDB();
//
// try {
// String sql = "insert into sheep_log (update_index, name, flags, time) values (0, '" + name + "', " + flags + ", " + time + ")";
// //System.out.println("logRemove: " + sql);
// Statement s = dbm.getStatement();
// s.executeUpdate(sql);
//
// // Clear this entity from the log hash.
// _logHash.remove(name);
// }
// catch (Exception x) {
// Logger.getLogger("").severe("Database error!");
// x.printStackTrace();
// }
}
// Read in the changeset of all entities active at the given update index.
public void readFromDb(long updateTime) {
//System.out.println("readFromDB: looking for index " + updateTime);
String sql = "select name, type, flags, x_rot, y_rot, z_rot, w_rot, x_pos, y_pos, z_pos from sheep_log where time = " + updateTime;
SheepPhysicsState sps = Utils.GetSps();
DatabaseManager dbm = sps.getSheepDB();
// Create the arraylists for the elements active in this update.
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> types = new ArrayList<String>();
ArrayList<Long> flags = new ArrayList<Long>();
ArrayList<Float> rx = new ArrayList<Float>();
ArrayList<Float> ry = new ArrayList<Float>();
ArrayList<Float> rz = new ArrayList<Float>();
ArrayList<Float> rw = new ArrayList<Float>();
ArrayList<Float> px = new ArrayList<Float>();
ArrayList<Float> py = new ArrayList<Float>();
ArrayList<Float> pz = new ArrayList<Float>();
try {
Statement s = dbm.getStatement();
s.execute(sql);
ResultSet rs = s.getResultSet();
// Go to the first result.
while(rs.next()) {
String name = rs.getString("name");
String type = rs.getString("type");
Long flag = rs.getLong("flags");
float x_rot = rs.getFloat("x_rot");
float y_rot = rs.getFloat("y_rot");
float z_rot = rs.getFloat("z_rot");
float w_rot = rs.getFloat("w_rot");
float x_pos = rs.getFloat("x_pos");
float y_pos = rs.getFloat("y_pos");
float z_pos = rs.getFloat("z_pos");
// Add all this stuff to the appropriate fields of the update msg.
names.add(name);
types.add(type);
flags.add(flag);
rx.add(x_rot);
ry.add(y_rot);
rz.add(z_rot);
rw.add(w_rot);
px.add(x_pos);
py.add(y_pos);
pz.add(z_pos);
}
}
catch (Exception x) {
Logger.getLogger("").severe("Database error!");
x.printStackTrace();
}
// Set the instance variables of this update msg.
_names = names;
_types = types;
_flags = flags;
_x = px;
_y = py;
_z = pz;
_rotX = rx;
_rotY = ry;
_rotZ = rz;
_rotW = rw;
}
@Override
// Right now toString just tells the names of the entities contained in the update.
public String toString() {
String retVal = "";
int numItems = _names.size();
for (int i=0; i<numItems; i++) {
String name = _names.get(i);
retVal = retVal + "\n" + name;
}
return retVal;
}
}
| mit |
gavilancomun/irc-explorer | src/main/java/gavilan/irc/webmvc/FeaturesController.java | 1140 | package gavilan.irc.webmvc;
import gavilan.irc.Cron;
import gavilan.irc.Features;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FeaturesController {
private final Features features;
private final Cron cron;
@Autowired
public FeaturesController(Features features, Cron cron) {
this.features = features;
this.cron = cron;
}
@RequestMapping(value = "/get/features", method = RequestMethod.GET)
public Map<String, Boolean> features() {
return features.getFeatures();
}
@RequestMapping(value = "/command/toggle/{feature}", method = RequestMethod.GET)
public Map<String, Boolean> toggle(@PathVariable String feature) {
features.setFeature(feature, !features.hasFeature(feature));
if ("cron".equals(feature)) {
cron.updateCron();
}
return features.getFeatures();
}
}
| mit |
adetalhouet/MOM | app/src/com/onmobile/mom/accountmanager/MyAccount.java | 1964 | package com.onmobile.mom.accountmanager;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.util.Log;
import com.onmobile.mom.app.Config;
/**
* This class manage the creation of an {@link Account}. The will allow to
* create a calendar and an other contact raw.
*
* @author adetalouet
*/
public abstract class MyAccount {
/**
* Tag to debug
*/
private static final String TAG = "MyAccountManager - ";
/**
* The Android user account
*/
private static Account mAccount;
/**
* This function creates an {@link Account} and add it to the
* {@link AccountManager}. The ACCOUNT_NAME and ACCOUNT_TYPE can be set in
* the {@link Config} class.
*
* @param context - the context of the test case
*/
public static void createAccount(Context context) {
mAccount = new Account(Config.ACCOUNT_NAME, Config.ACCOUNT_TYPE);
AccountManager am = AccountManager.get(context);
boolean accountCreated = am.addAccountExplicitly(mAccount,
null, null);
Log.d(Config.TAG_APP, TAG + "Account created: " + (accountCreated ? true : false + ". The account already exist"));
}
/**
* This function deletes the created {@link Account}.
* <p/>
* TODO Doesn't work for now
*
* @param context - the context of the test case
*/
public static void deleteAccount(Context context) {
AccountManager am = AccountManager.get(context);
am.removeAccount(mAccount, null, null);
Account[] accounts = am.getAccounts();
for (Account aAccount : accounts)
if (aAccount.name == Config.ACCOUNT_NAME)
Log.d(Config.TAG_APP, TAG + "Account not deleted");
else
Log.d(Config.TAG_APP, TAG + "Account deleted");
}
}
| mit |
webratio/typescript.java | eclipse/jsdt/ts.eclipse.ide.jsdt.ui/src/ts/eclipse/ide/jsdt/internal/ui/editor/contentassist/JSDTTypeScriptCompletionProposal.java | 919 | package ts.eclipse.ide.jsdt.internal.ui.editor.contentassist;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wst.jsdt.ui.text.java.IJavaCompletionProposal;
import ts.client.ITypeScriptServiceClient;
import ts.client.completions.ICompletionEntryMatcher;
import ts.eclipse.ide.jsdt.internal.ui.JSDTTypeScriptUIPlugin;
import ts.eclipse.jface.text.contentassist.TypeScriptCompletionProposal;
public class JSDTTypeScriptCompletionProposal extends TypeScriptCompletionProposal implements IJavaCompletionProposal {
public JSDTTypeScriptCompletionProposal(ICompletionEntryMatcher matcher, String fileName, int line, int offset,
ITypeScriptServiceClient client, int position, String prefix) {
super(matcher, fileName, line, offset, client, position, prefix);
}
@Override
protected Shell getActiveWorkbenchShell() {
return JSDTTypeScriptUIPlugin.getActiveWorkbenchShell();
}
}
| mit |
rishabh1403/java-code-samples | data_structure/linkedlist/linkedlist.java | 2593 | import java.util.*;
//Here goes node class
//it contains next node and data in it
class Node{
private Node next;
private int data;
public Node(int data){
this.data = data;
this.next = null;
}
public int getData(){
return this.data;
}
public void setData(int data){
this.data = data;
}
public Node getNext(){
return this.next;
}
public void setNext(Node next){
this.next = next;
}
}
// main list class
// here all function goes
class list {
private Node head;
public list(){
this.head = null;
}
public list(int data){
head = new Node(data);
}
public void traverse(){
Node temp = head;
if(head == null)
System.out.println("list is empty");
else{
while(temp != null){
System.out.println(temp.getData());
temp = temp.getNext();
}
}
}
public boolean isEmpty(){
return ((head==null)?true:false);
}
public void addFirst(int data){
if(isEmpty())
head = new Node(data);
else{
Node temp = new Node(data);
temp.setNext(head);
head = temp;
}
}
public void addAfter(int data , int newData){
if(isEmpty())
System.out.println("Empty list , no data matching");
else{
Node temp = head;
while(temp != null ){
if(temp.getData() == data){
Node temp2 = new Node(newData);
temp2.setNext(temp.getNext());
temp.setNext(temp2);
//System.out.println("setting node");
break;
}
temp = temp.getNext();
}
System.out.println((temp == null ) ? "No data found" : "Data inserted");
}
}
public void addAtPosition(int index , int data){
if(isEmpty())
head = new Node(data);
else{
Node temp = head;
for(int i=0;i<index;i++)
temp = temp.getNext();
Node T2 = new Node(data);
t2.setNext(temp.getNext());
temp.setNext(T2);
}
}
}
public class linkedlist{
public static void main(String args[]){
list l = new list(4);
//l.traverse();
l.addFirst(5);
l.addFirst(6);
//l.traverse();
l.addAfter(8,12);
//l.traverse();
l.addAfter(5,13);
l.addAfter(4,8);
}
}
| mit |
michaldo/spring-single-context-demo | src/main/java/q/Q.java | 562 | package q;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class Q {
@RequestMapping
@ResponseBody
public String q(@AuthenticationPrincipal Authentication currentUser ) {
return "Hello " + currentUser.getName();
}
}
| mit |
sensorberg-dev/android-sdk | android-sdk/src/androidTest/java/com/sensorberg/sdk/model/server/TheTimeFrameShould.java | 1278 | package com.sensorberg.sdk.model.server;
import org.fest.assertions.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import android.support.test.runner.AndroidJUnit4;
@RunWith(AndroidJUnit4.class)
public class TheTimeFrameShould {
@Test
public void be_valid_when_start_time_is_null() throws Exception {
Timeframe tested = new Timeframe(null, 1000L);
Assertions.assertThat(tested.valid(1)).isTrue();
Assertions.assertThat(tested.valid(1000)).isTrue();
Assertions.assertThat(tested.valid(1001)).isFalse();
}
@Test
public void be_valid_when_end_time_is_null() throws Exception {
Timeframe tested = new Timeframe(1000L, null);
Assertions.assertThat(tested.valid(1)).isFalse();
Assertions.assertThat(tested.valid(1000)).isTrue();
Assertions.assertThat(tested.valid(1001)).isTrue();
}
@Test
public void answer_correctly_with_both_values() throws Exception {
Timeframe tested = new Timeframe(0L, 1000L);
Assertions.assertThat(tested.valid(-1)).isFalse();
Assertions.assertThat(tested.valid(1)).isTrue();
Assertions.assertThat(tested.valid(1000)).isTrue();
Assertions.assertThat(tested.valid(1001)).isFalse();
}
}
| mit |
DonkeyCore/MinigameManager | src/main/java/minigamemanager/config/PlayerProfileConfiguration.java | 2238 | package minigamemanager.config;
import org.bukkit.configuration.ConfigurationSection;
import minigamemanager.api.config.CustomConfig;
import minigamemanager.api.profile.PlayerProfile;
import minigamemanager.api.profile.ProfileData;
import minigamemanager.core.MinigameManager;
/**
* Class for profiles of players
*
* @author DonkeyCore
*/
public class PlayerProfileConfiguration extends CustomConfig {
/**
* Create a new instance of MinigameLocations
*/
public PlayerProfileConfiguration() {
super(MinigameManager.getPlugin(), MinigameManager.getPlugin().getDataFolder(), "profiles.yml");
}
/**
* Create data for a profile based on config
*
* @param profile The PlayerProfile instance to retrieve data for
*
* @return An instance of ProfileData
*/
public ProfileData getProfileData(PlayerProfile profile) {
ProfileData data = new ProfileData();
ConfigurationSection cs = getConfig().getConfigurationSection(profile.getUUID().toString());
MinigameSettings settings = MinigameManager.getMinigameManager().getMinigameSettings();
if (cs == null) {
data.setELO(settings.defaultELO());
return data;
}
if (settings.eloEnabled())
data.setELO(cs.getLong("elo"));
if (!settings.vaultEnabled())
data.setCurrency(cs.getDouble("currency"));
data.setGamesPlayed(cs.getLong("gamesPlayed"));
data.setAchievements(ProfileData.getAchievementsFromString(cs.getString("achievements")));
return data;
}
/**
* Save a profile to the config
*
* @param profile The profile to save
*/
public void saveProfile(PlayerProfile profile) {
ProfileData data = profile.getData();
ConfigurationSection cs = getConfig().getConfigurationSection(profile.getUUID().toString());
if (cs == null) {
getConfig().createSection(profile.getUUID().toString());
cs = getConfig().getConfigurationSection(profile.getUUID().toString());
}
MinigameSettings settings = MinigameManager.getMinigameManager().getMinigameSettings();
if (settings.eloEnabled())
cs.set("elo", data.getELO());
if (!settings.vaultEnabled())
cs.set("currency", data.getCurrency());
cs.set("gamesPlayed", data.getGamesPlayed());
cs.set("achievements", data.getAchievementString());
saveConfig();
}
}
| mit |
Miskerest/Hasher | app/src/main/java/com/misker/mike/hasher/Main.java | 10147 | package com.misker.mike.hasher;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class Main extends AppCompatActivity implements MainView {
private static final int READ_REQUEST_CODE = 42;
private ClipboardManager clipboard;
private Uri fileURI;
private String hashtype = "MD5";
@BindView(R.id.hashOutput)
TextView hashOutput;
@BindView(R.id.progress)
ProgressBar progress;
@BindView(R.id.hashButton)
Button hashButton;
@BindView(R.id.hashCmpButton)
Button hashCmpButton;
@BindView(R.id.hashText)
TextView hashText;
@BindView(R.id.adView)
AdView mAdView;
@BindView(R.id.fileButton)
Button fileButton;
@BindView(R.id.activity_main)
View contentView;
@BindView(R.id.hashSelectionSpinner)
Spinner selector;
@BindView(R.id.tabs)
TabLayout tabs;
@BindView(R.id.viewpager)
ViewPager pager;
@BindString(R.string.banner_ad_unit_id)
String ad_unit_id;
@BindView(R.id.shareHashBtn)
FloatingActionButton shareHashBtn;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//ad init
MobileAds.initialize(this, ad_unit_id);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
setupFileHashPane(getApplicationContext());
}
private void showFileViews(){
fileButton.setVisibility(View.VISIBLE);
hashText.setVisibility(View.INVISIBLE);
hashButton.setEnabled(false);
}
private void showTextViews() {
fileButton.setVisibility(View.INVISIBLE);
hashText.setVisibility(View.VISIBLE);
hashButton.setEnabled(true);
}
private void setupFileHashPane(Context context){
clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//setup tabs
FixedTabsPagerAdapter adapter = new FixedTabsPagerAdapter(getSupportFragmentManager());
adapter.setContext(context);
pager.setAdapter(adapter);
tabs.setupWithViewPager(pager);
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
try {
closeKeyboard();
}
catch (NullPointerException e){
Log.e("CloseKeyboard NPE", Objects.requireNonNull(e.getMessage()));
}
if(tab.getPosition() == 1) {
showTextViews();
}
else {
showFileViews();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
fileButton.setVisibility(View.VISIBLE);
hashText.setVisibility(View.INVISIBLE);
hashButton.setEnabled(true);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//set visibility and initialize labels/buttons
hashCmpButton.setText(getString(R.string.compare_hashes));
hashButton.setEnabled(false);
progress.setVisibility(View.INVISIBLE);
shareHashBtn.hide();
//Done setting up
fileButton.setOnClickListener(v -> showFileChooser());
// handlers for comparing hash text when hashCmpText is clicked
hashCmpButton.setOnClickListener(view -> compareHashes());
selector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
hashtype = adapterView.getItemAtPosition(i).toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
}
private void closeKeyboard() {
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager == null || getCurrentFocus() == null)
return;
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
@OnClick(R.id.hashButton)
public void hashButtonClick() {
if(fileButton.getVisibility() == View.VISIBLE) {
ContentResolver cr = getContentResolver();
HashRunnable hasher = new HashRunnable(hashtype, cr, this);
hasher.execute(fileURI);
}
else if(hashText.getVisibility() == View.VISIBLE){
String toHash = hashText.getText().toString();
HashRunnable hasher = new HashRunnable(hashtype, toHash, this);
hasher.execute(fileURI);
}
closeKeyboard();
hashCmpButton.setText(R.string.compare_hashes);
hashCmpButton.setTextColor(Color.WHITE);
shareHashBtn.show();
}
@OnClick(R.id.shareHashBtn)
public void shareHash() {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, hashOutput.getText().toString());
startActivity(Intent.createChooser(sendIntent, "Share this hash..."));
}
private void compareHashes(){
Toast toast;
Context context = getApplicationContext();
if(!clipboard.hasPrimaryClip()){
toast = Toast.makeText(context, R.string.emptyClipboard, Toast.LENGTH_SHORT);
toast.show();
return;
}
hashCmpButton.setText(Objects.requireNonNull(clipboard.getPrimaryClip())
.getItemAt(0).coerceToText(getApplicationContext()).toString().toLowerCase());
if(hashCmpButton.getText().toString().toUpperCase()
.equals(hashOutput.getText().toString().toUpperCase())) {
toast = Toast.makeText(context, getString(R.string.hashesMatch), Toast.LENGTH_SHORT);
hashCmpButton.setTextColor(Color.GREEN);
toast.show();
}
else {
toast = Toast.makeText(context, getString(R.string.hashesDontMatch), Toast.LENGTH_SHORT);
hashCmpButton.setTextColor(Color.RED);
toast.show();
}
}
/* File chooser for selecting files */
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
/* For selecting files for file-hashing */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK && resultData != null) {
fileURI = resultData.getData();
//grant permission in advance to prevent SecurityException
try {
grantUriPermission(getPackageName(), fileURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
catch (NullPointerException e) {
Toast toast = Toast.makeText(getApplicationContext(),
"Failed to get file reading permissions.", Toast.LENGTH_SHORT);
toast.show();
return;
}
// Check for the freshest data.
try {
getContentResolver().takePersistableUriPermission(fileURI,
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
catch (SecurityException e) {
Toast toast = Toast.makeText(getApplicationContext(),
"Opening file failed- report to developer!", Toast.LENGTH_SHORT);
toast.show();
return;
}
ContentResolver cr = getContentResolver();
try {
InputStream is = cr.openInputStream(fileURI);
if(is != null)
hashButton.setEnabled(true);
}
catch (FileNotFoundException e) {
Log.e("FileDebug", Objects.requireNonNull(e.getMessage()));
}
}
}
public void displayWaitProgress() {
progress.setVisibility(View.VISIBLE);
hashOutput.setText(R.string.waitText);
}
public void displayResults(String results) {
progress.setVisibility(View.INVISIBLE);
hashOutput.setText(results.toUpperCase());
}
} | mit |
jimmyblylee/ESH | src/framework/dispatcher/src/main/java/com/lee/jwaf/dto/bind/package-info.java | 1128 | /* ***************************************************************************
* EZ.JWAF/EZ.JCWAP: Easy series Production.
* Including JWAF(Java-based Web Application Framework)
* and JCWAP(Java-based Customized Web Application Platform).
* Copyright (C) 2016-2017 the original author or authors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of MIT License as published by
* the Free Software Foundation;
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the MIT License for more details.
*
* You should have received a copy of the MIT License along
* with this library; if not, write to the Free Software Foundation.
* ***************************************************************************/
/**
* ClassName : package-info <br>
* Description : the bean which implements aware interface will be set dto <br>
* Create Time : 2016-09-18 <br>
* Create by : jimmyblylee@126.com
*/
package com.lee.jwaf.dto.bind;
| mit |
BinEP/Games | ScoreInfo.java | 3561 | package utilityClasses;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.lang.Class;
public class ScoreInfo {
private String gameName;
public ScoreInfo(String gN) {
gameName = gN;
}
public void setScores(int score, String person) {
String gameScores = gameName.concat("Scores.txt");
String gamePeople = gameName.concat("People.txt");
try {
Scanner scoreContents = new Scanner(new File(gameScores));
ArrayList<Integer> scores = new ArrayList<Integer>();
while (scoreContents.hasNext()) {
scores.add(Integer.parseInt(scoreContents.next()));
}
scores.add(score);
// ///////////////////////////////////////////////////////////
Scanner peopleContents = new Scanner(new File(gamePeople));
ArrayList<String> people = new ArrayList<String>();
while (peopleContents.hasNext()) {
people.add(peopleContents.next());
}
people.add(person);
ArrayList<String[]> results = scoreOrder(scores, people);
PrintWriter scoreWriter = new PrintWriter(new FileWriter(gameScores));
PrintWriter peopleWriter = new PrintWriter(new FileWriter(gamePeople));
for (String[] sp : results) {
scoreWriter.println(sp[0]);
peopleWriter.println(sp[1]);
}
peopleWriter.flush();
scoreWriter.flush();
peopleWriter.close();
scoreWriter.close();
scoreContents.close();
peopleContents.close();
} catch (IOException e) {
}
}
public ArrayList<String[]> getScores() {
String gameScores = gameName.concat("Scores.txt");
String gamePeople = gameName.concat("People.txt");
try {
Scanner scoreContents = new Scanner(new File(gameScores));
ArrayList<Integer> scores = new ArrayList<Integer>();
while (scoreContents.hasNext()) {
scores.add(Integer.parseInt(scoreContents.next()));
}
Scanner peopleContents = new Scanner(new File(gamePeople));
ArrayList<String> people = new ArrayList<String>();
while (peopleContents.hasNext()) {
people.add(peopleContents.next());
}
ArrayList<String[]> results = new ArrayList<String[]>();
for (int i = 0; i < people.size(); i++) {
String[] hs = {scores.get(i).toString(), people.get(i)};
results.add(hs);
}
scoreContents.close();
peopleContents.close();
return results;
} catch (FileNotFoundException e) {
ArrayList<String[]> n = new ArrayList<String[]>();
String[] m = {"0", "UNK"};
n.add(m);
return n;
}
}
public ArrayList<String[]> scoreOrder(ArrayList<Integer> scores,
ArrayList<String> people) {
ArrayList<String[]> results = new ArrayList<String[]>();
for (int i = 0; i < people.size(); i++) {
String[] sp = { scores.get(i).toString(), people.get(i) };
results.add(sp);
}
Collections.sort(results, new Comparator<String[]>() {
@Override
public int compare(String[] person1, String[] person2) {
return person1[1].compareTo(person2[1]);
}
});
Collections.sort(results, new Comparator<String[]>() {
@Override
public int compare(String[] score1, String[] score2) {
return Integer.parseInt(score2[0])
- Integer.parseInt(score1[0]);
}
});
return results;
}
// public static void main(String[] args) {
//
// ScoreInfo SI = new ScoreInfo("hole");
// ArrayList<String[]> scores = SI.getScores();
// SI.setScores(10, "BradyTest1");
// System.out.println();
//
// }
}
| mit |
ThaynanAndrey/Projeto-SI1 | src/main/java/br/edu/ufcg/computacao/si1/model/anuncio/Anuncio.java | 5164 | package br.edu.ufcg.computacao.si1.model.anuncio;
import javax.persistence.*;
import br.edu.ufcg.computacao.si1.model.usuario.Usuario;
import java.util.Date;
/**
* Classe abstrata para objetos do tipo Anuncio, onde serão contidos valores e métodos para o mesmo.
*
* @author Thaynan Andrey
* @author Giuseppe Mongiovi
*/
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Anuncio {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "anuncio_id", nullable = false, unique = true)
private Long _id;
@Column(name = "titulo", nullable = false)
private String titulo;
@Column(name = "quantia", nullable = false)
private double quantia;
@Column(name = "data_criacao", nullable = false)
private Long dataDeCriacao;
private int diasDeVidaUtil;
@ManyToOne
@JoinColumn(name="usuario_id")
private Usuario dono;
/**
* Construtor default
*/
public Anuncio() {
titulo = "";
dataDeCriacao = new Date().getTime();
quantia = 0;
}
/**
* Construtor do objeto
*/
public Anuncio(String titulo, double quantia, Usuario dono, Long dataDeCriacao, int diasDeVidaUtil) {
this.titulo = titulo;
this.quantia = quantia;
this.dataDeCriacao = dataDeCriacao;
this.dono = dono;
this.diasDeVidaUtil = diasDeVidaUtil;
}
/**
* Metodo para retorno da quantidade de dias de vida útil do anúncio
* @return int - Quantidade de dias de vida útil do anúncio.
*/
public int getDiasDeVidaUtil() {
return diasDeVidaUtil;
}
/**
* Metodo para alteracao da quantidade de dias de vida útil do anúncio
* @param int diasDeVidaUtil - Quantidade de dias de vida útil do anúncio.
*/
public void setDiasDeVidaUtil(int diasDeVidaUtil) {
this.diasDeVidaUtil = diasDeVidaUtil;
}
/**
* Metodo abstrato para retorno do tipo do anúncio que deve ser implementado nas subclasses.
* @return String - Tipo do anuncio.
*/
public abstract String getTipo();
/**
* Metodo para alteracao do dono do anúncio
* @param Usuario dono = dono do anuncio.
*/
public void setDono(Usuario dono) {
this.dono = dono;
}
public Usuario pegueDono() {
return this.dono;
}
/**
* Metodo para retorno do id do anúncio
* @return Long id - o id do anuncio
*/
public Long get_id() {
return _id;
}
/**
* Metodo para alteracao do id do anúncio
* @param long _id - id a ser colocado no anuncio
*/public void set_id(Long _id) {
this._id = _id;
}
/**
* Metodo para retorno do titulo do anúncio
* @return String - Titulo do anuncio.
*/
public String getTitulo() {
return titulo;
}
/**
* Metodo para alteracao do titulo do anúncio
* @param String titulo - Titulo do anuncio.
*/
public void setTitulo(String titulo) {
this.titulo = titulo;
}
/**
* Metodo para retorno da data de criação do anúncio
* @return String - Data de criacao do anuncio.
*/
public Long getDataDeCriacao() {
return dataDeCriacao;
}
/**
* Metodo para alteracao da data de criação do anúncio
* @param String dataDeCriacao - Data de criacao do anuncio.
*/
public void setDataDeCriacao(Long dataDeCriacao) {
this.dataDeCriacao = dataDeCriacao;
}
/**
* Metodo para retorno do preço do anúncio
* @return Double - Valor ou salario referente ao anuncio.
*/
public double getQuantia() {
return quantia;
}
/**
* Metodo para alteracao do preço do anúncio
* @param Double quantia - Valor ou salario referente ao anuncio.
*/
public void setQuantia(double quantia) {
this.quantia = quantia;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Anuncio)) return false;
Anuncio anuncio = (Anuncio) o;
if (Double.compare(anuncio.getQuantia(), getQuantia()) != 0) return false;
if (!get_id().equals(anuncio.get_id())) return false;
if (!getTitulo().equals(anuncio.getTitulo())) return false;
if (!getDataDeCriacao().equals(anuncio.getDataDeCriacao())) return false;
return getTipo().equals(anuncio.getTipo());
}
@Override
public int hashCode() {
int result;
long temp;
result = get_id().hashCode();
result = 31 * result + getTitulo().hashCode();
result = 31 * result + getDataDeCriacao().hashCode();
temp = Double.doubleToLongBits(getQuantia());
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + getTipo().hashCode();
return result;
}
@Override
public String toString() {
return "Anuncio{" +
"_id=" + _id +
", titulo='" + titulo + '\'' +
", dataDeCriacao=" + getDataDeCriacao() +
", quantia=" + quantia +
'}';
}
}
| mit |
phil-lopreiato/the-blue-alliance-android | android/src/test/java/com/thebluealliance/androidclient/di/MockDatafeedModule.java | 5262 | package com.thebluealliance.androidclient.di;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.thebluealliance.androidclient.api.ApiConstants;
import com.thebluealliance.androidclient.api.rx.TbaApiV2;
import com.thebluealliance.androidclient.api.rx.TbaApiV3;
import com.thebluealliance.androidclient.database.Database;
import com.thebluealliance.androidclient.datafeed.APICache;
import com.thebluealliance.androidclient.datafeed.CacheableDatafeed;
import com.thebluealliance.androidclient.datafeed.HttpModule;
import com.thebluealliance.androidclient.datafeed.refresh.RefreshController;
import com.thebluealliance.androidclient.datafeed.retrofit.FirebaseAPI;
import com.thebluealliance.androidclient.datafeed.retrofit.GitHubAPI;
import com.thebluealliance.androidclient.datafeed.retrofit.LenientGsonConverterFactory;
import com.thebluealliance.androidclient.datafeed.status.TBAStatusController;
import com.thebluealliance.androidclient.fragments.FirebaseTickerFragment;
import org.mockito.Mockito;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import static org.mockito.Mockito.when;
@Module(includes = MockTbaAndroidModule.class)
public class MockDatafeedModule {
@Provides @Singleton @Named("tba_retrofit")
public Retrofit provideTBARetrofit(
Gson gson,
OkHttpClient okHttpClient,
SharedPreferences prefs) {
return new Retrofit.Builder()
.baseUrl(ApiConstants.TBA_URL)
.client(okHttpClient)
.addConverterFactory(LenientGsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
@Provides @Singleton @Named("github_retrofit")
public Retrofit provideGithubRetrofit(
Gson gson,
OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.client(okHttpClient)
.addConverterFactory(LenientGsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
@Provides @Singleton @Named("tba_api")
public TbaApiV2 provideRxTBAAPI(@Named("tba_retrofit") Retrofit retrofit) {
return Mockito.mock(TbaApiV2.class);
}
@Provides @Singleton @Named("tba_apiv3_rx")
public TbaApiV3 provideRxApiv3() {
return Mockito.mock(TbaApiV3.class);
}
@Provides @Singleton @Named("tba_apiv3_call")
public com.thebluealliance.androidclient.api.call.TbaApiV3 provideCallApiV3() {
return Mockito.mock(com.thebluealliance.androidclient.api.call.TbaApiV3.class);
}
@Provides @Singleton
public com.thebluealliance.androidclient.api.call.TbaApiV2 provideTBAAPI(@Named("tba_retrofit") Retrofit retrofit) {
return Mockito.mock(com.thebluealliance.androidclient.api.call.TbaApiV2.class);
}
@Provides @Singleton @Named("github_api")
public GitHubAPI provideGitHubAPI(@Named("github_retrofit") Retrofit retrofit) {
return Mockito.mock(GitHubAPI.class);
}
@Provides @Singleton @Named("firebase_retrofit")
public Retrofit provideFirebaseRetrofit(Context context, Gson gson, OkHttpClient okHttpClient) {
String firebaseUrl = FirebaseTickerFragment.FIREBASE_URL_DEFAULT;
return new Retrofit.Builder()
.baseUrl(firebaseUrl)
.client(okHttpClient)
.addConverterFactory(LenientGsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
@Provides @Singleton @Named("firebase_api")
public FirebaseAPI provideFirebaseAPI(@Named("firebase_retrofit") Retrofit retrofit) {
return Mockito.mock(FirebaseAPI.class);
}
@Provides @Singleton
public Gson provideGson() {
return HttpModule.getGson();
}
@Provides @Singleton
public Cache provideOkCache(Context context) {
return new Cache(context.getCacheDir(), HttpModule.CACHE_SIZE);
}
@Provides @Singleton
public OkHttpClient getOkHttp(Cache responseCache) {
return Mockito.mock(OkHttpClient.class);
}
@Provides @Singleton
public APICache provideApiCache(Database db) {
return Mockito.mock(APICache.class);
}
@Provides @Singleton
public CacheableDatafeed provideDatafeed(APICache cache) {
CacheableDatafeed df = Mockito.mock(CacheableDatafeed.class);
when(df.getCache()).thenReturn(cache);
return df;
}
@Provides @Singleton
public RefreshController provideRefreshController() {
return Mockito.mock(RefreshController.class);
}
@Provides @Singleton
public TBAStatusController provideTbaStatusController(SharedPreferences prefs, Gson gson,
Cache cache, Context context) {
return Mockito.mock(TBAStatusController.class);
}
}
| mit |
dr-chase-g3ka1/Progtech_Korny_beadando | src/main/java/model/character/spellcaster/spell/SpellRangeEnum.java | 383 | /*
* 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 model.character.spellcaster.spell;
/**
*
* @author Dr.Chase
*/
public enum SpellRangeEnum {
VISIBILITY, //caster must see target
TOUCH //caster must touch target
}
| mit |
muzir/Kek | src/main/java/com/muzir/kek/enums/DoneStatus.java | 269 | package com.muzir.kek.enums;
/**
* @author erhun.baycelik
*
*/
public enum DoneStatus {
TODO("0"), DONE("1");
private DoneStatus(String _value) {
value = _value;
}
public String getValue() {
return value;
}
private String value;
}
| mit |
gazbert/bxbot-ui-server | bxbot-ui-server-core/src/main/java/com/gazbert/bxbot/ui/server/BXBotUIServer.java | 1707 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Gareth Jon Lynch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.gazbert.bxbot.ui.server;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* BX-bot UI Server - here be the main boot app.
*
* @author gazbert
*/
@SpringBootApplication
public class BXBotUIServer implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(BXBotUIServer.class, args);
}
@Override
public void run(String... strings) throws Exception {
}
} | mit |
plumer/codana | tomcat_files/6.0.0/SSIInclude.java | 2465 | /*
* Copyright 1999,2004 The Apache Software Foundation. Licensed under the
* Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
* law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.apache.catalina.ssi;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Implements the Server-side #include command
*
* @author Bip Thelin
* @author Paul Speed
* @author Dan Sandberg
* @author David Becker
* @version $Revision: 303882 $, $Date: 2005-04-23 12:22:37 +0200 (sam., 23 avr. 2005) $
*/
public final class SSIInclude implements SSICommand {
/**
* @see SSICommand
*/
public long process(SSIMediator ssiMediator, String commandName,
String[] paramNames, String[] paramValues, PrintWriter writer) {
long lastModified = 0;
String configErrMsg = ssiMediator.getConfigErrMsg();
for (int i = 0; i < paramNames.length; i++) {
String paramName = paramNames[i];
String paramValue = paramValues[i];
String substitutedValue = ssiMediator
.substituteVariables(paramValue);
try {
if (paramName.equalsIgnoreCase("file")
|| paramName.equalsIgnoreCase("virtual")) {
boolean virtual = paramName.equalsIgnoreCase("virtual");
lastModified = ssiMediator.getFileLastModified(
substitutedValue, virtual);
String text = ssiMediator.getFileText(substitutedValue,
virtual);
writer.write(text);
} else {
ssiMediator.log("#include--Invalid attribute: "
+ paramName);
writer.write(configErrMsg);
}
} catch (IOException e) {
ssiMediator.log("#include--Couldn't include file: "
+ substitutedValue, e);
writer.write(configErrMsg);
}
}
return lastModified;
}
} | mit |
arkbriar/nju_ds_lab2 | nodes/src/main/java/services/interceptors/FileSystemAuthInterceptor.java | 3136 | package services.interceptors;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import utils.SimpleForwardingServerCallListener;
/**
* Created by Shunjie Ding on 14/12/2016.
*/
public class FileSystemAuthInterceptor implements ServerInterceptor {
private static Logger logger = Logger.getLogger(FileSystemAuthInterceptor.class.getName());
private final RedissonClient redissonClient;
@VisibleForTesting
static final Metadata.Key<String> TokenHeader =
Metadata.Key.of("TOKEN", Metadata.ASCII_STRING_MARSHALLER);
public FileSystemAuthInterceptor(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
/**
* Intercept {@link ServerCall} dispatch by the {@code next} {@link ServerCallHandler}. General
* semantics of {@link ServerCallHandler#startCall} apply and the returned
* {@link ServerCall.Listener} must not be {@code null}.
*
* <p>If the implementation throws an exception, {@code call} will be closed with an error.
* Implementations must not throw an exception if they started processing that may use {@code
* call} on another thread.
* @param call object to receive response messages
* @param next next processor in the interceptor chain @return listener for processing incoming
* messages for {@code call}, never {@code null}.
*/
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
logger.log(Level.OFF, "header received from client:" + headers);
String token = headers.get(TokenHeader);
ServerCall.Listener<ReqT> delegateListener = next.startCall(call, headers);
boolean tokenValid = false;
if (token != null && !token.isEmpty()) {
RBucket<String> tokenBucket =
redissonClient.getBucket("token/" + token, new StringCodec());
if (tokenBucket.isExists() && !tokenBucket.get().isEmpty()) {
tokenBucket.expireAsync(5, TimeUnit.MINUTES);
tokenValid = true;
}
}
if (!tokenValid) {
return new SimpleForwardingServerCallListener<ReqT>(delegateListener) {
/**
* The client completed all message sending. However, the call may still be
* cancelled.
*/
@Override
public void onHalfClose() {
throw Status.UNAUTHENTICATED
.withDescription("Token invalid or may be expired, please relogin.")
.asRuntimeException();
}
};
}
return delegateListener;
}
}
| mit |
tdebatty/spark-kmedoids | spark-kmedoids-eval/src/main/java/spark/kmedoids/eval/fish/AbstractTest.java | 2882 | /*
* The MIT License
*
* Copyright 2017 Thibault Debatty.
*
* 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 spark.kmedoids.eval.fish;
import info.debatty.java.datasets.fish.TimeSerie;
import info.debatty.jinu.TestInterface;
import info.debatty.spark.kmedoids.Clusterer;
import info.debatty.spark.kmedoids.NeighborGenerotor;
import info.debatty.spark.kmedoids.Solution;
import info.debatty.spark.kmedoids.budget.SimilaritiesBudget;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
/**
*
* @author Thibault Debatty
*/
public class AbstractTest implements TestInterface {
public static String dataset_path;
public static int parallelism;
private final NeighborGenerotor<TimeSerie> neighbor_generator;
/**
*
* @param neighbor_generator
*/
public AbstractTest(final NeighborGenerotor<TimeSerie> neighbor_generator) {
this.neighbor_generator = neighbor_generator;
}
@Override
public final double[] run(final double budget) throws Exception {
SparkConf conf = new SparkConf();
conf.setAppName("Spark k-medoids for FISHES");
conf.setIfMissing("spark.master", "local[*]");
Solution<TimeSerie> solution;
try (JavaSparkContext sc = new JavaSparkContext(conf)) {
JavaRDD<TimeSerie> data = sc.objectFile(dataset_path, parallelism);
Clusterer<TimeSerie> clusterer = new Clusterer<>();
clusterer.setK(10);
clusterer.setSimilarity(new TimeSerieSimilarity());
clusterer.setNeighborGenerator(neighbor_generator);
clusterer.setBudget(new SimilaritiesBudget((long) budget));
solution = clusterer.cluster(data);
}
return new double[]{solution.getTotalSimilarity()};
}
}
| mit |
tancolo/IDouban | app/src/main/java/com/shrimpcolo/johnnytam/idouban/api/DoubanManager.java | 1128 | package com.shrimpcolo.johnnytam.idouban.api;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Johnny Tam on 2016/7/10.
*/
public class DoubanManager {
private static IDoubanService sDoubanService;
public synchronized static IDoubanService createDoubanService() {
if (sDoubanService == null) {
Retrofit retrofit = createRetrofit();
sDoubanService = retrofit.create(IDoubanService.class);
}
return sDoubanService;
}
private static Retrofit createRetrofit() {
OkHttpClient httpClient;
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
return new Retrofit.Builder()
.baseUrl(IDoubanService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
}
}
| mit |
adatapost/student-projects | src/in/safal/AttendenceMaster.java | 8459 | package in.safal;
import java.util.List;
import java.util.ArrayList;
/*
create table attendance
(
att_code number(10) primary key,
profile_code number(7) references employee_profile(profile_code),
att_date date,
overtime_hours number(3),
present number(2),
absent number(2),
weekoff number(2),
leave number(2),
holiday number(2),
halfday number(2)
)
*/
public class AttendenceMaster
{
private int attCode=0;
private int profileCode=0;
private String attdate="";
private int overtimehours=0;
private int present=0;
private int absent=0;
private int weekoff=0;
private int leave=0;
private int holiday=0;
private int halfday=0;
public AttendenceMaster() {}
public AttendenceMaster(int attCode)
{
this.attCode=attCode;
}
public AttendenceMaster(int attCode,
int profileCode,
String attdate,
int overtimehours,
int present,
int absent,
int weekoff,
int leave,
int holiday,
int halfday)
{
this.attCode=attCode;
this.profileCode=profileCode;
this.attdate=attdate;
this.overtimehours=overtimehours;
this.present=present;
this.absent=absent;
this.weekoff=weekoff;
this.leave=leave;
this.holiday=holiday;
this.halfday=halfday;
}
public void setattCode(int attCode)
{
this.attCode=attCode;
}
public int getattCode()
{
return attCode;
}
public void setprofileCode(int profileCode)
{
this.profileCode=profileCode;
}
public int getprofileCode()
{
return profileCode;
}
public void setattdate(String attdate)
{
this.attdate=attdate;
}
public String getattdate()
{
return attdate;
}
public void setovertimehours(int overtimehours)
{
this.overtimehours=overtimehours;
}
public int getovertimehours()
{
return overtimehours;
}
public void setpresent(int present)
{
this.present=present;
}
public int getpresent()
{
return present;
}
public void setabsent(int absent)
{
this.absent=absent;
}
public int getabsent()
{
return absent;
}
public void setweekoff(int weekoff)
{
this.weekoff=weekoff;
}
public int getweekoff()
{
return weekoff;
}
public void setleave(int leave)
{
this.leave=leave;
}
public int getleave()
{
return leave;
}
public void setholiday(int holiday)
{
this.holiday=holiday;
}
public int getholiday()
{
return holiday;
}
public void sethalfday(int halfday)
{
this.halfday=halfday;
}
public int gethalfday()
{
return halfday;
}
public String toString()
{
return "AttendenceMaster [attCode=" + attCode + ", profileCode=" + profileCode + ", attdate=" + attdate
+ ",overtimehours=" + overtimehours + ",present=" + present + ",absent=" + absent + ", weekoff="
+ weekoff + ", leave=" + leave + ", holiday=" + holiday + ", halfday=" + halfday + "]";
}
//Database logic
public boolean addAttend()
{
try{
attCode =Db.newAttCode();
Db x=new Db("insert into attendence values (?,?,?,?,?,?,?,?,?,?)");
x.getPs().setInt(1,attCode);
x.getPs().setInt(2,profileCode);
x.getPs().setString(3,attdate);
x.getPs().setInt(4,overtimehours);
x.getPs().setInt(5,present);
x.getPs().setInt(6,absent);
x.getPs().setInt(7,weekoff);
x.getPs().setInt(8,leave);
x.getPs().setInt(8,holiday);
x.getPs().setInt(10,halfday);
x.execute();
return true;
}
catch(Exception ex)
{
System.err.println(ex);
}
return false;
}
public boolean updateAttend()
{
try{
Db x=new Db("update attendence set profile_code=?,att_date=?,overtime_hours=?,present=? ,absent=?,weakoff=? ,leave=?,holiday=?,halfday=? where att_code=?");
x.getPs().setInt(1,attCode);
x.getPs().setInt(2,profileCode);
x.getPs().setString(3,attdate);
x.getPs().setInt(4,overtimehours);
x.getPs().setInt(5,present);
x.getPs().setInt(6,absent);
x.getPs().setInt(7,weekoff);
x.getPs().setInt(8,leave);
x.getPs().setInt(9,holiday);
x.getPs().setInt(10,halfday);
x.execute();
return true;
}
catch(Exception ex)
{
System.err.println(ex);
}
return false;
}
public boolean deleteAttend()
{
try{
Db x=new Db("delete from attendence where att_code=?");
x.getPs().setInt(1,attCode);
x.execute();
return true;
}
catch(Exception ex)
{
System.err.println(ex);
}
return false;
}
public boolean fetchAttend()
{
try{
Db x=new Db("select * from attendence where att_code=?");
x.getPs().setInt(1,attCode);
Object []r=x.row();
if(r!=null)
{
attCode=Integer.parseInt(r[0].toString());
profileCode=Integer.parseInt(r[1].toString());
attdate=r[2].toString();
overtimehours=Integer.parseInt(r[3].toString());
present=Integer.parseInt(r[4].toString());
absent=Integer.parseInt(r[5].toString());
weekoff=Integer.parseInt(r[6].toString());
leave=Integer.parseInt(r[7].toString());
holiday=Integer.parseInt(r[8].toString());
halfday=Integer.parseInt(r[9].toString());
return true;
}
}catch(Exception ex){
System.err.println(ex);
}
return false;
}
public static List<AttendenceMaster> getAttend()
{
List<AttendenceMaster> list=new ArrayList<AttendenceMaster>();
try{
Db x=new Db("select * from attendance");
List<Object[]> result=x.rows();
for(Object []r:result)
{
AttendenceMaster attd=new AttendenceMaster();
attd.setattCode(Integer.parseInt(r[0].toString()));
attd.setprofileCode(Integer.parseInt(r[1].toString()));
attd.setattdate(r[2].toString());
attd.setovertimehours(Integer.parseInt(r[3].toString()));
attd.setpresent(Integer.parseInt(r[4].toString()));
attd.setabsent(Integer.parseInt(r[5].toString()));
attd.setweekoff(Integer.parseInt(r[6].toString()));
attd.setleave(Integer.parseInt(r[7].toString()));
attd.setholiday(Integer.parseInt(r[8].toString()));
attd.sethalfday(Integer.parseInt(r[9].toString()));
list.add(attd);
}
}
catch(Exception ex)
{
System.err.println(ex);
}
return list;
}
}
| mit |
joreilly/geofire-java | src/test/java/com/firebase/geofire/GeoFireTest.java | 6325 | package com.firebase.geofire;
import com.firebase.geofire.util.ReadFuture;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
@RunWith(JUnit4.class)
public class GeoFireTest extends RealDataTest {
@Rule
public org.junit.rules.ExpectedException exception = ExpectedException.none();
@Test
public void geoFireSetsLocations() throws InterruptedException, ExecutionException, TimeoutException {
GeoFire geoFire = newTestGeoFire();
setLoc(geoFire, "loc1", 0.1, 0.1);
setLoc(geoFire, "loc2", 50.1, 50.1);
setLoc(geoFire, "loc3", -89.1, -89.1, true);
Future<Object> future = new ReadFuture(geoFire.getDatabaseReference());
Map<String, Object> expected = new HashMap<>();
expected.put("loc1", new HashMap<String, Object>() {{
put("l", Arrays.asList(0.1, 0.1));
put("g", "s000d60yd1");
}});
expected.put("loc2", new HashMap<String, Object>() {{
put("l", Arrays.asList(50.1, 50.1));
put("g", "v0gth03tws");
}});
expected.put("loc3", new HashMap<String, Object>() {{
put("l", Arrays.asList(-89.1, -89.1));
put("g", "400th7z6gs");
}});
Object result = future.get(TestHelpers.TIMEOUT_SECONDS, TimeUnit.SECONDS);
Assert.assertEquals(expected, ((DataSnapshot)result).getValue());
}
@Test
public void getLocationReturnsCorrectLocation() throws InterruptedException, ExecutionException, TimeoutException {
GeoFire geoFire = newTestGeoFire();
TestCallback testCallback1 = new TestCallback();
geoFire.getLocation("loc1", testCallback1);
Assert.assertEquals(TestCallback.noLocation("loc1"), testCallback1.getCallbackValue());
TestCallback testCallback2 = new TestCallback();
setLoc(geoFire, "loc1", 0, 0, true);
geoFire.getLocation("loc1", testCallback2);
Assert.assertEquals(TestCallback.location("loc1", 0, 0), testCallback2.getCallbackValue());
TestCallback testCallback3 = new TestCallback();
setLoc(geoFire, "loc2", 1, 1, true);
geoFire.getLocation("loc2", testCallback3);
Assert.assertEquals(TestCallback.location("loc2", 1, 1), testCallback3.getCallbackValue());
TestCallback testCallback4 = new TestCallback();
setLoc(geoFire, "loc1", 5, 5, true);
geoFire.getLocation("loc1", testCallback4);
Assert.assertEquals(TestCallback.location("loc1", 5, 5), testCallback4.getCallbackValue());
TestCallback testCallback5 = new TestCallback();
removeLoc(geoFire, "loc1");
geoFire.getLocation("loc1", testCallback5);
Assert.assertEquals(TestCallback.noLocation("loc1"), testCallback5.getCallbackValue());
}
@Test
public void getLocationOnWrongDataReturnsError() throws InterruptedException {
GeoFire geoFire = newTestGeoFire();
setValueAndWait(geoFire.getDatabaseRefForKey("loc1"), "NaN");
final Semaphore semaphore = new Semaphore(0);
geoFire.getLocation("loc1", new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
Assert.fail("This should not be a valid location!");
}
@Override
public void onCancelled(DatabaseError databaseError) {
semaphore.release();
}
});
semaphore.tryAcquire(TestHelpers.TIMEOUT_SECONDS, TimeUnit.SECONDS);
setValueAndWait(geoFire.getDatabaseRefForKey("loc2"), new HashMap<String, Object>() {{
put("l", 10);
put("g", "abc");
}});
geoFire.getLocation("loc2", new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
Assert.fail("This should not be a valid location!");
}
@Override
public void onCancelled(DatabaseError databaseError) {
semaphore.release();
}
});
semaphore.tryAcquire(TestHelpers.TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
@Test
public void invalidCoordinatesThrowException() {
GeoFire geoFire = newTestGeoFire();
try {
geoFire.setLocation("test", new GeoLocation(-91, 90));
Assert.fail("Did not throw illegal argument exception!");
} catch (IllegalArgumentException e) {
}
try {
geoFire.setLocation("test", new GeoLocation(0, -180.1));
Assert.fail("Did not throw illegal argument exception!");
} catch (IllegalArgumentException e) {
}
try {
geoFire.setLocation("test", new GeoLocation(0, 181.1));
Assert.fail("Did not throw illegal argument exception!");
} catch (IllegalArgumentException e) {
}
}
@Test
public void locationWorksWithLongs() throws InterruptedException, ExecutionException, TimeoutException {
GeoFire geoFire = newTestGeoFire();
DatabaseReference databaseReference = geoFire.getDatabaseRefForKey("loc");
final Semaphore semaphore = new Semaphore(0);
databaseReference.setValue(new HashMap<String, Object>() {{
put("l", Arrays.asList(1L, 2L));
put("g", "7zzzzzzzzz"); // this is wrong but we don't care in this test
}}, "7zzzzzzzzz", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
semaphore.release();
}
});
semaphore.tryAcquire(TestHelpers.TIMEOUT_SECONDS, TimeUnit.SECONDS);
TestCallback testCallback = new TestCallback();
geoFire.getLocation("loc", testCallback);
Assert.assertEquals(TestCallback.location("loc", 1, 2), testCallback.getCallbackValue());
}
}
| mit |
tcsiwula/java_code | classes/cs212/LectureCode/src/io/CloseFile.java | 618 | /*
|============================================================|
|- Project: SampleCode -|
|- File: CloseFile.java -|
|- Date: Sep 17, 2015 -|
|- Author: timsiwula -|
|- Description: This file servers the purpose of ... . -|
|============================================================|
*/
/**
*
*/
package io;
/**
* @author timsiwula
*
*/
public class CloseFile
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
}
}
| mit |
chris-ch/yahoofinance-api | src/main/java/yahoofinance/Stock.java | 20369 | package yahoofinance;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yahoofinance.histquotes.HistQuotesRequest;
import yahoofinance.histquotes.HistoricalQuote;
import yahoofinance.histquotes.Interval;
import yahoofinance.histquotes2.HistDividendsRequest;
import yahoofinance.histquotes2.HistQuotes2Request;
import yahoofinance.histquotes2.HistSplitsRequest;
import yahoofinance.histquotes2.HistoricalDividend;
import yahoofinance.histquotes2.HistoricalSplit;
import yahoofinance.quotes.query1v7.StockQuotesQuery1V7Request;
import yahoofinance.quotes.stock.StockDividend;
import yahoofinance.quotes.stock.StockQuote;
import yahoofinance.quotes.csv.StockQuotesData;
import yahoofinance.quotes.csv.StockQuotesRequest;
import yahoofinance.quotes.stock.StockStats;
/**
*
* @author Stijn Strickx
*/
public class Stock implements Serializable {
private static final Logger log = LoggerFactory.getLogger(Stock.class);
private final String symbol;
private String name;
private String currency;
private String stockExchange;
private StockQuote quote;
private StockStats stats;
private StockDividend dividend;
private List<HistoricalQuote> history;
private List<HistoricalDividend> dividendHistory;
private List<HistoricalSplit> splitHistory;
public Stock(String symbol) {
this.symbol = symbol;
}
private void update() throws IOException {
if(YahooFinance.QUOTES_QUERY1V7_ENABLED.equalsIgnoreCase("true")) {
StockQuotesQuery1V7Request request = new StockQuotesQuery1V7Request(this.symbol);
Stock stock = request.getSingleResult();
if (stock != null) {
this.setName(stock.getName());
this.setCurrency(stock.getCurrency());
this.setStockExchange(stock.getStockExchange());
this.setQuote(stock.getQuote());
this.setStats(stock.getStats());
this.setDividend(stock.getDividend());
log.info("Updated Stock with symbol: {}", this.symbol);
} else {
log.error("Failed to update Stock with symbol: {}", this.symbol);
}
} else {
StockQuotesRequest request = new StockQuotesRequest(this.symbol);
StockQuotesData data = request.getSingleResult();
if (data != null) {
this.setQuote(data.getQuote());
this.setStats(data.getStats());
this.setDividend(data.getDividend());
log.info("Updated Stock with symbol: {}", this.symbol);
} else {
log.error("Failed to update Stock with symbol: {}", this.symbol);
}
}
}
/**
* Checks if the returned name is null. This probably means that the symbol was not recognized by Yahoo Finance.
* @return whether this stock's symbol is known by Yahoo Finance (true) or not (false)
*/
public boolean isValid() {
return this.name != null;
}
/**
* Returns the basic quotes data available for this stock.
*
* @return basic quotes data available for this stock
* @see #getQuote(boolean)
*/
public StockQuote getQuote() {
return this.quote;
}
/**
* Returns the basic quotes data available for this stock.
* This method will return null in the following situations:
* <ul>
* <li> the data hasn't been loaded yet
* in a previous request and refresh is set to false.
* <li> refresh is true and the data cannot be retrieved from Yahoo Finance
* for whatever reason (symbol not recognized, no network connection, ...)
* </ul>
* <p>
* When the quote data gets refreshed, it will automatically also refresh
* the statistics and dividend data of the stock from Yahoo Finance
* in the same request.
*
* @param refresh indicates whether the data should be requested again to Yahoo Finance
* @return basic quotes data available for this stock
* @throws java.io.IOException when there's a connection problem
*/
public StockQuote getQuote(boolean refresh) throws IOException {
if(refresh) {
this.update();
}
return this.quote;
}
public void setQuote(StockQuote quote) {
this.quote = quote;
}
/**
* Returns the statistics available for this stock.
*
* @return statistics available for this stock
* @see #getStats(boolean)
*/
public StockStats getStats() {
return this.stats;
}
/**
* Returns the statistics available for this stock.
* This method will return null in the following situations:
* <ul>
* <li> the data hasn't been loaded yet
* in a previous request and refresh is set to false.
* <li> refresh is true and the data cannot be retrieved from Yahoo Finance
* for whatever reason (symbol not recognized, no network connection, ...)
* </ul>
* <p>
* When the statistics get refreshed, it will automatically also refresh
* the quote and dividend data of the stock from Yahoo Finance
* in the same request.
*
* @param refresh indicates whether the data should be requested again to Yahoo Finance
* @return statistics available for this stock
* @throws java.io.IOException when there's a connection problem
*/
public StockStats getStats(boolean refresh) throws IOException {
if(refresh) {
this.update();
}
return this.stats;
}
public void setStats(StockStats stats) {
this.stats = stats;
}
/**
* Returns the dividend data available for this stock.
*
* @return dividend data available for this stock
* @see #getDividend(boolean)
*/
public StockDividend getDividend() {
return this.dividend;
}
/**
* Returns the dividend data available for this stock.
*
* This method will return null in the following situations:
* <ul>
* <li> the data hasn't been loaded yet
* in a previous request and refresh is set to false.
* <li> refresh is true and the data cannot be retrieved from Yahoo Finance
* for whatever reason (symbol not recognized, no network connection, ...)
* </ul>
* <p>
* When the dividend data get refreshed, it will automatically also refresh
* the quote and statistics data of the stock from Yahoo Finance
* in the same request.
*
* @param refresh indicates whether the data should be requested again to Yahoo Finance
* @return dividend data available for this stock
* @throws java.io.IOException when there's a connection problem
*/
public StockDividend getDividend(boolean refresh) throws IOException {
if(refresh) {
this.update();
}
return this.dividend;
}
public void setDividend(StockDividend dividend) {
this.dividend = dividend;
}
/**
* This method will return historical quotes from this stock.
* If the historical quotes are not available yet, they will
* be requested first from Yahoo Finance.
* <p>
* If the historical quotes are not available yet, the
* following characteristics will be used for the request:
* <ul>
* <li> from: 1 year ago (default)
* <li> to: today (default)
* <li> interval: MONTHLY (default)
* </ul>
* <p>
* There are several more methods available that allow you
* to define some characteristics of the historical data.
* Calling one of those methods will result in a new request
* being sent to Yahoo Finance.
*
* @return a list of historical quotes from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getHistory(yahoofinance.histquotes.Interval)
* @see #getHistory(java.util.Calendar)
* @see #getHistory(java.util.Calendar, java.util.Calendar)
* @see #getHistory(java.util.Calendar, yahoofinance.histquotes.Interval)
* @see #getHistory(java.util.Calendar, java.util.Calendar, yahoofinance.histquotes.Interval)
*/
public List<HistoricalQuote> getHistory() throws IOException {
if(this.history != null) {
return this.history;
}
return this.getHistory(HistQuotesRequest.DEFAULT_FROM);
}
/**
* Requests the historical quotes for this stock with the following characteristics.
* <ul>
* <li> from: 1 year ago (default)
* <li> to: today (default)
* <li> interval: specified value
* </ul>
*
* @param interval the interval of the historical data
* @return a list of historical quotes from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getHistory()
*/
public List<HistoricalQuote> getHistory(Interval interval) throws IOException {
return this.getHistory(HistQuotesRequest.DEFAULT_FROM, interval);
}
/**
* Requests the historical quotes for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: today (default)
* <li> interval: MONTHLY (default)
* </ul>
*
* @param from start date of the historical data
* @return a list of historical quotes from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getHistory()
*/
public List<HistoricalQuote> getHistory(Calendar from) throws IOException {
return this.getHistory(from, HistQuotesRequest.DEFAULT_TO);
}
/**
* Requests the historical quotes for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: today (default)
* <li> interval: specified value
* </ul>
*
* @param from start date of the historical data
* @param interval the interval of the historical data
* @return a list of historical quotes from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getHistory()
*/
public List<HistoricalQuote> getHistory(Calendar from, Interval interval) throws IOException {
return this.getHistory(from, HistQuotesRequest.DEFAULT_TO, interval);
}
/**
* Requests the historical quotes for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: specified value
* <li> interval: MONTHLY (default)
* </ul>
*
* @param from start date of the historical data
* @param to end date of the historical data
* @return a list of historical quotes from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getHistory()
*/
public List<HistoricalQuote> getHistory(Calendar from, Calendar to) throws IOException {
return this.getHistory(from, to, Interval.MONTHLY);
}
/**
* Requests the historical quotes for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: specified value
* <li> interval: specified value
* </ul>
*
* @param from start date of the historical data
* @param to end date of the historical data
* @param interval the interval of the historical data
* @return a list of historical quotes from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getHistory()
*/
public List<HistoricalQuote> getHistory(Calendar from, Calendar to, Interval interval) throws IOException {
if(YahooFinance.HISTQUOTES2_ENABLED.equalsIgnoreCase("true")) {
HistQuotes2Request hist = new HistQuotes2Request(this.symbol, from, to, interval);
this.setHistory(hist.getResult());
} else {
HistQuotesRequest hist = new HistQuotesRequest(this.symbol, from, to, interval);
this.setHistory(hist.getResult());
}
return this.history;
}
public void setHistory(List<HistoricalQuote> history) {
this.history = history;
}
/**
* This method will return historical dividends from this stock.
* If the historical dividends are not available yet, they will
* be requested first from Yahoo Finance.
* <p>
* If the historical dividends are not available yet, the
* following characteristics will be used for the request:
* <ul>
* <li> from: 1 year ago (default)
* <li> to: today (default)
* </ul>
* <p>
* There are several more methods available that allow you
* to define some characteristics of the historical data.
* Calling one of those methods will result in a new request
* being sent to Yahoo Finance.
*
* @return a list of historical dividends from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getDividendHistory(java.util.Calendar)
* @see #getDividendHistory(java.util.Calendar, java.util.Calendar)
*/
public List<HistoricalDividend> getDividendHistory() throws IOException {
if(this.dividendHistory != null) {
return this.dividendHistory;
}
return this.getDividendHistory(HistDividendsRequest.DEFAULT_FROM);
}
/**
* Requests the historical dividends for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: today (default)
* </ul>
*
* @param from start date of the historical data
* @return a list of historical dividends from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getDividendHistory()
*/
public List<HistoricalDividend> getDividendHistory(Calendar from) throws IOException {
return this.getDividendHistory(from, HistDividendsRequest.DEFAULT_TO);
}
/**
* Requests the historical dividends for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: specified value
* </ul>
*
* @param from start date of the historical data
* @param to end date of the historical data
* @return a list of historical dividends from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getDividendHistory()
*/
public List<HistoricalDividend> getDividendHistory(Calendar from, Calendar to) throws IOException {
if(YahooFinance.HISTQUOTES2_ENABLED.equalsIgnoreCase("true")) {
HistDividendsRequest histDiv = new HistDividendsRequest(this.symbol, from, to);
this.setDividendHistory(histDiv.getResult());
} else {
// Historical dividends cannot be retrieved without CRUMB
this.setDividendHistory(null);
}
return this.dividendHistory;
}
public void setDividendHistory(List<HistoricalDividend> dividendHistory) {
this.dividendHistory = dividendHistory;
}
/**
* This method will return historical splits from this stock.
* If the historical splits are not available yet, they will
* be requested first from Yahoo Finance.
* <p>
* If the historical splits are not available yet, the
* following characteristics will be used for the request:
* <ul>
* <li> from: 1 year ago (default)
* <li> to: today (default)
* </ul>
* <p>
* There are several more methods available that allow you
* to define some characteristics of the historical data.
* Calling one of those methods will result in a new request
* being sent to Yahoo Finance.
*
* @return a list of historical splits from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getSplitHistory(java.util.Calendar)
* @see #getSplitHistory(java.util.Calendar, java.util.Calendar)
*/
public List<HistoricalSplit> getSplitHistory() throws IOException {
if(this.splitHistory != null) {
return this.splitHistory;
}
return this.getSplitHistory(HistSplitsRequest.DEFAULT_FROM);
}
/**
* Requests the historical splits for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: today (default)
* </ul>
*
* @param from start date of the historical data
* @return a list of historical splits from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getSplitHistory()
*/
public List<HistoricalSplit> getSplitHistory(Calendar from) throws IOException {
return this.getSplitHistory(from, HistSplitsRequest.DEFAULT_TO);
}
/**
* Requests the historical splits for this stock with the following characteristics.
* <ul>
* <li> from: specified value
* <li> to: specified value
* </ul>
*
* @param from start date of the historical data
* @param to end date of the historical data
* @return a list of historical splits from this stock
* @throws java.io.IOException when there's a connection problem
* @see #getSplitHistory()
*/
public List<HistoricalSplit> getSplitHistory(Calendar from, Calendar to) throws IOException {
if(YahooFinance.HISTQUOTES2_ENABLED.equalsIgnoreCase("true")) {
HistSplitsRequest histSplit = new HistSplitsRequest(this.symbol, from, to);
this.setSplitHistory(histSplit.getResult());
} else {
// Historical splits cannot be retrieved without CRUMB
this.setSplitHistory(null);
}
return this.splitHistory;
}
public void setSplitHistory(List<HistoricalSplit> splitHistory) {
this.splitHistory = splitHistory;
}
public String getSymbol() {
return symbol;
}
/**
* Get the full name of the stock
*
* @return the name or null if the data is not available
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* Get the currency of the stock
*
* @return the currency or null if the data is not available
*/
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
/**
* Get the exchange on which the stock is traded
*
* @return the exchange or null if the data is not available
*/
public String getStockExchange() {
return stockExchange;
}
public void setStockExchange(String stockExchange) {
this.stockExchange = stockExchange;
}
@Override
public String toString() {
return this.symbol + ": " + this.quote.getPrice();
}
public void print() {
System.out.println(this.symbol);
System.out.println("--------------------------------");
for (Field f : this.getClass().getDeclaredFields()) {
try {
System.out.println(f.getName() + ": " + f.get(this));
} catch (IllegalArgumentException ex) {
log.error(null, ex);
} catch (IllegalAccessException ex) {
log.error(null, ex);
}
}
System.out.println("--------------------------------");
}
}
| mit |
SystematicTesting/QDOS | st-qdos-recorder/src/main/java/com/systematictesting/media/VideoFormatKeys.java | 2533 |
package com.systematictesting.media;
import com.systematictesting.media.math.Rational;
public class VideoFormatKeys extends FormatKeys {
public static final String ENCODING_BUFFERED_IMAGE = "image";
public static final String ENCODING_QUICKTIME_CINEPAK = "cvid";
public static final String COMPRESSOR_NAME_QUICKTIME_CINEPAK = "Cinepak";
public static final String ENCODING_QUICKTIME_JPEG = "jpeg";
public static final String COMPRESSOR_NAME_QUICKTIME_JPEG = "Photo - JPEG";
public static final String ENCODING_QUICKTIME_PNG = "png ";
public static final String COMPRESSOR_NAME_QUICKTIME_PNG = "PNG";
public static final String ENCODING_QUICKTIME_ANIMATION = "rle ";
public static final String COMPRESSOR_NAME_QUICKTIME_ANIMATION = "Animation";
public static final String ENCODING_QUICKTIME_RAW = "raw ";
public static final String COMPRESSOR_NAME_QUICKTIME_RAW = "NONE";
public static final String ENCODING_AVI_DIB = "DIB ";
public static final String ENCODING_AVI_RLE = "RLE ";
public static final String ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE = "tscc";
public static final String COMPRESSOR_NAME_AVI_TECHSMITH_SCREEN_CAPTURE = "Techsmith Screen Capture";
public static final String ENCODING_AVI_DOSBOX_SCREEN_CAPTURE = "ZMBV";
public static final String ENCODING_AVI_MJPG = "MJPG";
public static final String ENCODING_AVI_PNG = "png ";
public static final String ENCODING_BITMAP_IMAGE = "ILBM";
public final static FormatKey<Integer> WidthKey = new FormatKey<Integer>("dimX","width", Integer.class);
public final static FormatKey<Integer> HeightKey = new FormatKey<Integer>("dimY","height", Integer.class);
public final static FormatKey<Integer> DepthKey = new FormatKey<Integer>("dimZ","depth", Integer.class);
public final static FormatKey<Class> DataClassKey = new FormatKey<Class>("dataClass", Class.class);
public final static FormatKey<String> CompressorNameKey = new FormatKey<String>("compressorName", "compressorName",String.class, true);
public final static FormatKey<Rational> PixelAspectRatioKey = new FormatKey<Rational>("pixelAspectRatio", Rational.class);
public final static FormatKey<Boolean> FixedFrameRateKey = new FormatKey<Boolean>("fixedFrameRate", Boolean.class);
public final static FormatKey<Boolean> InterlaceKey = new FormatKey<Boolean>("interlace", Boolean.class);
public final static FormatKey<Float> QualityKey = new FormatKey<Float>("quality", Float.class);
}
| mit |
karim/adila | database/src/main/java/adila/db/acer5ft07.java | 216 | // This file is automatically generated.
package adila.db;
/*
* Acer Liquid Zest 4G
*
* DEVICE: acer_t07
* MODEL: T07
*/
final class acer5ft07 {
public static final String DATA = "Acer|Liquid Zest 4G|";
}
| mit |
ExtraCells/ExtraCells1 | src/main/java/extracells/util/FluidRequestPattern.java | 940 | package extracells.util;
import appeng.api.me.util.ICraftingPattern;
import appeng.api.me.util.ITileCraftingProvider;
import com.google.common.collect.Lists;
import extracells.ItemEnum;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import java.util.List;
public class FluidRequestPattern implements ICraftingPattern
{
ITileCraftingProvider provider;
FluidStack stack;
public FluidRequestPattern(ITileCraftingProvider provider, FluidStack stack)
{
this.provider = provider;
this.stack = stack;
}
@Override
public ItemStack getOutput()
{
return new ItemStack(ItemEnum.FLUIDDISPLAY.getItemInstance(), stack.amount, stack.fluidID);
}
@Override
public List<ItemStack> getRequirements()
{
return null;
}
@Override
public List<ITileCraftingProvider> getProviders()
{
return Lists.newArrayList(provider);
}
@Override
public void addProviders(ITileCraftingProvider a)
{
}
}
| mit |
nullEuro/5zigCubecraft | src/main/java/net/frozenbit/plugin5zig/cubecraft/commands/handlers/ColorCommandHandler.java | 2559 | package net.frozenbit.plugin5zig.cubecraft.commands.handlers;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import eu.the5zig.mod.The5zigAPI;
import eu.the5zig.util.minecraft.ChatColor;
import net.frozenbit.plugin5zig.cubecraft.commands.CommandHandler;
import net.frozenbit.plugin5zig.cubecraft.commands.CommandOutputPrinter;
import net.frozenbit.plugin5zig.cubecraft.commands.UsageException;
import java.util.Iterator;
import java.util.List;
/**
* Handler for .color
* Shows help for minecrafts color codes
*/
public class ColorCommandHandler extends CommandHandler {
public static final Iterable<ChatColor> RAINBOW_IT =
Iterables.cycle(ChatColor.DARK_RED, ChatColor.RED, ChatColor.GOLD, ChatColor.YELLOW,
ChatColor.GREEN, ChatColor.DARK_GREEN, ChatColor.DARK_AQUA, ChatColor.AQUA,
ChatColor.BLUE, ChatColor.LIGHT_PURPLE, ChatColor.DARK_PURPLE);
public ColorCommandHandler() {
super("color", "Show all color codes", "c");
}
@Override
public void run(String cmd, List<String> args, CommandOutputPrinter printer) throws UsageException {
if (args.isEmpty()) {
StringBuilder lineBuf = new StringBuilder();
for (ChatColor chatColor : ChatColor.values()) {
lineBuf.append(chatColor)
.append(chatColor.getCode())
.append(ChatColor.RESET)
.append(chatColor == ChatColor.MAGIC ? "(k)" : "")
.append(" ");
}
printer.println(lineBuf.toString());
} else {
String text = Joiner.on(' ').join(args);
StringBuilder fancy = new StringBuilder();
Iterator<ChatColor> rainbowColors = RAINBOW_IT.iterator();
for (char c : text.toCharArray()) {
if (c != ' ') {
fancy.append("&")
.append(rainbowColors.next().getCode());
}
fancy.append(c);
}
The5zigAPI.getAPI().sendPlayerMessage(fancy.toString());
}
}
@Override
public void printUsage(String cmd, CommandOutputPrinter printer) {
printer.println(".color - show a cheatsheet of the color codes")
.println(".color <text> - makes the given text colorful and posts it")
.println(ChatColor.ITALIC + "Note that only ranked players can use colors on CubeCraft")
.println("Alias: .c");
}
}
| mit |
schillermann/SpigotSurvivalKit | src/de/schillermann/spigotsurvivalkit/commands/WarpCommand.java | 3217 | package de.schillermann.spigotsurvivalkit.commands;
import de.schillermann.spigotsurvivalkit.databases.tables.WarpTable;
import de.schillermann.spigotsurvivalkit.menu.warps.WarpsMenu;
import java.util.Arrays;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @author Mario Schillermann
*/
final public class WarpCommand implements CommandExecutor {
final private WarpTable tableWarp;
final private WarpsMenu menuWarps;
final private WarpCommandMessage message;
public WarpCommand(
WarpTable tableWarp,
WarpsMenu menuWarps,
WarpCommandMessage message
) {
this.tableWarp = tableWarp;
this.menuWarps = menuWarps;
this.message = message;
}
@Override
public boolean onCommand(
CommandSender sender,
Command command,
String label,
String[] args
) {
if(args.length < 2 || !(sender instanceof Player)) return false;
String action = args[0];
if(!action.equals("set") && !action.equals("remove")) return false;
Player player = (Player) sender;
String warpName = args[1];
if(action.equals("set")) {
if(this.setWarp(warpName, convertWarpDescription(args), player))
player.sendMessage(this.message.getSetWarpSuccess(warpName));
else
player.sendMessage(this.message.getSetWarpError(warpName));
}
else {
if(this.removeWarp(warpName))
player.sendMessage(this.message.getRemoveWarpSuccess(warpName));
else
player.sendMessage(this.message.getRemoveWarpError(warpName));
}
return true;
}
private boolean setWarp(String warpName, String warpDescription, Player player) {
World world = player.getLocation().getWorld();
if(world.getEnvironment() != World.Environment.NORMAL)
return false;
boolean isCreatedWarp = this.tableWarp.insertWarp(
warpName,
warpDescription,
player.getItemInHand().getType(),
world.getUID(),
player.getLocation().getX(),
player.getLocation().getY(),
player.getLocation().getZ(),
player.getUniqueId()
);
if(isCreatedWarp) this.menuWarps.reloadInventory();
return isCreatedWarp;
}
private static String convertWarpDescription(String[] descriptionLines) {
if(descriptionLines.length < 3) return "";
String[] cutDescription =
Arrays.copyOfRange(descriptionLines, 2, descriptionLines.length);
return String.join(" ", cutDescription);
}
private boolean removeWarp(String warpName) {
boolean isRemovedWarp = this.tableWarp.deleteWarp(warpName);
if(isRemovedWarp) this.menuWarps.reloadInventory();
return isRemovedWarp;
}
}
| mit |
kylc/jab | src/com/kylc/bytecode/internal/constants/ConstantFieldRef.java | 1048 | package com.kylc.bytecode.internal.constants;
import java.io.DataInputStream;
import java.io.IOException;
import com.kylc.bytecode.ConstantPool;
public class ConstantFieldRef extends Constant {
private final int classIndex;
private final int nameAndTypeIndex;
public ConstantFieldRef(int classIndex, int nameAndTypeIndex) {
this.classIndex = classIndex;
this.nameAndTypeIndex = nameAndTypeIndex;
}
public int getClassIndex() {
return classIndex;
}
public int getNameAndTypeIndex() {
return nameAndTypeIndex;
}
public ConstantClass getClassReference(ConstantPool constantPool) {
return constantPool.getConstantClass(getClassIndex());
}
public ConstantNameAndType getNameAndTypeReference(ConstantPool constantPool) {
return constantPool.getConstantNameAndType(getNameAndTypeIndex());
}
public static ConstantFieldRef parse(DataInputStream input) throws IOException {
int classIndex = input.readShort();
int nameAndTypeIndex = input.readShort();
return new ConstantFieldRef(classIndex, nameAndTypeIndex);
}
}
| mit |
cliffano/swaggy-jenkins | clients/jaxrs-resteasy/generated/src/gen/java/org/openapitools/model/GithubScmlinks.java | 2112 | package org.openapitools.model;
import java.util.Objects;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.openapitools.model.Link;
import javax.validation.constraints.*;
import io.swagger.annotations.*;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyServerCodegen", date = "2022-02-13T02:21:30.640855Z[Etc/UTC]")
public class GithubScmlinks {
private Link self;
private String propertyClass;
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("self")
public Link getSelf() {
return self;
}
public void setSelf(Link self) {
this.self = self;
}
/**
**/
@ApiModelProperty(value = "")
@JsonProperty("_class")
public String getPropertyClass() {
return propertyClass;
}
public void setPropertyClass(String propertyClass) {
this.propertyClass = propertyClass;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GithubScmlinks githubScmlinks = (GithubScmlinks) o;
return Objects.equals(self, githubScmlinks.self) &&
Objects.equals(propertyClass, githubScmlinks.propertyClass);
}
@Override
public int hashCode() {
return Objects.hash(self, propertyClass);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GithubScmlinks {\n");
sb.append(" self: ").append(toIndentedString(self)).append("\n");
sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| mit |
KehxStudios/Atlas | core/src/com/kehxstudios/atlas/actions/DestroyEntityAction.java | 1683 | /*******************************************************************************
* Copyright 2017 See AUTHORS file.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
package com.kehxstudios.atlas.actions;
import com.kehxstudios.atlas.entities.Entity;
import com.kehxstudios.atlas.managers.EntityManager;
/**
* Used to destroy an Entity on trigger
*/
public class DestroyEntityAction extends Action {
public EntityManager entityManager;
public int entityId;
@Override
public void trigger() {
entityManager.markEntityForRemoval(entityId);
}
}
| mit |
andreasb242/settlers-remake | jsettlers.main.android/src/main/java/jsettlers/main/android/core/controls/NotificationBuilder.java | 3999 | /*
* Copyright (c) 2017
*
* 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 jsettlers.main.android.core.controls;
import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.res.StringRes;
import jsettlers.main.android.R;
import jsettlers.main.android.gameplay.ui.activities.GameActivity_;
import jsettlers.main.android.mainmenu.navigation.Actions;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
/**
* Created by Andreas Eberle on 13.05.2017.
*/
@EBean
class NotificationBuilder {
private final Context context;
private NotificationCompat.Builder builder;
@StringRes(R.string.notification_game_in_progress)
String title;
@StringRes(R.string.game_menu_quit)
String quit;
@StringRes(R.string.game_menu_quit_confirm)
String quitConfirmString;
@StringRes(R.string.save_string)
String saveString;
@StringRes(R.string.pause_string)
String pauseString;
@StringRes(R.string.game_menu_unpause)
String unpauseString;
public NotificationBuilder(Context context) {
this.context = context;
}
@AfterInject
void setupBuilder() {
Intent gameActivityIntent = GameActivity_.intent(context).action(Actions.ACTION_RESUME_GAME).get();
PendingIntent gameActivityPendingIntent = PendingIntent.getActivity(context, 0, gameActivityIntent, 0);
builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentIntent(gameActivityPendingIntent);
}
public NotificationBuilder addQuitButton() {
PendingIntent quitPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_QUIT), 0);
builder.addAction(R.drawable.ic_stop, quit, quitPendingIntent);
return this;
}
public NotificationBuilder addQuitConfirmButton() {
PendingIntent quitPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_QUIT_CONFIRM), 0);
builder.addAction(R.drawable.ic_stop, quitConfirmString, quitPendingIntent);
return this;
}
public NotificationBuilder addSaveButton() {
PendingIntent savePendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_SAVE), 0);
builder.addAction(R.drawable.ic_save, saveString, savePendingIntent);
return this;
}
public NotificationBuilder addPauseButton() {
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_PAUSE), 0);
builder.addAction(R.drawable.ic_pause, pauseString, pausePendingIntent);
return this;
}
public NotificationBuilder addUnPauseButton() {
PendingIntent unPausePendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_UNPAUSE), 0);
builder.addAction(R.drawable.ic_play, unpauseString, unPausePendingIntent);
return this;
}
public Notification build() {
return builder.build();
}
} | mit |
JosielSantos/android-metronome | app/src/main/java/net/jssantos/metronome/ui/fragment/Settings.java | 455 | package net.jssantos.metronome.ui.fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import net.jssantos.metronome.R;
public class Settings extends PreferenceFragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
| mit |
webdude21/HackerRank | src/main/java/algorithms/largestrectangle/Solution.java | 994 | package algorithms.largestrectangle;
import java.util.Scanner;
public class Solution {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] h = new int[n];
String[] hItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int hItem = Integer.parseInt(hItems[i]);
h[i] = hItem;
}
long result = largestRectangle(h);
System.out.println(result);
scanner.close();
}
static int largestRectangle(int[] input) {
int maxArea = Integer.MIN_VALUE;
for (int i = 0; i < input.length; i++) {
int localMin = Integer.MAX_VALUE;
for (int j = i; j < input.length; j++) {
localMin = Math.min(input[j], localMin);
maxArea = Math.max((j + 1 - i) * localMin, maxArea);
}
}
return maxArea;
}
}
| mit |
weizhongjia/werewolf | src/main/java/com/msh/room/model/room/RoomState.java | 657 | package com.msh.room.model.room;
import com.msh.room.dto.event.JudgeEvent;
import com.msh.room.dto.event.PlayerEvent;
import com.msh.room.dto.response.JudgeDisplayInfo;
import com.msh.room.dto.response.PlayerDisplayInfo;
import com.msh.room.dto.room.RoomStateData;
import com.msh.room.service.DataBaseService;
/**
* Created by zhangruiqian on 2017/5/25.
*/
public interface RoomState {
void setDataService(DataBaseService service);
RoomStateData resolveJudgeEvent(JudgeEvent event);
JudgeDisplayInfo displayJudgeInfo();
RoomStateData resolvePlayerEvent(PlayerEvent event);
PlayerDisplayInfo displayPlayerInfo(int seatNumber);
}
| mit |
grzegorzblaszczyk/transcoder | src/test/java/gbc/i18n/pl/PolishTranscoderTest.java | 1414 | package gbc.i18n.pl;
import static org.junit.Assert.assertEquals;
import gbc.i18n.AbstractTranscoderTest;
import org.junit.Before;
import org.junit.Test;
public class PolishTranscoderTest extends AbstractTranscoderTest {
public static final String TEST_DATA = "zażółć gęślą jaźń";
public static final String TEST_DATA_ENTITIES = "zażółć gęślą jaźń";
public static final String EXPECTED_RESULT = "zazolc gesla jazn";
public static final String[] PANGRAMS = {
"Pchnąć w tę łódź jeża lub ośm skrzyń fig.",
"Pójdźże, kiń tę chmurność w głąb flaszy!",
"Dość gróźb fuzją, klnę, pych i małżeństw!",
"Pójdź w loch zbić małżeńską gęś futryn!",
"Filmuj rzeź żądań, pość, gnęb chłystków!",
"O, mógłże sęp chlań wyjść furtką bździn.",
"Mężny bądź, chroń pułk twój i sześć flag.",
"Chwyć małżonkę, strój bądź pleśń z fugi."
};
@Before
public void setUp() throws Exception {
transcoder = new PolishTranscoder();
}
@Test
public void testDecode() {
assertEquals(EXPECTED_RESULT, transcoder.decode(TEST_DATA));
assertEquals(EXPECTED_RESULT.toUpperCase(), transcoder.decode(TEST_DATA.toUpperCase()));
}
@Test
public void testEntitiesAndNative() {
testEntitiesAndNative(transcoder, TEST_DATA, TEST_DATA_ENTITIES);
testPangrams(transcoder, PANGRAMS);
}
}
| mit |
charques/renthell | scoring-mgmt-srv/src/main/java/io/renthell/scoringmgmtsrv/configuration/JacksonConfiguration.java | 1306 | package io.renthell.scoringmgmtsrv.configuration;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
ObjectMapper mapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());;
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
mapper.setDateFormat(df);
return mapper;
}
}
| mit |
zellerdev/jabref | src/main/java/org/jabref/logic/importer/fileformat/OvidImporter.java | 11216 | package org.jabref.logic.importer.fileformat;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.entry.AuthorList;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UnknownField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.EntryTypeFactory;
import org.jabref.model.entry.types.StandardEntryType;
/**
* Imports an Ovid file.
*/
public class OvidImporter extends Importer {
private static final Pattern OVID_SOURCE_PATTERN = Pattern
.compile("Source ([ \\w&\\-,:]+)\\.[ ]+([0-9]+)\\(([\\w\\-]+)\\):([0-9]+\\-?[0-9]+?)\\,.*([0-9][0-9][0-9][0-9])");
private static final Pattern OVID_SOURCE_PATTERN_NO_ISSUE = Pattern
.compile("Source ([ \\w&\\-,:]+)\\.[ ]+([0-9]+):([0-9]+\\-?[0-9]+?)\\,.*([0-9][0-9][0-9][0-9])");
private static final Pattern OVID_SOURCE_PATTERN_2 = Pattern.compile(
"([ \\w&\\-,]+)\\. Vol ([0-9]+)\\(([\\w\\-]+)\\) ([A-Za-z]+) ([0-9][0-9][0-9][0-9]), ([0-9]+\\-?[0-9]+)");
private static final Pattern INCOLLECTION_PATTERN = Pattern.compile(
"(.+)\\(([0-9][0-9][0-9][0-9])\\)\\. ([ \\w&\\-,:]+)\\.[ ]+\\(pp. ([0-9]+\\-?[0-9]+?)\\).[A-Za-z0-9, ]+pp\\. "
+ "([\\w, ]+): ([\\w, ]+)");
private static final Pattern BOOK_PATTERN = Pattern.compile(
"\\(([0-9][0-9][0-9][0-9])\\)\\. [A-Za-z, ]+([0-9]+) pp\\. ([\\w, ]+): ([\\w, ]+)");
private static final String OVID_PATTERN_STRING = "<[0-9]+>";
private static final Pattern OVID_PATTERN = Pattern.compile(OVID_PATTERN_STRING);
private static final int MAX_ITEMS = 50;
@Override
public String getName() {
return "Ovid";
}
@Override
public StandardFileType getFileType() {
return StandardFileType.TXT;
}
@Override
public String getDescription() {
return "Imports an Ovid file.";
}
@Override
public boolean isRecognizedFormat(BufferedReader reader) throws IOException {
String str;
int i = 0;
while (((str = reader.readLine()) != null) && (i < MAX_ITEMS)) {
if (OvidImporter.OVID_PATTERN.matcher(str).find()) {
return true;
}
i++;
}
return false;
}
@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
List<BibEntry> bibitems = new ArrayList<>();
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (!line.isEmpty() && (line.charAt(0) != ' ')) {
sb.append("__NEWFIELD__");
}
sb.append(line);
sb.append('\n');
}
String[] items = sb.toString().split(OVID_PATTERN_STRING);
for (int i = 1; i < items.length; i++) {
Map<Field, String> h = new HashMap<>();
String[] fields = items[i].split("__NEWFIELD__");
for (String field : fields) {
int linebreak = field.indexOf('\n');
String fieldName = field.substring(0, linebreak).trim();
String content = field.substring(linebreak).trim();
// Check if this is the author field (due to a minor special treatment for this field):
boolean isAuthor = (fieldName.indexOf("Author") == 0)
&& !fieldName.contains("Author Keywords")
&& !fieldName.contains("Author e-mail");
// Remove unnecessary dots at the end of lines, unless this is the author field,
// in which case a dot at the end could be significant:
if (!isAuthor && content.endsWith(".")) {
content = content.substring(0, content.length() - 1);
}
if (isAuthor) {
h.put(StandardField.AUTHOR, content);
} else if (fieldName.startsWith("Title")) {
content = content.replaceAll("\\[.+\\]", "").trim();
if (content.endsWith(".")) {
content = content.substring(0, content.length() - 1);
}
h.put(StandardField.TITLE, content);
} else if (fieldName.startsWith("Chapter Title")) {
h.put(new UnknownField("chaptertitle"), content);
} else if (fieldName.startsWith("Source")) {
Matcher matcher;
if ((matcher = OvidImporter.OVID_SOURCE_PATTERN.matcher(content)).find()) {
h.put(StandardField.JOURNAL, matcher.group(1));
h.put(StandardField.VOLUME, matcher.group(2));
h.put(StandardField.ISSUE, matcher.group(3));
h.put(StandardField.PAGES, matcher.group(4));
h.put(StandardField.YEAR, matcher.group(5));
} else if ((matcher = OvidImporter.OVID_SOURCE_PATTERN_NO_ISSUE.matcher(content)).find()) { // may be missing the issue
h.put(StandardField.JOURNAL, matcher.group(1));
h.put(StandardField.VOLUME, matcher.group(2));
h.put(StandardField.PAGES, matcher.group(3));
h.put(StandardField.YEAR, matcher.group(4));
} else if ((matcher = OvidImporter.OVID_SOURCE_PATTERN_2.matcher(content)).find()) {
h.put(StandardField.JOURNAL, matcher.group(1));
h.put(StandardField.VOLUME, matcher.group(2));
h.put(StandardField.ISSUE, matcher.group(3));
h.put(StandardField.MONTH, matcher.group(4));
h.put(StandardField.YEAR, matcher.group(5));
h.put(StandardField.PAGES, matcher.group(6));
} else if ((matcher = OvidImporter.INCOLLECTION_PATTERN.matcher(content)).find()) {
h.put(StandardField.EDITOR, matcher.group(1).replace(" (Ed)", ""));
h.put(StandardField.YEAR, matcher.group(2));
h.put(StandardField.BOOKTITLE, matcher.group(3));
h.put(StandardField.PAGES, matcher.group(4));
h.put(StandardField.ADDRESS, matcher.group(5));
h.put(StandardField.PUBLISHER, matcher.group(6));
} else if ((matcher = OvidImporter.BOOK_PATTERN.matcher(content)).find()) {
h.put(StandardField.YEAR, matcher.group(1));
h.put(StandardField.PAGES, matcher.group(2));
h.put(StandardField.ADDRESS, matcher.group(3));
h.put(StandardField.PUBLISHER, matcher.group(4));
}
// Add double hyphens to page ranges:
if (h.get(StandardField.PAGES) != null) {
h.put(StandardField.PAGES, h.get(StandardField.PAGES).replace("-", "--"));
}
} else if ("Abstract".equals(fieldName)) {
h.put(StandardField.ABSTRACT, content);
} else if ("Publication Type".equals(fieldName)) {
if (content.contains("Book")) {
h.put(InternalField.TYPE_HEADER, "book");
} else if (content.contains("Journal")) {
h.put(InternalField.TYPE_HEADER, "article");
} else if (content.contains("Conference Paper")) {
h.put(InternalField.TYPE_HEADER, "inproceedings");
}
} else if (fieldName.startsWith("Language")) {
h.put(StandardField.LANGUAGE, content);
} else if (fieldName.startsWith("Author Keywords")) {
content = content.replace(";", ",").replace(" ", " ");
h.put(StandardField.KEYWORDS, content);
} else if (fieldName.startsWith("ISSN")) {
h.put(StandardField.ISSN, content);
} else if (fieldName.startsWith("DOI Number")) {
h.put(StandardField.DOI, content);
}
}
// Now we need to check if a book entry has given editors in the author field;
// if so, rearrange:
String auth = h.get(StandardField.AUTHOR);
if ((auth != null) && auth.contains(" [Ed]")) {
h.remove(StandardField.AUTHOR);
h.put(StandardField.EDITOR, auth.replace(" [Ed]", ""));
}
// Rearrange names properly:
auth = h.get(StandardField.AUTHOR);
if (auth != null) {
h.put(StandardField.AUTHOR, fixNames(auth));
}
auth = h.get(StandardField.EDITOR);
if (auth != null) {
h.put(StandardField.EDITOR, fixNames(auth));
}
// Set the entrytype properly:
EntryType entryType = h.containsKey(InternalField.TYPE_HEADER) ? EntryTypeFactory.parse(h.get(InternalField.TYPE_HEADER)) : BibEntry.DEFAULT_TYPE;
h.remove(InternalField.TYPE_HEADER);
if (entryType.equals(StandardEntryType.Book) && h.containsKey(new UnknownField("chaptertitle"))) {
// This means we have an "incollection" entry.
entryType = StandardEntryType.InCollection;
// Move the "chaptertitle" to just "title":
h.put(StandardField.TITLE, h.remove(new UnknownField("chaptertitle")));
}
BibEntry b = new BibEntry(entryType);
b.setField(h);
bibitems.add(b);
}
return new ParserResult(bibitems);
}
/**
* Convert a string of author names into a BibTeX-compatible format.
* @param content The name string.
* @return The formatted names.
*/
private static String fixNames(String content) {
String names;
if (content.indexOf(';') > 0) { //LN FN; [LN FN;]*
names = content.replaceAll("[^\\.A-Za-z,;\\- ]", "").replace(";", " and");
} else if (content.indexOf(" ") > 0) {
String[] sNames = content.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sNames.length; i++) {
if (i > 0) {
sb.append(" and ");
}
sb.append(sNames[i].replaceFirst(" ", ", "));
}
names = sb.toString();
} else {
names = content;
}
return AuthorList.fixAuthorLastNameFirst(names);
}
}
| mit |
Azure/azure-sdk-for-java | sdk/streamanalytics/azure-resourcemanager-streamanalytics/src/samples/java/com/azure/resourcemanager/streamanalytics/generated/InputsCreateOrReplaceSamples.java | 6195 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.streamanalytics.generated;
import com.azure.resourcemanager.streamanalytics.models.AvroSerialization;
import com.azure.resourcemanager.streamanalytics.models.BlobReferenceInputDataSource;
import com.azure.resourcemanager.streamanalytics.models.BlobStreamInputDataSource;
import com.azure.resourcemanager.streamanalytics.models.CsvSerialization;
import com.azure.resourcemanager.streamanalytics.models.Encoding;
import com.azure.resourcemanager.streamanalytics.models.EventHubStreamInputDataSource;
import com.azure.resourcemanager.streamanalytics.models.IoTHubStreamInputDataSource;
import com.azure.resourcemanager.streamanalytics.models.JsonSerialization;
import com.azure.resourcemanager.streamanalytics.models.ReferenceInputProperties;
import com.azure.resourcemanager.streamanalytics.models.StorageAccount;
import com.azure.resourcemanager.streamanalytics.models.StreamInputProperties;
import java.util.Arrays;
/** Samples for Inputs CreateOrReplace. */
public final class InputsCreateOrReplaceSamples {
/*
* x-ms-original-file: specification/streamanalytics/resource-manager/Microsoft.StreamAnalytics/stable/2020-03-01/examples/Input_Create_Stream_IoTHub_Avro.json
*/
/**
* Sample code: Create a stream IoT Hub input with Avro serialization.
*
* @param manager Entry point to StreamAnalyticsManager.
*/
public static void createAStreamIoTHubInputWithAvroSerialization(
com.azure.resourcemanager.streamanalytics.StreamAnalyticsManager manager) {
manager
.inputs()
.define("input7970")
.withExistingStreamingjob("sjrg3467", "sj9742")
.withProperties(
new StreamInputProperties()
.withSerialization(new AvroSerialization())
.withDatasource(
new IoTHubStreamInputDataSource()
.withIotHubNamespace("iothub")
.withSharedAccessPolicyName("owner")
.withSharedAccessPolicyKey("sharedAccessPolicyKey=")
.withConsumerGroupName("sdkconsumergroup")
.withEndpoint("messages/events")))
.create();
}
/*
* x-ms-original-file: specification/streamanalytics/resource-manager/Microsoft.StreamAnalytics/stable/2020-03-01/examples/Input_Create_Reference_Blob_CSV.json
*/
/**
* Sample code: Create a reference blob input with CSV serialization.
*
* @param manager Entry point to StreamAnalyticsManager.
*/
public static void createAReferenceBlobInputWithCSVSerialization(
com.azure.resourcemanager.streamanalytics.StreamAnalyticsManager manager) {
manager
.inputs()
.define("input7225")
.withExistingStreamingjob("sjrg8440", "sj9597")
.withProperties(
new ReferenceInputProperties()
.withSerialization(new CsvSerialization().withFieldDelimiter(",").withEncoding(Encoding.UTF8))
.withDatasource(new BlobReferenceInputDataSource()))
.create();
}
/*
* x-ms-original-file: specification/streamanalytics/resource-manager/Microsoft.StreamAnalytics/stable/2020-03-01/examples/Input_Create_Stream_EventHub_JSON.json
*/
/**
* Sample code: Create a stream Event Hub input with JSON serialization.
*
* @param manager Entry point to StreamAnalyticsManager.
*/
public static void createAStreamEventHubInputWithJSONSerialization(
com.azure.resourcemanager.streamanalytics.StreamAnalyticsManager manager) {
manager
.inputs()
.define("input7425")
.withExistingStreamingjob("sjrg3139", "sj197")
.withProperties(
new StreamInputProperties()
.withSerialization(new JsonSerialization().withEncoding(Encoding.UTF8))
.withDatasource(
new EventHubStreamInputDataSource()
.withConsumerGroupName("sdkconsumergroup")
.withEventHubName("sdkeventhub")
.withServiceBusNamespace("sdktest")
.withSharedAccessPolicyName("RootManageSharedAccessKey")
.withSharedAccessPolicyKey("someSharedAccessPolicyKey==")))
.create();
}
/*
* x-ms-original-file: specification/streamanalytics/resource-manager/Microsoft.StreamAnalytics/stable/2020-03-01/examples/Input_Create_Stream_Blob_CSV.json
*/
/**
* Sample code: Create a stream blob input with CSV serialization.
*
* @param manager Entry point to StreamAnalyticsManager.
*/
public static void createAStreamBlobInputWithCSVSerialization(
com.azure.resourcemanager.streamanalytics.StreamAnalyticsManager manager) {
manager
.inputs()
.define("input8899")
.withExistingStreamingjob("sjrg8161", "sj6695")
.withProperties(
new StreamInputProperties()
.withSerialization(new CsvSerialization().withFieldDelimiter(",").withEncoding(Encoding.UTF8))
.withDatasource(
new BlobStreamInputDataSource()
.withSourcePartitionCount(16)
.withStorageAccounts(
Arrays
.asList(
new StorageAccount()
.withAccountName("someAccountName")
.withAccountKey("someAccountKey==")))
.withContainer("state")
.withPathPattern("{date}/{time}")
.withDateFormat("yyyy/MM/dd")
.withTimeFormat("HH")))
.create();
}
}
| mit |
murex/murex-coding-dojo | Beirut/2016/2016-01-20-codeline/src/main/java/CodeLine.java | 1623 | import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class CodeLine {
public static long lineCount(List<String> lines) throws IOException {
List<String> strings = linesWithoutBackslashStarComment(lines);
return listWithoutDoubleSlashComments(strings).count();
}
private static Stream<String> listWithoutDoubleSlashComments(List<String> lines) {
return lines.stream().filter((l) -> {
String trimmedLine = l.trim();
return !(trimmedLine.startsWith("//") || trimmedLine.isEmpty());
});
}
private static List<String> linesWithoutBackslashStarComment(List<String> lines) throws IOException {
List<String> linesWithoutBackslashStar = Lists.newArrayList();
boolean findmatch = false;
for(String line : lines){
if(line.contains("/*")&& !findmatch){
findmatch= true;
if(!line.startsWith("/*")){
linesWithoutBackslashStar.add(line);
}
}
if(line.contains("*/")){
int lastIndexOfCommentBlockEnding = line.lastIndexOf("*/");
String codeLineTail = line.substring(lastIndexOfCommentBlockEnding + 2);
if(listWithoutDoubleSlashComments(ImmutableList.of(codeLineTail)).count()==0)
{
findmatch = false;
continue;
}
}
if(!findmatch){
linesWithoutBackslashStar.add(line);
}
}
return linesWithoutBackslashStar;
}
}
| mit |
tdsis/lambda-forest | src/main/java/br/com/tdsis/lambda/forest/http/exception/MethodNotAllowedException.java | 1048 | package br.com.tdsis.lambda.forest.http.exception;
import org.apache.http.HttpStatus;
/**
* The MethodNotAllowedException class
* <p>
* This is a concrete class of the the HttpException class.
* It represents a method not allowed http response.
*
* @author nmelo
* @version 1.0.0
* @since 1.0.0
* @see {@link HttpStatus#SC_METHOD_NOT_ALLOWED}
*/
public class MethodNotAllowedException extends HttpException {
private static final long serialVersionUID = 3099405537692347007L;
public MethodNotAllowedException() {
super(HttpStatus.SC_METHOD_NOT_ALLOWED);
}
public MethodNotAllowedException(Object entity) {
super(entity, HttpStatus.SC_METHOD_NOT_ALLOWED);
}
public MethodNotAllowedException(final String message, final Throwable cause) {
super(HttpStatus.SC_METHOD_NOT_ALLOWED, message, cause);
}
public MethodNotAllowedException(Object entity, final String message, final Throwable cause) {
super(entity, HttpStatus.SC_METHOD_NOT_ALLOWED, message, cause);
}
}
| mit |
dede12138/androidScreenShareAndControl | lib/src/main/java/com/client/Install.java | 3466 | package com.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
/**
* Created by wanjian on 2017/4/5.
*/
public class Install {
public static void main(String[] args) {
install();
}
public static void install() {
adbCommond("push Main.dex /sdcard/Main.dex");
String path = "export CLASSPATH=/sdcard/Main.dex";
String app = "exec app_process /sdcard com.wanjian.puppet.Main";
shellCommond(new String[]{path, app});
}
private static void adbCommond(String com) {
System.out.println("adbCommond...."+com);
commond("sh", "./adb " + com);
}
private static void shellCommond(String[] com) {
System.out.println("shell commond..."+ Arrays.toString(com));
try {
Process process = Runtime
.getRuntime()
.exec("./adb shell "); // adb
// shell
final BufferedWriter outputStream = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream()));
for (String s : com) {
outputStream.write(s);
outputStream.write("\n");
}
outputStream.flush();
System.out.println("shell write finished...");
readError(process.getErrorStream());
adbCommond("forward tcp:8888 localabstract:puppet-ver1");
readResult(process.getInputStream());
while (true) {
Thread.sleep(Integer.MAX_VALUE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readError(final InputStream errorStream) {
new Thread(){
@Override
public void run() {
super.run();
readResult(errorStream);
}
}.start();
}
///////////////
private static void commond(String c, String com) {
System.out.println("---> " + c + com);
try {
Process process = Runtime
.getRuntime()
.exec(c); // adb
final BufferedWriter outputStream = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream()));
outputStream.write(com);
outputStream.write("\n");
outputStream.write("exit\n");
outputStream.flush();
int i = process.waitFor();
readResult(process.getInputStream());
System.out.println("------END-------");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void readResult(final InputStream stream) {
System.out.println("read result.....");
try {
String line;
final BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("-------END------");
} catch (IOException e) {
e.printStackTrace();
try {
stream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
| mit |
masayuki038/bon-ten | src/main/java/net/wrap_trap/bonten/message/StepOk.java | 78 | package net.wrap_trap.bonten.message;
public class StepOk extends Message {}
| mit |