blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1603037f5c744005191412b8d08b6c04abb5338c | 3d32b414776777d1fe482719ef59f20eb39e9f48 | /app/src/main/java/com/example/krishnadamarla/sunshine/sync/SunshineSyncAdapter.java | 120cddee08c24d4a4bdf6ae0457e397f55c4bbfc | [] | no_license | kk3399/Sunshine | 8e4123e3e1d82abf114fd33d70fffc3192d473b0 | 70441142ae46133863b439caf28821c1ea3608a9 | refs/heads/master | 2016-09-05T20:58:15.861830 | 2015-01-11T23:26:21 | 2015-01-11T23:26:21 | 28,484,749 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,774 | java | package com.example.krishnadamarla.sunshine.sync;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SyncRequest;
import android.content.SyncResult;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.example.krishnadamarla.sunshine.MainActivity;
import com.example.krishnadamarla.sunshine.R;
import com.example.krishnadamarla.sunshine.WeatherAPIClient;
import com.example.krishnadamarla.sunshine.data.WeatherContract;
import com.example.krishnadamarla.sunshine.helpers.Utility;
import com.example.krishnadamarla.sunshine.helpers.WeatherJsonParser;
import org.json.JSONException;
import java.util.Calendar;
import java.util.Date;
/**
* Created by krishnadamarla on 1/10/15.
*/
public class SunshineSyncAdapter extends AbstractThreadedSyncAdapter {
public final static String LOG_TAG = SunshineSyncAdapter.class.getSimpleName();
// Interval at which to sync with the weather, in milliseconds.
// 60 seconds (1 minute) * 180 = 3 hours
public static final int SYNC_INTERVAL = 10; // 60 * 180;
public static final int SYNC_FLEXTIME = SYNC_INTERVAL/3;
private static final String[] NOTIFY_WEATHER_PROJECTION = new String[] {
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC
};
// these indices must match the projection
private static final int INDEX_WEATHER_ID = 0;
private static final int INDEX_MAX_TEMP = 1;
private static final int INDEX_MIN_TEMP = 2;
private static final int INDEX_SHORT_DESC = 3;
private static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
private static final int WEATHER_NOTIFICATION_ID = 3004;
public SunshineSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
private String getWeatherMapAPI(String zipCode, int numOfDays)
{
Uri.Builder builder = new Uri.Builder();
builder.scheme("http");
builder.authority("api.openweathermap.org");
builder.appendPath("data");
builder.appendPath("2.5");
builder.appendPath("forecast");
builder.appendPath("daily");
builder.appendQueryParameter("q", zipCode);
builder.appendQueryParameter("mode", "json");
builder.appendQueryParameter("units", "metric");
builder.appendQueryParameter("cnt",Integer.toString(numOfDays));
return builder.build().toString();
}
public static long addLocation(Context context, String locationSetting, String cityName, double lat, double lon)
{
long locationId;
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(WeatherContract.LocationEntry.CONTENT_URI,
new String[]{WeatherContract.LocationEntry._ID},
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
new String[]{locationSetting},
null);
if (cursor.moveToNext())
{
Log.v(LOG_TAG, "location already exists " + locationSetting);
locationId = cursor.getLong(0);
cursor.close();
}
else
{
cursor.close();
ContentValues values = new ContentValues();
values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
Uri locationUri = resolver.insert(WeatherContract.LocationEntry.CONTENT_URI, values);
cursor.close();
locationId = ContentUris.parseId(locationUri);
}
return locationId;
}
public static int addWeather(Context context, ContentValues[] values)
{
Log.v(LOG_TAG,"addWeather is getting called");
ContentResolver resolver = context.getContentResolver();
return resolver.bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, values);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Log.i(LOG_TAG, "Code reached onPerformSync");
String zipCode = Utility.getPreferredLocation(getContext());
String weatherJson = WeatherAPIClient.GetForecastForAWeek(getWeatherMapAPI(zipCode, 14));
if (weatherJson == null || weatherJson.isEmpty())
return;
try
{
WeatherJsonParser.getWeatherDataFromJson(weatherJson, zipCode, getContext());
notifyWeather();
}
catch(JSONException je)
{ Log.e("JSON Exception", "exception while converting results to json", je);}
}
private void notifyWeather() {
Context context = getContext();
//checking the last update and notify if it' the first of the day
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if(!prefs.getBoolean(context.getString(R.string.pref_general_notifications_key),
Boolean.parseBoolean(context.getString(R.string.pref_general_notifications_default))))
{
Log.i(LOG_TAG, "NOT SET FOR NOTIFICATIONS");
return;
}
else
{
Log.i(LOG_TAG, "SHOW FOR NOTIFICATIONS");
}
String lastNotificationKey = context.getString(R.string.pref_last_notification);
long lastSync = prefs.getLong(lastNotificationKey, 0);
if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) {
// Last sync was more than 1 day ago, let's send a notification with the weather.
String locationQuery = Utility.getPreferredLocation(context);
Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, WeatherContract.getDbDateString(new Date()));
boolean isMetric = Utility.isMetric(context);
// we'll query our contentProvider, as always
Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
int weatherId = cursor.getInt(INDEX_WEATHER_ID);
double high = cursor.getDouble(INDEX_MAX_TEMP);
double low = cursor.getDouble(INDEX_MIN_TEMP);
String desc = cursor.getString(INDEX_SHORT_DESC);
int iconId = Utility.getIconResourceForWeatherCondition(weatherId);
String title = context.getString(R.string.app_name);
// Define the text of the forecast.
String contentText = String.format(context.getString(R.string.format_notification),
desc,
Utility.formatTemperature(context, high, isMetric),
Utility.formatTemperature(context, low,isMetric));
//build your notification here.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(context.getString(R.string.notification_title))
.setContentText(contentText);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(lastNotificationKey, WEATHER_NOTIFICATION_ID, mBuilder.build());
//refreshing last sync
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(lastNotificationKey, System.currentTimeMillis());
editor.commit();
}
}
}
/*
* Helper method to schedule the sync adapter periodic execution
*/
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
Account account = getSyncAccount(context);
String authority = context.getString(R.string.content_authority);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// we can enable inexact timers in our periodic sync
Log.i(LOG_TAG, "old sync process used");
SyncRequest request = new SyncRequest.Builder().
setExtras(new Bundle()).
syncPeriodic(syncInterval, flexTime).
setSyncAdapter(account, authority).build();
ContentResolver.requestSync(request);
} else {
ContentResolver.addPeriodicSync(account,
authority, new Bundle(), syncInterval);
}
}
/**
* Helper method to have the sync adapter sync immediately
* @param context The context used to access the account service
*/
public static void syncImmediately(Context context) {
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(getSyncAccount(context),
context.getString(R.string.content_authority), bundle);
}
private static void onAccountCreated(Account newAccount, Context context) {
/*
* Since we've created an account
*/
/*
* Without calling setSyncAutomatically, our periodic sync will not be enabled.
*/
ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true);
ContentResolver.setIsSyncable(newAccount, context.getString(R.string.content_authority), 1);
SunshineSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME);
/*
* Finally, let's do a sync to get things started
*/
syncImmediately(context);
}
public static void initializeSyncAdapter(Context context) {
getSyncAccount(context);
}
/**
* Helper method to get the fake account to be used with SyncAdapter, or make a new one
* if the fake account doesn't exist yet. If we make a new account, we call the
* onAccountCreated method so we can initialize things.
*
* @param context The context used to access the account service
* @return a fake account.
*/
public static Account getSyncAccount(Context context) {
// Get an instance of the Android account manager
AccountManager accountManager =
(AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
// Create the account type and default account
Account newAccount = new Account(
context.getString(R.string.app_name), context.getString(R.string.sync_account_type));
// If the password doesn't exist, the account doesn't exist
if ( null == accountManager.getPassword(newAccount) ) {
/*
* Add the account and account type, no password or user data
* If successful, return the Account object, otherwise report an error.
*/
if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
return null;
}
/*
* If you don't set android:syncable="true" in
* in your <provider> element in the manifest,
* then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
* here.
*/
//ContentResolver.setIsSyncable(newAccount, context.getString(R.string.content_authority), 1);
onAccountCreated(newAccount, context);
}
return newAccount;
}
}
| [
"damarla.kk@gmail.com"
] | damarla.kk@gmail.com |
3ec0eb14b31e5abd4204aa48e6f82980a77bfaa4 | 5d77761194064b637d0f25b791d84e99c2683b6e | /spring-test/spring-bean-test/src/main/java/org/wcframework/entity/DemoAnnotationEntity.java | 413b9a7050965b2b23a4790dc8780da86493ce96 | [] | no_license | wanghaojia/WCFrameWork | 339966acfd431e12478f52f4d730800eeded758a | fef999f4338a7a62c01203ddd0683f4df443deed | refs/heads/master | 2020-03-14T12:36:49.209101 | 2018-05-02T10:24:08 | 2018-05-02T10:24:08 | 131,612,628 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,076 | java | package org.wcframework.entity;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* @author haojia.wang
* @version v1.0
* @Package org.wcframework.entity
* @Description 测试实体,使用注解方式注入实体
* @date 2018/3/9 11:53
*/
@Component
public class DemoAnnotationEntity implements Serializable {
private static final long serialVersionUID = 1273822905598363157L;
/** 测试参数1,类型:String */
private String param1;
/** 测试参数2,类型:Integer */
private Integer param2;
/** 测试参数3、类型:Boolean */
private Boolean param3;
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public Integer getParam2() {
return param2;
}
public void setParam2(Integer param2) {
this.param2 = param2;
}
public Boolean getParam3() {
return param3;
}
public void setParam3(Boolean param3) {
this.param3 = param3;
}
}
| [
"whj74110"
] | whj74110 |
a4cfa2014e8248de55e6008ecd646281f7f9ca9b | 2ca93846ab8f638a7d8cd80f91566ee3632cf186 | /Entire Dataset/3-37/seng2200/ConsumeTerritory.java | 303e4d6cb6e9c614d64d73889a5ec6361fa6aa66 | [
"MIT"
] | permissive | hjc851/SourceCodePlagiarismDetectionDataset | 729483c3b823c455ffa947fc18d6177b8a78a21f | f67bc79576a8df85e8a7b4f5d012346e3a76db37 | refs/heads/master | 2020-07-05T10:48:29.980984 | 2019-08-15T23:51:55 | 2019-08-15T23:51:55 | 202,626,196 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 259 | java | package seng2200;
public class ConsumeTerritory extends Sate {
public static double diagnose = 0.4523795593889639;
public ConsumeTerritory() {
super("Starve State");
}
public ConsumeTerritory(double keh) {
super("Starve State", keh);
}
}
| [
"hayden.cheers@me.com"
] | hayden.cheers@me.com |
ae68de5c344274635a8b7ecf68fb1baba77c925f | c66a0383d347605a96032db54714fafc6cb61a98 | /src/test/java/king/greg/aoc2019/Day13Test.java | e7019963537a28f6559e4090881e251f2c0b3163 | [] | no_license | gsking80/AoC-2019 | 14c5dc6aebaa69bc13101aa577f0043484439790 | b279309f14e83fcb0a5b97a087a44d98e49dff7d | refs/heads/master | 2021-07-11T04:27:16.102543 | 2020-11-29T19:15:28 | 2020-11-29T19:15:28 | 220,522,344 | 1 | 0 | null | 2020-10-13T17:19:11 | 2019-11-08T18:08:02 | Java | UTF-8 | Java | false | false | 1,071 | java | package king.greg.aoc2019;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class Day13Test {
@Test
public void testSolution1() throws FileNotFoundException {
final FileReader fileReader = new FileReader(getClass().getClassLoader().getResource("Day13/input.txt").getPath());
final Day13 day13 = new Day13(fileReader);
final List<Long> inputs = new ArrayList<>();
day13.execute(inputs);
Assertions.assertThat(day13.numTiles(2L)).isEqualTo(236L);
}
@Test
public void testSolution2() throws FileNotFoundException {
final FileReader fileReader = new FileReader(getClass().getClassLoader().getResource("Day13/input.txt").getPath());
final Day13 day13 = new Day13(fileReader);
final List<Long> inputs = new ArrayList<>();
day13.editProgram(0, 0L, 2L);
day13.execute(inputs);
Assertions.assertThat(day13.getScore()).isEqualTo(11040L);
}
}
| [
"king.greg@gmail.com"
] | king.greg@gmail.com |
b8873b0f875d0140429c753b40863e9783e760ba | 0696e5d40c3c17b1b54194fb3baf11cfbd27b062 | /src/it/unitn/rakwaht/security/testing/teacher/ManageGrades.java | 3972b3b6ef0c6e5d4c99a2fa6e3b5cdfbc77f855 | [] | no_license | rakwaht/Schoolmate-Security-Assessment | 34f58e09fcf336aaf26b522c1695d01f78cd010a | 9aa126dcf9948b03c2e8837a05573ac45c3b330c | refs/heads/master | 2021-01-18T09:53:42.783065 | 2015-05-20T15:16:02 | 2015-05-20T15:16:02 | 35,955,607 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,699 | java | package it.unitn.rakwaht.security.testing.teacher;
import it.unitn.rakwaht.security.testing.util.Manager;
import net.sourceforge.jwebunit.junit.WebTester;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ManageGrades {
private WebTester tester;
@Before
public void setup(){
tester = new WebTester();
tester.setBaseUrl(Manager.getBaseUrl());
tester.beginAt("index.php");
tester.setTextField("username", "teacher");
tester.setTextField("password", "teacher");
tester.submit();
tester.clickLinkWithExactText("Class");
}
@Test
public void page(){
tester.assertMatch("Class Settings");
tester.setWorkingForm("teacher");
tester.setHiddenField("page", "2'> <a href=www.unitn.it>malicious link</a> <br '");
tester.clickLinkWithExactText("Grades");
tester.assertMatch("Grades");
tester.assertLinkNotPresentWithText("malicious link");
}
@Test
public void page2(){
tester.assertMatch("Class Settings");
tester.setWorkingForm("teacher");
tester.setHiddenField("page2","3'><a href=www.unitn.it>malicious link</a> <br ");
Manager.addNewSubmitButton("/html//form[@name=\"teacher\"]",tester);
tester.submit();
tester.assertMatch("Grades");
tester.assertLinkNotPresentWithText("malicious link");
}
@Test
public void selectclass(){
tester.assertMatch("Class Settings");
tester.setWorkingForm("teacher");
tester.setHiddenField("selectclass", "1' -- '> <a href=www.unitn.it>malicious link</a> <br '");
tester.clickLinkWithExactText("Grades");
tester.assertMatch("Grades");
tester.assertLinkNotPresentWithText("malicious link");
}
@After
public void restore(){
}
}
| [
"Martintoni@MacBook-Pro-di-Martintoni.local"
] | Martintoni@MacBook-Pro-di-Martintoni.local |
baa30ee85c66f5140f1ba4b36648aeb592e0ec95 | 87c16c410b8ba1d66376f22ebc5c494b4b8b6294 | /study/study/flightsearch/main/java/filereader/CSVFileReader.java | d62da76468c9200c24bb2bd2b406b6b110206f2e | [] | no_license | DRahul89/ds-algo-practise | 47bb6f887b9aaca73df69dba98da834abdb4a4d6 | 93c164a3e0de07aba50c1508983e7f28d7ce5552 | refs/heads/master | 2021-08-28T04:45:12.460967 | 2017-12-11T07:26:29 | 2017-12-11T07:26:29 | 110,454,062 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,653 | java | package main.java.filereader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import main.java.constants.FlightDataConstants;
import main.java.model.FlightData;
/**
* This class will read the CSV flight data files
*
* @author rdixi7
*
*/
public class CSVFileReader implements FileReader {
@SuppressWarnings("deprecation")
@Override
public List<FlightData> readFlighDataFile(final String filePath) {
int count = 0;
String csvSeperator = FlightDataConstants.CSV_FILE_SEPERATOR;
List<FlightData> flightData = new ArrayList<>();
SimpleDateFormat smf = new SimpleDateFormat("dd-mm-yy");
String fileLine = null;
try (BufferedReader br = new BufferedReader(new java.io.FileReader(filePath))) {
while ((fileLine = br.readLine()) != null) {
try {
if (++count == 1)
continue;
String[] data = fileLine.split(csvSeperator);
FlightData fiData = new FlightData();
fiData.setFlightNum(data[0]);
fiData.setDepLocation(data[1]);
fiData.setArrLocation(data[2]);
fiData.setValidity(smf.parse(data[3]));
fiData.setFlightTime(data[4]);
fiData.setFlightDuration(Double.parseDouble(data[5]));
fiData.setFare(Integer.parseInt(data[6]));
flightData.add(fiData);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return flightData;
}
}
| [
"dixit.rahul09@gmail.com"
] | dixit.rahul09@gmail.com |
e9d0172f1c15a64abce49f710ba4055392a35276 | 1f88c90a0def4ef15db68c611a52ea4157c3c3ac | /app/src/main/java/com/androidexample/lazyimagedownload/ImageLoader.java | 9ae561bb12b3537a1afa2edc69799b3c15b3e679 | [] | no_license | masterUNG/LoadImageURL | 216844e21fec76e108fc1fa2914bbd41496542a8 | 7fe10d86e4ea6d88a80523c5ebfd565ecea50650 | refs/heads/master | 2021-01-10T19:25:21.564443 | 2015-06-28T17:14:09 | 2015-06-28T17:14:09 | 38,207,149 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,530 | java | package com.androidexample.lazyimagedownload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
// Initialize MemoryCache
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
//Create Map (collection) to store image and image url in key value pair
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
//handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context){
fileCache = new FileCache(context);
// Creates a thread pool that reuses a fixed number of
// threads operating off a shared unbounded queue.
executorService=Executors.newFixedThreadPool(5);
}
// default image show in list (Before online image download)
final int stub_id=R.drawable.stub;
public void DisplayImage(String url, ImageView imageView)
{
//Store image and url in Map
imageViews.put(imageView, url);
//Check image is stored in MemoryCache Map or not (see MemoryCache.java)
Bitmap bitmap = memoryCache.get(url);
if(bitmap!=null){
// if image is stored in MemoryCache Map then
// Show image in listview row
imageView.setImageBitmap(bitmap);
}
else
{
//queue Photo to download from url
queuePhoto(url, imageView);
//Before downloading image show default image
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
// Store image and url in PhotoToLoad object
PhotoToLoad p = new PhotoToLoad(url, imageView);
// pass PhotoToLoad object to PhotosLoader runnable class
// and submit PhotosLoader runnable to executers to run runnable
// Submits a PhotosLoader runnable task for execution
executorService.submit(new PhotosLoader(p));
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
try{
//Check if image already downloaded
if(imageViewReused(photoToLoad))
return;
// download image from web url
Bitmap bmp = getBitmap(photoToLoad.url);
// set image data in Memory Cache
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
// Get bitmap to display
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
// Causes the Runnable bd (BitmapDisplayer) to be added to the message queue.
// The runnable will be run on the thread to which this handler is attached.
// BitmapDisplayer run method will call
handler.post(bd);
}catch(Throwable th){
th.printStackTrace();
}
}
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
//CHECK : if trying to decode file which not exist in cache return null
Bitmap b = decodeFile(f);
if(b!=null)
return b;
// Download image file from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
// Constructs a new FileOutputStream that writes to file
// if file not exist then it will create file
OutputStream os = new FileOutputStream(f);
// See Utils class CopyStream method
// It will each pixel from input stream and
// write pixels to output stream (file)
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
//Now file created and going to resize file with defined height
// Decodes image and scales it to reduce memory consumption
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1=new FileInputStream(f);
BitmapFactory.decodeStream(stream1,null,o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
// Set width/height of recreated image
final int REQUIRED_SIZE=85;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with current scale values
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
FileInputStream stream2=new FileInputStream(f);
Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
//Check url is already exist in imageViews MAP
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
// Show bitmap on UI
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
//Clear cache directory downloaded images and stored data in maps
memoryCache.clear();
fileCache.clear();
}
}
| [
"phrombutr@gmail.com"
] | phrombutr@gmail.com |
64b06f26d1f892df7f8ee5c94657ffcf3f2379b5 | dfadecb1314f614b86188c5c81acbbaf924debb6 | /src/java/org/apache/hadoop/hive/jdbc/storagehandler/JdbcInputFormat.java | 231ab61ded1576753eca296b07888e4019969b02 | [
"Apache-2.0"
] | permissive | matt-acton/HiveJdbcStorageHandler | 4588d40a874b56017c14da28f48e720ff8b5a5d4 | 6d70be4ba3b58912b7d368b333064564dcba57cb | refs/heads/master | 2021-01-18T00:25:13.813884 | 2015-07-15T05:59:12 | 2015-07-15T05:59:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,174 | java | /*
* Copyright 2013-2015 Makoto YUI
*
* 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.hadoop.hive.jdbc.storagehandler;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.lib.db.DBInputFormat;
public class JdbcInputFormat extends DBInputFormat<DbRecordWritable> {
private boolean jobConfSet = false;
/**
* @see org.apache.hadoop.util.ReflectionUtils#setConf(Object, Configuration)
*/
@Override
public void setConf(Configuration conf) {
// delay for TableJobProperties is set to the jobConf
}
/**
* @see org.apache.hadoop.hive.ql.exec.FetchOperator#getRecordReader()
*/
@Override
public void configure(JobConf jobConf) {
// delay for TableJobProperties is set to the jobConf
}
@Override
public RecordReader<LongWritable, DbRecordWritable> getRecordReader(InputSplit split, JobConf jobConf, Reporter reporter)
throws IOException {
if(!jobConfSet) {
super.configure(jobConf);
this.jobConfSet = true;
}
return super.getRecordReader(split, jobConf, reporter);
}
@Override
public InputSplit[] getSplits(JobConf jobConf, int chunks) throws IOException {
if(!jobConfSet) {
super.configure(jobConf);
this.jobConfSet = true;
}
return super.getSplits(jobConf, chunks);
}
}
| [
"yuin405@gmail.com"
] | yuin405@gmail.com |
28680d8b88bb9b9e98b42648fdeb60377df90e04 | 94ea4b9ffc73f50e13ce8dd3ceccf8eb931e6dbc | /Kgamelib/src/com/yayawan/proxy/GameApi.java | b1a507d83be77926566b6436c1de94f34c513b1d | [] | no_license | Aquarids/sdkworkspace | aa0c9fbb7aa92f1aeb23888319551421acb76fbd | 9d7ca2db6faad2aa5b7e6fadca1debe4d95beb99 | refs/heads/master | 2020-09-23T13:44:23.566240 | 2019-07-02T10:30:51 | 2019-07-02T10:30:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,833 | java | package com.yayawan.proxy;
import org.json.JSONException;
import org.json.JSONObject;
import com.kkgame.utils.Yayalog;
import com.yayawan.callback.YYWAnimCallBack;
import com.yayawan.callback.YYWExitCallback;
import com.yayawan.callback.YYWPayCallBack;
import com.yayawan.callback.YYWUserCallBack;
import com.yayawan.domain.YYWOrder;
import com.yayawan.domain.YYWUser;
import com.yayawan.main.Kgame;
import android.app.Activity;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
public class GameApi {
public Activity mActivity;
public WebView mWebView;
public GameApi(Activity mactivity,WebView webview){
this.mActivity=mactivity;
this.mWebView=webview;
}
@JavascriptInterface
public void anmi() {
Kgame.getInstance().anim(mActivity, new YYWAnimCallBack() {
@Override
public void onAnimSuccess(String arg0, Object arg1) {
// TODO Auto-generated method stub
}
@Override
public void onAnimFailed(String arg0, Object arg1) {
// TODO Auto-generated method stub
}
@Override
public void onAnimCancel(String arg0, Object arg1) {
// TODO Auto-generated method stub
}
});
}
@JavascriptInterface
public void login() {
Kgame.getInstance().login(mActivity, new YYWUserCallBack() {
@Override
public void onLogout(Object arg0) {
// TODO Auto-generated method stub
mWebView.loadUrl("javascript:GameCallBack.loginOut()");
}
@Override
public void onLoginSuccess(YYWUser user, Object arg1) {
// TODO Auto-generated method stub
System.out.println("登陆成功");
JSONObject userjson = new JSONObject();
try {
userjson.put("uid", user.uid);
userjson.put("username", user.userName);
userjson.put("token", user.token);
Yayalog.loger("Gameapi登陆成功:"+userjson.toString());
mWebView.loadUrl("javascript:GameCallBack.loginSuc("+userjson.toString()+")");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onLoginFailed(String arg0, Object arg1) {
// TODO Auto-generated method stub
mWebView.loadUrl("javascript:GameCallBack.loginFail()");
}
@Override
public void onCancel() {
// TODO Auto-generated method stub
mWebView.loadUrl("javascript:GameCallBack.loginFail()");
}
});
}
@JavascriptInterface
public void ceshi() {
}
@JavascriptInterface
public void pay(String orderid,String goods,String money,String ext) {
YYWOrder order = new YYWOrder(orderid, goods,
Long.parseLong(money), ext);
Kgame.getInstance().pay(mActivity, order, new YYWPayCallBack() {
@Override
public void onPaySuccess(YYWUser arg0, YYWOrder arg1, Object arg2) {
// TODO Auto-generated method stub
mWebView.loadUrl("javascript:GameCallBack.paySuc()");
}
@Override
public void onPayFailed(String arg0, Object arg1) {
// TODO Auto-generated method stub
mWebView.loadUrl("javascript:GameCallBack.payFail()");
}
@Override
public void onPayCancel(String arg0, Object arg1) {
// TODO Auto-generated method stub
mWebView.loadUrl("javascript:GameCallBack.payFail()");
}
});
}
@JavascriptInterface
public void exit() {
Kgame.getInstance().exit(mActivity, new YYWExitCallback() {
@Override
public void onExit() {
// TODO Auto-generated method stub
mWebView.loadUrl("javascript:GameCallBack.exitSuc()");
}
});
}
@JavascriptInterface
public void setdata( String roleId, String roleName,String roleLevel,String zoneId,String zoneName,String roleCTime,String ext) {
Yayalog.loger("gameapisetdata:");
Kgame.getInstance().setData(mActivity, roleId, roleName, roleLevel, zoneId, zoneName, roleCTime, ext);
}
}
| [
"424587636@qq.com"
] | 424587636@qq.com |
eabe2d897e964213a7f11baf7ee077920ba4b009 | d55bcf9d7558bf46b95e86f748a26ace1af3b9c2 | /RxSandbox/test/java/reactive_sum/rx/Test.java | 167b2ca415239ee2a7d7e2197fda29f79e1c719b | [] | no_license | ohhhHenry/RxSandbox | a4ec6b9282e4ddb7595ca2fb9df25a9cca25965a | 77cd04565ebe70313f09f229c84f6f6483bc807e | refs/heads/master | 2021-06-01T02:21:30.620200 | 2016-07-04T20:56:39 | 2016-07-04T20:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 142 | java | package reactive_sum.rx;
public class Test {
public static void main(String[] args) {
int[] arr = new int[]{1, 2, 3};
}
}
| [
"joethorngren@gmail.com"
] | joethorngren@gmail.com |
8fb6effd8ca8dae881c6893f91a89bd193869dfc | ec80cce2f219e83e4e52b2553baf4203dd90aa80 | /boser-model-core/src/main/java/it/quartara/boser/model/PdfConversion.java | b4754e9dfbaebf361bba2260d07df1c1cf6e60a4 | [
"Apache-2.0"
] | permissive | vernyquartara/boser | 45e3eb8619aed4067a5f9c585606e9d80ab28a3a | 6a2e959dadf8fd4f6fbc3db9a6823db4120af0ce | refs/heads/master | 2020-05-21T12:35:19.178936 | 2016-05-17T10:19:30 | 2016-05-17T10:19:30 | 39,530,263 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,021 | java | package it.quartara.boser.model;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
@Entity
@Table(name="PDF_CONVERTIONS")
public class PdfConversion extends PersistentEntity {
private static final long serialVersionUID = 7867084774347308125L;
private short countCompleted;
private short countFailed;
private long fileSize;
private String zipFilePath;
@Enumerated(EnumType.STRING)
private ExecutionState state;
private Date creationDate;
private Date startDate;
private Date endDate;
private Date lastUpdate;
@OneToMany(mappedBy="conversion", cascade=CascadeType.ALL)
private List<PdfConversionItem> items;
private String xlsFileName;
private String destDir;
@Version
private long version;
public int getCountWorking() {
int count = 0;
if (items == null) {
return count;
}
for (PdfConversionItem item : items) {
if (item.getState()==ExecutionState.STARTED) {
count++;
}
}
return count;
}
public int getCountRemaining() {
int count = 0;
if (items == null) {
return count;
}
for (PdfConversionItem item : items) {
if (item.getState()==ExecutionState.STARTED
|| item.getState()==ExecutionState.READY) {
count++;
}
}
return count;
}
public int getCountReady() {
int count = 0;
if (items == null) {
return count;
}
for (PdfConversionItem item : items) {
if (item.getState()==ExecutionState.READY) {
count++;
}
}
return count;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long size) {
this.fileSize = size;
}
public String getZipFilePath() {
return zipFilePath;
}
public void setZipFilePath(String filePath) {
this.zipFilePath = filePath;
}
public ExecutionState getState() {
return state;
}
public void setState(ExecutionState state) {
this.state = state;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getLabel() {
if (zipFilePath != null) {
int start = zipFilePath.lastIndexOf("/")+1; //FIXME se usato File.separator in inserimento, potrebbe non essere /
int end = zipFilePath.lastIndexOf(".");
return zipFilePath.substring(start, end);
}
return null;
}
public short getCountCompleted() {
return countCompleted;
}
public void setCountCompleted(short countCompleted) {
this.countCompleted = countCompleted;
}
public short getCountFailed() {
return countFailed;
}
public void setCountFailed(short countFailed) {
this.countFailed = countFailed;
}
public short getCountTotal() {
if (items != null) {
return (short) items.size();
}
return 0;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public List<PdfConversionItem> getItems() {
return items;
}
public void setItems(List<PdfConversionItem> items) {
this.items = items;
}
/**
* restituisce il nome del file xls originale, senza percorso.
* @return
*/
public String getXlsFileName() {
return xlsFileName;
}
public void setXlsFileName(String xlsFileName) {
this.xlsFileName = xlsFileName;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
/**
* Restituisce il percorso della directory di destinazione della conversione.
* @return
*/
public String getDestDir() {
return destDir;
}
public void setDestDir(String destDir) {
this.destDir = destDir;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
}
| [
"webny23@gmail.com"
] | webny23@gmail.com |
c07c9ff4090669b8ad5c172c06702f618bae7474 | 12a99ab3fe76e5c7c05609c0e76d1855bd051bbb | /src/main/java/com/alipay/api/domain/AntMerchantExpandIndirectAttachmentUploadModel.java | 2c332cc32778323b1e1fb8386126faebe295ee2c | [
"Apache-2.0"
] | permissive | WindLee05-17/alipay-sdk-java-all | ce2415cfab2416d2e0ae67c625b6a000231a8cfc | 19ccb203268316b346ead9c36ff8aa5f1eac6c77 | refs/heads/master | 2022-11-30T18:42:42.077288 | 2020-08-17T05:57:47 | 2020-08-17T05:57:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,352 | java | package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 间连商户文件上传
*
* @author auto create
* @since 1.0, 2019-05-15 11:16:46
*/
public class AntMerchantExpandIndirectAttachmentUploadModel extends AlipayObject {
private static final long serialVersionUID = 8572972222397798656L;
/**
* 商户附件信息
*/
@ApiListField("attachment_info")
@ApiField("attachment_info")
private List<AttachmentInfo> attachmentInfo;
/**
* 备注信息
*/
@ApiField("memo")
private String memo;
/**
* 商户在支付宝入驻成功后,生成的支付宝内全局唯一的商户编号
*/
@ApiField("sub_merchant_id")
private String subMerchantId;
public List<AttachmentInfo> getAttachmentInfo() {
return this.attachmentInfo;
}
public void setAttachmentInfo(List<AttachmentInfo> attachmentInfo) {
this.attachmentInfo = attachmentInfo;
}
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getSubMerchantId() {
return this.subMerchantId;
}
public void setSubMerchantId(String subMerchantId) {
this.subMerchantId = subMerchantId;
}
}
| [
"ben.zy@antfin.com"
] | ben.zy@antfin.com |
fb4c59f3434c20e8ca900b8b732b405eb3f37bc8 | eb5cd6d47657d8cfda72b636f6ff8c8b904324be | /Topic0/src/builder/DatabaseConnectionBuilder.java | 646c1a79e2e70676b5325b8ec02f7e8539d7a750 | [
"Apache-2.0"
] | permissive | edwarx/java-bootcamp-2016 | 743f7dd7a4b7dfd0cfb8b1a3c7ec4d53f8b74154 | 1f7b8627679904f0b289a946a15597840517e89c | refs/heads/master | 2021-01-21T09:39:20.063683 | 2016-02-12T18:15:15 | 2016-02-12T18:15:15 | 49,563,255 | 0 | 0 | null | 2016-01-13T09:21:23 | 2016-01-13T09:21:22 | null | UTF-8 | Java | false | false | 240 | java | package builder;
public interface DatabaseConnectionBuilder {
public void buildDatabaseType();
public void buildUrl();
public void buildUsername();
public void buildPassword();
public DatabaseConnection getDatabaseConnection();
}
| [
"edwarx@gmail.com"
] | edwarx@gmail.com |
00424a85b753db8b4356569fe9fc9bc77eb5b87c | 9dccdfcdb4192eee7f81432dcc82aac53f02aeb9 | /src/main/java/controller/ViewContainerController.java | 34f45e2f0ea020e25badd6d952531c92587a51f3 | [] | no_license | shahidaarbi/AppointmentBookingSystem | 2a5e3466cb1dda79c10fbab1e9f87ada8e813efd | 1bb658f736f8a5d243c85ec9682c6135c8d2e851 | refs/heads/master | 2023-03-17T14:49:06.241300 | 2017-11-02T19:55:46 | 2017-11-02T19:55:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 539 | java | package controller;
import controller.protocols.ViewController;
import view.protocols.ViewContainerView;
public class ViewContainerController {
private ViewController viewController;
private ViewContainerView view;
public ViewContainerController(ViewController viewController,
ViewContainerView view) {
this.viewController = viewController;
this.view = view;
}
public void home() {
viewController.gotoHome();
}
public void logout() {
viewController.logout();
}
}
| [
"s3438465@student.rmit.edu.au"
] | s3438465@student.rmit.edu.au |
8b439a2000a13dd669079fe26ce0dc034dabe8c4 | c44f208414584906494d4fb7cfa172a7d9af88c0 | /MyDrawer/app/src/main/java/org/techtown/drawer/ui/slideshow/SlideshowFragment.java | d0a4617512a3857c61815bb457d9b3e0df4196c1 | [] | no_license | Realhyeonwoo/study-android | 6c860258e70a36424bfbce787ad240592421d621 | aa1b9557807083b258fdaac79642d9ebaaf9e306 | refs/heads/master | 2022-07-29T06:23:38.998574 | 2020-05-20T01:37:40 | 2020-05-20T01:37:40 | 264,199,976 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,194 | java | package org.techtown.drawer.ui.slideshow;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import org.techtown.drawer.R;
public class SlideshowFragment extends Fragment {
private SlideshowViewModel slideshowViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
slideshowViewModel =
ViewModelProviders.of(this).get(SlideshowViewModel.class);
View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
final TextView textView = root.findViewById(R.id.text_slideshow);
slideshowViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
| [
"gusdn7269@naver.com"
] | gusdn7269@naver.com |
45c2169394dd59c0c6e7718c945168b9844d36ad | 62b7f084f563141242478a08e9eb74c036a0abf1 | /user-api/src/main/java/lol/maki/socks/oauth/IdTokenEnhancer.java | ffeb769ff79852b9542e819b75d5918bdd79fcee | [
"Apache-2.0"
] | permissive | making/spring-socks | 3ae32de42a32de699f3d34790fb77eb327bb4ed3 | 20ea1d0fa5e6e3bc34a399d8693600ebe7f50607 | refs/heads/master | 2023-06-03T23:05:13.590958 | 2021-06-22T02:04:02 | 2021-06-22T02:04:02 | 275,103,492 | 54 | 21 | Apache-2.0 | 2021-06-21T22:03:13 | 2020-06-26T07:57:54 | Java | UTF-8 | Java | false | false | 1,418 | java | package lol.maki.socks.oauth;
import java.util.Map;
import java.util.Set;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
public class IdTokenEnhancer implements TokenEnhancer {
private final JwtAccessTokenConverter jwtAccessTokenConverter;
public IdTokenEnhancer(JwtAccessTokenConverter jwtAccessTokenConverter) {
this.jwtAccessTokenConverter = jwtAccessTokenConverter;
}
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
if (accessToken.getScope().contains(OidcScopes.OPENID)) {
final DefaultOAuth2AccessToken idToken = new DefaultOAuth2AccessToken(accessToken);
idToken.setScope(Set.of(OidcScopes.OPENID));
idToken.setRefreshToken(null);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(Map.of(OidcParameterNames.ID_TOKEN, this.jwtAccessTokenConverter.enhance(idToken, authentication).getValue()));
}
return accessToken;
}
} | [
"tmaki@pivotal.io"
] | tmaki@pivotal.io |
5d22e36070cc61995ca32c710e822bae323d9f31 | 3a59bd4f3c7841a60444bb5af6c859dd2fe7b355 | /sources/kotlin/sequences/SequencesKt___SequencesKt$sorted$1.java | 4001bf85d24d803c451e2ff514b067fde839cd96 | [] | no_license | sengeiou/KnowAndGo-android-thunkable | 65ac6882af9b52aac4f5a4999e095eaae4da3c7f | 39e809d0bbbe9a743253bed99b8209679ad449c9 | refs/heads/master | 2023-01-01T02:20:01.680570 | 2020-10-22T04:35:27 | 2020-10-22T04:35:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,128 | java | package kotlin.sequences;
import java.util.Iterator;
import java.util.List;
import kotlin.Metadata;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
@Metadata(mo39784bv = {1, 0, 3}, mo39785d1 = {"\u0000\u0011\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010(\n\u0000*\u0001\u0000\b\n\u0018\u00002\b\u0012\u0004\u0012\u00028\u00000\u0001J\u000f\u0010\u0002\u001a\b\u0012\u0004\u0012\u00028\u00000\u0003H\u0002¨\u0006\u0004"}, mo39786d2 = {"kotlin/sequences/SequencesKt___SequencesKt$sorted$1", "Lkotlin/sequences/Sequence;", "iterator", "", "kotlin-stdlib"}, mo39787k = 1, mo39788mv = {1, 1, 15})
/* compiled from: _Sequences.kt */
public final class SequencesKt___SequencesKt$sorted$1 implements Sequence<T> {
final /* synthetic */ Sequence $this_sorted;
SequencesKt___SequencesKt$sorted$1(Sequence<? extends T> sequence) {
this.$this_sorted = sequence;
}
@NotNull
public Iterator<T> iterator() {
List mutableList = SequencesKt.toMutableList(this.$this_sorted);
CollectionsKt.sort(mutableList);
return mutableList.iterator();
}
}
| [
"joshuahj.tsao@gmail.com"
] | joshuahj.tsao@gmail.com |
bdc830419390f24455c7216ca2e9a2fd3e98dd63 | 4547923df949b7b3e416306d479fed7b1d05af78 | /src/main/java/com/cuisine_mart/restaurant/controller/RestaurantController.java | b2b78d63ec0ef1beaf1f23154735c825a19b232f | [] | no_license | mmaharjan/foodieHome | 188586db61a5436404dfb34e864497997afff505 | 104a2b5992328d8552c986e6036d82d4f3d50d82 | refs/heads/master | 2021-01-22T03:14:22.889674 | 2017-05-25T04:56:13 | 2017-05-25T04:56:13 | 92,363,951 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,674 | java | package com.cuisine_mart.restaurant.controller;
import com.cuisine_mart.restaurant.domain.Restaurant;
import com.cuisine_mart.restaurant.service.IServiceContract.IRestaurantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
/**
* Created by Minesh on 8/27/2016.
*/
@Controller
@RequestMapping("/restaurant")
public class RestaurantController {
@Autowired
IRestaurantService restaurantService;
@RequestMapping(value = "/list")
public String showRestaurants(ModelMap modelMap){
List<Restaurant> restaurants = restaurantService.findAll();
modelMap.addAttribute("restaurants",restaurants);
return "restaurantList";
}
@RequestMapping(value = "/details/{restaurantId}", method = RequestMethod.GET)
public String showDetail(@PathVariable Long restaurantId,ModelMap modelMap){
Restaurant restaurant = restaurantService.get(restaurantId);
modelMap.addAttribute("restaurant",restaurant);
return "restaurantDetails";
}
//
// @RequestMapping(value = "/byLocation/{addressId}", method = RequestMethod.GET)
// public String searchByLocation(@PathVariable Long addressId,ModelMap modelMap){
// Restaurant restaurant = restaurantService.findByLocation(addressId);
// modelMap.addAttribute("restaurant",restaurant);
// return "restaurantDetails";
// }
}
| [
"m.minesh@live.com"
] | m.minesh@live.com |
4ae0083e97603affefe94b673d8434251b1953cb | eb2587f305bee28bfdb66f6f230eaac2cafde30b | /src/TestaLacos2.java | d33000c18b00b067da9e21a42d581007b46049b5 | [] | no_license | keyneskanno/sintaxe-basica | 540f74763a28fe793cbff8d3ae80eb98e5dbba24 | 83f758e4993338c625e036f59b5679c58d9aa98c | refs/heads/master | 2023-07-26T04:35:03.159651 | 2021-08-31T22:54:11 | 2021-08-31T22:54:11 | 401,794,903 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 278 | java |
public class TestaLacos2 {
public static void main(String[] args) {
for (int linha = 1; linha <= 10; linha++) {
for (int coluna = 0; coluna <= 10; coluna++) {
if (coluna > linha) {
break;
}
System.out.print("*");
}
System.out.println();
}
}
}
| [
"keyneskanno@gmail.com"
] | keyneskanno@gmail.com |
58cfd361f5430fcf9d744f9cc8d8854c7fad39a0 | 1bed4bac697fb96d67f92f78d2c42503dfeeb112 | /src/main/java/com/kerwin/apps/cms/utils/Message.java | c6e80680342cc58374203047f0aa6019712f3b91 | [] | no_license | kerwinYX/cms | 5812fabb8df55d014c2c9cd36099f1d8ee82ab5f | dd83b9dacd07c8a0570465e46d3fcf747a5d7327 | refs/heads/master | 2020-09-08T13:25:15.322564 | 2019-11-29T02:16:04 | 2019-11-29T02:16:04 | 221,146,217 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 927 | java | package com.kerwin.apps.cms.utils;
/**
* @author kerwin
* @title: Message
* @projectName cms
* @date 2019/11/12 - 15:14
*/
public class Message {
private Integer status; //状态码
private String message; //信息
private Object data; //携带的数据 结果数据等等
private Long timestamp; //时间戳
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
| [
"1952075564@qq.com"
] | 1952075564@qq.com |
bc6c6f5c93e16a940a0d2d19db52dd5722354e86 | f7a7a6e0aa9719416319a4bdec56a5c870c595b4 | /alloy-ucenter-biz/src/main/java/com/alloy/cloud/ucenter/biz/entity/SysUser.java | 5934e78080264b55503408c37c966b9aa8bf06ba | [] | no_license | t051506/alloy-ucenter | fc8b151e327e438855e4fbf2ad52b2acc9f904a5 | 27ebdda402c4c079bdb92c8edc7a1da267148b89 | refs/heads/master | 2023-05-06T09:32:11.937343 | 2021-05-28T01:48:55 | 2021-05-28T01:48:55 | 301,914,955 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,175 | java | package com.alloy.cloud.ucenter.biz.entity;
import com.alloy.cloud.common.core.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
/**
* 用户
*
* @author tankechao
* @since 2020-12-12
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class SysUser extends BaseEntity{
private static final long serialVersionUID = -76423951816146867L;
/**
* 主键ID
*/
private Long userId;
/**
* 用户名
*/
private String username;
private String password;
/**
* 姓名
*/
private String personName;
/**
* 电话
*/
private String phone;
/**
* 头像
*/
private String headImg;
/**
* 部门ID
*/
private Integer orgCode;
/**
* 身份证
*/
private String idCard;
/**
* 邮箱
*/
private String email;
/**
* 出生日期
*/
private LocalDate birthday;
/**
* 性别(0:男,1:女)
*/
private Integer gender;
/**
* 年龄
*/
private Integer age;
/**
* 0-正常,9-锁定
*/
private Integer isLock;
}
| [
"tankechao@quanyou.com"
] | tankechao@quanyou.com |
efbfae4730aec75df04699e3c8470e5066093cb7 | 5f62da1dd0fd6da6b4fd451841ed8a4543583395 | /app/src/androidTest/java/com/example/lazyworkout/ExampleInstrumentedTest.java | 5f04f3f44f544a0ddaba7078149d497f06c7bf35 | [] | no_license | khoahre123/Orbital-2021-Lazy-Workout | 6c2a9b5a2352c21c149f05f4d29551c7df082e52 | 5558fded026405bc6164238aef5a9a73c687eb58 | refs/heads/main | 2023-07-14T00:50:54.798268 | 2021-08-15T16:02:10 | 2021-08-15T16:02:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 760 | java | package com.example.lazyworkout;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.lazyworkout", appContext.getPackageName());
}
} | [
"mailnq02112002@gmail.com"
] | mailnq02112002@gmail.com |
2b5d9dac6b87933b3ebb5c664871d9eb4d36ebfa | 3845540f0601e99a3e151185379c2013a2d34a91 | /tst/domain/Tuple3Test.java | a893431adec3919f36cb95e2d400af4748336597 | [] | no_license | deadly-platypus/TransparentTablets | 278aae2f9c25b49cac125da4fed73a81889b9ee0 | ab36cbe5a51b1025b842adde3f9eba88932be54b | refs/heads/master | 2020-06-05T11:49:32.269016 | 2014-04-30T00:30:49 | 2014-04-30T00:30:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,613 | java | package domain;
import static org.junit.Assert.*;
import graphics.ScreenRenderer;
import org.junit.Test;
public class Tuple3Test {
@Test
public void testAdd() {
Tuple3 t1 = new Tuple3(1.0f, 1.0f, 1.0f);
assertEquals(new Tuple3(2.0f, 2.0f, 2.0f), t1.add(new Tuple3(1.0f, 1.0f, 1.0f)));
}
@Test
public void testSubtract() {
Tuple3 t1 = new Tuple3(1.0f, 1.0f, 1.0f);
assertEquals(new Tuple3(0.0f, 0.0f, 0.0f), t1.subtract(new Tuple3(1.0f, 1.0f, 1.0f)));
}
@Test
public void testRotate() {
Tuple3 x = new Tuple3(1.0f, 0.0f, 0.0f);
Vec3 axis = new Vec3(0.0f, 0.0f, 1.0f);
Tuple3 test = x.rotate(axis, (float)Math.PI / 2.0f);
assertEquals(1.0f, test.y, Tuple3.epsilon);
assertEquals(0.0f, test.x, Tuple3.epsilon);
assertEquals(0.0f, test.z, Tuple3.epsilon);
axis = new Vec3(0.0f, 1.0f, 0.0f);
test = x.rotate(axis, (float)Math.PI / 2.0f);
assertEquals(-1.0f, test.z, Tuple3.epsilon);
assertEquals(0.0f, test.x, Tuple3.epsilon);
assertEquals(0.0f, test.y, Tuple3.epsilon);
PPC cam = EnvironmentState.getInstance().getCurrentCamera();
Vec3 orig = new Vec3(cam.getView_corner());
axis = new Vec3(ScreenRenderer.WIGGLE, 0.0f, 0.0f);
axis.normalize();
test = cam.getView_corner().rotate(axis , ScreenRenderer.ROTATION_AMT / 1000.0f);
assertEquals(orig.getX(), test.x, Tuple3.epsilon);
Vec3 y = new Vec3(0.0f, 1.0f, 0.0f);
axis = new Vec3(1.0f, 0.0f, 0.0f);
y = y.rotate(axis, (float)Math.PI / 2.0f).toVec3();
assertEquals(0.0f, y.x, Tuple3.epsilon);
assertEquals(0.0f, y.y, Tuple3.epsilon);
assertEquals(1.0f, y.z, Tuple3.epsilon);
}
}
| [
"derrick.mckee@gmail.com"
] | derrick.mckee@gmail.com |
4d0b7c2bb61a3a76ad2a1147cfc1dc8b7eff4cee | ab4d8b1914c8558a1c531af8d5fc56ff709193a2 | /src/com/techstudio/smpp/SMSReceiver.java | 85e124c9c61c9d021d099058be12f6ee8a11d192 | [] | no_license | cartmansom1968/WILAS_SMPP_CONNECTOR | 4695684e4ecd1bae121e7d7108cd924b5746a2b4 | 94f7950ad66eb79398d9454fcf1115c145850476 | refs/heads/master | 2021-01-19T23:57:34.560767 | 2017-04-22T08:30:03 | 2017-04-22T08:30:03 | 89,055,555 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,958 | java | package com.techstudio.smpp;
import com.techstudio.smpp.util.*;
import org.apache.log4j.*;
import java.io.*;
public class SMSReceiver extends Thread implements DefaultSetting{
Logger logger = null;
InputStream reader;
Connection connection;
String name = "SMSReceiver";
public SMSReceiver(Connection connection, String aname, Logger logger){
super(aname);
this.name = aname;
this.logger = logger;
this.reader = connection.getReader();
this.connection = connection;
start();
}
public void run(){
int length = 0;
while (connection.isContReceive()){
try{
byte[] receiveBuffer = new byte[4];
for ( int i=0; i<SZ_INT; i++ ){
int input = reader.read();
while (input==-1 )
input = reader.read();
//logger.info("in ("+i+") = "+input);
receiveBuffer[i] = (byte)input;
}
printBytes(receiveBuffer, name);
ByteBuffer buffer = new ByteBuffer(receiveBuffer);
int packetlength = buffer.removeInt();
packetlength = packetlength - 4;
if ( packetlength>0 ){
int bytesToRead = reader.available();
byte[] tempbuffer = new byte[packetlength];
for ( int i=0; i<packetlength; i++ ){
int input = reader.read();
tempbuffer[i] = (byte)input;
}
buffer.add(tempbuffer);
logger.info("-->> RECEIVE packet length == "+packetlength);
connection.addInputMsg((new MOObj(tempbuffer)));
}
}catch(Exception e){
e.printStackTrace();
connection.reconnect(name);
break;
}
}
logger.info("************ EXIT SMSReceiver ************");
if ( connection!=null )
connection.reconnect("SMSReceiver");
else
System.exit(1);
}
public void printBytes(byte[] array, String name) {
for (int k=0; k< array.length; k++) {
//logger.info(name + "[" + k + "] = " + "0x" + com.techstudio.converter.UnicodeFormatter.byteToHex(array[k]));
}
}
}
| [
"cartmansom@gmail.com"
] | cartmansom@gmail.com |
81df233479de90f7e79092e1bcf812477aa068ef | b8dd7af8660eacc0074dfdeee5d520f929ba4047 | /geoapi/src/test/java/org/opengis/tools/export/CanNotExportException.java | bbc97d13545d4871a2de75c940f6781714144201 | [
"LicenseRef-scancode-ogc"
] | permissive | rouault/geoapi | 4a248a939c8703143c17c4bd1ba2355ec9a726fb | edd4136fb78a01384c7f393941bf26c7442c087c | refs/heads/master | 2020-03-09T18:11:35.133846 | 2018-03-30T09:58:44 | 2018-03-30T09:58:44 | 128,926,294 | 1 | 0 | null | 2018-04-10T12:05:01 | 2018-04-10T12:05:00 | null | UTF-8 | Java | false | false | 2,651 | java | /*
* GeoAPI - Java interfaces for OGC/ISO standards
* http://www.geoapi.org
*
* Copyright (C) 2018 Open Geospatial Consortium, Inc.
* All Rights Reserved. http://www.opengeospatial.org/ogc/legal
*
* Permission to use, copy, and modify this software and its documentation, with
* or without modification, for any purpose and without fee or royalty is hereby
* granted, provided that you include the following on ALL copies of the software
* and documentation or portions thereof, including modifications, that you make:
*
* 1. The full text of this NOTICE in a location viewable to users of the
* redistributed or derivative work.
* 2. Notice of any changes or modifications to the OGC files, including the
* date changes were made.
*
* THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE
* NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT
* THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY
* PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
*
* COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR
* CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION.
*
* The name and trademarks of copyright holders may NOT be used in advertising or
* publicity pertaining to the software without specific, written prior permission.
* Title to copyright in this software and any associated documentation will at all
* times remain with copyright holders.
*/
package org.opengis.tools.export;
/**
* Thrown when a Java element can not be exported to the target language.
*
* @author Martin Desruisseaux (Geomatys)
* @version 3.1
* @since 3.1
*/
@SuppressWarnings("serial")
public class CanNotExportException extends RuntimeException {
/**
* Constructs an exception with the specified detail message.
*
* @param message the detail message, saved for later retrieval by the {@link #getMessage()} method.
*/
public CanNotExportException(String message) {
super(message);
}
/**
* Constructs an exception with the specified detail message and cause.
*
* @param message the detail message, saved for later retrieval by the {@link #getMessage()} method.
* @param cause the cause of this exception, saved for later retrieval by the {@link #getCause()} method.
*/
public CanNotExportException(String message, Exception cause) {
super(message, cause);
}
}
| [
"martin.desruisseaux@geomatys.com"
] | martin.desruisseaux@geomatys.com |
badf8a88e42cbef3b72431fd6f313e516426b075 | 9d32980f5989cd4c55cea498af5d6a413e08b7a2 | /A92s_10_0_0/src/main/java/com/oppo/internal/telephony/rf/WifiOemProximitySensorManager.java | 79eb95e39f79fe1016c3647d010f054718b5b207 | [] | no_license | liuhaosource/OppoFramework | e7cc3bcd16958f809eec624b9921043cde30c831 | ebe39acabf5eae49f5f991c5ce677d62b683f1b6 | refs/heads/master | 2023-06-03T23:06:17.572407 | 2020-11-30T08:40:07 | 2020-11-30T08:40:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 67,205 | java | package com.oppo.internal.telephony.rf;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pGroup;
import android.os.AsyncResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemProperties;
import android.provider.Settings;
import android.telephony.PhoneStateListener;
import android.telephony.Rlog;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.AbstractPhone;
import com.android.internal.telephony.OemConstant;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.SubscriptionController;
import com.android.internal.telephony.util.OemTelephonyUtils;
import com.android.internal.telephony.util.ReflectionHelper;
import com.oppo.internal.telephony.OppoRIL;
import com.oppo.internal.telephony.OppoTelephonyController;
import com.oppo.internal.telephony.explock.RegionLockPlmnListParser;
public class WifiOemProximitySensorManager {
private static int AP_BAND_DUAL = 0;
private static String EXTRA_WIFI_AP_WORKING_FREQUENCY = null;
private static final String LOG_TAG = "Wifisar";
static String TAG = "WifiOemProximitySensor";
private static String WIFI_AP_CHANNEL_CHANGED_ACTION = null;
protected static final int WIFI_SAR_EXEC_6771 = 1;
protected static final int WIFI_SAR_EXEC_6779 = 2;
/* access modifiers changed from: private */
public static String WIFI_SHARING_STATE_CHANGED_ACTION;
/* access modifiers changed from: private */
public static int WIFI_SHARING_STATE_ENABLED;
/* access modifiers changed from: private */
public static final String[] mCeCountryList = {"SG", "ID", "KZ", "NP", "NG", "IQ", "HK", "MY", "TR", "MM", "EG", "JO", "TH", "AU", "PK", "MA", "KE", "LB", "KH", "NZ", "LK", "DZ", "SA", "PS", "PH", "UA", "BD", "TN", "AE", "UZ"};
/* access modifiers changed from: private */
public static final String[] mEuropeCountryList = {"AT", "BE", "BG", "CY", "HR", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "GB", "SE", "CH"};
/* access modifiers changed from: private */
public static final String[] mFccCountryList = {"US", "MA"};
/* access modifiers changed from: private */
public static Handler mHandler;
private static HandlerThread mHandlerThread;
public static WifiManager mWifiManager = null;
static WifiOemProximitySensorManager sInstance = null;
ProximitySensorEventListener mProximitySensorListener;
public interface IOemListener {
boolean isTestCard();
void onCallChange(PhoneState phoneState);
void onDataChange(PhoneState phoneState);
void onSensorChange(SensorState sensorState);
void onSreenChange(boolean z);
}
public enum PhoneState {
IDLE,
OFFHOOK
}
public enum SensorState {
FAR,
NEAR
}
public enum SwitchWifiSar {
SAR_OFF,
SAR_ON_Group1,
SAR_ON_Group2,
SAR_ON_Group3,
SAR_ON_Group4,
SAR_ON_Group5,
SAR_ON_Group6,
SAR_ON_Group7,
SAR_ON_Group8,
SAR_ON_Group9,
SAR_ON_Group10,
SAR_ON_Group11,
SAR_ON_Group12,
SAR_ON_Group13,
SAR_ON_Group14,
SAR_ON_Group15,
SAR_ON_Group16,
SAR_ON_Group17,
SAR_ON_Group18,
SAR_ON_Group19,
SAR_ON_Group20,
SAR_ON_Group21,
SAR_ON_Group22,
SAR_ON_Group23,
SAR_ON_Group24,
SAR_ON_Group25,
SAR_ON_Group26,
SAR_ON_Group27,
SAR_ON_Group28,
SAR_ON_Group29,
SAR_ON_Group30,
SAR_ON_Group31,
SAR_ON_Group32
}
public enum WifiState {
CLOSED,
WIFI_CONCURRENT,
WIFI_2P4GHZ,
WIFI_5GHZ
}
protected class OemWifiSarHandler extends Handler {
public OemWifiSarHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
int i = msg.what;
if (i == 1) {
OemConstant.setWifiSar(msg.arg1);
} else if (i == 2) {
Bundle date = msg.getData();
OemConstant.runExecCmd(date.getInt("wifisar"), date.getString(RegionLockPlmnListParser.PlmnCodeEntry.COUNTRY_ATTR), date.getString("project"));
} else if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.LOG_TAG, "msg is error");
}
}
}
private static class ProximitySensorEventListener extends Handler implements SensorEventListener {
private static final String ACTION_SAR_UPDATE_BY_ENG = "oppo.intent.action.SAR_UPDATE_BY_ENG";
protected static final int EVENT_OEM_DATA_DELAY = 297;
protected static final int EVENT_OEM_DELAY_REGISTER_PROXIMI = 299;
protected static final int EVENT_OEM_SCREEN_CHANGED = 298;
private static final float FAR_THRESHOLD = 5.0f;
protected static final int TIMER_DATA_DELAY = 3000;
private static int WIFI_SAR_TEST_MODEM_WORK_TYPE_4G_MODE = 2;
private static int WIFI_SAR_TEST_MODEM_WORK_TYPE_5G_MODE = 3;
private static int WIFI_SAR_TEST_MODEM_WORK_TYPE_DISABLE = 1;
private static int WIFI_SAR_TEST_MODEM_WORK_TYPE_FOLLOW = 0;
private static int WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_DISABLE = 0;
/* access modifiers changed from: private */
public static int WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_FOLLOW = -1;
/* access modifiers changed from: private */
public int mApBand = -1;
private AudioManager mAudioManager = null;
private int mConcurenceWifiState = 0;
/* access modifiers changed from: private */
public boolean mIsConnected = false;
private boolean mIsHotspot24 = false;
private boolean mIsHotspot5 = false;
/* access modifiers changed from: private */
public boolean mIsNormal24 = false;
/* access modifiers changed from: private */
public boolean mIsNormal5 = false;
private boolean mIsP2P24 = false;
private boolean mIsP2P5 = false;
private volatile boolean mIsPhoneListen = false;
private volatile boolean mIsProximListen = false;
/* access modifiers changed from: private */
public volatile boolean mIsTestCard = false;
private boolean mIsWifistate24 = false;
private boolean mIsWifistate5 = false;
private int mLastCallSlotId = -1;
/* access modifiers changed from: private */
public PhoneState mLastCallState;
/* access modifiers changed from: private */
public PhoneState mLastDataState;
/* access modifiers changed from: private */
public volatile boolean mLastScreenOn;
private SensorState mLastSensorState;
private volatile SwitchWifiSar mLastWifiSar;
private final IOemListener mListener;
private final float mMaxValue;
private OemReceiver mOemReceiver = null;
/* access modifiers changed from: private */
public WifiP2pGroup mP2pGroup = null;
/* access modifiers changed from: private */
public boolean mP2pStart = false;
private PhoneStateListener[] mPhoneStateListeners = null;
private final Sensor mProximitySensor;
private final SensorManager mSensorManager;
/* access modifiers changed from: private */
public int mSoftApFreq = -1;
/* access modifiers changed from: private */
public boolean mSoftApStart = false;
/* access modifiers changed from: private */
public int mWifiSarTestChanel2G = -1;
/* access modifiers changed from: private */
public int mWifiSarTestChanel5G = -1;
/* access modifiers changed from: private */
public String mWifiSarTestCountryCode = "";
/* access modifiers changed from: private */
public boolean mWifiSarTestEnable = false;
/* access modifiers changed from: private */
public int mWifiSarTestModeWorkType = -1;
/* access modifiers changed from: private */
public boolean mWifiShareInDiffChannel = false;
protected class OemPhoneStateListener extends PhoneStateListener {
ProximitySensorEventListener mPssListener;
public OemPhoneStateListener(ProximitySensorEventListener pssListener, int slotId) {
this.mPssListener = pssListener;
}
public void onDataActivity(int direction) {
this.mPssListener.onDataActivity(direction);
}
public void onCallStateChanged(int value, String incomingNumber) {
this.mPssListener.onCallStateChanged(value, incomingNumber);
}
}
protected class OemReceiver extends BroadcastReceiver {
private static final String ACTION_WIFI_SAR_TEST_CFG = "oppo.intent.action.WIFI_SAR_TEST_CONFIG";
private static final String CFG_COUNTRY_CODE = "countryCode";
private static final String CFG_MODEM_TYPE = "modemWorkType";
private static final String CFG_SAR_ENABLE = "enableSarTest";
private static final String CFG_WIFI_CHANNEL_2G = "wifiChannel2G";
private static final String CFG_WIFI_CHANNEL_5G = "wifiChannel5G";
ProximitySensorEventListener mProximityListener;
public OemReceiver(ProximitySensorEventListener orienListener) {
this.mProximityListener = orienListener;
ProximitySensorEventListener.this.registerPhone();
}
/* JADX WARNING: Code restructure failed: missing block: B:108:0x0253, code lost:
return;
*/
/* JADX WARNING: Code restructure failed: missing block: B:38:0x00ac, code lost:
return;
*/
public void onReceive(Context context, Intent intent) {
String action;
if (intent != null && (action = intent.getAction()) != null) {
synchronized (this) {
boolean isModemWork = true;
if (action.equals("android.net.wifi.WIFI_AP_STATE_CHANGED")) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "Ash recevice WIFI_AP_STATE_CHANGED_ACTION");
}
WifiConfiguration mWifiConfiguration = null;
if (intent.getIntExtra("wifi_state", 11) == 13) {
boolean unused = ProximitySensorEventListener.this.mSoftApStart = true;
} else {
boolean unused2 = ProximitySensorEventListener.this.mSoftApStart = false;
int unused3 = ProximitySensorEventListener.this.mSoftApFreq = -1;
}
int unused4 = ProximitySensorEventListener.this.mApBand = -1;
if (ProximitySensorEventListener.this.mSoftApStart) {
if (WifiOemProximitySensorManager.mWifiManager != null) {
try {
mWifiConfiguration = WifiOemProximitySensorManager.mWifiManager.getWifiApConfiguration();
} catch (Exception e) {
Rlog.e(WifiOemProximitySensorManager.TAG, "WIFI_AP_STATE_CHANGED_ACTION getWifiApConfiguration Exception");
}
if (mWifiConfiguration != null) {
int unused5 = ProximitySensorEventListener.this.mApBand = mWifiConfiguration.apBand;
Rlog.d(WifiOemProximitySensorManager.TAG, "mApBand " + ProximitySensorEventListener.this.mApBand);
}
} else {
Rlog.e(WifiOemProximitySensorManager.TAG, "mWifiManager is NULL!");
}
}
ProximitySensorEventListener.this.wifiChangeState();
ProximitySensorEventListener.this.processWifiSwitch();
} else if (action.equals("android.net.wifi.WIFI_STATE_CHANGED")) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "Ash recevice WIFI_STATE_CHANGED_ACTION");
}
} else if (action.equals("android.net.wifi.STATE_CHANGE")) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "Recevice NETWORK_STATE_CHANGED_ACTION");
}
WifiInfo wifiInfo = null;
if (WifiOemProximitySensorManager.mWifiManager != null) {
wifiInfo = WifiOemProximitySensorManager.mWifiManager.getConnectionInfo();
}
NetworkInfo networkinfo = (NetworkInfo) intent.getParcelableExtra("networkInfo");
if (networkinfo != null) {
boolean unused6 = ProximitySensorEventListener.this.mIsConnected = networkinfo.isConnected();
}
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "mIsConnected: " + ProximitySensorEventListener.this.mIsConnected);
}
if (!(ProximitySensorEventListener.this.mLastDataState == PhoneState.OFFHOOK || ProximitySensorEventListener.this.mLastCallState == PhoneState.OFFHOOK)) {
isModemWork = false;
}
if (!ProximitySensorEventListener.this.mIsTestCard) {
if (ProximitySensorEventListener.this.mLastScreenOn || !ProximitySensorEventListener.this.mIsConnected || !isModemWork) {
ProximitySensorEventListener.this.unregisterProximi();
} else {
ProximitySensorEventListener.this.registerProximi();
}
} else if (ProximitySensorEventListener.this.mIsConnected) {
ProximitySensorEventListener.this.registerProximi();
} else {
ProximitySensorEventListener.this.unregisterProximi();
}
if (ProximitySensorEventListener.this.mIsConnected) {
ProximitySensorEventListener.this.registerPhone();
}
if (wifiInfo != null) {
int haveNetworkId = wifiInfo.getNetworkId();
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "haveNetworkId: " + haveNetworkId);
}
if (-1 != haveNetworkId) {
boolean unused7 = ProximitySensorEventListener.this.mIsNormal24 = wifiInfo.is24GHz();
boolean unused8 = ProximitySensorEventListener.this.mIsNormal5 = wifiInfo.is5GHz();
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "mIsNormal24: " + ProximitySensorEventListener.this.mIsNormal24 + " mIsNormal5: " + ProximitySensorEventListener.this.mIsNormal5);
}
ProximitySensorEventListener.this.processWifiSwitch();
} else {
boolean unused9 = ProximitySensorEventListener.this.mIsNormal24 = false;
boolean unused10 = ProximitySensorEventListener.this.mIsNormal5 = false;
}
} else {
boolean unused11 = ProximitySensorEventListener.this.mIsNormal24 = false;
boolean unused12 = ProximitySensorEventListener.this.mIsNormal5 = false;
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "Ash info is NULL!");
}
}
ProximitySensorEventListener.this.wifiChangeState();
ProximitySensorEventListener.this.processWifiSwitch();
} else if (action.equals(WifiOemProximitySensorManager.WIFI_SHARING_STATE_CHANGED_ACTION)) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "Recevice WIFI_SHARING_STATE_CHANGED_ACTION");
}
int wifiSharingState = intent.getIntExtra("wifi_state", 14);
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "wifiSharingState: " + wifiSharingState);
}
if (wifiSharingState == WifiOemProximitySensorManager.WIFI_SHARING_STATE_ENABLED && ProximitySensorEventListener.this.mIsNormal5 && Build.HARDWARE.equals("mt6779")) {
boolean unused13 = ProximitySensorEventListener.this.mWifiShareInDiffChannel = true;
ProximitySensorEventListener.this.processWifiSwitch();
} else {
boolean unused14 = ProximitySensorEventListener.this.mWifiShareInDiffChannel = false;
}
} else if (action.equals("android.net.wifi.p2p.CONNECTION_STATE_CHANGE")) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "Recevice WIFI_P2P_CONNECTION_CHANGED_ACTION");
}
NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra("networkInfo");
WifiP2pGroup unused15 = ProximitySensorEventListener.this.mP2pGroup = (WifiP2pGroup) intent.getParcelableExtra("p2pGroupInfo");
if (ProximitySensorEventListener.this.mP2pGroup == null || networkInfo == null || !networkInfo.isConnected()) {
boolean unused16 = ProximitySensorEventListener.this.mP2pStart = false;
} else {
boolean unused17 = ProximitySensorEventListener.this.mP2pStart = true;
ProximitySensorEventListener.this.wifiChangeState();
}
ProximitySensorEventListener.this.processWifiSwitch();
} else if (action.equals(ACTION_WIFI_SAR_TEST_CFG)) {
Log.d(WifiOemProximitySensorManager.TAG, "Ash recevice ACTION_WIFI_SAR_TEST_CFG");
int enable = intent.getIntExtra(CFG_SAR_ENABLE, 0);
ProximitySensorEventListener proximitySensorEventListener = ProximitySensorEventListener.this;
if (enable == 0) {
isModemWork = false;
}
boolean unused18 = proximitySensorEventListener.mWifiSarTestEnable = isModemWork;
if (ProximitySensorEventListener.this.mWifiSarTestEnable) {
String unused19 = ProximitySensorEventListener.this.mWifiSarTestCountryCode = intent.getStringExtra(CFG_COUNTRY_CODE);
int unused20 = ProximitySensorEventListener.this.mWifiSarTestModeWorkType = intent.getIntExtra(CFG_MODEM_TYPE, -1);
int unused21 = ProximitySensorEventListener.this.mWifiSarTestChanel2G = intent.getIntExtra(CFG_WIFI_CHANNEL_2G, ProximitySensorEventListener.WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_FOLLOW);
int unused22 = ProximitySensorEventListener.this.mWifiSarTestChanel5G = intent.getIntExtra(CFG_WIFI_CHANNEL_5G, ProximitySensorEventListener.WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_FOLLOW);
}
ProximitySensorEventListener.this.processWifiSwitch();
} else if (action.equals(ProximitySensorEventListener.ACTION_SAR_UPDATE_BY_ENG)) {
Log.d(WifiOemProximitySensorManager.TAG, "onEngineerModeChanged, processWifiSwitch");
ProximitySensorEventListener.this.processWifiSwitch();
}
}
}
}
public void register(Context context) {
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED");
filter.addAction("android.net.wifi.STATE_CHANGE");
filter.addAction(WifiOemProximitySensorManager.WIFI_SHARING_STATE_CHANGED_ACTION);
filter.addAction("android.net.wifi.p2p.CONNECTION_STATE_CHANGE");
filter.addAction(ACTION_WIFI_SAR_TEST_CFG);
filter.addAction(ProximitySensorEventListener.ACTION_SAR_UPDATE_BY_ENG);
context.registerReceiver(this, filter);
}
public void unregister(Context context) {
context.unregisterReceiver(this);
}
}
public ProximitySensorEventListener(SensorManager sensorManager, Sensor proximitySensor, IOemListener listener) {
this.mSensorManager = sensorManager;
this.mProximitySensor = proximitySensor;
this.mMaxValue = proximitySensor.getMaximumRange();
this.mListener = listener;
this.mLastSensorState = SensorState.FAR;
this.mLastDataState = PhoneState.IDLE;
this.mLastCallState = PhoneState.IDLE;
this.mLastScreenOn = true;
Context context = getContext();
this.mLastWifiSar = SwitchWifiSar.SAR_OFF;
int numPhones = TelephonyManager.from(context).getPhoneCount();
this.mPhoneStateListeners = new OemPhoneStateListener[numPhones];
for (int i = 0; i < numPhones; i++) {
this.mPhoneStateListeners[i] = new OemPhoneStateListener(this, i);
}
this.mOemReceiver = new OemReceiver(this);
}
public static Context getContext() {
return PhoneFactory.getPhone(0).getContext();
}
public void register() {
registerSceeen();
this.mOemReceiver.register(getContext());
}
public void unregister() {
unregisterScreen();
this.mOemReceiver.unregister(getContext());
}
public void registerSceeen() {
OppoTelephonyController.getInstance(getContext()).registerForOemScreenChanged(this, EVENT_OEM_SCREEN_CHANGED, null);
}
public void unregisterScreen() {
OppoTelephonyController.getInstance(getContext()).unregisterOemScreenChanged(this);
}
public void registerProximi() {
if (!this.mIsProximListen) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "registerProximi");
}
this.mIsProximListen = true;
this.mSensorManager.registerListener(this, this.mProximitySensor, 2);
}
}
public void unregisterProximi() {
if (this.mIsProximListen) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "unregisterProximi");
}
this.mIsProximListen = false;
this.mSensorManager.unregisterListener(this);
}
}
public void registerPhone() {
if (!this.mIsPhoneListen) {
Log.d(WifiOemProximitySensorManager.TAG, "registerPhone");
this.mIsPhoneListen = true;
TelephonyManager tm = TelephonyManager.from(PhoneFactory.getPhone(0).getContext());
int numPhones = tm.getPhoneCount();
for (int i = 0; i < numPhones; i++) {
int subId = SubscriptionController.getInstance().getSubIdUsingPhoneId(i);
if (SubscriptionController.getInstance().isActiveSubId(subId)) {
tm.createForSubscriptionId(subId).listen(this.mPhoneStateListeners[i], 160);
}
}
}
}
public void unregisterPhone() {
if (this.mIsPhoneListen) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "unregisterPhone");
}
this.mIsPhoneListen = false;
TelephonyManager tm = TelephonyManager.from(PhoneFactory.getPhone(0).getContext());
int numPhones = tm.getPhoneCount();
for (int i = 0; i < numPhones; i++) {
tm.listen(this.mPhoneStateListeners[i], 0);
}
}
}
public void onSensorChanged(SensorEvent event) {
if (event.values != null && event.values.length != 0) {
SensorState state = getStateFromValue(event.values[0]);
if (OemConstant.SWITCH_LOG) {
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, "onSensorChanged:" + state);
}
synchronized (this) {
if (state != this.mLastSensorState) {
this.mLastSensorState = state;
this.mListener.onSensorChange(state);
processWifiSwitch();
}
}
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/* JADX WARNING: Code restructure failed: missing block: B:33:?, code lost:
return;
*/
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_OEM_DATA_DELAY /*{ENCODED_INT: 297}*/:
synchronized (this) {
if (this.mLastDataState != PhoneState.IDLE) {
if (!this.mIsProximListen) {
registerProximi();
break;
}
} else {
return;
}
}
break;
case EVENT_OEM_SCREEN_CHANGED /*{ENCODED_INT: 298}*/:
AsyncResult arscreen = (AsyncResult) msg.obj;
if (arscreen != null) {
boolean isOn = ((Boolean) arscreen.result).booleanValue();
if (OemConstant.SWITCH_LOG) {
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, "EVENT_OEM_SCREEN_CHANGED " + isOn);
}
onSreenChanged(isOn);
return;
} else if (OemConstant.SWITCH_LOG) {
Log.w(WifiOemProximitySensorManager.TAG, "EVENT_OEM_SCREEN_CHANGED error");
return;
} else {
return;
}
case EVENT_OEM_DELAY_REGISTER_PROXIMI /*{ENCODED_INT: 299}*/:
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "EVENT_OEM_DELAY_REGISTER_PROXIMI ");
}
registerProximi();
return;
default:
return;
}
}
/* JADX WARNING: Code restructure failed: missing block: B:16:0x0049, code lost:
r4.mListener.onDataChange(r0);
processWifiSwitch();
*/
/* JADX WARNING: Code restructure failed: missing block: B:17:0x0051, code lost:
return;
*/
public void onDataActivity(int direction) {
PhoneState state = getDataStateFromValue(direction);
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, "onDataActivity state:" + state);
synchronized (this) {
if (state != this.mLastDataState) {
this.mLastDataState = state;
if (this.mLastDataState == PhoneState.OFFHOOK) {
Message msg = Message.obtain();
msg.what = EVENT_OEM_DATA_DELAY;
sendMessageDelayed(msg, 3000);
} else {
removeMessages(EVENT_OEM_DATA_DELAY);
if (this.mLastCallState == PhoneState.IDLE && this.mIsProximListen) {
unregisterProximi();
}
}
}
}
}
/* JADX WARNING: Code restructure failed: missing block: B:11:0x0028, code lost:
r4.mListener.onCallChange(r0);
*/
/* JADX WARNING: Code restructure failed: missing block: B:12:0x002f, code lost:
if (com.android.internal.telephony.OemConstant.SWITCH_LOG == false) goto L_0x004c;
*/
/* JADX WARNING: Code restructure failed: missing block: B:13:0x0031, code lost:
r1 = com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.TAG;
android.util.Log.d(r1, "onCallStateChanged:" + r0 + ", processSwitch");
*/
/* JADX WARNING: Code restructure failed: missing block: B:14:0x004c, code lost:
processWifiSwitch();
*/
/* JADX WARNING: Code restructure failed: missing block: B:15:0x004f, code lost:
return;
*/
public void onCallStateChanged(int value, String incomingNumber) {
PhoneState state = getCallStateFromValue(value);
if (OemConstant.SWITCH_LOG) {
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, "onCallStateChanged:" + state);
}
synchronized (this) {
if (state != this.mLastCallState) {
this.mLastCallState = state;
}
}
}
/* JADX WARNING: Code restructure failed: missing block: B:22:0x003b, code lost:
r4.mListener.onSreenChange(r5);
*/
/* JADX WARNING: Code restructure failed: missing block: B:23:0x0042, code lost:
if (com.android.internal.telephony.OemConstant.SWITCH_LOG == false) goto L_0x005f;
*/
/* JADX WARNING: Code restructure failed: missing block: B:24:0x0044, code lost:
r0 = com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.TAG;
android.util.Log.d(r0, "onSreenChange:" + r5 + ", processSwitch");
*/
/* JADX WARNING: Code restructure failed: missing block: B:25:0x005f, code lost:
processWifiSwitch();
*/
/* JADX WARNING: Code restructure failed: missing block: B:26:0x0062, code lost:
return;
*/
/* JADX WARNING: Removed duplicated region for block: B:15:0x001d */
public void onSreenChanged(boolean isOn) {
synchronized (this) {
if (this.mLastScreenOn != isOn) {
this.mLastScreenOn = isOn;
if (this.mLastDataState != PhoneState.OFFHOOK) {
if (this.mLastCallState != PhoneState.OFFHOOK) {
if (!this.mIsTestCard) {
if (this.mLastScreenOn || !this.mIsConnected) {
removeMessages(EVENT_OEM_DELAY_REGISTER_PROXIMI);
unregisterProximi();
} else {
Message msg = Message.obtain();
msg.what = EVENT_OEM_DELAY_REGISTER_PROXIMI;
sendMessageDelayed(msg, 2000);
}
}
}
}
if (!this.mIsTestCard) {
}
}
}
}
private boolean isEuropeCountry(String country) {
if (country == null || country.isEmpty()) {
Log.d(WifiOemProximitySensorManager.TAG, "country = null");
return false;
} else if (WifiOemProximitySensorManager.mEuropeCountryList == null) {
Log.e(WifiOemProximitySensorManager.TAG, "mEuropeCountryList = null");
return false;
} else {
for (int i = 0; i < WifiOemProximitySensorManager.mEuropeCountryList.length; i++) {
if (country.equalsIgnoreCase(WifiOemProximitySensorManager.mEuropeCountryList[i])) {
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, "is Europe Country " + country);
return true;
}
}
return false;
}
}
private boolean isCeCountry(String country) {
if (country == null || country.isEmpty()) {
Log.d(WifiOemProximitySensorManager.TAG, "ce country = null");
return false;
} else if (WifiOemProximitySensorManager.mCeCountryList == null) {
Log.e(WifiOemProximitySensorManager.TAG, "mCeCountryList = null");
return false;
} else {
for (int i = 0; i < WifiOemProximitySensorManager.mCeCountryList.length; i++) {
if (country.equalsIgnoreCase(WifiOemProximitySensorManager.mCeCountryList[i])) {
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, "is ce Country " + country);
return true;
}
}
return false;
}
}
private boolean isFccCountry(String country) {
if (country == null || country.isEmpty()) {
Log.d(WifiOemProximitySensorManager.TAG, "Fcc country = null");
return false;
} else if (WifiOemProximitySensorManager.mFccCountryList == null) {
Log.e(WifiOemProximitySensorManager.TAG, "mCeCountryList = null");
return false;
} else {
for (int i = 0; i < WifiOemProximitySensorManager.mFccCountryList.length; i++) {
if (country.equalsIgnoreCase(WifiOemProximitySensorManager.mFccCountryList[i])) {
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, "is Fcc Country " + country);
return true;
}
}
return false;
}
}
/* access modifiers changed from: private */
public void wifiChangeState() {
if (this.mP2pStart) {
int freq = this.mP2pGroup.getFrequency();
if (freq >= 2412 && freq <= 2472) {
this.mIsP2P5 = false;
this.mIsP2P24 = true;
} else if (freq > 5000) {
this.mIsP2P5 = true;
this.mIsP2P24 = false;
}
String str = WifiOemProximitySensorManager.TAG;
Log.d(str, " p2p freq = " + freq);
}
int freq2 = this.mApBand;
if (freq2 == 1) {
this.mIsHotspot24 = false;
this.mIsHotspot5 = true;
} else if (freq2 == 0) {
this.mIsHotspot24 = true;
this.mIsHotspot5 = false;
} else {
this.mIsHotspot24 = false;
this.mIsHotspot5 = false;
}
if (this.mIsP2P24 || this.mIsHotspot24 || this.mIsNormal24) {
this.mIsWifistate24 = true;
} else {
this.mIsWifistate24 = false;
}
if (this.mIsP2P5 || this.mIsHotspot5 || this.mIsNormal5) {
this.mIsWifistate5 = true;
} else {
this.mIsWifistate5 = false;
}
}
/* access modifiers changed from: private */
/* JADX WARNING: Removed duplicated region for block: B:114:0x022e */
/* JADX WARNING: Removed duplicated region for block: B:117:0x0234 */
/* JADX WARNING: Removed duplicated region for block: B:118:0x0255 */
/* JADX WARNING: Removed duplicated region for block: B:121:0x025f */
/* JADX WARNING: Removed duplicated region for block: B:186:0x02f9 */
/* JADX WARNING: Removed duplicated region for block: B:36:0x007a */
/* JADX WARNING: Removed duplicated region for block: B:390:0x04db A[DONT_GENERATE] */
/* JADX WARNING: Removed duplicated region for block: B:392:0x04dd */
/* JADX WARNING: Removed duplicated region for block: B:393:0x0517 */
/* JADX WARNING: Removed duplicated region for block: B:408:0x053e */
/* JADX WARNING: Removed duplicated region for block: B:418:0x0551 */
/* JADX WARNING: Removed duplicated region for block: B:457:0x05cc */
/* JADX WARNING: Removed duplicated region for block: B:49:0x00e2 */
/* JADX WARNING: Removed duplicated region for block: B:500:0x063d A[DONT_GENERATE] */
/* JADX WARNING: Removed duplicated region for block: B:502:0x063f */
/* JADX WARNING: Removed duplicated region for block: B:52:0x00e8 */
/* JADX WARNING: Removed duplicated region for block: B:93:0x0199 */
public void processWifiSwitch() {
boolean z;
boolean isSensorSwitchOn;
boolean isModemWork;
boolean headSar;
this.mIsTestCard = this.mListener.isTestCard();
synchronized (this) {
SystemProperties.get("ro.oppo.regionmark", "EX").equalsIgnoreCase("IN");
SwitchWifiSar state = SwitchWifiSar.SAR_OFF;
String country = "";
if (WifiOemProximitySensorManager.mWifiManager != null) {
country = WifiOemProximitySensorManager.mWifiManager.getCountryCode();
}
String Project = OemConstant.getProjectForWifi();
boolean fakeCardNear = this.mIsTestCard && this.mLastSensorState == SensorState.NEAR;
boolean fakeCardFar = this.mIsTestCard && this.mLastSensorState == SensorState.FAR;
boolean realCardNearScrOff = !this.mIsTestCard && this.mLastSensorState == SensorState.NEAR && !this.mLastScreenOn;
if (this.mLastDataState != PhoneState.OFFHOOK) {
if (this.mLastCallState != PhoneState.OFFHOOK) {
z = false;
boolean isModemWork2 = z;
if (!OemConstant.SWITCH_LOG) {
String str = WifiOemProximitySensorManager.TAG;
StringBuilder sb = new StringBuilder();
sb.append("processWifiSwitch mIsTestCard=");
sb.append(this.mIsTestCard);
sb.append(",realCardNear=");
sb.append(this.mLastSensorState == SensorState.NEAR);
sb.append(",DataState=");
sb.append(this.mLastDataState == PhoneState.OFFHOOK);
sb.append(",CallState=");
sb.append(this.mLastCallState == PhoneState.OFFHOOK);
sb.append(",country=");
sb.append(country);
sb.append(",Project=");
sb.append(Project);
sb.append(",mLastScreenOn=");
sb.append(this.mLastScreenOn);
Log.d(str, sb.toString());
}
if (this.mWifiSarTestEnable) {
country = this.mWifiSarTestCountryCode;
isModemWork2 = this.mWifiSarTestModeWorkType == WIFI_SAR_TEST_MODEM_WORK_TYPE_4G_MODE;
if (this.mWifiSarTestChanel2G != WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_FOLLOW) {
this.mIsWifistate24 = this.mWifiSarTestChanel2G != WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_DISABLE;
this.mIsNormal24 = this.mIsWifistate24;
} else {
this.mIsNormal24 = false;
}
if (this.mWifiSarTestChanel5G != WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_FOLLOW) {
this.mIsWifistate5 = this.mWifiSarTestChanel5G != WIFI_SAR_TEST_WIFI_CHANNEL_TYPE_DISABLE;
this.mIsNormal5 = this.mIsWifistate5;
if (this.mIsWifistate5) {
if (this.mWifiSarTestChanel5G < 5180 || this.mWifiSarTestChanel5G > 5320) {
if (this.mWifiSarTestChanel5G < 5500 || this.mWifiSarTestChanel5G > 5700) {
if (this.mWifiSarTestChanel5G < 5745 || this.mWifiSarTestChanel5G > 5825) {
this.mIsWifistate5 = false;
}
}
}
}
} else {
this.mIsWifistate5 = false;
}
Log.d(WifiOemProximitySensorManager.TAG, "countryCode: " + country + " isModemWork: " + isModemWork2 + " mIsWifistate24: " + this.mIsWifistate24 + " mIsWifistate5: " + this.mIsWifistate5);
}
if (!Build.HARDWARE.equals("mt6779")) {
String fakeProxiState = SystemProperties.get("core.oppo.network.fake_near", "-1");
if (this.mIsTestCard) {
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "fakeProxiState=" + fakeProxiState);
}
if (fakeProxiState.equals("1")) {
fakeCardNear = true;
fakeCardFar = false;
} else if (fakeProxiState.equals("0")) {
fakeCardNear = false;
fakeCardFar = true;
}
}
if (OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "processWifiSwitch1, fakeCardNear=" + fakeCardNear + ",realCardNearScrOff=" + realCardNearScrOff + ",isModemWork=" + isModemWork2 + ",mIsNormal24=" + this.mIsNormal24 + ",mIsNormal5=" + this.mIsNormal5);
}
if (!fakeCardNear) {
if (!realCardNearScrOff) {
headSar = false;
boolean isAirplaneModeOn = false;
if (Settings.Global.getInt(getContext().getContentResolver(), "airplane_mode_on", 0) == 1) {
isAirplaneModeOn = true;
}
if (!OemConstant.SWITCH_LOG) {
Log.d(WifiOemProximitySensorManager.TAG, "processWifiSwitch2, headSar=" + headSar + ",bodySar=" + fakeCardFar);
}
if (!"IN".equals(country)) {
if (headSar) {
if (!isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group1;
} else if (!isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group2;
} else if (isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group3;
} else if (isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group4;
}
} else if (isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group5;
} else if (isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group6;
} else if (!isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group7;
} else if (!isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group8;
}
} else if (isCeCountry(country)) {
if (headSar) {
if (!isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group9;
} else if (!isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group10;
} else if (isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group11;
} else if (isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group12;
}
} else if (isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group13;
} else if (isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group14;
} else if (!isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group15;
} else if (!isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group16;
}
} else if (isFccCountry(country)) {
if (headSar) {
if (!isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group17;
} else if (!isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group18;
} else if (isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group19;
} else if (isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group20;
}
} else if (isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group21;
} else if (isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group22;
} else if (!isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group23;
} else if (!isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group24;
}
} else if (!isEuropeCountry(country)) {
state = SwitchWifiSar.SAR_OFF;
} else if (headSar) {
if (!isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group25;
} else if (!isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group26;
} else if (isModemWork2 && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group27;
} else if (isModemWork2 && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group28;
}
} else if (isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group29;
} else if (isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group30;
} else if (!isAirplaneModeOn && ((this.mIsWifistate24 && !this.mIsWifistate5) || (!this.mIsWifistate24 && this.mIsWifistate5))) {
state = SwitchWifiSar.SAR_ON_Group31;
} else if (!isAirplaneModeOn && this.mIsWifistate24 && this.mIsWifistate5) {
state = SwitchWifiSar.SAR_ON_Group32;
}
if (this.mLastWifiSar == state) {
this.mLastWifiSar = state;
Message msg = Message.obtain();
msg.what = 2;
Bundle data = new Bundle();
data.putInt("wifisar", this.mLastWifiSar.ordinal());
data.putString(RegionLockPlmnListParser.PlmnCodeEntry.COUNTRY_ATTR, country);
data.putString("project", Project);
msg.setData(data);
WifiOemProximitySensorManager.mHandler.removeMessages(2);
WifiOemProximitySensorManager.mHandler.sendMessage(msg);
} else {
return;
}
}
}
headSar = true;
boolean isAirplaneModeOn2 = false;
if (Settings.Global.getInt(getContext().getContentResolver(), "airplane_mode_on", 0) == 1) {
}
if (!OemConstant.SWITCH_LOG) {
}
if (!"IN".equals(country)) {
}
if (this.mLastWifiSar == state) {
}
} else {
boolean headSar2 = false;
if (Build.HARDWARE.equals("mt6771")) {
if (!this.mIsTestCard) {
if (!this.mIsTestCard) {
if (!this.mIsNormal24) {
if (this.mIsNormal5) {
}
}
}
isSensorSwitchOn = false;
if (this.mLastDataState != PhoneState.OFFHOOK) {
if (this.mLastCallState != PhoneState.OFFHOOK) {
isModemWork = false;
if (fakeCardNear || realCardNearScrOff) {
headSar2 = true;
}
if (isSensorSwitchOn || !"18531".equals(Project)) {
if (isSensorSwitchOn || !"19531".equals(Project)) {
state = SwitchWifiSar.SAR_OFF;
} else if ("IN".equals(country)) {
if (!isModemWork && (this.mIsNormal24 || this.mIsNormal5)) {
state = headSar2 ? SwitchWifiSar.SAR_ON_Group3 : SwitchWifiSar.SAR_OFF;
} else if (isModemWork && (this.mIsNormal24 || this.mIsNormal5)) {
state = headSar2 ? SwitchWifiSar.SAR_ON_Group4 : fakeCardFar ? SwitchWifiSar.SAR_OFF : SwitchWifiSar.SAR_OFF;
}
} else if (isModemWork || (!this.mIsNormal24 && !this.mIsNormal5)) {
if (isModemWork && (this.mIsNormal24 || this.mIsNormal5)) {
state = headSar2 ? SwitchWifiSar.SAR_ON_Group6 : fakeCardFar ? SwitchWifiSar.SAR_OFF : SwitchWifiSar.SAR_OFF;
}
} else if (!headSar2) {
state = SwitchWifiSar.SAR_OFF;
}
} else if (isModemWork && this.mIsNormal24) {
state = (this.mLastSensorState != SensorState.NEAR || this.mLastScreenOn) ? this.mLastSensorState == SensorState.FAR ? SwitchWifiSar.SAR_ON_Group2 : SwitchWifiSar.SAR_OFF : SwitchWifiSar.SAR_ON_Group1;
} else if (isModemWork && this.mIsNormal5) {
state = (this.mLastSensorState != SensorState.NEAR || this.mLastScreenOn) ? this.mLastSensorState == SensorState.FAR ? SwitchWifiSar.SAR_ON_Group2 : SwitchWifiSar.SAR_OFF : SwitchWifiSar.SAR_ON_Group1;
} else if (this.mIsNormal24) {
state = (this.mLastSensorState != SensorState.NEAR || this.mLastScreenOn) ? this.mLastSensorState == SensorState.FAR ? SwitchWifiSar.SAR_ON_Group2 : SwitchWifiSar.SAR_OFF : SwitchWifiSar.SAR_ON_Group1;
} else {
boolean z2 = this.mIsNormal5;
}
if (this.mLastWifiSar != state) {
this.mLastWifiSar = state;
Message msg2 = Message.obtain();
msg2.what = 1;
msg2.arg1 = this.mLastWifiSar.ordinal();
WifiOemProximitySensorManager.mHandler.removeMessages(1);
WifiOemProximitySensorManager.mHandler.sendMessage(msg2);
} else {
return;
}
}
}
isModemWork = true;
headSar2 = true;
if (isSensorSwitchOn) {
}
if (isSensorSwitchOn) {
}
state = SwitchWifiSar.SAR_OFF;
if (this.mLastWifiSar != state) {
}
}
isSensorSwitchOn = true;
if (this.mLastDataState != PhoneState.OFFHOOK) {
}
isModemWork = true;
headSar2 = true;
if (isSensorSwitchOn) {
}
if (isSensorSwitchOn) {
}
state = SwitchWifiSar.SAR_OFF;
if (this.mLastWifiSar != state) {
}
} else {
Log.d(WifiOemProximitySensorManager.TAG, "processWifiSwitch project is error");
}
}
Log.d(WifiOemProximitySensorManager.TAG, "processWifiSwitch mLastWifiSar.ordinal()=" + this.mLastWifiSar.ordinal());
}
}
z = true;
boolean isModemWork22 = z;
if (!OemConstant.SWITCH_LOG) {
}
if (this.mWifiSarTestEnable) {
}
if (!Build.HARDWARE.equals("mt6779")) {
}
Log.d(WifiOemProximitySensorManager.TAG, "processWifiSwitch mLastWifiSar.ordinal()=" + this.mLastWifiSar.ordinal());
}
}
private SensorState getStateFromValue(float value) {
return (value > FAR_THRESHOLD || value == this.mMaxValue) ? SensorState.FAR : SensorState.NEAR;
}
private PhoneState getDataStateFromValue(int value) {
return (value == 1 || value == 2 || value == 3) ? PhoneState.OFFHOOK : PhoneState.IDLE;
}
private PhoneState getCallStateFromValue(int value) {
return value == 0 ? PhoneState.IDLE : PhoneState.OFFHOOK;
}
}
public WifiOemProximitySensorManager(Context context) {
this(context, new IOemListener() {
/* class com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.AnonymousClass1 */
boolean mIsTestCard = false;
@Override // com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.IOemListener
public void onSensorChange(SensorState state) {
this.mIsTestCard = initTestCard();
}
@Override // com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.IOemListener
public void onDataChange(PhoneState state) {
}
@Override // com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.IOemListener
public void onCallChange(PhoneState state) {
}
@Override // com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.IOemListener
public void onSreenChange(boolean isOn) {
}
@Override // com.oppo.internal.telephony.rf.WifiOemProximitySensorManager.IOemListener
public boolean isTestCard() {
return this.mIsTestCard;
}
private synchronized boolean initTestCard() {
for (Phone phone : PhoneFactory.getPhones()) {
if (((AbstractPhone) OemTelephonyUtils.typeCasting(AbstractPhone.class, phone)).is_test_card()) {
return true;
}
}
return false;
}
});
mHandlerThread = new HandlerThread("wifi-sarthread");
mHandlerThread.start();
mHandler = new OemWifiSarHandler(mHandlerThread.getLooper());
mWifiManager = (WifiManager) context.getSystemService("wifi");
}
public WifiOemProximitySensorManager(Context context, IOemListener listener) {
this.mProximitySensorListener = null;
SensorManager sensorManager = (SensorManager) context.getSystemService("sensor");
Sensor proximitySensor = sensorManager.getDefaultSensor(8);
if (proximitySensor == null) {
this.mProximitySensorListener = null;
} else {
initValueByReflection();
this.mProximitySensorListener = new ProximitySensorEventListener(sensorManager, proximitySensor, listener);
this.mProximitySensorListener.register();
}
Log.d(TAG, "WifiOemProximitySensorManager: init and release first");
}
private void initValueByReflection() {
Object obj = ReflectionHelper.getDeclaredField(WifiManager.class, "android.net.wifi.WifiManager", "WIFI_AP_CHANNEL_CHANGED_ACTION");
WIFI_AP_CHANNEL_CHANGED_ACTION = obj != null ? (String) obj : "android.net.wifi.WIFI_AP_CHANNEL_CHANGED";
Object obj2 = ReflectionHelper.getDeclaredField(WifiManager.class, "android.net.wifi.WifiManager", "EXTRA_WIFI_AP_WORKING_FREQUENCY");
EXTRA_WIFI_AP_WORKING_FREQUENCY = obj2 != null ? (String) obj2 : "wifi_ap_working_frequency";
Object obj3 = ReflectionHelper.getDeclaredField(WifiConfiguration.class, "android.net.wifi.WifiConfiguration", "AP_BAND_DUAL");
AP_BAND_DUAL = obj3 != null ? ((Integer) obj3).intValue() : 2;
Object obj4 = ReflectionHelper.getDeclaredField(WifiManager.class, "android.net.wifi.WifiManager", "WIFI_SHARING_STATE_CHANGED_ACTION");
WIFI_SHARING_STATE_CHANGED_ACTION = obj4 != null ? (String) obj4 : "oppo.intent.action.wifi.WIFI_SHARING_STATE_CHANGED";
Object obj5 = ReflectionHelper.getDeclaredField(WifiManager.class, "android.net.wifi.WifiManager", "WIFI_SHARING_STATE_ENABLED");
WIFI_SHARING_STATE_ENABLED = obj5 != null ? ((Integer) obj5).intValue() : OppoRIL.SYS_OEM_NW_DIAG_CAUSE_DATA_STALL_ERROR;
}
public static synchronized WifiOemProximitySensorManager getDefault(Context context) {
WifiOemProximitySensorManager wifiOemProximitySensorManager;
synchronized (WifiOemProximitySensorManager.class) {
if (sInstance == null) {
sInstance = new WifiOemProximitySensorManager(context);
}
wifiOemProximitySensorManager = sInstance;
}
return wifiOemProximitySensorManager;
}
public void register() {
this.mProximitySensorListener.register();
}
public void unregister() {
ProximitySensorEventListener proximitySensorEventListener = this.mProximitySensorListener;
if (proximitySensorEventListener != null) {
proximitySensorEventListener.unregister();
}
}
}
| [
"dstmath@163.com"
] | dstmath@163.com |
28ac2b355333d462821b6e2dbe25eb13e83c292a | c9da71648dfc400548884bc309cca823450e8663 | /OTAS-DM-Project/nWave-DM-Common/src/com/npower/dm/setup/task/SoftwareCategoryTask.java | 576ea716129ed3ba3034ac036ff57cacc8512b74 | [] | no_license | chrisyun/macho-project-home | 810f984601bd42bc8bf6879b278e2cde6230e1d8 | f79f18f980178ebd01d3e916829810e94fd7dc04 | refs/heads/master | 2016-09-05T17:10:18.021448 | 2014-05-22T07:46:09 | 2014-05-22T07:46:09 | 36,444,782 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,335 | java | /**
* $Header: /home/master/nWave-DM-Common/src/com/npower/dm/setup/task/SoftwareCategoryTask.java,v 1.4 2008/11/28 10:26:17 chenlei Exp $
* $Revision: 1.4 $
* $Date: 2008/11/28 10:26:17 $
*
* ===============================================================================================
* License, Version 1.1
*
* Copyright (c) 1994-2008 NPower Network Software Ltd. All rights reserved.
*
* This SOURCE CODE FILE, which has been provided by NPower as part
* of a NPower product for use ONLY by licensed users of the product,
* includes CONFIDENTIAL and PROPRIETARY information of NPower.
*
* USE OF THIS SOFTWARE IS GOVERNED BY THE TERMS AND CONDITIONS
* OF THE LICENSE STATEMENT AND LIMITED WARRANTY FURNISHED WITH
* THE PRODUCT.
*
* IN PARTICULAR, YOU WILL INDEMNIFY AND HOLD NPower, ITS RELATED
* COMPANIES AND ITS SUPPLIERS, HARMLESS FROM AND AGAINST ANY CLAIMS
* OR LIABILITIES ARISING OUT OF THE USE, REPRODUCTION, OR DISTRIBUTION
* OF YOUR PROGRAMS, INCLUDING ANY CLAIMS OR LIABILITIES ARISING OUT OF
* OR RESULTING FROM THE USE, MODIFICATION, OR DISTRIBUTION OF PROGRAMS
* OR FILES CREATED FROM, BASED ON, AND/OR DERIVED FROM THIS SOURCE
* CODE FILE.
* ===============================================================================================
*/
package com.npower.dm.setup.task;
import java.io.File;
import java.util.List;
import com.npower.dm.core.DMException;
import com.npower.dm.core.SoftwareCategory;
import com.npower.dm.management.ManagementBeanFactory;
import com.npower.dm.management.SoftwareBean;
import com.npower.setup.core.SetupException;
/**
* @author chenlei
* @version $Revision: 1.4 $ $Date: 2008/11/28 10:26:17 $
*/
public class SoftwareCategoryTask extends DMTask {
private List<String> filenames;
/**
*
*/
public SoftwareCategoryTask() {
super();
}
public void copy(SoftwareCategoryItem item, SoftwareCategory softwareCategory, SoftwareCategory parentCategory) {
softwareCategory.setName(item.getName());
softwareCategory.setDescription(item.getDescription());
softwareCategory.setParent(parentCategory);
}
public List<String> getFilenames() {
if (this.filenames == null || this.filenames.size() == 0) {
return this.getPropertyValues("import.files");
}
return this.filenames;
}
public void setFilenames(List<String> filenames) {
this.filenames = filenames;
}
/* (non-Javadoc)
* @see com.npower.setup.core.AbstractTask#process()
*/
@Override
protected void process() throws SetupException {
filenames = this.getFilenames();
ManagementBeanFactory factory = null;
try {
factory = this.getManagementBeanFactory();
SoftwareBean softwareBean = factory.createSoftwareBean();
factory.beginTransaction();
for (String filename: filenames) {
// Process the file, and import data into database.
File file = new File(filename);
if (!file.isAbsolute()) {
file = new File(this.getSetup().getWorkDir(), filename);
}
List<SoftwareCategoryItem> items = this.loadSoftwareCategoryItems(file.getAbsolutePath());
update(items, softwareBean, null);
}
factory.commit();
} catch (Exception ex) {
if (factory != null) {
factory.rollback();
}
throw new SetupException("Error in import SoftwareCategory.", ex);
} finally {
if (factory != null) {
factory.release();
}
}
}
protected void update(List<SoftwareCategoryItem> items, SoftwareBean softwareBean, SoftwareCategory parentCategory) throws DMException{
for (SoftwareCategoryItem item: items) {
SoftwareCategory softwareCategory = softwareBean.newCategoryInstance();
this.copy(item, softwareCategory, parentCategory);
softwareBean.update(softwareCategory);
if (item.getSoftwareCategory().size() > 0) {
update(item.getSoftwareCategory(), softwareBean, softwareCategory);
}
}
}
/* (non-Javadoc)
* @see com.npower.setup.core.AbstractTask#rollback()
*/
@Override
protected void rollback() throws SetupException {
}
}
| [
"machozhao@bea0ad5c-f690-c3dd-0edd-70527fc306d2"
] | machozhao@bea0ad5c-f690-c3dd-0edd-70527fc306d2 |
bf632771d36013c8892abc47da4ec02440e1584f | 0eb1598c91e4f1762d47fd6ddfdbb73275810a0b | /src/br/com/siscca/entidade/Uf.java | 7d336b475119849d2d3cb20f4b4b74820267d246 | [] | no_license | thifernandes/siscca-jsf | e396e42aecf3614a7ea9f50d30c9df9369d35c13 | b0039f25130cd3255392a1f02ffb28b3faf71898 | refs/heads/master | 2020-03-29T19:28:04.777581 | 2018-09-25T12:55:50 | 2018-09-25T12:55:50 | 150,264,749 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,049 | java | package br.com.siscca.entidade;
import java.io.Serializable;
public class Uf implements Serializable {
/**
* Serial UID.
*/
private static final long serialVersionUID = 1L;
private String siglaUf;
private String nomeUf;
public Uf() {
}
public Uf(String siglaUf) {
this.siglaUf = siglaUf;
}
public String getSiglaUf() {
return siglaUf;
}
public void setSiglaUf(String siglaUf) {
this.siglaUf = siglaUf;
}
public String getNomeUf() {
return nomeUf;
}
public void setNomeUf(String nomeUf) {
this.nomeUf = nomeUf;
}
@Override
public String toString() {
return String.format("Uf[%s, %s]", siglaUf, nomeUf);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Uf))
return false;
Uf other = (Uf) obj;
if (siglaUf == null){
if (other.siglaUf != null)
return false;
} else if (!siglaUf.equals(other.siglaUf))
return false;
return true;
}
}
| [
"thifernandes@gmail.com"
] | thifernandes@gmail.com |
8396501f08d2849a1a992cd6add5e3c95279faec | 590f10f439fc7b8835c84434aea334be5f4496ef | /src/main/java/edu/uiowa/slis/ClinicalTrialsTagLib/locationCountries/LocationCountriesIterator.java | 93c7f6b474a2284a263df6db41171e1c2ea68554 | [] | no_license | data2health/ClinicalTrialsTagLib | 9202067a2627727f4570f12cb1875bc0e87f7d41 | cd209a50afbf2cc5dc82f5e5a360719ccf18eadf | refs/heads/master | 2021-12-08T06:50:14.620121 | 2021-01-11T22:59:09 | 2021-01-11T22:59:09 | 213,464,785 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,906 | java | package edu.uiowa.slis.ClinicalTrialsTagLib.locationCountries;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import edu.uiowa.slis.ClinicalTrialsTagLib.ClinicalTrialsTagLibTagSupport;
import edu.uiowa.slis.ClinicalTrialsTagLib.ClinicalTrialsTagLibBodyTagSupport;
import edu.uiowa.slis.ClinicalTrialsTagLib.clinicalStudy.ClinicalStudy;
@SuppressWarnings("serial")
public class LocationCountriesIterator extends ClinicalTrialsTagLibBodyTagSupport {
int ID = 0;
int seqnum = 0;
String country = null;
Vector<ClinicalTrialsTagLibTagSupport> parentEntities = new Vector<ClinicalTrialsTagLibTagSupport>();
private static final Log log = LogFactory.getLog(LocationCountriesIterator.class);
PreparedStatement stat = null;
ResultSet rs = null;
String sortCriteria = null;
int limitCriteria = 0;
String var = null;
int rsCount = 0;
public static String locationCountriesCountByClinicalStudy(String ID) throws JspTagException {
int count = 0;
LocationCountriesIterator theIterator = new LocationCountriesIterator();
try {
PreparedStatement stat = theIterator.getConnection().prepareStatement("SELECT count(*) from clinical_trials.location_countries where 1=1"
+ " and id = ?"
);
stat.setInt(1,Integer.parseInt(ID));
ResultSet crs = stat.executeQuery();
if (crs.next()) {
count = crs.getInt(1);
}
stat.close();
} catch (SQLException e) {
log.error("JDBC error generating LocationCountries iterator", e);
throw new JspTagException("Error: JDBC error generating LocationCountries iterator");
} finally {
theIterator.freeConnection();
}
return "" + count;
}
public static Boolean clinicalStudyHasLocationCountries(String ID) throws JspTagException {
return ! locationCountriesCountByClinicalStudy(ID).equals("0");
}
public static Boolean locationCountriesExists (String ID, String seqnum) throws JspTagException {
int count = 0;
LocationCountriesIterator theIterator = new LocationCountriesIterator();
try {
PreparedStatement stat = theIterator.getConnection().prepareStatement("SELECT count(*) from clinical_trials.location_countries where 1=1"
+ " and id = ?"
+ " and seqnum = ?"
);
stat.setInt(1,Integer.parseInt(ID));
stat.setInt(2,Integer.parseInt(seqnum));
ResultSet crs = stat.executeQuery();
if (crs.next()) {
count = crs.getInt(1);
}
stat.close();
} catch (SQLException e) {
log.error("JDBC error generating LocationCountries iterator", e);
throw new JspTagException("Error: JDBC error generating LocationCountries iterator");
} finally {
theIterator.freeConnection();
}
return count > 0;
}
public int doStartTag() throws JspException {
ClinicalStudy theClinicalStudy = (ClinicalStudy)findAncestorWithClass(this, ClinicalStudy.class);
if (theClinicalStudy!= null)
parentEntities.addElement(theClinicalStudy);
if (theClinicalStudy == null) {
} else {
ID = theClinicalStudy.getID();
}
try {
//run count query
int webapp_keySeq = 1;
stat = getConnection().prepareStatement("SELECT count(*) from " + generateFromClause() + " where 1=1"
+ generateJoinCriteria()
+ (ID == 0 ? "" : " and id = ?")
+ generateLimitCriteria());
if (ID != 0) stat.setInt(webapp_keySeq++, ID);
rs = stat.executeQuery();
if (rs.next()) {
pageContext.setAttribute(var+"Total", rs.getInt(1));
}
//run select id query
webapp_keySeq = 1;
stat = getConnection().prepareStatement("SELECT clinical_trials.location_countries.id, clinical_trials.location_countries.seqnum from " + generateFromClause() + " where 1=1"
+ generateJoinCriteria()
+ (ID == 0 ? "" : " and id = ?")
+ " order by " + generateSortCriteria() + generateLimitCriteria());
if (ID != 0) stat.setInt(webapp_keySeq++, ID);
rs = stat.executeQuery();
if (rs.next()) {
ID = rs.getInt(1);
seqnum = rs.getInt(2);
pageContext.setAttribute(var, ++rsCount);
return EVAL_BODY_INCLUDE;
}
} catch (SQLException e) {
log.error("JDBC error generating LocationCountries iterator: " + stat.toString(), e);
clearServiceState();
freeConnection();
throw new JspTagException("Error: JDBC error generating LocationCountries iterator: " + stat.toString());
}
return SKIP_BODY;
}
private String generateFromClause() {
StringBuffer theBuffer = new StringBuffer("clinical_trials.location_countries");
return theBuffer.toString();
}
private String generateJoinCriteria() {
StringBuffer theBuffer = new StringBuffer();
return theBuffer.toString();
}
private String generateSortCriteria() {
if (sortCriteria != null) {
return sortCriteria;
} else {
return "id,seqnum";
}
}
private String generateLimitCriteria() {
if (limitCriteria > 0) {
return " limit " + limitCriteria;
} else {
return "";
}
}
public int doAfterBody() throws JspTagException {
try {
if (rs.next()) {
ID = rs.getInt(1);
seqnum = rs.getInt(2);
pageContext.setAttribute(var, ++rsCount);
return EVAL_BODY_AGAIN;
}
} catch (SQLException e) {
log.error("JDBC error iterating across LocationCountries", e);
clearServiceState();
freeConnection();
throw new JspTagException("Error: JDBC error iterating across LocationCountries");
}
return SKIP_BODY;
}
public int doEndTag() throws JspTagException, JspException {
try {
rs.close();
stat.close();
} catch (SQLException e) {
log.error("JDBC error ending LocationCountries iterator",e);
throw new JspTagException("Error: JDBC error ending LocationCountries iterator");
} finally {
clearServiceState();
freeConnection();
}
return super.doEndTag();
}
private void clearServiceState() {
ID = 0;
seqnum = 0;
parentEntities = new Vector<ClinicalTrialsTagLibTagSupport>();
this.rs = null;
this.stat = null;
this.sortCriteria = null;
this.var = null;
this.rsCount = 0;
}
public String getSortCriteria() {
return sortCriteria;
}
public void setSortCriteria(String sortCriteria) {
this.sortCriteria = sortCriteria;
}
public int getLimitCriteria() {
return limitCriteria;
}
public void setLimitCriteria(int limitCriteria) {
this.limitCriteria = limitCriteria;
}
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
public int getID () {
return ID;
}
public void setID (int ID) {
this.ID = ID;
}
public int getActualID () {
return ID;
}
public int getSeqnum () {
return seqnum;
}
public void setSeqnum (int seqnum) {
this.seqnum = seqnum;
}
public int getActualSeqnum () {
return seqnum;
}
}
| [
"david-eichmann@uiowa.edu"
] | david-eichmann@uiowa.edu |
23a15f7b1c5c0b5feaee01da1a4f4cf69a7938f5 | ca11a4e47f91d70f0fb002fd7bfddd23c7eebf72 | /Switch/app/src/androidTest/java/com/example/sujankandeepan/aswitch/ExampleInstrumentedTest.java | fc97aa3b0cc467e8fc5c345dda086b7a32303f0b | [] | no_license | Sujan-Kandeepan/MaterialDesign | bc0228cc4310b4a92fbbbde247bf9a1cadf06de7 | 9e6cfe4a6cf0d68e9be81d2994ffd9c796075c0d | refs/heads/master | 2020-03-26T23:00:23.189295 | 2018-12-27T08:21:44 | 2018-12-27T08:21:44 | 145,502,907 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 752 | java | package com.example.sujankandeepan.aswitch;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.sujankandeepan.aswitch", appContext.getPackageName());
}
}
| [
"kandeeps@mcmaster.ca"
] | kandeeps@mcmaster.ca |
efaf933165ff3e22824d85546b8883e65f1ab4dc | 1ab3b85d0ec13970a3dbb1e5f6737b180a42eee8 | /ImageSelectorDemo/app/src/main/java/com/example/com/imageselectordemo/adapter/ImgSelectAdapter.java | 9a7f4f41f82573b8423f62a2cfa39aeeaf1870cd | [] | no_license | ChailynY/ImageSelectorDemo | 13ea6eb0c807d5e783fc68f6a7436386a795bdd2 | 607aca4b704772f6c605e754fd27555b002fe6a3 | refs/heads/master | 2021-06-07T02:46:13.343737 | 2016-10-13T09:43:59 | 2016-10-13T09:43:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,545 | java | package com.example.com.imageselectordemo.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.example.com.imageselectordemo.R;
import com.example.com.imageselectordemo.interfaces.OnImgItemClickListener;
import java.util.List;
/**
* Created by yuanqingying on 2016/10/11.
*/
public class ImgSelectAdapter extends BaseAdapter {
private Context context;
private List<String> mLists;
private ImgSelectViewHolder imgSelectViewHolder;
private OnImgItemClickListener listener;
public ImgSelectAdapter(Context context, List<String> mLists) {
this.context = context;
this.mLists = mLists;
}
@Override
public int getCount() {
return mLists.size() == 0 ? 0 : mLists.size();
}
@Override
public Object getItem(int position) {
return mLists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_img_selsect, parent, false);
imgSelectViewHolder = new ImgSelectViewHolder();
convertView.setTag(imgSelectViewHolder);
} else {
imgSelectViewHolder = (ImgSelectViewHolder) convertView.getTag();
}
imgSelectViewHolder.imageView = (ImageView) convertView.findViewById(R.id.imgviewselsect);
imgSelectViewHolder.ivPhotoDelete= (ImageView) convertView.findViewById(R.id.ivPhotoDelete);
Glide.with(context).load(mLists.get(position)).override(200,200).into(imgSelectViewHolder.imageView);
imgSelectViewHolder.ivPhotoDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(listener!=null){
listener.onCheckedClick(mLists.get(position));
}else{
Log.i("yqy","点击删除此时的listener为空---null----");
}
}
});
return convertView;
}
class ImgSelectViewHolder {
ImageView imageView,ivPhotoDelete;
}
public void setListener(OnImgItemClickListener listener) {
this.listener = listener;
}
}
| [
"yuanqingying@1905.tv"
] | yuanqingying@1905.tv |
53d35bdc81fc76b5c7b83eb799120bb85b578134 | 93047c7f1dbb2f67214c33e93766fe8e88b69e37 | /src/com/totalIP/action/TotalNodeOneDateManageAction.java | 84aaf48d6d1f30d966e9a7182ba48220562e6a9c | [] | no_license | sunny-guo/MyProject | 70cc7ec2695120578b87ddb22e8607a6fabb8e37 | 85c28fbe97655e6236eaa3d1ffda8943bc8a7434 | refs/heads/master | 2021-03-12T22:46:16.665607 | 2015-05-24T14:20:03 | 2015-05-24T14:20:03 | 34,899,212 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 351 | java | package com.totalIP.action;
import com.base.util.BaseAction;
public class TotalNodeOneDateManageAction extends BaseAction{
private String dateStr ;
public String execute() throws Exception {
return SUCCESS;
}
public String getDateStr() {
return dateStr;
}
public void setDateStr(String dateStr) {
this.dateStr = dateStr;
}
}
| [
"sunny.guo@yunzhihui.com"
] | sunny.guo@yunzhihui.com |
cbb2f55781bc0fefd16bd339bca58c9de75ec2dd | 9254e7279570ac8ef687c416a79bb472146e9b35 | /paistudio-20210202/src/main/java/com/aliyun/paistudio20210202/models/UpdateExperimentContentResponse.java | 5fb764dc29e0115724167dd6efdc8127571130f4 | [
"Apache-2.0"
] | permissive | lquterqtd/alibabacloud-java-sdk | 3eaa17276dd28004dae6f87e763e13eb90c30032 | 3e5dca8c36398469e10cdaaa34c314ae0bb640b4 | refs/heads/master | 2023-08-12T13:56:26.379027 | 2021-10-19T07:22:15 | 2021-10-19T07:22:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,139 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.paistudio20210202.models;
import com.aliyun.tea.*;
public class UpdateExperimentContentResponse extends TeaModel {
@NameInMap("headers")
@Validation(required = true)
public java.util.Map<String, String> headers;
@NameInMap("body")
@Validation(required = true)
public UpdateExperimentContentResponseBody body;
public static UpdateExperimentContentResponse build(java.util.Map<String, ?> map) throws Exception {
UpdateExperimentContentResponse self = new UpdateExperimentContentResponse();
return TeaModel.build(map, self);
}
public UpdateExperimentContentResponse setHeaders(java.util.Map<String, String> headers) {
this.headers = headers;
return this;
}
public java.util.Map<String, String> getHeaders() {
return this.headers;
}
public UpdateExperimentContentResponse setBody(UpdateExperimentContentResponseBody body) {
this.body = body;
return this;
}
public UpdateExperimentContentResponseBody getBody() {
return this.body;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
7af51f3ab6021bd273b81ae833315bb3555bcebe | 81ce6a9aa8cd7f7d5404b579eb2bfdfdd7121b03 | /src/java/br/com/fatecpg/quiz/Question.java | d1502c9452cea79b4837950b71afa10e3dd5a31f | [] | no_license | carlosatec/ProjetoPoo-Quiz | d437301a0cdcea95c3ede34ed6bc246697ceca7a | 8e7f7bcd539064d3ad600dd7bd90a5db130b8b8a | refs/heads/master | 2023-01-28T00:30:02.185442 | 2018-11-10T06:55:24 | 2018-11-10T06:55:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,008 | java | /*
* 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 br.com.fatecpg.quiz;
/**
*
* @author Carlos
*/
public class Question {
private String title;
private String answer;
private String alternatives[];
public Question(String title, String answer, String[] alternatives) {
this.title = title;
this.answer = answer;
this.alternatives = alternatives;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String[] getAlternatives() {
return alternatives;
}
public void setAlternatives(String[] alternatives) {
this.alternatives = alternatives;
}
}
| [
"cs.alberto.ti@gmail.com"
] | cs.alberto.ti@gmail.com |
f153328f47662c55728ad3f0676e3220778537f6 | b3f264fef082f61e223ab95b545eca6d3c22bde2 | /disc07/src/graph/Graph.java | 403656f44c2b1a52fa4cd32f8e907e4361aa6383 | [] | no_license | bhavgarg/cmsc132summer21 | b27592d108631d770d3cd69aa4bc36be065e56c4 | 24f84eec0131786e354da8b4ab98b5ea5f8a56a6 | refs/heads/main | 2023-07-09T00:12:20.169600 | 2021-08-04T04:16:00 | 2021-08-04T04:16:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,251 | java | package graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Graph {
/**
* This implements a Directed Graph using adjacency lists
* Values of the nodes will be the indices of the matrix.
*/
public int[][] adj;
public Graph(int[][] num) {
adj = num;
}
public void addEdge(int start, int e) {
adj[start][e] = 1;
adj[e][start] = 1;
}
public void addDirEdge(int start, int e) {
adj[start][e] = 1;
}
/**
* Execute Breadth-First Search starting at the given node of the graph
* When multiple out degrees exist, prioritize smaller numbers
* Return a string containing the data in the nodes concatenated together
* (no spaces)
*/
public String BFS(int g) {
//TODO
}
/**
* Execute Depth-First Search starting at the given node of the graph
* When multiple out degrees exist, prioritize larger numbers
* Return a string containing the data in the nodes concatenated together
* (no spaces)
*/
public String DFS(int g) {
//TODO
}
/**
* Given a node, simply return if a crcle exists in the reachable graph
*/
public boolean hasCycle(int g) {
//TODO
}
}
| [
"pranavkop@live.com"
] | pranavkop@live.com |
1ce2158ea6a63ca09be159a994592fcd1af807e1 | 37a6054c9d656bb4556e2db505c490921e6c2b25 | /src/main/java/com/vtkty/vtktyacc/service/repository/AddressRepository.java | cb5bebd046747893870231042c0048f345fa4326 | [] | no_license | adhikari-jagdish/vtktyacc | 7c848317a69363714577dfedcb479113907f7609 | c166872b6f6089e32107778f58eb9bf328bcd264 | refs/heads/master | 2022-02-22T18:06:34.215673 | 2019-09-23T18:53:16 | 2019-09-23T18:53:16 | 195,873,229 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 492 | java | package com.vtkty.vtktyacc.service.repository;
import com.vtkty.vtktyacc.service.model.Address;
import com.vtkty.vtktyacc.service.model.Invoice;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface AddressRepository extends MongoRepository<Address, String> {
Address findByAgencyCode(String agencyCode);
}
| [
"grango153@gmail.com"
] | grango153@gmail.com |
f69d8096e98037058bd489c22cd08dfad5e55cb9 | 197dc2625b1753f03b8bc470fb9ea26b2a514376 | /src/main/java/chapter/ch05/sec01/TryWithResourcesDemo.java | 26da00ddc80c3d0f57952a6c32fd768076b32abc | [] | no_license | kujin521/Java9 | a2de9921fed8c7dd962f40f4bca43ee0f32a1119 | cb6fe19e639eef6de3a449bd4758101382b42266 | refs/heads/master | 2023-01-11T20:42:05.129564 | 2020-11-12T11:45:14 | 2020-11-12T11:45:14 | 306,370,857 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,263 | java | package chapter.ch05.sec01;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
public class TryWithResourcesDemo {
public static void print(Scanner in, PrintWriter out) {
try (in; out) { // Effectively final variables
while (in.hasNext())
out.println(in.next().toLowerCase());
}
}
public static void main(String[] args) throws IOException {
List<String> lines = List.of("Mary had a little lamb. Its fleece was white as snow.".split(" "));
try (PrintWriter out = new PrintWriter("/tmp/output1.txt")) {
for (String line : lines) {
out.println(line.toLowerCase());
}
}
try (Scanner in = new Scanner(Paths.get("/usr/share/dict/words"));
PrintWriter out = new PrintWriter("/tmp/output2.txt")) {
while (in.hasNext())
out.println(in.next().toLowerCase());
}
PrintWriter out3 = new PrintWriter("/tmp/output3.txt");
try (out3) {
for (String line : lines) {
out3.println(line.toLowerCase());
}
}
}
} | [
"1604323361@qq.com"
] | 1604323361@qq.com |
ddf45b32ee6714c0482be716f7532ca72144eff5 | 4fe1012aaea39a7aa12d5610a5fe057c95ddeeb8 | /src/main/java/com/bittiger/querypool/bq13.java | 010fb2577f73a802ac0cdfe4ccb6d90417b6dafc | [] | no_license | junzhiwang/elasticDB | 31b423a5b8ddcc1e1c4d40974da24c2e330f303e | 8c72437fcd85f9ccfd3b176ce75665b92abd03f3 | refs/heads/master | 2021-01-12T05:46:32.367642 | 2017-06-10T23:17:08 | 2017-06-10T23:17:08 | 77,196,226 | 4 | 1 | null | null | null | null | UTF-8 | Java | false | false | 736 | java | package com.bittiger.querypool;
import java.util.StringTokenizer;
// sql.getCDiscount
public class bq13 implements QueryMetaData {
public String query = "select max(c_discount) from customer where "
+ "(c_uname not like '?')";
ParmGenerator pg = new ParmGenerator();
public String getQueryStr() {
String qString = "";
int count = 0;
StringTokenizer st = new StringTokenizer(query, "?", false);
while (st.hasMoreTokens()) {
qString += st.nextToken();
count++;
switch (count) {
case 1:
qString += pg.getCustomerUserName();
break;
case 2:
break;
default:
System.out.println("More token than expected");
System.exit(100);
}
}
return qString;
}
}
| [
"pxiong@apache.org"
] | pxiong@apache.org |
8919d2029c5a665b6ecc70f4756ce8497db9aaf1 | 582de29d3627ed687c3681580abac1fa6ab2e692 | /Luminet/LumiWorld/src/main/java/com/luminet/mobile/luminetandroid/activity/SetPasswordActivity.java | c710eeca1a7ec834da25446b717cef2c1ebdc33e | [] | no_license | christiankriz/LuminetAndroid | 670d941c4e7cc00d6e9b2c8b7c5ddae03f469d76 | 46420d5d04553a935343f5735add8079f7d175b1 | refs/heads/master | 2021-05-15T15:36:51.549680 | 2017-11-03T12:41:14 | 2017-11-03T12:41:14 | 107,402,971 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,900 | java | package com.luminet.mobile.luminetandroid.activity;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toolbar;
import com.luminet.mobile.luminetandroid.R;
import com.luminet.mobile.luminetandroid.api.MuleAPI;
import com.luminet.mobile.luminetandroid.login.Login;
import com.luminet.mobile.luminetandroid.login.RegisterUser;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.content.ContentValues.TAG;
import static com.luminet.mobile.luminetandroid.app.LuminetSplashScreen.MyPREFERENCES;
/**
* Created by chris on 2017/10/25.
*/
public class SetPasswordActivity extends Activity {
private final OkHttpClient client = new OkHttpClient();
Toolbar toolbar;
TextView screenName;
EditText newPassword, confirmPassword;
TextView changePasswordNumber;
Button next;
String userId, password, newPasswordText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
userId = intent.getStringExtra("userId");
password = intent.getStringExtra("pWord");
setContentView(R.layout.user_registration_password);
changePasswordNumber = findViewById(R.id.label_reg_num);
changePasswordNumber.setText(userId);
newPassword = findViewById(R.id.new_password_text_input);
newPassword = findViewById(R.id.new_password_text_input);
confirmPassword = findViewById(R.id.confirm_new_password_text_input);
next = findViewById(R.id.register_next_button);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updatePassword();
}
});
}
private void updatePassword(){
newPasswordText = newPassword.getText().toString();
if(newPassword.getText().equals("") || confirmPassword.getText().equals("")){
String message = "Please enter all the required fields";
String title = "Change Password Error";
displayMessage(message, title);
}else {
if (newPassword.getText().equals(confirmPassword.getText())) {
if (isValidPassword(newPassword.getText().toString())) {
uploadNewPassword();
}
} else {
String message = "New passwords not same";
String title = "Change Password Error";
displayMessage(message, title);
}
}
}
public void login(){
FormBody.Builder formBuilder = new FormBody.Builder()
.add("cell", userId)
.add("password", password);
RequestBody formBody = formBuilder.build();
Request request = new Request.Builder()
.url(MuleAPI.userLoginUrl)
.post(formBody)
.build();
Call call = client.newCall(request);
MuleAPI muleAPI = new MuleAPI();
muleAPI.getData(call, new MuleAPI.DataListener(){
@Override
public void onDataSucceeded(Call call, Response response){
String respondData = null;
try {
respondData = response.body().string();
if (response.isSuccessful()) {
if(respondData.equals("\"2\"") || respondData.equals("\"3\"")){
} else{
String message = "Your Mobile Number or Password is incorrect. Please try again.";
String title = "Error Login";
displayMessage(message, title);
}
}
//}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onDataFailed(Call call, IOException e){
String message = "We could not connect to Luminet World please check you internet connectivity and try again";
String title = "Error Registration";
displayMessage(message, title);
Log.v(TAG, "SMS Exception : ", e);
}
});
}
public static boolean isValidPassword(final String password) {
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
private void uploadNewPassword(){
String currentTime = (String) android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date());
String paramData = "{\"properties\":{\"gcmId\":\"\",\"appVersion\":\"0.5.28.125\",\"status\":2,\"updateDate\":\"" + currentTime + "\",\"password\":\"" + newPasswordText + "\"},\"nodeLabel\":\"Consumer\",\"nodeKey\":\"cell\",\"nodeKeyValue\":\"" + userId + "\"}\"";
FormBody.Builder formBuilder = new FormBody.Builder()
.add("params", paramData);
RequestBody formBody = formBuilder.build();
Request request = new Request.Builder()
.url(MuleAPI.setPasswordUrl)
.post(formBody)
.build();
Call call = client.newCall(request);
MuleAPI muleAPI = new MuleAPI();
muleAPI.getData(call, new MuleAPI.DataListener(){
@Override
public void onDataSucceeded(Call call, Response response){
String respondData = null;
try {
respondData = response.body().string();
if (response.isSuccessful()) {
Intent intent = new Intent(getBaseContext(), RegisterActivity.class);
intent.putExtra("userId", userId);
//intent.putExtra("pWord", codeNumberString);
startActivity(intent);
}
} catch (IOException e) {
e.printStackTrace();
}
Log.v(TAG, "Check Log " + respondData);
}
@Override
public void onDataFailed(Call call, IOException e){
String message = "We could not connect to Luminet World please check you internet connectivity and try again";
String title = "Register Error";
displayMessage(message, title);
Log.v(TAG, "Registration Exception : ", e);
}
});
}
private void displayMessage(final String message, final String title){
android.support.v7.app.AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new android.support.v7.app.AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new android.support.v7.app.AlertDialog.Builder(this);
}
builder.setTitle(title)
.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
| [
"christiankriz@gmailcom"
] | christiankriz@gmailcom |
cbe3e76670adc0807087d2adcc45298a70bf86ba | 6989ad4e424d68deb1c43cb07d04db7f2f9d909b | /src/Packages/Green_Flight.java | 2ced2f1619252a4e36c080b118343690a7bb1638 | [] | no_license | You-Yeon/SAVE-PRINCESS | 9323950dd80a901e5be071883b9e2ebae8897ea0 | c4f947463dd9d51e3feb9039d8794d4fba86aeb3 | refs/heads/master | 2022-04-01T15:48:49.287411 | 2019-11-20T17:43:18 | 2019-11-20T17:43:18 | 218,475,822 | 0 | 1 | null | null | null | null | UHC | Java | false | false | 303 | java | package Packages;
public class Green_Flight extends Flight{
boolean Big_MS; // 대형 미사일 여부
Green_Flight()
{
this.player_Hitpoint = 4; // 최초 유닛 체력
this.player_Speed = 5; // 플레이어 이동속도
this.missile_Speed = 7; // 미사일 움직임 속도
}
}
| [
"cyy0067@naver.com"
] | cyy0067@naver.com |
df139008c626d6d3354cdbd6a87d886d5006e14f | 950dd5bd833f92d5ca8b0adceda7f8c1336e52de | /yqlplus_engine/src/main/java/com/yahoo/yqlplus/engine/internal/bytecode/types/gambit/PopExpression.java | 977c41c8b0e38423083bb8924ba89544c4296334 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yahoo/yql-plus | 6ab6c5e17c71a9c946f407a3ee05552bd4362ded | 0ba7dcf8df58eae7cb6144599fa5120194eee5e9 | refs/heads/master | 2023-09-04T05:53:38.112255 | 2020-09-30T00:42:03 | 2020-09-30T00:42:03 | 76,505,423 | 43 | 17 | Apache-2.0 | 2023-03-21T04:34:40 | 2016-12-14T23:24:01 | Java | UTF-8 | Java | false | false | 719 | java | /*
* Copyright (c) 2016 Yahoo Inc.
* Licensed under the terms of the Apache version 2.0 license.
* See LICENSE file for terms.
*/
package com.yahoo.yqlplus.engine.internal.bytecode.types.gambit;
import com.yahoo.yqlplus.engine.internal.compiler.CodeEmitter;
import com.yahoo.yqlplus.engine.internal.plan.types.BytecodeExpression;
import com.yahoo.yqlplus.engine.internal.plan.types.BytecodeSequence;
public class PopExpression implements BytecodeSequence {
private final BytecodeExpression expr;
public PopExpression(BytecodeExpression expr) {
this.expr = expr;
}
@Override
public void generate(CodeEmitter code) {
code.exec(expr);
code.pop(expr.getType());
}
}
| [
"daisyzhu@yahoo-inc.com"
] | daisyzhu@yahoo-inc.com |
e57de183474062ebd31cd012a709a08e27fa7eb7 | 5a5906cfdc64c0f0b35aea97ad1e4da16a0c8dd1 | /src/hfj/chapter5/DotCom.java | 8f687cec3e2d75ad50e31788fc3aaaac9b84d1ab | [] | no_license | anannyadutta09/HeadFirstJava | 51d5276f5ba8426f7ad05e8c866fcab9656fd6ee | 69f502372e021963b00b2862ef7281798106e78c | refs/heads/master | 2023-07-05T04:06:39.581520 | 2021-08-17T18:05:26 | 2021-08-17T18:05:26 | 375,751,586 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 515 | java | package hfj.chapter5;
import java.util.ArrayList;
public class DotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> locs) {
locationCells = locs;
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
}
System.out.println(result);
return result;
}
}
| [
"anannyadutta09@gmail.com"
] | anannyadutta09@gmail.com |
ce70d27bc8e1f7e43983f1f36faf9330c6212826 | 5c6bbcc19377696f8ce85d36af9108a1c1cbe813 | /app/src/main/java/com/example/erpqpp/mvp/mode/TestAdd.java | d8c41bcb084cd9d1e1f1c1937929360d45993f4d | [] | no_license | Gui779/arpapp | bff75633590f16f12bba3e16c3f299a31f850bab | 36088b0f99e816614759a46e0d1f78939495b4d2 | refs/heads/master | 2023-03-03T22:35:28.505628 | 2019-09-20T09:46:38 | 2019-09-20T09:46:38 | 236,629,220 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 573 | java | package com.example.erpqpp.mvp.mode;
import java.io.Serializable;
public class TestAdd implements Serializable {
private String name;
private String count;
public TestAdd(String name, String count) {
this.name = name;
this.count = count;
}
public TestAdd() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
| [
"18600218366@qq.com"
] | 18600218366@qq.com |
9119e15979fdd30e0d2a180b4132a03b0082d191 | c866f71058bce8ec5ef0d93d23550287a5be4405 | /svc/app/models/services/asset/ListAssetsServiceOperation.java | f0806530cbc2028330333366d36d1eb08e93a8a5 | [] | no_license | craig-i-h/Team2 | 05b2fac7d41ba1b2f19cb2c2899d9dea28c9252f | f6316d762257946fe953d38ce3e5b5c9477e4e19 | refs/heads/master | 2016-08-11T15:12:01.087571 | 2016-01-22T10:42:46 | 2016-01-22T10:42:46 | 49,947,265 | 0 | 2 | null | 2016-01-22T10:42:47 | 2016-01-19T11:09:10 | JavaScript | UTF-8 | Java | false | false | 885 | java | package models.services.asset;
import com.fasterxml.jackson.databind.JsonNode;
import common.util.json.play.JSONHelper;
import models.persistence.dao.impl.AssetDao;
import models.persistence.entities.AssetEntity;
import models.services.ServiceOperation;
import play.Logger;
import javax.inject.Inject;
import java.util.List;
public class ListAssetsServiceOperation extends ServiceOperation
{
private static final Logger.ALogger logger = Logger.of(ListAssetsServiceOperation.class);
private AssetDao dao;
private JSONHelper jsonHelper;
@Inject
public ListAssetsServiceOperation(AssetDao dao, JSONHelper jsonHelper)
{
this.dao = dao;
this.jsonHelper = jsonHelper;
}
@Override protected JsonNode doExecute(JsonNode jsonRequest)
{
List<AssetEntity> assets = dao.list();
return jsonHelper.toJson(assets);
}
}
| [
"jordan.francis@atos.net"
] | jordan.francis@atos.net |
2432441af1a5f540823d9bf836fc6b2fb518889e | 83494ac0d112a5788034fc76a631c60bf0ec54da | /school/spring/cs111/Project6/King.java | cca10ae5befd524b9eec04e50583b7fc4154388e | [] | no_license | skstewart/2016 | 4ace23d803e3ea939ed040012b0617ba49a296d4 | 266030ba8e5207b058b53d63d1ac98319d7b35ed | refs/heads/master | 2020-03-07T11:58:34.928136 | 2018-03-30T20:48:44 | 2018-03-30T20:48:44 | 127,467,716 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,110 | java | /*
* 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.
*/
/**
*
* @author Shayna
*/
public class King extends Human implements BattleCry {
King(String name, String weapon, int xPosition, int yPosition, String crown) {
String crownColor = crown;
setName(name);
setWeapon(weapon);
setXPosition(xPosition);
setYPosition(yPosition);
}
@Override
public String battleCry() {
if (getName() == "Richard III"){
return "Loyaulte me.";
}
else {
return "Engarde!";
}
}
@Override
public void attack(Actor actor){
System.out.println("King " + getName() + " yells " + battleCry());
actor.setStatus(false);
}
@Override
public String toString() {
return "King " + getName() + " is at " + getXPosition() + " , " + getYPosition() + ".";
}
}
| [
"noreply@github.com"
] | noreply@github.com |
bbfdef7fb2524809c2f0a94730252356fbdca196 | d2e858432eba07120e92be5cd6ecb53d36610671 | /src/test/java/com/example/crudrepository/CrudrepositoryApplicationTests.java | 17bffbdaf9653efc4ffa12cb93f109363e259e00 | [] | no_license | dujuejue/crudrepository | b98a34cd4237ba60a753a298870401df51aad13b | d01c634571c1abacf758a11d8175c4ca8eabd37b | refs/heads/master | 2020-08-02T21:18:20.888233 | 2019-09-28T14:12:15 | 2019-09-28T14:12:15 | 209,317,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 360 | java | package com.example.crudrepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CrudrepositoryApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"dutingjue@163.com"
] | dutingjue@163.com |
ce01e4591c3e22ae372a95f3f4f2ef8b7346c80e | 5751ca219ec4e078635ba6dd02f30e268aa754a7 | /eclipse-workspace/Learnjava/src/com/selenium/BootstrapDropdown.java | d7297a320fa339a9c74228d67485e159d97724b5 | [] | no_license | muneendrag/javaprograms | e6def231873259b8bd5b932dd767f866262f01b7 | e9d897ed858cf9491abbef1641514b573aad908e | refs/heads/master | 2020-09-03T12:45:07.982361 | 2019-11-04T09:46:11 | 2019-11-04T09:46:11 | 219,465,329 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,251 | java | package com.selenium;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BootstrapDropdown {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\selenium softwares\\chromedriver.exe");
//how to launch the chrome browser
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.w3schools.com/bootstrap/bootstrap_dropdowns.asp");
driver.findElement(By.xpath("//button[contains(text(),'Dropdown Example')]")).click();
Thread.sleep(2000);
List<WebElement> list = driver.findElements(By.xpath("//div[@class='dropdown open']//ul[1][@class='dropdown-menu test']//li//a"));
System.out.println(list.size());
for(int i=0;i<list.size();i++) {
System.out.println(list.get(i).getText());
if(list.get(i).getText().equalsIgnoreCase("JavaScript")) {
list.get(i).click();
break;
}
}
}
}
| [
"munnareddy4637@gmail.com"
] | munnareddy4637@gmail.com |
21bfd916290310e54c631103c1ec354536437cc4 | d38c273ac67ea5c0c637e3287883bda918b851cc | /src/main/java/HelloProject.java | 02b43db16102f58e5e01623c8c7a97a89463e0b2 | [] | no_license | Sebastian-Noren/CloudBD-PA2577-SebastianNoren | 64556f054718ba2e7f73bae96ac43a9d5f576d4c | 2c8aa1158f46d288cdc5298870e125658d9038fc | refs/heads/master | 2023-07-22T11:29:39.980784 | 2021-09-02T11:46:44 | 2021-09-02T11:46:44 | 402,399,899 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 125 | java | public class HelloProject {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
| [
"sebastian@sportadmin.se"
] | sebastian@sportadmin.se |
d35469e50b56aa5c7b5100b0f2298ea6d67834d3 | 1268864286499ad88b3a0981a462c4386f157fce | /asianwallets-base/src/main/java/com/asianwallets/base/controller/MerchantCardCodeController.java | d9568c70ab152d936da6ff01d11c787146b5ceac | [] | no_license | happyjianguo/asianwalletsSaas | 3ecda62133382eff0492ed8f036d5f56a6e970ea | 217220735c4e47f19b372534c354371bc778f00f | refs/heads/master | 2022-11-13T06:06:41.034508 | 2020-07-06T03:50:08 | 2020-07-06T03:50:08 | 285,756,447 | 0 | 6 | null | 2020-08-07T06:34:54 | 2020-08-07T06:34:54 | null | UTF-8 | Java | false | false | 2,310 | java | package com.asianwallets.base.controller;
import com.asianwallets.base.service.MerchantCardCodeService;
import com.asianwallets.common.base.BaseController;
import com.asianwallets.common.dto.MerchantCardCodeDTO;
import com.asianwallets.common.response.BaseResponse;
import com.asianwallets.common.response.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/cardCode")
@Api(description = "码牌管理接口")
public class MerchantCardCodeController extends BaseController {
@Autowired
private MerchantCardCodeService merchantCardCodeService;
@ApiOperation(value = "分页查询商户码牌信息信息")
@PostMapping("/pageFindMerchantCardCode")
public BaseResponse pageFindMerchantCardCode(@RequestBody @ApiParam MerchantCardCodeDTO merchantCardCodeDTO) {
return ResultUtil.success(merchantCardCodeService.pageFindMerchantCardCode(merchantCardCodeDTO));
}
@ApiOperation(value = "查询商户码牌详情信息")
@PostMapping("/getMerchantCardCode")
public BaseResponse getMerchantCardCode(@RequestBody @ApiParam MerchantCardCodeDTO merchantCardCodeDTO) {
return ResultUtil.success(merchantCardCodeService.getMerchantCardCode(merchantCardCodeDTO));
}
@ApiOperation(value = "修改商户码牌信息")
@PostMapping("/updateMerchantCardCode")
public BaseResponse updateMerchantCardCode(@RequestBody @ApiParam MerchantCardCodeDTO merchantCardCodeDTO){
return ResultUtil.success(merchantCardCodeService.updateMerchantCardCode(this.getSysUserVO().getUsername(),merchantCardCodeDTO));
}
@ApiOperation(value = "查看商户静态码")
@PostMapping("/selectMerchantCardCode")
public BaseResponse selectMerchantCardCode(@RequestBody @ApiParam MerchantCardCodeDTO merchantCardCodeDTO) {
return ResultUtil.success(merchantCardCodeService.selectMerchantCardCode(merchantCardCodeDTO));
}
}
| [
"yangshanlong@asianwallets.com"
] | yangshanlong@asianwallets.com |
b2787d2b4c61cda83d3f24e1facf87db1e88d977 | cce10dfcb55a09defe9783c454fc6d943c7012fd | /rWorldGUI/src/org/whitehack97/rWorldGUI/api/GlowEffect.java | 37842eac77d5e4294df0e55c6362e22c21181fb1 | [] | no_license | ReanKR/rWorldGUI | 91d35667c599ee7379bf12a901617b5645d9e778 | 81e86f36fd0b392e9ccc45bbabbefe61a65d673a | refs/heads/master | 2016-08-12T14:09:10.381198 | 2016-03-20T17:44:10 | 2016-03-20T17:44:10 | 52,778,736 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,367 | java | package org.whitehack97.rWorldGUI.api;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
import net.minecraft.server.v1_8_R3.NBTTagList;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
/**
* Class, that allows adding glow effect to item.
*/
public class GlowEffect
{
/**
* Adds the glow.
*
* @param item
* the item
* @return the item stack
*/
public static ItemStack addGlow(ItemStack item)
{
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound tag = null;
if (!nmsStack.hasTag()) {
tag = new NBTTagCompound();
nmsStack.setTag(tag);
}
if (tag == null) tag = nmsStack.getTag();
NBTTagList ench = new NBTTagList();
tag.set("ench", ench);
nmsStack.setTag(tag);
return CraftItemStack.asCraftMirror(nmsStack);
}
/**
* Removes the glow.
*
* @param item
* the item
* @return the item stack
*/
public static ItemStack removeGlow(ItemStack item)
{
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound tag = null;
if (!nmsStack.hasTag()) return item;
tag = nmsStack.getTag();
tag.set("ench", null);
nmsStack.setTag(tag);
return CraftItemStack.asCraftMirror(nmsStack);
}
} | [
"whitehack97@gmail.com"
] | whitehack97@gmail.com |
461a5459ae02ea6a22256edf455c74f07804b0ef | c324a4d5de91a6249a3628fca19338b9eae29038 | /AADSDKOWN_change_download12121/src/com/ymzz/plat/alibs/zwu/MyLogcat.java | 73a8915e8a252037aa3537a98c940152da29fdb1 | [] | no_license | ChenHe0411/AdvertSDK | a4d0eeaa4c6a1ac613c89cebe6766f0f768bc779 | b132d17e219ec79698ac6e79044ffd017d97328f | refs/heads/master | 2021-01-10T18:17:39.882501 | 2015-10-13T08:09:57 | 2015-10-13T08:09:57 | 44,159,458 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 352 | java | package com.ymzz.plat.alibs.zwu;
import android.util.Log;
/**
* 日志�?
* @author zouwei
*
*/
public class MyLogcat {
// static boolean islog = true; //发布时改为false 屏蔽log打印�?
static boolean islog = false; //发布时改为false 屏蔽log打印�?
static public void log(String s){
if(islog){
Log.d("dth", s);
}
}
}
| [
"chenhe@3gu.com"
] | chenhe@3gu.com |
8e82486fe3f56f7f189bdb370b60b2a2c5ed5df7 | d375e009eee63374ae568b6240bae9a538f9bc6a | /src/main/java/org/hl7/fhir/instance/model/Contact.java | 6dcd79eca5a7c1e8c31220a1e5fb2e9c9608b47d | [] | no_license | hubertvijay/swift | 44078fbdcb6fb1365257889712d92e9398553b93 | a4aac7b9dc8a9192a5b4f9294ad71b1d0141f10b | refs/heads/master | 2021-01-18T14:05:47.924166 | 2015-03-08T19:25:13 | 2015-03-08T19:25:13 | 31,833,553 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,009 | java | package org.hl7.fhir.instance.model;
/*
Copyright (c) 2011-2013, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Tue, Sep 30, 2014 18:08+1000 for FHIR v0.0.82
import java.util.*;
/**
* All kinds of technology mediated contact details for a person or organization, including telephone, email, etc.
*/
public class Contact extends Type {
public enum ContactSystem {
phone, // The value is a telephone number used for voice calls. Use of full international numbers starting with + is recommended to enable automatic dialing support but not required.
fax, // The value is a fax machine. Use of full international numbers starting with + is recommended to enable automatic dialing support but not required.
email, // The value is an email address.
url, // The value is a url. This is intended for various personal contacts including blogs, Twitter, Facebook, etc. Do not use for email addresses.
Null; // added to help the parsers
public static ContactSystem fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
return null;
if ("phone".equals(codeString))
return phone;
if ("fax".equals(codeString))
return fax;
if ("email".equals(codeString))
return email;
if ("url".equals(codeString))
return url;
throw new Exception("Unknown ContactSystem code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case phone: return "phone";
case fax: return "fax";
case email: return "email";
case url: return "url";
default: return "?";
}
}
}
public static class ContactSystemEnumFactory implements EnumFactory {
public Enum<?> fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("phone".equals(codeString))
return ContactSystem.phone;
if ("fax".equals(codeString))
return ContactSystem.fax;
if ("email".equals(codeString))
return ContactSystem.email;
if ("url".equals(codeString))
return ContactSystem.url;
throw new Exception("Unknown ContactSystem code '"+codeString+"'");
}
public String toCode(Enum<?> code) throws Exception {
if (code == ContactSystem.phone)
return "phone";
if (code == ContactSystem.fax)
return "fax";
if (code == ContactSystem.email)
return "email";
if (code == ContactSystem.url)
return "url";
return "?";
}
}
public enum ContactUse {
home, // A communication contact at a home; attempted contacts for business purposes might intrude privacy and chances are one will contact family or other household members instead of the person one wishes to call. Typically used with urgent cases, or if no other contacts are available.
work, // An office contact. First choice for business related contacts during business hours.
temp, // A temporary contact. The period can provide more detailed information.
old, // This contact is no longer in use (or was never correct, but retained for records).
mobile, // A telecommunication device that moves and stays with its owner. May have characteristics of all other use codes, suitable for urgent matters, not the first choice for routine business.
Null; // added to help the parsers
public static ContactUse fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return home;
if ("work".equals(codeString))
return work;
if ("temp".equals(codeString))
return temp;
if ("old".equals(codeString))
return old;
if ("mobile".equals(codeString))
return mobile;
throw new Exception("Unknown ContactUse code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case home: return "home";
case work: return "work";
case temp: return "temp";
case old: return "old";
case mobile: return "mobile";
default: return "?";
}
}
}
public static class ContactUseEnumFactory implements EnumFactory {
public Enum<?> fromCode(String codeString) throws Exception {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return ContactUse.home;
if ("work".equals(codeString))
return ContactUse.work;
if ("temp".equals(codeString))
return ContactUse.temp;
if ("old".equals(codeString))
return ContactUse.old;
if ("mobile".equals(codeString))
return ContactUse.mobile;
throw new Exception("Unknown ContactUse code '"+codeString+"'");
}
public String toCode(Enum<?> code) throws Exception {
if (code == ContactUse.home)
return "home";
if (code == ContactUse.work)
return "work";
if (code == ContactUse.temp)
return "temp";
if (code == ContactUse.old)
return "old";
if (code == ContactUse.mobile)
return "mobile";
return "?";
}
}
/**
* Telecommunications form for contact - what communications system is required to make use of the contact.
*/
protected Enumeration<ContactSystem> system;
/**
* The actual contact details, in a form that is meaningful to the designated communication system (i.e. phone number or email address).
*/
protected StringType value;
/**
* Identifies the purpose for the address.
*/
protected Enumeration<ContactUse> use;
/**
* Time period when the contact was/is in use.
*/
protected Period period;
private static final long serialVersionUID = 1117502294L;
public Contact() {
super();
}
/**
* @return {@link #system} (Telecommunications form for contact - what communications system is required to make use of the contact.)
*/
public Enumeration<ContactSystem> getSystem() {
return this.system;
}
/**
* @param value {@link #system} (Telecommunications form for contact - what communications system is required to make use of the contact.)
*/
public Contact setSystem(Enumeration<ContactSystem> value) {
this.system = value;
return this;
}
/**
* @return Telecommunications form for contact - what communications system is required to make use of the contact.
*/
public ContactSystem getSystemSimple() {
return this.system == null ? null : this.system.getValue();
}
/**
* @param value Telecommunications form for contact - what communications system is required to make use of the contact.
*/
public Contact setSystemSimple(ContactSystem value) {
if (value == null)
this.system = null;
else {
if (this.system == null)
this.system = new Enumeration<ContactSystem>();
this.system.setValue(value);
}
return this;
}
/**
* @return {@link #value} (The actual contact details, in a form that is meaningful to the designated communication system (i.e. phone number or email address).)
*/
public StringType getValue() {
return this.value;
}
/**
* @param value {@link #value} (The actual contact details, in a form that is meaningful to the designated communication system (i.e. phone number or email address).)
*/
public Contact setValue(StringType value) {
this.value = value;
return this;
}
/**
* @return The actual contact details, in a form that is meaningful to the designated communication system (i.e. phone number or email address).
*/
public String getValueSimple() {
return this.value == null ? null : this.value.getValue();
}
/**
* @param value The actual contact details, in a form that is meaningful to the designated communication system (i.e. phone number or email address).
*/
public Contact setValueSimple(String value) {
if (value == null)
this.value = null;
else {
if (this.value == null)
this.value = new StringType();
this.value.setValue(value);
}
return this;
}
/**
* @return {@link #use} (Identifies the purpose for the address.)
*/
public Enumeration<ContactUse> getUse() {
return this.use;
}
/**
* @param value {@link #use} (Identifies the purpose for the address.)
*/
public Contact setUse(Enumeration<ContactUse> value) {
this.use = value;
return this;
}
/**
* @return Identifies the purpose for the address.
*/
public ContactUse getUseSimple() {
return this.use == null ? null : this.use.getValue();
}
/**
* @param value Identifies the purpose for the address.
*/
public Contact setUseSimple(ContactUse value) {
if (value == null)
this.use = null;
else {
if (this.use == null)
this.use = new Enumeration<ContactUse>();
this.use.setValue(value);
}
return this;
}
/**
* @return {@link #period} (Time period when the contact was/is in use.)
*/
public Period getPeriod() {
return this.period;
}
/**
* @param value {@link #period} (Time period when the contact was/is in use.)
*/
public Contact setPeriod(Period value) {
this.period = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("system", "code", "Telecommunications form for contact - what communications system is required to make use of the contact.", 0, Integer.MAX_VALUE, system));
childrenList.add(new Property("value", "string", "The actual contact details, in a form that is meaningful to the designated communication system (i.e. phone number or email address).", 0, Integer.MAX_VALUE, value));
childrenList.add(new Property("use", "code", "Identifies the purpose for the address.", 0, Integer.MAX_VALUE, use));
childrenList.add(new Property("period", "Period", "Time period when the contact was/is in use.", 0, Integer.MAX_VALUE, period));
}
public Contact copy() {
Contact dst = new Contact();
dst.system = system == null ? null : system.copy();
dst.value = value == null ? null : value.copy();
dst.use = use == null ? null : use.copy();
dst.period = period == null ? null : period.copy();
return dst;
}
protected Contact typedCopy() {
return copy();
}
}
| [
"vsowrira@asu.edu"
] | vsowrira@asu.edu |
f2f37e91eea635dcb3300d5e3695b46f48978c6b | 9036fc6db1f1074023ba69a7f689de90ac9094f6 | /src/com/leiqjl/FindAllAnagramsInAString.java | 1f7e335a72ec8a8cffb7dfaec063b5dea0fdc23c | [] | no_license | leiqjl/leetcode | 646e6fc0a7bba120934996203536b6decb62a5a8 | 1d1faf4c283e694143b9886685a6430521d1860e | refs/heads/master | 2023-09-01T06:45:45.353434 | 2023-08-29T09:27:26 | 2023-08-29T09:27:26 | 136,191,772 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,465 | java | package com.leiqjl;
import java.util.ArrayList;
import java.util.List;
/**
* 438. Find All Anagrams in a String - Medium
* <p>
* Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
* <p>
* An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
*/
public class FindAllAnagramsInAString {
//1 <= s.length, p.length <= 3 * 10^4
//s and p consist of lowercase English letters.
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
if (s.length() < p.length()) {
return result;
}
int len1 = p.length();
int len2 = s.length();
int[] cnt = new int[26];
for (int i = 0; i < len1; i++) {
cnt[p.charAt(i) - 'a']++;
cnt[s.charAt(i) - 'a']--;
}
if (check(cnt)) {
result.add(0);
}
for (int i = len1; i < len2; i++) {
cnt[s.charAt(i) - 'a']--;
cnt[s.charAt(i - len1) - 'a']++;
if (check(cnt)) {
result.add(i - len1 + 1);
}
}
return result;
}
private boolean check(int[] cnt) {
for (int c : cnt) {
if (c != 0) {
return false;
}
}
return true;
}
}
| [
"leiqjl@gmail.com"
] | leiqjl@gmail.com |
0cb9058d0a358378e216648875f481ca6be43e79 | 8b49344c2b6cb156966cdf2564ad5d9622c6a196 | /src/main/java/com/william/film/mapper/FilmPersonMapper.java | c491b1c488aa83ced904c5b761c9250e77760791 | [] | no_license | tanbinh123/film-1 | b9f0ebf167e31c1f4a5b706ad521d8df81f92692 | f26084f7f7ba5806597984dc8121b4ab436c45bb | refs/heads/master | 2022-11-14T12:48:29.781210 | 2019-11-13T01:43:06 | 2019-11-13T01:43:06 | 471,768,409 | 1 | 0 | null | 2022-03-19T17:38:29 | 2022-03-19T17:38:28 | null | UTF-8 | Java | false | false | 909 | java | package com.william.film.mapper;
import com.william.film.pojo.FilmPerson;
import com.william.film.pojo.FilmPersonExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface FilmPersonMapper {
long countByExample(FilmPersonExample example);
int deleteByExample(FilmPersonExample example);
int deleteByPrimaryKey(Integer personId);
int insert(FilmPerson record);
int insertSelective(FilmPerson record);
List<FilmPerson> selectByExample(FilmPersonExample example);
FilmPerson selectByPrimaryKey(Integer personId);
int updateByExampleSelective(@Param("record") FilmPerson record, @Param("example") FilmPersonExample example);
int updateByExample(@Param("record") FilmPerson record, @Param("example") FilmPersonExample example);
int updateByPrimaryKeySelective(FilmPerson record);
int updateByPrimaryKey(FilmPerson record);
} | [
"41105739+923340695@users.noreply.github.com"
] | 41105739+923340695@users.noreply.github.com |
eee45584de0660b2fac0058f5553ec631c068476 | 929b37e05bf1aa2b5b88b07a820ba56a7e00701f | /bonaparte-adapters-money-bd/src/main/java/de/jpaw/bonaparte/adapters/moneybd/BonaCurrencyAdapter.java | 98941037d42ca13474b9a6799d665cf33a46701a | [
"Apache-2.0"
] | permissive | jpaw/bonaparte-java | f882984cb78059d20cce7c602ede2a7b6977fc51 | 8f0fc09d07a9b394ecbd0dade69829ec219caf9b | refs/heads/master | 2023-04-28T23:45:52.309194 | 2022-06-03T17:32:01 | 2022-06-03T17:32:01 | 5,228,646 | 2 | 4 | Apache-2.0 | 2023-04-14T20:42:22 | 2012-07-30T05:23:07 | Java | UTF-8 | Java | false | false | 1,238 | java | package de.jpaw.bonaparte.adapters.moneybd;
import de.jpaw.bonaparte.core.BonaPortable;
import de.jpaw.bonaparte.core.ExceptionConverter;
import de.jpaw.bonaparte.pojos.adapters.moneybd.BCurrency;
import de.jpaw.money.BonaCurrency;
import de.jpaw.money.MonetaryException;
public class BonaCurrencyAdapter {
/** Convert the custom type into a serializable BonaPortable. */
public static BCurrency marshal(BonaCurrency currency) {
return new BCurrency(currency.getCurrencyCode(), currency.getDecimals());
}
/** Convert a parsed adapter type into the custom type. */
public static <E extends Exception> BonaCurrency unmarshal(BonaPortable obj, ExceptionConverter<E> p) throws E {
if (obj instanceof BCurrency) {
BCurrency currency = (BCurrency)obj;
try {
return new BonaCurrency(
currency.getCurrencyCode(),
currency.getDecimals()
);
} catch (MonetaryException e) {
throw p.customExceptionConverter("Cannot convert " + obj + " to BonaCurrency", e);
}
} else {
throw new IllegalArgumentException("Incorrect type returned");
}
}
}
| [
"jpaw@online.de"
] | jpaw@online.de |
86a606fa9a7d520f88e85d1453df5e1f936491e6 | 94d90a261681aa28e1844ace1bc44f76701ed868 | /src/com/covid/baseDatosConexion/ConexionBD.java | 96f893a5353adcfb293eeac99ed9d2d0ee15923e | [] | no_license | alcatuto/alcatutoPracticum | 16c1e8f72e99f0d0227cfbcd2cab2cebcd6f55ac | 374b506fcdff8cc8c716a29bdc0580f19fec4fb5 | refs/heads/master | 2023-03-08T21:15:05.510021 | 2021-02-04T04:20:20 | 2021-02-04T04:20:20 | 335,828,743 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 872 | java | package com.covid.baseDatosConexion;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
public class ConexionBD {
private static BasicDataSource dataSource = null;
private static DataSource getDataSource() {
if (dataSource == null) {
dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("ana");
dataSource.setPassword("anita2020");
dataSource.setUrl("jdbc:mysql://localhost:3306/covidbasedatos?serverTimezone=UTC");
dataSource.setInitialSize(20);
dataSource.setMaxIdle(15);
dataSource.setMaxTotal(20);
dataSource.setMaxWaitMillis(50000);
}
return dataSource;
}
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
} | [
"anitacatuto@gmail.com"
] | anitacatuto@gmail.com |
e99e1c48fe448c5aaab5baa9d63d7b85641161d9 | 5599fd77abf57b4885e8106659659107992ad553 | /src/com/mr_replete/particles/lib/expressions/Dick.java | 9055ddcdc0e2a7242409baba73111cc1afd16615 | [] | no_license | Colasuonno/MoreParticles | b96d19286d632c7ddad7cb0ecfd7951a1560e2b9 | 07193e2077a5d3b279e104016c3978a70d367a5b | refs/heads/master | 2020-03-14T08:20:22.890118 | 2018-04-29T19:22:44 | 2018-04-29T19:22:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,379 | java | package com.mr_replete.particles.lib.expressions;
import com.mr_replete.particles.lib.EffectDisplay;
import com.mr_replete.particles.lib.ParticleEffect;
import com.mr_replete.particles.lib.ParticleType;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class Dick extends Expression {
public Dick() {
super("dick");
}
@Override
public void draw(Player sender, ParticleEffect effect) {
final Location secondBall = effect.getLocation().clone().add(4.0D,0.0D,0.0D);
Circle circle = new Circle(2,360);
Circle circle2 = new Circle(2,360);
circle.draw(sender,effect);
circle2.draw(sender, new ParticleEffect(secondBall, ParticleType.DRAGON_BREATH,0.0f,0.0f,0.0f,0,10));
for (double x = 1.5; x < 3; x+=0.5){
for (double z = 3; z < 11; z++){
new EffectDisplay().draw(sender,ParticleType.DRAGON_BREATH,0.0f,0.0f,0.0f,0,100,new Location(effect.getLocation().getWorld(),effect.getLocation().getX()+x,effect.getLocation().getY(),effect.getLocation().getZ()+z));
}
}
for (double x = 1.5; x < 3; x+=0.5){
new EffectDisplay().draw(sender,ParticleType.CLOUD,1.0f,1.0f,1.0f,1,20,new Location(effect.getLocation().getWorld(),effect.getLocation().getX()+x,effect.getLocation().getY(),effect.getLocation().getZ()+10));
}
}
}
| [
"colasuonno.scuola@gmail.com"
] | colasuonno.scuola@gmail.com |
d49a13a6665d3ffa6a1d434b126b450e0a22898e | 08b36b6872bc9d114ed2ab9f76782f6e734e1f83 | /index/WikiSearch/src/DirectoryVisitor.java | b8bb206f63e4b93e3dccf0d8a3db1db6ea7a837c | [] | no_license | karanjude/projectmoo | 40069f9206ea926cfbb37d147fbd91db4023077e | 17bf1c7b6e1c7a20dcaf2bf9fd8ffe2476939d6e | refs/heads/master | 2016-09-06T04:15:21.716854 | 2012-04-21T13:54:05 | 2012-04-21T13:54:05 | 2,740,614 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 845 | java | import java.io.File;
import java.io.IOException;
public class DirectoryVisitor {
private File wikipaediaDirectory;
public DirectoryVisitor(String wikipaediaDirectory) {
this.wikipaediaDirectory = new File(wikipaediaDirectory);
}
public void visit(HtmlFileCollector htmlFileCollector) {
visit(this.wikipaediaDirectory, htmlFileCollector);
}
private void visit(File toVisit, HtmlFileCollector htmlFileCollector) {
if (toVisit.isDirectory()) {
String[] filenames = toVisit.list();
for (String entity : filenames) {
File child = new File(toVisit.getAbsolutePath()
+ File.separatorChar + entity);
if (child.isDirectory()) {
visit(child, htmlFileCollector);
} else {
try {
htmlFileCollector.collect(child);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
| [
"karan.jude@gmail.com"
] | karan.jude@gmail.com |
799165af25acff69f06769637676f9b905a1f2f0 | e5c98f14a29d4b00c2cace4a4fca083daf8085ff | /src/main/java/data/converter/MusicConverter.java | 65300e01ba530fc3be0a2f01df91bb625b6697f8 | [] | no_license | Le-Fond-de-l-Etang/mediaservice | aedc235a6d3fbc972bb65ffdb038b64d9adcfbc6 | a91ae03eedbca1a04c4f26048a59c8c3c34b55a7 | refs/heads/master | 2021-08-27T23:43:54.041738 | 2017-12-10T20:26:41 | 2017-12-10T20:26:41 | 108,819,159 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,398 | java | package data.converter;
import data.beans.MusicEntity;
import io.spring.guides.gs_producing_web_service.Music;
public class MusicConverter {
/**
* Convert a music entity to a SOAP music bean
* @param musicEntity Entity to convert
* @return SOAP ready object
*/
public static Music convertEntityToSoap(MusicEntity musicEntity) {
Music music = new Music();
music.setId(musicEntity.getId());
music.setIsmn(musicEntity.getIsmn());
music.setTitle(musicEntity.getTitle());
music.setAuthor(musicEntity.getAuthor());
music.setAlbum(musicEntity.getAlbum());
music.setBorrowed(musicEntity.isBorrowed());
music.setBorrower(musicEntity.getBorrower());
return music;
}
/**
* Convert a SOAP music bean to a entity used for persistence
* @param musicSoap Soap object to convert
* @return Entity to persist
*/
public static MusicEntity convertSoapToEntity(Music musicSoap) {
MusicEntity music = new MusicEntity();
music.setId(musicSoap.getId());
music.setIsmn(musicSoap.getIsmn());
music.setTitle(musicSoap.getTitle());
music.setAuthor(musicSoap.getAuthor());
music.setAlbum(musicSoap.getAlbum());
music.setBorrowed(musicSoap.isBorrowed());
music.setBorrower(musicSoap.getBorrower());
return music;
}
}
| [
"zessirb@gmail.com"
] | zessirb@gmail.com |
64d5f9d7ba5dfd7a2e6f3ba0994d198827150429 | 1a07fa87ddbd138ab44567d1247ac3aee2339caa | /src/main/java/com/shimizukenta/httpserver/HttpResponseStatusLine.java | 18dfa90813f0844fd7aadf37e8ad2e403a6a6be5 | [
"Apache-2.0"
] | permissive | kenta-shimizu/httpserver4java8 | fcbf23c443b054e685940769d56a730be6cec1de | 9415f4e3e0166bf7c27fc6552eeb40375daecb95 | refs/heads/main | 2023-03-22T17:33:18.349756 | 2021-03-14T15:59:24 | 2021-03-14T15:59:24 | 338,604,219 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,620 | java | package com.shimizukenta.httpserver;
import java.util.Objects;
public class HttpResponseStatusLine {
private static final String SP = " ";
private final HttpVersion version;
private final String versionStr;
private HttpResponseCode statusCode;
private final String statusCodeStr;
private final String reasonPhrase;
private String cacheLine;
public HttpResponseStatusLine(CharSequence version, CharSequence code, CharSequence reasonPhrase) {
this.version = HttpVersion.from(version);
this.versionStr = Objects.requireNonNull(version).toString();
this.statusCode = null;
this.statusCodeStr = Objects.requireNonNull(code).toString();
this.reasonPhrase = Objects.requireNonNull(reasonPhrase).toString();
this.cacheLine = null;
}
public HttpResponseStatusLine(HttpVersion version, HttpResponseCode responseCode) {
this.version = version;
this.versionStr = version.toString();
this.statusCode = responseCode;
this.statusCodeStr = responseCode.codeString();
this.reasonPhrase = responseCode.defaultReasonPhrase();
this.cacheLine = null;
}
public HttpVersion version() {
return this.version;
}
public HttpResponseCode statusCode() {
synchronized ( this ) {
if ( this.statusCode == null ) {
this.statusCode = HttpResponseCode.from(statusCodeStr);
}
return this.statusCode;
}
}
public String toLine() {
synchronized ( this ) {
if ( this.cacheLine == null ) {
this.cacheLine = versionStr + SP
+ statusCodeStr + SP
+ reasonPhrase;
}
return this.cacheLine;
}
}
@Override
public String toString() {
return toLine();
}
}
| [
"shimizukentagm1@gmail.com"
] | shimizukentagm1@gmail.com |
05d59ab5d8e38c4723487b2545aafdb8946f84b0 | d16f17f3b9d0aa12c240d01902a41adba20fad12 | /src/help_requests/trading_stats/Listing.java | 0b8023d2dbb5a0a7b4d6dcc6a98022a832e4b9c6 | [] | no_license | redsun9/leetcode | 79f9293b88723d2fd123d9e10977b685d19b2505 | 67d6c16a1b4098277af458849d352b47410518ee | refs/heads/master | 2023-06-23T19:37:42.719681 | 2023-06-09T21:11:39 | 2023-06-09T21:11:39 | 242,967,296 | 38 | 3 | null | null | null | null | UTF-8 | Java | false | false | 89 | java | package help_requests.trading_stats;
public record Listing(String name, int amount) {
}
| [
"mokeev.vladimir@gmail.com"
] | mokeev.vladimir@gmail.com |
daf350ffe129c2dd72160336ea60bc2fb120f986 | 07cc7387f3c2b31ec2a30da0c6038528c877b014 | /property-service/src/main/java/fr/urbanmarkets/propertyservice/model/Price.java | a87e953bfb251542b3eb483b4fe52d4e4666ad58 | [
"Apache-2.0"
] | permissive | dmrlvnt/jp-property-manager | bef8bc8b0ebc54b0c6b52a331842c45eddb483d0 | 49e7b9115a5a7a4160f71754564606ac30421237 | refs/heads/master | 2020-03-09T19:06:04.583442 | 2018-04-17T22:56:37 | 2018-04-17T22:56:37 | 128,949,318 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,158 | java | package fr.urbanmarkets.propertyservice.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "price")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Price {
@Id
@Column(name = "priceId", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long priceId;
@Column(name = "date", nullable = false)
@JsonFormat(pattern = "dd.MM.yyyy")
private LocalDate date;
@Column(name = "amount", nullable = false)
private Long amount;
}
| [
"dmrlvnt@gmail.com"
] | dmrlvnt@gmail.com |
c80c1b89eb795d02ad27e47bd80591b850de6e64 | eceb87c3cf6601e4cce8e38ed268dfbefb8497fc | /src/main/java/com/thebrodyaga/vkobjects/users/responses/SearchResponse.java | c95563c31e9f8fdb592dba5b87fda3e93d25abe6 | [] | no_license | thebrodyaga/VkResponseObjects | 2cc5cdcaa44c129a2766792f6f5f552a60305d05 | c280bb01dd29994cdce39bb696c3dab3d320fa5b | refs/heads/master | 2021-01-24T04:21:01.174072 | 2018-09-23T21:47:52 | 2018-09-23T21:47:52 | 122,935,697 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,170 | java | package com.thebrodyaga.vkobjects.users.responses;
import com.thebrodyaga.vkobjects.users.UserFull;
import java.util.List;
import java.util.Objects;
/**
* SearchResponse object
*/
public class SearchResponse {
/**
* Total number of available results
*/
private Integer count;
private List<UserFull> items;
public Integer getCount() {
return count;
}
public List<UserFull> getItems() {
return items;
}
@Override
public int hashCode() {
return Objects.hash(count, items);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SearchResponse searchResponse = (SearchResponse) o;
return Objects.equals(count, searchResponse.count) &&
Objects.equals(items, searchResponse.items);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("SearchResponse{");
sb.append("count=").append(count);
sb.append(", items=").append(items);
sb.append('}');
return sb.toString();
}
}
| [
"Emelyanov.n4@wildberries.ru"
] | Emelyanov.n4@wildberries.ru |
1d82d37f4ccdfe6c587413ba1a0f1c633a5897c1 | d16f3af05a2a0cabad608c44c1265d0c07eb7358 | /app/src/androidTest/java/com/example/mahendran/teacherspet/ExampleInstrumentedTest.java | e6c1677083118dc6001a4ffc62c79c7b889a31a0 | [] | no_license | mahen92/Teacher-Pet | 24835f8494c8a5bc84a6accd750dfa4a398982e9 | 778911f14fdf0883f68228c5cd2176beccd3c529 | refs/heads/master | 2021-01-01T04:58:55.964284 | 2017-07-15T14:28:28 | 2017-07-15T14:28:28 | 97,282,463 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package com.example.mahendran.teacherspet;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.mahendran.teacherspet", appContext.getPackageName());
}
}
| [
"mahenicecold@gmail.com"
] | mahenicecold@gmail.com |
2a7252ec86ffd6d1f872c15aa508f8e15ea90060 | cf63dce44d373052d54e3362d8984f12fa61a569 | /engine/src/main/java/game/engine/drawable/KBitmap.java | cba6001a3c97a82737bcd938d80b2d43d869a4fe | [] | no_license | zhangkari/tetris-app | a4cc448d029148d96d966672a57539cda5351be9 | f0c1487cf9c413755aab89160fa9d1544a773250 | refs/heads/master | 2022-04-20T20:25:17.220653 | 2019-04-30T09:08:18 | 2019-04-30T09:08:18 | 174,291,278 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 971 | java | package game.engine.drawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
public class KBitmap extends KDrawable {
private Bitmap mBitmap;
private Rect mDestRect;
public KBitmap(Bitmap bitmap) {
this(bitmap, bitmap.getWidth(), bitmap.getHeight());
}
public KBitmap(Bitmap bitmap, int width, int height) {
super(width, height);
mBitmap = bitmap;
mDestRect = new Rect(padding, padding, width - padding, height - padding);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawBitmap(
mBitmap,
null,
mDestRect,
paint);
}
@Override
public void onDestroy() {
if (mBitmap != null) {
if (!mBitmap.isRecycled()) {
mBitmap.recycle();
}
mBitmap = null;
}
}
}
| [
"472128467@qq.com"
] | 472128467@qq.com |
78ee4d9ad25644ccbd99c6c2c5a23e38b7830bcd | d1e8c43f38854645275aea66624073f8b4e69d0a | /StackThreads/src/usc/sabarre/stackthreads/Push.java | 2ad677df76e10f902163a92b13ec5e1ddb0a2290 | [] | no_license | hjsab91/CS178_Act02_Sab_HJ | 9ca08e7a3b79e4d35438314993092fa386315ad4 | f5c26a44cafb922a959d5d7171c206d2ec58ca35 | refs/heads/master | 2020-04-28T06:25:44.898099 | 2013-01-13T13:15:25 | 2013-01-13T13:15:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 398 | java | package usc.sabarre.stackthreads;
public class Push extends Thread implements Runnable {
private long ID;
private Stack stack;
Push(long ID, Stack stack)
{
this.ID = ID;
this.stack=stack;
}
@Override
public void run()
{
for(int i = 0; i<=9; i++)
{
stack.push(i);
System.out.println("Pushed " + i
+ ". Currently: " + (stack.getLast()+1));
}
}
}
| [
"hjsab91"
] | hjsab91 |
b19d1f920beac6c83420c4a6b584cd73e4ee2aea | 69313f739b91a84f58e68a6447f3fbff226e8dfc | /CC150/callservice/Manager.java | 15f8d03f4f0423a332146c6e1d54bc60092113bd | [] | no_license | jessexu20/Leetcode | e9ff4d81b903642320eee9aa0bf714c8a738454d | 7a1844ebd1a7d1555af8fcded07cd6a9e550ee39 | refs/heads/master | 2020-04-06T15:50:45.394462 | 2016-10-09T20:04:02 | 2016-10-09T20:04:02 | 24,825,431 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 149 | java | package callservice;
public class Manager extends Employee{
public Manager() {
// TODO Auto-generated constructor stub
rank=Rank.MANAGER;
}
}
| [
"jesse.xu.20@gmail.com"
] | jesse.xu.20@gmail.com |
a0d2310dbc705998fb8ea02e64de734dca566fbf | c17158f27ef600f61ddedc06e05f40ea70cd6476 | /ch4/Project.java | 58f7fab843c8a19ccd5aaf1841d0781e79b41dc2 | [] | no_license | LvYe-Go/CCAssignment | 6a658b3a616aefc1c382cc23ccfa51e33dfb6331 | aaa556a6a9b1f84178e57330aa61fe5c8143f3ab | refs/heads/master | 2020-12-01T01:18:44.356697 | 2015-10-02T15:46:16 | 2015-10-02T15:46:16 | 42,418,924 | 0 | 0 | null | 2015-09-14T00:53:40 | 2015-09-14T00:53:40 | null | UTF-8 | Java | false | false | 737 | java | package ch4;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Project {
public enum State {COMPLETE, PARTIAL, BLANK}; // record the state of visited node
private List<Project> children = new ArrayList<Project>();
private HashMap<String, Project> map = new HashMap<String, Project>();
private String name;
private State state = State.BLANK;
public Project(String n) {name = n;}
public String getName() {return name;}
public State getState() { return state;}
public void setState(State st) {state = st;}
public List<Project> getChildren() {return children;}
public void addNeighbor(Project node) {
if (!map.containsKey(node.getName()))
children.add(node);
}
}
| [
"yujinglove1992@gmail.com"
] | yujinglove1992@gmail.com |
108f2375640240ab11a0b70842e6f4de428da543 | 413a806b5cf470fc650848c58b3696679f293426 | /src/org/jsoup/select/TestNotClassQueryParser.java | 4d4af405a2bdc0c763244af9cadb32d5df143164 | [] | no_license | JS-Team6/JsoupProject | fbd13a85cc88f8e534e513249b96c90771baaf18 | 036396e2696d1204f02171ae2b82d4560ef5bb7b | refs/heads/master | 2020-09-03T08:55:47.126475 | 2019-12-09T03:14:10 | 2019-12-09T03:14:10 | 219,430,961 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,996 | java | package org.jsoup.select;
import org.jsoup.internal.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.parser.TokenQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.jsoup.internal.Normalizer.normalize;
/**
* Parses a CSS selector into an Evaluator tree.
*/
public class TestNotClassQueryParser extends AbstractQueryParser{
/**
* Create a new QueryParser.
* @param query CSS query
*/
public TestNotClassQueryParser() {
}
/**
* Parse a CSS query into an Evaluator.
* @param query CSS query
* @return Evaluator
*/
public Evaluator parse(String query) {
this.query = query;
this.tq = new TokenQueue(query);
try {
return parse();
} catch (IllegalArgumentException e) {
throw new Selector.SelectorParseException(e.getMessage());
}
}
/**
* Parse the query
* @return Evaluator
*/
public Evaluator parse() {
tq.consumeWhitespace();
if (tq.matchesAny(combinators)) { // if starts with a combinator, use root as elements
evals.add(new StructuralEvaluator.Root());
combinator(tq.consume());
} else {
findElements();
}
while (!tq.isEmpty()) {
// hierarchy and extras
boolean seenWhite = tq.consumeWhitespace();
if (tq.matchesAny(combinators)) {
combinator(tq.consume());
} else if (seenWhite) {
combinator(' ');
} else { // E.class, E#id, E[attr] etc. AND
findElements(); // take next el, #. etc off queue
}
}
if (evals.size() == 1)
return evals.get(0);
return new CombiningEvaluator.And(evals);
}
protected void findElements() {
if (tq.matchChomp("#"))
byId();
else if (tq.matchesWord() || tq.matches("*|"))
byTag();
else if (tq.matches("["))
byAttribute();
else if (tq.matchChomp("*"))
allElements();
else if (tq.matchChomp(":lt("))
indexLessThan();
else if (tq.matchChomp(":gt("))
indexGreaterThan();
else if (tq.matchChomp(":eq("))
indexEquals();
else if (tq.matches(":has("))
has();
else if (tq.matches(":contains("))
contains(false);
else if (tq.matches(":containsOwn("))
contains(true);
else if (tq.matches(":containsData("))
containsData();
else if (tq.matches(":matches("))
matches(false);
else if (tq.matches(":matchesOwn("))
matches(true);
else if (tq.matches(":not("))
not();
else if (tq.matchChomp(":matchText"))
evals.add(new Evaluator.MatchText());
else // unhandled
throw new Selector.SelectorParseException("Could not parse query '%s': unexpected token at '%s'", query, tq.remainder());
}
private void byId() {
String id = tq.consumeCssIdentifier();
Validate.notEmpty(id);
evals.add(new Evaluator.Id(id));
}
private void byTag() {
String tagName = tq.consumeElementSelector();
Validate.notEmpty(tagName);
// namespaces: wildcard match equals(tagName) or ending in ":"+tagName
if (tagName.startsWith("*|")) {
evals.add(new CombiningEvaluator.Or(new Evaluator.Tag(normalize(tagName)), new Evaluator.TagEndsWith(normalize(tagName.replace("*|", ":")))));
} else {
// namespaces: if element name is "abc:def", selector must be "abc|def", so flip:
if (tagName.contains("|"))
tagName = tagName.replace("|", ":");
evals.add(new Evaluator.Tag(tagName.trim()));
}
}
private void byAttribute() {
TokenQueue cq = new TokenQueue(tq.chompBalanced('[', ']')); // content queue
String key = cq.consumeToAny(AttributeEvals); // eq, not, start, end, contain, match, (no val)
Validate.notEmpty(key);
cq.consumeWhitespace();
if (cq.isEmpty()) {
if (key.startsWith("^"))
evals.add(new Evaluator.AttributeStarting(key.substring(1)));
else
evals.add(new Evaluator.Attribute(key));
} else {
if (cq.matchChomp("="))
evals.add(new Evaluator.AttributeWithValue(key, cq.remainder()));
else if (cq.matchChomp("!="))
evals.add(new Evaluator.AttributeWithValueNot(key, cq.remainder()));
else if (cq.matchChomp("^="))
evals.add(new Evaluator.AttributeWithValueStarting(key, cq.remainder()));
else if (cq.matchChomp("$="))
evals.add(new Evaluator.AttributeWithValueEnding(key, cq.remainder()));
else if (cq.matchChomp("*="))
evals.add(new Evaluator.AttributeWithValueContaining(key, cq.remainder()));
else if (cq.matchChomp("~="))
evals.add(new Evaluator.AttributeWithValueMatching(key, Pattern.compile(cq.remainder())));
else
throw new Selector.SelectorParseException("Could not parse attribute query '%s': unexpected token at '%s'", query, cq.remainder());
}
}
private void allElements() {
evals.add(new Evaluator.AllElements());
}
// pseudo selectors :lt, :gt, :eq
private void indexLessThan() {
evals.add(new Evaluator.IndexLessThan(consumeIndex()));
}
private void indexGreaterThan() {
evals.add(new Evaluator.IndexGreaterThan(consumeIndex()));
}
private void indexEquals() {
evals.add(new Evaluator.IndexEquals(consumeIndex()));
}
private int consumeIndex() {
String indexS = tq.chompTo(")").trim();
Validate.isTrue(StringUtil.isNumeric(indexS), "Index must be numeric");
return Integer.parseInt(indexS);
}
// pseudo selector :has(el)
private void has() {
tq.consume(":has");
String subQuery = tq.chompBalanced('(', ')');
Validate.notEmpty(subQuery, ":has(el) subselect must not be empty");
evals.add(new StructuralEvaluator.Has(parse(subQuery)));
}
// pseudo selector :contains(text), containsOwn(text)
private void contains(boolean own) {
tq.consume(own ? ":containsOwn" : ":contains");
String searchText = TokenQueue.unescape(tq.chompBalanced('(', ')'));
Validate.notEmpty(searchText, ":contains(text) query must not be empty");
if (own)
evals.add(new Evaluator.ContainsOwnText(searchText));
else
evals.add(new Evaluator.ContainsText(searchText));
}
// pseudo selector :containsData(data)
private void containsData() {
tq.consume(":containsData");
String searchText = TokenQueue.unescape(tq.chompBalanced('(', ')'));
Validate.notEmpty(searchText, ":containsData(text) query must not be empty");
evals.add(new Evaluator.ContainsData(searchText));
}
// :matches(regex), matchesOwn(regex)
private void matches(boolean own) {
tq.consume(own ? ":matchesOwn" : ":matches");
String regex = tq.chompBalanced('(', ')'); // don't unescape, as regex bits will be escaped
Validate.notEmpty(regex, ":matches(regex) query must not be empty");
if (own)
evals.add(new Evaluator.MatchesOwn(Pattern.compile(regex)));
else
evals.add(new Evaluator.Matches(Pattern.compile(regex)));
}
// :not(selector)
private void not() {
tq.consume(":not");
String subQuery = tq.chompBalanced('(', ')');
Validate.notEmpty(subQuery, ":not(selector) subselect must not be empty");
evals.add(new StructuralEvaluator.Not(parse(subQuery)));
}
}
| [
"chaeefe@gmail.com"
] | chaeefe@gmail.com |
c082344ed79704780c0de02d8dc35b30a36a929d | 3a8aac0198e1abe460896b465596c95a2e5bb621 | /app/src/main/java/com/example/samsung/gistnotes/api/GitHubClient.java | 5efc5a65a9c0ceed1b5cbcb5031480fdda93e682 | [] | no_license | btow/GistNotes | 6dfe5d3cb3234f31781efd0a9969fa2b6f347c15 | 9b1116b76f5b31d2a1e8c8c5b8d363eabf7a4fb1 | refs/heads/master | 2020-12-24T20:09:46.163281 | 2017-03-28T10:22:09 | 2017-03-28T10:22:09 | 86,237,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,817 | java | package com.example.samsung.gistnotes.api;
import com.example.samsung.gistnotes.model.GithubPublic;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by btow on 25.03.2017.
*/
public class GitHubClient {
private static final String BASE_URL = "https://api.github.com/" ;
private static Retrofit retrofitClient = null;
private static OkHttpClient okHttpClient;
public static Retrofit getRetrofitClientWithOkHttpClient() {
okHttpClient = new Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Accept", "Applocation/JSON")
.build();
return chain.proceed(request);
}
}).build();
if (retrofitClient == null) {
retrofitClient = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitClient;
}
public static Retrofit getRetrofitClient() {
if (retrofitClient == null) {
retrofitClient = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitClient;
}
}
| [
"btow@yandex.ru"
] | btow@yandex.ru |
92ea5eaef18c59187b61743fdd73ac28ed55930f | 77b8a2233e4cea6d7d08d88e281254b2cfafebc7 | /TooManyCharactersException.java | db2255b95fcfcd9d97f29c2675284bbf0cee166a | [] | no_license | tcoffey1/hangman | 423f42c880523a903d32b9a2e2104dfe2d71b86f | e6b36ff3b317ab00bca900dd0b583620aff21b5d | refs/heads/master | 2021-01-25T06:40:00.144507 | 2014-06-04T01:13:07 | 2014-06-04T01:13:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 244 | java | /* Tadhg Coffey
* Raymond Naval
* Project #4: Hangman
* December 17, 2013
*/
package hangman;
public class TooManyCharactersException extends Exception{
public TooManyCharactersException(){
super("Too many characters inputted.");
}
} | [
"tcoffey1@mail.ccsf.edu"
] | tcoffey1@mail.ccsf.edu |
326fc13bc0f1e0f864851041ee5386003c5b0ea6 | 5e2644e2c04bfdd8781b5f36a908d8fc497bb84f | /src/com/android/settings/LiveDemoUnit.java | aed44195af31212a0293fa79f9ee7b9464e5b192 | [
"Apache-2.0"
] | permissive | biantao712/Settings | 2f61bfb4ce21f29e308afc2d0e6b138b4c8f6fa6 | eba1e20cdc131ff4678ba246451fb20796337468 | refs/heads/master | 2021-07-05T13:23:15.596634 | 2017-09-26T03:30:01 | 2017-09-26T03:30:01 | 105,894,988 | 1 | 0 | null | 2017-10-05T13:44:14 | 2017-10-05T13:44:14 | null | UTF-8 | Java | false | false | 1,274 | java | /*
* Arica_Chen 20130812
* LiveDemo
*/
package com.android.settings;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.util.Log;
public class LiveDemoUnit {
public static int AccFlagRead()
{
String strPath = "/ADF/ADF";
File file = new File(strPath);
if (!file.exists()){
strPath = "/dev/block/ADF";
file = new File(strPath);
if (!file.exists()){
strPath = "/dev/block/demoflag";
file = new File(strPath);
if (!file.exists()){
return 0;
}
}
}
int flag = 0;
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(strPath, "r");
if(randomAccessFile.length() >= 4){
flag = randomAccessFile.readInt();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(randomAccessFile != null){
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(flag>2)
flag = 0;
return flag;
}
}
| [
"dylan_wang@asus.com"
] | dylan_wang@asus.com |
a9b8f00015772ff0f8f86a41a15acd9d4f14cc09 | b23c9cdcbf22dd3e10cf391c2b0c449a9d065098 | /src/test/java/com/niit/test/UserTest.java | a5ac6168b400b7567bba46d6ee96f2aa1a9bc520 | [] | no_license | manikantareddy111/collaboration | 78b279f3881fa419e634d09189a7cfac55c43814 | 251240485b71ee8304380e76664b51ecc48da25a | refs/heads/master | 2021-05-10T13:53:41.666150 | 2018-01-22T18:16:28 | 2018-01-22T18:16:28 | 118,494,567 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,475 | java | /*package com.niit.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import com.niit.DAO.UserDAO;
import com.niit.config.DbConfig;
import com.niit.model.User;
@ComponentScan("collbackend")
@Ignore
public class UserTest {
static UserDAO userDAO;
@BeforeClass
public static void initialize()
{
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
context.register(DbConfig.class);
context.scan("collbackend");
context.refresh();
userDAO=(UserDAO)context.getBean("userDAO");
}
@Ignore
@Test
public void addUserTest()
{
User user=new User();
user.setUserId(1003);
user.setFirstName("santhosh");
user.setLastName("m");
user.setEmailId("santhoshreddy182@gmail.com");
user.setPassword("12345");
user.setRole("user");
user.setStatus("N");
user.setIsOnlime("Y");
assertTrue("Problem in Inserting User",userDAO.addUser(user));
}
@Ignore
@Test
public void updateUser()
{
User user=new User();
user.setUserId(1003);
user.setFirstName("santhu");
user.setLastName("m");
user.setEmailId("santhu@gmail.com");
user.setPassword("12345");
user.setRole("user");
user.setStatus("Y");
user.setIsOnlime("Y");
assertTrue("Problem in Inserting User",userDAO.updateUser(user));
}
@Ignore
@Test
public void getUserTest(){
User user=(User)userDAO.getUser(3);
System.out.println("FirstName:" + user.getFirstName());
System.out.println("Role:" +user.getRole());
assertNotNull("user not found", user);
}
@Ignore
@Test
public void deleteUserTest(){
User user=(User)userDAO.getUser(3);
assertTrue("Problem in deletion",userDAO.deleteUser(user));
}
@Ignore
@Test
public void approveUserTest(){
User user=(User)userDAO.getUser(1003);
assertTrue("Problem in approving",userDAO.approveUser(user));
}
@Ignore
@Test
public void getAllUserTest(){
List<User> userList=(List<User>)userDAO.getAllusers();
assertNotNull("User list not found ",userList.get(0));
for(User user:userList)
{
System.out.println("UserID:"+user.getUserId() + "FirstName:"+user.getFirstName());
}
}
}*/ | [
"Manikanta@DESKTOP-QF37HN5"
] | Manikanta@DESKTOP-QF37HN5 |
28bcd4e36ba77bc657b966af18b34c1f8b5ed806 | 6dbae30c806f661bcdcbc5f5f6a366ad702b1eea | /Corpus/eclipse.pde.ui/2013.java | 3f38eda7f377392c30a68a59cac728c93cd8faf7 | [
"MIT"
] | permissive | SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018 | d3fd21745dfddb2979e8ac262588cfdfe471899f | 0f8f4affd0ce1ecaa8ff8f487426f8edd6ad02c0 | refs/heads/master | 2020-03-31T15:52:01.005505 | 2018-10-01T23:38:50 | 2018-10-01T23:38:50 | 152,354,327 | 1 | 0 | MIT | 2018-10-10T02:57:02 | 2018-10-10T02:57:02 | null | UTF-8 | Java | false | false | 641 | java | /*******************************************************************************
* Copyright (c) 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package a.methods.modifiers;
/**
*
*/
public class AddNoOverride {
public void method() {
}
}
| [
"masudcseku@gmail.com"
] | masudcseku@gmail.com |
eb8a596361de2fbd7c86d69cc76f03a938aa5fed | 243a31a30a60dbf7521e2e0d780177b5851d3b71 | /spring-boot-modules/spring-boot-content-negotiation/src/main/java/com/tom/web/DemoController.java | fb0ff9a66108e433cc5397cc8f7a3623b482a421 | [] | no_license | tomlxq/tutorials | db6c5524d0324631c4b5d9338ed9e20b9efa87f7 | 3bd7739e89b6d5dff3e4518c0b8fe98425600809 | refs/heads/master | 2020-12-19T07:13:42.578910 | 2020-07-19T16:23:10 | 2020-07-19T16:23:10 | 235,655,480 | 0 | 0 | null | 2020-06-13T02:00:22 | 2020-01-22T20:00:48 | Java | UTF-8 | Java | false | false | 1,925 | java | package com.tom.web;
import com.tom.model.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
/**
* 功能描述
*
* @author TomLuo
* @date 2020/3/29
*/
@Controller
public class DemoController {
final static Map<Long, Employee> employeeMap = new HashMap<>();
static {
employeeMap.put(10L, new Employee(10L, "Test Employee", "999-999-9999", "rh"));
}
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee/{Id}", produces = {"application/json", "application/xml"}, method = RequestMethod.GET)
public @ResponseBody
Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
}
| [
"21429503@qq.com"
] | 21429503@qq.com |
07687d998651e632f8006a8974e97e957eb49974 | de6bdcf32e523e3fd69cf32e2889f4150653eb22 | /src/main/java/regexmatcher/domain/Edge.java | 286298b1296173587c1fcbd3b190c259ad097519 | [] | no_license | Jeeses313/RegexMatcher | 1afab136e755f3c7124c5c7fbe483495342eb2ac | 11f284a550f437536c2cc1d4f489c7bb50391434 | refs/heads/master | 2021-03-18T05:22:11.083017 | 2020-05-06T22:01:40 | 2020-05-06T22:01:40 | 247,049,283 | 0 | 0 | null | 2020-10-13T20:50:57 | 2020-03-13T10:50:50 | HTML | UTF-8 | Java | false | false | 859 | java | package regexmatcher.domain;
/**
* Luokka, joka toimii verkon kaarena.
*/
public class Edge {
private int goalNode;
private char character;
/**
* Luokan konstruktori, joka saa parametreina maalisolmun viitteen ja kaaren
* kirjaimen.
*
* @param goalNode int, joka viittaa maalisolmuun.
* @param character char, joka on kaaren kirjain.
*/
public Edge(int goalNode, char character) {
this.goalNode = goalNode;
this.character = character;
}
/**
* Palauttaa kaaren kirjaimen.
*
* @return char, joka on kaaren kirjain.
*/
public char getCaharacter() {
return character;
}
/**
* Palauttaa kaaren maalisolmun viitteen.
*
* @return int, joka viittaa maalisolmuun.
*/
public int getGoalNode() {
return goalNode;
}
}
| [
"jesse.vilkman@hotmail.fi"
] | jesse.vilkman@hotmail.fi |
636e8a1229c1eb3f1e8dcc3322cb0feba68bcbeb | 5b4bf1d11c4dec43dae7f7bdc628d0ce6e22adc9 | /xchange-examples/src/main/java/com/xeiam/xchange/examples/cavirtex/marketdata/DepthDemo.java | fae4bba0b851e63e0c77b158c835e45faac4781a | [
"MIT"
] | permissive | moneta-dev/XChange | fa4b703c5c9259665d58b2b9218e75674de208c4 | 04c52774fa308d7b283fe52f36ff1d35b2403add | refs/heads/develop | 2020-12-25T05:37:47.565999 | 2014-03-23T22:10:52 | 2014-03-23T22:10:52 | 30,105,937 | 0 | 1 | null | 2015-01-31T07:33:37 | 2015-01-31T07:33:37 | null | UTF-8 | Java | false | false | 3,363 | java | /**
* Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.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.xeiam.xchange.examples.cavirtex.marketdata;
import java.io.IOException;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeFactory;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.service.polling.PollingMarketDataService;
import com.xeiam.xchange.virtex.VirtExExchange;
import com.xeiam.xchange.virtex.dto.marketdata.VirtExDepth;
import com.xeiam.xchange.virtex.service.polling.VirtExMarketDataServiceRaw;
/**
* Demonstrate requesting Order Book at VirtEx
*/
public class DepthDemo {
public static void main(String[] args) throws IOException {
// Use the factory to get the VirtEx exchange API using default settings
Exchange cavirtex = ExchangeFactory.INSTANCE.createExchange(VirtExExchange.class.getName());
// Interested in the public polling market data feed (no authentication)
PollingMarketDataService marketDataService = cavirtex.getPollingMarketDataService();
generic(marketDataService);
raw((VirtExMarketDataServiceRaw) marketDataService);
}
private static void generic(PollingMarketDataService marketDataService) throws IOException {
// Get the latest order book data for BTC/CAD
OrderBook orderBook = marketDataService.getOrderBook(CurrencyPair.BTC_CAD);
System.out.println("Current Order Book size for BTC / CAD: " + (orderBook.getAsks().size() + orderBook.getBids().size()));
System.out.println("First Ask: " + orderBook.getAsks().get(0).toString());
System.out.println("First Bid: " + orderBook.getBids().get(0).toString());
System.out.println(orderBook.toString());
}
private static void raw(VirtExMarketDataServiceRaw marketDataService) throws IOException {
// Get the latest order book data for BTC/CAD
VirtExDepth orderBook = marketDataService.getVirtExOrderBook("CAD");
System.out.println("Current Order Book size for BTC / CAD: " + (orderBook.getAsks().size() + orderBook.getBids().size()));
System.out.println("Last Ask: " + orderBook.getAsks().get(0)[0].toString());
System.out.println("Last Bid: " + orderBook.getBids().get(0)[0].toString());
System.out.println(orderBook.toString());
}
}
| [
"tim.molter@gmail.com"
] | tim.molter@gmail.com |
85ec291ae0fedbba1227c55d12d9e184d258f1a9 | 5797319aac59e8b45b3411293e30493fa49ad32f | /MultiThread/src/ch10/problem/q5/Main.java | 35a12848d67f8444f33d30e23104125c3f780af1 | [] | no_license | jyking99/multithreadSamples | 8688099874cbb21725ed8fcc2ff541f9fb80e1ba | f159249614272ae5872df559a7fef4cb604f09ec | refs/heads/master | 2023-06-28T03:02:12.633727 | 2021-07-30T23:34:35 | 2021-07-30T23:34:35 | 297,204,918 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 122 | java | package ch10.problem.q5;
public class Main {
public static void main(String[] args) {
new MyFrame();
}
}
| [
"wangcgv@bc.edu"
] | wangcgv@bc.edu |
86e87ad99be8f66c2a8454761b99941e6a9ecc60 | 91de9309dd4a06163396aaab82f5b2cdab518769 | /java/src/common/TCDBOutofSync/TestCaseMatcher.java | fcd3bcc8fc63c77b80fdc89eac08bf9837992d41 | [] | no_license | canito487/CIT360-Personal-Portfolio | 3bde0e1732d22a7688154a809530eefa0ae233ae | a9d6b948ba4e49c3c0b013d2008428c86b19f360 | refs/heads/master | 2021-01-20T18:36:02.174273 | 2016-07-19T06:05:21 | 2016-07-19T06:05:21 | 60,808,319 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,166 | java | package common.TCDBOutofSync;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by alex.hernandez on 7/16/16.
*/
public class TestCaseMatcher {
/**
* Walks the File Structure and returns a filtered list of test cases containing @TestCaseId Annotation
*
* @param startingPath
* @return
* @throws IOException
*/
public List<String> walkFileTree(Path startingPath) throws IOException {
List<String> filteredTestCases = new ArrayList<>();
FileWalker walker = new FileWalker();
// Grab all Test Class files that end with .java
Files.walkFileTree(startingPath, walker);
// Run through each file and check if it contains TCDBD Definition and stores them in a List
for (Path filePath : walker.getJavaList()) {
File file = filePath.toFile();
List<String> filteredText = containsTCDBDefinition(file);
for (String line : filteredText) {
filteredTestCases.add(line);
}
}
return filteredTestCases;
}
/**
* Runs through every java class file and returns a list of filteredText with @TestCaseId annotation
*
* @param fileAbsolutePath
* @return
*/
public static List<String> containsTCDBDefinition(File fileAbsolutePath) throws IOException {
String line;
List<String> fileText = new ArrayList<>();
List<String> filteredText = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileAbsolutePath));
while ((line = bufferedReader.readLine()) != null) {
fileText.add(line);
}
// Stream each line and if it matches @TestCaseId add it to list
fileText.stream()
.filter(line1 -> line1.contains("@TestCaseId"))
.forEach(line1 -> filteredText.add(line1));
return filteredText;
}
/**
* Runs through a List of Filtered Test Cases and Extracts TC Id and Version
*
* @param filteredTestCases
* @return
*/
public HashMap<String, String> getMatchedTestCases(List<String> filteredTestCases) {
HashMap<String, String> testCases = new HashMap<>();
for (String testCase : filteredTestCases) {
String re1 = ".*?";
String re2 = "\\d+";
String re3 = ".*?";
String re4 = "(\\d+)";
String line = testCase;
Pattern p = Pattern.compile("[0-9]{5}");
Pattern p2 = Pattern.compile(re1 + re2 + re3 + re4, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = p.matcher(line);
Matcher matcher1 = p2.matcher(line);
while (matcher.find() && matcher1.find()) {
testCases.put(matcher.group(), matcher1.group(1));
}
}
return testCases;
}
}
| [
"Alex Hernandez"
] | Alex Hernandez |
266aab427b242fad4dcc56be121111c9d16a49c8 | 67b12aa7f6acdf99dd627c1b7a68a8cefda9fc16 | /app/src/main/java/rs/ltt/android/ui/model/AbstractQueryViewModel.java | b84190b8ef7a0f9eb0d53ef9118dc15edcd51b61 | [
"Apache-2.0"
] | permissive | wiktor-k/lttrs-android | f69a594c989ca057c6728d9f8b71189fdcf0cb72 | e24346d44c6daac50fe2a9437720fcd55d9d4c4e | refs/heads/master | 2020-12-01T19:54:57.461780 | 2019-12-29T11:47:42 | 2019-12-29T11:47:42 | 230,748,947 | 0 | 0 | Apache-2.0 | 2019-12-29T12:44:04 | 2019-12-29T12:44:04 | null | UTF-8 | Java | false | false | 4,554 | java | /*
* Copyright 2019 Daniel Gultsch
* 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 rs.ltt.android.ui.model;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Transformations;
import androidx.paging.PagedList;
import androidx.work.WorkManager;
import com.google.common.util.concurrent.ListenableFuture;
import rs.ltt.android.entity.AccountWithCredentials;
import rs.ltt.android.entity.MailboxWithRoleAndName;
import rs.ltt.android.entity.ThreadOverviewItem;
import rs.ltt.android.repository.QueryRepository;
import rs.ltt.android.util.WorkInfoUtil;
import rs.ltt.android.worker.AbstractMuaWorker;
import rs.ltt.jmap.common.entity.query.EmailQuery;
public abstract class AbstractQueryViewModel extends AndroidViewModel {
final QueryRepository queryRepository;
private final LiveData<Boolean> emailModificationWorkInfo;
private LiveData<PagedList<ThreadOverviewItem>> threads;
private LiveData<Boolean> refreshing;
private LiveData<Boolean> runningPagingRequest;
private ListenableFuture<MailboxWithRoleAndName> important;
AbstractQueryViewModel(@NonNull Application application, ListenableFuture<AccountWithCredentials> account) {
super(application);
final WorkManager workManager = WorkManager.getInstance(application);
this.queryRepository = new QueryRepository(application, account);
this.important = this.queryRepository.getImportant();
this.emailModificationWorkInfo = Transformations.map(workManager.getWorkInfosByTagLiveData(AbstractMuaWorker.TAG_EMAIL_MODIFICATION), WorkInfoUtil::allDone);
}
void init() {
this.threads = Transformations.switchMap(getQuery(), queryRepository::getThreadOverviewItems);
this.refreshing = Transformations.switchMap(getQuery(), queryRepository::isRunningQueryFor);
this.runningPagingRequest = Transformations.switchMap(getQuery(), queryRepository::isRunningPagingRequestFor);
}
public LiveData<Boolean> isRefreshing() {
final LiveData<Boolean> refreshing = this.refreshing;
if (refreshing == null) {
throw new IllegalStateException("LiveData for refreshing not initialized. Forgot to call init()?");
}
return refreshing;
}
public ListenableFuture<MailboxWithRoleAndName> getImportant() {
return this.important;
}
public LiveData<Boolean> isRunningPagingRequest() {
final LiveData<Boolean> paging = this.runningPagingRequest;
if (paging == null) {
throw new IllegalStateException("LiveData for paging not initialized. Forgot to call init()?");
}
return paging;
}
public LiveData<PagedList<ThreadOverviewItem>> getThreadOverviewItems() {
final LiveData<PagedList<ThreadOverviewItem>> liveData = this.threads;
if (liveData == null) {
throw new IllegalStateException("LiveData for thread items not initialized. Forgot to call init()?");
}
return liveData;
}
public LiveData<Boolean> getEmailModificationWorkInfo() {
return emailModificationWorkInfo;
}
public void onRefresh() {
final EmailQuery emailQuery = getQuery().getValue();
if (emailQuery != null) {
queryRepository.refresh(emailQuery);
}
}
public void refreshInBackground() {
final EmailQuery emailQuery = getQuery().getValue();
if (emailQuery != null) {
queryRepository.refreshInBackground(emailQuery);
}
}
protected abstract LiveData<EmailQuery> getQuery();
public void toggleFlagged(String threadId, boolean target) {
this.queryRepository.toggleFlagged(threadId, target);
}
public void archive(ThreadOverviewItem item) {
queryRepository.archive(item.threadId);
}
public void moveToInbox(ThreadOverviewItem item) {
queryRepository.moveToInbox(item.threadId);
}
}
| [
"daniel@gultsch.de"
] | daniel@gultsch.de |
2e659b25a344e1acd25887da9c15d731e43b99d7 | a424a2282ef69179c6ecbbcd88908b5cdcfdeb9d | /Quad.java | 0a1490eebef3685700a7affb14f4510769c95ad1 | [] | no_license | hongming-wong/Big-Two | 16e3b82c94c48d4d33d21f06d969c8426718b7e1 | e1337466466b5daaf75793fcba945567bfa9a6f2 | refs/heads/main | 2023-02-09T04:19:41.559822 | 2020-12-28T04:53:06 | 2020-12-28T04:53:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,041 | java | /**
*
* A subclass of Hand that is one of the 8 legal combinations that can be played.
* A Quad is a set of five cards, with 4 cards having the same rank and an additional card that can be any rank or suit.
* A Quad beats any five card combination except the Straight Flush. Therefore its getOrder() method will return a value
* higher than the previous three combinations.
* @author Hong Ming, Wong
*
*/
public class Quad extends Hand{
/**
* The only public constructor that builds a hand with the specified player and cards.
* @param player the specified player
* @param cards the specified list of cards
*/
public Quad(CardGamePlayer player, CardList cards) {
super(player, cards);
}
/**
* Checks whether then hand is a Quad
* @return returns true if it is a Quad. Else, returns false.
*/
public boolean isValid(){
if(size() == 5) {
sort();
if (getCard(0).getRank() == getCard(1).getRank()) {
if (getCard(1).getRank() == getCard(2).getRank()) {
if (getCard(2).getRank() == getCard(3).getRank()) {
return true;
}
}
}
if (getCard(1).getRank() == getCard(2).getRank()) {
if (getCard(2).getRank() == getCard(3).getRank()) {
if (getCard(3).getRank() == getCard(4).getRank()) {
return true;
}
}
}
return false;
}
return false;
}
/**
* the getTopCard() method is overridden here to reflect that the top card is the highest suit among the quadruplet.
* @return Assuming the Quad is valid, the top card of the Quad Hand
*
*/
public Card getTopCard() {
if (getCard(3).getRank() == getCard(4).getRank()) return getCard(4);
return getCard(3);
/**
* Retrieves the type of hand
* @return A string - "Quad"
*/
}
public String getType(){
return "Quad";
}
/**
* Retrieves the order of a Quad among the 8 legal combinations
* @return The order of a Quad - 7
*/
public int getOrder() {
return 7;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
dbbb2ea3ca4031fde050c2b50ce29ed2de6f9ed3 | c8c8eba5211fa7d778f8fa9150a2c122b8ad62ff | /obj/obj/src/main/java/com/objetivos/obj/controller/objetivosController.java | cb77590d223276f375241f3ff1b222ab9f69fcd5 | [] | no_license | ViniciusSP1995/Git_SpringBoot | 5c9cfab7c4cfa5efe80ac777470295aec6a6a4bf | b4faf783237d17f887f54eaf85f93a265b8d0e01 | refs/heads/main | 2023-04-30T01:53:45.089646 | 2021-05-13T23:05:08 | 2021-05-13T23:05:08 | 361,864,213 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 456 | java | package com.objetivos.obj.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/objetivos")
public class objetivosController {
@GetMapping
public String objetivos_aprendizagem () {
return "Introdução a Rest\nMétodos e Status Http\nCamadas\nHello World";
}
}
| [
"vds199sp@gmail.com"
] | vds199sp@gmail.com |
e0b9c031ef18f74a858641ec9e3d59669f18b16e | 25eb08ebcda6cfc07d62c1949f93afa014c6fce2 | /src/Profun/front.java | 9f85422e6bad3614b64e49d2138b7128fbe93076 | [] | no_license | jhs18/HBV401G-ThrounHugbunadar-Lokaverkefni-2021 | 3fb2020d894c5b6d7d371a537d59e4c2a267037a | 4b64b6626bf0c8209254d9f02038c03c67d19318 | refs/heads/main | 2023-04-20T20:37:49.035542 | 2021-04-28T19:10:38 | 2021-04-28T19:10:38 | 362,578,712 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 740 | java | package Profun;
public class front {
// Run this file to start the program.
public static void main(String[] args) throws ClassNotFoundException {
// INTRODUCTION
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("----------------------WELCOME-----------------------");
System.out.println("");
System.out.println("Welcome to our program!");
System.out.println("Here you can check on flights");
System.out.println("To quit type \"quit\" ");
// GO TO THE MENU
menu.Menu();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
b85e8acab4ad503dd54227168086d7538a190ece | 1a83f3f213dca04890764ac096ba3613f50e5665 | /plugins/plugin/command/impl/player/DropsCommand.java | a0451edef8995f6f7c7e341aa97d116ec3d5c71b | [] | no_license | noveltyps/NewRunityRebelion | 52dfc757d6f784cce4d536c509bcdd6247ae57ef | 6b0e5c0e7330a8a9ee91c691fb150cb1db567457 | refs/heads/master | 2020-05-20T08:44:36.648909 | 2019-05-09T17:23:50 | 2019-05-09T17:23:50 | 185,468,893 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 494 | java | package plugin.command.impl.player;
import io.server.content.DropDisplay;
import io.server.content.command.Command;
import io.server.game.world.entity.mob.player.Player;
public class DropsCommand implements Command {
@Override
public void execute(Player player, String command, String[] parts) {
DropDisplay.open(player);
}
@Override
public boolean canUse(Player player) {
return true;
}
@Override
public String description() {
return "Opens the drop table interface.";
}
}
| [
"43006455+donvlee97@users.noreply.github.com"
] | 43006455+donvlee97@users.noreply.github.com |
1762faad15aedd3c5c67833c0768ee097585091c | e2065966c37633a0fe30fa3d136dd4efe77400a6 | /src/com/common/MyRecord.java | 62fc65e8d1f049f6a2f0bb17384784431782298d | [] | no_license | cqzaiercn/tool | 2fe3092e0dcb2da36c4b93fb62ec4249508923a1 | adf6a7f440a63f9429ede19181c6384227fca0a3 | refs/heads/master | 2021-11-26T05:59:34.864000 | 2018-04-18T01:35:19 | 2018-04-18T01:35:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,110 | java | /**
*
*/
package com.common;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyRecord extends JFrame implements ActionListener{
//定义录音格式
AudioFormat af = null;
//定义目标数据行,可以从中读取音频数据,该 TargetDataLine 接口提供从目标数据行的缓冲区读取所捕获数据的方法。
TargetDataLine td = null;
//定义源数据行,源数据行是可以写入数据的数据行。它充当其混频器的源。应用程序将音频字节写入源数据行,这样可处理字节缓冲并将它们传递给混频器。
SourceDataLine sd = null;
//定义字节数组输入输出流
ByteArrayInputStream bais = null;
ByteArrayOutputStream baos = null;
//定义音频输入流
AudioInputStream ais = null;
//定义停止录音的标志,来控制录音线程的运行
Boolean stopflag = false;
//定义所需要的组件
JPanel jp1,jp2,jp3;
JLabel jl1=null;
JButton captureBtn,stopBtn,playBtn,saveBtn;
public static void main(String[] args) {
//创造一个实例
MyRecord mr = new MyRecord();
}
//构造函数
public MyRecord()
{
//组件初始化
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
//定义字体
Font myFont = new Font("华文新魏",Font.BOLD,30);
jl1 = new JLabel("录音机功能的实现");
jl1.setFont(myFont);
jp1.add(jl1);
captureBtn = new JButton("开始录音");
//对开始录音按钮进行注册监听
captureBtn.addActionListener(this);
captureBtn.setActionCommand("captureBtn");
//对停止录音进行注册监听
stopBtn = new JButton("停止录音");
stopBtn.addActionListener(this);
stopBtn.setActionCommand("stopBtn");
//对播放录音进行注册监听
playBtn = new JButton("播放录音");
playBtn.addActionListener(this);
playBtn.setActionCommand("playBtn");
//对保存录音进行注册监听
saveBtn = new JButton("保存录音");
saveBtn.addActionListener(this);
saveBtn.setActionCommand("saveBtn");
this.add(jp1,BorderLayout.NORTH);
this.add(jp2,BorderLayout.CENTER);
this.add(jp3,BorderLayout.SOUTH);
jp3.setLayout(null);
jp3.setLayout(new GridLayout(1, 4,10,10));
jp3.add(captureBtn);
jp3.add(stopBtn);
jp3.add(playBtn);
jp3.add(saveBtn);
//设置按钮的属性
captureBtn.setEnabled(true);
stopBtn.setEnabled(false);
playBtn.setEnabled(false);
saveBtn.setEnabled(false);
//设置窗口的属性
this.setSize(400,300);
this.setTitle("录音机");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("captureBtn"))
{
//点击开始录音按钮后的动作
//停止按钮可以启动
captureBtn.setEnabled(false);
stopBtn.setEnabled(true);
playBtn.setEnabled(false);
saveBtn.setEnabled(false);
//调用录音的方法
capture();
}else if (e.getActionCommand().equals("stopBtn")) {
//点击停止录音按钮的动作
captureBtn.setEnabled(true);
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
saveBtn.setEnabled(true);
//调用停止录音的方法
stop();
}else if(e.getActionCommand().equals("playBtn"))
{
//调用播放录音的方法
play();
}else if(e.getActionCommand().equals("saveBtn"))
{
//调用保存录音的方法
save();
}
}
//开始录音
public void capture()
{
try {
//af为AudioFormat也就是音频格式
af = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class,af);
td = (TargetDataLine)(AudioSystem.getLine(info));
//打开具有指定格式的行,这样可使行获得所有所需的系统资源并变得可操作。
td.open(af);
//允许某一数据行执行数据 I/O
td.start();
//创建播放录音的线程
Record record = new Record();
Thread t1 = new Thread(record);
t1.start();
} catch (LineUnavailableException ex) {
ex.printStackTrace();
return;
}
}
//停止录音
public void stop()
{
stopflag = true;
}
//播放录音
public void play()
{
//将baos中的数据转换为字节数据
byte audioData[] = baos.toByteArray();
//转换为输入流
bais = new ByteArrayInputStream(audioData);
af = getAudioFormat();
ais = new AudioInputStream(bais, af, audioData.length/af.getFrameSize());
try {
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, af);
sd = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sd.open(af);
sd.start();
//创建播放进程
Play py = new Play();
Thread t2 = new Thread(py);
t2.start();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
//关闭流
if(ais != null)
{
ais.close();
}
if(bais != null)
{
bais.close();
}
if(baos != null)
{
baos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//保存录音
public void save()
{
//取得录音输入流
af = getAudioFormat();
byte audioData[] = baos.toByteArray();
bais = new ByteArrayInputStream(audioData);
ais = new AudioInputStream(bais,af, audioData.length / af.getFrameSize());
//定义最终保存的文件名
File file = null;
//写入文件
try {
//以当前的时间命名录音的名字
//将录音的文件存放到F盘下语音文件夹下
File filePath = new File("F:/语音文件");
if(!filePath.exists())
{//如果文件不存在,则创建该目录
filePath.mkdir();
}
file = new File(filePath.getPath()+"/"+System.currentTimeMillis()+".mp3");
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, file);
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭流
try {
if(bais != null)
{
bais.close();
}
if(ais != null)
{
ais.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//设置AudioFormat的参数
public AudioFormat getAudioFormat()
{
//下面注释部分是另外一种音频格式,两者都可以
AudioFormat.Encoding encoding = AudioFormat.Encoding.
PCM_SIGNED ;
float rate = 8000f;
int sampleSize = 16;
String signedString = "signed";
boolean bigEndian = true;
int channels = 1;
return new AudioFormat(encoding, rate, sampleSize, channels,
(sampleSize / 8) * channels, rate, bigEndian);
// //采样率是每秒播放和录制的样本数
// float sampleRate = 16000.0F;
// // 采样率8000,11025,16000,22050,44100
// //sampleSizeInBits表示每个具有此格式的声音样本中的位数
// int sampleSizeInBits = 16;
// // 8,16
// int channels = 1;
// // 单声道为1,立体声为2
// boolean signed = true;
// // true,false
// boolean bigEndian = true;
// // true,false
// return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,bigEndian);
}
//录音类,因为要用到MyRecord类中的变量,所以将其做成内部类
class Record implements Runnable
{
//定义存放录音的字节数组,作为缓冲区
byte bts[] = new byte[10000];
//将字节数组包装到流里,最终存入到baos中
//重写run函数
public void run() {
baos = new ByteArrayOutputStream();
try {
System.out.println("ok3");
stopflag = false;
while(stopflag != true)
{
//当停止录音没按下时,该线程一直执行
//从数据行的输入缓冲区读取音频数据。
//要读取bts.length长度的字节,cnt 是实际读取的字节数
int cnt = td.read(bts, 0, bts.length);
if(cnt > 0)
{
baos.write(bts, 0, cnt);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
//关闭打开的字节数组流
if(baos != null)
{
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
td.drain();
td.close();
}
}
}
}
//播放类,同样也做成内部类
class Play implements Runnable
{
//播放baos中的数据即可
public void run() {
byte bts[] = new byte[10000];
try {
int cnt;
//读取数据到缓存数据
while ((cnt = ais.read(bts, 0, bts.length)) != -1)
{
if (cnt > 0)
{
//写入缓存数据
//将音频数据写入到混频器
sd.write(bts, 0, cnt);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
sd.drain();
sd.close();
}
}
}
}
| [
"zehua951203@gmail.com"
] | zehua951203@gmail.com |
cac407ef692f952c03abda6cc2a982a69af014b0 | 7c1c33f1bd426db0b2807f64e95cea9eb10f7323 | /app/src/main/java/de/fhdw/bfws115a/team1/caloriecounter/activities/calendar/Gui.java | 78910c5c42593d65ff7baa6c71ba061e76914bcd | [] | no_license | olgatabac/CalorieCounter | f0b63c4e9886c89ab27921700f79037cb326c75b | 3a24145ef67c0639ca474469683c7e7fe9c90ffd | refs/heads/master | 2020-06-20T19:38:38.809411 | 2017-01-07T10:19:55 | 2017-01-07T10:19:55 | 74,745,243 | 0 | 0 | null | 2016-11-25T11:24:40 | 2016-11-25T09:41:29 | Java | UTF-8 | Java | false | false | 969 | java | package de.fhdw.bfws115a.team1.caloriecounter.activities.calendar;
import android.widget.Button;
import android.widget.CalendarView;
import java.util.Calendar;
import de.fhdw.bfws115a.team1.caloriecounter.R;
public class Gui {
private CalendarView mCalendarView;
private Button mTodayButton;
public Gui(Init activity) {
activity.setContentView(R.layout.calendar);
mCalendarView = (CalendarView) activity.findViewById(R.id.idCalendarView);
mTodayButton = (Button) activity.findViewById(R.id.idTodayButton);
}
public CalendarView getCalendarView() {
return mCalendarView;
}
public Button getTodayButton() {
return mTodayButton;
}
/* Methods to apply changes */
public void setSelectedDate(int year, int month, int day) {
Calendar date = Calendar.getInstance();
date.set(year, month, day);
mCalendarView.setDate(date.getTimeInMillis(), true, true);
}
}
| [
"xyShadowyx@googlemail.com"
] | xyShadowyx@googlemail.com |
3935c0ac144311d8bf11d7abc895c435869dbf0c | f3528c80ef576fd90d7e1c40a07efc38a5fcdc55 | /src/main/java/com/gxb/tmall/service/OrderService.java | c0a11c51462d8ed46685f42e040f300ddfc675d9 | [] | no_license | Geligamesh/tmall_springboot | 9aedcf12d5775a7365c260b3cd14409a0aa48778 | 87111a9c3821055c403f03c126e4334e4231a4f2 | refs/heads/master | 2022-06-24T11:57:22.987991 | 2019-09-21T14:53:37 | 2019-09-21T14:53:37 | 177,995,235 | 5 | 1 | null | 2022-06-21T01:01:17 | 2019-03-27T12:59:58 | HTML | UTF-8 | Java | false | false | 3,220 | java | package com.gxb.tmall.service;
import com.gxb.tmall.dao.OrderDAO;
import com.gxb.tmall.pojo.Order;
import com.gxb.tmall.pojo.OrderItem;
import com.gxb.tmall.pojo.User;
import com.gxb.tmall.util.Page4Navigator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class OrderService {
public static final String waitPay = "waitPay";
public static final String waitDelivery = "waitDelivery";
public static final String waitConfirm = "waitConfirm";
public static final String waitReview = "waitReview";
public static final String finish = "finish";
public static final String delete = "delete";
@Autowired
private OrderDAO orderDAO;
@Autowired
private OrderItemService orderItemService;
public Page4Navigator<Order> list(int start, int size, int navigatePages){
Sort sort = new Sort(Sort.Direction.DESC,"id");
Pageable pageable = new PageRequest(start,size,sort);
Page page = orderDAO.findAll(pageable);
return new Page4Navigator<>(navigatePages,page);
}
public void removeOrderFromOrderItem(Order order){
List<OrderItem> orderItems = order.getOrderItems();
for (OrderItem orderItem : orderItems) {
orderItem.setOrder(null);
}
}
public void removeOrderFromOrderItem(List<Order> orders){
for (Order order : orders) {
removeOrderFromOrderItem(order);
}
}
public Order get(int oid){
return orderDAO.findOne(oid);
}
public void update(Order order){
orderDAO.save(order);
}
public void add(Order order) {
orderDAO.save(order);
}
@Transactional(propagation = Propagation.REQUIRED,rollbackForClassName = "Exception")
public float add(Order order,List<OrderItem> orderItems) {
float total = 0;
add(order);
if (false) {
throw new RuntimeException();
}
for (OrderItem orderItem : orderItems) {
orderItem.setOrder(order);
orderItemService.update(orderItem);
total += orderItem.getProduct().getPromotePrice();
}
return total;
}
public List<Order> listByUserAndNotDeleted(User user) {
return orderDAO.findByUserAndStatusNotOrderByIdDesc(user, OrderService.delete);
}
public List<Order> listByUserWithoutDelete(User user) {
List<Order> orders = listByUserAndNotDeleted(user);
orderItemService.fill(orders);
return orders;
}
public void cacl(Order order) {
List<OrderItem> orderItems = order.getOrderItems();
float total = 0l;
for (OrderItem orderItem : orderItems) {
total += orderItem.getProduct().getPromotePrice() * orderItem.getNumber();
}
order.setTotal(total);
}
}
| [
"535758155@qq.com"
] | 535758155@qq.com |
001f591fc9998b662fddb7ca380100605dab7bba | 4013a3e98d2ea47790ed36cec752f8d8d2c78d85 | /src/Calendar/Calendar.java | 22ffb34b83c6d9c161bb56a9fb75eade51702e24 | [] | no_license | Jeffreylsq/CalendarDemo | a48356a30be5a2f1e0dba301e854f7b8561f6be3 | 689b0c54b421f9e1cb018097eee6cd2ba0438e37 | refs/heads/master | 2020-04-20T23:42:23.556321 | 2019-02-05T01:26:05 | 2019-02-05T01:26:05 | 169,175,392 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,231 | java | package Calendar;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Calendar {
public static void main(String[] args) throws IOException
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the year ");
int year = kb.nextInt();
printCalendar(year);
}
public static String Calendar(int month)
{
String [] array = {"January", "Feburary", "March", "April", "May","June","July","Angust","September","October","November","December"};
return array[month-1];
}
public static boolean isLeap(int year)
{
boolean result = (year%4 == 0 && year %100 !=0)||(year%400 == 0)?true:false;
return result;
}
public static int getNumberOfDay (int month, int year)
{ int day = 0 ;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
day = (isLeap(year))?29:28;
break;
default:
day = 30;
}
return day;
}
public static int getDayOfTheWeek(int day, int month, int year)
{
int sum = 0 ;
for(int i = 1900; i < year ; i++)
{
if(isLeap(i))
{
sum += 366;
}
else
{
sum += 365;
}
}
for(int i = 1; i<= month; i++ )
{
sum += getNumberOfDay(i, year);
}
sum += day;
return (sum%7);
}
public static void printCalendar(int year)throws IOException
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter your output file name");
String fileName = kb.next();
PrintWriter output = new PrintWriter(fileName);
output.println("**********" + year +"'s calendar*******");
for(int i = 1; i <= 12 ; i++)
{ output.println("\t"+ Calendar(i));
output.println(" Sun Mon Tue Wed Thr Fri Sat ");
int startDay = getDayOfTheWeek(1, i, year);
for(int j = 1 ; j <= startDay; j++ )
{
output.print(" ");
}
int numberOfDay = getNumberOfDay(i, year);
for(int j = 1 ; j <= numberOfDay ; j++)
{
output.printf("%4d", j);
if((startDay + j)%7 == 0)
{
output.println();
}
}
output.println();
output.println();
}
output.close();
}
}
| [
"40809623+Jeffreylsq@users.noreply.github.com"
] | 40809623+Jeffreylsq@users.noreply.github.com |
e404b7b90102a5f8a86138f7b81206e409aacbd3 | eab7618911ac2e07c07e18a2c650233acc5ac105 | /exo7/exo7.java | 2d552d32e9dfd47eaa1a94ae4344a461d5e33726 | [] | no_license | alex3469/algorithme_exos | 6d6585c9bf4e2a06be721d055c81221a60e0c4f4 | 77b1dbc24dd7c557776c5af1e1e1f591b8be8a45 | refs/heads/master | 2021-01-12T04:36:36.579416 | 2016-12-30T15:39:41 | 2016-12-30T15:39:41 | 77,686,155 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,756 | java | import java.util.Scanner;
public class exo7
{
public static void palindrome(String word)
{
boolean flag = false;
int i = 0;
int j = word.length()-1;
System.out.println(word);
while (i < word.length()-1)
{
if(word.charAt(i) == word.charAt(j))
{
j--;
i++;
flag = true;
}
else
{
flag = false;
break;
}
}
if(flag == true)
{
System.out.println("ce mot est un palindrome");
}
else
{
System.out.println("ce mot n'est pas un palindrome");
}
}
public static void countLetter(String word)
{
int i = 0;
int nbLetter = 0;
System.out.println(word);
for( i = 0; i < word.length(); i++ )
{
char temp = word.charAt(i);
if(Character.isLetter(temp))
{
nbLetter++;
}
}
System.out.println("nombre de lettres alpha : " +nbLetter);
}
public static void replaceLetter(String word,String charA,String charB)
{
int i = 0;
System.out.println(word);
while(i < word.length())
{
if(word.charAt(i) == charA.charAt(0))
{
word = word.substring(0,i)+charB+word.substring(i+1);
}
i++;
}
System.out.println("la lettre "+charA+" est remplacé par la lettre "+charB);
System.out.println("resulat : "+word);
}
public static void cutText(String text)
{
int i = 0;
System.out.println(text);
while(i < text.length())
{
if(text.charAt(i) == ' ')
{
text = text.substring(0,i)+'\n'+text.substring(i+1);
}
i++;
}
System.out.println(text);
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean drapeau = false;
System.out.println("Bonjour,");
while(drapeau == false)
{
System.out.println("Veuillez entrer une phrase ou un mot :\n");
String word = input.nextLine();
System.out.println("Veuillez choisir une action a effectuer\nTapez 1 pour verifier si le mot ou phrase est un palindrome\nTapez 2 pour nombres de caractere alphabetique dans le mot ou phrase\nTapez 3 pour remplacer un caractere par un autre\nTapez 4 pour decouper la phrase\nTapez 5 pour resaisir le mot ou la phrase a traiter\nTapez q pour quitter\n");
String mode = input.nextLine();
switch(mode)
{
case "1":
palindrome(word);
break;
case "2":
countLetter(word);
break;
case "3":
System.out.println("Veuillez entrez la lettre a modifier");
String charA =input.nextLine();
System.out.println("Veuillez entrez la nouvelle lettre");
String charB =input.nextLine();
replaceLetter(word,charA,charB);
break;
case "4":
cutText(word);
break;
case "5":
break;
case "q":
System.exit(0);
break;
default:
System.out.println("Try again");
break;
}
}
}
}
| [
"brunet.alex34@gmail.com"
] | brunet.alex34@gmail.com |
51816946ee95f947fea181305d16c54c089b4597 | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/training/org/apache/activemq/broker/RedeliveryRestartTest.java | d0018d340c9dc582a54f722ad92502233bf659f6 | [] | no_license | STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919811 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | null | UTF-8 | Java | false | false | 10,674 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker;
import Session.CLIENT_ACKNOWLEDGE;
import Session.SESSION_TRANSACTED;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.TopicSubscriber;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.TestSupport;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.transport.failover.FailoverTransport;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.activemq.TestSupport.PersistenceAdapterChoice.KahaDB;
@RunWith(Parameterized.class)
public class RedeliveryRestartTest extends TestSupport {
private static final transient Logger LOG = LoggerFactory.getLogger(RedeliveryRestartTest.class);
ActiveMQConnection connection;
BrokerService broker = null;
String queueName = "redeliveryRestartQ";
@Parameterized.Parameter
public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = KahaDB;
@Test
public void testValidateRedeliveryFlagAfterRestartNoTx() throws Exception {
ConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory((("failover:(" + (broker.getTransportConnectors().get(0).getPublishableConnectString())) + ")?jms.prefetchPolicy.all=0"));
connection = ((ActiveMQConnection) (connectionFactory.createConnection()));
connection.start();
Session session = connection.createSession(false, CLIENT_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
populateDestination(10, destination, connection);
MessageConsumer consumer = session.createConsumer(destination);
TextMessage msg = null;
for (int i = 0; i < 5; i++) {
msg = ((TextMessage) (consumer.receive(20000)));
RedeliveryRestartTest.LOG.info(("not redelivered? got: " + msg));
assertNotNull("got the message", msg);
assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
assertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
consumer.close();
restartBroker();
// make failover aware of the restarted auto assigned port
connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
consumer = session.createConsumer(destination);
for (int i = 0; i < 5; i++) {
msg = ((TextMessage) (consumer.receive(4000)));
RedeliveryRestartTest.LOG.info(("redelivered? got: " + msg));
assertNotNull("got the message again", msg);
assertEquals("re delivery flag", true, msg.getJMSRedelivered());
assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount"));
msg.acknowledge();
}
// consume the rest that were not redeliveries
for (int i = 0; i < 5; i++) {
msg = ((TextMessage) (consumer.receive(20000)));
RedeliveryRestartTest.LOG.info(("not redelivered? got: " + msg));
assertNotNull("got the message", msg);
assertEquals("not a redelivery", false, msg.getJMSRedelivered());
assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
msg.acknowledge();
}
connection.close();
}
@Test
public void testDurableSubRedeliveryFlagAfterRestartNotSupported() throws Exception {
ConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory((("failover:(" + (broker.getTransportConnectors().get(0).getPublishableConnectString())) + ")?jms.prefetchPolicy.all=0"));
connection = ((ActiveMQConnection) (connectionFactory.createConnection()));
connection.setClientID("id");
connection.start();
Session session = connection.createSession(false, CLIENT_ACKNOWLEDGE);
ActiveMQTopic destination = new ActiveMQTopic(queueName);
TopicSubscriber durableSub = session.createDurableSubscriber(destination, "id");
populateDestination(10, destination, connection);
TextMessage msg = null;
for (int i = 0; i < 5; i++) {
msg = ((TextMessage) (durableSub.receive(20000)));
RedeliveryRestartTest.LOG.info(("not redelivered? got: " + msg));
assertNotNull("got the message", msg);
assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
assertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
durableSub.close();
restartBroker();
// make failover aware of the restarted auto assigned port
connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
durableSub = session.createDurableSubscriber(destination, "id");
for (int i = 0; i < 10; i++) {
msg = ((TextMessage) (durableSub.receive(4000)));
RedeliveryRestartTest.LOG.info(("redelivered? got: " + msg));
assertNotNull("got the message again", msg);
assertEquals("no reDelivery flag", false, msg.getJMSRedelivered());
msg.acknowledge();
}
connection.close();
}
@Test
public void testValidateRedeliveryFlagAfterRestart() throws Exception {
ConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory((("failover:(" + (broker.getTransportConnectors().get(0).getPublishableConnectString())) + ")?jms.prefetchPolicy.all=0"));
connection = ((ActiveMQConnection) (connectionFactory.createConnection()));
connection.start();
Session session = connection.createSession(true, SESSION_TRANSACTED);
Destination destination = session.createQueue(queueName);
populateDestination(10, destination, connection);
MessageConsumer consumer = session.createConsumer(destination);
TextMessage msg = null;
for (int i = 0; i < 5; i++) {
msg = ((TextMessage) (consumer.receive(20000)));
RedeliveryRestartTest.LOG.info(("not redelivered? got: " + msg));
assertNotNull("got the message", msg);
assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
assertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
session.rollback();
consumer.close();
restartBroker();
// make failover aware of the restarted auto assigned port
connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
consumer = session.createConsumer(destination);
for (int i = 0; i < 5; i++) {
msg = ((TextMessage) (consumer.receive(4000)));
RedeliveryRestartTest.LOG.info(("redelivered? got: " + msg));
assertNotNull("got the message again", msg);
assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount"));
assertEquals("re delivery flag", true, msg.getJMSRedelivered());
}
session.commit();
// consume the rest that were not redeliveries
for (int i = 0; i < 5; i++) {
msg = ((TextMessage) (consumer.receive(20000)));
RedeliveryRestartTest.LOG.info(("not redelivered? got: " + msg));
assertNotNull("got the message", msg);
assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
assertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
session.commit();
connection.close();
}
@Test
public void testValidateRedeliveryFlagAfterRecovery() throws Exception {
ConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory(((broker.getTransportConnectors().get(0).getPublishableConnectString()) + "?jms.prefetchPolicy.all=0"));
connection = ((ActiveMQConnection) (connectionFactory.createConnection()));
connection.start();
Session session = connection.createSession(true, SESSION_TRANSACTED);
Destination destination = session.createQueue(queueName);
populateDestination(1, destination, connection);
MessageConsumer consumer = session.createConsumer(destination);
TextMessage msg = ((TextMessage) (consumer.receive(5000)));
RedeliveryRestartTest.LOG.info(("got: " + msg));
assertNotNull("got the message", msg);
assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
assertEquals("not a redelivery", false, msg.getJMSRedelivered());
stopBrokerWithStoreFailure(broker, persistenceAdapterChoice);
broker = createRestartedBroker();
broker.start();
connection.close();
connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString());
connection = ((ActiveMQConnection) (connectionFactory.createConnection()));
connection.start();
session = connection.createSession(true, SESSION_TRANSACTED);
consumer = session.createConsumer(destination);
msg = ((TextMessage) (consumer.receive(10000)));
assertNotNull("got the message again", msg);
assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount"));
assertEquals("re delivery flag", true, msg.getJMSRedelivered());
session.commit();
connection.close();
}
}
| [
"benjamin.danglot@inria.fr"
] | benjamin.danglot@inria.fr |
4adb7853f7bb12e41b333bcb0b4c07e872bcc451 | 7e41614c9e3ddf095e57ae55ae3a84e2bdcc2844 | /development/workspace(helios)/Poseidon/src/com/gentleware/poseidon/custom/diagrams/node/impl/InitialStateNodeGem.java | 952a0344ce4d28237b133f3ce83b9daaca7d3024 | [] | no_license | ygarba/mde4wsn | 4aaba2fe410563f291312ffeb40837041fb143ff | a05188b316cc05923bf9dee9acdde15534a4961a | refs/heads/master | 2021-08-14T09:52:35.948868 | 2017-11-15T08:02:31 | 2017-11-15T08:02:31 | 109,995,809 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 996 | java |
package com.gentleware.poseidon.custom.diagrams.node.impl;
import java.awt.Color;
import com.gentleware.poseidon.dsl.MetamodelElementWrapper;
import org.eclipse.emf.ecore.EObject;
import com.gentleware.poseidon.idraw.foundation.DiagramFacet;
import com.gentleware.poseidon.idraw.foundation.persistence.PersistentFigure;
import com.gentleware.poseidon.idraw.foundation.persistence.PersistentProperties;
import com.gentleware.poseidon.diagrams.gen.node.DslGenInitialStateNodeGem;
public class InitialStateNodeGem extends DslGenInitialStateNodeGem {
public InitialStateNodeGem(Color initialFillColor, PersistentFigure figure, String figureName) {
super(initialFillColor, figure, figureName);
}
public InitialStateNodeGem(EObject subject, DiagramFacet diagram, String figureId, Color initialFillColor,
PersistentProperties properties, String figureName) {
super(subject, diagram, figureId, initialFillColor, properties, figureName);
}
}
| [
"ygarba@gmail.com"
] | ygarba@gmail.com |
291abd7575c3a2caf8f5cd942d4c18116a235d08 | fe2e22d64876209f92dcb4bb54b7e30243d1bf8f | /marketdata-web/src/test/java/com/handson/rx/StockServerTest.java | 20385d5799991392588311c59ab60e37893616ba | [
"Apache-2.0"
] | permissive | nebrass/MarketData | bd945da0a8dac613f937f9882e93557e53097605 | bc4acb013d0cb9887c5000509320bae8dca6294f | refs/heads/master | 2020-05-29T11:40:36.899120 | 2016-04-17T15:01:59 | 2016-04-17T15:01:59 | 56,890,636 | 1 | 0 | null | 2016-04-22T23:26:21 | 2016-04-22T23:26:20 | null | UTF-8 | Java | false | false | 3,763 | java | package com.handson.rx;
import com.handson.dto.Quote;
import com.handson.dto.Stock;
import com.handson.infra.EventStreamClient;
import com.handson.infra.RequestReplyClient;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import rx.Observable;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
import rx.subjects.TestSubject;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class StockServerTest {
private RequestReplyClient stockClient;
private EventStreamClient stockQuoteClient;
private TestScheduler scheduler;
private StockServer stockServer;
private TestSubject<String> quoteSourceSubject;
@Before
public void setUpServer() {
stockClient = mock(RequestReplyClient.class);
stockQuoteClient = mock(EventStreamClient.class);
scheduler = Schedulers.test();
stockServer = new StockServer(42, stockClient, stockQuoteClient, scheduler);
quoteSourceSubject = TestSubject.create(scheduler);
when(stockQuoteClient.readServerSideEvents()).thenReturn(quoteSourceSubject);
when(stockClient.request(eq("GOOGL")))
.then(
code -> Observable.just(
new Stock("GOOGL", "Alphabet Inc", "NASDAQ").toJson()
)
);
when(stockClient.request(eq("IBM")))
.then(
code -> Observable.just(
new Stock("IBM", "International Business Machines Corp.", "NYSE").toJson()
)
);
}
/**
* Test 7
*/
@Test
@Ignore
public void should_send_a_stock_message_when_receiving_a_quote() {
// given
TestSubscriber<Stock> testSubscriber = new TestSubscriber<>();
stockServer.getEvents(null).subscribe(testSubscriber);
// when
quoteSourceSubject.onNext(new Quote("GOOGL", 705.8673).toJson());
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
// then
List<Stock> events = testSubscriber.getOnNextEvents();
assertThat(events).hasSize(1);
assertThat(events.get(0).companyName).isEqualTo("Alphabet Inc");
}
/**
* Test 8
*/
@Test
@Ignore
public void should_send_a_stock_message_only_once_when_receiving_two_quotes_for_the_same_stock() {
// given
TestSubscriber<Stock> testSubscriber = new TestSubscriber<>();
stockServer.getEvents(null).subscribe(testSubscriber);
// when
quoteSourceSubject.onNext(new Quote("GOOGL", 705.8673).toJson());
quoteSourceSubject.onNext(new Quote("GOOGL", 705.8912).toJson(), 20);
quoteSourceSubject.onNext(new Quote("IBM", 126.344).toJson(), 110);
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
// then
List<Stock> events = testSubscriber.getOnNextEvents();
assertThat(events).hasSize(2);
assertThat(events.get(0).companyName).isEqualTo("Alphabet Inc");
assertThat(events.get(1).companyName).isEqualTo("International Business Machines Corp.");
}
/**
* Test 9
*/
@Test
@Ignore
public void should_stop_stream_after_10_seconds() {
// given
TestSubscriber<Stock> testSubscriber = new TestSubscriber<>();
stockServer.getEvents(null).subscribe(testSubscriber);
// when
scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
// then
testSubscriber.assertCompleted();
}
} | [
"alexvictoor@gmail.com"
] | alexvictoor@gmail.com |
3f434ee45ec34df1e46143ccc74a8f7dcf6d24d1 | 30821f8d1cf1a5d352905d896e5c6e620416210b | /src/mulitples35/multiples.java | 39b19a09d708f81e18141c61d36be7d977628b75 | [] | no_license | calee14/JavaChallenges | 766a62175a973835b528395e2f0bcefe3155fb96 | 992d022b9e81f64c71321d5a6b252dafad757101 | refs/heads/master | 2021-09-06T03:24:17.347186 | 2018-02-02T01:40:18 | 2018-02-02T01:40:18 | 119,236,623 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 506 | java | package mulitples35;
public class multiples {
public static int getmultiples(int num1, int num2) {
int sum = 0;
for(int i=0; i<1000;i+=1) {
if(i % num1 == 0 || i % num2 == 0) {
sum += i;
}
}
return sum;
}
public static void main(String[] args) {
long startTime = System.nanoTime();
System.out.println(getmultiples(3, 5));
long endTime = System.nanoTime();
long totalTimeMS = (endTime - startTime) / 1000000;
System.out.println("Program took " + totalTimeMS + " ms");
}
}
| [
"caplee1000@gmail.com"
] | caplee1000@gmail.com |
06da5368f709160a796dc1a6329eff3d882e47a1 | d4d2dc53f41fca21a503a4d2d40719bef67c9198 | /src/com/htc/utilities/CommonUtilities.java | 015af20069e1265606142d0325111fbf5a9de9ad | [] | no_license | ritika2734/Holons-Smart-Grid | 2dc9eb93a1f9305b32185826246551c3b963e15f | da7c6e627cceb0aa21fa1d3983dd6a879a8e92fb | refs/heads/master | 2020-12-02T19:33:36.780669 | 2017-07-05T21:06:12 | 2017-07-05T21:06:12 | 96,360,289 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 48,933 | java | package com.htc.utilities;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.htc.action.PowerSwitchAction;
import com.htc.hibernate.pojo.Holon;
import com.htc.hibernate.pojo.HolonElement;
import com.htc.hibernate.pojo.HolonObject;
import com.htc.hibernate.pojo.LatLng;
import com.htc.hibernate.pojo.PowerLine;
import com.htc.hibernate.pojo.PowerSource;
import com.htc.hibernate.pojo.PowerSwitch;
import com.htc.hibernate.pojo.Supplier;
import com.htc.service.ServiceAware;
import com.opensymphony.xwork2.ActionContext;
/**
* This class contains variables and functions that are used by all action classes.
*/
public class CommonUtilities extends ServiceAware {
private static final long serialVersionUID = 1L;
//Global(to class only) member map and array list to be used by the recursive function connectedPowerLines(Integer powerLineId)
private Map<Integer, PowerLine> listOfAllConnectedPowerLines = new TreeMap<Integer, PowerLine>();
private ArrayList<PowerLine> listOfAllNeighbouringConnectedPowerLines = new ArrayList<PowerLine>();
static Logger log = Logger.getLogger(CommonUtilities.class);
protected HttpServletResponse response; //HTTP response object to be used by all AJAX calls
protected HttpServletRequest request; // HTTP request object to be used by all AJAX calls
protected HttpSession httpSession; // HTTP session object to be used by all AJAX calls
public HttpServletResponse getResponse() {
return (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public HttpServletRequest getRequest() {
return (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpSession getHttpSession() {
return getRequest().getSession();
}
public void setHttpSession(HttpSession httpSession) {
this.httpSession = httpSession;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
/**
* This method calculates the percentage power capacity remaining for the Power Line
* @param x This is the current remaining power capacity of the power line
* @param y This is the maximum capacity of the power line
* @return It returns the percentage of the power capacity currently available in the power line
*/
public static int getPercent(int x, int y) {
float xF=new Float(x);
float yF=new Float(y);
float perc= ((xF/yF)*100);
log.info("x is "+x);
log.info("y is "+y);
log.info("percent is "+perc);
return (int) perc;
}
/**
* This method returns the color of the line based on the current power capacity of the power line.
* @param percentCap It is the current power capacity of the line in percent.
* @return The color of the line.
*/
public static String getLineColor(int percentCap) {
String color="brown";
if(0<percentCap && percentCap<=20) {
color = "red";
} else if(20<percentCap && percentCap<=50) {
color = "yellow";
} else if(percentCap>50 && percentCap<100) {
color ="green";
} else if(percentCap==100) {
color ="black";
}
return color;
}
/**
* This method calculates energy details of the holon object passed as parameter and returns the same in the form of a map.
* @param holonObject Holon Object for which energy needs to be calculated
* @return Map of various parameters containing holon object energy details.
*/
public Map<String, Integer> getHolonObjectEnergyDetails(HolonObject holonObject) {
Map<String, Integer> holonObjectEnergyDetails = new TreeMap<String, Integer>();
Integer minimumEnergyRequired = 0;
Integer maximumEnergyRequired = 0;
Integer originalEnergyRequired = 0;
Integer minimumProductionCapacity = 0;
Integer maximumProductionCapacity = 0;
Integer currentProduction=0;
Integer currentEnergyRequired = 0;
Integer flexibility = 0;
Integer originalEnergyRequiredAfterCurrentProduction = 0;
ArrayList<HolonElement> holonElementList= getHolonElementService().getHolonElements(holonObject);
for(HolonElement holonElement : holonElementList) {
if(holonElement.getHolonElementType().getProducer()) {
minimumProductionCapacity = minimumProductionCapacity + holonElement.getHolonElementType().getMinCapacity();
maximumProductionCapacity = maximumProductionCapacity + holonElement.getHolonElementType().getMaxCapacity();
if(holonElement.getHolonElementState().getId()==1) {
currentProduction = currentProduction + holonElement.getCurrentCapacity();
}
} else {
minimumEnergyRequired = minimumEnergyRequired+holonElement.getHolonElementType().getMinCapacity();
maximumEnergyRequired = maximumEnergyRequired+holonElement.getHolonElementType().getMaxCapacity();
if(holonElement.getHolonElementState().getId()==1) {
originalEnergyRequired = originalEnergyRequired+holonElement.getCurrentCapacity();
}
}
}
currentEnergyRequired = originalEnergyRequired;
if(originalEnergyRequired > 0) {
if(currentProduction > 0 && currentProduction <= originalEnergyRequired) {
currentEnergyRequired = originalEnergyRequired - currentProduction;
} else if(currentProduction > 0 && currentProduction > originalEnergyRequired) {
currentEnergyRequired = 0;
}
}
originalEnergyRequiredAfterCurrentProduction = currentEnergyRequired;
Map<String, Integer> flexibilityAndCurrentRequirement = getFlexibilityAndCurrentEnergyRequirementOfHolonObject(holonObject, currentEnergyRequired);
currentEnergyRequired = flexibilityAndCurrentRequirement.get("currentEnergyRequired");
flexibility = flexibilityAndCurrentRequirement.get("flexibility");
holonObjectEnergyDetails.put("noOfHolonElements", holonElementList.size());
holonObjectEnergyDetails.put("minimumEnergyRequired", minimumEnergyRequired);
holonObjectEnergyDetails.put("maximumEnergyRequired", maximumEnergyRequired);
holonObjectEnergyDetails.put("originalEnergyRequired", originalEnergyRequired);
holonObjectEnergyDetails.put("minimumProductionCapacity", minimumProductionCapacity);
holonObjectEnergyDetails.put("maximumProductionCapacity", maximumProductionCapacity);
holonObjectEnergyDetails.put("currentProduction", currentProduction);
holonObjectEnergyDetails.put("currentEnergyRequired", currentEnergyRequired);
holonObjectEnergyDetails.put("flexibility", flexibility);
holonObjectEnergyDetails.put("originalEnergyRequiredAfterCurrentProduction", originalEnergyRequiredAfterCurrentProduction);
return holonObjectEnergyDetails;
}
/**
* This method calculates energy details of the entire holon represented by the holon coordinator passed as parameter.
* @param holonCoordinator Holon Coordinator for which holon energy details needs to be calculated.
* @return Map of various parameters containing holon energy details.
*/
public Map<String, String> getHolonEnergyDetails(HolonObject holonCoordinator) {
Map<String, String> holonEnergyDetails = new TreeMap<String, String>();
PowerLine powerLine = getPowerLineService().getPowerLineByHolonObject(holonCoordinator);
ArrayList<HolonObject> holonObjectListByConnectedPowerLines = getHolonObjectListByConnectedPowerLines(powerLine, holonCoordinator);
Integer noOfHolonObjects = 0;
StringBuffer holonObjectList=new StringBuffer("");
Integer minimumProductionCapacityHolon = 0;
Integer maximumProductionCapacityHolon = 0;
Integer currentProductionHolon = 0;
Integer minimumEnergyRequiredHolon = 0;
Integer maximumEnergyRequiredHolon = 0;
Integer currentEnergyRequiredHolon = 0;
Integer originalEnergyRequiredHolon = 0;
Integer flexibilityHolon = 0;
Integer flexibilityPowerSource = 0;
Integer minimumProductionCapacityPowerSource = 0;
Integer maximumProductionCapacityPowerSource = 0;
Integer currentProductionPowerSource = 0;
boolean checkFlagForCoordinator = false;
if(holonObjectListByConnectedPowerLines .size() == 0 && holonCoordinator.getIsCoordinator()) {
holonObjectListByConnectedPowerLines.add(holonCoordinator);
checkFlagForCoordinator = true;
} else if(holonObjectListByConnectedPowerLines.size() > 0) {
for(HolonObject holonObject : holonObjectListByConnectedPowerLines) {
if(holonObject.getId() == holonCoordinator.getId()) {
checkFlagForCoordinator = true;
}
}
}
if(!checkFlagForCoordinator) {
if(holonCoordinator.getIsCoordinator()) {
holonObjectListByConnectedPowerLines.add(holonCoordinator);
}
}
noOfHolonObjects = holonObjectListByConnectedPowerLines.size();
Map<String, Integer> holonObjectEnergyDetails = null;
holonObjectList.append("<option value=\"Select Holon\" id= \"infoWinOpt\" selected>Select Holon Object</option>");
for(HolonObject holonObject : holonObjectListByConnectedPowerLines) {
holonObjectEnergyDetails = getHolonObjectEnergyDetails(holonObject);
minimumProductionCapacityHolon = minimumProductionCapacityHolon + holonObjectEnergyDetails.get("minimumProductionCapacity");
maximumProductionCapacityHolon = maximumProductionCapacityHolon + holonObjectEnergyDetails.get("maximumProductionCapacity");
currentProductionHolon = currentProductionHolon + holonObjectEnergyDetails.get("currentProduction");
minimumEnergyRequiredHolon = minimumEnergyRequiredHolon + holonObjectEnergyDetails.get("minimumEnergyRequired");
maximumEnergyRequiredHolon = maximumEnergyRequiredHolon + holonObjectEnergyDetails.get("maximumEnergyRequired");
currentEnergyRequiredHolon = currentEnergyRequiredHolon + holonObjectEnergyDetails.get("currentEnergyRequired");
if(holonObjectEnergyDetails.get("currentEnergyRequired") > 0) {
holonObjectList.append("<option value="+holonObject.getId()+" id= \"infoWinOpt\">"+holonObject.getHolonObjectType().getName()+
" (Id:"+holonObject.getId()+") - Requires "+holonObjectEnergyDetails.get("currentEnergyRequired")+" energy</option>");
} else {
holonObjectList.append("<option value="+holonObject.getId()+" id= \"infoWinOpt\">"+holonObject.getHolonObjectType().getName()+
" (Id:"+holonObject.getId()+")"+"</option>");
}
originalEnergyRequiredHolon = originalEnergyRequiredHolon + holonObjectEnergyDetails.get("originalEnergyRequired");
flexibilityHolon = flexibilityHolon + holonObject.getFlexibility();
}
//Code to get connected Power Sources
ArrayList<PowerSource> listConnectedPowerSources = getPowerSourceListByConnectedPowerLines(powerLine, holonCoordinator);
for(PowerSource powerSource : listConnectedPowerSources) {
flexibilityPowerSource = flexibilityPowerSource + powerSource.getFlexibility();
minimumProductionCapacityPowerSource = minimumProductionCapacityPowerSource + powerSource.getMinProduction();
maximumProductionCapacityPowerSource = maximumProductionCapacityPowerSource + powerSource.getMaxProduction();
currentProductionPowerSource = currentProductionPowerSource + powerSource.getCurrentProduction();
}
//Adding power source details to the holon.
flexibilityHolon = flexibilityHolon + flexibilityPowerSource;
minimumProductionCapacityHolon = minimumProductionCapacityHolon + minimumProductionCapacityPowerSource;
maximumProductionCapacityHolon = maximumProductionCapacityHolon + maximumProductionCapacityPowerSource;
currentProductionHolon = currentProductionHolon + currentProductionPowerSource;
holonEnergyDetails.put("noOfHolonObjects", noOfHolonObjects.toString());
holonEnergyDetails.put("minimumProductionCapacityHolon", minimumProductionCapacityHolon.toString());
holonEnergyDetails.put("maximumProductionCapacityHolon", maximumProductionCapacityHolon.toString());
holonEnergyDetails.put("currentProductionHolon", currentProductionHolon.toString());
holonEnergyDetails.put("minimumEnergyRequiredHolon", minimumEnergyRequiredHolon.toString());
holonEnergyDetails.put("maximumEnergyRequiredHolon", maximumEnergyRequiredHolon.toString());
holonEnergyDetails.put("currentEnergyRequiredHolon", currentEnergyRequiredHolon.toString());
holonEnergyDetails.put("originalEnergyRequiredHolon", originalEnergyRequiredHolon.toString());
holonEnergyDetails.put("flexibilityHolon", flexibilityHolon.toString());
holonEnergyDetails.put("holonObjectList", holonObjectList.toString());
return holonEnergyDetails;
}
/**
* This method checks whether a power line is connected to a holon object or a power source or not and returns the status as true or false.
* @param connectedPowerLines Array list of connected power lines
* @param powerLine Object of powerLine POJO for which we need to check the connected status
* @return boolean connected status as true or false.
*/
public boolean checkConnectedStatusForLine(ArrayList<PowerLine> connectedPowerLines, PowerLine powerLine) {
if(powerLine.getType().equals(ConstantValues.SUBLINE) || powerLine.getType().equals(ConstantValues.POWERSUBLINE)) {
return true;
} else {
for(PowerLine powerLine2 : connectedPowerLines) {
if(powerLine2.getType().equals(ConstantValues.SUBLINE) ||powerLine2.getType().equals(ConstantValues.POWERSUBLINE) ) {
return true;
}
}
}
return false;
}
/**
* This method takes LatLng object as a parameter and then stores it in database if there is no latitude and longitude of the same location.
* Otherwise, it just returns the already existing LatLng object and does not create a new one in database.
* This is to avoid duplicate entries in database.
* @param locationToSave The location to be saved in database.
* @return location ID or the id of LatLng object (either a new one or an existing one)
*/
public Integer saveLocation(LatLng locationToSave) {
Integer locationid=0;
Double lat =locationToSave.getLatitude();
Double lng =locationToSave.getLongitude();
ArrayList<LatLng> locationList=getLatLngService().findByLocation(lat,lng);
log.info("Size of latLng Object list is "+locationList);
if(locationList.size()==0) {
log.info("Location is not in database ");
locationid=getLatLngService().persist(locationToSave);
} else {
log.info("Location is already in database ");
LatLng location = locationList.get(0);
locationid=location.getId();
}
return locationid;
}
/**
* This method takes powerline ID as an input and finds all connected power lines.
* This method is used by almost all modules like dynamic holon, dissolve holon, distribute holon energy, leadership election for holon coordinator etc...
* @param powerLineId ID of the power line for which we want to calculate connected power lines.
* @return Array list of connected power lines.
*/
public ArrayList<PowerLine> connectedPowerLines(Integer powerLineId) {
PowerLine powerLine = null;
if(powerLineId.compareTo(0) > 0 ){
powerLine = getPowerLineService().findById(powerLineId);
}
ArrayList<PowerLine> connectedPowerLines = new ArrayList<PowerLine>();
ArrayList<PowerLine> removeIndexListA = new ArrayList<PowerLine>();
ArrayList<PowerLine> removeIndexListB = new ArrayList<PowerLine>();
if(!(powerLine == null)) {
connectedPowerLines = getPowerLineService().getConnectedPowerLines(powerLine);
}
PowerLine powerLine2 = null;
PowerSwitch powerSwitch = null;
for(int i =0; i< connectedPowerLines.size();i++) {
powerLine2 = connectedPowerLines.get(i);
powerSwitch = getPowerSwitchService().checkSwitchStatusBetweenPowerLines(powerLine, powerLine2);
if(!(powerSwitch == null)){
if(!powerSwitch.getStatus()) {
removeIndexListA.add(powerLine2);
}
}
}
for(int i=0; i<removeIndexListA.size();i++) {
connectedPowerLines.remove(removeIndexListA.get(i));
}
for(PowerLine powerLine3 : connectedPowerLines) {
if(!(listOfAllConnectedPowerLines.containsKey(powerLine3.getId()))) {
listOfAllConnectedPowerLines.put(powerLine3.getId(), powerLine3);
listOfAllNeighbouringConnectedPowerLines.add(powerLine3);
}
}
for(PowerLine powerLine3 : connectedPowerLines) {
ArrayList<PowerLine> tempConnectedPowerLines = getPowerLineService().getConnectedPowerLines(powerLine3);
int indexToRemove = -1;
for(int i=0; i<tempConnectedPowerLines.size(); i++) {
PowerLine powerLine4 = tempConnectedPowerLines.get(i);
if(powerLine4.getId().equals(powerLineId)) {
indexToRemove = i;
}
}
if(indexToRemove>= 0 ) {
tempConnectedPowerLines.remove(indexToRemove);
}
PowerLine powerLineTemp = null;
PowerSwitch powerSwitchTemp = null;
for(int i =0; i< tempConnectedPowerLines.size();i++) {
powerLineTemp = tempConnectedPowerLines.get(i);
powerSwitchTemp = getPowerSwitchService().checkSwitchStatusBetweenPowerLines(powerLine3, powerLineTemp);
if(!(powerSwitchTemp == null)) {
if(!powerSwitchTemp.getStatus()) {
removeIndexListB.add(powerLineTemp);
}
}
}
for(int i=0; i<removeIndexListB.size();i++) {
tempConnectedPowerLines.remove(removeIndexListB.get(i));
}
for(PowerLine powerLine4 : tempConnectedPowerLines) {
if(!(listOfAllConnectedPowerLines.containsKey(powerLine4.getId()))) {
connectedPowerLines(powerLine3.getId());//Recursive call to get list of neighbors of neighbor
}
}
}
return listOfAllNeighbouringConnectedPowerLines;
}
/**
* This method updates all connected holon objects and power sources and is called whenever:
* 1 - Holon Object is added to a main line.
* 2 - Power Source is added to a main line.
* 3 - Switch is toggled.
* 4 - Power source is toggled.
* 5 - Power source is edited.
* 6 - Holon Element is deleted from a holon object.
* 7 - Holon Element is edited in such a way that its current capacity is less than the previous current capacity.
* @param powerLineId ID of the power line for which we want to update the connected holon objects and power sources.
*/
public void updateHolonObjectsAndPowerSources(Integer powerLineId) {
PowerLine powerLine = getPowerLineService().findById(powerLineId);
String powerLineType = powerLine.getType();
PowerSource immediatePowerSource = null;
HolonObject immediateHolonObject = null;
Integer immediateHolonObjectId = 0;
Holon existingHolon = null;
if(powerLineType.equals(ConstantValues.SUBLINE)) {
immediateHolonObject = powerLine.getHolonObject();
immediateHolonObjectId = immediateHolonObject.getId();
} else if(powerLineType.equals(ConstantValues.POWERSUBLINE)) {
immediatePowerSource = powerLine.getPowerSource();
}
ArrayList<PowerLine> connectedPowerLines = connectedPowerLines(powerLineId);
for(PowerLine powerLine2 : connectedPowerLines) {
powerLineType = powerLine2.getType();
if(powerLineType.equals(ConstantValues.SUBLINE)) {
if(powerLine2.getHolonObject() != null && powerLine2.getHolonObject().getHolon() != null){
existingHolon = powerLine2.getHolonObject().getHolon();
}
//Condition to set holon coordinator for the newly joined holon object
if(immediateHolonObject != null && immediateHolonObject.getIsCoordinator() == false) {
if(powerLine2.getHolonObject().getIsCoordinator().booleanValue() == true) {
immediateHolonObject.setIsCoordinator(false);
immediateHolonObject.setHolon(powerLine2.getHolonObject().getHolon());
getHolonObjectService().merge(immediateHolonObject);
}
}
//Condition to set holon coordinator for the newly joined power source
if(immediatePowerSource != null && immediatePowerSource.getHolonCoordinator() == null) {
if(powerLine2.getHolonObject().getIsCoordinator().booleanValue() == true) {
immediatePowerSource.setHolonCoordinator(powerLine2.getHolonObject());
getPowerSourceService().merge(immediatePowerSource);
}
}
} else if(powerLineType.equals(ConstantValues.POWERSUBLINE)) {
if(powerLine2.getPowerSource() != null && powerLine2.getPowerSource().getHolonCoordinator() != null
&& powerLine2.getPowerSource().getHolonCoordinator().getHolon() != null){
existingHolon = powerLine2.getPowerSource().getHolonCoordinator().getHolon();
}
//Condition to set holon coordinator for the newly joined holon object
if(immediateHolonObject != null && immediateHolonObject.getIsCoordinator().booleanValue() == false) {
if(powerLine2.getPowerSource().getHolonCoordinator() != null) {
immediateHolonObject.setIsCoordinator(false);
immediateHolonObject.setHolon(powerLine2.getPowerSource().getHolonCoordinator().getHolon());
getHolonObjectService().merge(immediateHolonObject);
}
}
//Condition to set holon coordinator for the newly joined power source
if(immediatePowerSource != null && immediatePowerSource.getHolonCoordinator() == null) {
if(powerLine2.getPowerSource().getHolonCoordinator() != null) {
immediatePowerSource.setHolonCoordinator(powerLine2.getPowerSource().getHolonCoordinator());
getPowerSourceService().merge(immediatePowerSource);
}
}
}
}//End of parent for loop
immediateHolonObject = getHolonObjectService().findById(immediateHolonObjectId);
/*Checking whether a holon coordinator has been assigned to the newly joined holon object or not.
* If not, set a random holon and make this the new holon coordinator of that holon.*/
if(immediateHolonObject != null && immediateHolonObject.getHolon() == null) {
Integer randomHolonId = randomNumber(1, 4);
Holon randomHolon = getHolonService().findById(randomHolonId);
if(existingHolon != null) {
immediateHolonObject.setHolon(existingHolon);
} else {
immediateHolonObject.setHolon(randomHolon);
}
immediateHolonObject.setIsCoordinator(true);
getHolonObjectService().merge(immediateHolonObject);
}
//Code to assign holonCoordinator to already existing power source
for(PowerLine powerLine2 : connectedPowerLines) {
if(powerLine2.getPowerSource() != null && powerLine2.getPowerSource().getHolonCoordinator() == null) {
Holon holon = null;
immediateHolonObject = getHolonObjectService().findById(immediateHolonObjectId);
if(immediateHolonObject != null && immediateHolonObject.getHolon() != null) {
holon = immediateHolonObject.getHolon();
HolonObject holonCoordinator = findConnectedHolonCoordinatorByHolon(holon, powerLine2);
PowerSource powerSource = powerLine2.getPowerSource();
powerSource.setHolonCoordinator(holonCoordinator);
getPowerSourceService().merge(powerSource);
}
}
}
}
/**
* This method finds a random integer value between two integers passed as parameter.
* @param min Minimum value of the random integer
* @param max Maximum value of the random integer
* @return Random integer value between 1st and 2nd parameter.
*/
public int randomNumber(int min, int max) {
return (min + (int)(Math.random()*((max-min)+1)));
}
/**
* This method finds all connected holon objects to a single holon object
* @param powerLine This is the object of powerLine POJO and power line type is MAINLINE
* @param holonObject The holon object for which we want to find other connected holon objects
* @return ArrayList of connected holon objects
*/
public ArrayList<HolonObject> getHolonObjectListByConnectedPowerLines(PowerLine powerLine, HolonObject holonObject) {
ArrayList<HolonObject> connectedHolonObjects = new ArrayList<HolonObject>();
Integer powerLineId = 0;
ArrayList<PowerLine> connectedPowerLines = new ArrayList<PowerLine>();
if(powerLine != null) {
powerLineId = powerLine.getId();
connectedPowerLines = new CommonUtilities().connectedPowerLines(powerLineId);
}
for(PowerLine powerLine2 : connectedPowerLines) {
if(powerLine2.getType().equalsIgnoreCase(ConstantValues.SUBLINE)) {
if(powerLine2.getHolonObject() != null && powerLine2.getHolonObject().getHolon()!= null && holonObject != null &&holonObject.getHolon() != null &&
powerLine2.getHolonObject().getHolon().getId() == holonObject.getHolon().getId()) {
connectedHolonObjects.add(powerLine2.getHolonObject());
}
}
}
return connectedHolonObjects;
}
/**
* This method finds list of all power sources connected to a power line and of a particular holon represented by the 2nd parameter (holonObject).
* @param powerLine Power line object for which we need to find the connected power sources.
* @param holonObject The holon object which is used to find only those power sources which have the same holon as this holon object.
* @return Array list of power sources
*/
public ArrayList<PowerSource> getPowerSourceListByConnectedPowerLines(PowerLine powerLine, HolonObject holonObject) {
ArrayList<PowerSource> connectedPowerSources = new ArrayList<PowerSource>();
Integer powerLineId = powerLine!= null?powerLine.getId():null;
ArrayList<PowerLine> connectedPowerLines = powerLineId!=null?connectedPowerLines(powerLineId):new ArrayList<PowerLine>();
for(PowerLine powerLine2 : connectedPowerLines) {
if(powerLine2.getType().equalsIgnoreCase(ConstantValues.POWERSUBLINE)) {
if(powerLine2.getPowerSource().getStatus() && powerLine2.getPowerSource().getHolonCoordinator()!=null && powerLine2.getPowerSource().
getHolonCoordinator().getHolon() != null && holonObject.getHolon() != null && powerLine2.getPowerSource().getHolonCoordinator().getHolon().getId()
== holonObject.getHolon().getId()) {
connectedPowerSources.add(powerLine2.getPowerSource());
}
}
}
return connectedPowerSources;
}
/**
* This method checks whether two holon objects are connected or not.
* @param holonObjectA 1st holon object for which we need to check the connectivity.
* @param holonObjectB 2nd holon object for which we need to check the connectivity.
* @return Connectivity status in the form of true or false.
*/
public boolean checkConnectivityBetweenHolonObjects(HolonObject holonObjectA, HolonObject holonObjectB) {
Integer powerLineIdA = holonObjectA.getHolon()!=null?getPowerLineService().getPowerLineByHolonObject(holonObjectA).getId():null;
Integer holonObjectBId = holonObjectB.getId();
ArrayList<PowerLine> connectedPowerLines = powerLineIdA != null?connectedPowerLines(powerLineIdA):null;
if(connectedPowerLines != null) {
for(PowerLine powerLine2 : connectedPowerLines) {
if(powerLine2.getType().equalsIgnoreCase(ConstantValues.SUBLINE)) {
if(holonObjectBId.equals(powerLine2.getHolonObject().getId())) {
return true;
}
}
}
}
return false;
}
/**
* This method checks whether a holon object and a power source are connected or not.
* @param holonObject The holon object that needs to be checked for connectivity.
* @param powerSource The power source that needs to be checked for connectivity.
* @return Connectivity status in the form of true or false.
*/
public boolean checkConnectivityBetweenHolonObjectAndPowerSource(HolonObject holonObject, PowerSource powerSource) {
Integer powerLineId = getPowerLineService().getPowerLineByHolonObject(holonObject).getId();
Integer powerSourceId = powerSource.getId();
ArrayList<PowerLine> connectedPowerLines = connectedPowerLines(powerLineId);
for(PowerLine powerLine : connectedPowerLines) {
if(powerLine.getType().equalsIgnoreCase(ConstantValues.POWERSUBLINE)) {
if(powerLine.getPowerSource().getStatus() && powerSourceId.equals(powerLine.getPowerSource().getId())) {
return true;
}
}
}
return false;
}
/**
* This method calculates the flexibility and current energy required by a holon object by checking all possible scenarios.
* @param holonObject The holon object for which calculation needs to be done.
* @param currentEnergyRequired Current energy originally required by the holon object.
* @return Map containing values for flexibility and currentEnergyRequired.
*/
public Map<String, Integer> getFlexibilityAndCurrentEnergyRequirementOfHolonObject(HolonObject holonObject, Integer currentEnergyRequired) {
Map<String, Integer> flexibilityAndCurrentEnergyRequiredMap = new TreeMap<String, Integer>();
Integer originalEnergyRequired = 0;
Integer currentProduction=0;
Integer flexibility = 0;
ArrayList<HolonElement> holonElementList= getHolonElementService().getHolonElements(holonObject);
for(HolonElement holonElement : holonElementList) {
if(holonElement.getHolonElementType().getProducer()) {
if(holonElement.getHolonElementState().getId()==1) {
currentProduction = currentProduction + holonElement.getCurrentCapacity();
}
} else {
if(holonElement.getHolonElementState().getId()==1) {
originalEnergyRequired = originalEnergyRequired+holonElement.getCurrentCapacity();
}
}
}
flexibility = currentProduction;
if(originalEnergyRequired > 0) {
if(currentProduction > 0 && currentProduction > originalEnergyRequired) {
flexibility = currentProduction - originalEnergyRequired;
} else if (currentProduction > 0 && currentProduction <= originalEnergyRequired) {
flexibility = 0;
}
}
//Scenario from producer's perspective
ArrayList<Supplier> supplierListForProducer = getSupplierService().getSupplierListForProducer(holonObject);
for(Supplier supplier : supplierListForProducer) {
if(!checkConnectivityBetweenHolonObjects(holonObject, supplier.getHolonObjectConsumer())
&& supplier.getMessageStatus().equals(ConstantValues.ACCEPTED)) {
supplier.setMessageStatus(ConstantValues.CONNECTION_RESET);
getSupplierService().merge(supplier);
}
if(checkConnectivityBetweenHolonObjects(holonObject, supplier.getHolonObjectConsumer())) {
if(supplier.getMessageStatus().equalsIgnoreCase(ConstantValues.ACCEPTED)) {
if(flexibility >= supplier.getPowerGranted()) {
flexibility = flexibility - supplier.getPowerGranted();
} else {
flexibility = 0;
}
}
}
}
//Scenario from consumer's perspective
ArrayList<Supplier> supplierListForConsumer = getSupplierService().getSupplierListForConsumer(holonObject);
for(Supplier supplier : supplierListForConsumer) {
if(supplier.getHolonObjectProducer() != null) {
if(!checkConnectivityBetweenHolonObjects(holonObject, supplier.getHolonObjectProducer())
&& supplier.getMessageStatus().equals(ConstantValues.ACCEPTED)) {
supplier.setMessageStatus(ConstantValues.CONNECTION_RESET);
getSupplierService().merge(supplier);
}
if(checkConnectivityBetweenHolonObjects(holonObject, supplier.getHolonObjectProducer())) {
if(supplier.getMessageStatus().equalsIgnoreCase(ConstantValues.ACCEPTED)) {
if(currentEnergyRequired >= supplier.getPowerGranted()) {
currentEnergyRequired = currentEnergyRequired - supplier.getPowerGranted();
} else {
currentEnergyRequired = 0;
}
}
}
} else if(supplier.getPowerSource() != null) {
if(!checkConnectivityBetweenHolonObjectAndPowerSource(holonObject, supplier.getPowerSource())
&& supplier.getMessageStatus().equals(ConstantValues.ACCEPTED)) {
supplier.setMessageStatus(ConstantValues.CONNECTION_RESET);
getSupplierService().merge(supplier);
PowerSource powerSource = supplier.getPowerSource();
powerSource.setFlexibility(powerSource.getFlexibility() + supplier.getPowerGranted());
getPowerSourceService().merge(powerSource);
}
if(checkConnectivityBetweenHolonObjectAndPowerSource(holonObject, supplier.getPowerSource())) {
if(supplier.getMessageStatus().equalsIgnoreCase(ConstantValues.ACCEPTED)) {
if(currentEnergyRequired >= supplier.getPowerGranted()) {
currentEnergyRequired = currentEnergyRequired - supplier.getPowerGranted();
} else {
currentEnergyRequired = 0;
}
}
}
}
}
holonObject.setFlexibility(flexibility);
getHolonObjectService().merge(holonObject);
flexibilityAndCurrentEnergyRequiredMap.put("flexibility", flexibility);
flexibilityAndCurrentEnergyRequiredMap.put("currentEnergyRequired", currentEnergyRequired);
return flexibilityAndCurrentEnergyRequiredMap;
}
/**
* This method finds the connected holon coordinator of the holon passed as parameter. Calculation are based on the power line object passed as 2nd parameter.
* @param holon The holon for which we need to find the holon coordinator.
* @param powerLine The power line object which is used to find the connected holon coordinator.
* @return Connected holon coordinator
*/
public HolonObject findConnectedHolonCoordinatorByHolon(Holon holon, PowerLine powerLine) {
HolonObject holonCoordinator = null;
Integer powerLineId = powerLine!=null?powerLine.getId():0;
ArrayList<PowerLine> connectedPowerLines = connectedPowerLines(powerLineId);
for(PowerLine powerLine2 : connectedPowerLines) {
if(powerLine2.getType().equalsIgnoreCase(ConstantValues.SUBLINE)) {
HolonObject tempHolonObject = powerLine2.getHolonObject();
if(tempHolonObject != null && tempHolonObject.getHolon() != null && tempHolonObject.getHolon().getId() == holon.getId()
&& tempHolonObject.getIsCoordinator() == true ) {
holonCoordinator = tempHolonObject;
return holonCoordinator;
}
}
}
return holonCoordinator;
}
/**
* This method is used to find the new holon coordinator by using leadership election algorithm.
* @param powerLine The power line which is used to find connected holon objects.
* @param holonObject The holon object which wants to be a part of leadership election for holon coordinator.
* @return The new holon coordinator
*/
public HolonObject getHolonCoordinatorByElectionUsingPowerLineId(PowerLine powerLine, HolonObject holonObject){
ArrayList<HolonObject> connectedholonObject = new ArrayList<HolonObject>();
HolonObject newCoordinator= null;
BigDecimal coordinatorCompetency;
BigDecimal trustValue;
BigDecimal maxValue = new BigDecimal(0.00);
BigDecimal currentValue ;
MathContext mc = new MathContext(2);
connectedholonObject = getHolonObjectListByConnectedPowerLines(powerLine, holonObject);
//Adding own holon object to connected list for leadership election
if(holonObject != null){
connectedholonObject.add(holonObject);
}
for(int j=0;j<connectedholonObject.size();j++)
{
if(connectedholonObject.size() > 0){
coordinatorCompetency= connectedholonObject.get(j).getCoordinatorCompetency();
trustValue=connectedholonObject.get(j).getTrustValue();
currentValue=coordinatorCompetency.multiply(trustValue,mc);
if(maxValue.compareTo(currentValue) == -1){
// -1 means 2nd value is greater
maxValue=currentValue;
newCoordinator= connectedholonObject.get(j);
}
}
}
for(int k=0;k<connectedholonObject.size();k++){
if(connectedholonObject.size() > 0){
if(connectedholonObject.get(k).getId() == newCoordinator.getId()){
//Set isCoordinator true
newCoordinator.setIsCoordinator(true);
getHolonObjectService().merge(newCoordinator);
}
else{
HolonObject tempHolonObject = connectedholonObject.get(k);
//Set isCoordinator false
tempHolonObject.setIsCoordinator(false);
getHolonObjectService().merge(tempHolonObject);
}
}
}
return newCoordinator;
}
/**
* This method calculates list of new and old coordinators when a main line is connected to another main line or when a switch is toggled.
* @param powerLine The power line object which is used for connectivity purpose.
* @param status The status value to find which method to call as there are two methods which perform the same function.
* @return Array list of new and old holon coordinators.
*/
public Map<String, ArrayList<HolonObject>> getHolonCoordinatorByElectionUsingForMainLineAndSwitch(PowerLine powerLine, String status){
Map<String, ArrayList<HolonObject>> mapOfNewAndOldCoordinators = new TreeMap<String, ArrayList<HolonObject>>();
ArrayList<HolonObject> connectedHolonObjectsOfAllHolons = getHolonObjectListByConnectedPowerLinesOfAllHolons(powerLine, status);
Map<String, ArrayList<HolonObject>> mapOfHolonCoordinatorsOfAllHolons = getHolonCoordinatorsOfAllHolons(connectedHolonObjectsOfAllHolons);
ArrayList<HolonObject> newCoordinators = new ArrayList<HolonObject>();
ArrayList<HolonObject> oldCoordinators = new ArrayList<HolonObject>();
ArrayList<HolonObject> redHolonCoordinatorsList = mapOfHolonCoordinatorsOfAllHolons.get("redCoordinators");
ArrayList<HolonObject> yellowHolonCoordinatorsList = mapOfHolonCoordinatorsOfAllHolons.get("yellowCoordinators");
ArrayList<HolonObject> blueHolonCoordinatorsList = mapOfHolonCoordinatorsOfAllHolons.get("blueCoordinators");
ArrayList<HolonObject> greenHolonCoordinatorsList = mapOfHolonCoordinatorsOfAllHolons.get("greenCoordinators");
//Holon Coordinator leadership election for RED holon.
if(redHolonCoordinatorsList.size() > 1) {
HolonObject coordinator1 = redHolonCoordinatorsList.get(0);
HolonObject coordinator2 = redHolonCoordinatorsList.get(1);
BigDecimal competencyTrust1 = coordinator1.getCoordinatorCompetency().multiply(coordinator1.getTrustValue());
BigDecimal competencyTrust2 = coordinator2.getCoordinatorCompetency().multiply(coordinator2.getTrustValue());
if(competencyTrust1.compareTo(competencyTrust2) == -1) {
newCoordinators.add(coordinator2);
oldCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(false);
getHolonObjectService().merge(coordinator1);
} else {
newCoordinators.add(coordinator1);
oldCoordinators.add(coordinator2);
coordinator2.setIsCoordinator(false);
getHolonObjectService().merge(coordinator2);
}
} else if(redHolonCoordinatorsList.size() == 1) {
HolonObject coordinator1 = redHolonCoordinatorsList.get(0);
newCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(true);
getHolonObjectService().merge(coordinator1);
}
//Holon Coordinator leadership election for BLUE holon.
if(blueHolonCoordinatorsList.size() > 1) {
HolonObject coordinator1 = blueHolonCoordinatorsList.get(0);
HolonObject coordinator2 = blueHolonCoordinatorsList.get(1);
BigDecimal competencyTrust1 = coordinator1.getCoordinatorCompetency().multiply(coordinator1.getTrustValue());
BigDecimal competencyTrust2 = coordinator2.getCoordinatorCompetency().multiply(coordinator2.getTrustValue());
if(competencyTrust1.compareTo(competencyTrust2) == -1) {
newCoordinators.add(coordinator2);
oldCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(false);
getHolonObjectService().merge(coordinator1);
} else {
newCoordinators.add(coordinator1);
oldCoordinators.add(coordinator2);
coordinator2.setIsCoordinator(false);
getHolonObjectService().merge(coordinator2);
}
} else if(blueHolonCoordinatorsList.size() == 1) {
HolonObject coordinator1 = blueHolonCoordinatorsList.get(0);
newCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(true);
getHolonObjectService().merge(coordinator1);
}
//Holon Coordinator leadership election for GREEN holon.
if(greenHolonCoordinatorsList.size() > 1) {
HolonObject coordinator1 = greenHolonCoordinatorsList.get(0);
HolonObject coordinator2 = greenHolonCoordinatorsList.get(1);
BigDecimal competencyTrust1 = coordinator1.getCoordinatorCompetency().multiply(coordinator1.getTrustValue());
BigDecimal competencyTrust2 = coordinator2.getCoordinatorCompetency().multiply(coordinator2.getTrustValue());
if(competencyTrust1.compareTo(competencyTrust2) == -1) {
newCoordinators.add(coordinator2);
oldCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(false);
getHolonObjectService().merge(coordinator1);
} else {
newCoordinators.add(coordinator1);
oldCoordinators.add(coordinator2);
coordinator2.setIsCoordinator(false);
getHolonObjectService().merge(coordinator2);
}
} else if(greenHolonCoordinatorsList.size() == 1) {
HolonObject coordinator1 = greenHolonCoordinatorsList.get(0);
newCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(true);
getHolonObjectService().merge(coordinator1);
}
//Holon Coordinator leadership election for YELLOW holon.
if(yellowHolonCoordinatorsList.size() > 1) {
HolonObject coordinator1 = yellowHolonCoordinatorsList.get(0);
HolonObject coordinator2 = yellowHolonCoordinatorsList.get(1);
BigDecimal competencyTrust1 = coordinator1.getCoordinatorCompetency().multiply(coordinator1.getTrustValue());
BigDecimal competencyTrust2 = coordinator2.getCoordinatorCompetency().multiply(coordinator2.getTrustValue());
if(competencyTrust1.compareTo(competencyTrust2) == -1) {
newCoordinators.add(coordinator2);
oldCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(false);
getHolonObjectService().merge(coordinator1);
} else {
newCoordinators.add(coordinator1);
oldCoordinators.add(coordinator2);
coordinator2.setIsCoordinator(false);
getHolonObjectService().merge(coordinator2);
}
} else if(yellowHolonCoordinatorsList.size() == 1) {
HolonObject coordinator1 = yellowHolonCoordinatorsList.get(0);
newCoordinators.add(coordinator1);
coordinator1.setIsCoordinator(true);
getHolonObjectService().merge(coordinator1);
}
mapOfNewAndOldCoordinators.put("newCoordinators", newCoordinators);
mapOfNewAndOldCoordinators.put("oldCoordinators", oldCoordinators);
return mapOfNewAndOldCoordinators;
}
/**
* This method finds connected holon objects of all holons(red, blue, green and yellow).
* @param powerLine The power line object which is used to check the connectivity.
* @param status The status value to find which method to call as there are two methods which perform the same function.
* @return Array list of connected holon objects of all holons.
*/
public ArrayList<HolonObject> getHolonObjectListByConnectedPowerLinesOfAllHolons(PowerLine powerLine, String status) {
ArrayList<HolonObject> connectedHolonObjectsOfAllHolons = new ArrayList<HolonObject>();
Integer powerLineId = 0;
ArrayList<PowerLine> connectedPowerLines = null;
if(powerLine != null) {
powerLineId = powerLine.getId();
if(status.equalsIgnoreCase("common")) {
connectedPowerLines = connectedPowerLines(powerLineId);
} else {
connectedPowerLines = new PowerSwitchAction().connectedPowerLines(powerLineId);
}
}
for(PowerLine powerLine2 : connectedPowerLines) {
if(powerLine2.getType().equalsIgnoreCase(ConstantValues.SUBLINE)) {
if(powerLine2.getHolonObject() != null) {
connectedHolonObjectsOfAllHolons.add(powerLine2.getHolonObject());
}
}
}
return connectedHolonObjectsOfAllHolons;
}
/**
* This method finds all Holon Coordinators of all holons(red, blue, green, yellow)
* @param connectedHolonObjectsOfAllHolons Aray list of all connected holon objects of all holons(red, blue, green, yellow).
* @return Map containing holon coordinators of all holons.
*/
public Map<String, ArrayList<HolonObject>> getHolonCoordinatorsOfAllHolons(ArrayList<HolonObject> connectedHolonObjectsOfAllHolons) {
Map<String, ArrayList<HolonObject>> mapOfCoordinatorsOfAllHolons= new TreeMap<String, ArrayList<HolonObject>>();
ArrayList<HolonObject> redHolonCoordinatorsList = new ArrayList<HolonObject>();
ArrayList<HolonObject> yellowHolonCoordinatorsList = new ArrayList<HolonObject>();
ArrayList<HolonObject> blueHolonCoordinatorsList = new ArrayList<HolonObject>();
ArrayList<HolonObject> greenHolonCoordinatorsList = new ArrayList<HolonObject>();
Boolean redFlag = false, yellowFlag = false, greenFlag = false, blueFlag = false;
for(HolonObject holonObject : connectedHolonObjectsOfAllHolons) {
if(holonObject.getHolon()!=null) {
if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_RED && holonObject.getIsCoordinator()) {
redHolonCoordinatorsList.add(holonObject);
redFlag = true;
} else if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_BLUE && holonObject.getIsCoordinator()) {
blueHolonCoordinatorsList.add(holonObject);
blueFlag = true;
} else if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_GREEN && holonObject.getIsCoordinator()) {
greenHolonCoordinatorsList.add(holonObject);
greenFlag = true;
} else if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_YELLOW && holonObject.getIsCoordinator()) {
yellowHolonCoordinatorsList.add(holonObject);
yellowFlag = true;
}
}
}
HolonObject newRedCoordinator = null;
HolonObject newBlueCoordinator = null;
HolonObject newGreenCoordinator = null;
HolonObject newYellowCoordinator = null;
for(HolonObject holonObject : connectedHolonObjectsOfAllHolons) {
BigDecimal redMaxValue = new BigDecimal(0.0);
BigDecimal redCurrentValue = new BigDecimal(0.0);
BigDecimal blueMaxValue = new BigDecimal(0.0);
BigDecimal blueCurrentValue = new BigDecimal(0.0);
BigDecimal greenMaxValue = new BigDecimal(0.0);
BigDecimal greenCurrentValue = new BigDecimal(0.0);
BigDecimal yellowMaxValue = new BigDecimal(0.0);
BigDecimal yellowCurrentValue = new BigDecimal(0.0);
//Condition for red holon
if(!redFlag) {
if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_RED) {
redCurrentValue = holonObject.getTrustValue().multiply(holonObject.getCoordinatorCompetency());
if(redMaxValue.compareTo(redCurrentValue) == -1) {
redMaxValue = redCurrentValue;
newRedCoordinator = holonObject;
}
}
}
//Condition for blue holon
if(!blueFlag) {
if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_BLUE) {
blueCurrentValue = holonObject.getTrustValue().multiply(holonObject.getCoordinatorCompetency());
if(blueMaxValue.compareTo(blueCurrentValue) == -1) {
blueMaxValue = blueCurrentValue;
newBlueCoordinator = holonObject;
}
}
}
//Condition for green holon
if(!greenFlag) {
if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_GREEN) {
greenCurrentValue = holonObject.getTrustValue().multiply(holonObject.getCoordinatorCompetency());
if(greenMaxValue.compareTo(greenCurrentValue) == -1) {
greenMaxValue = greenCurrentValue;
newGreenCoordinator = holonObject;
}
}
}
//Condition for yellow holon
if(!yellowFlag) {
if(holonObject.getHolon().getId() == ConstantValues.HOLON_CO_YELLOW) {
yellowCurrentValue = holonObject.getTrustValue().multiply(holonObject.getCoordinatorCompetency());
if(yellowMaxValue.compareTo(yellowCurrentValue) == -1) {
yellowMaxValue = yellowCurrentValue;
newYellowCoordinator = holonObject;
}
}
}
}
if(newRedCoordinator != null) {
redHolonCoordinatorsList.add(newRedCoordinator);
}
if(newBlueCoordinator != null) {
blueHolonCoordinatorsList.add(newBlueCoordinator);
}
if(newGreenCoordinator != null) {
greenHolonCoordinatorsList.add(newGreenCoordinator);
}
if(newYellowCoordinator != null) {
yellowHolonCoordinatorsList.add(newYellowCoordinator);
}
mapOfCoordinatorsOfAllHolons.put("redCoordinators", redHolonCoordinatorsList);
mapOfCoordinatorsOfAllHolons.put("blueCoordinators", blueHolonCoordinatorsList);
mapOfCoordinatorsOfAllHolons.put("greenCoordinators", greenHolonCoordinatorsList);
mapOfCoordinatorsOfAllHolons.put("yellowCoordinators", yellowHolonCoordinatorsList);
return mapOfCoordinatorsOfAllHolons;
}
/**
* This method finds all power line IDs that lie inside a disaster circle.
* @param latitudeOfCircle Latitude of the disaster circle.
* @param longitudeOfCircle Longitude of the disaster circle.
* @param radiusOfCircle Radius of the disaster circle.
* @return Map containing concerned power line IDs.
*/
public Map<Integer, PowerLine> getListOfAllPowerLineIdsInsideCircle(Double latitudeOfCircle,Double longitudeOfCircle,Double radiusOfCircle) {
ArrayList<LatLng> listOfAllLatLngIdsInsideCircle= getLatLngService().findAllLatLngInsideTheCircle(latitudeOfCircle, longitudeOfCircle, radiusOfCircle);
Map<Integer, PowerLine> mapOfAllPowerLinesInsideCircles = new TreeMap<Integer, PowerLine>();
for(LatLng latLng : listOfAllLatLngIdsInsideCircle){
ArrayList<PowerLine> powerLineListFromLatLng = getPowerLineService().getPowerLineFromLatLng(latLng);
for(PowerLine powerLine : powerLineListFromLatLng){
if(!mapOfAllPowerLinesInsideCircles.containsKey(powerLine.getId())) {
mapOfAllPowerLinesInsideCircles.put(powerLine.getId(), powerLine);
}
}
}
return mapOfAllPowerLinesInsideCircles;
}
} | [
"ritika.2734@gmail.com"
] | ritika.2734@gmail.com |
50711f916de32f68c6d3c79518aedab1b55ffb06 | ed9197f16e85df78f5596eb2223bbf654e21c264 | /application/src/main/java/org/thingsboard/server/controller/AlarmController.java | 7d29d57dc9dc450da8cf25000dedfcacc0c160a2 | [
"Apache-2.0"
] | permissive | kinbod/thingsboard | a6da307f4bb3129492dddaa2e5962560cd0ab8d6 | d2b7850d49c3148684c199f936593929209c958e | refs/heads/master | 2021-01-23T01:50:40.742750 | 2017-05-30T16:47:48 | 2017-05-30T16:47:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,733 | java | /**
* Copyright © 2016-2017 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.controller;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Event;
import org.thingsboard.server.common.data.alarm.Alarm;
import org.thingsboard.server.common.data.alarm.AlarmId;
import org.thingsboard.server.common.data.alarm.AlarmQuery;
import org.thingsboard.server.common.data.alarm.AlarmStatus;
import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.id.*;
import org.thingsboard.server.common.data.page.TextPageData;
import org.thingsboard.server.common.data.page.TextPageLink;
import org.thingsboard.server.common.data.page.TimePageData;
import org.thingsboard.server.common.data.page.TimePageLink;
import org.thingsboard.server.dao.asset.AssetSearchQuery;
import org.thingsboard.server.dao.exception.IncorrectParameterException;
import org.thingsboard.server.dao.model.ModelConstants;
import org.thingsboard.server.exception.ThingsboardErrorCode;
import org.thingsboard.server.exception.ThingsboardException;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api")
public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}", method = RequestMethod.GET)
@ResponseBody
public Alarm getAlarmById(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {
checkParameter("alarmId", strAlarmId);
try {
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
return checkAlarmId(alarmId);
} catch (Exception e) {
throw handleException(e);
}
}
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm", method = RequestMethod.POST)
@ResponseBody
public Alarm saveAlarm(@RequestBody Alarm alarm) throws ThingsboardException {
try {
alarm.setTenantId(getCurrentUser().getTenantId());
return checkNotNull(alarmService.createOrUpdateAlarm(alarm));
} catch (Exception e) {
throw handleException(e);
}
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/alarm/{alarmId}/ack", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void ackAlarm(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {
checkParameter("alarmId", strAlarmId);
try {
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
checkAlarmId(alarmId);
alarmService.ackAlarm(alarmId, System.currentTimeMillis()).get();
} catch (Exception e) {
throw handleException(e);
}
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/alarm/{alarmId}/clear", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void clearAlarm(@PathVariable("alarmId") String strAlarmId) throws ThingsboardException {
checkParameter("alarmId", strAlarmId);
try {
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
checkAlarmId(alarmId);
alarmService.clearAlarm(alarmId, System.currentTimeMillis()).get();
} catch (Exception e) {
throw handleException(e);
}
}
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{entityType}/{entityId}", method = RequestMethod.GET)
@ResponseBody
public TimePageData<Alarm> getAlarms(
@PathVariable("entityType") String strEntityType,
@PathVariable("entityId") String strEntityId,
@RequestParam(required = false) String status,
@RequestParam int limit,
@RequestParam(required = false) Long startTime,
@RequestParam(required = false) Long endTime,
@RequestParam(required = false, defaultValue = "false") boolean ascOrder,
@RequestParam(required = false) String offset
) throws ThingsboardException {
checkParameter("EntityId", strEntityId);
checkParameter("EntityType", strEntityType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strEntityType, strEntityId);
AlarmStatus alarmStatus = StringUtils.isEmpty(status) ? null : AlarmStatus.valueOf(status);
checkEntityId(entityId);
try {
TimePageLink pageLink = createPageLink(limit, startTime, endTime, ascOrder, offset);
return checkNotNull(alarmService.findAlarms(new AlarmQuery(entityId, pageLink, alarmStatus)).get());
} catch (Exception e) {
throw handleException(e);
}
}
}
| [
"ashvayka@thingsboard.io"
] | ashvayka@thingsboard.io |
e1f86f1e232adc7985df04cdb5772fd81b9c5754 | 38522d48fcf653e185d7f68369c1ecd715aa0868 | /app/src/main/java/com/apkprovider/verticalviewpager/verticalviewpager/ZoomOutTransformer.java | 8db0df54aec179a6d760b2ab038911d76db92c14 | [] | no_license | apkprovider/VerticalViewPager | 6a7fab79830530b55eb8f2d0e0674796f6125ce8 | 89b60b1f78550182f83f4337f40dfc5238454d1a | refs/heads/master | 2016-08-12T04:24:16.971077 | 2015-10-20T13:21:33 | 2015-10-20T13:21:33 | 44,603,648 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,332 | java | package com.apkprovider.verticalviewpager.verticalviewpager;
import android.support.v4.view.ViewPager;
import android.view.View;
public class ZoomOutTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.90f;
@Override
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
float alpha = 0;
if (0 <= position && position <= 1) {
alpha = 1 - position;
} else if (-1 < position && position < 0) {
float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
float verticalMargin = pageHeight * (1 - scaleFactor) / 2;
float horizontalMargin = pageWidth * (1 - scaleFactor) / 2;
if (position < 0) {
view.setTranslationX(horizontalMargin - verticalMargin / 2);
} else {
view.setTranslationX(-horizontalMargin + verticalMargin / 2);
}
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
alpha = position + 1;
}
view.setAlpha(alpha);
view.setTranslationX(view.getWidth() * -position);
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);
}
}
| [
"krishnakumar@WS-AND-004.in.webmyne.com"
] | krishnakumar@WS-AND-004.in.webmyne.com |
1ef2a886dd0df1fe545edc102fa7981d4e496898 | 7cda529581c206fd8201b6120b304bc11b6d3f2a | /src/core/model/units/BigUnit.java | 8b9270a7d7dfa092b8bc72e9901f60653f9e263d | [] | no_license | johan-gras/Castle-Rush | afa96ae564895d0c612fb907b5eaf7e49d54ecb7 | 8d1bf74ad70b86646486912704dd7593da3a71dc | refs/heads/master | 2020-05-30T10:59:29.812858 | 2019-06-06T18:37:47 | 2019-06-06T18:37:47 | 189,686,607 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 627 | java | package core.model.units;
import com.badlogic.gdx.math.Vector2;
import core.model.Unit;
public class BigUnit extends Unit {
private static final float SIZE = 1f;
private Unit unitLink;
/**
* Constructeur
* @param position
* @param unitLink
*/
public BigUnit(Vector2 position, Unit unitLink) {
super(position);
this.unitLink = unitLink;
}
@Override
public void update(float delta) {
// TODO Auto-generated method stub
}
public float getSize() {
return SIZE;
}
public Unit getUnitLink() {
return unitLink;
}
public void setUnitLink(Unit unitLink) {
this.unitLink = unitLink;
}
}
| [
"johan.gras-sub@outlook.com"
] | johan.gras-sub@outlook.com |
4760610195ae3be1a85487fbf0c2f5b3b53fad82 | b67ebace5d76d36324f04fc7c4ec4a3b9faa161e | /Java_Workspace/hibernate_assignment/src/main/java/com/capgemini/hibernate/assignment/JpqlReadDynamic.java | 01fb2783d40c61c85c9ebf3b5c909d2c0ef75b31 | [] | no_license | NarendraMaganti/demo | 11d8d5453a9ed595e59af9444d907ad9e1810434 | 3a0eb163cf52d2fff89f07b3e5e5fac3dd6a524c | refs/heads/master | 2022-12-22T18:59:42.947102 | 2020-03-27T16:01:08 | 2020-03-27T16:01:08 | 238,342,840 | 0 | 0 | null | 2022-12-15T23:58:21 | 2020-02-05T01:24:15 | Java | UTF-8 | Java | false | false | 806 | java | package com.capgemini.hibernate.assignment;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import com.capgemini.hibernate.assignment.dto.Emp_primary_info;
public class JpqlReadDynamic {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test1");
EntityManager manager = factory.createEntityManager();
String jpql = "select e from Emp_primary_info e where e.emp_id=:no";
TypedQuery<Emp_primary_info> query = manager.createQuery(jpql, Emp_primary_info.class);
query.setParameter("no", 104);
Emp_primary_info record = query.getSingleResult();
System.out.println("employee Name : "+record.getEmp_name());
}
}
| [
"magantinarendra3939@gmail.com"
] | magantinarendra3939@gmail.com |
2b6405cce3bd3bc9891d77769b1e46e921ab2685 | e1b1ce58fb1277b724022933176f0809169682d9 | /sources/fr/pcsoft/wdjava/database/hf/C0860m.java | 59a59c59e2f01b6beef2be2ddfdcbda4bb4658c5 | [] | no_license | MR-116/com.masociete.projet_mobile-1_source_from_JADX | a5949c814f0f77437f74b7111ea9dca17140f2ea | 6cd80095cd68cb9392e6e067f26993ab2bf08bb2 | refs/heads/master | 2020-04-11T15:00:54.967026 | 2018-12-15T06:33:57 | 2018-12-15T06:33:57 | 161,873,466 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,410 | java | package fr.pcsoft.wdjava.database.hf;
import fr.pcsoft.wdjava.core.context.WDAppelContexte;
import fr.pcsoft.wdjava.core.debug.C0691a;
/* renamed from: fr.pcsoft.wdjava.database.hf.m */
public class C0860m implements C0542t, Cloneable {
private static final String ae = C0860m.m6067z(C0860m.m6068z("\u0005\u0013=2\u00042A+2Q#\r 9\u0010'\u0004o3V5\u000f*w\u00142\u0013*\"\u0003`)\ty"));
private String Rd = "";
private String Sd = "";
private String Td = "";
private String Ud = "";
private int Vd = 0;
private String Wd = "";
private int Xd = 0;
private String Yd = "";
private String Zd = "";
public C0860m(int i, String str, int i2, String str2, String str3, String str4, String str5, String str6) {
this.Vd = i;
this.Rd = str;
this.Ud = str2;
this.Xd = i2;
this.Wd = str3;
this.Yd = str4;
this.Zd = str5;
this.Td = str6;
this.Sd = WDAppelContexte.getContexte().m2731r();
}
public C0860m(int i, String str, String str2) {
this.Vd = i;
this.Rd = str;
this.Wd = str2;
this.Sd = WDAppelContexte.getContexte().m2731r();
}
/* renamed from: z */
private static String m6067z(char[] cArr) {
int length = cArr.length;
for (int i = 0; length > i; i++) {
int i2;
char c = cArr[i];
switch (i % 5) {
case 0:
i2 = 64;
break;
case 1:
i2 = 97;
break;
case 2:
i2 = 79;
break;
case 3:
i2 = 87;
break;
default:
i2 = 113;
break;
}
cArr[i] = (char) (i2 ^ c);
}
return new String(cArr).intern();
}
/* renamed from: z */
private static char[] m6068z(String str) {
char[] toCharArray = str.toCharArray();
if (toCharArray.length < 2) {
toCharArray[0] = (char) (toCharArray[0] ^ 113);
}
return toCharArray;
}
/* renamed from: a */
public String m6069a() {
return this.Zd;
}
/* renamed from: b */
public String m6070b() {
return this.Wd;
}
/* renamed from: c */
public void m6071c() {
this.Rd = null;
this.Ud = null;
this.Wd = null;
this.Yd = null;
this.Sd = null;
this.Zd = null;
this.Td = null;
}
/* renamed from: d */
public int m6072d() {
return this.Xd;
}
/* renamed from: e */
public String m6073e() {
return this.Rd;
}
/* renamed from: f */
public String m6074f() {
return this.Sd;
}
/* renamed from: g */
public C0860m m6075g() {
try {
return (C0860m) super.clone();
} catch (Exception e) {
C0691a.m2863b(ae, e);
return this;
}
}
/* renamed from: h */
public String m6076h() {
return this.Td;
}
/* renamed from: i */
public int m6077i() {
return this.Vd;
}
/* renamed from: j */
public String m6078j() {
return this.Ud;
}
/* renamed from: k */
public String m6079k() {
return this.Yd;
}
}
| [
"Entrepreneursmalaysia1@gmail.com"
] | Entrepreneursmalaysia1@gmail.com |
694f4f821561940ee638b7d4dab74288f97b35fa | d067585a5f22fd754db9616be7f8798543b565e6 | /CodeChallanges/src/com/java/learning/Contact.java | 874e4f26cdf08fefd617c5fc0c4d9fb75c8393ef | [] | no_license | SatyadevDangeti/JavaLearning | ca88a6ec82a86043baa0fef20c8dc359a8da3130 | ed75945503d6d416e9fa4d788bce1b95a585269e | refs/heads/master | 2023-07-10T12:09:29.722537 | 2020-06-25T23:07:44 | 2020-06-25T23:07:44 | 258,613,316 | 0 | 0 | null | 2021-08-30T16:27:30 | 2020-04-24T20:08:49 | Java | UTF-8 | Java | false | false | 484 | java | package com.java.learning;
public class Contact{
private String name;
private long phoneNumber;
public Contact(String name, long phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public long getPhoneNumber() {
return phoneNumber;
}
public static Contact createContact(String name, long phoneNumber){
return new Contact(name,phoneNumber);
}
}
| [
"satyadevdangeti@Satyadevs-MacBook-Pro-2.local"
] | satyadevdangeti@Satyadevs-MacBook-Pro-2.local |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.