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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e4a8bd98a0cb1956f69d6d3e955e0c0bb62108d5 | 8c7a025b30aab5ce7ea6041b5c8f10c02935f1d3 | /src/main/java/com/wyvs/wp/util/Message.java | 22dd0f07755e354b8a665693846433e28381fa42 | [] | no_license | SunShibo/wyvs-sys | 0e4063503d9cad0a834e8a696d9a72694dd044b8 | 2e16cba8431c26d3e318d4c4deffacfbeed05cd2 | refs/heads/master | 2021-01-18T21:30:49.026488 | 2016-05-17T04:18:52 | 2016-05-17T04:18:52 | 36,498,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,821 | java | package com.wyvs.wp.util;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 从资源文件中读取数据 该文件为系统中所放置的汉字文字
*
* @author Shibo_Sun
*/
public class Message {
private static final String BUNDLE_NAME = "message_text";
private static final String BUNDLE_PATH_NAME = "message_path";
/**
* 文本文件
*/
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME);
/**
* 路径文件
*/
private static final ResourceBundle RESOURCE_PTTH_BUNDLE = ResourceBundle
.getBundle(BUNDLE_PATH_NAME);
private Message() {
}
/**
* get the value from the properties file
*
* @param key
* the key in the properties file
* @return
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return "no " + key + " key!";
}
}
/**
* 获取路径文件值
*
* @author sun
* @version 2014-12-4 上午10:55:08
* @param key
* (key值不包含后缀名)
* @return
*/
public static String getPath(String key) {
try {
// 获取版本
String version = Message.getPathString("version");
key = key + version;
return getPathString(key);
} catch (MissingResourceException e) {
return "no " + key + " key!";
}
}
/**
* 获取路径文件的数据
*
* @author sun
* @version 2014-12-4 上午10:30:25
* @param key
* @return
*/
private static String getPathString(String key) {
try {
return RESOURCE_PTTH_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return "no " + key + " key!";
}
}
public static void main(String[] args) {
System.out.println(Message.getPath("doctor_head_image"));
}
}
| [
"wb-sunshibo.a@alibaba-inc.com"
] | wb-sunshibo.a@alibaba-inc.com |
b4ee7b0fcf4c186ec4699b5bfca3307d31702f30 | 4604972a5f6b04eaaad55f672b9fa5d23d35a042 | /src/main/java/tv/anypoint/kafka/producer/ProducerFactory.java | 9da0068cd0bea35b61fa8a0f46d107d8696ffe00 | [] | no_license | ddONGzaru/anypoint-kafka-producer-gui | b28dfcf2442ff99ad04218eb820b25d260cbaf78 | 0029ae5f434a4ded19dcc1fd00cb847e56124bcf | refs/heads/master | 2021-01-10T11:58:33.736801 | 2015-11-09T07:05:33 | 2015-11-09T07:05:33 | 45,386,316 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,382 | java | package tv.anypoint.kafka.producer;
import kafka.javaapi.producer.Producer;
import kafka.producer.ProducerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
* Created by twjang on 15. 10. 26.
*/
@Component
public class ProducerFactory {
private static Producer<String, byte[]> producer;
public static Producer<String, byte[]> getInstance() {
if (producer == null) {
return buildProducer();
} else {
return producer;
}
}
private static String metadataBrokerList;
@Value("${kafka.metadata.broker.list}")
public void setMetadataBrokerList(String metadataBrokerList) {
ProducerFactory.metadataBrokerList = metadataBrokerList;
System.out.println("broker list: " + metadataBrokerList);
}
private static Producer<String, byte[]> buildProducer() {
Properties props = new Properties();
props.put("metadata.broker.list", metadataBrokerList);
props.put("partitioner.class", RoundRobinPartitioner.class.getName());
props.put("compression.codec", "2");
props.put("key.serializer.class", "kafka.serializer.StringEncoder");
ProducerConfig producerConfig = new ProducerConfig(props);
return new Producer<>(producerConfig);
}
}
| [
"tw.jang@anypointmedia.com"
] | tw.jang@anypointmedia.com |
7642434981badfff1512809db6a89f92a4913534 | 082e26b011e30dc62a62fae95f375e4f87d9e99c | /docs/weixin_7.0.4_source/反编译源码/未反混淆/src/main/java/com/tencent/tencentmap/mapsdk/maps/a/es.java | abfd7901bee0a95af84648fd26b4c8425b02b68e | [] | no_license | xsren/AndroidReverseNotes | 9631a5aabc031006e795a112b7ac756a8edd4385 | 9202c276fe9f04a978e4e08b08e42645d97ca94b | refs/heads/master | 2021-04-07T22:50:51.072197 | 2019-07-16T02:24:43 | 2019-07-16T02:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,494 | java | package com.tencent.tencentmap.mapsdk.maps.a;
import com.tencent.matrix.trace.core.AppMethodBeat;
import java.util.Map;
public final class es {
private static boolean a = true;
private static boolean b = true;
public static void a(String str, int i, int i2, String str2, Map<String, String> map, Map<String, String> map2, boolean z) {
AppMethodBeat.i(98825);
bx.a(str, i, i2, str2, map, map2, z, 1);
AppMethodBeat.o(98825);
}
public static boolean a(String str, int i, Map<String, String> map) {
boolean z;
AppMethodBeat.i(98827);
if (i == bt.c()) {
if (a && ("HLReqRspEvent".equals(str) || "HLHttpAgent".equals(str))) {
a = false;
z = true;
AppMethodBeat.o(98827);
return z;
} else if (b && "HLHttpDirect".equals(str)) {
String str2 = (String) map.get("B15");
if (!eu.a(str2) && str2.equals("app")) {
b = false;
z = true;
AppMethodBeat.o(98827);
return z;
}
}
}
z = false;
AppMethodBeat.o(98827);
return z;
}
public static void b(String str, int i, int i2, String str2, Map<String, String> map, Map<String, String> map2, boolean z) {
AppMethodBeat.i(98826);
bx.a(str, i, i2, str2, map, map2, z);
AppMethodBeat.o(98826);
}
}
| [
"alwangsisi@163.com"
] | alwangsisi@163.com |
785bb624488a136c482c4bf74b9992a06b79a578 | 5593a6d4c7fc163e0bcd8e6d444ee90702fcf2a8 | /app/src/main/java/com/pombingsoft/planet_iot/activity/security_monitor/DataLogActivity.java | 889c4d4f76f46b395447f74c24b50403eba55dd4 | [] | no_license | PlanetEComSolution/Arduino | b1c8fa185090e940a85700cdf98c2a753a0abac8 | af6e72e1e7242af74c6be9bfca883076c8bc12e1 | refs/heads/master | 2020-05-23T12:44:27.467135 | 2019-05-15T06:08:26 | 2019-05-15T06:08:26 | 186,763,820 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 25,680 | java | package com.pombingsoft.planet_iot.activity.security_monitor;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.pombingsoft.planet_iot.R;
import com.pombingsoft.planet_iot.util.AppController;
import com.pombingsoft.planet_iot.util.ConnectionDetector;
import com.pombingsoft.planet_iot.util.UTIL;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class DataLogActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
ListView listview_devices;
Context myContext;
UTIL utill;
TextView tv_msg;
String time_1, date_1;
ArrayList<HashMap<String, String>> list = new ArrayList<>();
ArrayList<HashMap<String, String>> list_dataLog = new ArrayList<>();
// LinearLayout ll_AddDevice;
AlertDialog alertDialog;
boolean start_date_clicked, start_time_clicked;
String sDate, endDate;
String DeviceName, DeviceId;
EditText et_Time, et_Date, et_End_Date, et_End_Time;
Button btn_getData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_log_main);
myContext = DataLogActivity.this;
utill = new UTIL(myContext);
listview_devices = findViewById(R.id.device_listview);
tv_msg = findViewById(R.id.tv_msg);
tv_msg.setVisibility(View.GONE);
btn_getData = findViewById(R.id.btn_getData);
et_Time = findViewById(R.id.et_Time);
et_Date = findViewById(R.id.et_Date);
et_End_Date = findViewById(R.id.et_End_Date);
et_End_Time = findViewById(R.id.et_End_Time);
try {
Intent i = getIntent();
DeviceName = i.getStringExtra("DeviceName");
DeviceId = i.getStringExtra("DeviceId");
} catch (Exception e) {
e.getMessage();
}
et_Time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start_time_clicked = true;
//end_time_clicked=false;
Click_getTime();
}
});
et_Date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start_date_clicked = true;
// end_date_clicked=false;
Click_getDate();
}
});
et_End_Date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start_date_clicked = false;
Click_getDate();
// end_date_clicked=true;
}
});
et_End_Time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start_time_clicked = false;
Click_getTime();
// end_time_clicked=true;
}
});
btn_getData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String date = et_Date.getText().toString();
String time = et_Time.getText().toString();
String End_date = et_End_Date.getText().toString();
String End_time = et_End_Time.getText().toString();
if (date.isEmpty()) {
Toast.makeText(myContext,
"Please enter start date!", Toast.LENGTH_SHORT)
.show();
} else if (time.isEmpty()) {
Toast.makeText(myContext,
"Please enter start time!", Toast.LENGTH_SHORT)
.show();
} else if (End_date.isEmpty()) {
Toast.makeText(myContext,
"Please enter end date!", Toast.LENGTH_SHORT)
.show();
} else if (End_time.isEmpty()) {
Toast.makeText(myContext,
"Please enter end time!", Toast.LENGTH_SHORT)
.show();
} else {
/* String startDate=et_Date.getText().toString().trim()+"T"+et_Time.getText().toString().trim()+":00";
String endDate=et_End_Date.getText().toString().trim()+"T"+et_End_Time.getText().toString().trim()+":00";
*/
sDate = et_Date.getText().toString().trim() + "T" + et_Time.getText().toString().trim();
endDate = et_End_Date.getText().toString().trim() + "T" + et_End_Time.getText().toString().trim();
boolean isAfter = UTIL.compareDates(sDate, endDate);
if (isAfter) {
Toast.makeText(myContext,
"Start date cannot be greater than end date!", Toast.LENGTH_SHORT)
.show();
return;
}
/* String dt = et_Date.getText().toString().trim() + "_" + et_Time.getText().toString().trim() + "," +
et_End_Date.getText().toString().trim() + "_" + et_End_Time.getText().toString().trim() + "," + freq;
*/
if (new ConnectionDetector(myContext).isConnectingToInternet()) {
getDataLog_ApiCall();
} else {
DialogInternet();
}
}
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
if (list_dataLog.size() == 0) {
Toast.makeText(myContext, "No data to download.\nClick GET DATA button", Toast.LENGTH_SHORT).show();
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String data = String.valueOf(list_dataLog);
data = data.replaceAll("[{}]", "");
data = data.replaceAll(",", "\n");
data = data.substring(1, data.length() - 1);
generateNoteOnSD(myContext, "Log_" + currentDateandTime + ".txt", data);
}
}
});
}
void getDataLog_ApiCall() {
list.clear();
list_dataLog.clear();
String tag_string_req = "req_login";
/* final ProgressDialog pDialog = new ProgressDialog(myContext);
pDialog.setCancelable(false);
pDialog.setMessage("Getting devices...");
if (!pDialog.isShowing())
pDialog.show();*/
utill.showProgressDialog("Fetching data...");
String URL_LOGIN = null;
/*
* http://localhost:63020/api/arduino/
* GetDeviceDDataLog?deviceId=kmbpHDekB9&sdate=2018-04-18%2011:19:30&edate=2018-04-18%2012:24:03
* */
try {
URL_LOGIN = UTIL.Domain_Arduino + UTIL.getDeviceDataLog_API + "deviceId=" + DeviceId + "&sdate=" + sDate + "&edate=" + endDate;
} catch (Exception e) {
e.printStackTrace();
}
StringRequest strReq = new StringRequest(Request.Method.GET,
URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
utill.hideProgressDialog();
// utill.hideProgressDialog();
//1. //[]
try {
JSONArray jsonArray = new JSONArray(response);
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// String DeviceId = jsonObject.getString("DeviceId");
String Temperature = jsonObject.getString("Temperature");
String Humidity = jsonObject.getString("Humidity");
String Secuirity_Breach = jsonObject.getString("Secuirity_Breach");
String Flood_Level = jsonObject.getString("Flood_Level");
String Fire_Alarm = jsonObject.getString("Fire_Alarm");
String NDateTime = jsonObject.getString("NDateTime");
if (Temperature.equals("null") || Temperature.equals(null)) {// || Temperature == null || Temperature.equals(null)) {
Temperature = "N/A";
}
if (Humidity.equals("null") || Humidity.equals(null)) {// || Humidity == null || Humidity.equals(null)) {
Humidity = "N/A";
}
NDateTime = NDateTime.replace("T", " ");
NDateTime = NDateTime.substring(0, NDateTime.indexOf("."));
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Temperature", Temperature);
hashMap.put("Humidity", Humidity);
hashMap.put("Secuirity_Breach", Secuirity_Breach);
hashMap.put("Flood_Level", Flood_Level);
hashMap.put("Fire_Alarm", Fire_Alarm);
hashMap.put("NDateTime", NDateTime);
list.add(hashMap);
//Data Log
HashMap<String, String> hashMap_2 = new HashMap<>();
/* hashMap_2.put("Id", String.valueOf(i+1));
hashMap_2.put("Temperature", Temperature);
hashMap_2.put("Humidity", Humidity);
hashMap_2.put("Date_Time", NDateTime+"\n");
*/
hashMap_2.put("Temperature", Temperature);
hashMap_2.put("Humidity", Humidity);
hashMap_2.put("Date_Time", NDateTime);
hashMap_2.put("Id", String.valueOf(i + 1) + "\n");
list_dataLog.add(hashMap_2);
}
if (list.size() < 1) {
tv_msg.setVisibility(View.VISIBLE);
} else {
tv_msg.setVisibility(View.GONE);
}
} else {
tv_msg.setVisibility(View.VISIBLE);
Toast.makeText(myContext,
"No data found!", Toast.LENGTH_SHORT).show();
}
device_list_adapter adapter = new device_list_adapter(myContext, list);
listview_devices.setAdapter(adapter);
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(myContext, "Json error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
utill.hideProgressDialog();
Toast.makeText(myContext,
"Volley Error!", Toast.LENGTH_SHORT).show();
}
}) {
};
strReq.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void DialogInternet() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.fancyalertdialog, null);
dialogBuilder.setView(dialogView);
final TextView title = dialogView.findViewById(R.id.title);
final TextView message = dialogView.findViewById(R.id.message);
final Button positiveBtn = dialogView.findViewById(R.id.positiveBtn);
final Button negativeBtn = dialogView.findViewById(R.id.negativeBtn);
// dialogBuilder.setTitle("Device Details");
title.setText("No Internet Connection !");
message.setText("Please connect to a working internet connection");
positiveBtn.setText("Ok");
negativeBtn.setText("No");
negativeBtn.setVisibility(View.GONE);
positiveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
finish();
}
});
negativeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog = dialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.show();
/*
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(UTIL.NoInternet);
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//yes
alertDialog.dismiss();
finish();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();*/
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = +dayOfMonth + "/" + (++monthOfYear) + "/" + year;
String dayOfMonthString = dayOfMonth < 10 ? "0" + dayOfMonth : "" + dayOfMonth;
String monthOfYearString = monthOfYear < 10 ? "0" + monthOfYear : "" + monthOfYear;
//2018-01-19%20
date_1 = year + "-" + monthOfYearString + "-" + dayOfMonthString;
if (start_date_clicked) {
et_Date.setText(date_1);
} else {
et_End_Date.setText(date_1);
}
}
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
String hourString = hourOfDay < 10 ? "0" + hourOfDay : "" + hourOfDay;
String minuteString = minute < 10 ? "0" + minute : "" + minute;
String secondString = second < 10 ? "0" + second : "" + second;
String time = "You picked the following time: " + hourString + "h" + minuteString + "m" + secondString + "s";
String t = hourString + ":" + minuteString;
//19:11:09.983
// et_Time.setText(t);
time_1 = hourString + ":" + minuteString;//+ ":" + secondString + "." + "000";
if (start_time_clicked) {
et_Time.setText(time_1);
} else {
et_End_Time.setText(time_1);
}
}
private void Click_getDate() {
Calendar calendar = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
DataLogActivity.this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
dpd.setThemeDark(false);
dpd.vibrate(false);
dpd.dismissOnPause(false);
dpd.showYearPickerFirst(false);
dpd.setVersion(DatePickerDialog.Version.VERSION_2);
// dpd.setAccentColor(Color.parseColor("#9C27B0"));
dpd.setAccentColor(getResources().getColor(R.color.light_skyblue));
dpd.setTitle("Select Date");
dpd.setYearRange(1985, 2028);
// dpd.setMinDate(calendar);
/*
* Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date2.add(Calendar.WEEK_OF_MONTH, -1);
Calendar date3 = Calendar.getInstance();
date3.add(Calendar.WEEK_OF_MONTH, 1);
Calendar[] days = {date1, date2, date3};
dpd.setHighlightedDays(days);
* */
/*
* Calendar[] days = new Calendar[13];
for (int i = -6; i < 7; i++) {
Calendar day = Calendar.getInstance();
day.add(Calendar.DAY_OF_MONTH, i * 2);
days[i + 6] = day;
}
dpd.setSelectableDays(days);
*
*
* */
dpd.show(getFragmentManager(), "Datepickerdialog");
}
private void Click_getTime() {
boolean is24HourMode = true;
Calendar calendar = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(
DataLogActivity.this,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
true);
tpd.setThemeDark(false);
tpd.vibrate(false);
tpd.dismissOnPause(false);
tpd.enableSeconds(false);
tpd.setVersion(TimePickerDialog.Version.VERSION_2);
// tpd.setAccentColor(Color.parseColor("#9C27B0"));
tpd.setAccentColor(getResources().getColor(R.color.light_skyblue));
tpd.setTitle("Select Time");
/* if (limitSelectableTimes.isChecked()) {
if (enableSeconds.isChecked()) {
tpd.setTimeInterval(3, 5, 10);
} else {
tpd.setTimeInterval(3, 5, 60);
}
}
if (disableSpecificTimes.isChecked()) {
Timepoint[] disabledTimes = {
new Timepoint(10),
new Timepoint(10, 30),
new Timepoint(11),
new Timepoint(12, 30)
};
tpd.setDisabledTimes(disabledTimes);
}*/
tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
Log.d("TimePicker", "Dialog was cancelled");
}
});
tpd.show(getFragmentManager(), "Timepickerdialog");
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
/* final ProgressDialog pDialog = new ProgressDialog(myContext);
pDialog.setCancelable(false);
pDialog.setMessage("Downloading...");
if (!pDialog.isShowing())
pDialog.show();*/
utill.showProgressDialog("Downloading...");
try {
File root = new File(Environment.getExternalStorageDirectory(), "Data Log");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
utill.hideProgressDialog();
/* Toast.makeText(myContext, "File downloaded successfully !\n" +
"" + "Location:" + gpxfile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
*/
dialog_fileDownloaded("Location:" + gpxfile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
utill.hideProgressDialog();
Toast.makeText(context, "Some error occurred!", Toast.LENGTH_SHORT).show();
}
}
public class device_list_adapter extends BaseAdapter {
List<HashMap<String, String>> beanArrayList;
Context context;
int count = 1;
public device_list_adapter(Context context, List<HashMap<String, String>> beanArrayList) {
this.context = context;
this.beanArrayList = beanArrayList;
}
@Override
public int getCount() {
return beanArrayList.size();
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertview, ViewGroup viewGroup) {
final device_list_adapter.Holder holder;
final String index1 = String.valueOf(i + 1);
String Temperature = beanArrayList.get(i).get("Temperature");
String Humidity = beanArrayList.get(i).get("Humidity");
final String Secuirity_Breach = beanArrayList.get(i).get("Secuirity_Breach");
final String Flood_Level = beanArrayList.get(i).get("Flood_Level");
final String Fire_Alarm = beanArrayList.get(i).get("Fire_Alarm");
String NDateTime = beanArrayList.get(i).get("NDateTime");
if (convertview == null) {
holder = new device_list_adapter.Holder();
convertview = LayoutInflater.from(context).inflate(R.layout.row_data_log, null);
holder.index_no = (Button) convertview.findViewById(R.id.serial_no);
holder.Date = (TextView) convertview.findViewById(R.id.Date);
holder.temp = (TextView) convertview.findViewById(R.id.temp);
holder.humidity = (TextView) convertview.findViewById(R.id.humidity);
convertview.setTag(holder);
} else {
holder = (device_list_adapter.Holder) convertview.getTag();
}
/* NDateTime = NDateTime.replace("T", " ");
NDateTime = NDateTime.substring(0, NDateTime.indexOf("."));
if (Temperature.equals("null")) {// || Temperature == null || Temperature.equals(null)) {
Temperature = "N/A";
}
if (Humidity.equals("null")) {// || Humidity == null || Humidity.equals(null)) {
Humidity = "N/A";
}*/
holder.index_no.setText(index1);
holder.Date.setText(NDateTime);
holder.temp.setText(Temperature);
holder.humidity.setText(Humidity);
return convertview;
}
class Holder {
TextView Date, temp, humidity;
LinearLayout row_jobFile;
Button index_no;
//nks
}
}
private void dialog_fileDownloaded(String path) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.fancyalertdialog, null);
dialogBuilder.setView(dialogView);
final TextView title = dialogView.findViewById(R.id.title);
final TextView message = dialogView.findViewById(R.id.message);
final Button positiveBtn = dialogView.findViewById(R.id.positiveBtn);
final Button negativeBtn = dialogView.findViewById(R.id.negativeBtn);
// dialogBuilder.setTitle("Device Details");
title.setText("File downloaded successfully!");
message.setText(path);
positiveBtn.setText("Ok");
negativeBtn.setVisibility(View.GONE);
positiveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog = dialogBuilder.create();
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
| [
"nvnkmr1290@gmail.com"
] | nvnkmr1290@gmail.com |
f1f441e0224c94676821574f6e14faa46ac8f031 | bce741ced3b96bb7e26c0095c67554be25985935 | /EmployeeRest/src/main/java/org/cap/demo/model/Employee.java | 6cc625c523fced85b2a85f90788593bbd78e864f | [] | no_license | capgteam/demo | c45c45e8bea9b78dac82a7422f6abda5a263eae5 | b0ebc0a3c07c30d6f7c49a7faf6c90061d4b1ac2 | refs/heads/master | 2023-07-10T08:25:22.189545 | 2021-08-05T09:59:42 | 2021-08-05T09:59:42 | 392,991,642 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,684 | java | package org.cap.demo.model;
import java.time.LocalDate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonFormat;
@Entity
public class Employee {
@Id
@GeneratedValue
private int employeeId;
private String firstName;
private String lastName;
private double salary;
@JsonFormat(pattern = "yyyy-MM-dd",shape = JsonFormat.Shape.STRING)
private LocalDate dateOfJoining;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public LocalDate getDateOfJoining() {
return dateOfJoining;
}
public void setDateOfJoining(LocalDate dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
public Employee(int employeeId, String firstName, String lastName, double salary, LocalDate dateOfJoining) {
super();
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
this.dateOfJoining = dateOfJoining;
}
public Employee() {
super();
}
@Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", lastName=" + lastName
+ ", salary=" + salary + ", dateOfJoining=" + dateOfJoining + "]";
}
}
| [
"capgteam22020@gmail.com"
] | capgteam22020@gmail.com |
2bafb3e4e86e2e3f47a4b10f607705e77ec43a04 | 7a161407945162be3eb1578839f97c19c5a89f49 | /app/src/main/java/com/canplay/milk/mvp/activity/home/AddMilkActivity.java | 05cdca3ae0fa6c7fd67b4ebcf1b4e85f8ba18d2f | [] | no_license | Meikostar/Milk_Machines | 264a3751fdc441ee0aecc4d36f3068c538134db0 | b2a264360565ce64f26ec2accdff7ac6ba95d78f | refs/heads/master | 2020-03-16T20:42:52.607813 | 2018-06-06T10:48:27 | 2018-06-06T10:48:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,684 | java | package com.canplay.milk.mvp.activity.home;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.canplay.medical.R;
import com.canplay.milk.base.BaseActivity;
import com.canplay.milk.base.BaseApplication;
import com.canplay.milk.base.RxBus;
import com.canplay.milk.base.SubscriptionBean;
import com.canplay.milk.bean.SetMilk;
import com.canplay.milk.mvp.component.DaggerBaseComponent;
import com.canplay.milk.mvp.present.BaseContract;
import com.canplay.milk.mvp.present.BasesPresenter;
import com.canplay.milk.util.SpUtil;
import com.canplay.milk.view.BaseSelector;
import com.canplay.milk.view.HintDialogone;
import com.canplay.milk.view.NavigationBar;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* 冲奶设置
*/
public class AddMilkActivity extends BaseActivity implements BaseContract.View {
@Inject
BasesPresenter presenter;
@BindView(R.id.navigationBar)
NavigationBar navigationBar;
@BindView(R.id.tv_equptname)
TextView tvEquptname;
@BindView(R.id.tv_milk)
TextView tvMilk;
@BindView(R.id.bs_ml)
BaseSelector bsMl;
@BindView(R.id.bs_wd)
BaseSelector bsWd;
@BindView(R.id.bs_nd)
BaseSelector bsNd;
private HintDialogone dialogone;
@Override
public void initViews() {
setContentView(R.layout.acitivity_add_milk);
ButterKnife.bind(this);
DaggerBaseComponent.builder().appComponent(((BaseApplication) getApplication()).getAppComponent()).build().inject(this);
presenter.attachView(this);
dialogone = new HintDialogone(this, 2);
}
private SetMilk milk = new SetMilk();
@Override
public void bindEvents() {
dialogone.setBindClickListener(new HintDialogone.BindClickListener() {
@Override
public void clicks(int type, int right) {
finish();
}
});
navigationBar.setNavigationBarListener(new NavigationBar.NavigationBarListener() {
@Override
public void navigationLeft() {
finish();
}
@Override
public void navigationRight() {
milk.waterQuantity = bsMl.getSelector();
milk.consistence = bsNd.getSelector().equals("高") ? "high" : (bsNd.getSelector().equals("中") ? "middle" : "low");
milk.waterTemperature = bsWd.getSelector();
showProgress("保存中...");
presenter.setUserMilkConf(milk.consistence, milk.waterQuantity, milk.waterTemperature);
}
@Override
public void navigationimg() {
}
});
tvMilk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AddMilkActivity.this, PushMilkActivity.class));
finish();
}
});
}
@Override
public void initData() {
SetMilk milk = SpUtil.getInstance().getMilk();
bsMl.setData(2,milk.waterQuantity);
bsNd.setData(1,milk.consistence);
bsNd.setData(0,milk.waterTemperature);
}
@Override
public <T> void toEntity(T entity, int type) {
dimessProgress();
RxBus.getInstance().send(SubscriptionBean.createSendBean(SubscriptionBean.REFEST_SET,""));
dialogone.show(findViewById(R.id.line));
}
@Override
public void toNextStep(int type) {
}
@Override
public void showTomast(String msg) {
dimessProgress();
showToasts(msg);
}
}
| [
"admin"
] | admin |
5ae862322e1b2d784be2f059805af6951fde641c | 9007d83afab7c4c9e48f8c2b9fdcbbc4089a4e2b | /app/src/main/java/com/grocery/food/Model/Category.java | 0744d88184848f02823a7ea60647864acbd4d6f4 | [] | no_license | fernandomineiro/aislanhot | 310a46ab0da73a76ff8cb5871ec5d919fa312e64 | 7c6575411a31fbb61c02e9edc3f77487bc92ff73 | refs/heads/master | 2022-09-24T21:44:28.906587 | 2020-06-05T16:37:13 | 2020-06-05T16:37:13 | 269,705,122 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,099 | java |
package com.grocery.food.Model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
@SuppressWarnings("unused")
public class Category {
@SerializedName("data")
private List<CatItem> mData;
@SerializedName("ResponseCode")
private String mResponseCode;
@SerializedName("ResponseMsg")
private String mResponseMsg;
@SerializedName("Result")
private String mResult;
public List<CatItem> getData() {
return mData;
}
public void setData(List<CatItem> data) {
mData = data;
}
public String getResponseCode() {
return mResponseCode;
}
public void setResponseCode(String responseCode) {
mResponseCode = responseCode;
}
public String getResponseMsg() {
return mResponseMsg;
}
public void setResponseMsg(String responseMsg) {
mResponseMsg = responseMsg;
}
public String getResult() {
return mResult;
}
public void setResult(String result) {
mResult = result;
}
}
| [
"fernandofitilan@hotmail.com"
] | fernandofitilan@hotmail.com |
89d7bef319f8f7400abd812edcaeb2c625317b3a | 6c258fd0d974f81d72c0b1eb7181abdd7d6055c2 | /JustJava/src/oopconcepts2/Vehicle.java | ee38a263e940862eb4953ccef61b68f7463efa9b | [
"Apache-2.0"
] | permissive | asytnik/TestRepo | fdcb7a937e71514a61f2817ce5b6e59259fe9abb | bbe247b4eeca15326b13e1f963094b25249deae8 | refs/heads/master | 2020-03-18T13:20:48.551564 | 2018-08-10T23:40:59 | 2018-08-10T23:40:59 | 134,777,564 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 121 | java | package oopconcepts2;
public class Vehicle {
public void engine(){
System.out.println("Vehicle --> Engine");
}
}
| [
"asytnik07@gmail.com"
] | asytnik07@gmail.com |
b343e6736cda4e6941a40305c385cabdf57efbaf | 8d8d43da33b31adcc95d87246a0f78e775c0d984 | /app/src/main/java/com/example/android/themepixli/Main2ActivityFragment.java | 1d9180fa4d01b9191acff239442b6a4bc30baf22 | [] | no_license | raza-ahmed/ThemePixli | 121bd47c159162930dfc1b03e00a6d39283efaef | 4b41eb98d7c4f32d95d983dee745804fbae5561f | refs/heads/master | 2021-01-10T22:27:57.149153 | 2016-08-26T04:04:49 | 2016-08-26T04:04:49 | 66,523,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,058 | java | package com.example.android.themepixli;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import java.util.Arrays;
/**
* Created by ahmedraza on 25/08/16.
*/
public class Main2ActivityFragment extends Fragment {
public Main2ActivityFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.main2_activity_fragment, container, false);
PixliTeamCustomClass[] picArray = {
new PixliTeamCustomClass(R.drawable.pixli1),
new PixliTeamCustomClass(R.drawable.pixli3),
new PixliTeamCustomClass(R.drawable.image_tiwaco),
new PixliTeamCustomClass(R.drawable.marriage8034),
new PixliTeamCustomClass(R.drawable.dot_it),
new PixliTeamCustomClass(R.drawable.personstreetdarkbike),
new PixliTeamCustomClass(R.drawable.marriage8033),
new PixliTeamCustomClass(R.drawable.pixli4),
new PixliTeamCustomClass(R.drawable.pixli2),
new PixliTeamCustomClass(R.drawable.marriage8059),
new PixliTeamCustomClass(R.drawable.marriage8035),
new PixliTeamCustomClass(R.drawable.headlight),
new PixliTeamCustomClass(R.drawable.pixli1),
new PixliTeamCustomClass(R.drawable.marriage8060),
new PixliTeamCustomClass(R.drawable.pixli3),
new PixliTeamCustomClass(R.drawable.marriage8065),
new PixliTeamCustomClass(R.drawable.pixli5),
new PixliTeamCustomClass(R.drawable.pixli6),
new PixliTeamCustomClass(R.drawable.marriage8077),
new PixliTeamCustomClass(R.drawable.marriage8125),
new PixliTeamCustomClass(R.drawable.pixli7),
new PixliTeamCustomClass(R.drawable.marriage8129),
new PixliTeamCustomClass(R.drawable.marriage8130),
new PixliTeamCustomClass(R.drawable.pixli8),
new PixliTeamCustomClass(R.drawable.marriage8135),
new PixliTeamCustomClass(R.drawable.smartphone),
new PixliTeamCustomClass(R.drawable.pixli9),
new PixliTeamCustomClass(R.drawable.pixli10),
new PixliTeamCustomClass(R.drawable.pixli11),
new PixliTeamCustomClass(R.drawable.pixli12),
new PixliTeamCustomClass(R.drawable.pixli5),
new PixliTeamCustomClass(R.drawable.pixli6),
new PixliTeamCustomClass(R.drawable.marriage8077)
};
PixliTeamCustomClassAdapter pixliAdapter = new PixliTeamCustomClassAdapter(getActivity(), Arrays.asList(picArray));
GridView gridView = (GridView) rootView.findViewById(R.id.gidViewhold);
gridView.setAdapter(pixliAdapter);
return rootView;
}
}
| [
"raza2393@gmail.com"
] | raza2393@gmail.com |
ec8ba922d7909050e4c1bf57b1b222d1a2729a5d | 86987033159de8d0b97863bc1b4015c610eb2974 | /selleck/email/interest/MatchInterestByAbstract.java | ca282165d29d74cebcc15cb73a7f6f6d53425189 | [] | no_license | troublrMan/PmcSearchTools | 704d625a33525aef1ef554a630423c21e15795bc | a95b9d6294504d0ec54d64502853ebffbdcf99d6 | refs/heads/master | 2021-01-17T12:58:44.717042 | 2016-08-11T15:42:35 | 2016-08-11T15:42:35 | 65,481,144 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,453 | java | package selleck.email.interest;
import java.util.ArrayList;
import java.util.List;
public class MatchInterestByAbstract extends AbstractMatchInterest{
public MatchInterestByAbstract(){
super();
}
/**
* 把要匹配的内容分成一个个单词List<String>
* 摘要不需要分词
*/
@Override
List<String> splitWord(String word) {
// List<String> words = new ArrayList<String>();
// List<String> wordsList = new ArrayList<String>(); // 最终分好的word list
// String[] tmpwords = word.replace("/font>", "").replaceAll(escapeChar," ").split(" ");
// for(String tmp:tmpwords){
// if(tmp == null)continue;
// tmp = tmp.trim().toString();
// if(!tmp.equals("") && !tmp.equals(" "))
// words.add(tmp);
// }
//
// tmpwords = null;
// //将单独的数字与相邻的词组合
// for (int i = 0; i < words.size(); i++) {
// if (isNumeric(words.get(i))) {
// if(i!=0)
// wordsList.add(words.get(i-1)+words.get(i));
// if(i!=words.size()-1)
// wordsList.add(words.get(i)+words.get(i+1));
// }else{
// wordsList.add(words.get(i));
// }
// }
// return wordsList;
List<String> words = new ArrayList<String>();
words.add(word);
return words;
}
/**
* 找到wos文章的摘要里关键词的缩写。stem cells(SCs) 要记录SCs也作为关键词
*/
@Override
List<String> findShortKeyword(String word) {
return null;
}
}
| [
"chao.wang1@newtouch.cn"
] | chao.wang1@newtouch.cn |
68069f22df2ad8c37394cb350ef55d70b90c8f68 | 7712cf01ca99036a93d3b52e31eb4884602c3b97 | /AnalyseVente/src/main/java/Analyse/ReducePhase2.java | 45cf58646ac6063b5f134d6d15abf7e2494a372d | [] | no_license | AchrefJaouidaa/ProjetCarrefour | b88d0160cd6f268802b9ebb72928cf21b87576f7 | ec07c4b69fde8b19f757d0692edfad4ef7b17490 | refs/heads/master | 2021-07-06T05:36:08.548377 | 2019-06-27T08:00:09 | 2019-06-27T08:00:09 | 193,747,928 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,634 | java | package Analyse;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
/**
* Cette classe permet de grouper un ou plusieurs fichiers dans un ou plusieurs dossiers selon une clé;
* La clé est définie par le type de reduce global ou par magasin et le résultat souhaité par ventes ou par chiffre d'affaire
* param: sortCV est le type de résultat souhaité par chiffre d"affaire ou par quantite de ventes
*/
public class ReducePhase2 extends ReducerAbstract {
private SortCAOrVentes sortCV;
public ReducePhase2 (int indexDate,
String tempName,
SortGlobalOrMg sortGMType,
SortCAOrVentes sortCV,
File... fileToSplit) {
super (indexDate, tempName, sortGMType, fileToSplit);
this.sortCV = sortCV;
}
public ReducePhase2 (int indexDate,
String tempName,
SortGlobalOrMg sortGMType,
SortCAOrVentes sortCV,
int numFields,
File... fileToSplit) {
super (indexDate, tempName, sortGMType, numFields, fileToSplit);
this.sortCV = sortCV;
}
/**
* cette méthode permet d"écrire le résultat de ReduceCol dans un fichier dans le cas de tous les magasins /ou plusieurs fichiers par magasin
*/
@Override
public void TransFile () {
HashMap <String, ArrayList <float[]>> aggMap = getReducedCol ();
String fileName = fileToTrans[0].getName ();
FileWriter filePart = null;
BufferedWriter writer = null;
try {
switch (sortType){
case Mg:{
Set <String> tmpSet = aggMap.keySet ();
for (String str : tmpSet) {
ArrayList <float[]> val = aggMap.get (str);
File fileDirectoryNew = new File (fileDirectory + "/" + sortType + "/");
if ( !fileDirectoryNew.exists () ) {
fileDirectoryNew.mkdirs ();
}
String temppStr = fileName;
if ( indexDate == 8 ) {
temppStr = "all";
}
else {
temppStr = fileName.substring (20, 28);
}
filePart = new FileWriter (fileDirectoryNew + "/" + "top_100_" + sortCV + "_" + temppStr + "_" + str);
writer = new BufferedWriter (filePart);
int numb_result=0;
for (float[] tempfloat : val) {
if(numb_result<100){
writer.write ((int) tempfloat[0] + "|" + (int) tempfloat[1] + "|" + tempfloat[2]);
writer.newLine ();
numb_result= numb_result+1;
}
else {
continue;
}
}
writer.close ();
}
}
break;
case global:{
ArrayList <float[]> val = aggMap.get ("ANYKEY");
File fileDirectoryNew = new File (fileDirectory + "/" + sortType + "/");
if ( !fileDirectoryNew.exists () ) {
fileDirectoryNew.mkdirs ();
}
String tempStrr = fileName;
if ( indexDate == 10 ) {
tempStrr = "all";
}
else {
tempStrr = fileName.substring (20, 28);
}
filePart = new FileWriter (fileDirectoryNew + "/" + "top_100_" + sortCV + "_" + tempStrr);
writer = new BufferedWriter (filePart);
int numb_result=0;
for (float[] tempfloat : val) {
if(numb_result<100) {
writer.write ((int) tempfloat[0] + "|" + (int) tempfloat[1] + "|" + tempfloat[2]);
writer.newLine ();
numb_result = numb_result + 1;
}
else {
continue;
}
}
writer.close ();
}
break;
}
}
catch (IOException e) {
e.printStackTrace ();
}
}
/**
* cette méthode permet de lire à partir des fichiers et ordonner les éléments selon une clé qui dépend du sorType
* @return: une Hashmap dont la clé est une liste de String
* dans le cas de global la clé est aléatoire
* dans le cas de Mg la clé est le magasin id
*/
public HashMap <String, ArrayList <float[]>> getReducedCol () {
HashMap <String, ArrayList <float[]>> aggMaptmp = new HashMap <> ();
TextRowDecoder decoder = new TextRowDecoder (numFields, delimiter);
FileReader <byte[][]> reader;
if ( fileToTrans.length == 1 && fileToTrans[0].listFiles () == null ) {
reader = FileReader.create (decoder, CHUNK_SIZE, fileToTrans[0]);
}
else if ( fileToTrans.length > 1 ) {
reader = FileReader.create (decoder, CHUNK_SIZE, fileToTrans);
}
else {
reader = FileReader.create (decoder, CHUNK_SIZE, fileToTrans[0].listFiles ());
}
for (List <byte[][]> chunk : reader) {
for (byte[][] element : chunk) {
String key = null;
float idPdTemp = Float.parseFloat (new String (element[1 - (4 - numFields)]));
float qtyPdTemp = Float.parseFloat (new String (element[2 - (4 - numFields)]));
float prixPdTemp = Float.parseFloat (new String (element[3 - (4 - numFields)]));
switch (sortType){
case Mg:{
key = new String (element[0]);
}
break;
case global:{
key = "ANYKEY";
}
break;
}
ArrayList <float[]> tempList = null;
if ( aggMaptmp.containsKey (key) ) {
int i = 0;
tempList = aggMaptmp.get (key);
switch (sortCV){
case VENTES:{
for (float[] tempArray : tempList) {
if ( tempArray[1] > qtyPdTemp ) {
i = i + 1;
}
else break;
}
}
break;
case CA:{
for (float[] tempArray : tempList) {
if ( tempArray[2] > prixPdTemp ) {
i = i + 1;
}
else break;
}
}
break;
}
if ( i > tempList.size () ) {
tempList.add (new float[] {idPdTemp, qtyPdTemp, prixPdTemp});
}
else {
tempList.add (i, new float[] {idPdTemp, qtyPdTemp, prixPdTemp});
}
aggMaptmp.put (key, tempList);
}
else {
tempList = new ArrayList <> (Arrays.asList (new float[] {idPdTemp, qtyPdTemp, prixPdTemp}));
aggMaptmp.put (key, tempList);
}
}
}
return aggMaptmp;
}
}
| [
"achref.jaouida@gmail.com"
] | achref.jaouida@gmail.com |
c176a08840cc68e89cc357c8a15571cddd359236 | d44f1a556ade3c46b930cd6aa992b06fa9203694 | /algorithms/src/algorithms/recursions/mergesort/MergeSort.java | 57390bdc8e07649a7cbeed64ebeb3a54821588be | [] | no_license | kihong017/algorithms | cd88b44020bc60f6fe3d7e2a9ec9014a714983d6 | b30b182502b9c78211bef0a2a6e30c26a74f8e23 | refs/heads/master | 2020-07-25T04:43:34.122697 | 2019-10-29T05:13:18 | 2019-10-29T05:13:18 | 208,168,917 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,120 | java | package algorithms.recursions.mergesort;
public class MergeSort {
public void sort(int[] inputArray) {
mergeSort(inputArray, 0, inputArray.length-1);
}
private void mergeSort(int[] inputArray, int start, int end) {
if (start < end) {
int mid = (int) Math.floor( (start+end)/2 );
mergeSort(inputArray, start, mid);
mergeSort(inputArray, mid+1, end);
merge(inputArray, start, mid, end);
}
}
private void merge(int[] inputArray, int start, int mid, int end) {
int leftLength = mid - start + 1;
int rightLength = end - mid;
int[] leftArray = new int[leftLength];
int[] rightArray = new int[rightLength];
for (int i = 0; i < leftLength; i++) {
leftArray[i] = inputArray[start + i];
}
for (int j = 0; j < rightLength; j++) {
rightArray[j] = inputArray[mid + 1 + j];
}
int i = 0, j = 0;
for (int k = start; k <= end; k++) {
if ( (j >= rightLength) || (i < leftLength && leftArray[i] <= rightArray[j]) ) {
inputArray[k] = leftArray[i];
i++;
} else {
inputArray[k] = rightArray[j];
j++;
}
}
}
}
| [
"kihong017@gmail.com"
] | kihong017@gmail.com |
3e5e2d36bd44c10454dc8082058974ee8207e30e | ba13d086cddb85aedbe854440535e7bbe47764c7 | /SampleProject/src/main/java/com/hsbc/sampleproject/PavitraNew.java | 5d8f362acb05ab20bb3609db16a3007e60cddadd | [] | no_license | PAVITRAJAVOOR/Demo | f8973fc2e6942f3804cfc48c7373ff18f2f32d99 | c61c5e5d1439131f63d770c4fd85b092cae51ba8 | refs/heads/development | 2022-12-23T09:04:01.919062 | 2020-09-19T12:30:45 | 2020-09-19T12:30:45 | 296,849,273 | 0 | 0 | null | 2020-09-19T12:30:46 | 2020-09-19T11:04:28 | Java | UTF-8 | Java | false | false | 62 | java | package com.hsbc.sampleproject;
public class PavitraNew {
}
| [
"Dell@DESKTOP-QJ51BCM"
] | Dell@DESKTOP-QJ51BCM |
bddde7d5d2fe61a55cf27db1a3901c81e20fbe06 | e4ddb74125fc25e2d373d07ef83d200b78a2968b | /MyShopingCart/app/src/androidTest/java/com/derysudrajat/daftarbelanja/ExampleInstrumentedTest.java | f58a85776b3adf2dc16ecbca3f5416b2b9a01ad0 | [] | no_license | derysudrajat/Pemrogramman-Mobile | 7de151abf3d9ff21614cdc3f6c84a3da647ee2af | bb889555b1232690a8695ba91df1899068795258 | refs/heads/master | 2020-08-02T21:18:55.566477 | 2020-01-11T03:48:14 | 2020-01-11T03:48:14 | 211,510,117 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 776 | java | package com.derysudrajat.daftarbelanja;
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.derysudrajat.daftarbelanja", appContext.getPackageName());
}
}
| [
"dery.sudrajat17@gmail.com"
] | dery.sudrajat17@gmail.com |
ac6f395b6d96c636ffc3ae346ff7aea076349077 | 59b0af4fec7428ae61a77f3ac2d0287def2471f6 | /app/src/test/java/com/lloydfinch/tools/ExampleUnitTest.java | 7e32d5ad41eaccc635ed6d54c4335d9b2691bc81 | [] | no_license | Zoo2Animal/LloydFinch_Tools | a79e0e5d6839dafe9c8bdf444d57b6d5d9d4356e | b6a26df92078519838da950225ad5f4686bb2777 | refs/heads/master | 2021-03-04T08:03:25.470030 | 2020-03-09T13:06:42 | 2020-03-09T13:06:42 | 246,018,512 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 381 | java | package com.lloydfinch.tools;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"wangwenqi@orangelab.cn"
] | wangwenqi@orangelab.cn |
57448aba1c106db89daf0546f75afadead6e37d6 | 8444fa132eaffbf7db26000071effc079c4271bc | /feign-consumer/src/main/java/com/example/web/ConsumerController.java | c9b0c9bfaaf20d245772a79044e970d4e0d397f2 | [] | no_license | lansebing/spring-cloud-demo | 37a9f3a130a8c4b4e36d47cc8cd49210530f9896 | ac6d2ef044434e578536b01332d50e56bb9570fa | refs/heads/master | 2021-03-15T08:41:41.026981 | 2020-03-13T14:02:15 | 2020-03-13T14:02:15 | 246,838,041 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 985 | java | package com.example.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConsumerController {
@Autowired
HelloService helloService;
@RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
public String helloConsumer() {
return helloService.hello();
}
@RequestMapping(value = "/feign-consumer2", method = RequestMethod.GET)
public String helloConsumer2() {
StringBuilder sb = new StringBuilder();
sb.append(helloService.hello()).append("\n");
sb.append(helloService.hello1("Mic")).append("\n");
sb.append(helloService.hello2("Mic", 18)).append("\n");
sb.append(helloService.hello3(new User("Jack", 20))).append("\n");
return sb.toString();
}
} | [
"jin_rongjie@163.com"
] | jin_rongjie@163.com |
48290743a070c6b5c622b3d60084279786c9dc31 | e9a55dc37cc3bcda3e755c5bde68df53fac374ea | /src/main/java/de/burandt/artists/exhibition/domain/ExhibitionPoster.java | 27878e8fad65120a7bc1c4981f5f2312e3d44e56 | [] | no_license | Ginbob/ArtistDemo | 7f95b6e6fe750326bd4a4b805dfac2b2ce79db5e | c235cd284055118aef12c6956357eb9565f9365a | refs/heads/master | 2020-04-15T06:49:38.911689 | 2019-01-07T18:50:38 | 2019-01-07T18:50:38 | 164,474,765 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,583 | java | package de.burandt.artists.exhibition.domain;
import javax.persistence.*;
@Entity
public class ExhibitionPoster {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne
@JoinColumn(name = "exhibition")
private Exhibition exhibition;
private String filename;
public ExhibitionPoster() {
}
public ExhibitionPoster(Exhibition exhibition, String filename) {
this.exhibition = exhibition;
this.filename = filename;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Exhibition getExhibition() {
return exhibition;
}
public void setExhibition(Exhibition exhibition) {
this.exhibition = exhibition;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ExhibitionPoster)) return false;
ExhibitionPoster that = (ExhibitionPoster) o;
if (exhibition != null ? !exhibition.equals(that.exhibition) : that.exhibition != null) return false;
return filename != null ? filename.equals(that.filename) : that.filename == null;
}
@Override
public int hashCode() {
int result = exhibition != null ? exhibition.hashCode() : 0;
result = 31 * result + (filename != null ? filename.hashCode() : 0);
return result;
}
}
| [
"henning.nobbe@innoq.com"
] | henning.nobbe@innoq.com |
06ed43f875dc010503d32ec0cd901789a5f47ff1 | f525deacb5c97e139ae2d73a4c1304affb7ea197 | /gitv-DeObfuscate/src/main/java/com/gala/appmanager/p002a/C0104b.java | ef156d3b8c690c676a20203162b5f8d421d5660e | [] | no_license | AgnitumuS/gitv | 93b2359e1bf9f2b6c945298c61c5c6dbfeea49b3 | 242c9a10a0aeb41b9589de9f254e6ce9f57bd77a | refs/heads/master | 2021-08-08T00:50:10.630301 | 2017-11-09T08:10:33 | 2017-11-09T08:10:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 135 | java | package com.gala.appmanager.p002a;
public interface C0104b {
void m181a(String str, int i);
void m182b(String str, int i);
}
| [
"liuwencai@le.com"
] | liuwencai@le.com |
0eb916d1c3db12a5cfe15738e833c857547f3ec9 | a0450e9d6005cef113b83bafe6e591d15c835ed8 | /src/main/java/com/enat/sharemanagement/agenda/AgendaVoteDTO.java | 012409eed627f8ffbecd9276a781b3e1ca006ca6 | [] | no_license | birhaneTinsae/share-management | 66dddc5a343bcdf453ade5fc6e70c7096af52c75 | 006c8028e4bc2fd875cb42ae9c8e54ed91f545be | refs/heads/master | 2023-03-22T23:05:32.409132 | 2021-01-29T09:08:09 | 2021-01-29T09:08:09 | 330,198,878 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 302 | java | package com.enat.sharemanagement.agenda;
import com.enat.sharemanagement.attendance.AttendanceDTO;
import lombok.Data;
import java.io.Serializable;
@Data
public class AgendaVoteDTO implements Serializable {
private AgendaDTO agenda;
private AttendanceDTO attendance;
private int vote;
}
| [
"birhane.tinsaa@gmail.com"
] | birhane.tinsaa@gmail.com |
7b2987d272da1876d1c273d1fd968d92413f5ee0 | 4ad54a56ea1d1da711c1423c254b2b40b5619c9f | /service.api/src/main/java/com/hack23/cia/service/api/action/application/LogoutResponse.java | f2e6d90a3bac23fba457f0b82808ea8a995cdb86 | [
"Apache-2.0"
] | permissive | mushfiqur47/cia | 1cc52cf2eb2bb96be7bd26822b5c3832fbc16905 | 3ddc99ffa278df6b479bf2df9cc59d7d6194cef8 | refs/heads/master | 2022-10-23T06:28:17.475685 | 2020-06-20T12:48:33 | 2020-06-20T12:48:33 | 273,761,227 | 1 | 0 | Apache-2.0 | 2020-06-20T18:15:15 | 2020-06-20T18:15:14 | null | UTF-8 | Java | false | false | 1,118 | java | /*
* Copyright 2010-2020 James Pether Sörling
*
* 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.
*
* $Id$
* $HeadURL$
*/
package com.hack23.cia.service.api.action.application;
import com.hack23.cia.service.api.action.common.AbstractResponse;
/**
* The Class LogoutResponse.
*/
public final class LogoutResponse extends AbstractResponse {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new logout response.
*
* @param result
* the result
*/
public LogoutResponse(final ServiceResult result) {
super(result);
}
}
| [
"pether.sorling@gmail.com"
] | pether.sorling@gmail.com |
5903265d736542da6f18677c11ad1e3c8787afc4 | 553dfd60b80cc282ed2737123d7fb1c969338668 | /app/src/main/java/com/example/yuzhong/stressmeter/PSM.java | 47e7855376abf04b236be2ffd96e96debdcff28d | [] | no_license | cuteQ/StressMeter | e3932c2331d69774443b99b59ff6d37e0348b185 | 41b22b9a5ac6f1a09a920d4361500835bbd903d0 | refs/heads/master | 2016-09-13T22:54:20.695994 | 2016-04-16T17:50:53 | 2016-04-16T17:50:53 | 56,169,348 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,856 | java | package com.example.yuzhong.stressmeter;
/**
* Created by ruiwang on 8/23/15.
*/
public class PSM {
public static int[] getGridById(int id) {
switch (id) {
case 1:
return getGrid1();
case 2:
return getGrid2();
case 3:
return getGrid3();
}
return null;
}
public static int[] getGrid1() {
int[] grid = new int[16];
grid[0] = R.drawable.psm_talking_on_phone2;
grid[1] = R.drawable.psm_stressed_person;
grid[2] = R.drawable.psm_stressed_person12;
grid[3] = R.drawable.psm_lonely;
grid[4] = R.drawable.psm_gambling4;
grid[5] = R.drawable.psm_clutter3;
grid[6] = R.drawable.psm_reading_in_bed2;
grid[7] = R.drawable.psm_stressed_person4;
grid[8] = R.drawable.psm_lake3;
grid[9] = R.drawable.psm_cat;
grid[10] = R.drawable.psm_puppy3;
grid[11] = R.drawable.psm_neutral_person2;
grid[12] = R.drawable.psm_beach3;
grid[13] = R.drawable.psm_peaceful_person;
grid[14] = R.drawable.psm_alarm_clock2;
grid[15] = R.drawable.psm_sticky_notes2;
return grid;
}
public static int[] getGrid2() {
int[] grid = new int[16];
grid[0] = R.drawable.psm_anxious;
grid[1] = R.drawable.psm_hiking3;
grid[2] = R.drawable.psm_stressed_person3;
grid[3] = R.drawable.psm_lonely2;
grid[4] = R.drawable.psm_dog_sleeping;
grid[5] = R.drawable.psm_running4;
grid[6] = R.drawable.psm_alarm_clock;
grid[7] = R.drawable.psm_headache;
grid[8] = R.drawable.psm_baby_sleeping;
grid[9] = R.drawable.psm_puppy;
grid[10] = R.drawable.psm_stressed_cat;
grid[11] = R.drawable.psm_angry_face;
grid[12] = R.drawable.psm_bar;
grid[13] = R.drawable.psm_running3;
grid[14] = R.drawable.psm_neutral_child;
grid[15] = R.drawable.psm_headache2;
return grid;
}
public static int[] getGrid3() {
int[] grid = new int[16];
grid[0] = R.drawable.psm_mountains11;
grid[1] = R.drawable.psm_wine3;
grid[2] = R.drawable.psm_barbed_wire2;
grid[3] = R.drawable.psm_clutter;
grid[4] = R.drawable.psm_blue_drop;
grid[5] = R.drawable.psm_to_do_list;
grid[6] = R.drawable.psm_stressed_person7;
grid[7] = R.drawable.psm_stressed_person6;
grid[8] = R.drawable.psm_yoga4;
grid[9] = R.drawable.psm_bird3;
grid[10] = R.drawable.psm_stressed_person8;
grid[11] = R.drawable.psm_exam4;
grid[12] = R.drawable.psm_kettle;
grid[13] = R.drawable.psm_lawn_chairs3;
grid[14] = R.drawable.psm_to_do_list3;
grid[15] = R.drawable.psm_work4;
return grid;
}
}
| [
"lilly.lly@hotmail.com"
] | lilly.lly@hotmail.com |
be4f564111731cdf3c6031ac3ff68043d76f37f0 | c6b05f2169c30e386765d709d9ecd59294a47164 | /Personal/src/main/java/com/scala/library/SampleJson.java | fb17c86819839d21ffa9714338c6a6a6e46d05ac | [] | no_license | amanjadon54/ScalaIntegrationWithJava | 5ede20a7cf4ad938d9c6d721c0fa6a2783708230 | 502323aae4693493494605f6873c1f800f6772d3 | refs/heads/master | 2020-04-14T21:05:46.179168 | 2019-01-04T16:32:27 | 2019-01-04T16:32:27 | 164,117,314 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,847 | java | package com.scala.library;
public class SampleJson {
static String json="{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Evelyn Waugh\",\n" +
" \"title\": \"Sword of Honour\",\n" +
" \"price\": 12.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Herman Melville\",\n" +
" \"title\": \"Moby Dick\",\n" +
" \"isbn\": \"0-553-21311-3\",\n" +
" \"price\": 8.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"J. R. R. Tolkien\",\n" +
" \"title\": \"The Lord of the Rings\",\n" +
" \"isbn\": \"0-395-19395-8\",\n" +
" \"price\": 22.99\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" },\n" +
" \"expensive\": 10\n" +
"}\n" +
" ";
}
| [
"amanjadon54@gmail.com"
] | amanjadon54@gmail.com |
4288530e1262bddd220bf3ff5f2c8df26fd701ff | 2dc55280583e54cd3745fad4145eb7a0712eb503 | /stardust-engine-ws-cxf/src/main/java/org/eclipse/stardust/engine/api/ws/FindRuntimeArtifacts.java | 3480b5f800d11b6629f46bfac263c5a77dc81f41 | [] | no_license | markus512/stardust.engine | 9d5f4fd7016a38c5b3a1fe09cc7a445c00a31b57 | 76e0b326446e440468b4ab54cfb8e26a6403f7d8 | refs/heads/master | 2022-02-06T23:03:21.305045 | 2016-03-09T14:56:01 | 2016-03-09T14:56:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,002 | java |
package org.eclipse.stardust.engine.api.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.eclipse.stardust.engine.api.ws.query.DeployedRuntimeArtifactQueryXto;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="deployedRuntimeArtifactQuery" type="{http://eclipse.org/stardust/ws/v2012a/api/query}DeployedRuntimeArtifactQuery"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"deployedRuntimeArtifactQuery"
})
@XmlRootElement(name = "findRuntimeArtifacts")
public class FindRuntimeArtifacts {
@XmlElement(required = true, nillable = true)
protected DeployedRuntimeArtifactQueryXto deployedRuntimeArtifactQuery;
/**
* Gets the value of the deployedRuntimeArtifactQuery property.
*
* @return
* possible object is
* {@link DeployedRuntimeArtifactQueryXto }
*
*/
public DeployedRuntimeArtifactQueryXto getDeployedRuntimeArtifactQuery() {
return deployedRuntimeArtifactQuery;
}
/**
* Sets the value of the deployedRuntimeArtifactQuery property.
*
* @param value
* allowed object is
* {@link DeployedRuntimeArtifactQueryXto }
*
*/
public void setDeployedRuntimeArtifactQuery(DeployedRuntimeArtifactQueryXto value) {
this.deployedRuntimeArtifactQuery = value;
}
}
| [
"thomas.wolfram@sungard.com"
] | thomas.wolfram@sungard.com |
39816846ed6f598e083f85daa5c15277437bad9a | ee5207436a3362bdb791727c73a3189dfa868ed8 | /src/org/dgpf/aggregation/alternative/CalculationParameters.java | 53842a201a36288b5d4d51b247487011a1de41ea | [] | no_license | GIPSY-dev/WSC-Gen | 7f1c387b47470f277e27e7994fbf6e4f942fddf6 | 25beebdda5c1a4a0e4c213fa97155e2b3455da87 | refs/heads/master | 2020-04-06T04:20:49.760697 | 2018-03-13T16:30:34 | 2018-03-13T19:11:48 | 82,968,360 | 1 | 2 | null | 2018-04-23T17:06:51 | 2017-02-23T20:27:06 | Java | UTF-8 | Java | false | false | 3,982 | java | /*
* Copyright (c) 2007 Thomas Weise for sigoa
* Simple Interface for Global Optimization Algorithms
* http://www.sigoa.org/
*
* E-Mail : info@sigoa.org
* Creation Date : 2007-03-27
* Creator : Thomas Weise
* Original Filename: org.dgpf.aggregation.simulation.CalculationParameters.java
* Last modification: 2007-03-27
* by: Thomas Weise
*
* License : GNU LESSER GENERAL PUBLIC LICENSE
* Version 2.1, February 1999
* You should have received a copy of this license along
* with this library; if not, write to theFree Software
* Foundation, Inc. 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA or download the license
* under http://www.gnu.org/licenses/lgpl.html or
* http://www.gnu.org/copyleft/lesser.html.
*
* Warranty : This software is provided "as is" without any
* warranty; without even the implied warranty of
* merchantability or fitness for a particular purpose.
* See the Gnu Lesser General Public License for more
* details.
*/
package org.dgpf.aggregation.alternative;
import java.io.Serializable;
/**
* This class represents the parameters needed by a calculation.
*
* @author Thomas Weise
*/
public class CalculationParameters implements Serializable {
/**
* the serial version uid
*/
private static final long serialVersionUID = 1;
/**
* the variable count
*/
private final int m_varCnt;
/**
* the virtual machine count
*/
private final int m_vmCnt;
/**
* the test count
*/
private final int m_testCnt;
/**
* the step count
*/
private final int m_stepCnt;
/**
* is the data constant or (otherwise) volatile?
*/
private final boolean m_isConstant;
/**
* Create a new calculation parameter record
*
* @param varCnt
* the count of variables
* @param vmCnt
* the virtual machine count
* @param testCnt
* the test count
* @param stepCnt
* the step count
* @param isConstant
* is the data constant or (otherwise) volatile?
*/
public CalculationParameters(final int varCnt, final int vmCnt,
final int testCnt, final int stepCnt, final boolean isConstant) {
super();
this.m_varCnt = varCnt;
this.m_vmCnt = vmCnt;
this.m_testCnt = Math.max(Calculation.MIN_TESTS, testCnt);
this.m_stepCnt = stepCnt;
this.m_isConstant = isConstant;
}
/**
* Create a new calculation parameter record
*
* @param params
* the parameters to copy
*/
public CalculationParameters(final CalculationParameters params) {
this(params.getVariableCount(), params.getVMCount(), params
.getTestCount(), params.getStepsPerTest(), params.isConstant());
}
/**
* Check whether the data is constant or (otherwise) volatile?
*
* @return <code>true</code> if and only if the is data constant,
* <code>false</code> if it is volatile?
*/
public boolean isConstant() {
return this.m_isConstant;
}
/**
* Obtain the variable count.
*
* @return the variable count
*/
public int getVariableCount() {
return this.m_varCnt;
}
/**
* Obtain the virtual machine count
*
* @return the virtual machine count
*/
public int getVMCount() {
return this.m_vmCnt;
}
/**
* Obtain the test count
*
* @return the test count
*/
public int getTestCount() {
return this.m_testCnt;
}
/**
* Obtain the count of steps per test
*
* @return the count of steps per test
*/
public int getStepsPerTest() {
return this.m_stepCnt;
}
}
| [
"happy.hacking.geek@gmail.com"
] | happy.hacking.geek@gmail.com |
fa113d777d6644dddc1cc6f567e8be412deaf7fb | 384e34588a18d5996674e37c0f0fe89f26c251d2 | /amazon/OverlapRectangle.java | 74e2c3237abded8a0c1e48934e7f6e678114824a | [] | no_license | wguo32/TechInterviewProblems | a52dc8d3ec9e4b7c099e6e21948c21af06b82658 | bec76ab423d0cd65bbae5d401fd72dd1d1678920 | refs/heads/master | 2020-03-24T08:57:50.150633 | 2018-07-27T12:49:02 | 2018-07-27T12:49:02 | 142,614,167 | 4 | 1 | null | 2018-07-27T19:04:02 | 2018-07-27T19:04:02 | null | UTF-8 | Java | false | false | 402 | java | /**
A rectangle is defined with two points, the upper left point and lower right point.
Point is a class with p.x, p.y;
*/
public class Solution {
public boolean isOverlap(Point l1, Point r1, Point l2, Point r2) {
if (l1.x> r2.x || r1.x < l2.x) {
return false;
}
if (l1.y < l2.y || r1.y > l2.y) {
return false;
}
return true;
}
}
| [
"shanfangzhao@gmail.com"
] | shanfangzhao@gmail.com |
8332669743f46dc9c4f44bb5ce2cc3833fe5b010 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/apache--cassandra/a991b64811f4d6adb6c7b31c0df52288eb06cf19/before/CompressedStreamReader.java | 8094c53bb462dd69194bbd465b8bb55a3cc9d98e | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,547 | 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.cassandra.streaming.compress;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import com.google.common.base.Throwables;
import org.apache.cassandra.io.sstable.format.SSTableWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.io.compress.CompressionMetadata;
import org.apache.cassandra.streaming.ProgressInfo;
import org.apache.cassandra.streaming.StreamReader;
import org.apache.cassandra.streaming.StreamSession;
import org.apache.cassandra.streaming.messages.FileMessageHeader;
import org.apache.cassandra.utils.BytesReadTracker;
import org.apache.cassandra.utils.Pair;
/**
* StreamReader that reads from streamed compressed SSTable
*/
public class CompressedStreamReader extends StreamReader
{
private static final Logger logger = LoggerFactory.getLogger(CompressedStreamReader.class);
protected final CompressionInfo compressionInfo;
public CompressedStreamReader(FileMessageHeader header, StreamSession session)
{
super(header, session);
this.compressionInfo = header.compressionInfo;
}
/**
* @return SSTable transferred
* @throws java.io.IOException if reading the remote sstable fails. Will throw an RTE if local write fails.
*/
@Override
@SuppressWarnings("resource")
public SSTableWriter read(ReadableByteChannel channel) throws IOException
{
logger.debug("reading file from {}, repairedAt = {}", session.peer, repairedAt);
long totalSize = totalSize();
Pair<String, String> kscf = Schema.instance.getCF(cfId);
if (kscf == null)
{
// schema was dropped during streaming
throw new IOException("CF " + cfId + " was dropped during streaming");
}
ColumnFamilyStore cfs = Keyspace.open(kscf.left).getColumnFamilyStore(kscf.right);
SSTableWriter writer = createWriter(cfs, totalSize, repairedAt, format);
CompressedInputStream cis = new CompressedInputStream(Channels.newInputStream(channel), compressionInfo);
BytesReadTracker in = new BytesReadTracker(new DataInputStream(cis));
try
{
for (Pair<Long, Long> section : sections)
{
assert cis.getTotalCompressedBytesRead() <= totalSize;
int sectionLength = (int) (section.right - section.left);
// skip to beginning of section inside chunk
cis.position(section.left);
in.reset(0);
while (in.getBytesRead() < sectionLength)
{
writeRow(writer, in, cfs);
// when compressed, report total bytes of compressed chunks read since remoteFile.size is the sum of chunks transferred
session.progress(desc, ProgressInfo.Direction.IN, cis.getTotalCompressedBytesRead(), totalSize);
}
}
return writer;
}
catch (Throwable e)
{
writer.abort();
drain(cis, in.getBytesRead());
if (e instanceof IOException)
throw (IOException) e;
else
throw Throwables.propagate(e);
}
}
@Override
protected long totalSize()
{
long size = 0;
// calculate total length of transferring chunks
for (CompressionMetadata.Chunk chunk : compressionInfo.chunks)
size += chunk.length + 4; // 4 bytes for CRC
return size;
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
2a6b8dc33d0ff0c409c2ff443cea2dd49914c9b4 | 1d3402be82764e6c670b3689c6995b527cbaa16b | /src/main/java/ru/netology/model/PurchaseItem.java | 23a2834e5061ec63f181428f1e8b1f923eb7cac5 | [] | no_license | Flayka/Lambda | 9652e0f8767c52f58e64f8f386fb67eef38acf42 | 2bf161899292cf3bf12930d873758cbc8aaf88af | refs/heads/master | 2022-11-07T09:45:17.515378 | 2020-06-28T16:34:33 | 2020-06-28T16:34:33 | 275,626,529 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 265 | java | package ru.netology.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PurchaseItem {
private int itemId;
private int itemPrice;
private int count;
}
| [
"rudakalexx@gmail.com"
] | rudakalexx@gmail.com |
a4245a461c09ee232bc09665c44279b53463c766 | ad3f163e6b3ce082acbc75812bac1d0ad2e56598 | /BlackCardnew6.2/app/src/main/java/com/sainti/blackcard/minterface/CoffeeRightItemClickListener.java | 6c2ab105826743f40f4612346ec98297598034fe | [] | no_license | NewBlackYoung/BlackCard-android | 5fec46fe0607f3fecf35608d7bb6e7dc762a1125 | e19d3d1171f0793dfdf5468524cae67461f27836 | refs/heads/master | 2020-04-01T17:12:38.202993 | 2018-10-17T09:04:51 | 2018-10-17T09:04:51 | 153,418,457 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 206 | java | package com.sainti.blackcard.minterface;
/**
* Created by YuZhenpeng on 2018/3/16.
*/
public interface CoffeeRightItemClickListener {
void onCoffeeRightItemClick(int position, int code, int wai);
}
| [
"guohuichen@blackfish.cn"
] | guohuichen@blackfish.cn |
5d8abcc9310cb0534c1c76ce3fd2bf269db96d30 | 8dc365115779303871081ec3246387073a644713 | /0305SampleProject/src/servlet/member/MemberDeleteServlet.java | c2a708e84e18b9655032f887f19bd60970bd71e3 | [] | no_license | hahacandy/jsp_s | eddeb7eabddf967bc4bcbcf18e3d26198b70d437 | aed6bac075820e2564f8d2b3e4e9945aeca617be | refs/heads/master | 2021-01-08T16:01:21.993537 | 2020-08-03T18:59:33 | 2020-08-03T18:59:33 | 242,073,322 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,856 | java | package servlet.member;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.member.MemberDAO;
import model.member.MemberVO;
/**
* Servlet implementation class MemberDeleteServlet
*/
@WebServlet("/MemberDeleteServlet")
public class MemberDeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MemberDeleteServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("Member/userinfo_del.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
MemberDAO dao = new MemberDAO();
HttpSession session = request.getSession();
String userid = ((MemberVO)session.getAttribute("user")).getUserid();
String currentPasswd = request.getParameter("passwd");
int result = dao.deleteUser(userid, currentPasswd);
request.setAttribute("result", result);
RequestDispatcher rd = request.getRequestDispatcher("Member/userinfo_del_pro.jsp");
rd.forward(request, response);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
b81e9b7442962e59b593b30b54a786a19c1476fe | 59a2044e454542e7f7412dbd2f31fffe27f3c3f3 | /onlinepharmacymanagement/src/main/java/com/mahbub/securitywithsql/controller/SalesDto.java | 428b03cd192547c8e3ac20755f6f3e58c4d39abb | [] | no_license | sakmahbub/problem | 6c623895ee4ff81dfc7871fd90dba247481b9e88 | f1662dcbafd1fd32e70c4b55ca6dbf570b277c25 | refs/heads/master | 2020-05-09T13:00:10.933212 | 2019-04-13T07:05:07 | 2019-04-13T07:05:07 | 181,133,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 616 | java | package com.mahbub.securitywithsql.controller;
import com.mahbub.securitywithsql.entity.Sales;
import java.util.ArrayList;
import java.util.List;
public class SalesDto {
private List<Sales> saless = new ArrayList<>();
public SalesDto() {
this.saless.add(new Sales());
}
public void addSales(Sales sales) {
this.saless.add(sales);
}
public void removeSales(int index) {
this.saless.remove(index);
}
public List<Sales> getSaless() {
return saless;
}
public void setSaless(List<Sales> saless) {
this.saless = saless;
}
}
| [
"sakmahbub@gmail.com"
] | sakmahbub@gmail.com |
6cb6f3667768238fc80086c2b9c9ac901b332c58 | 704498e15d729d23d8ad433f526be50d3c926247 | /src/main/java/com/sunmq/rabbitmq/RabbitmqApplication.java | a6c311e40356ca9410156931b54b1099da09978f | [] | no_license | JasonsSun/rabbitmq | b6f97b7ca20c8d69511948dc8047f5fe5a2d9b87 | f5477c6ff1b360ead92620dac07ad6ecd1eac923 | refs/heads/master | 2020-11-24T20:09:08.095130 | 2019-12-17T02:57:01 | 2019-12-17T02:57:01 | 228,324,751 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package com.sunmq.rabbitmq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RabbitmqApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitmqApplication.class, args);
}
}
| [
"chuzhenhua"
] | chuzhenhua |
5735be5582945ffca2488011276d975e025c5009 | 826ebdb83fe62fd95b9e640431e093ef6cfd8e92 | /app/src/main/java/com/app05/app05/MainActivity.java | b3add1fc130cf95e29efaadbc342ef2aab576072 | [] | no_license | wanage/Androidkadai | 612722442a1a9630be0c1df6efba61bbdb7e08ba | 3017c0d9d33fcb9132bcfbbc05f1d074f140fa50 | refs/heads/master | 2020-06-27T18:27:16.716364 | 2016-08-18T11:51:01 | 2016-08-18T11:51:01 | 65,992,922 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,848 | java | package com.app05.app05;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Calendar;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.SMO;
import weka.classifiers.meta.FilteredClassifier;
import weka.classifiers.trees.J48;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Utils;
import weka.core.converters.ArffLoader;
import weka.core.converters.ConverterUtils;
import weka.filters.unsupervised.attribute.Remove;
import weka.core.*;
public class MainActivity extends Activity /*implements SensorEventListener*/{
private SensorManager manager;
private Sensor sensor;
private SensorEventListener sample_listener;
float gx,gy,gz;
TextView text1;
TextView text2;
TextView text3;
TextView text4;
int s,m;
Instances train;
J48 classifier;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(R.layout.activity_main);
text1 = (TextView)findViewById(R.id.textView1);
text2 = (TextView)findViewById(R.id.textView2);
text3 = (TextView)findViewById(R.id.textView3);
text4 = (TextView)findViewById(R.id.answerView);
sample_listener = new SampleSensorEventListener();
Button sendButton = (Button) findViewById(R.id.button1);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), MyView.class);
startActivity(intent);
}
});
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Start:",s +":"+ m);
}
});
Button stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Stop:",s +":"+ m);
}
});
//ArffLoader al = new ArffLoader();
try {
ArffLoader al = new ArffLoader();
al.setFile(new File("/storage/sdcard0/arffdata/Human.arff"));
train = new Instances(al.getDataSet());
train.setClassIndex(train.numAttributes()-1);
classifier = new J48();
classifier.buildClassifier(train);
//} catch (IOException e) {
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// @SuppressLint("SdCardPath") ConverterUtils.DataSource source = new ConverterUtils.DataSource("/storage/sdcard0/arffdata/Human.arff");
// Instances train= source.getDataSet();
// Evaluation eval = new Evaluation(train);
// eval.evaluateModel(classifier, train);
// System.out.println(eval.toSummaryString());
}
@Override
protected void onResume(){
super.onResume();
manager = (SensorManager)getSystemService(SENSOR_SERVICE);
sensor = manager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
manager.registerListener(sample_listener, sensor, SensorManager.SENSOR_DELAY_NORMAL );
}
@Override
protected void onPause(){
super.onPause();
manager.unregisterListener(sample_listener);
}
class SampleSensorEventListener implements SensorEventListener{
@Override
public void onSensorChanged(SensorEvent e) {
if(e.sensor.getType() == Sensor.TYPE_ACCELEROMETER ){
Log.d("aiueo","mae");
gx = e.values[0];
gy = e.values[1];
gz = e.values[2];
String str_x = "X軸の加速度:" + gx;
text1.setText(str_x);
String str_y = "Y軸の加速度:" + gy;
text2.setText(str_y);
String str_z = "Z軸の加速度:" + gz;
text3.setText(str_z);
// Kakikomi();
Log.d("aiueo","ato");
j48make();
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
}
private void Kakikomi(){
super.onStop();
OutputStream out;
Calendar now = Calendar.getInstance();
s = now.get(now.SECOND);
m = now.get(now.MILLISECOND);
try {
out = openFileOutput("XYZ.csv", Context.MODE_APPEND);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
//追記する
writer.write(String.valueOf(gx) + "," + String.valueOf(gy) + ","+String.valueOf(gz)+",,,"+s+":"+m+"\n");
writer.close();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
/**
* This example class trains a J48 classifier on a dataset and outputs for
* a second dataset the actual and predicted class label, as well as the
* class distribution.
*/
public void j48make() {
try {
Attribute x = new Attribute("x", 0);
Attribute y = new Attribute("y", 1);
Attribute z = new Attribute("z", 2);
Instance instance = new DenseInstance(3);
instance.setValue(x, gx);
instance.setValue(y, gy);
instance.setValue(z, gz);
instance.setDataset(train);
double result = classifier.classifyInstance(instance);
// System.out.println(result);
if(result == 1){
text4.setText("静止中");
}
else if(result == 0){
text4.setText("歩行中");
}
else {
text4.setText("走行中");
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | [
"ezimeso@ezimeso.local"
] | ezimeso@ezimeso.local |
e440633389e2daeff3860428466f5b3324b37501 | 7a91ab0cffc9d30912840b7752ef11775040ef8a | /java/annotations/src/UseCase.java | 92e4e4714f705b6b13f3fd4cb64cb52628e1e3a5 | [] | no_license | tttqqq/code | 8728910411f8df1d064cb25ceb2f52b83e73973b | ea9121e093ff6c1c6fa4023f9925c0e4ee051faf | refs/heads/master | 2022-02-03T23:02:09.681486 | 2022-01-22T13:30:30 | 2022-01-22T13:30:30 | 131,322,942 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 206 | java | import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
public int id();
public String description() default "nod description";
}
| [
"tttqqq@foxmail.com"
] | tttqqq@foxmail.com |
a1c437eba202a2ea311dbc73184a1e3087fe7b45 | 462668f00eefbc55be61963b113dc9217c8adde4 | /Spring_MVC/ninja_gold_game/src/main/java/com/aws/code/Gold.java | 63f20f37d15d52cc913f47199f927c68a5f4453b | [] | no_license | AwsRadwan/Java_Stack | 432156654a0f7858bd4c0a2d106587080c09f89d | fd6c7ef695aa06bfad8cf868e49d52563b3fcbb3 | refs/heads/master | 2023-06-03T03:57:30.979453 | 2021-06-30T17:11:46 | 2021-06-30T17:11:46 | 378,265,472 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,300 | java | package com.aws.code;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Gold {
public static int count=0;
public static ArrayList<String> list = new ArrayList<String>();
// HttpSession session;
@RequestMapping("/")
public String main(HttpSession session) {
session.setAttribute("count", count);
session.setAttribute("list", list);
return "ninja.jsp";
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public String addGold(@RequestParam(value = "hidden") String val) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
if(val.equals("hidden1")) {
int randomNum = ThreadLocalRandom.current().nextInt(10, 21);
count += randomNum;
LocalDateTime now = LocalDateTime.now();
String x = String.format("earned %d golds from the farm! %s .", randomNum, dtf.format(now));
list.add(x);
return "redirect:/";
}
if(val.equals("hidden2")) {
int r2 = ThreadLocalRandom.current().nextInt(5, 11);
count += r2;
LocalDateTime now = LocalDateTime.now();
String x = String.format("earned %d golds from the Cave! %s .", r2, dtf.format(now));
list.add(x);
return "redirect:/";
}
if(val.equals("hidden3")) {
int r3 = ThreadLocalRandom.current().nextInt(2, 6);
count += r3;
LocalDateTime now = LocalDateTime.now();
String x = String.format("earned %d golds from the House! %s .", r3, dtf.format(now));
list.add(x);
return "redirect:/";
}
if(val.equals("hidden4")) {
int r4 = ThreadLocalRandom.current().nextInt(-50, 51);
count += r4;
LocalDateTime now = LocalDateTime.now();
String x = String.format("earned %d golds from the Casino! %s .", r4, dtf.format(now));
list.add(x);
return "redirect:/";
}
return "redirect:/";
}
@RequestMapping("/reset")
public String reset() {
count =0;
list.clear();
return "redirect:/";
}
}
| [
"awsradwan3@gmail.com"
] | awsradwan3@gmail.com |
cd04a0c21b2124f7b4b65d28b055a80f5b039d4e | 1ccb847c1d9a8f2078971c56f775cb83ee7220d7 | /src/main/java/ua/com/karre/topjava/util/exception/ExceptionUtil.java | 61b0ff7e0b162b3708546591a5c79b77f41873ca | [] | no_license | Nom3355/topjava | 8043e01261f486a5fcadb45a32dc8f4f2f5893c2 | 03b4580ab4eb9e2fe8a6feccc85666201831b6c9 | refs/heads/master | 2021-01-10T15:51:36.548676 | 2015-10-15T11:31:05 | 2015-10-15T11:31:05 | 43,289,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 670 | java | package ua.com.karre.topjava.util.exception;
import ua.com.karre.topjava.LoggerWrapper;
public class ExceptionUtil {
private static final LoggerWrapper LOG = LoggerWrapper.get(ExceptionUtil.class);
public static void check(boolean found, int id) {
check(found, "id=" + id);
}
public static void check(boolean found, String msg) {
if (!found) throw LOG.getNotFoundException("Not found entity with " + msg);
}
public static <T> T check(T object, int id) {
return check(object, "id=" + id);
}
public static <T> T check(T object, String msg) {
check(object != null, msg);
return object;
}
}
| [
"vladv3355@gmail.com"
] | vladv3355@gmail.com |
0ccff6d1fb43816a146f0dd34295ef85f86e8fa1 | 4bbfa242353fe0485fb2a1f75fdd749c7ee05adc | /ims-core/src/main/java/com/ailk/ims/complex/AccountComplex.java | 96c1f476b24ebd98d6523a16d12053a326731e78 | [] | no_license | 859162000/infosystem | 88b23a5b386600503ec49b14f3b4da4df7a6d091 | 96d4d50cd9964e713bb95520d6eeb7e4aa32c930 | refs/heads/master | 2021-01-20T04:39:24.383807 | 2017-04-01T10:59:24 | 2017-04-01T10:59:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 449 | java | package com.ailk.ims.complex;
import com.ailk.openbilling.persistence.acct.entity.CaAccount;
/**
* Acct3hBean使用的账户封装类
* @Description
* @author luojb
* @Date 2012-8-30
*/
public class AccountComplex extends BaseComplex
{
private CaAccount account;
public CaAccount getAccount()
{
return account;
}
public void setAccount(CaAccount account)
{
this.account = account;
}
}
| [
"ljyshiqian@126.com"
] | ljyshiqian@126.com |
ab6ff927808911ad91927fb7108ad0d9ce7880d7 | 9cabe1b78fc1d1905b74bcc26fffb72308e2b771 | /baekjoon/src/step2/No_7.java | d29af65cf80c4140a18454085bc1392e5c27bbef | [] | no_license | mod157/acmicpc | eb05e2dc2b103b9a1e9bf21162aa8f6bfda7b2b2 | 017a1702429dfd02a543504758f2b87797087050 | refs/heads/master | 2021-08-15T03:54:04.950538 | 2017-11-17T08:53:29 | 2017-11-17T08:53:29 | 107,522,360 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 294 | java | package step2;
/*
* 7´Ü°è 2558¹ø A+B-2
*/
import java.util.Scanner;
public class No_7 {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
if(a+b > 0 && a+b < 10)
System.out.println(a+b);
}
}
| [
"Nammu8395@gmail.com"
] | Nammu8395@gmail.com |
a60c318a755fc32758f6a651d9e2c79301a54654 | e89fdebd9e9345fea9e99020f56411c1a3d4d06d | /src/main/java/com/nc/finalproject/service/PetService.java | 57bd49b703a3bb9038ae4bf4d3a4ff4b621e72a9 | [] | no_license | ant4ded/VetClinic | 782d00ed2c80f6011be020d9d38234e1ba596716 | 9f9703a73326ca378110e2da4e2ffcaffed5c4b0 | refs/heads/master | 2022-07-06T11:31:14.072532 | 2020-04-07T17:12:18 | 2020-04-07T17:12:18 | 243,492,657 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 456 | java | package com.nc.finalproject.service;
import com.nc.finalproject.model.Pet;
import java.util.List;
/**
* Interface for operations with entity {@link Pet} and associated table in the database.
*
* @author WildDed
* @version 1.0
*/
public interface PetService {
Pet findByName(String name);
List<Pet> findAll();
<S extends Pet> S saveAndFlush(S s);
void deleteById(Long aLong);
List<Pet> findAllByUsername(String username);
}
| [
"prostochelik2ooo@gmail.com"
] | prostochelik2ooo@gmail.com |
0065aa94d86e253427037faedecf0fd626680f5e | ed485890395b0adc7b6544986c5cbdb5098caaaa | /src/main/java/com/qinfei/qferp/service/dto/PlateHistoryOutDto.java | 82ed935d31703f0c0199556e462f55cb9a07a865 | [] | no_license | xeon-ye/croa | ef44a2a3815badd216cd93d829d810d84ef34ffc | fc3806685f9b4676fcaa9cec940f902c4bfcff7f | refs/heads/master | 2023-02-23T13:21:18.820765 | 2021-01-28T11:01:37 | 2021-01-28T11:01:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 625 | java | package com.qinfei.qferp.service.dto;
import com.qinfei.qferp.entity.performance.PerformanceHistory;
import java.util.List;
/**
* 返回plate和所有子节点
*/
public class PlateHistoryOutDto {
private PerformanceHistory plate;
private List<PerformanceHistory> childs;
public PerformanceHistory getPlate() {
return plate;
}
public void setPlate(PerformanceHistory plate) {
this.plate = plate;
}
public List<PerformanceHistory> getChilds() {
return childs;
}
public void setChilds(List<PerformanceHistory> childs) {
this.childs = childs;
}
}
| [
"649681131@qq.com"
] | 649681131@qq.com |
52759f555b9a417972dfee1f98a58ad061a13351 | 6c50c267d654fd539b7add70578820e3822e4eef | /Program2/src/ServerThread.java | 4d04a83bb581efd252fa75bce03c5c53491c5def | [] | no_license | ChaseKnapp/DataComm | 357c0c7034de1474254f70ce9a2cc1e57a6e392f | a7f35d696dd7238b26c9a4efb6165aa4f1b01761 | refs/heads/master | 2021-01-12T06:46:58.429150 | 2016-12-19T10:35:59 | 2016-12-19T10:35:59 | 76,826,707 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,424 | java |
import java.io.*;
import java.net.*;
/**
Sends to server
*/
public class ServerThread extends Thread
{
private Socket sock;
private Logger log;
private PrintWriter out;
private BufferedReader in;
public ServerThread(Socket sock, Logger log)
{
this.log = log;
this.sock = sock;
try
{
out = new PrintWriter(sock.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
}
catch (Exception e)
{
log.print("Error: " + e.getClass().toString() + e);
}
}
@Override
public void run()
{
try
{
PolyAlphabet pa = new PolyAlphabet();
boolean quit = false;
while (!quit)
{
if (!sock.isClosed())
{
String inLine = in.readLine();
if (inLine.equalsIgnoreCase("Quit"))
quit = true;
else
{
String outLine = pa.encode(inLine);
out.println(outLine);
}
}
else
quit = true;
}
out.println("Good Bye!");
sock.close();
log.print("\tConnection Closed. Port " + sock.getPort());
}
catch (Exception e)
{
log.print("\tConnection Closed. Port " + sock.getPort());
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
8bacaff2f7e8a8ac2f72ca01c6c2fa143395bdee | a4c62586548e6e7c6276eff5ae0df9b76439d6ae | /src/test/java/ar/com/fn/domain/match/SimpleMatchResolverTest.java | 76a7a2f5e2806dcc3914fca8a0fc46811a16baf9 | [] | no_license | loniszczuk/furry-ninja | 0035e5b15cd20cadcde8504da5c5bb75c932acfe | 9f6fe7d3ae427e7498988827d0647188cc13a939 | refs/heads/master | 2020-12-26T03:22:59.135906 | 2014-04-10T20:38:59 | 2014-04-10T20:38:59 | 17,033,106 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,341 | java | package ar.com.fn.domain.match;
import ar.com.fn.domain.goalie.SimpleGoalie;
import ar.com.fn.domain.kicker.SimpleKicker;
import ar.com.fn.domain.matchmaking.User;
import ar.com.fn.domain.penalty.Position;
import org.testng.annotations.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class SimpleMatchResolverTest {
@Test
public void test() {
Team t1 = new Team("team1");
t1.addKicker(new SimpleKicker("jose", 0, Position.CENTER));
t1.addKicker(new SimpleKicker("jose", 0, Position.CENTER));
t1.addKicker(new SimpleKicker("jose", 0, Position.CENTER));
t1.addKicker(new SimpleKicker("jose", 0, Position.CENTER));
t1.addKicker(new SimpleKicker("jose", 0, Position.CENTER));
Team t2 = new Team("team2");
t2.addGoalie(new SimpleGoalie("jose", 1, Position.CENTER));
t2.addGoalie(new SimpleGoalie("jose", 1, Position.CENTER));
t2.addGoalie(new SimpleGoalie("jose", 1, Position.CENTER));
t2.addGoalie(new SimpleGoalie("jose", 1, Position.CENTER));
t2.addGoalie(new SimpleGoalie("jose", 1, Position.CENTER));
SimpleMatchResolver m = new SimpleMatchResolver(new User("u1"), t1, new User("u2"), t2);
Match s = m.getMatch();
assertEquals(s.getWinner(), "u2");
}
@Test
public void test2() {
Team t1 = new Team("team1");
t1.addKicker(new SimpleKicker("pepe", 1, Position.CENTER));
t1.addKicker(new SimpleKicker("pepe", 1, Position.CENTER));
t1.addKicker(new SimpleKicker("pepe", 1, Position.CENTER));
t1.addKicker(new SimpleKicker("pepe", 1, Position.CENTER));
t1.addKicker(new SimpleKicker("pepe", 1, Position.CENTER));
Team t2 = new Team("team2");
t2.addGoalie(new SimpleGoalie("jose", 0.001f, Position.LEFT));
t2.addGoalie(new SimpleGoalie("jose", 0.001f, Position.LEFT));
t2.addGoalie(new SimpleGoalie("jose", 0.001f, Position.LEFT));
t2.addGoalie(new SimpleGoalie("jose", 0.001f, Position.LEFT));
t2.addGoalie(new SimpleGoalie("jose", 0.001f, Position.LEFT));
SimpleMatchResolver m = new SimpleMatchResolver(new User("u1"), t1, new User("u2"), t2);
Match s = m.getMatch();
assertEquals(s.getWinner(), "u1");
}
} | [
"loniszczuk@gmail.com"
] | loniszczuk@gmail.com |
b82241f1cd7700414452ca2acc86bfa93d4ae17e | 6d9f43cfe25f91a0aba12454e193eaf8b80e6ab9 | /selectView/app/src/main/java/exam/day03/view/selectview/view/adapter/ActorItem.java | 03c312a33d968754a81671aff91beb4516461c8f | [] | no_license | sonic247897/multicampus-android | 5f35a9571f17bbc06a26ada415146142eb6987db | 914cc401091682c77e65e9281f715d7c9873b816 | refs/heads/master | 2021-04-23T12:42:55.482707 | 2020-06-02T05:31:23 | 2020-06-02T05:31:23 | 249,926,079 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 578 | java | package exam.day03.view.selectview.view.adapter;
public class ActorItem {
int Img;
String name;
String date;
String msg;
public ActorItem(int img, String name, String date, String msg) {
this.Img = img;
this.name = name;
this.date = date;
this.msg = msg;
}
@Override
public String toString() {
return "ActorItem{" +
"Img=" + Img +
", name='" + name + '\'' +
", date='" + date + '\'' +
", msg='" + msg + '\'' +
'}';
}
}
| [
"sonic247897@gmail.com"
] | sonic247897@gmail.com |
43d39a797ef907247c722778b78bd4774fddfdfd | 9b95d74efbda27e949913d16fda7b9e578701b23 | /ArrayException.java | b6558177f3ac89c7fedc0680dddf4a8b7be51bf3 | [] | no_license | ParthGada/JavaPrograms | ea62f4d8088acf39c6011dfa6303ebee1f7b1159 | 26a26f023cd29b992efc9e4049d8e84273a672f9 | refs/heads/master | 2020-12-02T09:59:42.483109 | 2017-07-09T09:44:13 | 2017-07-09T09:44:13 | 96,673,747 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 331 | java | package MYP_4B;
public class ArrayException {
public static void main(String args[]){
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3] );
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("exception thrown :" +e);
}
System.out.println("out of bounds");
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7bd6b656f679aeda1494f084080e19b9bff3e08a | 5807339e04d597cb87b12c7f2a18a148044d90d3 | /src/main/java/com/itaas/ott/ChannelList.java | 5cc5dfe7b9ca35a6f68b26a28f247639430b68f4 | [] | no_license | simhadrisidhu/FirstRepo | 28e7fb6d81fbfa130b7c04dcfb8ac2ac559f7522 | ee226d67339c6af45dc48b16123e3f1fd0627488 | refs/heads/master | 2021-06-03T11:46:15.068233 | 2018-06-09T14:24:35 | 2018-06-09T14:24:35 | 56,225,765 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,523 | java | package com.itaas.ott;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class ChannelList {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpPost httpPost1 = new HttpPost("http://221.226.2.232:17200/EPG/JSON/ChannelList");
System.out.println("inside ChannelList....");
HttpResponse httpResponse2 = null;
DefaultHttpClient httpClient2 = new DefaultHttpClient();
httpPost1.setHeader("Cookie", "JSESSIONID="+args[0]);
JSONObject object = new JSONObject();
object.put("count",-1);
object.put("offset",0);
object.put("contenttype","CHANNEL");
object.put("domain",0);
String content = object.toString();
System.out.println(" ChannelList Request::"+ content);
httpPost1.setEntity(new StringEntity(content, "UTF-8"));
httpResponse2 = httpClient2.execute(httpPost1);
BufferedReader reader2 = new BufferedReader(new InputStreamReader(httpResponse2.getEntity().getContent()));
String inputLine2;
StringBuffer response2 = new StringBuffer();
while ((inputLine2 = reader2.readLine()) != null) {
response2.append(inputLine2);
}
reader2.close();
System.out.println(" ChannelList Response::"+ response2.toString());
}
}
| [
"simhadrisidhu@gmail.com"
] | simhadrisidhu@gmail.com |
fde681ed9ada483298ec74bf1e071bfdb2eb1986 | 69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e | /methods/Method_45340.java | 0237dc619feb6c03daaaaccf4e9651d13b8419ff | [] | no_license | P79N6A/icse_20_user_study | 5b9c42c6384502fdc9588430899f257761f1f506 | 8a3676bc96059ea2c4f6d209016f5088a5628f3c | refs/heads/master | 2020-06-24T08:25:22.606717 | 2019-07-25T15:31:16 | 2019-07-25T15:31:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 150 | java | public static MocoJunitRunner restRunner(final RestServer server){
checkNotNull(server,"Server should not be null");
return httpRunner(server);
}
| [
"sonnguyen@utdallas.edu"
] | sonnguyen@utdallas.edu |
1afb857c78db58d90c41fcc86abec625681620c5 | 1f9849973568577c97902b5bdbc19b45138e4086 | /src/main/java/com/yihan/happy/user/service/OrderForMoneyFromAndroidServiceImpl.java | cf659ef372b8aa4478bfed8f06a8bb2caf982b69 | [] | no_license | jianying9/happy | 7af416ecc8dc32b2c106d21e24251bc8fb146a09 | c17d7207c8c39a1c7334e158431f793f001add3e | refs/heads/master | 2020-04-11T02:41:05.583772 | 2014-09-17T14:30:23 | 2014-09-17T14:30:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,063 | java | package com.yihan.happy.user.service;
import com.wolf.framework.data.TypeEnum;
import com.wolf.framework.local.InjectLocalService;
import com.wolf.framework.service.ResponseState;
import com.wolf.framework.service.Service;
import com.wolf.framework.service.ServiceConfig;
import com.wolf.framework.service.parameter.RequestConfig;
import com.wolf.framework.service.parameter.ResponseConfig;
import com.wolf.framework.worker.context.MessageContext;
import com.yihan.happy.config.ActionGroupNames;
import com.yihan.happy.config.ActionNames;
import com.yihan.happy.user.localservice.UserLocalService;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author jianying9
*/
@ServiceConfig(
actionName = ActionNames.ORDER_FOR_MONEY_FROM_ANDROID,
requestConfigs = {
@RequestConfig(name = "zfb", typeEnum = TypeEnum.CHAR_60, desc = "支付宝帐号"),
@RequestConfig(name = "androidPoint", typeEnum = TypeEnum.LONG, desc = "兑换的android积分数量")
},
responseConfigs = {
@ResponseConfig(name = "orderId", typeEnum = TypeEnum.LONG, desc = "订单id")
},
responseStates = {
@ResponseState(state = "SUCCESS", desc = "订单创建成功")
},
validateSession = true,
response = true,
group = ActionGroupNames.USER,
desc = "android创建提现类型的订单")
public class OrderForMoneyFromAndroidServiceImpl implements Service {
//
@InjectLocalService()
private UserLocalService userLocalService;
@Override
public void execute(MessageContext messageContext) {
String zfb = messageContext.getParameter("zfb");
String androidPoint = messageContext.getParameter("androidPoint");
String id = messageContext.getSession().getSid();
String orderId = this.userLocalService.insertMoneyOrderFromAndroid(id, zfb, androidPoint);
Map<String, String> resultMap = new HashMap<String, String>(2, 1);
resultMap.put("orderId", orderId);
messageContext.setMapData(resultMap);
messageContext.success();
}
}
| [
"jianying9@jianying9"
] | jianying9@jianying9 |
44469e2bd2f7fbbac3c12733b1eb0bb9e6d97c1c | 344365c8156f3f1717129ea7c04c783e58d7518b | /src/main/java/com/wapple/mapper/ProductMapper.java | 030ba1a88a1f35656d5fae9343454e8b09f18db1 | [] | no_license | gexiaotong1994/wapple | 4ffc584ff0082ef2f3e388559958b2b32681219a | 6a0b86d59ea72efda9ba2bbf5a39910204cf1c80 | refs/heads/master | 2020-03-20T09:29:47.345629 | 2018-07-22T23:07:09 | 2018-07-22T23:07:09 | 137,339,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 734 | java | package com.wapple.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import com.wapple.pojo.Product;
@Mapper
public interface ProductMapper {
String insertProductSql = "INSERT INTO t_product(category_id,`name`,main_image,stock,`desc`,price,sales,`title`) VALUE(#{categoryId},#{name},#{mainImage},#{stock},#{desc},#{price},#{sales},#{title})";
String queryProductListSql = "select * from t_product";
@Insert(insertProductSql)
int insertProductMapper(Product prodcut);
}
| [
"1138366029@qq.com"
] | 1138366029@qq.com |
fd58e5653f38c461c92fb15c8a5e48c7125ea419 | 9a70b3e505c57f2ac8ce17ca9e94df65b4e89558 | /android/app/src/main/kotlin/com/app/apprfid/asciiprotocol/parameters/IQueryParameters.java | 5265a194e4fc22f14aa1ee30c077e8f00bd7f043 | [] | no_license | MobilyteApps/volteo_RFID | d655c5ee1b0177dc2731f22d6255b0e5df737292 | 4e2f269d5e66897bd1e4a5d47322f2323ac0d5cf | refs/heads/master | 2022-04-16T22:00:49.857984 | 2020-03-11T10:10:58 | 2020-03-11T10:10:58 | 246,535,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 561 | java | package com.app.apprfid.asciiprotocol.parameters;
import com.app.apprfid.asciiprotocol.enumerations.QuerySelect;
import com.app.apprfid.asciiprotocol.enumerations.QuerySession;
import com.app.apprfid.asciiprotocol.enumerations.QueryTarget;
public interface IQueryParameters {
QuerySelect getQuerySelect();
QuerySession getQuerySession();
QueryTarget getQueryTarget();
void setQuerySelect(QuerySelect querySelect);
void setQuerySession(QuerySession querySession);
void setQueryTarget(QueryTarget queryTarget);
}
| [
"sanjeev.kumar@infostride.com"
] | sanjeev.kumar@infostride.com |
7e5fcb375d03a2cc38452360eeb512dcc14feea0 | 90a3c5abe3eacdff925ddfba9d79e9076ae9fd78 | /jgk-springsecurity-root/jgk-springsecurity-stateless-restful/src/main/java/com/jgk/springrecipes/springsecurity/stateless/restful/controller/SimpleController.java | 8f9d8590be662a513a75336193607d426d8518c2 | [] | no_license | test-user-bb/jgk-spring-recipes | 60407a6a6f58b306d1844651ae2c5a3bee3a9cb7 | 47b19c4afef510beded46006145656d6062be11d | refs/heads/master | 2016-09-06T11:58:39.818564 | 2012-04-01T19:02:18 | 2012-04-01T19:02:18 | 42,295,670 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,599 | java | package com.jgk.springrecipes.springsecurity.stateless.restful.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SimpleController {
public SimpleController() {
System.out.println("SimpleController");
}
@RequestMapping(value="/")
public @ResponseBody List<String> restRoot() {
List<String> deployHelp = new ArrayList<String>();
deployHelp.add("Root for root, this is the default page");
deployHelp.add(String.format(" - ../%s/","ROOT TIME"));
return deployHelp;
}
@RequestMapping(value="/simple")
public @ResponseBody List<String> restSimple() {
List<String> deployHelp = new ArrayList<String>();
deployHelp.add("Simple for root");
deployHelp.add(String.format(" - ../%s/","SOMI"));
return deployHelp;
}
@RequestMapping(value="/help")
public @ResponseBody List<String> restHelp() {
List<String> deployHelp = new ArrayList<String>();
deployHelp.add("Help for root");
deployHelp.add(String.format(" - ../%s/","HELPY"));
return deployHelp;
}
@RequestMapping(value="/OUCHER")
public @ResponseBody List<String> restBOGEY() {
List<String> deployHelp = new ArrayList<String>();
deployHelp.add("OUCHER for ROOT");
deployHelp.add(String.format(" - ../%s/","CLJVOIJSOJFS"));
return deployHelp;
}
}
| [
"javapda@gmail.com"
] | javapda@gmail.com |
8db5d48a4877ff67fcaec719cc98013a91ce75c9 | 9fa3461f47951b96fb6f754ee543b15f1eb9b0a6 | /app/src/main/java/com/troop/freedcam/sonyapi/sonystuff/SimpleCameraEventObserver.java | 073b5891921964eaf0d7daecc9445092da618720 | [] | no_license | stephenstud/FreeDCam | 42ccc3a31260c911f4ec77af857c8403ffc76d2c | 450e6913a78563813cf589c9ca5877c6bf21d020 | refs/heads/master | 2021-01-17T22:08:20.240021 | 2014-12-22T09:29:18 | 2014-12-22T09:29:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,644 | java | /*
* Copyright 2014 Sony Corporation
*/
package com.troop.freedcam.sonyapi.sonystuff;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* A simple observer class for some status values in Camera. This class supports
* only a few of values of getEvent result, so please add implementation for the
* rest of values you want to handle.
*/
public class SimpleCameraEventObserver {
private static final String TAG = SimpleCameraEventObserver.class.getSimpleName();
/**
* A listener interface to receive these changes. These methods will be
* called by UI thread.
*/
public interface ChangeListener {
/**
* Called when the list of available APIs is modified.
*
* @param apis a list of available APIs
*/
void onApiListModified(List<String> apis);
/**
* Called when the value of "Camera Status" is changed.
*
* @param status camera status (ex."IDLE")
*/
void onCameraStatusChanged(String status);
/**
* Called when the value of "Liveview Status" is changed.
*
* @param status liveview status (ex.true)
*/
void onLiveviewStatusChanged(boolean status);
/**
* Called when the value of "Shoot Mode" is changed.
*
* @param shootMode shoot mode (ex."still")
*/
void onShootModeChanged(String shootMode);
/**
* Called when the value of "zoomPosition" is changed.
*
* @param zoomPosition zoom position (ex.12)
*/
void onZoomPositionChanged(int zoomPosition);
/**
* Called when the value of "storageId" is changed.
*
* @param storageId storageId (ex. "Memory Card 1")
*/
void onStorageIdChanged(String storageId);
// :
// : add methods for Event data as necessary.
}
/**
* Abstract class to receive these changes. please override methods that you
* need.
*/
public abstract static class ChangeListenerTmpl implements ChangeListener {
@Override
public void onApiListModified(List<String> apis) {
}
@Override
public void onCameraStatusChanged(String status) {
}
@Override
public void onLiveviewStatusChanged(boolean status) {
}
@Override
public void onShootModeChanged(String shootMode) {
}
@Override
public void onZoomPositionChanged(int zoomPosition) {
}
@Override
public void onStorageIdChanged(String storageId) {
}
}
private final Handler mUiHandler;
private SimpleRemoteApi mRemoteApi;
private ChangeListener mListener;
private boolean mWhileEventMonitoring = false;
private boolean mIsActive = false;
// Current Camera Status value.
private String mCameraStatus;
// Current Liveview Status value.
private boolean mLiveviewStatus;
// Current Shoot Mode value.
private String mShootMode;
// Current Zoom Position value.
private int mZoomPosition;
// Current Storage Id value.
private String mStorageId;
// :
// : add attributes for Event data as necessary.
/**
* Constructor.
*
* @param context context to notify the changes by UI thread.
* @param apiClient API client
*/
public SimpleCameraEventObserver(Context context, SimpleRemoteApi apiClient) {
if (context == null) {
throw new IllegalArgumentException("context is null.");
}
if (apiClient == null) {
throw new IllegalArgumentException("apiClient is null.");
}
mRemoteApi = apiClient;
mUiHandler = new Handler(context.getMainLooper());
}
/**
* Starts monitoring by continuously calling getEvent API.
*
* @return true if it successfully started, false if a monitoring is already
* started.
*/
public boolean start() {
if (!mIsActive) {
Log.w(TAG, "start() observer is not active.");
return false;
}
if (mWhileEventMonitoring) {
Log.w(TAG, "start() already starting.");
return false;
}
mWhileEventMonitoring = true;
new Thread() {
@Override
public void run() {
Log.d(TAG, "start() exec.");
// Call getEvent API continuously.
boolean firstCall = true;
MONITORLOOP: while (mWhileEventMonitoring) {
// At first, call as non-Long Polling.
boolean longPolling = !firstCall;
try {
// Call getEvent API.
JSONObject replyJson = mRemoteApi.getEvent(longPolling);
// Check error code at first.
int errorCode = findErrorCode(replyJson);
Log.d(TAG, "getEvent errorCode: " + errorCode);
switch (errorCode) {
case 0: // no error
// Pass through.
break;
case 1: // "Any" error
case 12: // "No such method" error
break MONITORLOOP; // end monitoring.
case 2: // "Timeout" error
// Re-call immediately.
continue MONITORLOOP;
case 40402: // "Already polling" error
// Retry after 5 sec.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// do nothing.
}
continue MONITORLOOP;
default:
Log.w(TAG, "SimpleCameraEventObserver: Unexpected error: "
+ errorCode);
break MONITORLOOP; // end monitoring.
}
List<String> availableApis = findAvailableApiList(replyJson);
if (!availableApis.isEmpty()) {
fireApiListModifiedListener(availableApis);
}
// CameraStatus
String cameraStatus = findCameraStatus(replyJson);
Log.d(TAG, "getEvent cameraStatus: " + cameraStatus);
if (cameraStatus != null && !cameraStatus.equals(mCameraStatus)) {
mCameraStatus = cameraStatus;
fireCameraStatusChangeListener(cameraStatus);
}
// LiveviewStatus
Boolean liveviewStatus = findLiveviewStatus(replyJson);
Log.d(TAG, "getEvent liveviewStatus: " + liveviewStatus);
if (liveviewStatus != null && !liveviewStatus.equals(mLiveviewStatus)) {
mLiveviewStatus = liveviewStatus;
fireLiveviewStatusChangeListener(liveviewStatus);
}
// ShootMode
String shootMode = findShootMode(replyJson);
Log.d(TAG, "getEvent shootMode: " + shootMode);
if (shootMode != null && !shootMode.equals(mShootMode)) {
mShootMode = shootMode;
fireShootModeChangeListener(shootMode);
}
// zoomPosition
int zoomPosition = findZoomInformation(replyJson);
Log.d(TAG, "getEvent zoomPosition: " + zoomPosition);
if (zoomPosition != -1) {
mZoomPosition = zoomPosition;
fireZoomInformationChangeListener(0, 0, zoomPosition, 0);
}
// storageId
String storageId = findStorageId(replyJson);
Log.d(TAG, "getEvent storageId:" + storageId);
if (storageId != null && !storageId.equals(mStorageId)) {
mStorageId = storageId;
fireStorageIdChangeListener(storageId);
}
// :
// : add implementation for Event data as necessary.
} catch (IOException e) {
// Occurs when the server is not available now.
Log.d(TAG, "getEvent timeout by client trigger.");
break MONITORLOOP;
} catch (JSONException e) {
Log.w(TAG, "getEvent: JSON format error. " + e.getMessage());
break MONITORLOOP;
}
firstCall = false;
} // MONITORLOOP end.
mWhileEventMonitoring = false;
}
}.start();
return true;
}
/**
* Requests to stop the monitoring.
*/
public void stop() {
mWhileEventMonitoring = false;
}
/**
* Requests to release resource.
*/
public void release() {
mWhileEventMonitoring = false;
mIsActive = false;
}
public void activate() {
mIsActive = true;
}
/**
* Checks to see whether a monitoring is already started.
*
* @return true when monitoring is started.
*/
public boolean isStarted() {
return mWhileEventMonitoring;
}
/**
* Sets a listener object.
*
* @param listener
*/
public void setEventChangeListener(ChangeListener listener) {
mListener = listener;
}
/**
* Clears a listener object.
*/
public void clearEventChangeListener() {
mListener = null;
}
/**
* Returns the current Camera Status value.
*
* @return camera status
*/
public String getCameraStatus() {
return mCameraStatus;
}
/**
* Returns the current Camera Status value.
*
* @return camera status
*/
public boolean getLiveviewStatus() {
return mLiveviewStatus;
}
/**
* Returns the current Shoot Mode value.
*
* @return shoot mode
*/
public String getShootMode() {
return mShootMode;
}
/**
* Returns the current Zoom Position value.
*
* @return zoom position
*/
public int getZoomPosition() {
return mZoomPosition;
}
/**
* Returns the current Storage Id value.
*
* @return
*/
public String getStorageId() {
return mStorageId;
}
/**
* Notify the change of available APIs
*
* @param availableApis
*/
private void fireApiListModifiedListener(final List<String> availableApis) {
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (mListener != null) {
mListener.onApiListModified(availableApis);
}
}
});
}
/**
* Notify the change of Camera Status.
*
* @param status
*/
private void fireCameraStatusChangeListener(final String status) {
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (mListener != null) {
mListener.onCameraStatusChanged(status);
}
}
});
}
/**
* Notify the change of Liveview Status.
*
* @param status
*/
private void fireLiveviewStatusChangeListener(final boolean status) {
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (mListener != null) {
mListener.onLiveviewStatusChanged(status);
}
}
});
}
/**
* Notify the change of Shoot Mode.
*
* @param shootMode
*/
private void fireShootModeChangeListener(final String shootMode) {
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (mListener != null) {
mListener.onShootModeChanged(shootMode);
}
}
});
}
/**
* Notify the change of Zoom Information
*
* @param zoomIndexCurrentBox
* @param zoomNumberBox
* @param zoomPosition
* @param zoomPositionCurrentBox
*/
private void fireZoomInformationChangeListener(final int zoomIndexCurrentBox,
final int zoomNumberBox,
final int zoomPosition, final int zoomPositionCurrentBox) {
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (mListener != null) {
mListener.onZoomPositionChanged(zoomPosition);
}
}
});
}
/**
* Notify the change of Storage Id.
*
* @param storageId
*/
private void fireStorageIdChangeListener(final String storageId) {
mUiHandler.post(new Runnable() {
@Override
public void run() {
if (mListener != null) {
mListener.onStorageIdChanged(storageId);
}
}
});
}
/**
* Finds and extracts an error code from reply JSON data.
*
* @param replyJson
* @return
* @throws org.json.JSONException
*/
private static int findErrorCode(JSONObject replyJson) throws JSONException {
int code = 0; // 0 means no error.
if (replyJson.has("error")) {
JSONArray errorObj = replyJson.getJSONArray("error");
code = errorObj.getInt(0);
}
return code;
}
/**
* Finds and extracts a list of available APIs from reply JSON data. As for
* getEvent v1.0, results[0] => "availableApiList"
*
* @param replyJson
* @return
* @throws org.json.JSONException
*/
private static List<String> findAvailableApiList(JSONObject replyJson) throws JSONException {
List<String> availableApis = new ArrayList<String>();
int indexOfAvailableApiList = 0;
JSONArray resultsObj = replyJson.getJSONArray("result");
if (!resultsObj.isNull(indexOfAvailableApiList)) {
JSONObject availableApiListObj = resultsObj.getJSONObject(indexOfAvailableApiList);
String type = availableApiListObj.getString("type");
if ("availableApiList".equals(type)) {
JSONArray apiArray = availableApiListObj.getJSONArray("names");
for (int i = 0; i < apiArray.length(); i++) {
availableApis.add(apiArray.getString(i));
}
} else {
Log.w(TAG, "Event reply: Illegal Index (0: AvailableApiList) " + type);
}
}
return availableApis;
}
/**
* Finds and extracts a value of Camera Status from reply JSON data. As for
* getEvent v1.0, results[1] => "cameraStatus"
*
* @param replyJson
* @return
* @throws org.json.JSONException
*/
private static String findCameraStatus(JSONObject replyJson) throws JSONException {
String cameraStatus = null;
int indexOfCameraStatus = 1;
JSONArray resultsObj = replyJson.getJSONArray("result");
if (!resultsObj.isNull(indexOfCameraStatus)) {
JSONObject cameraStatusObj = resultsObj.getJSONObject(indexOfCameraStatus);
String type = cameraStatusObj.getString("type");
if ("cameraStatus".equals(type)) {
cameraStatus = cameraStatusObj.getString("cameraStatus");
} else {
Log.w(TAG, "Event reply: Illegal Index (1: CameraStatus) " + type);
}
}
return cameraStatus;
}
/**
* Finds and extracts a value of Liveview Status from reply JSON data. As
* for getEvent v1.0, results[3] => "liveviewStatus"
*
* @param replyJson
* @return
* @throws org.json.JSONException
*/
private static Boolean findLiveviewStatus(JSONObject replyJson) throws JSONException {
Boolean liveviewStatus = null;
int indexOfLiveviewStatus = 3;
JSONArray resultsObj = replyJson.getJSONArray("result");
if (!resultsObj.isNull(indexOfLiveviewStatus)) {
JSONObject liveviewStatusObj = resultsObj.getJSONObject(indexOfLiveviewStatus);
String type = liveviewStatusObj.getString("type");
if ("liveviewStatus".equals(type)) {
liveviewStatus = liveviewStatusObj.getBoolean("liveviewStatus");
} else {
Log.w(TAG, "Event reply: Illegal Index (3: LiveviewStatus) " + type);
}
}
return liveviewStatus;
}
/**
* Finds and extracts a value of Shoot Mode from reply JSON data. As for
* getEvent v1.0, results[21] => "shootMode"
*
* @param replyJson
* @return
* @throws org.json.JSONException
*/
private static String findShootMode(JSONObject replyJson) throws JSONException {
String shootMode = null;
int indexOfShootMode = 21;
JSONArray resultsObj = replyJson.getJSONArray("result");
if (!resultsObj.isNull(indexOfShootMode)) {
JSONObject shootModeObj = resultsObj.getJSONObject(indexOfShootMode);
String type = shootModeObj.getString("type");
if ("shootMode".equals(type)) {
shootMode = shootModeObj.getString("currentShootMode");
} else {
Log.w(TAG, "Event reply: Illegal Index (21: ShootMode) " + type);
}
}
return shootMode;
}
/**
* Finds and extracts a value of Zoom Information from reply JSON data. As
* for getEvent v1.0, results[2] => "zoomInformation"
*
* @param replyJson
* @return
* @throws org.json.JSONException
*/
private static int findZoomInformation(JSONObject replyJson) throws JSONException {
int zoomPosition = -1;
int indexOfZoomInformation = 2;
JSONArray resultsObj = replyJson.getJSONArray("result");
if (!resultsObj.isNull(indexOfZoomInformation)) {
JSONObject zoomInformationObj = resultsObj.getJSONObject(indexOfZoomInformation);
String type = zoomInformationObj.getString("type");
if ("zoomInformation".equals(type)) {
zoomPosition = zoomInformationObj.getInt("zoomPosition");
} else {
Log.w(TAG, "Event reply: Illegal Index (2: zoomInformation) " + type);
}
}
return zoomPosition;
}
/**
* Finds and extracts value of Storage Id from reply JSON data. As for
* getEvent v1.0, results[10] => "storageInformation"
*
* @param replyJson
* @return
* @throws org.json.JSONException
*/
private static String findStorageId(JSONObject replyJson) throws JSONException {
String storageId = null;
int indexOfStorageInfomation = 10;
JSONArray resultsObj = replyJson.getJSONArray("result");
if (!resultsObj.isNull(indexOfStorageInfomation)) {
JSONArray storageInformationArray = resultsObj.getJSONArray(indexOfStorageInfomation);
if (!storageInformationArray.isNull(0)) {
JSONObject storageInformationObj = storageInformationArray.getJSONObject(0);
String type = storageInformationObj.getString("type");
if ("storageInformation".equals(type)) {
storageId = storageInformationObj.getString("storageID");
} else {
Log.w(TAG, "Event reply: Illegal Index (11: storageInformation) " + type);
}
}
}
return storageId;
}
}
| [
"trooopiii@googlemail.com"
] | trooopiii@googlemail.com |
227ed9bcee21a6921c11c415f9afb5d27b46729e | 6bf6d50a30f11a8c4a21786b3351e100f541d574 | /app/src/test/java/com/conradcrates/pulselivetechnicalchallenge/ExampleUnitTest.java | a916d98b41df75ee31d6904564d05d30ea55d252 | [] | no_license | ccrates/PulseliveTechnicalChallenge | 84146b0a5329caa4ded7af62ac0bae6ccb0bfae1 | 61818a9bbe86e14fd690ba07d247e89c73cbe732 | refs/heads/master | 2021-07-08T06:36:46.069329 | 2017-10-03T11:23:44 | 2017-10-03T11:23:44 | 105,642,490 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 422 | java | package com.conradcrates.pulselivetechnicalchallenge;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"conrad-crates@hotmail.co.uk"
] | conrad-crates@hotmail.co.uk |
8bc993961071ac9b72cb23930693f88a1ba61209 | a860f013c0febe4304fd899c99c44a0b0345456b | /mathProblems/SumSquareDifference6.java | fe9395dd1625c81056bdc7941b6307574efd031a | [] | no_license | dbroeder/randomJavaProjects | ea34a566ff8053eb99ef089a83e28c39e69e458d | 661695aebb7eb284125eff97ff31d6fcd8212177 | refs/heads/master | 2020-03-15T13:16:36.300351 | 2018-05-09T12:59:41 | 2018-05-09T12:59:41 | 132,162,778 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 441 | java | package mathProblems;
public class SumSquareDifference6 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int sumOfSquares=0;
int sum=0;
int total=0;
int difference=0;
for(int dex=1;dex<=100;dex++)
{
sumOfSquares+=dex*dex;
sum+=dex;
}
total=sum*sum;
difference=total-sumOfSquares;
System.out.print(difference);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
166cbaba3fe908fa25af1d1b5e38ec93c03808ef | b52966e5417ccd4f530208859b06b5eef415bb32 | /src/test/java/org/stathry/commons/utils/PinyinTest.java | 5e47fe2ccf6f893983ed545617c8ce3c44862266 | [] | no_license | stathry/commons | 6b0bbc734760692e6a315ac01ee2ae5e1bb540ed | fd2b126bb0b5a6fdbe32c726c7139685f6d006ac | refs/heads/master | 2021-07-20T21:44:48.056430 | 2019-11-18T02:56:04 | 2019-11-18T02:56:04 | 120,720,368 | 0 | 0 | null | 2021-06-04T01:38:30 | 2018-02-08T06:24:57 | Java | UTF-8 | Java | false | false | 387 | java | package org.stathry.commons.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.junit.Test;
import java.util.Arrays;
/**
* TODO
* Created by dongdaiming on 2018-07-02 10:22
*/
public class PinyinTest {
@Test
public void testToPinyin() {
String[] a = PinyinHelper.toHanyuPinyinStringArray('单');
System.out.println(Arrays.toString(a));
}
}
| [
"dongdaiming@socian.com.cn"
] | dongdaiming@socian.com.cn |
ec919b0d499615b7bba55a4ad306e3efec64ef68 | 0c9385eab760b091fb9b4f4b852ecdc6be9223e0 | /src/de/gammas/e4/multithreading/handlers/QuitHandler.java | f96302f7b37b845336d6113939d65ed08370519a | [] | no_license | hendrikstill/de.gammas.e4.multithreading | 53a6f21abd83badf75e71b9ba5191d0ad9536619 | ade93e2a118f60484b9325ead25bd9c811ce9e4d | refs/heads/master | 2020-05-17T01:19:37.561051 | 2013-07-04T08:20:44 | 2013-07-04T08:20:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,207 | java | /*******************************************************************************
* Copyright (c) 2010 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 de.gammas.e4.multithreading.handlers;
import java.lang.reflect.InvocationTargetException;
import javax.inject.Named;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
public class QuitHandler {
@Execute
public void execute(IWorkbench workbench,
@Named(IServiceConstants.ACTIVE_SHELL) Shell shell){
if (MessageDialog.openConfirm(shell, "Confirmation",
"Do you want to exit?")) {
workbench.close();
}
}
}
| [
"hendrik.still@gammas.de"
] | hendrik.still@gammas.de |
a5c1f86353987c6992a89b6991b1823204bbd728 | 92b9f68faf89715dc65e5e1da07f1dc7d20e8aad | /SportsMarketBackend/src/main/java/com/aditya/SportsMarketBackend/dto/Category.java | 00137812240bac7dd28d83d9debc4b7d1c4eb865 | [] | no_license | aditya184/Onlineshop | bc152209861a2170b5d45c98d67b9093857d9dbb | 89aba88a9b1d969a4c003d3826e7ef2db6c4e4c5 | refs/heads/master | 2021-01-19T16:25:40.051221 | 2017-07-08T12:22:31 | 2017-07-08T12:22:31 | 88,262,780 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,303 | java | package com.aditya.SportsMarketBackend.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
@Column(name="description")
private String desc;
@Column(name="image_url")
private String imageUrl;
@Column(name="is_active")
private boolean active=true;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + ", desc=" + desc + ", imageUrl=" + imageUrl + ", active="
+ active + "]";
}
}
| [
"joshiaditya184@gmail.com"
] | joshiaditya184@gmail.com |
d51277de1bdf69080819fed373bdc74653525e65 | 6dadd675206ea148132c6d22a827cbbcaee78f60 | /src/main/java/com/example/template/BlackListCheckCompleted.java | 6c3630e870ad788e9fded2f8b2409dd63a1b35f6 | [] | no_license | minniemk/marketing | ca77633df7efc854800f8836e1ce647974243136 | 6c0ffeea94c593cbfdebc22931fb17f11568ef9c | refs/heads/master | 2020-06-27T17:25:35.922235 | 2019-08-02T08:06:11 | 2019-08-02T08:06:11 | 200,008,321 | 0 | 0 | null | 2019-08-01T08:17:59 | 2019-08-01T08:17:59 | null | UTF-8 | Java | false | false | 262 | java | package com.example.template;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class BlackListCheckCompleted {
private String type ;
private String stateMessage;
private String customerName;
private String surveyMessage;
}
| [
"minnie.mk16@gmail.com"
] | minnie.mk16@gmail.com |
1a9d046b2d507ff9885d93c8535dd9319952332c | 46b7fe8e8b9a166e4f93bbf4046a2bc5a94c4e4b | /webBee-core/src/test/java/downFile/TestDownVideo.java | c22fe1ae9f746d7a4fcbc1c0d835d5c8d47775c3 | [
"MIT"
] | permissive | shenyinquan/webBee | 286d411886ed61d6c7ea5554270a62e5d84cef76 | 1c730285675d312e5b81283813571291e5d7d2f6 | refs/heads/master | 2020-12-30T15:53:47.678067 | 2017-05-13T01:32:20 | 2017-05-13T01:32:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,894 | java | package downFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.bee.webBee.Bee;
import org.bee.webBee.download.FileDownloader;
import org.bee.webBee.linker.Page;
import org.bee.webBee.linker.Request;
import org.bee.webBee.processor.PageProcessor;
import org.bee.webBee.processor.Setting;
import java.io.IOException;
import java.util.Scanner;
/**
* data 2017-05-11 00:03
* E-mail sis.nonacosa@gmail.com
* @author sis.nonacosa
*/
public class TestDownVideo implements PageProcessor {
private Setting setting;
@Override
public void process(Page page) throws IOException {
String api = page.getApi();
String course_name = ((JSONObject) ((JSONObject) JSON.parse(api)).get("data")).get("course_name").toString();
JSONArray video = JSON.parseArray( ((JSONObject) ((JSONObject) JSON.parse(api)).get("data")).get("video_list").toString());
for(java.lang.Object v : video){
String video_url = JSON.parseObject(v.toString()).get("video_url").toString();
String video_name = JSON.parseObject(v.toString()).get("video_name").toString();
System.out.println(video_name + " : " + video_url);
new FileDownloader(new Request(video_url),page.getTask()).downFileProcessor("/Users/pg/Desktop/",video_name);
}
}
@Override
public Setting getSetting() {
System.out.print("请输入课程id:");
Scanner scanner = new Scanner(System.in);
int courseid = scanner.nextInt();
setting = Setting.create().setStartUrl("http://api.maiziedu.com/v2/getCoursePlayInfo/?courseId="+ courseid +"&client=android");
setting = setting.setHttpMethod("GET");
return setting;
}
public static void main(String[] args) {
Bee.create(new TestDownVideo()).run();
}
}
| [
"pkwenda@163.com"
] | pkwenda@163.com |
526a7e55f708055a90edbfcae3b5eedefac1e7dc | 24d8cf871b092b2d60fc85d5320e1bc761a7cbe2 | /JFreeChart/rev91-2020/right-trunk-1969/source/org/jfree/chart/imagemap/URLTagFragmentGenerator.java | c62b940cfa0665670a7c8220f875e93dcb5568bd | [] | no_license | joliebig/featurehouse_fstmerge_examples | af1b963537839d13e834f829cf51f8ad5e6ffe76 | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | refs/heads/master | 2016-09-05T10:24:50.974902 | 2013-03-28T16:28:47 | 2013-03-28T16:28:47 | 9,080,611 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 330 | java |
package org.jfree.chart.imagemap;
import org.jfree.chart.urls.CategoryURLGenerator;
import org.jfree.chart.urls.PieURLGenerator;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.chart.urls.XYZURLGenerator;
public interface URLTagFragmentGenerator {
public String generateURLFragment(String urlText);
}
| [
"joliebig@fim.uni-passau.de"
] | joliebig@fim.uni-passau.de |
5cb3996128dde9b2d1ccd87e4bfd4a583739a3a7 | d645a561fe307d15c675b3b793156c830244ef11 | /fr/src/test/java/com/vdranik/fr/FrApplicationTests.java | f956010f29b36e8c7a8bcb5c2e2e154c18b0d656 | [] | no_license | vdranik/FlightBooking | 1382f1e1cdae71c2716166143bface5e302f2c2a | 5a088b82849a6e54a2db2130e3812c3f413f2de6 | refs/heads/master | 2020-04-08T02:43:51.361525 | 2018-11-28T07:19:06 | 2018-11-28T07:19:06 | 158,946,603 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package com.vdranik.fr;
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 FrApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"v.dranik@gmail.com"
] | v.dranik@gmail.com |
55c27d4846bc0985864bc27d2d68cca8e806c938 | f09870cf2048a7be1eaecefc493e60b866c2e527 | /wlufei-rpc-framework/src/main/java/com/wlufei/rpc/framework/common/utils/ClassUtils.java | 548d2b4f5db49fd41e6f197f16c3c73e34d395c2 | [
"Apache-2.0"
] | permissive | wanghongbean/wlufei-rpc | aebb9995468672d9d15fa36400eb29040a855961 | cc8eb0b06a33e0d7fe013d28987616c2de761917 | refs/heads/master | 2023-07-23T21:18:27.801432 | 2021-09-02T07:50:56 | 2021-09-02T07:50:56 | 391,849,972 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,201 | java | package com.wlufei.rpc.framework.common.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* 类处理 工具类
*
* @author labu
* @date 2021/08/06
*/
public class ClassUtils {
public static final String CLASS_EXTENSION = ".class";
public static final String JAVA_EXTENSION = ".java";
public static Object newInstance(String name) {
try {
return forName(name).newInstance();
} catch (InstantiationException e) {
throw new IllegalStateException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
public static Class<?> forName(String[] packages, String className) {
try {
return _forName(className);
} catch (ClassNotFoundException e) {
if (packages != null && packages.length > 0) {
for (String pkg : packages) {
try {
return _forName(pkg + "." + className);
} catch (ClassNotFoundException e2) {
}
}
}
throw new IllegalStateException(e.getMessage(), e);
}
}
public static Class<?> forName(String className) {
try {
return _forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
public static Class<?> _forName(String className) throws ClassNotFoundException {
if ("boolean".equals(className))
return boolean.class;
if ("byte".equals(className))
return byte.class;
if ("char".equals(className))
return char.class;
if ("short".equals(className))
return short.class;
if ("int".equals(className))
return int.class;
if ("long".equals(className))
return long.class;
if ("float".equals(className))
return float.class;
if ("double".equals(className))
return double.class;
if ("boolean[]".equals(className))
return boolean[].class;
if ("byte[]".equals(className))
return byte[].class;
if ("char[]".equals(className))
return char[].class;
if ("short[]".equals(className))
return short[].class;
if ("int[]".equals(className))
return int[].class;
if ("long[]".equals(className))
return long[].class;
if ("float[]".equals(className))
return float[].class;
if ("double[]".equals(className))
return double[].class;
try {
return arrayForName(className);
} catch (ClassNotFoundException e) {
if (className.indexOf('.') == -1) { // 尝试java.lang包
try {
return arrayForName("java.lang." + className);
} catch (ClassNotFoundException e2) {
// 忽略尝试异常, 抛出原始异常
}
}
throw e;
}
}
private static Class<?> arrayForName(String className) throws ClassNotFoundException {
return Class.forName(className.endsWith("[]")
? "[L" + className.substring(0, className.length() - 2) + ";"
: className, true, Thread.currentThread().getContextClassLoader());
}
public static Class<?> getBoxedClass(Class<?> type) {
if (type == boolean.class) {
return Boolean.class;
} else if (type == char.class) {
return Character.class;
} else if (type == byte.class) {
return Byte.class;
} else if (type == short.class) {
return Short.class;
} else if (type == int.class) {
return Integer.class;
} else if (type == long.class) {
return Long.class;
} else if (type == float.class) {
return Float.class;
} else if (type == double.class) {
return Double.class;
} else {
return type;
}
}
public static Boolean boxed(boolean v) {
return Boolean.valueOf(v);
}
public static Character boxed(char v) {
return Character.valueOf(v);
}
public static Byte boxed(byte v) {
return Byte.valueOf(v);
}
public static Short boxed(short v) {
return Short.valueOf(v);
}
public static Integer boxed(int v) {
return Integer.valueOf(v);
}
public static Long boxed(long v) {
return Long.valueOf(v);
}
public static Float boxed(float v) {
return Float.valueOf(v);
}
public static Double boxed(double v) {
return Double.valueOf(v);
}
public static Object boxed(Object v) {
return v;
}
public static boolean unboxed(Boolean v) {
return v == null ? false : v.booleanValue();
}
public static char unboxed(Character v) {
return v == null ? '\0' : v.charValue();
}
public static byte unboxed(Byte v) {
return v == null ? 0 : v.byteValue();
}
public static short unboxed(Short v) {
return v == null ? 0 : v.shortValue();
}
public static int unboxed(Integer v) {
return v == null ? 0 : v.intValue();
}
public static long unboxed(Long v) {
return v == null ? 0 : v.longValue();
}
public static float unboxed(Float v) {
return v == null ? 0 : v.floatValue();
}
public static double unboxed(Double v) {
return v == null ? 0 : v.doubleValue();
}
public static Object unboxed(Object v) {
return v;
}
public static boolean isNotEmpty(Object object) {
return getSize(object) > 0;
}
public static int getSize(Object object) {
if (object == null) {
return 0;
} if (object instanceof Collection<?>) {
return ((Collection<?>)object).size();
} else if (object instanceof Map<?, ?>) {
return ((Map<?, ?>)object).size();
} else if (object.getClass().isArray()) {
return Array.getLength(object);
} else {
return -1;
}
}
public static URI toURI(String name) {
try {
return new URI(name);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public static Class<?> getGenericClass(Class<?> cls) {
return getGenericClass(cls, 0);
}
public static Class<?> getGenericClass(Class<?> cls, int i) {
try {
ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
Object genericClass = parameterizedType.getActualTypeArguments()[i];
if (genericClass instanceof ParameterizedType) { // 处理多级泛型
return (Class<?>) ((ParameterizedType) genericClass).getRawType();
} else if (genericClass instanceof GenericArrayType) { // 处理数组泛型
return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
} else if (genericClass != null) {
return (Class<?>) genericClass;
}
} catch (Throwable e) {
}
if (cls.getSuperclass() != null) {
return getGenericClass(cls.getSuperclass(), i);
} else {
throw new IllegalArgumentException(cls.getName() + " generic type undefined!");
}
}
public static boolean isBeforeJava5(String javaVersion) {
return (javaVersion == null || javaVersion.length() == 0 || "1.0".equals(javaVersion)
|| "1.1".equals(javaVersion) || "1.2".equals(javaVersion)
|| "1.3".equals(javaVersion) || "1.4".equals(javaVersion));
}
public static boolean isBeforeJava6(String javaVersion) {
return isBeforeJava5(javaVersion) || "1.5".equals(javaVersion);
}
public static String toString(Throwable e) {
StringWriter w = new StringWriter();
PrintWriter p = new PrintWriter(w);
p.print(e.getClass().getName() + ": ");
if (e.getMessage() != null) {
p.print(e.getMessage() + "\n");
}
p.println();
try {
e.printStackTrace(p);
return w.toString();
} finally {
p.close();
}
}
private static final int JIT_LIMIT = 5 * 1024;
public static void checkBytecode(String name, byte[] bytecode) {
if (bytecode.length > JIT_LIMIT) {
System.err.println("The template bytecode too long, may be affect the JIT compiler. template class: " + name);
}
}
public static String getSizeMethod(Class<?> cls) {
try {
return cls.getMethod("size", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e) {
try {
return cls.getMethod("length", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e2) {
try {
return cls.getMethod("getSize", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e3) {
try {
return cls.getMethod("getLength", new Class<?>[0]).getName() + "()";
} catch (NoSuchMethodException e4) {
return null;
}
}
}
}
}
public static String getMethodName(Method method, Class<?>[] parameterClasses, String rightCode) {
if (method.getParameterTypes().length > parameterClasses.length) {
Class<?>[] types = method.getParameterTypes();
StringBuilder buf = new StringBuilder(rightCode);
for (int i = parameterClasses.length; i < types.length; i ++) {
if (buf.length() > 0) {
buf.append(",");
}
Class<?> type = types[i];
String def;
if (type == boolean.class) {
def = "false";
} else if (type == char.class) {
def = "\'\\0\'";
} else if (type == byte.class
|| type == short.class
|| type == int.class
|| type == long.class
|| type == float.class
|| type == double.class) {
def = "0";
} else {
def = "null";
}
buf.append(def);
}
}
return method.getName() + "(" + rightCode + ")";
}
public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes) throws NoSuchMethodException {
if (currentClass == null) {
throw new NoSuchMethodException("class == null");
}
try {
return currentClass.getMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
for (Method method : currentClass.getMethods()) {
if (method.getName().equals(name)
&& parameterTypes.length == method.getParameterTypes().length
&& Modifier.isPublic(method.getModifiers())) {
if (parameterTypes.length > 0) {
Class<?>[] types = method.getParameterTypes();
boolean match = true;
for (int i = 0; i < parameterTypes.length; i ++) {
if (! types[i].isAssignableFrom(parameterTypes[i])) {
match = false;
break;
}
}
if (! match) {
continue;
}
}
return method;
}
}
throw e;
}
}
public static String getInitCode(Class<?> type) {
if (byte.class.equals(type)
|| short.class.equals(type)
|| int.class.equals(type)
|| long.class.equals(type)
|| float.class.equals(type)
|| double.class.equals(type)) {
return "0";
} else if (char.class.equals(type)) {
return "'\\0'";
} else if (boolean.class.equals(type)) {
return "false";
} else {
return "null";
}
}
public static <K, V> Map<K, V> toMap(Map.Entry<K, V>[] entries) {
Map<K, V> map = new HashMap<K, V>();
if (entries != null && entries.length > 0) {
for (Map.Entry<K, V> enrty : entries) {
map.put(enrty.getKey(), enrty.getValue());
}
}
return map;
}
private ClassUtils() {}
}
| [
"wanghongbean@gmail.com"
] | wanghongbean@gmail.com |
5113b3658b9e382cdadf482b9815fdde92a709af | 647eef4da03aaaac9872c8b210e4fc24485e49dc | /TestMemory/admobsdk/src/main/java/com/google/android/gms/internal/zzfl.java | ff0f7ecbd4da7bb72af9d27104a204c0e2635075 | [] | no_license | AlbertSnow/git_workspace | f2d3c68a7b6e62f41c1edcd7744f110e2bf7f021 | a0b2cd83cfa6576182f440a44d957a9b9a6bda2e | refs/heads/master | 2021-01-22T17:57:16.169136 | 2016-12-05T15:59:46 | 2016-12-05T15:59:46 | 28,154,580 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,037 | java | package com.google.android.gms.internal;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdRequest.Gender;
import com.google.ads.AdSize;
import com.google.ads.mediation.MediationAdRequest;
import com.google.android.gms.ads.internal.client.AdRequestParcel;
import com.google.android.gms.ads.internal.client.AdSizeParcel;
import com.google.android.gms.ads.zza;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@zzhb
public final class zzfl
{
public static AdSize zzb(AdSizeParcel paramAdSizeParcel)
{
AdSize[] arrayOfAdSize = { AdSize.SMART_BANNER, AdSize.BANNER, AdSize.IAB_MRECT, AdSize.IAB_BANNER, AdSize.IAB_LEADERBOARD, AdSize.IAB_WIDE_SKYSCRAPER };
for (int i = 0; i < arrayOfAdSize.length; i++)
if ((arrayOfAdSize[i].getWidth() == paramAdSizeParcel.width) && (arrayOfAdSize[i].getHeight() == paramAdSizeParcel.height))
return arrayOfAdSize[i];
return new AdSize(zza.zza(paramAdSizeParcel.width, paramAdSizeParcel.height, paramAdSizeParcel.zzuh));
}
public static AdRequest.Gender zzu(int paramInt)
{
switch (paramInt)
{
case 2:
return AdRequest.Gender.FEMALE;
case 1:
return AdRequest.Gender.MALE;
case 0:
}
return AdRequest.Gender.UNKNOWN;
}
public static int zza(AdRequest.ErrorCode paramErrorCode)
{
switch (1.zzCT[paramErrorCode.ordinal()])
{
case 1:
default:
return 0;
case 2:
return 1;
case 3:
return 2;
case 4:
}
return 3;
}
public static MediationAdRequest zzj(AdRequestParcel paramAdRequestParcel)
{
Set localSet = paramAdRequestParcel.zztE != null ? new HashSet(paramAdRequestParcel.zztE) : null;
return new MediationAdRequest(new Date(paramAdRequestParcel.zztC), zzu(paramAdRequestParcel.zztD), localSet, paramAdRequestParcel.zztF, paramAdRequestParcel.zztK);
}
}
/* Location: C:\Users\Administrator\Downloads\classes.jar
* Qualified Name: com.google.android.gms.internal.zzfl
* JD-Core Version: 0.6.0
*/ | [
"zhaojialiang@conew.com"
] | zhaojialiang@conew.com |
f915a255720897f0a9060d0b6758490da71416aa | 1e3b4df1a61b1fd57496e4a2c52081f22ac2d42f | /src/main/java/com/capgemini/chess/batch/ScheduledChallengesDelete.java | 5694ba10c2520a170f4f2e5589a1bdda89e878e9 | [] | no_license | pwojtkow/chess-scheduler | bbad7a7f1b18172e1a0488c92616d01b9c4ee070 | ac9e1172966ba154db3dcd9b6d5fb8eb889515e0 | refs/heads/master | 2020-12-24T05:54:22.958809 | 2016-08-01T06:26:50 | 2016-08-01T06:27:03 | 64,585,059 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 861 | java | package com.capgemini.chess.batch;
import static com.capgemini.chess.ApplicationProperties.DELETING_CHALLENGES_SCHEDULE_PERIOD;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.capgemini.chess.dao.ChallengeDao;
import com.capgemini.chess.dataaccess.entities.ChallengeEntity;
/**
* Scheduler which role is delete all expired challenges found in the database
* @author PWOJTKOW
*/
@Component
public class ScheduledChallengesDelete {
@Autowired
ChallengeDao challengeDao;
@Scheduled(cron = DELETING_CHALLENGES_SCHEDULE_PERIOD)
public void deleteChallenges() {
List<ChallengeEntity> entityList = challengeDao.getExpiredChallenges();
challengeDao.deleteExpiredChallenges(entityList);
}
}
| [
"przemyslaw.wojtkow@capgemini.com"
] | przemyslaw.wojtkow@capgemini.com |
a093f80e86734e0f8f46ab8febf723d9821190b2 | 1c2fae13a3740e6ceb4ccfc8d8e7041dadfb3c9b | /src/main/java/org/apache/accumulo/trace/instrument/receivers/zipkin/ZipkinSpanReceiver.java | c47d68a3ad404198517fd5ce07437af641625940 | [] | no_license | unautre/accumulo-trace-zipkin | 65feca252d679ea9e0793fdd618c4c972ad1beed | ccbef9e8c06446ef27c1c0bdddfa3d8d3d3fa970 | refs/heads/master | 2022-03-01T06:15:18.305970 | 2013-08-31T05:51:12 | 2013-08-31T05:51:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,181 | 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.accumulo.trace.instrument.receivers.zipkin;
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.accumulo.trace.instrument.Trace;
import org.apache.accumulo.trace.instrument.Tracer;
import org.apache.accumulo.trace.instrument.receivers.AsyncSpanReceiver;
import org.apache.accumulo.trace.instrument.receivers.SpanReceiver;
import org.apache.accumulo.trace.thrift.RemoteSpan;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TIOStreamTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import com.google.common.collect.Lists;
import com.twitter.zipkin.gen.LogEntry;
import com.twitter.zipkin.gen.Scribe;
import com.twitter.zipkin.gen.Scribe.Client;
import com.twitter.zipkin.gen.Span;
/**
* An Accumulo SpanReceiver implementation that sends Spans to a Zipkin Collector.
* Much of the logic/code is borrowed from HTrace's ZipkinSpanReceiver
* https://github.com/cloudera/htrace/blob/master/htrace-zipkin/src/main/java/org/cloudera/htrace/impl/ZipkinSpanReceiver.java
*
* TODO: Handle Client vs. Server annotations (see ZipkinSpanBuilder startTimeMs/stopTimeMs)
* TODO: see comment on send method - we could optimize if we can batch Spans sent in the Scribe Client
*
*/
public class ZipkinSpanReceiver extends AsyncSpanReceiver<InetSocketAddress, Client> {
private final Logger log = Logger.getLogger(ZipkinSpanReceiver.class);
private final String CATEGORY = "zipkin";
private final String host;
private final String serviceName;
private final String collectorHost;
private final int collectorPort;
private final InetSocketAddress collectorSocketAddress;
private final TProtocolFactory protocolFactory;
private final ByteArrayOutputStream byteArrayOutputStream;
private final TProtocol streamProtocol;
// the IP address of the specified host
private int ipv4Address;
private short port = 8080;
/**
* Create a ZipkinSpanReceiver to send Spans to a Zipkin Collector
* @param host The host name of the service being traced
* @param serviceName The name of the traced service
* @param collectorHost The host name of the Zipkin Collector
* @param collectorPort The port of the Zipkin Collector
* @param millis period to flush queued up Spans
*/
public ZipkinSpanReceiver(String host, String serviceName,
String collectorHost, int collectorPort, int millis) {
super(host, serviceName, millis);
this.host = host;
this.serviceName = serviceName;
this.collectorHost = collectorHost;
this.collectorPort = collectorPort;
this.collectorSocketAddress = new InetSocketAddress(collectorHost, collectorPort);
this.protocolFactory = new TBinaryProtocol.Factory();
byteArrayOutputStream = new ByteArrayOutputStream();
streamProtocol = protocolFactory.getProtocol(new TIOStreamTransport(
byteArrayOutputStream));
// Attempt to get the IP address of the specified host
try {
ipv4Address = ByteBuffer.wrap(
InetAddress.getByName(host).getAddress()).getInt();
} catch (UnknownHostException e) {
log.error("Unable to get address for host:" + host);
ipv4Address = 0;
}
}
public void flush() {
super.flush();
}
@Override
protected Client createDestination(InetSocketAddress destination) throws Exception {
if (destination == null)
return null;
log.debug("Connecting to " + destination.getHostName() + ":" + destination.getPort());
TTransport transport = new TFramedTransport(new TSocket(destination.getHostName(), destination.getPort()));
try {
transport.open();
} catch (TTransportException e) {
e.printStackTrace();
}
TProtocol protocol = protocolFactory.getProtocol(transport);
return new Scribe.Client(protocol);
}
@Override
protected InetSocketAddress getSpanKey(Map<String, String> data) {
return collectorSocketAddress;
}
/**
* Seems like we would want to be able to batch the Spans going to the Zipkin
* Collector as that is what the Scribe clients supports. This would require
* a change to the AsyncSpanReceiver class
*
* Also having already converted to a RemoteSpan doesn't make sense with a different
* receiver than the SendSpansViaThrift receiver
*/
@Override
protected void send(Client client, RemoteSpan remoteSpan) throws Exception {
if (client != null) {
log.debug("Span:" + remoteSpan.toString());
Span zipkinSpan = ZipkinSpanBuilder
.newBuilder(ipv4Address, port, serviceName)
.traceId(remoteSpan.getTraceId())
.spanId(remoteSpan.getSpanId())
.parentId(remoteSpan.getParentId())
.startTimeMs(remoteSpan.getStart())
.stopTimeMs(remoteSpan.getStop())
.description(remoteSpan.getDescription())
.data(remoteSpan.getData())
.build();
try {
// clear old data
byteArrayOutputStream.reset();
// write the Span to the underlying ByteArrayOutputStream
zipkinSpan.write(streamProtocol);
// Do Base64 encoding and put the string into a log entry.
LogEntry logEntry = new LogEntry(CATEGORY, Base64.encodeBase64String(byteArrayOutputStream.toByteArray()));
List<LogEntry> logEntries = Lists.newArrayList(logEntry);
client.Log(logEntries);
} catch (Exception e) {
log.error("Error writing to collector:" + collectorHost, e);
client.getInputProtocol().getTransport().close();
client = null;
}
}
}
public static void main(String[] args) {
BasicConfigurator.configure();
Tracer.getInstance().addReceiver(new ZipkinSpanReceiver("localhost", "Test Service", "localhost", 9410, 500));
Trace.on("Query");
org.apache.accumulo.trace.instrument.Span childSpan = Trace.start("Child");
try {
Thread.sleep(20);
} catch (Exception e) { }
childSpan.data("myKey", "myValue");
childSpan.stop();
Trace.off();
}
}
| [
"jaredwinick@koverse.com"
] | jaredwinick@koverse.com |
a67ce71f52488ccb6e32ad173998267b796ae7eb | 8cdba7a19530db0e9351448e503974c709746c4f | /app/src/main/java/com/villagemilk/services/MyInstanceIDListenerService.java | 815068343f7c59fdfc5ae4035423f93d225de2c1 | [] | no_license | smadavaram/village_milk_android | a2292088fa59bc1bc14e9fe2168a99be49fdf80f | e45d821fdea421551ebf1a88cd67ce8d80931364 | refs/heads/master | 2021-08-14T06:03:13.244971 | 2017-11-14T18:12:22 | 2017-11-14T18:12:22 | 110,695,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,343 | java | package com.villagemilk.services;
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.google.firebase.messaging.FirebaseMessaging;
import com.villagemilk.R;
import java.io.IOException;
/**
* Created by sagaryarnalkar on 08/05/16.
*/
public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
private static final String TAG = "MyInstanceIDLS";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. This call is initiated by the
* InstanceID provider.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
try {
String refreshedToken = FirebaseInstanceId.getInstance().getToken(getString(R.string.GCM_SENDER_ID), FirebaseMessaging.INSTANCE_ID_SCOPE);
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
// [END refresh_token]
}
| [
"dailyninja@DailyNinjas-MacBook-Pro.local"
] | dailyninja@DailyNinjas-MacBook-Pro.local |
3e74f12aed0292f2ea886d9942ffe0c0a6b0c462 | bbb1c5d6db61fe614f4f27b595d36ef0df128128 | /src/control/manageChoices.java | 45ddf9fcd139821f45faeb53f0ab41df154fc961 | [] | no_license | playbasfa/betting | 2b270a47011a1ee18e864958074b0741b7287576 | ac3efb7549b798f0ac4c338d2315a2495682d3d6 | refs/heads/master | 2021-01-02T08:33:44.463064 | 2013-11-04T15:04:51 | 2013-11-04T15:04:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,709 | java | package control;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
public class manageChoices
{
@Resource(name = "betDatasource")
private DataSource myDataSourceRef;
private static Connection openConn(){
Connection conn = null;
try{
String user="username_bet";
String password="212212";
String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url,user,password);
}catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
return conn;
}
protected static void toChoice(String n_choice,String i_choice,BigDecimal o_choice,String i_bet, String xml_date, Connection conn){
PreparedStatement statement = null;
try{
//Connection conn = myDataSourceRef.getConnection();
//Connection conn = openConn();
String query="INSERT INTO" + " CHOICES"+ " VALUES(?,?,?,?,?)";
statement = conn.prepareStatement(query);
statement.setString(1, n_choice);
statement.setString(2, i_choice);
statement.setBigDecimal(3, o_choice);
statement.setString(4, i_bet);
statement.setString(5, xml_date);
statement.executeUpdate();
statement.close();
//conn.close();
}catch(SQLException e){try {
statement.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}}
}
}
| [
"Marco@172.16.11.151"
] | Marco@172.16.11.151 |
182e4fc1b62b6010c0794778e6daa1c06fb87fed | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /newEvaluatedBugs/Jsoup_24_buggy/mutated/278/Element.java | b1bbd1ab214e96637514ac4df2b6d31884822d03 | [] | no_license | ozzydong/CapGen | 356746618848065cce4e253e5d3c381baa85044a | 0ba0321b6b1191443276021f1997833342f02515 | refs/heads/master | 2023-03-18T20:12:02.923428 | 2020-08-21T03:08:28 | 2020-08-21T03:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 42,454 | java | package org.jsoup.nodes;
import org.jsoup.helper.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.parser.Parser;
import org.jsoup.parser.Tag;
import org.jsoup.select.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* A HTML element consists of a tag name, attributes, and child nodes (including text nodes and
* other elements).
*
* From an Element, you can extract data, traverse the node graph, and manipulate the HTML.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class Element extends Node {
private Tag tag;
/**
* Create a new, standalone Element. (Standalone in that is has no parent.)
*
* @param tag tag of this element
* @param baseUri the base URI
* @param attributes initial attributes
* @see #appendChild(Node)
* @see #appendElement(String)
*/
public Element(Tag tag, String baseUri, Attributes attributes) {
super(baseUri, attributes);
Validate.notNull(tag);
this.tag = tag;
}
/**
* Create a new Element from a tag and a base URI.
*
* @param tag element tag
* @param baseUri the base URI of this element. It is acceptable for the base URI to be an empty
* string, but not null.
* @see Tag#valueOf(String)
*/
public Element(Tag tag, String baseUri) {
this(tag, baseUri, new Attributes());
}
@Override
public String nodeName() {
return tag.getName();
}
/**
* Get the name of the tag for this element. E.g. {@code div}
*
* @return the tag name
*/
public String tagName() {
return tag.getName();
}
/**
* Change the tag of this element. For example, convert a {@code <span>} to a {@code <div>} with
* {@code el.tagName("div");}.
*
* @param tagName new tag name for this element
* @return this element, for chaining
*/
public Element tagName(String tagName) {
Validate.notEmpty(tagName, "Tag name must not be empty.");
tag = Tag.valueOf(tagName);
return this;
}
/**
* Get the Tag for this element.
*
* @return the tag object
*/
public Tag tag() {
return tag;
}
/**
* Test if this element is a block-level element. (E.g. {@code <div> == true} or an inline element
* {@code <p> == false}).
*
* @return true if block, false if not (and thus inline)
*/
public boolean isBlock() {
return tag.isBlock();
}
/**
* Get the {@code id} attribute of this element.
*
* @return The id attribute, if present, or an empty string if not.
*/
public String id() {
String id = attr("id");
return id == null ? "" : id;
}
/**
* Set an attribute value on this element. If this element already has an attribute with the
* key, its value is updated; otherwise, a new attribute is added.
*
* @return this element
*/
public Element attr(String attributeKey, String attributeValue) {
super.attr(attributeKey, attributeValue);
return this;
}
/**
* Get this element's HTML5 custom data attributes. Each attribute in the element that has a key
* starting with "data-" is included the dataset.
* <p>
* E.g., the element {@code <div data-package="jsoup" data-language="Java" class="group">...} has the dataset
* {@code package=jsoup, language=java}.
* <p>
* This map is a filtered view of the element's attribute map. Changes to one map (add, remove, update) are reflected
* in the other map.
* <p>
* You can find elements that have data attributes using the {@code [^data-]} attribute key prefix selector.
* @return a map of {@code key=value} custom data attributes.
*/
public Map<String, String> dataset() {
return attributes.dataset();
}
@Override
public final Element parent() {
return (Element) parentNode;
}
/**
* Get this element's parent and ancestors, up to the document root.
* @return this element's stack of parents, closest first.
*/
public Elements parents() {
Elements parents = new Elements();
accumulateParents(this, parents);
return parents;
}
private static void accumulateParents(Element el, Elements parents) {
Element parent = el.parent();
if (parent != null && !parent.tagName().equals("#root")) {
parents.add(parent);
accumulateParents(parent, parents);
}
}
/**
* Get a child element of this element, by its 0-based index number.
* <p>
* Note that an element can have both mixed Nodes and Elements as children. This method inspects
* a filtered list of children that are elements, and the index is based on that filtered list.
* </p>
*
* @param index the index number of the element to retrieve
* @return the child element, if it exists, otherwise throws an {@code IndexOutOfBoundsException}
* @see #childNode(int)
*/
public Element child(int index) {
return children().get(index);
}
/**
* Get this element's child elements.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Element nodes.
* </p>
* @return child elements. If this element has no children, returns an
* empty list.
* @see #childNodes()
*/
public Elements children() {
// create on the fly rather than maintaining two lists. if gets slow, memoize, and mark dirty on change
List<Element> elements = new ArrayList<Element>(childNodes.size());
for (Node node : childNodes) {
if (node instanceof Element)
elements.add((Element) node);
}
return new Elements(elements);
}
/**
* Get this element's child text nodes. The list is unmodifiable but the text nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Text nodes.
* @return child text nodes. If this element has no text nodes, returns an
* empty list.
* </p>
* For example, with the input HTML: {@code <p>One <span>Two</span> Three <br> Four</p>} with the {@code p} element selected:
* <ul>
* <li>{@code p.text()} = {@code "One Two Three Four"}</li>
* <li>{@code p.ownText()} = {@code "One Three Four"}</li>
* <li>{@code p.children()} = {@code Elements[<span>, <br>]}</li>
* <li>{@code p.childNodes()} = {@code List<Node>["One ", <span>, " Three ", <br>, " Four"]}</li>
* <li>{@code p.textNodes()} = {@code List<TextNode>["One ", " Three ", " Four"]}</li>
* </ul>
*/
public List<TextNode> textNodes() {
List<TextNode> textNodes = new ArrayList<TextNode>();
for (Node node : childNodes) {
if (node instanceof TextNode)
textNodes.add((TextNode) node);
}
return Collections.unmodifiableList(textNodes);
}
/**
* Get this element's child data nodes. The list is unmodifiable but the data nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Data nodes.
* </p>
* @return child data nodes. If this element has no data nodes, returns an
* empty list.
* @see #data()
*/
public List<DataNode> dataNodes() {
List<DataNode> dataNodes = new ArrayList<DataNode>();
for (Node node : childNodes) {
if (node instanceof DataNode)
dataNodes.add((DataNode) node);
}
return Collections.unmodifiableList(dataNodes);
}
/**
* Find elements that match the {@link Selector} CSS query, with this element as the starting context. Matched elements
* may include this element, or any of its children.
* <p>
* This method is generally more powerful to use than the DOM-type {@code getElementBy*} methods, because
* multiple filters can be combined, e.g.:
* </p>
* <ul>
* <li>{@code el.select("a[href]")} - finds links ({@code a} tags with {@code href} attributes)
* <li>{@code el.select("a[href*=example.com]")} - finds links pointing to example.com (loosely)
* </ul>
* <p>
* See the query syntax documentation in {@link org.jsoup.select.Selector}.
* </p>
*
* @param cssQuery a {@link Selector} CSS-like query
* @return elements that match the query (empty if none match)
* @see org.jsoup.select.Selector
*/
public Elements select(String cssQuery) {
return Selector.select(cssQuery, this);
}
/**
* Add a node child node to this element.
*
* @param child node to add.
* @return this element, so that you can add more child nodes or elements.
*/
public Element appendChild(Node child) {
Validate.notNull(child);
// was - Node#addChildren(child). short-circuits an array create and a loop.
reparentChild(child);
childNodes.add(child);
child.setSiblingIndex(childNodes.size() - 1);
return this;
}
/**
* Add a node to the start of this element's children.
*
* @param child node to add.
* @return this element, so that you can add more child nodes or elements.
*/
public Element prependChild(Node child) {
Validate.notNull(child);
addChildren(0, child);
return this;
}
/**
* Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the
* right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first.
*
* @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the
* end
* @param children child nodes to insert
* @return this element, for chaining.
*/
public Element insertChildren(int index, Collection<? extends Node> children) {
Validate.notNull(children, "Children collection to be inserted must not be null.");
int currentSize = childNodeSize();
if (index < 0) index += currentSize +1; // roll around
Validate.isTrue(index >= 0 && index <= currentSize, "Insert position out of bounds.");
ArrayList<Node> nodes = new ArrayList<Node>(children);
Node[] nodeArray = nodes.toArray(new Node[nodes.size()]);
addChildren(index, nodeArray);
return this;
}
/**
* Create a new element by tag name, and add it as the last child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.appendElement("h1").attr("id", "header").text("Welcome");}
*/
public Element appendElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName), baseUri());
appendChild(child);
return child;
}
/**
* Create a new element by tag name, and add it as the first child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.prependElement("h1").attr("id", "header").text("Welcome");}
*/
public Element prependElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName), baseUri());
prependChild(child);
return child;
}
/**
* Create and append a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element appendText(String text) {
TextNode node = new TextNode(text, baseUri());
appendChild(node);
return this;
}
/**
* Create and prepend a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element prependText(String text) {
TextNode node = new TextNode(text, baseUri());
prependChild(node);
return this;
}
/**
* Add inner HTML to this element. The supplied HTML will be parsed, and each node appended to the end of the children.
* @param html HTML to add inside this element, after the existing HTML
* @return this element
* @see #html(String)
*/
public Element append(String html) {
Validate.notNull(html);
List<Node> nodes = Parser.parseFragment(html, this, baseUri());
addChildren(nodes.toArray(new Node[nodes.size()]));
return this;
}
/**
* Add inner HTML into this element. The supplied HTML will be parsed, and each node prepended to the start of the element's children.
* @param html HTML to add inside this element, before the existing HTML
* @return this element
* @see #html(String)
*/
public Element prepend(String html) {
Validate.notNull(html);
List<Node> nodes = Parser.parseFragment(html, this, baseUri());
addChildren(0, nodes.toArray(new Node[nodes.size()]));
return this;
}
/**
* Insert the specified HTML into the DOM before this element (as a preceding sibling).
*
* @param html HTML to add before this element
* @return this element, for chaining
* @see #after(String)
*/
@Override
public Element before(String html) {
return (Element) super.before(html);
}
/**
* Insert the specified node into the DOM before this node (as a preceding sibling).
* @param node to add before this element
* @return this Element, for chaining
* @see #after(Node)
*/
@Override
public Element before(Node node) {
return (Element) super.before(node);
}
/**
* Insert the specified HTML into the DOM after this element (as a following sibling).
*
* @param html HTML to add after this element
* @return this element, for chaining
* @see #before(String)
*/
@Override
public Element after(String html) {
return (Element) super.after(html);
}
/**
* Insert the specified node into the DOM after this node (as a following sibling).
* @param node to add after this element
* @return this element, for chaining
* @see #before(Node)
*/
@Override
public Element after(Node node) {
return (Element) super.after(node);
}
/**
* Remove all of the element's child nodes. Any attributes are left as-is.
* @return this element
*/
public Element empty() {
childNodes.clear();
return this;
}
/**
* Wrap the supplied HTML around this element.
*
* @param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
* @return this element, for chaining.
*/
@Override
public Element wrap(String html) {
return (Element) super.wrap(html);
}
/**
* Get a CSS selector that will uniquely select this element.
* <p>
* If the element has an ID, returns #id;
* otherwise returns the parent (if any) CSS selector, followed by {@literal '>'},
* followed by a unique selector for the element (tag.class.class:nth-child(n)).
* </p>
*
* @return the CSS Path that can be used to retrieve the element in a selector.
*/
public String cssSelector() {
if (id().length() > 0)
return "#" + id();
StringBuilder selector = new StringBuilder(tagName());
String classes = StringUtil.join(classNames(), ".");
if (classes.length() > 0)
selector.append('.').append(classes);
if (parent() == null || parent() instanceof Document) // don't add Document to selector, as will always have a html node
return selector.toString();
selector.insert(0, " > ");
if (parent().select(selector.toString()).size() > 1)
selector.append(String.format(
":nth-child(%d)", elementSiblingIndex() + 1));
return parent().cssSelector() + selector.toString();
}
/**
* Get sibling elements. If the element has no sibling elements, returns an empty list. An element is not a sibling
* of itself, so will not be included in the returned list.
* @return sibling elements
*/
public Elements siblingElements() {
if (parentNode == null)
return new Elements(0);
List<Element> elements = parent().children();
Elements siblings = new Elements(elements.size() - 1);
for (Element el: elements)
if (el != this)
siblings.add(el);
return siblings;
}
/**
* Gets the next sibling element of this element. E.g., if a {@code div} contains two {@code p}s,
* the {@code nextElementSibling} of the first {@code p} is the second {@code p}.
* <p>
* This is similar to {@link #nextSibling()}, but specifically finds only Elements
* </p>
* @return the next element, or null if there is no next element
* @see #previousElementSibling()
*/
public Element nextElementSibling() {
if (parentNode == null) return null;
List<Element> siblings = parent().children();
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (siblings.size() > index+1)
return siblings.get(index+1);
else
return null;
}
/**
* Gets the previous element sibling of this element.
* @return the previous element, or null if there is no previous element
* @see #nextElementSibling()
*/
public Element previousElementSibling() {
if (parentNode == null) return null;
List<Element> siblings = parent().children();
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (index > 0)
return siblings.get(index-1);
else
return null;
}
/**
* Gets the first element sibling of this element.
* @return the first sibling that is an element (aka the parent's first element child)
*/
public Element firstElementSibling() {
// todo: should firstSibling() exclude this?
List<Element> siblings = parent().children();
return siblings.size() > 1 ? siblings.get(0) : null;
}
/**
* Get the list index of this element in its element sibling list. I.e. if this is the first element
* sibling, returns 0.
* @return position in element sibling list
*/
public Integer elementSiblingIndex() {
if (parent() == null) return 0;
return indexInList(this, parent().children());
}
/**
* Gets the last element sibling of this element
* @return the last sibling that is an element (aka the parent's last element child)
*/
public Element lastElementSibling() {
List<Element> siblings = parent().children();
return siblings.size() > 1 ? siblings.get(siblings.size() - 1) : null;
}
private static <E extends Element> Integer indexInList(Element search, List<E> elements) {
Validate.notNull(search);
Validate.notNull(elements);
for (int i = 0; i < elements.size(); i++) {
E element = elements.get(i);
if (element.equals(search))
return i;
}
return null;
}
// DOM type methods
/**
* Finds elements, including and recursively under this element, with the specified tag name.
* @param tagName The tag name to search for (case insensitively).
* @return a matching unmodifiable list of elements. Will be empty if this element and none of its children match.
*/
public Elements getElementsByTag(String tagName) {
Validate.notEmpty(tagName);
tagName = tagName.toLowerCase().trim();
return Collector.collect(new Evaluator.Tag(tagName), this);
}
/**
* Find an element by ID, including or under this element.
* <p>
* Note that this finds the first matching ID, starting with this element. If you search down from a different
* starting point, it is possible to find a different element by ID. For unique element by ID within a Document,
* use {@link Document#getElementById(String)}
* @param id The ID to search for.
* @return The first matching element by ID, starting with this element, or null if none found.
*/
public Element getElementById(String id) {
Validate.notEmpty(id);
Elements elements = Collector.collect(new Evaluator.Id(id), this);
if (elements.size() > 0)
return elements.get(0);
else
return null;
}
/**
* Find elements that have this class, including or under this element. Case insensitive.
* <p>
* Elements can have multiple classes (e.g. {@code <div class="header round first">}. This method
* checks each class, so you can find the above with {@code el.getElementsByClass("header");}.
*
* @param className the name of the class to search for.
* @return elements with the supplied class name, empty if none
* @see #hasClass(String)
* @see #classNames()
*/
public Elements getElementsByClass(String className) {
Validate.notEmpty(className);
return Collector.collect(new Evaluator.Class(className), this);
}
/**
* Find elements that have a named attribute set. Case insensitive.
*
* @param key name of the attribute, e.g. {@code href}
* @return elements that have this attribute, empty if none
*/
public Elements getElementsByAttribute(String key) {
Validate.notEmpty(key);
key = key.trim().toLowerCase();
return Collector.collect(new Evaluator.Attribute(key), this);
}
/**
* Find elements that have an attribute name starting with the supplied prefix. Use {@code data-} to find elements
* that have HTML5 datasets.
* @param keyPrefix name prefix of the attribute e.g. {@code data-}
* @return elements that have attribute names that start with with the prefix, empty if none.
*/
public Elements getElementsByAttributeStarting(String keyPrefix) {
Validate.notEmpty(keyPrefix);
keyPrefix = keyPrefix.trim().toLowerCase();
return Collector.collect(new Evaluator.AttributeStarting(keyPrefix), this);
}
/**
* Find elements that have an attribute with the specific value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that have this attribute with this value, empty if none
*/
public Elements getElementsByAttributeValue(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValue(key, value), this);
}
/**
* Find elements that either do not have this attribute, or have it with a different value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that do not have a matching attribute
*/
public Elements getElementsByAttributeValueNot(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValueNot(key, value), this);
}
/**
* Find elements that have attributes that start with the value prefix. Case insensitive.
*
* @param key name of the attribute
* @param valuePrefix start of attribute value
* @return elements that have attributes that start with the value prefix
*/
public Elements getElementsByAttributeValueStarting(String key, String valuePrefix) {
return Collector.collect(new Evaluator.AttributeWithValueStarting(key, valuePrefix), this);
}
/**
* Find elements that have attributes that end with the value suffix. Case insensitive.
*
* @param key name of the attribute
* @param valueSuffix end of the attribute value
* @return elements that have attributes that end with the value suffix
*/
public Elements getElementsByAttributeValueEnding(String key, String valueSuffix) {
return Collector.collect(new Evaluator.AttributeWithValueEnding(key, valueSuffix), this);
}
/**
* Find elements that have attributes whose value contains the match string. Case insensitive.
*
* @param key name of the attribute
* @param match substring of value to search for
* @return elements that have attributes containing this text
*/
public Elements getElementsByAttributeValueContaining(String key, String match) {
return Collector.collect(new Evaluator.AttributeWithValueContaining(key, match), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param pattern compiled regular expression to match against attribute values
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, Pattern pattern) {
return Collector.collect(new Evaluator.AttributeWithValueMatching(key, pattern), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param regex regular expression to match against attribute values. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsByAttributeValueMatching(key, pattern);
}
/**
* Find elements whose sibling index is less than the supplied index.
* @param index 0-based index
* @return elements less than index
*/
public Elements getElementsByIndexLessThan(int index) {
return Collector.collect(new Evaluator.IndexLessThan(index), this);
}
/**
* Find elements whose sibling index is greater than the supplied index.
* @param index 0-based index
* @return elements greater than index
*/
public Elements getElementsByIndexGreaterThan(int index) {
return Collector.collect(new Evaluator.IndexGreaterThan(index), this);
}
/**
* Find elements whose sibling index is equal to the supplied index.
* @param index 0-based index
* @return elements equal to index
*/
public Elements getElementsByIndexEquals(int index) {
return Collector.collect(new Evaluator.IndexEquals(index), this);
}
/**
* Find elements that contain the specified string. The search is case insensitive. The text may appear directly
* in the element, or in any of its descendants.
* @param searchText to look for in the element's text
* @return elements that contain the string, case insensitive.
* @see Element#text()
*/
public Elements getElementsContainingText(String searchText) {
return Collector.collect(new Evaluator.ContainsText(searchText), this);
}
/**
* Find elements that directly contain the specified string. The search is case insensitive. The text must appear directly
* in the element, not in any of its descendants.
* @param searchText to look for in the element's own text
* @return elements that contain the string, case insensitive.
* @see Element#ownText()
*/
public Elements getElementsContainingOwnText(String searchText) {
return Collector.collect(new Evaluator.ContainsOwnText(searchText), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(Pattern pattern) {
return Collector.collect(new Evaluator.Matches(pattern), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingText(pattern);
}
/**
* Find elements whose own text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(Pattern pattern) {
return Collector.collect(new Evaluator.MatchesOwn(pattern), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingOwnText(pattern);
}
/**
* Find all elements under this element (including self, and children of children).
*
* @return all elements
*/
public Elements getAllElements() {
return Collector.collect(new Evaluator.AllElements(), this);
}
/**
* Gets the combined text of this element and all its children. Whitespace is normalized and trimmed.
* <p>
* For example, given HTML {@code <p>Hello <b>there</b> now! </p>}, {@code p.text()} returns {@code "Hello there now!"}
*
* @return unencoded text, or empty string if none.
* @see #ownText()
* @see #textNodes()
*/
public String text() {
final StringBuilder accum = new StringBuilder();
new NodeTraversor(new NodeVisitor() {
public void head(Node node, int depth) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
appendNormalisedText(accum, textNode);
} else if (node instanceof Element) {
Element element = (Element) node;
if (element.isBlock())
accum.append(" ");
}
}
public void tail(Node node, int depth) {
}
}).traverse(this);
return accum.toString().trim();
}
/**
* Gets the text owned by this element only; does not get the combined text of all children.
* <p>
* For example, given HTML {@code <p>Hello <b>there</b> now!</p>}, {@code p.ownText()} returns {@code "Hello now!"},
* whereas {@code p.text()} returns {@code "Hello there now!"}.
* Note that the text within the {@code b} element is not returned, as it is not a direct child of the {@code p} element.
*
* @return unencoded text, or empty string if none.
* @see #text()
* @see #textNodes()
*/
public String ownText() {
StringBuilder sb = new StringBuilder();
ownText(sb);
return sb.toString().trim();
}
private void ownText(StringBuilder accum) {
for (Node child : childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
appendNormalisedText(accum, textNode);
} else if (child instanceof Element) {
appendWhitespaceIfBr((Element) child, accum);
}
}
}
private static void appendNormalisedText(StringBuilder accum, TextNode textNode) {
String text = textNode.getWholeText();
if (preserveWhitespace(textNode.parentNode))
accum.append(text);
else
StringUtil.appendNormalisedWhitespace(accum, text, TextNode.lastCharIsWhitespace(accum));
}
private static void appendWhitespaceIfBr(Element element, StringBuilder accum) {
if (element.tag.getName().equals("br") && !TextNode.lastCharIsWhitespace(accum))
accum.append(" ");
}
static boolean preserveWhitespace(Node node) {
// looks only at this element and one level up, to prevent recursion & needless stack searches
if (node != null && node instanceof Element) {
Element element = (Element) node;
return element.tag.preserveWhitespace() ||
element.parent() != null && element.parent().tag.preserveWhitespace();
}
return false;
}
/**
* Set the text of this element. Any existing contents (text or elements) will be cleared
* @param text unencoded text
* @return this element
*/
public Element text(String text) {
Validate.notNull(text);
empty();
TextNode textNode = new TextNode(text, baseUri);
appendChild(textNode);
return this;
}
/**
Test if this element has any text content (that is not just whitespace).
@return true if element has non-blank text content.
*/
public boolean hasText() {
for (Node child: childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
if (!textNode.isBlank())
return true;
} else if (child instanceof Element) {
Element el = (Element) child;
if (el.hasText())
return true;
}
}
return false;
}
/**
* Get the combined data of this element. Data is e.g. the inside of a {@code script} tag.
* @return the data, or empty string if none
*
* @see #dataNodes()
*/
public String data() {
StringBuilder sb = new StringBuilder();
for (Node childNode : childNodes) {
if (childNode instanceof DataNode) {
DataNode data = (DataNode) childNode;
sb.append(data.getWholeData());
} else if (childNode instanceof Element) {
Element element = (Element) childNode;
String elementData = element.data();
sb.append(elementData);
}
}
return sb.toString();
}
/**
* Gets the literal value of this element's "class" attribute, which may include multiple class names, space
* separated. (E.g. on <code><div class="header gray"></code> returns, "<code>header gray</code>")
* @return The literal class attribute, or <b>empty string</b> if no class attribute set.
*/
public String className() {
return attr("class").trim();
}
/**
* Get all of the element's class names. E.g. on element {@code <div class="header gray">},
* returns a set of two elements {@code "header", "gray"}. Note that modifications to this set are not pushed to
* the backing {@code class} attribute; use the {@link #classNames(java.util.Set)} method to persist them.
* @return set of classnames, empty if no class attribute
*/
public Set<String> classNames() {
String[] names = className().split("\\s+");
Set<String> classNames = new LinkedHashSet<String>(Arrays.asList(names));
classNames.remove(""); // if classNames() was empty, would include an empty class
return classNames;
}
/**
Set the element's {@code class} attribute to the supplied class names.
@param classNames set of classes
@return this element, for chaining
*/
public Element classNames(Set<String> classNames) {
Validate.notNull(classNames);
attributes.put("class", StringUtil.join(classNames, " "));
return this;
}
/**
* Tests if this element has a class. Case insensitive.
* @param className name of class to check for
* @return true if it does, false if not
*/
public boolean hasClass(String className) {
Set<String> classNames = classNames();
for (String name : classNames) {
if (className.equalsIgnoreCase(name))
return true;
}
return false;
}
/**
Add a class name to this element's {@code class} attribute.
@param className class name to add
@return this element
*/
public Element addClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.add(className);
classNames(classes);
return this;
}
/**
Remove a class name from this element's {@code class} attribute.
@param className class name to remove
@return this element
*/
public Element removeClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.remove(className);
classNames(classes);
return this;
}
/**
Toggle a class name on this element's {@code class} attribute: if present, remove it; otherwise add it.
@param className class name to toggle
@return this element
*/
public Element toggleClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
if (classes.contains(className))
classes.remove(className);
else
classes.add(className);
classNames(classes);
return this;
}
/**
* Get the value of a form element (input, textarea, etc).
* @return the value of the form element, or empty string if not set.
*/
public String val() {
if (tagName().equals("textarea"))
return text();
else
return attr("value");
}
/**
* Set the value of a form element (input, textarea, etc).
* @param value value to set
* @return this element (for chaining)
*/
public Element val(String value) {
if (tagName().equals("textarea"))
text(value);
else
attr("value", value);
return this;
}
void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) {
if (accum.length() > 0 && out.prettyPrint() && (tag.formatAsBlock() || (parent() != null && parent().tag().formatAsBlock()) || out.outline()) )
indent(accum, depth, out);
accum
.append("<")
.append(tagName());
attributes.html(accum, out);
// selfclosing includes unknown tags, isEmpty defines tags that are always empty
if (childNodes.isEmpty() && tag.isSelfClosing()) {
if (out.syntax() == Document.OutputSettings.Syntax.html && tag.isEmpty())
accum.append('>');
else
accum.append(" />"); // <img> in html, <img /> in xml
}
else
accum.append(">");
}
void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out) {
if (!(childNodes.isEmpty() && tag.isSelfClosing())) {
if (out.prettyPrint() && (!childNodes.isEmpty() && (
tag.formatAsBlock() || (out.outline() && (childNodes.size()>1 || (childNodes.size()==1 && !(childNodes.get(0) instanceof TextNode))))
)))
indent(accum, depth, out);
accum.append("</").append(tagName()).append(">");
}
}
/**
* Retrieves the element's inner HTML. E.g. on a {@code <div>} with one empty {@code <p>}, would return
* {@code <p></p>}. (Whereas {@link #outerHtml()} would return {@code <div><p></p></div>}.)
*
* @return String of HTML.
* @see #outerHtml()
*/
public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString();
}
private void html(StringBuilder accum) {
for (Node node : childNodes)
node.outerHtml(accum);
}
/**
* Set this element's inner HTML. Clears the existing HTML first.
* @param html HTML to parse and set into this element
* @return this element
* @see #append(String)
*/
public Element html(String html) {
empty();
append(html);
return this;
}
public String toString() {
return outerHtml();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Element element = (Element) o;
return tag.equals(element.tag);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (tag != null ? tag.hashCode() : 0);
return result;
}
@Override
public Element clone() {
return (Element) super.clone();
}
}
| [
"justinwm@163.com"
] | justinwm@163.com |
d4d06d17cb07b6e213712024fd44bd4526352a8f | 37a3d6560ed675d130f4f1ba7baaa2d154c043c9 | /trazeridioma/TrazerIdioma.java | 7a3d45adb0f7a7e0c55781f879044f39f1bb1bd6 | [] | no_license | isagalbero/AppJava | 4ec08325b9976380e0078ff45e8210dc9b73e982 | c2126477dcd45b58db21ced864c1b03d88977fd9 | refs/heads/master | 2021-01-05T18:41:22.886736 | 2020-02-21T17:45:56 | 2020-02-21T17:45:56 | 241,105,487 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 314 | java | package trazeridioma;
//import java.math.BigInteger;
import java.util.Locale;
public class TrazerIdioma {
public static void main(String[] args) {
Locale idioma = Locale.getDefault();
System.out.println(idioma.getDisplayLanguage());
System.out.println(idioma.getLanguage());
}
} | [
"isagalbero@gmail.com"
] | isagalbero@gmail.com |
cf38b9cc31cfcc0d99a8bd191f548a78bcc3d200 | dae8ff2c684979639c580ffa57d3590ee33fc9c3 | /src/binary_watch_401/PermutationTest.java | f68cfe3fa725af2a35a937cb54b22ced2793fc12 | [] | no_license | maksouth/leetcode-problems | 7b0f14431555acd6627165aa79f70332a7897f13 | 05218bc44225d73fc874896208e537e0b46dd077 | refs/heads/master | 2020-05-30T06:20:12.270145 | 2019-05-31T10:42:19 | 2019-05-31T10:42:19 | 189,576,678 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package binary_watch_401;
import org.junit.Test;
public class PermutationTest {
private Permutation permutation = new Permutation();
@Test
public void test1() {
permutation.permutate(new int[]{1,1,1,0,0,0});
}
}
class Backtracking {
int[] A;
void Binary(int n){
if(n<1){
for(int i : A)
System.out.print(i);
System.out.println();
}else{
A[n-1] = 0;
Binary(n-1);
A[n-1] = 1;
Binary(n-1);
}
}
public static void main(String[] args) {
// n is number of bits
int n = 8;
Backtracking backtracking = new Backtracking();
backtracking.A = new int[n];
backtracking.Binary(n);
}
} | [
"mharbovskyi@luxoft.com"
] | mharbovskyi@luxoft.com |
2b5a91a5a8f93357bee2024173ae011fc2d6b389 | ff0c33ccd3bbb8a080041fbdbb79e29989691747 | /jdk.incubator.jpackage/jdk/incubator/jpackage/internal/AppImageFile.java | e3abdbe557d4af93d554bd53d4545423ad8f4646 | [] | no_license | jiecai58/jdk15 | 7d0f2e518e3f6669eb9ebb804f3c89bbfb2b51f0 | b04691a72e51947df1b25c31175071f011cb9bbe | refs/heads/main | 2023-02-25T00:30:30.407901 | 2021-01-29T04:48:33 | 2021-01-29T04:48:33 | 330,704,930 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,215 | java | /*
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package jdk.incubator.jpackage.internal;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import static jdk.incubator.jpackage.internal.StandardBundlerParam.*;
public class AppImageFile {
// These values will be loaded from AppImage xml file.
private final String creatorVersion;
private final String creatorPlatform;
private final String launcherName;
private final List<String> addLauncherNames;
private final static String FILENAME = ".jpackage.xml";
private final static Map<Platform, String> PLATFORM_LABELS = Map.of(
Platform.LINUX, "linux", Platform.WINDOWS, "windows", Platform.MAC,
"macOS");
private AppImageFile() {
this(null, null, null, null);
}
private AppImageFile(String launcherName, List<String> addLauncherNames,
String creatorVersion, String creatorPlatform) {
this.launcherName = launcherName;
this.addLauncherNames = addLauncherNames;
this.creatorVersion = creatorVersion;
this.creatorPlatform = creatorPlatform;
}
/**
* Returns list of additional launchers configured for the application.
* Each item in the list is not null or empty string.
* Returns empty list for application without additional launchers.
*/
List<String> getAddLauncherNames() {
return addLauncherNames;
}
/**
* Returns main application launcher name. Never returns null or empty value.
*/
String getLauncherName() {
return launcherName;
}
void verifyCompatible() throws ConfigException {
// Just do nothing for now.
}
/**
* Returns path to application image info file.
* @param appImageDir - path to application image
*/
public static Path getPathInAppImage(Path appImageDir) {
return ApplicationLayout.platformAppImage()
.resolveAt(appImageDir)
.appDirectory()
.resolve(FILENAME);
}
/**
* Saves file with application image info in application image.
* @param appImageDir - path to application image
* @throws IOException
*/
static void save(Path appImageDir, Map<String, Object> params)
throws IOException {
IOUtils.createXml(getPathInAppImage(appImageDir), xml -> {
xml.writeStartElement("jpackage-state");
xml.writeAttribute("version", getVersion());
xml.writeAttribute("platform", getPlatform());
xml.writeStartElement("app-version");
xml.writeCharacters(VERSION.fetchFrom(params));
xml.writeEndElement();
xml.writeStartElement("main-launcher");
xml.writeCharacters(APP_NAME.fetchFrom(params));
xml.writeEndElement();
List<Map<String, ? super Object>> addLaunchers =
ADD_LAUNCHERS.fetchFrom(params);
for (int i = 0; i < addLaunchers.size(); i++) {
Map<String, ? super Object> sl = addLaunchers.get(i);
xml.writeStartElement("add-launcher");
xml.writeCharacters(APP_NAME.fetchFrom(sl));
xml.writeEndElement();
}
});
}
/**
* Loads application image info from application image.
* @param appImageDir - path to application image
* @return valid info about application image or null
* @throws IOException
*/
static AppImageFile load(Path appImageDir) throws IOException {
try {
Document doc = readXml(appImageDir);
XPath xPath = XPathFactory.newInstance().newXPath();
String mainLauncher = xpathQueryNullable(xPath,
"/jpackage-state/main-launcher/text()", doc);
if (mainLauncher == null) {
// No main launcher, this is fatal.
return new AppImageFile();
}
List<String> addLaunchers = new ArrayList<String>();
String platform = xpathQueryNullable(xPath,
"/jpackage-state/@platform", doc);
String version = xpathQueryNullable(xPath,
"/jpackage-state/@version", doc);
NodeList launcherNameNodes = (NodeList) xPath.evaluate(
"/jpackage-state/add-launcher/text()", doc,
XPathConstants.NODESET);
for (int i = 0; i != launcherNameNodes.getLength(); i++) {
addLaunchers.add(launcherNameNodes.item(i).getNodeValue());
}
AppImageFile file = new AppImageFile(
mainLauncher, addLaunchers, version, platform);
if (!file.isValid()) {
file = new AppImageFile();
}
return file;
} catch (XPathExpressionException ex) {
// This should never happen as XPath expressions should be correct
throw new RuntimeException(ex);
}
}
public static Document readXml(Path appImageDir) throws IOException {
try {
Path path = getPathInAppImage(appImageDir);
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newDefaultInstance();
dbf.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd",
false);
DocumentBuilder b = dbf.newDocumentBuilder();
return b.parse(new FileInputStream(path.toFile()));
} catch (ParserConfigurationException | SAXException ex) {
// Let caller sort this out
throw new IOException(ex);
}
}
/**
* Returns list of launcher names configured for the application.
* The first item in the returned list is main launcher name.
* Following items in the list are names of additional launchers.
*/
static List<String> getLauncherNames(Path appImageDir,
Map<String, ? super Object> params) {
List<String> launchers = new ArrayList<>();
try {
AppImageFile appImageInfo = AppImageFile.load(appImageDir);
if (appImageInfo != null) {
launchers.add(appImageInfo.getLauncherName());
launchers.addAll(appImageInfo.getAddLauncherNames());
return launchers;
}
} catch (IOException ioe) {
Log.verbose(ioe);
}
launchers.add(APP_NAME.fetchFrom(params));
ADD_LAUNCHERS.fetchFrom(params).stream().map(APP_NAME::fetchFrom).forEach(
launchers::add);
return launchers;
}
private static String xpathQueryNullable(XPath xPath, String xpathExpr,
Document xml) throws XPathExpressionException {
NodeList nodes = (NodeList) xPath.evaluate(xpathExpr, xml,
XPathConstants.NODESET);
if (nodes != null && nodes.getLength() > 0) {
return nodes.item(0).getNodeValue();
}
return null;
}
private static String getVersion() {
return System.getProperty("java.version");
}
private static String getPlatform() {
return PLATFORM_LABELS.get(Platform.getPlatform());
}
private boolean isValid() {
if (launcherName == null || launcherName.length() == 0 ||
addLauncherNames.indexOf("") != -1) {
// Some launchers have empty names. This is invalid.
return false;
}
// Add more validation.
return true;
}
}
| [
"caijie2@tuhu.cn"
] | caijie2@tuhu.cn |
b7fe543051b4d79416a2d908ded0d23350a1a70f | 44f19bb1926e547c1dd1d24dddc3a9fb0d9c1a2a | /spring-mvc-app/src/main/java/com/bkm/spring/aop/HelloWorldAspect.java | a4b4e68a602738a74575d4faf28eba2dc3300dd7 | [] | no_license | PuttyTree/spring-mvc-demo | 45635b94938e9de2e21deba1d8af8aa775472a17 | b21f74c572dc01f98d0d39020f90cd342389dd16 | refs/heads/master | 2020-05-22T21:53:50.462060 | 2017-08-01T06:25:10 | 2017-08-01T06:25:10 | 84,728,288 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,202 | java | package com.bkm.spring.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* Created by yongli.chen on 2017/7/11.
*/
@Aspect
@Component
public class HelloWorldAspect {
@Pointcut(value = "execution(* com.bkm.spring.service.impl.HelloWorldServiceImpl.*(..))&& args(param)",
argNames = "param")
private void beforePointcut(String param) {
}//定义一个切入点
@Before(value = "beforePointcut(param)", argNames = "param")
public void beforeAdvice(String param) {
System.out.println("前置通知:" + param);
}
/* @AfterReturning("anyMethod()")
public void doAfter() {
System.out.println("后置通知");
}
@After("anyMethod()")
public void after() {
System.out.println("最终通知");
}
@AfterThrowing("anyMethod()")
public void doAfterThrow() {
System.out.println("例外通知");
}
@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("进入环绕通知");
Object object = pjp.proceed();//执行该方法
System.out.println("退出方法");
return object;
}*/
}
| [
"jspwoody@qq.com"
] | jspwoody@qq.com |
468de3b327865624f9ee1cc136317bc08e0c4475 | b56c0aa8f041ac874de2d126df7552374d58af16 | /src/main/java/jp/ac/titech/c/cl/chatannotator/network/ChatIdMessage.java | 3989e794ee2bf860f13fca710c18bdc5c02da3a7 | [] | no_license | yokono/ddcraft.logging-mod | e2fd5bd8e4c5fec8082caa3604ca258043b4847e | fbdcf6ac9a2101c24ffb4f360cddfe1cf4eebab6 | refs/heads/master | 2023-03-21T12:24:17.975832 | 2021-03-17T10:35:35 | 2021-03-17T13:16:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,150 | java | package jp.ac.titech.c.cl.chatannotator.network;
import java.nio.charset.Charset;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
public class ChatIdMessage implements IMessage
{
public static final int MAX_MESSAGE_LENGTH = 20;
String serialId = "";
String message;
public ChatIdMessage()
{
};
public ChatIdMessage(String serialId, String message)
{
this.serialId = serialId;
if (message.length() > MAX_MESSAGE_LENGTH){
message = message.substring(0, MAX_MESSAGE_LENGTH);
}
this.message = message;
}
public String getSerialId()
{
return serialId;
}
public String getMessage()
{
return message;
}
@Override
public void fromBytes(ByteBuf buf)
{
try
{
serialId = ByteBufUtils.readUTF8String(buf);
message = ByteBufUtils.readUTF8String(buf);
}
catch(Exception e)
{
e.printStackTrace();
serialId = "hoge";
message = "huga";
}
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, serialId);
ByteBufUtils.writeUTF8String(buf, message);
}
}
| [
"ogawa.h.ai@m.titech.ac.jp"
] | ogawa.h.ai@m.titech.ac.jp |
ed79c275f56770cab31082a20b774ae3d0299d67 | e7d9b7ab98625538df2b0d2f7df97e4f4bc331fd | /app/src/main/java/com/enliple/pudding/keyboard/OnKeyboardVisibilityListener.java | 4aa1d918495a469f190511e8416b5515e7891333 | [] | no_license | ssang83/Pudding | 5c9f1703c5f7101b65c63db5af604f70474fee99 | 474fa922a1bc663bd3504c852837474da32617e8 | refs/heads/main | 2023-03-11T10:02:06.471278 | 2021-02-24T07:07:34 | 2021-02-24T07:07:34 | 341,803,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 141 | java | package com.enliple.pudding.keyboard;
public interface OnKeyboardVisibilityListener {
void onVisibilityChanged(boolean visible);
}
| [
"js.kim@petdoc.co.kr"
] | js.kim@petdoc.co.kr |
bec38f474e7ac1f9820ed856f98a2343c85b5a56 | 22c2f20b54aeed791bbd7a518d92df5a57cf7e72 | /Hello.java | 85583a8739f1317abbbd48c93318dd55c2de45d3 | [] | no_license | cgy19920418/ck | 38dbb319b30231865c0db6129c30d87a46de0fd1 | 03a92e099ee2905921f62dd207a852b092e12293 | refs/heads/master | 2021-01-10T13:34:30.561517 | 2015-11-03T02:50:07 | 2015-11-03T02:50:07 | 45,434,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 326 | java | public class Hello {
public static void main(String args[]) {
//System.out.printlin("Hello World!");
System.out.printlin("Hello World!");
System.out.printlin("Hello World!");
System.out.printlin("sadd");
System.out.printlin("Hssssrld!");
System.out.printlin("Hssssrld!");
System.out.printlin("Hssssrld!");
}
}
| [
"365530751@qq.com"
] | 365530751@qq.com |
5fdae36041296c3d05023d251d8781beeb02fa01 | ed1b513b9994e29e2b707d964bebbd9e0d7565e3 | /src/Week01/HWAssignment1_NumberInput.java | bfff8f0a896d54a7fe0b34585ffd57336cba7bf2 | [] | no_license | sliabraaten/SE1011-071_Labs | d5a98a5374473fa886c9c990b0d8dd4740367d98 | e1a4b0e600e9747390b5211d5b985adc575b8575 | refs/heads/master | 2021-01-13T01:29:55.369336 | 2014-12-18T16:56:15 | 2014-12-18T16:56:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 528 | java | package Week01;
import javax.swing.*;
/**
* 1011-071_HW, Purpose:to take user input of a number and return it to the user via GUI
*
* @version 1.0 Created on 9/15/2014 at 11:21 AM.
* @author: Seth
*/
public class HWAssignment1_NumberInput
{
public static void main(String args[])
{
String guiInput = (String)JOptionPane.showInputDialog("Enter a Number","Number Here...");
JOptionPane.showMessageDialog(null, "You Entered: " + guiInput, "Your Number Is Here", JOptionPane.PLAIN_MESSAGE);
}
}
| [
"seth100@liabraaten.info"
] | seth100@liabraaten.info |
e2a86ba610d83794c84e0946260acb2370328489 | 1c4a4b55af215058a80534486514b1cb6bb6cb7c | /15-121 Introduction to Data Structures/src/lec/l17/SortUtils.java | 01b4f260496acaa3d7ccff563bfff02f442debce | [] | no_license | sungjuc/Study | 539ac625e8c8241f68bb60c8ff48c18e3d6ed2c4 | 69d649518ad0941870aad1faa866da2a4387d28a | refs/heads/master | 2021-01-19T06:32:43.411492 | 2013-12-18T08:39:42 | 2013-12-18T08:39:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | package lec.l17;
public class SortUtils {
private static int indexOfMin(int[] a, int start) {
int minIndex = start;
for (int i = start; i < a.length; i++) {
if (a[i] < a[minIndex])
minIndex = i;
}
return minIndex;
}
public static void selectionSort(int[] a) {
for (int i = 0; i < a.length; i++) {
int minIndex = indexOfMin(a, i);
int temp = a[minIndex];
a[minIndex] = a[i];
a[i] = temp;
}
}
private static void insert(int[] a, int index) {
int toInsert = a[index];
while (index > 0 && a[index - 1] > toInsert) {
a[index] = a[index - 1];
index--;
}
a[index] = toInsert;
}
public static void insertionSort(int[] a) {
for (int i = 0; i < a.length; i++) {
insert(a, i);
}
}
}
| [
"sungjuc73@gmail.com"
] | sungjuc73@gmail.com |
e2adb38e7a859ac4999db5774eeccb3c15f8760c | 9623f83defac3911b4780bc408634c078da73387 | /powercraft_15/src/minecraft/codechicken/core/ReentrantCheck.java | 8cb9f09afadbbc056e8ef66781b709d2e7a94055 | [] | no_license | BlearStudio/powercraft-legacy | 42b839393223494748e8b5d05acdaf59f18bd6c6 | 014e9d4d71bd99823cf63d4fbdb65c1b83fde1f8 | refs/heads/master | 2021-01-21T21:18:55.774908 | 2015-04-06T20:45:25 | 2015-04-06T20:45:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 686 | java | package codechicken.core;
public class ReentrantCheck
{
private boolean entered;
public ReentrantCheck()
{
entered = false;
}
public boolean entered()
{
return entered;
}
public void enter()
{
entered = true;
}
public void exit()
{
entered = false;
}
public static ThreadLocal<ReentrantCheck> threadLocal()
{
return new ThreadLocal<ReentrantCheck>()
{
@Override
protected ReentrantCheck initialValue()
{
return new ReentrantCheck();
}
};
}
}
| [
"nils.h.emmerich@googlemail.com@ed9f5d1b-00bb-0f29-faab-e8ebad1a710c"
] | nils.h.emmerich@googlemail.com@ed9f5d1b-00bb-0f29-faab-e8ebad1a710c |
2b968743542311183206c1f8bbd59f6ee3da7687 | 4ea5417ecd70f8c6757603ad463bd1abf394d358 | /org.sheepy.lily.vulkan.api/src/generated/java/org/sheepy/lily/vulkan/model/impl/RunProcessImpl.java | b01ed62c25e4515ffd285294bef186519700bd00 | [
"MIT"
] | permissive | Ealrann/Lily-Vulkan | 88fd02373ce7ca390ab3581faf10a7a8b799adea | 04c72b506a1db472b9f23dde25c4e1915480f122 | refs/heads/master | 2023-08-12T16:43:33.403548 | 2023-08-11T21:05:09 | 2023-08-11T21:05:09 | 141,837,401 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,622 | java | /**
*/
package org.sheepy.lily.vulkan.model.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.sheepy.lily.core.api.model.LilyEObject;
import org.sheepy.lily.vulkan.model.IProcess;
import org.sheepy.lily.vulkan.model.RunProcess;
import org.sheepy.lily.vulkan.model.VulkanPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Run Process</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.sheepy.lily.vulkan.model.impl.RunProcessImpl#getProcess <em>Process</em>}</li>
* </ul>
*
* @generated
*/
public class RunProcessImpl extends LilyEObject implements RunProcess
{
/**
* The cached value of the '{@link #getProcess() <em>Process</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getProcess()
* @generated
* @ordered
*/
protected IProcess process;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RunProcessImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return VulkanPackage.Literals.RUN_PROCESS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public IProcess getProcess()
{
if (process != null && ((EObject)process).eIsProxy())
{
InternalEObject oldProcess = (InternalEObject)process;
process = (IProcess)eResolveProxy(oldProcess);
if (process != oldProcess)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, VulkanPackage.RUN_PROCESS__PROCESS, oldProcess, process));
}
}
return process;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IProcess basicGetProcess()
{
return process;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setProcess(IProcess newProcess)
{
IProcess oldProcess = process;
process = newProcess;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, VulkanPackage.RUN_PROCESS__PROCESS, oldProcess, process));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case VulkanPackage.RUN_PROCESS__PROCESS:
if (resolve) return getProcess();
return basicGetProcess();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case VulkanPackage.RUN_PROCESS__PROCESS:
setProcess((IProcess)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case VulkanPackage.RUN_PROCESS__PROCESS:
setProcess((IProcess)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case VulkanPackage.RUN_PROCESS__PROCESS:
return process != null;
}
return super.eIsSet(featureID);
}
} //RunProcessImpl
| [
"ealrann@gmail.com"
] | ealrann@gmail.com |
aee834311ee6388987e7ea82c46cbdfa5e77b7fc | cfb7858d673d411783de58e27a9feb4fc37c33b2 | /app/src/main/java/com/brioal/sourcecode/blogsharelist/presenter/BlogSharePresenterImpl.java | bc0f30e15d55e327a380bfb98e7601297655fc4a | [] | no_license | Brioal/SourceCode | effbf9f4b2b135c80a23626f2f1857896335cc97 | 6e32623fb2edc2c855d82cda4e98f31dd49417d1 | refs/heads/master | 2021-01-17T16:02:42.671326 | 2017-05-23T08:03:57 | 2017-05-23T08:03:57 | 83,178,852 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,558 | java | package com.brioal.sourcecode.blogsharelist.presenter;
import android.os.Handler;
import com.brioal.sourcecode.bean.BlogBean;
import com.brioal.sourcecode.blogsharelist.contract.BlogShareContract;
import com.brioal.sourcecode.blogsharelist.model.BlogShareModelImpl;
import com.brioal.sourcecode.interfaces.OnBlogLoadListener;
import java.util.List;
/**
* Created by Brioal on 2017/03/10
*/
public class BlogSharePresenterImpl implements BlogShareContract.Presenter {
private BlogShareContract.View mView;
private BlogShareContract.Model mModel;
private Handler mHandler = new Handler();
public BlogSharePresenterImpl(BlogShareContract.View view) {
mView = view;
mModel = new BlogShareModelImpl();
}
@Override
public void start() {
refresh();
}
@Override
public void refresh() {
mModel.loadShareList(mView.getUserBean(), new OnBlogLoadListener() {
@Override
public void success(final List<BlogBean> list) {
mHandler.post(new Runnable() {
@Override
public void run() {
mView.showList(list);
}
});
}
@Override
public void failed(final String errorMsg) {
mHandler.post(new Runnable() {
@Override
public void run() {
mView.showLoadFailed(errorMsg);
}
});
}
});
}
} | [
"brioal@foxmail.com"
] | brioal@foxmail.com |
05374ab9286ecc4518aac117faa914930d6ec5d5 | 15fbcc1c1dbd648399e05e108b5ed3f78a0795ee | /src/main/java/org/onnx4j/opsets/domain/aiOnnx/v1/ops/GatherV1.java | ccb5996f5705caef2cfa184c6a4ccfff7d29f569 | [
"Apache-2.0"
] | permissive | onnx4j/onnx4j | 3f9b1f65043098a472f50829b036a70a35ac4ebf | 3d2d6c9de231bd194ff0e811cfb3b79578d18144 | refs/heads/master | 2022-11-05T14:04:49.763155 | 2020-03-04T17:06:06 | 2020-03-04T17:06:06 | 227,007,353 | 25 | 3 | Apache-2.0 | 2022-10-04T23:55:10 | 2019-12-10T02:01:43 | Java | UTF-8 | Java | false | false | 5,343 | 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.onnx4j.opsets.domain.aiOnnx.v1.ops;
import org.onnx4j.Inputs;
import org.onnx4j.model.graph.Node;
import org.onnx4j.model.graph.node.attributes.IntAttribute;
import org.onnx4j.opsets.domain.aiOnnx.v1.AiOnnxOperatorV1;
import org.onnx4j.opsets.operator.Field;
import org.onnx4j.opsets.operator.Field.TypeConstraint;
import org.onnx4j.opsets.operator.OperatorInputs;
import org.onnx4j.opsets.operator.fields.AttributeField;
import org.onnx4j.opsets.operator.fields.InputField;
import org.onnx4j.opsets.operator.output.SingleOperatorOutputs;
import org.onnx4j.tensor.DataType;
/**
* Gather Operator v1
*
* <p>
* Given data tensor of rank {@literal r >= 1}, and indices tensor of rank q,
* gather entries of the axis dimension of data (by default outer-most one as
* axis=0) indexed by indices, and concatenates them in an output tensor of rank
* q + (r - 1).
*
* <p>
* Example 1:
*
* <pre>
* data = [
* [1.0, 1.2],
* [2.3, 3.4],
* [4.5, 5.7],
* ]
* indices = [
* [0, 1],
* [1, 2],
* ]
* output = [
* [
* [1.0, 1.2],
* [2.3, 3.4],
* ],
* [
* [2.3, 3.4],
* [4.5, 5.7],
* ],
* ]
* </pre>
*
* <p>
* Example 2:
*
* <pre>
* data = [
* [1.0, 1.2, 1.9],
* [2.3, 3.4, 3.9],
* [4.5, 5.7, 5.9],
* ]
* indices = [
* [0, 2],
* ]
* axis = 1,
* output = [
* [
* [1.0, 1.9],
* [2.3, 3.9],
* [4.5, 5.9],
* ],
* ]
* </pre>
*
* @author HarryLee {@literal <formaten@qq.com>}
* @version 1
* @since Version 1 of the default ONNX operator set
* @see <a href=
* "https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Reshape-1">
* ONNX.Changelog.md</a>
* @see <a href=
* "https://github.com/onnx/onnx/blob/master/docs/Operators.md#Reshape">
* ONNX.Operators.md</a>
*/
public interface GatherV1 extends AiOnnxOperatorV1 {
public static final String OP_TYPE = "Gather";
/**
* Constrain input and output types to any tensor type.
*/
public static final TypeConstraint TPYE_CONSTRAINT_T = new TypeConstraint(DataType.allTypes());
/**
* Constrain indices to integer types.
*/
public static final TypeConstraint TPYE_CONSTRAINT_TIND = new TypeConstraint(DataType.INT32, DataType.INT64);
/**
* Executes operator
*
* @param data
* Tensor of rank {@literal r >= 1}.
* @param indices
* Tensor of int32/int64 indices, of any rank q. All index values
* are expected to be within bounds. It is an error if any of the
* index values are out of bounds.
* @param axis
* Which axis to gather on. Negative value means counting
* dimensions from the back. Accepted range is [-r, r-1]
* @return Tensor of rank q + (r - 1).
*/
//public abstract T_TENSOR gather(T_TENSOR data, T_TENSOR indices, Long axis);
@Override
public default OperatorStatus getStatus() {
return OperatorStatus.STABLE;
}
@Override
public default String getOpType() {
return OP_TYPE;
}
class GatherInputsV1<T_TENSOR> extends OperatorInputs<T_TENSOR> {
public static final String ATTR_AXIS = "axis";
protected Field<T_TENSOR> dataField = new InputField<T_TENSOR>(this, TPYE_CONSTRAINT_T, super.inputArray[0]);
/**
* Tensor of int32/int64 indices, of any rank q. All index values are
* expected to be within bounds. It is an error if any of the index
* values are out of bounds.
*/
protected Field<T_TENSOR> indicesField = new InputField<T_TENSOR>(this, TPYE_CONSTRAINT_TIND,
super.inputArray[1]);
/**
* int (default is 0)
*
* Which axis to gather on. Negative value means counting dimensions
* from the back. Accepted range is [-r, r-1]
*/
protected Field<Long> axisField = new AttributeField<Long>(super.attrs, ATTR_AXIS, IntAttribute.class, 0L,
true);
public GatherInputsV1(Node node, Inputs inputs) {
super(node, inputs);
}
public Long getAxis() {
return axisField.getData();
}
public T_TENSOR getData() {
return dataField.getData();
}
public T_TENSOR getIndices() {
return indicesField.getData();
}
}
/**
* Outputs for operator execution (forward & backward) s
*
* @param <T_TENSOR>
* The backend tensor object.
*/
class GatherOutputV1<T_TENSOR> extends SingleOperatorOutputs<T_TENSOR> {
public GatherOutputV1(T_TENSOR output) {
super(output);
}
@Override
public TypeConstraint getTypeConstraint() {
return TPYE_CONSTRAINT_T;
}
}
} | [
"formaten@users.noreply.github.com"
] | formaten@users.noreply.github.com |
a30a55b883e51bb32e030f8f56b0e6df5869775f | a1e4b48c113359141edd16579d2a441388398b83 | /library/src/main/java/com/reelyactive/blesdk/support/ble/LBluetoothLeScannerCompat.java | abddd7d113267a7efac53f80c2f376bfc34b89a8 | [
"Apache-2.0"
] | permissive | jameschen00/ble-android-sdk | e2d945b616817fe06735a3216a9fbad6ef30cd04 | 4308c92e79f95c192358c54fc514a0c009a51d79 | refs/heads/master | 2021-01-19T07:10:43.179573 | 2015-05-26T21:10:02 | 2015-05-26T21:10:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,430 | java | package com.reelyactive.blesdk.support.ble;
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import com.reelyactive.blesdk.support.ble.util.Clock;
import com.reelyactive.blesdk.support.ble.util.Logger;
import com.reelyactive.blesdk.support.ble.util.SystemClock;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Implements Bluetooth LE scan related API on top of {@link android.os.Build.VERSION_CODES#LOLLIPOP}
* and later.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class LBluetoothLeScannerCompat extends BluetoothLeScannerCompat {
// Alarm Scan variables
private final Clock clock;
private final AlarmManager alarmManager;
private final PendingIntent alarmIntent;
private final Map<ScanCallback, ScanClient> callbacksMap =
new HashMap<ScanCallback, ScanClient>();
private final android.bluetooth.le.BluetoothLeScanner osScanner;
final HashMap<String, ScanResult> recentScanResults;
/**
* Package-protected constructor, used by {@link BluetoothLeScannerCompatProvider}.
* <p/>
* Cannot be called from emulated devices that don't implement a BluetoothAdapter.
*/
LBluetoothLeScannerCompat(Context context, BluetoothManager manager, AlarmManager alarmManager) {
this(manager, alarmManager, new SystemClock(),
PendingIntent.getBroadcast(context, 0 /* requestCode */,
new Intent(context, ScanWakefulBroadcastReceiver.class).putExtra(ScanWakefulService.EXTRA_USE_LOLLIPOP_API, true), 0 /* flags */));
}
LBluetoothLeScannerCompat(BluetoothManager manager, AlarmManager alarmManager,
Clock clock, PendingIntent alarmIntent) {
Logger.logDebug("BLE 'L' hardware access layer activated");
this.osScanner = manager.getAdapter().getBluetoothLeScanner();
this.recentScanResults = new HashMap<String, ScanResult>();
this.alarmManager = alarmManager;
this.clock = clock;
this.alarmIntent = alarmIntent;
}
@Override
public boolean startScan(List<ScanFilter> filters, ScanSettings settings, ScanCallback callback) {
if (callbacksMap.containsKey(callback)) {
Logger.logInfo("StartScan(): BLE 'L' hardware scan already in progress...");
stopScan(callback);
}
android.bluetooth.le.ScanSettings osSettings = toOs(settings);
ScanClient osCallback = toOs(callback, settings);
List<android.bluetooth.le.ScanFilter> osFilters = toOs(filters);
callbacksMap.put(callback, osCallback);
try {
Logger.logInfo("Starting BLE 'L' hardware scan");
osScanner.startScan(osFilters, osSettings, osCallback);
updateRepeatingAlarm();
return true;
} catch (Exception e) {
Logger.logError("Exception caught calling 'L' BluetoothLeScanner.startScan()", e);
return false;
}
}
@Override
public void stopScan(ScanCallback callback) {
android.bluetooth.le.ScanCallback osCallback = callbacksMap.get(callback);
if (osCallback != null) {
try {
Logger.logInfo("Stopping BLE 'L' hardware scan");
osScanner.stopScan(osCallback);
} catch (Exception e) {
Logger.logError("Exception caught calling 'L' BluetoothLeScanner.stopScan()", e);
}
callbacksMap.remove(callback);
updateRepeatingAlarm();
}
}
@Override
public Clock getClock() {
return clock;
}
private int getScanModePriority(int mode) {
switch (mode) {
case ScanSettings.SCAN_MODE_LOW_LATENCY:
return 2;
case ScanSettings.SCAN_MODE_BALANCED:
return 1;
case ScanSettings.SCAN_MODE_LOW_POWER:
return 0;
default:
Logger.logError("Unknown scan mode " + mode);
return 0;
}
}
protected int getMaxPriorityScanMode() {
int maxPriority = -1;
for (ScanClient scanClient : callbacksMap.values()) {
ScanSettings settings = scanClient.settings;
if (maxPriority == -1
|| getScanModePriority(settings.getScanMode()) > getScanModePriority(maxPriority)) {
maxPriority = settings.getScanMode();
}
}
return maxPriority;
}
@Override
protected boolean hasClients() {
return !callbacksMap.isEmpty();
}
@Override
protected AlarmManager getAlarmManager() {
return alarmManager;
}
@Override
protected PendingIntent getAlarmIntent() {
return alarmIntent;
}
/////////////////////////////////////////////////////////////////////////////
// Conversion methods
private static android.bluetooth.le.ScanSettings toOs(ScanSettings settings) {
return new android.bluetooth.le.ScanSettings.Builder()
.setReportDelay(settings.getReportDelayMillis())
.setScanMode(settings.getScanMode())
.build();
}
private ScanClient toOs(final ScanCallback callback, ScanSettings settings) {
return new ScanClient(callback, settings);
}
private static List<android.bluetooth.le.ScanFilter> toOs(List<ScanFilter> filters) {
List<android.bluetooth.le.ScanFilter> osFilters =
new ArrayList<android.bluetooth.le.ScanFilter>(filters.size());
for (ScanFilter filter : filters) {
osFilters.add(toOs(filter));
}
return osFilters;
}
private static android.bluetooth.le.ScanFilter toOs(ScanFilter filter) {
android.bluetooth.le.ScanFilter.Builder builder = new android.bluetooth.le.ScanFilter.Builder();
if (!isNullOrEmpty(filter.getDeviceAddress())) {
builder.setDeviceAddress(filter.getDeviceAddress());
}
if (!isNullOrEmpty(filter.getDeviceName())) {
builder.setDeviceName(filter.getDeviceName());
}
if (filter.getManufacturerId() != -1 && filter.getManufacturerData() != null) {
if (filter.getManufacturerDataMask() != null) {
builder.setManufacturerData(filter.getManufacturerId(), filter.getManufacturerData(),
filter.getManufacturerDataMask());
} else {
builder.setManufacturerData(filter.getManufacturerId(), filter.getManufacturerData());
}
}
if (filter.getServiceDataUuid() != null && filter.getServiceData() != null) {
if (filter.getServiceDataMask() != null) {
builder.setServiceData(
filter.getServiceDataUuid(), filter.getServiceData(), filter.getServiceDataMask());
} else {
builder.setServiceData(filter.getServiceDataUuid(), filter.getServiceData());
}
}
if (filter.getServiceUuid() != null) {
if (filter.getServiceUuidMask() != null) {
builder.setServiceUuid(filter.getServiceUuid(), filter.getServiceUuidMask());
} else {
builder.setServiceUuid(filter.getServiceUuid());
}
}
return builder.build();
}
private static List<ScanResult> fromOs(List<android.bluetooth.le.ScanResult> osResults) {
List<ScanResult> results = new ArrayList<ScanResult>(osResults.size());
for (android.bluetooth.le.ScanResult result : osResults) {
results.add(fromOs(result));
}
return results;
}
private static ScanResult fromOs(android.bluetooth.le.ScanResult osResult) {
return new ScanResult(
osResult.getDevice(),
fromOs(osResult.getScanRecord()),
osResult.getRssi(),
// Convert the osResult timestamp from 'nanos since boot' to 'nanos since epoch'.
osResult.getTimestampNanos() + getActualBootTimeNanos());
}
private static long getActualBootTimeNanos() {
long currentTimeNanos = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis());
long elapsedRealtimeNanos = android.os.SystemClock.elapsedRealtimeNanos();
return currentTimeNanos - elapsedRealtimeNanos;
}
private static ScanRecord fromOs(android.bluetooth.le.ScanRecord osRecord) {
return ScanRecord.parseFromBytes(osRecord.getBytes());
}
private static boolean isNullOrEmpty(String s) {
return (s == null) || s.isEmpty();
}
@Override
protected void onNewScanCycle() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Iterator<Map.Entry<String, ScanResult>> iter = recentScanResults.entrySet().iterator();
long lostTimestampMillis = getLostTimestampMillis();
// Clear out any expired notifications from the "old sightings" record.
while (iter.hasNext()) {
Map.Entry<String, ScanResult> entry = iter.next();
String address = entry.getKey();
ScanResult savedResult = entry.getValue();
if (TimeUnit.NANOSECONDS.toMillis(savedResult.getTimestampNanos()) < lostTimestampMillis) {
callbackLostLeScanClients(address, savedResult);
iter.remove();
}
}
}
});
}
@Override
protected Collection<ScanResult> getRecentScanResults() {
return recentScanResults.values();
}
private void callbackLostLeScanClients(String address, ScanResult result) {
for (ScanClient client : callbacksMap.values()) {
int wantAny = client.settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_ALL_MATCHES;
int wantLost = client.settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_MATCH_LOST;
if (client.addressesSeen.remove(address) && (wantAny | wantLost) != 0) {
// Catch any exceptions and log them but continue processing other scan results.
try {
client.callback.onScanResult(ScanSettings.CALLBACK_TYPE_MATCH_LOST, result);
} catch (Exception e) {
Logger.logError("Failure while sending 'lost' scan result to listener", e);
}
}
}
}
private class ScanClient extends android.bluetooth.le.ScanCallback {
final Set<String> addressesSeen;
final ScanCallback callback;
final ScanSettings settings;
ScanClient(ScanCallback callback, ScanSettings settings) {
this.settings = settings;
this.addressesSeen = new HashSet<String>();
this.callback = callback;
}
@Override
public void onScanResult(int callbackType, android.bluetooth.le.ScanResult osResult) {
String address = osResult.getDevice().getAddress();
boolean seenItBefore = addressesSeen.contains(address);
int clientFlags = settings.getCallbackType();
int firstMatchBit = clientFlags & ScanSettings.CALLBACK_TYPE_FIRST_MATCH;
int allMatchesBit = clientFlags & ScanSettings.CALLBACK_TYPE_ALL_MATCHES;
ScanResult result = fromOs(osResult);
recentScanResults.put(address, result);
// Catch any exceptions and log them but continue processing other listeners.
if ((firstMatchBit | allMatchesBit) != 0) {
try {
if (!seenItBefore) {
callback.onScanResult(ScanSettings.CALLBACK_TYPE_FIRST_MATCH, result);
} else if (allMatchesBit != 0) {
callback.onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, result);
}
} catch (Exception e) {
Logger.logError("Failure while handling scan result", e);
}
}
addressesSeen.add(address);
}
@Override
public void onScanFailed(int errorCode) {
Logger.logInfo("LBluetoothLeScannerCompat::onScanFailed(" + errorCode + ")");
callback.onScanFailed(errorCode);
}
}
}
| [
"s@sidereo.com"
] | s@sidereo.com |
fd176bfaeedd01bc4f3331dda108d976cd709d64 | d25221673bd55d2a6e09a48027033f471ee3574f | /api/src/main/java/com/tsco/api/domain/enums/GenderEnum.java | 88540232f24047b17d3f7b10769e10909e934aaf | [] | no_license | hello-xiaoleng/AnswerSystem | d78eb3fd83044ee84cfd065cb8d2dcf7981fd9c9 | 5d54787653deafd0a7072855283e26206477cb1a | refs/heads/master | 2020-04-28T20:43:20.640447 | 2019-02-19T14:03:17 | 2019-02-19T14:03:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 246 | java | package com.tsco.api.domain.enums;
public enum GenderEnum {
MALE("男"), FEMALE("女");
GenderEnum(String desc) {
this.desc = desc;
}
private String desc;
public String getDesc() {
return desc;
}
}
| [
"chenjia02@@chinatopcredit.com"
] | chenjia02@@chinatopcredit.com |
2eb277201104b8aa646b450cd1361eaba42ceac1 | c17b4458fb1bb709661c8a79b0514cea440155db | /src/com/java/designPattern/proxy/cglib/ProxyJdkTest.java | d241cd326ea8aafc6fe0d2a627b1541056a0b5fb | [] | no_license | range-123/DesignPattern | 84140f6045b8bea2faf7f28dc57deeb1647c801d | 5e5f2a444895913e4f413d8e34d0b537ad298cc2 | refs/heads/master | 2020-10-02T09:27:45.468887 | 2019-12-17T03:08:06 | 2019-12-17T03:08:06 | 227,747,172 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 751 | java | package com.java.designPattern.proxy.cglib;
import com.java.designPattern.proxy.jdkProxy.ProxyJdkReal;
import com.java.designPattern.proxy.staticProxy.IProxyStaticDb;
import com.java.designPattern.proxy.staticProxy.ProxyStaticPro;
import com.java.designPattern.proxy.staticProxy.ProxyStaticReal;
import com.java.designPattern.proxy.units.Book;
import com.java.designPattern.proxy.units.Customer;
/**
* @program: DesignPattern
* @description: 测试-静态代理
* @author: fz
* @create: 2019-12-16 14:59
*/
public class ProxyJdkTest {
public static void main(String[] args) {
ProxyCglibReal proxyCglib = (ProxyCglibReal) new ProxyCglibPro().getInstance(new ProxyCglibReal());
proxyCglib.introduce(new Customer());
}
} | [
"916042021@qq.com"
] | 916042021@qq.com |
22c4908398017a3eb0fa1037e975729a088bd7dd | 3bc62f2a6d32df436e99507fa315938bc16652b1 | /play/src/main/java/com/intellij/play/files/PlayStructureViewModel.java | 13e44d8768c4dbda192c750df875ada6a54f4b09 | [
"Apache-2.0"
] | permissive | JetBrains/intellij-obsolete-plugins | 7abf3f10603e7fe42b9982b49171de839870e535 | 3e388a1f9ae5195dc538df0d3008841c61f11aef | refs/heads/master | 2023-09-04T05:22:46.470136 | 2023-06-11T16:42:37 | 2023-06-11T16:42:37 | 184,035,533 | 19 | 29 | Apache-2.0 | 2023-07-30T14:23:05 | 2019-04-29T08:54:54 | Java | UTF-8 | Java | false | false | 4,199 | java | /*
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.play.files;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.structureView.TextEditorBasedStructureViewModel;
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.editor.Editor;
import com.intellij.play.language.PlayActionCompositeElement;
import com.intellij.play.language.PlayCompositeElement;
import com.intellij.play.language.psi.PlayNameValueCompositeElement;
import com.intellij.play.language.psi.PlayPsiFile;
import com.intellij.play.language.psi.PlayTag;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
public class PlayStructureViewModel extends TextEditorBasedStructureViewModel {
public PlayStructureViewModel(PsiFile file, Editor editor) {
super(editor, file);
}
@Override
@NotNull
public StructureViewTreeElement getRoot() {
return new PlayPsiFilePsiTreeElementBase((PlayPsiFile)getPsiFile());
}
private static class PlayTagPsiTreeElementBase extends PsiTreeElementBase<PlayTag> {
PlayTagPsiTreeElementBase(@NotNull PlayTag playTag) {
super(playTag);
}
@NotNull
@Override
public Collection<StructureViewTreeElement> getChildrenBase() {
Collection<StructureViewTreeElement> children = new ArrayList<>();
final PlayTag playTag = getElement();
if (playTag != null && playTag.isValid()) {
for (PlayTag subtag : playTag.getSubTags()) {
children.add(new PlayTagPsiTreeElementBase(subtag));
}
}
return children;
}
@Override
public String getPresentableText() {
final PlayTag playTag = getElement();
if (playTag != null && playTag.isValid()) {
return playTag.getName();
}
return "";
}
@Override
public String getLocationString() {
final PlayTag playTag = getElement();
if (playTag != null && playTag.isValid()) {
final PlayNameValueCompositeElement[] nameValues = playTag.getNameValues();
if (nameValues.length != 0) {
return elementsToString(nameValues);
}
final PlayActionCompositeElement[] actions = playTag.getActions();
if (actions.length > 0) {
return elementsToString(actions, "@");
}
return elementsToString(playTag.getTagExpressions());
}
return null;
}
@Nullable
private static String elementsToString(PlayCompositeElement[] nameValues) {
return elementsToString(nameValues, "");
}
@Nullable
private static String elementsToString(PlayCompositeElement[] nameValues, String prefix) {
if (nameValues.length == 0) return null;
StringBuilder sb = new StringBuilder();
for (PlayCompositeElement nameValue : nameValues) {
sb.append(prefix);
sb.append(nameValue.getText());
sb.append(" ");
}
return sb.toString();
}
@NotNull
@Override
public ItemPresentation getPresentation() {
return super.getPresentation();
}
@Override
public Icon getIcon(boolean open) {
return super.getIcon(open);
}
}
private static class PlayPsiFilePsiTreeElementBase extends PsiTreeElementBase<PlayPsiFile> {
PlayPsiFilePsiTreeElementBase(PlayPsiFile psiFile) {
super(psiFile);
}
@Override
@NotNull
public Collection<StructureViewTreeElement> getChildrenBase() {
Collection<StructureViewTreeElement> treeElements = new ArrayList<>();
final PlayPsiFile file = getElement();
if (file != null) {
for (final PlayTag playTag : file.getRootTags()) {
treeElements.add(new PlayTagPsiTreeElementBase(playTag));
}
}
return treeElements;
}
@Override
public String getPresentableText() {
final PlayPsiFile file = getElement();
return file == null ? "Play" : file.getPresentableName();
}
}
}
| [
"yuriy.artamonov@jetbrains.com"
] | yuriy.artamonov@jetbrains.com |
b2a25604ed60789fa35e7c4bf5ddf1c19fb1e4fe | 5598faaaaa6b3d1d8502cbdaca903f9037d99600 | /code_changes/Apache_projects/HIVE-15755/3ed7dc2b82f84ade5f2be0cb85a95b49dc30086c/~UpdateDeleteSemanticAnalyzer.java | f102786054dbabe621a1bed60e6794e7ad6cd505 | [] | no_license | SPEAR-SE/LogInBugReportsEmpirical_Data | 94d1178346b4624ebe90cf515702fac86f8e2672 | ab9603c66899b48b0b86bdf63ae7f7a604212b29 | refs/heads/master | 2022-12-18T02:07:18.084659 | 2020-09-09T16:49:34 | 2020-09-09T16:49:34 | 286,338,252 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 56,030 | 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.hadoop.hive.ql.parse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.antlr.runtime.TokenRewriteStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.hooks.Entity;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.HiveUtils;
import org.apache.hadoop.hive.ql.metadata.InvalidTableException;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
import org.apache.hadoop.hive.ql.session.SessionState;
/**
* A subclass of the {@link org.apache.hadoop.hive.ql.parse.SemanticAnalyzer} that just handles
* update, delete and merge statements. It works by rewriting the updates and deletes into insert
* statements (since they are actually inserts) and then doing some patch up to make them work as
* updates and deletes instead.
*/
public class UpdateDeleteSemanticAnalyzer extends SemanticAnalyzer {
boolean useSuper = false;
public UpdateDeleteSemanticAnalyzer(QueryState queryState) throws SemanticException {
super(queryState);
}
@Override
public void analyzeInternal(ASTNode tree) throws SemanticException {
if (useSuper) {
super.analyzeInternal(tree);
} else {
if (!SessionState.get().getTxnMgr().supportsAcid()) {
throw new SemanticException(ErrorMsg.ACID_OP_ON_NONACID_TXNMGR.getMsg());
}
switch (tree.getToken().getType()) {
case HiveParser.TOK_DELETE_FROM:
analyzeDelete(tree);
break;
case HiveParser.TOK_UPDATE_TABLE:
analyzeUpdate(tree);
break;
case HiveParser.TOK_MERGE:
analyzeMerge(tree);
break;
default:
throw new RuntimeException("Asked to parse token " + tree.getName() + " in " +
"UpdateDeleteSemanticAnalyzer");
}
cleanUpMetaColumnAccessControl();
}
}
private boolean updating() {
return currentOperation == Operation.UPDATE;
}
private boolean deleting() {
return currentOperation == Operation.DELETE;
}
private void analyzeUpdate(ASTNode tree) throws SemanticException {
currentOperation = Operation.UPDATE;
reparseAndSuperAnalyze(tree);
}
private void analyzeDelete(ASTNode tree) throws SemanticException {
currentOperation = Operation.DELETE;
reparseAndSuperAnalyze(tree);
}
/**
* Append list of partition columns to Insert statement, i.e. the 1st set of partCol1,partCol2
* INSERT INTO T PARTITION(partCol1,partCol2...) SELECT col1, ... partCol1,partCol2...
*/
private void addPartitionColsToInsert(List<FieldSchema> partCols, StringBuilder rewrittenQueryStr) {
// If the table is partitioned we have to put the partition() clause in
if (partCols != null && partCols.size() > 0) {
rewrittenQueryStr.append(" partition (");
boolean first = true;
for (FieldSchema fschema : partCols) {
if (first)
first = false;
else
rewrittenQueryStr.append(", ");
//would be nice if there was a way to determine if quotes are needed
rewrittenQueryStr.append(HiveUtils.unparseIdentifier(fschema.getName(), this.conf));
}
rewrittenQueryStr.append(")");
}
}
/**
* Append list of partition columns to Insert statement, i.e. the 2nd set of partCol1,partCol2
* INSERT INTO T PARTITION(partCol1,partCol2...) SELECT col1, ... partCol1,partCol2...
* @param target target table
*/
private void addPartitionColsToSelect(List<FieldSchema> partCols, StringBuilder rewrittenQueryStr,
ASTNode target) throws SemanticException {
String targetName = target != null ? getSimpleTableName(target) : null;
// If the table is partitioned, we need to select the partition columns as well.
if (partCols != null) {
for (FieldSchema fschema : partCols) {
rewrittenQueryStr.append(", ");
//would be nice if there was a way to determine if quotes are needed
if(targetName != null) {
rewrittenQueryStr.append(targetName).append('.');
}
rewrittenQueryStr.append(HiveUtils.unparseIdentifier(fschema.getName(), this.conf));
}
}
}
/**
* Assert that we are not asked to update a bucketing column or partition column
* @param colName it's the A in "SET A = B"
*/
private void checkValidSetClauseTarget(ASTNode colName, Table targetTable) throws SemanticException {
String columnName = normalizeColName(colName.getText());
// Make sure this isn't one of the partitioning columns, that's not supported.
for (FieldSchema fschema : targetTable.getPartCols()) {
if (fschema.getName().equalsIgnoreCase(columnName)) {
throw new SemanticException(ErrorMsg.UPDATE_CANNOT_UPDATE_PART_VALUE.getMsg());
}
}
//updating bucket column should move row from one file to another - not supported
if(targetTable.getBucketCols() != null && targetTable.getBucketCols().contains(columnName)) {
throw new SemanticException(ErrorMsg.UPDATE_CANNOT_UPDATE_BUCKET_VALUE,columnName);
}
boolean foundColumnInTargetTable = false;
for(FieldSchema col : targetTable.getCols()) {
if(columnName.equalsIgnoreCase(col.getName())) {
foundColumnInTargetTable = true;
break;
}
}
if(!foundColumnInTargetTable) {
throw new SemanticException(ErrorMsg.INVALID_TARGET_COLUMN_IN_SET_CLAUSE, colName.getText(),
getDotName(new String[] {targetTable.getDbName(), targetTable.getTableName()}));
}
}
private ASTNode findLHSofAssignment(ASTNode assignment) {
assert assignment.getToken().getType() == HiveParser.EQUAL :
"Expected set assignments to use equals operator but found " + assignment.getName();
ASTNode tableOrColTok = (ASTNode)assignment.getChildren().get(0);
assert tableOrColTok.getToken().getType() == HiveParser.TOK_TABLE_OR_COL :
"Expected left side of assignment to be table or column";
ASTNode colName = (ASTNode)tableOrColTok.getChildren().get(0);
assert colName.getToken().getType() == HiveParser.Identifier :
"Expected column name";
return colName;
}
private Map<String, ASTNode> collectSetColumnsAndExpressions(ASTNode setClause,
Set<String> setRCols, Table targetTable) throws SemanticException {
// An update needs to select all of the columns, as we rewrite the entire row. Also,
// we need to figure out which columns we are going to replace.
assert setClause.getToken().getType() == HiveParser.TOK_SET_COLUMNS_CLAUSE :
"Expected second child of update token to be set token";
// Get the children of the set clause, each of which should be a column assignment
List<? extends Node> assignments = setClause.getChildren();
// Must be deterministic order map for consistent q-test output across Java versions
Map<String, ASTNode> setCols = new LinkedHashMap<String, ASTNode>(assignments.size());
for (Node a : assignments) {
ASTNode assignment = (ASTNode)a;
ASTNode colName = findLHSofAssignment(assignment);
if(setRCols != null) {
addSetRCols((ASTNode) assignment.getChildren().get(1), setRCols);
}
checkValidSetClauseTarget(colName, targetTable);
String columnName = normalizeColName(colName.getText());
// This means that in UPDATE T SET x = _something_
// _something_ can be whatever is supported in SELECT _something_
setCols.put(columnName, (ASTNode)assignment.getChildren().get(1));
}
return setCols;
}
/**
* @return the Metastore representation of the target table
*/
private Table getTargetTable(ASTNode tabRef) throws SemanticException {
String[] tableName;
Table mTable;
switch (tabRef.getType()) {
case HiveParser.TOK_TABREF:
tableName = getQualifiedTableName((ASTNode) tabRef.getChild(0));
break;
case HiveParser.TOK_TABNAME:
tableName = getQualifiedTableName(tabRef);
break;
default:
throw raiseWrongType("TOK_TABREF|TOK_TABNAME", tabRef);
}
try {
mTable = db.getTable(tableName[0], tableName[1]);
} catch (InvalidTableException e) {
LOG.error("Failed to find table " + getDotName(tableName) + " got exception "
+ e.getMessage());
throw new SemanticException(ErrorMsg.INVALID_TABLE.getMsg(getDotName(tableName)), e);
} catch (HiveException e) {
LOG.error("Failed to find table " + getDotName(tableName) + " got exception "
+ e.getMessage());
throw new SemanticException(e.getMessage(), e);
}
return mTable;
}
// Walk through all our inputs and set them to note that this read is part of an update or a
// delete.
private void markReadEntityForUpdate() {
for (ReadEntity input : inputs) {
if(isWritten(input)) {
//todo: this is actually not adding anything since LockComponent uses a Trie to "promote" a lock
//except by accident - when we have a partitioned target table we have a ReadEntity and WriteEntity
//for the table, so we mark ReadEntity and then delete WriteEntity (replace with Partition entries)
//so DbTxnManager skips Read lock on the ReadEntity....
input.setUpdateOrDelete(true);//input.noLockNeeded()?
}
}
}
/**
* For updates, we need to set the column access info so that it contains information on
* the columns we are updating.
* (But not all the columns of the target table even though the rewritten query writes
* all columns of target table since that is an implmentation detail)
*/
private void setUpAccessControlInfoForUpdate(Table mTable, Map<String, ASTNode> setCols) {
ColumnAccessInfo cai = new ColumnAccessInfo();
for (String colName : setCols.keySet()) {
cai.add(Table.getCompleteName(mTable.getDbName(), mTable.getTableName()), colName);
}
setUpdateColumnAccessInfo(cai);
}
/**
* We need to weed ROW__ID out of the input column info, as it doesn't make any sense to
* require the user to have authorization on that column.
*/
private void cleanUpMetaColumnAccessControl() {
//we do this for Update/Delete (incl Merge) because we introduce this column into the query
//as part of rewrite
if (columnAccessInfo != null) {
columnAccessInfo.stripVirtualColumn(VirtualColumn.ROWID);
}
}
/**
* Parse the newly generated SQL statment to get a new AST
*/
private ReparseResult parseRewrittenQuery(StringBuilder rewrittenQueryStr, String originalQuery) throws SemanticException {
// Parse the rewritten query string
Context rewrittenCtx;
try {
// Set dynamic partitioning to nonstrict so that queries do not need any partition
// references.
// todo: this may be a perf issue as it prevents the optimizer.. or not
HiveConf.setVar(conf, HiveConf.ConfVars.DYNAMICPARTITIONINGMODE, "nonstrict");
rewrittenCtx = new Context(conf);
rewrittenCtx.setExplainConfig(ctx.getExplainConfig());
} catch (IOException e) {
throw new SemanticException(ErrorMsg.UPDATEDELETE_IO_ERROR.getMsg());
}
rewrittenCtx.setCmd(rewrittenQueryStr.toString());
ParseDriver pd = new ParseDriver();
ASTNode rewrittenTree;
try {
LOG.info("Going to reparse <" + originalQuery + "> as \n<" + rewrittenQueryStr.toString() + ">");
rewrittenTree = pd.parse(rewrittenQueryStr.toString(), rewrittenCtx);
rewrittenTree = ParseUtils.findRootNonNullToken(rewrittenTree);
} catch (ParseException e) {
throw new SemanticException(ErrorMsg.UPDATEDELETE_PARSE_ERROR.getMsg(), e);
}
return new ReparseResult(rewrittenTree, rewrittenCtx);
}
/**
* Assert it supports Acid write
*/
private void validateTargetTable(Table mTable) throws SemanticException {
if (mTable.getTableType() == TableType.VIRTUAL_VIEW ||
mTable.getTableType() == TableType.MATERIALIZED_VIEW) {
LOG.error("Table " + getDotName(new String[] {mTable.getDbName(), mTable.getTableName()}) + " is a view or materialized view");
throw new SemanticException(ErrorMsg.UPDATE_DELETE_VIEW.getMsg());
}
}
/**
* This supports update and delete statements
*/
private void reparseAndSuperAnalyze(ASTNode tree) throws SemanticException {
List<? extends Node> children = tree.getChildren();
// The first child should be the table we are deleting from
ASTNode tabName = (ASTNode)children.get(0);
assert tabName.getToken().getType() == HiveParser.TOK_TABNAME :
"Expected tablename as first child of " + operation() + " but found " + tabName.getName();
// Rewrite the delete or update into an insert. Crazy, but it works as deletes and update
// actually are inserts into the delta file in Hive. A delete
// DELETE FROM _tablename_ [WHERE ...]
// will be rewritten as
// INSERT INTO TABLE _tablename_ [PARTITION (_partcols_)] SELECT ROW__ID[,
// _partcols_] from _tablename_ SORT BY ROW__ID
// An update
// UPDATE _tablename_ SET x = _expr_ [WHERE...]
// will be rewritten as
// INSERT INTO TABLE _tablename_ [PARTITION (_partcols_)] SELECT _all_,
// _partcols_from _tablename_ SORT BY ROW__ID
// where _all_ is all the non-partition columns. The expressions from the set clause will be
// re-attached later.
// The where clause will also be re-attached later.
// The sort by clause is put in there so that records come out in the right order to enable
// merge on read.
StringBuilder rewrittenQueryStr = new StringBuilder();
Table mTable = getTargetTable(tabName);
validateTargetTable(mTable);
rewrittenQueryStr.append("insert into table ");
rewrittenQueryStr.append(getFullTableNameForSQL(tabName));
addPartitionColsToInsert(mTable.getPartCols(), rewrittenQueryStr);
rewrittenQueryStr.append(" select ROW__ID");
Map<Integer, ASTNode> setColExprs = null;
Map<String, ASTNode> setCols = null;
// Must be deterministic order set for consistent q-test output across Java versions
Set<String> setRCols = new LinkedHashSet<String>();
if (updating()) {
// We won't write the set
// expressions in the rewritten query. We'll patch that up later.
// The set list from update should be the second child (index 1)
assert children.size() >= 2 : "Expected update token to have at least two children";
ASTNode setClause = (ASTNode)children.get(1);
setCols = collectSetColumnsAndExpressions(setClause, setRCols, mTable);
setColExprs = new HashMap<>(setClause.getChildCount());
List<FieldSchema> nonPartCols = mTable.getCols();
for (int i = 0; i < nonPartCols.size(); i++) {
rewrittenQueryStr.append(',');
String name = nonPartCols.get(i).getName();
ASTNode setCol = setCols.get(name);
rewrittenQueryStr.append(HiveUtils.unparseIdentifier(name, this.conf));
if (setCol != null) {
// This is one of the columns we're setting, record it's position so we can come back
// later and patch it up.
// Add one to the index because the select has the ROW__ID as the first column.
setColExprs.put(i + 1, setCol);
}
}
}
addPartitionColsToSelect(mTable.getPartCols(), rewrittenQueryStr, null);
rewrittenQueryStr.append(" from ");
rewrittenQueryStr.append(getFullTableNameForSQL(tabName));
ASTNode where = null;
int whereIndex = deleting() ? 1 : 2;
if (children.size() > whereIndex) {
where = (ASTNode)children.get(whereIndex);
assert where.getToken().getType() == HiveParser.TOK_WHERE :
"Expected where clause, but found " + where.getName();
}
// Add a sort by clause so that the row ids come out in the correct order
rewrittenQueryStr.append(" sort by ROW__ID ");
ReparseResult rr = parseRewrittenQuery(rewrittenQueryStr, ctx.getCmd());
Context rewrittenCtx = rr.rewrittenCtx;
ASTNode rewrittenTree = rr.rewrittenTree;
ASTNode rewrittenInsert = (ASTNode)rewrittenTree.getChildren().get(1);
assert rewrittenInsert.getToken().getType() == HiveParser.TOK_INSERT :
"Expected TOK_INSERT as second child of TOK_QUERY but found " + rewrittenInsert.getName();
if(updating()) {
rewrittenCtx.addDestNamePrefix(rewrittenInsert, Context.DestClausePrefix.UPDATE);
}
else if(deleting()) {
rewrittenCtx.addDestNamePrefix(rewrittenInsert, Context.DestClausePrefix.DELETE);
}
if (where != null) {
// The structure of the AST for the rewritten insert statement is:
// TOK_QUERY -> TOK_FROM
// \-> TOK_INSERT -> TOK_INSERT_INTO
// \-> TOK_SELECT
// \-> TOK_SORTBY
// The following adds the TOK_WHERE and its subtree from the original query as a child of
// TOK_INSERT, which is where it would have landed if it had been there originally in the
// string. We do it this way because it's easy then turning the original AST back into a
// string and reparsing it. We have to move the SORT_BY over one,
// so grab it and then push it to the second slot, and put the where in the first slot
ASTNode sortBy = (ASTNode)rewrittenInsert.getChildren().get(2);
assert sortBy.getToken().getType() == HiveParser.TOK_SORTBY :
"Expected TOK_SORTBY to be first child of TOK_SELECT, but found " + sortBy.getName();
rewrittenInsert.addChild(sortBy);
rewrittenInsert.setChild(2, where);
}
// Patch up the projection list for updates, putting back the original set expressions.
if (updating() && setColExprs != null) {
// Walk through the projection list and replace the column names with the
// expressions from the original update. Under the TOK_SELECT (see above) the structure
// looks like:
// TOK_SELECT -> TOK_SELEXPR -> expr
// \-> TOK_SELEXPR -> expr ...
ASTNode rewrittenSelect = (ASTNode)rewrittenInsert.getChildren().get(1);
assert rewrittenSelect.getToken().getType() == HiveParser.TOK_SELECT :
"Expected TOK_SELECT as second child of TOK_INSERT but found " +
rewrittenSelect.getName();
for (Map.Entry<Integer, ASTNode> entry : setColExprs.entrySet()) {
ASTNode selExpr = (ASTNode)rewrittenSelect.getChildren().get(entry.getKey());
assert selExpr.getToken().getType() == HiveParser.TOK_SELEXPR :
"Expected child of TOK_SELECT to be TOK_SELEXPR but was " + selExpr.getName();
// Now, change it's child
selExpr.setChild(0, entry.getValue());
}
}
try {
useSuper = true;
super.analyze(rewrittenTree, rewrittenCtx);
} finally {
useSuper = false;
}
updateOutputs(mTable);
if (updating()) {
setUpAccessControlInfoForUpdate(mTable, setCols);
// Add the setRCols to the input list
for (String colName : setRCols) {
if(columnAccessInfo != null) {//assuming this means we are not doing Auth
columnAccessInfo.add(Table.getCompleteName(mTable.getDbName(), mTable.getTableName()),
colName);
}
}
}
}
/**
* Check that {@code readEntity} is also being written
*/
private boolean isWritten(Entity readEntity) {
for(Entity writeEntity : outputs) {
//make sure to compare them as Entity, i.e. that it's the same table or partition, etc
if(writeEntity.toString().equalsIgnoreCase(readEntity.toString())) {
return true;
}
}
return false;
}
private String operation() {
if (currentOperation == Operation.NOT_ACID) {
throw new IllegalStateException("UpdateDeleteSemanticAnalyzer neither updating nor " +
"deleting, operation not known.");
}
return currentOperation.toString();
}
// This method finds any columns on the right side of a set statement (thus rcols) and puts them
// in a set so we can add them to the list of input cols to check.
private void addSetRCols(ASTNode node, Set<String> setRCols) {
// See if this node is a TOK_TABLE_OR_COL. If so, find the value and put it in the list. If
// not, recurse on any children
if (node.getToken().getType() == HiveParser.TOK_TABLE_OR_COL) {
ASTNode colName = (ASTNode)node.getChildren().get(0);
assert colName.getToken().getType() == HiveParser.Identifier :
"Expected column name";
setRCols.add(normalizeColName(colName.getText()));
} else if (node.getChildren() != null) {
for (Node n : node.getChildren()) {
addSetRCols((ASTNode)n, setRCols);
}
}
}
/**
* Column names are stored in metastore in lower case, regardless of the CREATE TABLE statement.
* Unfortunately there is no single place that normalizes the input query.
* @param colName not null
*/
private static String normalizeColName(String colName) {
return colName.toLowerCase();
}
private enum Operation {UPDATE, DELETE, MERGE, NOT_ACID};
private Operation currentOperation = Operation.NOT_ACID;
private static final String Indent = " ";
private IdentifierQuoter quotedIdenfierHelper;
/**
* This allows us to take an arbitrary ASTNode and turn it back into SQL that produced it.
* Since HiveLexer.g is written such that it strips away any ` (back ticks) around
* quoted identifiers we need to add those back to generated SQL.
* Additionally, the parser only produces tokens of type Identifier and never
* QuotedIdentifier (HIVE-6013). So here we just quote all identifiers.
* (') around String literals are retained w/o issues
*/
private static class IdentifierQuoter {
private final TokenRewriteStream trs;
private final IdentityHashMap<ASTNode, ASTNode> visitedNodes = new IdentityHashMap<>();
IdentifierQuoter(TokenRewriteStream trs) {
this.trs = trs;
if(trs == null) {
throw new IllegalArgumentException("Must have a TokenRewriteStream");
}
}
private void visit(ASTNode n) {
if(n.getType() == HiveParser.Identifier) {
if(visitedNodes.containsKey(n)) {
/**
* Since we are modifying the stream, it's not idempotent. Ideally, the caller would take
* care to only quote Identifiers in each subtree once, but this makes it safe
*/
return;
}
visitedNodes.put(n, n);
trs.insertBefore(n.getToken(), "`");
trs.insertAfter(n.getToken(), "`");
}
if(n.getChildCount() <= 0) {return;}
for(Node c : n.getChildren()) {
visit((ASTNode)c);
}
}
}
/**
* This allows us to take an arbitrary ASTNode and turn it back into SQL that produced it without
* needing to understand what it is (except for QuotedIdentifiers)
*
*/
private String getMatchedText(ASTNode n) {
quotedIdenfierHelper.visit(n);
return ctx.getTokenRewriteStream().toString(n.getTokenStartIndex(),
n.getTokenStopIndex() + 1).trim();
}
/**
* Here we take a Merge statement AST and generate a semantically equivalent multi-insert
* statement to exectue. Each Insert leg represents a single WHEN clause. As much as possible,
* the new SQL statement is made to look like the input SQL statement so that it's easier to map
* Query Compiler errors from generated SQL to original one this way.
* The generated SQL is a complete representation of the original input for the same reason.
* In many places SemanticAnalyzer throws exceptions that contain (line, position) coordinates.
* If generated SQL doesn't have everything and is patched up later, these coordinates point to
* the wrong place.
*
* @throws SemanticException
*/
private void analyzeMerge(ASTNode tree) throws SemanticException {
currentOperation = Operation.MERGE;
quotedIdenfierHelper = new IdentifierQuoter(ctx.getTokenRewriteStream());
/*
* See org.apache.hadoop.hive.ql.parse.TestMergeStatement for some examples of the merge AST
For example, given:
merge into acidTbl using nonAcidPart2 source ON acidTbl.a = source.a2
WHEN MATCHED THEN UPDATE set b = source.b2
WHEN NOT MATCHED THEN INSERT VALUES(source.a2, source.b2)
We get AST like this:
"(tok_merge " +
"(tok_tabname acidtbl) (tok_tabref (tok_tabname nonacidpart2) source) " +
"(= (. (tok_table_or_col acidtbl) a) (. (tok_table_or_col source) a2)) " +
"(tok_matched " +
"(tok_update " +
"(tok_set_columns_clause (= (tok_table_or_col b) (. (tok_table_or_col source) b2))))) " +
"(tok_not_matched " +
"tok_insert " +
"(tok_value_row (. (tok_table_or_col source) a2) (. (tok_table_or_col source) b2))))");
And need to produce a multi-insert like this to execute:
FROM acidTbl right outer join nonAcidPart2 ON acidTbl.a = source.a2
Insert into table acidTbl select nonAcidPart2.a2, nonAcidPart2.b2 where acidTbl.a is null
INSERT INTO TABLE acidTbl select target.ROW__ID, nonAcidPart2.a2, nonAcidPart2.b2 where nonAcidPart2.a2=acidTbl.a sort by acidTbl.ROW__ID
*/
/*todo: we need some sort of validation phase over original AST to make things user friendly; for example, if
original command refers to a column that doesn't exist, this will be caught when processing the rewritten query but
the errors will point at locations that the user can't map to anything
- VALUES clause must have the same number of values as target table (including partition cols). Part cols go last in Select clause of Insert as Select
todo: do we care to preserve comments in original SQL?
todo: check if identifiers are propertly escaped/quoted in the generated SQL - it's currently inconsistent
Look at UnparseTranslator.addIdentifierTranslation() - it does unescape + unparse...
todo: consider "WHEN NOT MATCHED BY SOURCE THEN UPDATE SET TargetTable.Col1 = SourceTable.Col1 "; what happens when source is empty? This should be a runtime error - maybe not
the outer side of ROJ is empty => the join produces 0 rows. If supporting WHEN NOT MATCHED BY SOURCE, then this should be a runtime error
*/
ASTNode target = (ASTNode)tree.getChild(0);
ASTNode source = (ASTNode)tree.getChild(1);
String targetName = getSimpleTableName(target);
String sourceName = getSimpleTableName(source);
ASTNode onClause = (ASTNode) tree.getChild(2);
String onClauseAsText = getMatchedText(onClause);
Table targetTable = getTargetTable(target);
validateTargetTable(targetTable);
List<ASTNode> whenClauses = findWhenClauses(tree);
StringBuilder rewrittenQueryStr = new StringBuilder("FROM\n");
rewrittenQueryStr.append(Indent).append(getFullTableNameForSQL(target));
if(isAliased(target)) {
rewrittenQueryStr.append(" ").append(targetName);
}
rewrittenQueryStr.append('\n');
rewrittenQueryStr.append(Indent).append(chooseJoinType(whenClauses)).append("\n");
if(source.getType() == HiveParser.TOK_SUBQUERY) {
//this includes the mandatory alias
rewrittenQueryStr.append(Indent).append(getMatchedText(source));
}
else {
rewrittenQueryStr.append(Indent).append(getFullTableNameForSQL(source));
if(isAliased(source)) {
rewrittenQueryStr.append(" ").append(sourceName);
}
}
rewrittenQueryStr.append('\n');
rewrittenQueryStr.append(Indent).append("ON ").append(onClauseAsText).append('\n');
/**
* We allow at most 2 WHEN MATCHED clause, in which case 1 must be Update the other Delete
* If we have both update and delete, the 1st one (in SQL code) must have "AND <extra predicate>"
* so that the 2nd can ensure not to process the same rows.
* Update and Delete may be in any order. (Insert is always last)
*/
String extraPredicate = null;
int numWhenMatchedUpdateClauses = 0, numWhenMatchedDeleteClauses = 0;
for(ASTNode whenClause : whenClauses) {
switch (getWhenClauseOperation(whenClause).getType()) {
case HiveParser.TOK_INSERT:
handleInsert(whenClause, rewrittenQueryStr, target, onClause, targetTable, targetName, onClauseAsText);
break;
case HiveParser.TOK_UPDATE:
numWhenMatchedUpdateClauses++;
String s = handleUpdate(whenClause, rewrittenQueryStr, target, onClauseAsText, targetTable, extraPredicate);
if(numWhenMatchedUpdateClauses + numWhenMatchedDeleteClauses == 1) {
extraPredicate = s;//i.e. it's the 1st WHEN MATCHED
}
break;
case HiveParser.TOK_DELETE:
numWhenMatchedDeleteClauses++;
String s1 = handleDelete(whenClause, rewrittenQueryStr, target, onClauseAsText, targetTable, extraPredicate);
if(numWhenMatchedUpdateClauses + numWhenMatchedDeleteClauses == 1) {
extraPredicate = s1;//i.e. it's the 1st WHEN MATCHED
}
break;
default:
throw new IllegalStateException("Unexpected WHEN clause type: " + whenClause.getType() +
addParseInfo(whenClause));
}
if(numWhenMatchedDeleteClauses > 1) {
throw new SemanticException(ErrorMsg.MERGE_TOO_MANY_DELETE, ctx.getCmd());
}
if(numWhenMatchedUpdateClauses > 1) {
throw new SemanticException(ErrorMsg.MERGE_TOO_MANY_UPDATE, ctx.getCmd());
}
}
if(numWhenMatchedDeleteClauses + numWhenMatchedUpdateClauses == 2 && extraPredicate == null) {
throw new SemanticException(ErrorMsg.MERGE_PREDIACTE_REQUIRED, ctx.getCmd());
}
handleCardinalityViolation(rewrittenQueryStr, target, onClauseAsText, targetTable);
ReparseResult rr = parseRewrittenQuery(rewrittenQueryStr, ctx.getCmd());
Context rewrittenCtx = rr.rewrittenCtx;
ASTNode rewrittenTree = rr.rewrittenTree;
//set dest name mapping on new context
for(int insClauseIdx = 1, whenClauseIdx = 0;
insClauseIdx < rewrittenTree.getChildCount() - 1/*skip cardinality violation clause*/;
insClauseIdx++, whenClauseIdx++) {
//we've added Insert clauses in order or WHEN items in whenClauses
ASTNode insertClause = (ASTNode) rewrittenTree.getChild(insClauseIdx);
switch (getWhenClauseOperation(whenClauses.get(whenClauseIdx)).getType()) {
case HiveParser.TOK_INSERT:
rewrittenCtx.addDestNamePrefix(insertClause, Context.DestClausePrefix.INSERT);
break;
case HiveParser.TOK_UPDATE:
rewrittenCtx.addDestNamePrefix(insertClause, Context.DestClausePrefix.UPDATE);
break;
case HiveParser.TOK_DELETE:
rewrittenCtx.addDestNamePrefix(insertClause, Context.DestClausePrefix.DELETE);
break;
default:
assert false;
}
}
try {
useSuper = true;
super.analyze(rewrittenTree, rewrittenCtx);
} finally {
useSuper = false;
}
updateOutputs(targetTable);
}
/**
* SemanticAnalyzer will generate a WriteEntity for the target table since it doesn't know/check
* if the read and write are of the same table in "insert ... select ....". Since DbTxnManager
* uses Read/WriteEntity objects to decide which locks to acquire, we get more concurrency if we
* have change the table WriteEntity to a set of partition WriteEntity objects based on
* ReadEntity objects computed for this table.
*/
private void updateOutputs(Table targetTable) {
markReadEntityForUpdate();
if(targetTable.isPartitioned()) {
List<ReadEntity> partitionsRead = getRestrictedPartitionSet(targetTable);
if(!partitionsRead.isEmpty()) {
//if there is WriteEntity with WriteType=UPDATE/DELETE for target table, replace it with
//WriteEntity for each partition
List<WriteEntity> toRemove = new ArrayList<>();
for(WriteEntity we : outputs) {
WriteEntity.WriteType wt = we.getWriteType();
if(isTargetTable(we, targetTable) &&
(wt == WriteEntity.WriteType.UPDATE || wt == WriteEntity.WriteType.DELETE)) {
/**
* The assumption here is that SemanticAnalyzer will will generate ReadEntity for each
* partition that exists and is matched by the WHERE clause (which may be all of them).
* Since we don't allow updating the value of a partition column, we know that we always
* write the same (or fewer) partitions than we read. Still, the write is a Dynamic
* Partition write - see HIVE-15032.
*/
toRemove.add(we);
}
}
outputs.removeAll(toRemove);
for(ReadEntity re : partitionsRead) {
for(WriteEntity original : toRemove) {
//since we may have both Update and Delete branches, Auth needs to know
WriteEntity we = new WriteEntity(re.getPartition(), original.getWriteType());
we.setDynamicPartitionWrite(original.isDynamicPartitionWrite());
outputs.add(we);
}
}
}
}
}
/**
* If the optimizer has determined that it only has to read some of the partitions of the
* target table to satisfy the query, then we know that the write side of update/delete
* (and update/delete parts of merge)
* can only write (at most) that set of partitions (since we currently don't allow updating
* partition (or bucket) columns). So we want to replace the table level
* WriteEntity in the outputs with WriteEntity for each of these partitions
* ToDo: see if this should be moved to SemanticAnalyzer itself since it applies to any
* insert which does a select against the same table. Then SemanticAnalyzer would also
* be able to not use DP for the Insert...
*
* Note that the Insert of Merge may be creating new partitions and writing to partitions
* which were not read (WHEN NOT MATCHED...). WriteEntity for that should be created
* in MoveTask (or some other task after the query is complete)
*/
private List<ReadEntity> getRestrictedPartitionSet(Table targetTable) {
List<ReadEntity> partitionsRead = new ArrayList<>();
for(ReadEntity re : inputs) {
if(re.isFromTopLevelQuery && re.getType() == Entity.Type.PARTITION && isTargetTable(re, targetTable)) {
partitionsRead.add(re);
}
}
return partitionsRead;
}
/**
* if there is no WHEN NOT MATCHED THEN INSERT, we don't outer join
*/
private String chooseJoinType(List<ASTNode> whenClauses) {
for(ASTNode whenClause : whenClauses) {
if(getWhenClauseOperation(whenClause).getType() == HiveParser.TOK_INSERT) {
return "RIGHT OUTER JOIN";
}
}
return "INNER JOIN";
}
/**
* does this Entity belong to target table (partition)
*/
private boolean isTargetTable(Entity entity, Table targetTable) {
//todo: https://issues.apache.org/jira/browse/HIVE-15048
/**
* is this the right way to compare? Should it just compare paths?
* equals() impl looks heavy weight
*/
return targetTable.equals(entity.getTable());
}
/**
* Per SQL Spec ISO/IEC 9075-2:2011(E) Section 14.2 under "General Rules" Item 6/Subitem a/Subitem 2/Subitem B,
* an error should be raised if > 1 row of "source" matches the same row in "target".
* This should not affect the runtime of the query as it's running in parallel with other
* branches of the multi-insert. It won't actually write any data to merge_tmp_table since the
* cardinality_violation() UDF throws an error whenever it's called killing the query
*/
private void handleCardinalityViolation(StringBuilder rewrittenQueryStr, ASTNode target,
String onClauseAsString, Table targetTable)
throws SemanticException {
if(!conf.getBoolVar(HiveConf.ConfVars.MERGE_CARDINALITY_VIOLATION_CHECK)) {
LOG.info("Merge statement cardinality violation check is disabled: " +
HiveConf.ConfVars.MERGE_CARDINALITY_VIOLATION_CHECK.varname);
return;
}
//this is a tmp table and thus Session scoped and acid requires SQL statement to be serial in a
// given session, i.e. the name can be fixed across all invocations
String tableName = "merge_tmp_table";
rewrittenQueryStr.append("\nINSERT INTO ").append(tableName)
.append("\n SELECT cardinality_violation(")
.append(getSimpleTableName(target)).append(".ROW__ID");
addPartitionColsToSelect(targetTable.getPartCols(), rewrittenQueryStr, target);
rewrittenQueryStr.append(")\n WHERE ").append(onClauseAsString)
.append(" GROUP BY ").append(getSimpleTableName(target)).append(".ROW__ID");
addPartitionColsToSelect(targetTable.getPartCols(), rewrittenQueryStr, target);
rewrittenQueryStr.append(" HAVING count(*) > 1");
//say table T has partiton p, we are generating
//select cardinality_violation(ROW_ID, p) WHERE ... GROUP BY ROW__ID, p
//the Group By args are passed to cardinality_violation to add the violating value to the error msg
try {
if (null == db.getTable(tableName, false)) {
StorageFormat format = new StorageFormat(conf);
format.processStorageFormat("TextFile");
Table table = db.newTable(tableName);
table.setSerializationLib(format.getSerde());
List<FieldSchema> fields = new ArrayList<FieldSchema>();
fields.add(new FieldSchema("val", "int", null));
table.setFields(fields);
table.setDataLocation(Warehouse.getDnsPath(new Path(SessionState.get().getTempTableSpace(),
tableName), conf));
table.getTTable().setTemporary(true);
table.setStoredAsSubDirectories(false);
table.setInputFormatClass(format.getInputFormat());
table.setOutputFormatClass(format.getOutputFormat());
db.createTable(table, true);
}
}
catch(HiveException|MetaException e) {
throw new SemanticException(e.getMessage(), e);
}
}
/**
* @param onClauseAsString - because there is no clone() and we need to use in multiple places
* @param deleteExtraPredicate - see notes at caller
*/
private String handleUpdate(ASTNode whenMatchedUpdateClause, StringBuilder rewrittenQueryStr,
ASTNode target, String onClauseAsString, Table targetTable,
String deleteExtraPredicate) throws SemanticException {
assert whenMatchedUpdateClause.getType() == HiveParser.TOK_MATCHED;
assert getWhenClauseOperation(whenMatchedUpdateClause).getType() == HiveParser.TOK_UPDATE;
String targetName = getSimpleTableName(target);
rewrittenQueryStr.append("INSERT INTO ").append(getFullTableNameForSQL(target));
addPartitionColsToInsert(targetTable.getPartCols(), rewrittenQueryStr);
rewrittenQueryStr.append(" -- update clause\n select ").append(targetName).append(".ROW__ID");
ASTNode setClause = (ASTNode)getWhenClauseOperation(whenMatchedUpdateClause).getChild(0);
//columns being updated -> update expressions; "setRCols" (last param) is null because we use actual expressions
//before reparsing, i.e. they are known to SemanticAnalyzer logic
Map<String, ASTNode> setColsExprs = collectSetColumnsAndExpressions(setClause, null, targetTable);
//if target table has cols c1,c2,c3 and p1 partition col and we had "SET c2 = 5, c1 = current_date()" we want to end up with
//insert into target (p1) select current_date(), 5, c3, p1 where ....
//since we take the RHS of set exactly as it was in Input, we don't need to deal with quoting/escaping column/table names
List<FieldSchema> nonPartCols = targetTable.getCols();
for(FieldSchema fs : nonPartCols) {
rewrittenQueryStr.append(", ");
String name = fs.getName();
if (setColsExprs.containsKey(name)) {
String rhsExp = getMatchedText(setColsExprs.get(name));
//"set a=5, b=8" - rhsExp picks up the next char (e.g. ',') from the token stream
switch (rhsExp.charAt(rhsExp.length() - 1)) {
case ',':
case '\n':
rhsExp = rhsExp.substring(0, rhsExp.length() - 1);
}
rewrittenQueryStr.append(rhsExp);
}
else {
rewrittenQueryStr.append(getSimpleTableName(target)).append(".").append(HiveUtils.unparseIdentifier(name, this.conf));
}
}
addPartitionColsToSelect(targetTable.getPartCols(), rewrittenQueryStr, target);
rewrittenQueryStr.append("\n WHERE ").append(onClauseAsString);
String extraPredicate = getWhenClausePredicate(whenMatchedUpdateClause);
if(extraPredicate != null) {
//we have WHEN MATCHED AND <boolean expr> THEN DELETE
rewrittenQueryStr.append(" AND ").append(extraPredicate);
}
if(deleteExtraPredicate != null) {
rewrittenQueryStr.append(" AND NOT(").append(deleteExtraPredicate).append(")");
}
rewrittenQueryStr.append("\n sort by ");
rewrittenQueryStr.append(targetName).append(".ROW__ID \n");
setUpAccessControlInfoForUpdate(targetTable, setColsExprs);
//we don't deal with columns on RHS of SET expression since the whole expr is part of the
//rewritten SQL statement and is thus handled by SemanticAnalzyer. Nor do we have to
//figure which cols on RHS are from source and which from target
return extraPredicate;
}
/**
* @param onClauseAsString - because there is no clone() and we need to use in multiple places
* @param updateExtraPredicate - see notes at caller
*/
private String handleDelete(ASTNode whenMatchedDeleteClause, StringBuilder rewrittenQueryStr, ASTNode target,
String onClauseAsString, Table targetTable, String updateExtraPredicate) throws SemanticException {
assert whenMatchedDeleteClause.getType() == HiveParser.TOK_MATCHED;
assert getWhenClauseOperation(whenMatchedDeleteClause).getType() == HiveParser.TOK_DELETE;
List<FieldSchema> partCols = targetTable.getPartCols();
String targetName = getSimpleTableName(target);
rewrittenQueryStr.append("INSERT INTO ").append(getFullTableNameForSQL(target));
addPartitionColsToInsert(partCols, rewrittenQueryStr);
rewrittenQueryStr.append(" -- delete clause\n select ").append(targetName).append(".ROW__ID ");
addPartitionColsToSelect(partCols, rewrittenQueryStr, target);
rewrittenQueryStr.append("\n WHERE ").append(onClauseAsString);
String extraPredicate = getWhenClausePredicate(whenMatchedDeleteClause);
if(extraPredicate != null) {
//we have WHEN MATCHED AND <boolean expr> THEN DELETE
rewrittenQueryStr.append(" AND ").append(extraPredicate);
}
if(updateExtraPredicate != null) {
rewrittenQueryStr.append(" AND NOT(").append(updateExtraPredicate).append(")");
}
rewrittenQueryStr.append("\n sort by ");
rewrittenQueryStr.append(targetName).append(".ROW__ID \n");
return extraPredicate;
}
private static String addParseInfo(ASTNode n) {
return " at " + ErrorMsg.renderPosition(n);
}
/**
* Returns the table name to use in the generated query preserving original quotes/escapes if any
* @see #getFullTableNameForSQL(ASTNode)
*/
private String getSimpleTableName(ASTNode n) throws SemanticException {
return HiveUtils.unparseIdentifier(getSimpleTableNameBase(n), this.conf);
}
private String getSimpleTableNameBase(ASTNode n) throws SemanticException {
switch (n.getType()) {
case HiveParser.TOK_TABREF:
int aliasIndex = findTabRefIdxs(n)[0];
if (aliasIndex != 0) {
return n.getChild(aliasIndex).getText();//the alias
}
return getSimpleTableNameBase((ASTNode) n.getChild(0));
case HiveParser.TOK_TABNAME:
if(n.getChildCount() == 2) {
//db.table -> return table
return n.getChild(1).getText();
}
return n.getChild(0).getText();
case HiveParser.TOK_SUBQUERY:
return n.getChild(1).getText();//the alias
default:
throw raiseWrongType("TOK_TABREF|TOK_TABNAME|TOK_SUBQUERY", n);
}
}
/**
* @return table name in db.table form with proper quoting/escaping to be used in a SQL statement
*/
private String getFullTableNameForSQL(ASTNode n) throws SemanticException {
switch (n.getType()) {
case HiveParser.TOK_TABNAME:
String[] tableName = getQualifiedTableName(n);
return getDotName(new String[] {
HiveUtils.unparseIdentifier(tableName[0], this.conf),
HiveUtils.unparseIdentifier(tableName[1], this.conf) });
case HiveParser.TOK_TABREF:
return getFullTableNameForSQL((ASTNode) n.getChild(0));
default:
throw raiseWrongType("TOK_TABNAME", n);
}
} private static final class ReparseResult {
private final ASTNode rewrittenTree;
private final Context rewrittenCtx;
ReparseResult(ASTNode n, Context c) {
rewrittenTree = n;
rewrittenCtx = c;
}
}
private static IllegalArgumentException raiseWrongType(String expectedTokName, ASTNode n) {
return new IllegalArgumentException("Expected " + expectedTokName + "; got " + n.getType());
}
private boolean isAliased(ASTNode n) {
switch (n.getType()) {
case HiveParser.TOK_TABREF:
return findTabRefIdxs(n)[0] != 0;
case HiveParser.TOK_TABNAME:
return false;
case HiveParser.TOK_SUBQUERY:
assert n.getChildCount() > 1 : "Expected Derived Table to be aliased";
return true;
default:
throw raiseWrongType("TOK_TABREF|TOK_TABNAME", n);
}
}
/**
* Collect WHEN clauses from Merge statement AST
*/
private List<ASTNode> findWhenClauses(ASTNode tree) throws SemanticException {
assert tree.getType() == HiveParser.TOK_MERGE;
List<ASTNode> whenClauses = new ArrayList<>();
for(int idx = 3; idx < tree.getChildCount(); idx++) {
ASTNode whenClause = (ASTNode)tree.getChild(idx);
assert whenClause.getType() == HiveParser.TOK_MATCHED ||
whenClause.getType() == HiveParser.TOK_NOT_MATCHED :
"Unexpected node type found: " + whenClause.getType() + addParseInfo(whenClause);
whenClauses.add(whenClause);
}
if(whenClauses.size() <= 0) {
//Futureproofing: the parser will actually not allow this
throw new SemanticException("Must have at least 1 WHEN clause in MERGE statement");
}
return whenClauses;
}
private ASTNode getWhenClauseOperation(ASTNode whenClause) {
if(!(whenClause.getType() == HiveParser.TOK_MATCHED || whenClause.getType() == HiveParser.TOK_NOT_MATCHED)) {
throw raiseWrongType("Expected TOK_MATCHED|TOK_NOT_MATCHED", whenClause);
}
return (ASTNode) whenClause.getChild(0);
}
/**
* returns the <boolean predicate> as in WHEN MATCHED AND <boolean predicate> THEN...
* @return may be null
*/
private String getWhenClausePredicate(ASTNode whenClause) {
if(!(whenClause.getType() == HiveParser.TOK_MATCHED || whenClause.getType() == HiveParser.TOK_NOT_MATCHED)) {
throw raiseWrongType("Expected TOK_MATCHED|TOK_NOT_MATCHED", whenClause);
}
if(whenClause.getChildCount() == 2) {
return getMatchedText((ASTNode)whenClause.getChild(1));
}
return null;
}
/**
* Generates the Insert leg of the multi-insert SQL to represent WHEN NOT MATCHED THEN INSERT clause
* @param targetTableNameInSourceQuery - simple name/alias
* @throws SemanticException
*/
private void handleInsert(ASTNode whenNotMatchedClause, StringBuilder rewrittenQueryStr, ASTNode target,
ASTNode onClause, Table targetTable,
String targetTableNameInSourceQuery, String onClauseAsString) throws SemanticException {
assert whenNotMatchedClause.getType() == HiveParser.TOK_NOT_MATCHED;
assert getWhenClauseOperation(whenNotMatchedClause).getType() == HiveParser.TOK_INSERT;
List<FieldSchema> partCols = targetTable.getPartCols();
String valuesClause = getMatchedText((ASTNode)getWhenClauseOperation(whenNotMatchedClause).getChild(0));
valuesClause = valuesClause.substring(1, valuesClause.length() - 1);//strip '(' and ')'
rewrittenQueryStr.append("INSERT INTO ").append(getFullTableNameForSQL(target));
addPartitionColsToInsert(partCols, rewrittenQueryStr);
OnClauseAnalyzer oca = new OnClauseAnalyzer(onClause, targetTable, targetTableNameInSourceQuery,
conf, onClauseAsString);
oca.analyze();
rewrittenQueryStr.append(" -- insert clause\n select ")
.append(valuesClause).append("\n WHERE ").append(oca.getPredicate());
String extraPredicate = getWhenClausePredicate(whenNotMatchedClause);
if(extraPredicate != null) {
//we have WHEN NOT MATCHED AND <boolean expr> THEN INSERT
rewrittenQueryStr.append(" AND ")
.append(getMatchedText(((ASTNode)whenNotMatchedClause.getChild(1)))).append('\n');
}
}
/**
* Suppose the input Merge statement has ON target.a = source.b and c = d. Assume, that 'c' is from
* target table and 'd' is from source expression. In order to properly
* generate the Insert for WHEN NOT MATCHED THEN INSERT, we need to make sure that the Where
* clause of this Insert contains "target.a is null and target.c is null" This ensures that this
* Insert leg does not receive any rows that are processed by Insert corresponding to
* WHEN MATCHED THEN ... clauses. (Implicit in this is a mini resolver that figures out if an
* unqualified column is part of the target table. We can get away with this simple logic because
* we know that target is always a table (as opposed to some derived table).
* The job of this class is to generate this predicate.
*
* Note that is this predicate cannot simply be NOT(on-clause-expr). IF on-clause-expr evaluates
* to Unknown, it will be treated as False in the WHEN MATCHED Inserts but NOT(Unknown) = Unknown,
* and so it will be False for WHEN NOT MATCHED Insert...
*/
private static final class OnClauseAnalyzer {
private final ASTNode onClause;
private final Map<String, List<String>> table2column = new HashMap<>();
private final List<String> unresolvedColumns = new ArrayList<>();
private final List<FieldSchema> allTargetTableColumns = new ArrayList<>();
private final Set<String> tableNamesFound = new HashSet<>();
private final String targetTableNameInSourceQuery;
private final HiveConf conf;
private final String onClauseAsString;
/**
* @param targetTableNameInSourceQuery alias or simple name
*/
OnClauseAnalyzer(ASTNode onClause, Table targetTable, String targetTableNameInSourceQuery,
HiveConf conf, String onClauseAsString) {
this.onClause = onClause;
allTargetTableColumns.addAll(targetTable.getCols());
allTargetTableColumns.addAll(targetTable.getPartCols());
this.targetTableNameInSourceQuery = unescapeIdentifier(targetTableNameInSourceQuery);
this.conf = conf;
this.onClauseAsString = onClauseAsString;
}
/**
* finds all columns and groups by table ref (if there is one)
*/
private void visit(ASTNode n) {
if(n.getType() == HiveParser.TOK_TABLE_OR_COL) {
ASTNode parent = (ASTNode) n.getParent();
if(parent != null && parent.getType() == HiveParser.DOT) {
//the ref must be a table, so look for column name as right child of DOT
if(parent.getParent() != null && parent.getParent().getType() == HiveParser.DOT) {
//I don't think this can happen... but just in case
throw new IllegalArgumentException("Found unexpected db.table.col reference in " + onClauseAsString);
}
addColumn2Table(n.getChild(0).getText(), parent.getChild(1).getText());
}
else {
//must be just a column name
unresolvedColumns.add(n.getChild(0).getText());
}
}
if(n.getChildCount() == 0) {
return;
}
for(Node child : n.getChildren()) {
visit((ASTNode)child);
}
}
private void analyze() {
visit(onClause);
if(tableNamesFound.size() > 2) {
throw new IllegalArgumentException("Found > 2 table refs in ON clause. Found " +
tableNamesFound + " in " + onClauseAsString);
}
handleUnresolvedColumns();
if(tableNamesFound.size() > 2) {
throw new IllegalArgumentException("Found > 2 table refs in ON clause (incl unresolved). " +
"Found " + tableNamesFound + " in " + onClauseAsString);
}
}
/**
* Find those that belong to target table
*/
private void handleUnresolvedColumns() {
if(unresolvedColumns.isEmpty()) { return; }
for(String c : unresolvedColumns) {
for(FieldSchema fs : allTargetTableColumns) {
if(c.equalsIgnoreCase(fs.getName())) {
//c belongs to target table; strictly speaking there maybe an ambiguous ref but
//this will be caught later when multi-insert is parsed
addColumn2Table(targetTableNameInSourceQuery.toLowerCase(), c);
break;
}
}
}
}
private void addColumn2Table(String tableName, String columnName) {
tableName = tableName.toLowerCase();//normalize name for mapping
tableNamesFound.add(tableName);
List<String> cols = table2column.get(tableName);
if(cols == null) {
cols = new ArrayList<>();
table2column.put(tableName, cols);
}
//we want to preserve 'columnName' as it was in original input query so that rewrite
//looks as much as possible like original query
cols.add(columnName);
}
/**
* Now generate the predicate for Where clause
*/
private String getPredicate() {
//normilize table name for mapping
List<String> targetCols = table2column.get(targetTableNameInSourceQuery.toLowerCase());
StringBuilder sb = new StringBuilder();
for(String col : targetCols) {
if(sb.length() > 0) {
sb.append(" AND ");
}
//but preserve table name in SQL
sb.append(HiveUtils.unparseIdentifier(targetTableNameInSourceQuery, conf)).append(".").append(HiveUtils.unparseIdentifier(col, conf)).append(" IS NULL");
}
return sb.toString();
}
}
}
| [
"archen94@gmail.com"
] | archen94@gmail.com |
4eecccaf93bc787f2e1d585eae2188f615902d28 | 0702b4be1e8bfec91df54c347a7a0ef8898b9495 | /bytebank-herdado-conta/src/Conta.java | cd7309e7cd116cdb1b3e4c5308b1f6987dbf4c78 | [
"MIT"
] | permissive | ericafslaurenti/ProjetosAlura_Java | 7d2669e0858dfb62a068a0cb9361418fa176ca0c | 8cbd1edcf4002d2d855ea73e3310cae44eaa6254 | refs/heads/main | 2023-05-14T12:08:50.440777 | 2021-06-09T02:13:45 | 2021-06-09T02:13:45 | 367,885,276 | 1 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 3,127 | java | //private: a partir do momento que um atributo é privado, ele n pode ser lido, modificado por ninguém a n ser a própria classe
//protected: deixa público apenas para os filhos
public abstract class Conta {
protected double saldo;
private int agencia;
private int numero;
private Cliente titular; // o tipo titular deixa de ser uma String e passa a ser tipo cliente. o lado esq precisar ser o nome da variável
private static int total = 0;
//construtor padrão
// public Conta() {
//
// }
//construtor específico que foi criado
public Conta(int agencia, int numero) {//p/ invocá-lo obrigatoriamente tenho q informar a agencia e o nº da conta
Conta.total++;
//System.out.println("o total de contas é " + Conta.total);
this.agencia = agencia;
this.numero = numero;
//this.saldo = 100;
//System.out.println("Estou criando uma conta" + this.numero);
}
public abstract void deposita(double valor);
public boolean saca(double valor) {
if(this.saldo >= valor){ //se o saldo dessa conta for >= ao valor, eu retiro
this.saldo -= valor; //saldo será o saldo - o valor sacado
return true; //retorn palavra chave do Java q para a execução daquele método e volta p/ quem estava chamando e retorna o valor
} else {
return false;
}
}
public boolean transfere(double valor, Conta destino) {
if(this.saca(valor)) {
destino.deposita(valor);
return true;
} else {
return false;
}
}
//cria um método de devolve o saldo, já que le está private
public double getSaldo( ) {//public q devolve um double, q pega um saldo e n recebe nada()
return this.saldo;
}
//metodo para acessar a conta e devolver o nº dela
public int getNumero() {
return this.numero;
}
//metodo q altera o nº da conta
public void setNumero(int numero) {//tem q passar o parametro entre os parenteses.Métodos q alteram o atributo normalmente são void, alteram e n devolvem nada.
if(numero <= 0) {
System.out.println("Não pode valor <= 0");
return;
}
this.numero = numero;//nº dessa conta recebe(=) o novo nº p/ essa conta(parametro)
}
public int getAgencia() {
return this.agencia;
}
public void setAgencia(int agencia) {
if(agencia <= 0) { //se o valor ag <=0
System.out.println("Não pode valor menor igual a 0");
return; //pára a execução
}
this.agencia = agencia;
}
public void setTitular(Cliente titular) {
this.titular = titular;
}
public Cliente getTitular() {
return titular;
}
public static int getTotal() {
return Conta.total;
}
}
//void deposita(double valor)=> no () add q está sendo recebido pelo método, um parametro
//tem q especificar a variavel (valor) e o tipo (double)
//void Depois de depositar um valor na conta bancária, poderemos receber uma msg, nº ou comprovante. Nesse caso, como não existe qualquer tipo de retorno ao acionarmos um método, utilizamos a palavra-chave void.
//void deposita é q ele recebe - (double valor)é o q ele devolve
//this.saldo = this.saldo + valor; é o mesmo que: this.saldo += valor; soma o valor a ele mesmo, assim como o -= tira o valor dele mesmo | [
"ericafs.laurenti@gmail.com"
] | ericafs.laurenti@gmail.com |
cf04440a4ab7a72ef89282937a78bdc552c4645c | 37862e5dd860214d82a1ad6f8e21d4dde4e3cbcd | /src/main/java/turn/key/context/initialize/RestInitialize.java | 63de54a808b5e7f35485992517f5c0814785a544 | [] | no_license | keithkreissl/turn-key-webapp | d7df1d3b625f6d7b09c4c9bea3846dbdba5426b8 | 9fc38dd74b6901459b0cba9d436caef96d362db0 | refs/heads/master | 2021-01-25T10:43:48.099095 | 2015-04-06T16:04:52 | 2015-04-06T16:04:52 | 32,119,577 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 356 | java | package turn.key.context.initialize;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
@ApplicationPath("/rest")
public class RestInitialize extends ResourceConfig {
public RestInitialize(){
packages("turn.key.rest");
register(JacksonFeature.class);
}
}
| [
"kkreissl@cars.com"
] | kkreissl@cars.com |
0497050cfb6275c787169ee0eacba64d8ecd62e6 | 6ed06666810e0756dbc82ad4fe75ae3c6d512d53 | /src/main/java/br/com/bookstore/purchase/purchase/services/DeletePurchaseService.java | 779d0edbbc7f1c8b78ea60c3357d64becbe0cf71 | [
"MIT"
] | permissive | ayty-org/purchase-bookstore-microservice | e694c543178925578e7d10eec5218f24c343a9b6 | 50371c9d12e10ad8e82d9d27767c507f564ff376 | refs/heads/main | 2023-03-17T06:46:51.774326 | 2021-03-12T19:05:14 | 2021-03-12T19:05:14 | 343,879,694 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 144 | java | package br.com.bookstore.purchase.purchase.services;
@FunctionalInterface
public interface DeletePurchaseService {
void delete(Long id);
}
| [
"josinaldo.pontes@dcx.ufpb.br"
] | josinaldo.pontes@dcx.ufpb.br |
9343d14fcae7d5d836ad78203f5a398e332666a1 | 787da0bed0c1e06e990337027cb67768a4f7f943 | /spring-monitor/src/main/java/com/lyloou/component/monitor/ApplicationContextHelper.java | cde0781ae1c25e7198ce651512563722659750a7 | [] | no_license | lyloou/spring-monitor-parent | 4baf10b59de0e6e09c9583ca7d108a5bd89b89c4 | 2414de5a41991dad4ff60294ea68ffa557b108ab | refs/heads/master | 2023-05-30T22:12:36.826519 | 2021-04-28T09:30:55 | 2021-04-28T09:30:55 | 344,722,097 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,331 | java | package com.lyloou.component.monitor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
ApplicationContextHelper.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> targetClz) {
return applicationContext.getBean(targetClz);
}
public static Object getBean(String claz) {
return ApplicationContextHelper.applicationContext.getBean(claz);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return ApplicationContextHelper.applicationContext.getBean(name, requiredType);
}
public static <T> T getBean(Class<T> requiredType, Object... params) {
return ApplicationContextHelper.applicationContext.getBean(requiredType, params);
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
| [
"lilou@coocaa.com"
] | lilou@coocaa.com |
fbc7d2dec55e44464dcdfc980ebd9fd277d4082c | 0c280567a4b9a3331e9759da936eac726a513a4a | /Circle Analysis/Project1.java | bbe80a7c8859cbe43108e2a7b769ea765773e730 | [] | no_license | yakovsushenok/Java-Projects | f0faecacaa9efa067ef12bb07ae19368c5a0dba9 | e98d2d804c1650780edbf197ab7ee51fe3c1af63 | refs/heads/master | 2022-11-26T19:05:04.802309 | 2020-08-04T15:42:26 | 2020-08-04T15:42:26 | 242,352,310 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,144 | java | import java.util.Scanner;
import java.io.*;
/*
* PROJECT I: Project1.java
*
* As in project 0, this file - and the others you downloaded - form a
* template which should be modified to be fully functional.
*
* This file is the *last* file you should implement, as it depends on both
* Point and Circle. Thus your tasks are to:
*
* 1) Make sure you have carefully read the project formulation. It contains
* the descriptions of all of the functions and variables below.
* 2) Write the class Point.
* 3) Write the class Circle
* 4) Write this class, Project1. The Results() method will perform the tasks
* laid out in the project formulation.
*/
public class Project1 {
// -----------------------------------------------------------------------
// Do not modify the names of the variables below! This is where you will
// store the results generated in the Results() function.
// -----------------------------------------------------------------------
public int circleCounter; // Number of non-singular circles in the file.
public int envelopsFirstLast; //The result of the first circle enveloping the last circle in the file.
public double maxArea; // Area of the largest circle (by area).
public double minArea; // Area of the smallest circle (by area).
public double averageArea; // Average area of the circles.
public double stdArea; // Standard deviation of area of the circles.
public double medArea; // Median of the area.
public int stamp=472148;
// -----------------------------------------------------------------------
// You may implement - but *not* change the names or parameters of - the
// functions below.
// -----------------------------------------------------------------------
/**
* Default constructor for Project1. You should leave it empty.
*/
public Project1() {
// This method is complete.
}
/**
* Results function. It should open the file called FileName (using
* Scanner), and from it generate the statistics outlined in the project
* formulation. These are then placed in the instance variables above.
*
* @param fileName The name of the file containing the circle data.
*/
public void results(String fileName){
// You need to fill in this method.
double x1,y1,rad1,x2,y2,rad2; // I created two copies of variables and initialized them here so I can use them in two scans
// The first scan will be with the aim of calculating the number of circles, and the second one would be for creating an array of circles
int numberOfCircles = 0;
try {
Scanner s = new Scanner(new BufferedReader(new FileReader(fileName))); /*Here, just as in the ReadData class(example you
provided), we read the file with scanner. Note that on your computer the file path/location may be different from mine, so please make sure
when you compile it has the correct path*/
while(s.hasNext()) {
x1 = s.nextDouble(); // This will ensure that the first value scanned from the file is an x-coordinate(and every third value after that,
y1 = s.nextDouble(); //so 1st,4th,7th etc.) and the same way for y-coordinate, and radius)
rad1 = s.nextDouble();
if(rad1 > Point.GEOMTOL) { //This ensures that the circles we "accept" are well defined. i.e radius>0. For this, we use Geomtol from ->
numberOfCircles++; // class Point
}
}
}
catch(Exception e) {
System.err.println("An error has occured."); // This handles scanner error, if there are any
e.printStackTrace();
}
int m = numberOfCircles; // parameter m is the value of the number of well defined circles in project1.data
//The fact that we know the number of circles lets us create a new array of circles, which would be of length m
Circle[] circles = new Circle[m]; // This is our new array of circles with length m
int j = 0;
try {
Scanner s = new Scanner(new BufferedReader(new FileReader(fileName))); //Opening file again
while(s.hasNext()) {
x2 = s.nextDouble(); // Now we assign these values to a new circle in while loop.
y2 = s.nextDouble();
rad2 = s.nextDouble(); // These assign values to a new circle in while loop
if(rad2 > Point.GEOMTOL) { // This ensure that we'll be dealing with only well-defined circle (radius>0)
circles[j] = new Circle(x2, y2, rad2);
j++;
} //this creates m well defined circles in array
}
} catch(Exception e) {
System.err.println("An error has occured."); //making sure that we catch any errors
e.printStackTrace();
}
//In the lines below I assign values to the corresponding results
circleCounter = m;
envelopsFirstLast= circleEnvelopsFirstLast(circles);
maxArea = MaxAreaOfCircles(circles);
minArea = MinAreaOfCircles(circles);
averageArea = averageArea(circles);
stdArea = areaStandardDeviation(circles);
medArea = MedianAreaOfCircles(circles);
}
/**
* A function to calculate the avarage area of circles in the array provided.
*
* @param circles An array if Circles
*/
public double averageArea(Circle[] circles) { //This method will be dealing with array of circles, so it accepts an array of circles
// You need to fill in this method
double sumOfAreas = 0;
for (int j = 0; j < circles.length; j++) { // Iterates through all circles in the array, and sums their areas.
sumOfAreas += circles[j].area(); // This will sum all of the circle areas of the circle array
}
return sumOfAreas / circles.length; // Returns value of average area in the circles array
}
// The method below calculates the maximum area of a circle in the circles array
public double MaxAreaOfCircles(Circle[] circles) { // This method will be dealing with circles array as it's input parameter
double max = Double.MIN_VALUE; //Initializing our variable MAX to be the smallest double value a number can be, so then ->
// we can work with it in the loop conveniently maximizing it through every iteration which has a greater value of area than the previous->
//iteration
for (int j = 0; j < circles.length; j++) { // iterates through array to find maximum area
if (circles[j].area() > max) { // Here I use the area method from the Circle class
max = circles[j].area();
}
}
return max;
} //Return the maximum area of a circle in the circles array
// The method below calculates the minimum area of a circle in the circles array
public double MinAreaOfCircles(Circle[] circles) { // This method will be dealing with circles array as it's input parameter
double min = Double.MAX_VALUE; // Same way as in MaxAreaOfCircles but the opposite
for (int j = 0; j < circles.length; j++) { // similar to max function
if (circles[j].area() < min) {
min = circles[j].area();
}
}
return min; //Return the maximum area of a circle in the circles array
}
// The method below shows the digit value of the envelops method applied to the first and last circle of the circle array
public int circleEnvelopsFirstLast(Circle[] circles) { // This method will be dealing with circles array as it's input parameter
int envelop = circles[0].envelops(circles[circles.length - 1]);
// Uses envelops from circle class and compares 1st and last circle in the array
return envelop; //returns an integer as described in circle class.
}
/**
* A function to calculate the standart deviation of areas in the circles in the array provided.
*
* @param circles An array of Circles
*/
public double areaStandardDeviation(Circle[] circles) { // This method will be dealing with circles array as it's input parameter
//You need to complete this method.
double sumOfAreasSqaured = 0;
for (int j = 0; j < circles.length; j++) {
sumOfAreasSqaured += Math.pow(circles[j].area(), 2); // Mathematically this represents a summation series of squared circle areas ->
} //in the circles array
double squaredAreasAverage = Math.pow(averageArea(circles), 2); //squaredAreasAverage is the value of the average area ->
//(which is computed in a method above) squared
double standardDeviation = Math.sqrt((sumOfAreasSqaured / circles.length) - squaredAreasAverage); // This is the standard deviation formula
return standardDeviation;
}
// Below is a method which, as shown in the lecture notes, will sort the values in an array from min to max. The method will be implemented->
// in the MedianAreaOfCicles method below
public void bubbleSort(double[] arr) {
boolean doneSwap = true;
while (doneSwap) {
doneSwap = false;
for (int j = 0; j < arr.length-1; j++) {
if (arr[j+1] < arr[j]) {
double tmp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = tmp;
doneSwap = true;
}
}
}
}
//This method accepts an array of circles, sorts its values from min to max, and then proceeds to calculate the median of the areas of the array
public double MedianAreaOfCircles (Circle[] circles) { // This method will be dealing with circles array as it's input parameter
double[] areasArray = new double[circles.length];
for (int i = 0; i < circles.length; i++) {
areasArray[i] = circles[i].area(); // This will create an array of the circles' areas
}
bubbleSort(areasArray); // This method sorts the array of areas from smallest area to greatest area
int a = areasArray.length;
//Now that we have sorted the areas Array, we can set the median formula accordingly
if (a%2==1) {
double median = areasArray[(a-1)/2];
return median; // The if condition here serves as a check if the array is of odd or even number of elements, since the median ->
} //formula would be different for each case
else {
double median = ((areasArray[a/2 - 1] + areasArray[a/2]) / 2);
return median;
}
}
// =======================================================
// Tester - tests methods defined in this class
// =======================================================
/**
* Your tester function should go here (see week 14 lecture notes if
* you're confused). It is not tested by BOSS, but you will receive extra
* credit if it is implemented in a sensible fashion.
*/
public static void main(String args[]){
// You need to fill in this method.
Project1 project = new Project1(); // Creating an object "project" of "project1" Class
project.results("Project1.data"); // This opens the file and reads it with scanner
System.out.println();
System.out.println("Testing Project's 1 results");
System.out.println();
// The lines below will show the output of my tests
System.out.println("Number of well defined circles in file project1: "+ project.circleCounter);
System.out.println("Result of envelops method of first and last well defined circles in file: "+project.envelopsFirstLast);
System.out.println("Maximum area a circle attains in the file: " +project.maxArea);
System.out.println("Minimum area a circle attains in the file: " +project.minArea);
System.out.println("Average area of the circles in the file: " +project.averageArea);
System.out.println("Standard deviation of the circles in the file: " +project.stdArea);
System.out.println("Median area of the circles in the file: " +project.medArea);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
123060e63b8b090e92efc4e1d9af901fe4a78700 | 92af6d39a7e085b73f80981308c8d3a64702a230 | /src/main/java/com/en/rule/engine/constants/JsonConstants.java | c95a7390b24d00cf12ba13e711d1835d251be257 | [
"Apache-2.0"
] | permissive | Sumankumar16/rule-engine | 5c7cac0797b114e73e06b7e2bc21c5cce8f792d2 | dcd9fbd198c20290398706bbf5f5c938fdefe7a4 | refs/heads/master | 2020-03-23T16:32:14.987342 | 2018-08-12T10:22:00 | 2018-08-12T10:22:00 | 141,816,031 | 4 | 1 | null | 2018-07-31T17:45:25 | 2018-07-21T13:34:34 | Java | UTF-8 | Java | false | false | 637 | java | package com.en.rule.engine.constants;
/**
* @author Suman Kumar
*
*/
public final class JsonConstants {
public static final String SIGNAL = "signal";
public static final String VALUE_TYPE = "value_type";
public static final String VALUE = "value";
public static final String LOWER_BOUNDRY_OF_DATE = "lower_boundry_of_date";
public static final String UPPER_BOUNDRY_OF_DATE = "upper_boundry_of_date";
public static final String LOWER_BOUNDRY_OF_INT = "lower_boundry_of_int";
public static final String UPPER_BOUNDRY_OF_INT = "upper_boundry_of_int";
public static final String STRING_VALUE_TYPE = "string_value_type";
} | [
"suman.kumar@tandf.co.uk"
] | suman.kumar@tandf.co.uk |
cd34dfd36897c7db468f23a9b7f7bd3356783057 | 61823128df4d3add16578babf6ccc4804fb37027 | /5/da/src/main/java/hello/User.java | a256e399f097a614fefcd463cba70bbe7f49c4a6 | [] | no_license | amangoyal22/Assignment | a1dd3a62c2d3b45251220d6d2e62e05b47d7be45 | f80a5cf0a110d64a176f9da6405f58c66c56d37c | refs/heads/master | 2020-04-09T19:58:13.865561 | 2019-01-12T01:59:07 | 2019-01-12T01:59:07 | 160,559,180 | 0 | 0 | null | 2018-12-06T19:48:14 | 2018-12-05T18:11:03 | Java | UTF-8 | Java | false | false | 1,104 | java | package hello;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.sql.Date;
import java.sql.Time;
@Entity // This tells Hibernate to make a table out of this class
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private Time t;
public Time getT() {
return t;
}
public void setT(Time t) {
this.t = t;
}
private Date d;
public Date getD() {
return d;
}
public void setD(Date d) {
this.d = d;
}
private String phone;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| [
"aman.goyalwd@gmail.com"
] | aman.goyalwd@gmail.com |
899231de38e42aa8143f5931c527e48b6c263f66 | 8137ded4cdbc8869ec7e74ae802f68f2f2a50291 | /app/src/main/java/com/example/movieadda/Model/ForBookmark.java | 6177f9291a2c9acc147f3442593c337dd9e61d9d | [] | no_license | Bhupendrapatel98/MoviesAdda | 60d8184f4df444dd7eeb050c437adcb6e6d92c72 | e2c46b61ecc54e9bbddf1daa3f3119e546c0923f | refs/heads/master | 2021-01-15T00:50:58.376587 | 2020-04-09T12:15:10 | 2020-04-09T12:15:10 | 242,818,887 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,104 | java | package com.example.movieadda.Model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import com.example.movieadda.Room.typeconverter.MTvConverter;
import com.example.movieadda.utils.Type;
@Entity(foreignKeys = @ForeignKey(entity = InfoModel.class,
parentColumns = "movie_id",
childColumns = "minfo",
onDelete = ForeignKey.CASCADE))
@TypeConverters({MTvConverter.class})
public class ForBookmark {
@PrimaryKey(autoGenerate = true)
int mid;
Long minfo;
Type.MovTv type;
public ForBookmark(Long minfo, Type.MovTv type) {
this.minfo = minfo;
this.type = type;
}
public Type.MovTv getType() {
return type;
}
public void setType(Type.MovTv type) {
this.type = type;
}
public int getMid() {
return mid;
}
public void setMid(int mid) {
this.mid = mid;
}
public Long getMinfo() {
return minfo;
}
public void setMinfo(Long minfo) {
this.minfo = minfo;
}
}
| [
"bhupendrapatel.bp57@gmail.com"
] | bhupendrapatel.bp57@gmail.com |
4f4a01dd4ecbd9a4cc852329e3775f83887e907a | 7e6b8f8ab246298c55ad5dbca27366161b8c6cf6 | /src/main/gen-src/org/dmtf/schemas/wbem/wsman/_1/wsman/SelectorType.java | e8f06f74bc56007f2eee3cfb5b23ce969352f238 | [
"Apache-2.0"
] | permissive | RackHD/smi-lib-wiseman | a5488e4832e5c3f8b32105fdfe6009e3d0119059 | 15bf6c88bac8e91900cf68673c7ef0c199c4eda9 | refs/heads/master | 2021-01-01T16:02:47.064043 | 2018-07-16T07:36:06 | 2018-07-16T07:36:06 | 97,762,907 | 0 | 4 | Apache-2.0 | 2018-07-16T07:32:48 | 2017-07-19T21:30:48 | Java | UTF-8 | Java | false | false | 4,400 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-382
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2007.05.29 at 01:59:34 PM EDT
//
package org.dmtf.schemas.wbem.wsman._1.wsman;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
import org.xmlsoap.schemas.ws._2004._08.addressing.EndpointReferenceType;
/**
*
* Instances of this type can be only simple types or EPRs, not arbitrary mixed data.
*
*
* <p>
* Java class for SelectorType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SelectorType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://schemas.xmlsoap.org/ws/2004/08/addressing}EndpointReference" minOccurs="0"/>
* </sequence>
* <attribute name="Name" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SelectorType", propOrder = { "content" })
public class SelectorType {
@XmlElementRef(name = "EndpointReference", namespace = "http://schemas.xmlsoap.org/ws/2004/08/addressing", type = JAXBElement.class)
@XmlMixed
protected List<Serializable> content;
@XmlAttribute(name = "Name", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NCName")
protected String name;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
*
* Instances of this type can be only simple types or EPRs, not arbitrary mixed data. Gets the value of the content property.
*
* <p>
* This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the content property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list {@link JAXBElement }{@code <}{@link EndpointReferenceType }{@code >} {@link String }
*
*
*/
public List<Serializable> getContent() {
if (content == null) {
content = new ArrayList<Serializable>();
}
return this.content;
}
/**
* Gets the value of the name property.
*
* @return possible object is {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value allowed object is {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute by updating the map directly. Because of this design, there's no setter.
*
*
* @return always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
| [
"Michael_Hepfer@dell.com"
] | Michael_Hepfer@dell.com |
25d60b9edb0e31f36e0a507881b71d35a7b4fc7a | e923382bd3778f98db665e9db741603ce668a19e | /test/java/classtest/proxy/DynamicProxyHandler.java | e9485c5bdc1a29b0159a3d31409ff37ae6ce11e1 | [] | no_license | chengbaobao630/mytest | 4fef56ef905f598e2a380debcea7842886c42973 | 9a29e494313860ed9b3efab3ae1b12162a38fe72 | refs/heads/master | 2021-01-01T05:26:13.165768 | 2016-05-02T09:43:50 | 2016-05-02T09:43:50 | 56,248,913 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,193 | java | package classtest.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by cheng on 2016/4/7 0007.
*/
public class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
public DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("***** proxy: "+proxy.getClass()+
",method: "+method+",args: "+args);
if(args!=null)
for(Object o:args){
System.out.println(o);
}
return method.invoke(proxied,args);
}
}
class SimpleDynamicProxy{
public static void consumer(Interfcae iface){
iface.doSomething();
iface.somethingElse("bonobo");
}
public static void main(String[] args){
RealObject realObject=new RealObject();
consumer(realObject);
Interfcae proxy= (Interfcae) Proxy.newProxyInstance(Interfcae.class.getClassLoader(),new Class[]{Interfcae.class},new DynamicProxyHandler(realObject));
consumer(proxy);
}
}
| [
"chengbaobao630@hotmail.com"
] | chengbaobao630@hotmail.com |
7bf1033ef1c8424bf8b6a9afa16a88b949889121 | e245541e3f2cb5f3fbfbe8d374db2ae777b29bed | /src/main/java/com/upc/service/UserNodeService.java | 3dbedeebcbd65a08633c6a969984bf70d1dd3b32 | [] | no_license | bin9450/GuideBuy | 139bd9becaede60de12c3599198de0734d6235cd | c33b90bdaf9bea6db96dfda1466c2dd899b3af70 | refs/heads/master | 2022-12-01T16:02:20.178110 | 2019-11-06T10:04:10 | 2019-11-06T10:04:10 | 181,823,837 | 5 | 0 | null | 2022-11-16T11:47:47 | 2019-04-17T05:36:05 | CSS | UTF-8 | Java | false | false | 1,398 | java | package com.upc.service;
import com.upc.domain.node.UserNode;
import com.upc.repository.UserNodeRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
/**
* @Author: Pan
* @Date: 2019/4/11 17:30
* @Description:
**/
@Service
public class UserNodeService {
private final UserNodeRepository userNodeRepository;
public UserNodeService(UserNodeRepository userNodeRepository) {
this.userNodeRepository = userNodeRepository;
}
@Transactional(readOnly = true)
public UserNode findByNickName(String nickName){
UserNode result = userNodeRepository.findByNickName(nickName);
return result;
}
@Transactional(readOnly = true)
public Collection<UserNode> findByNickNameLike(String nickName){
Collection<UserNode> result = userNodeRepository.findByNickNameLike(nickName);
return result;
}
@Transactional(readOnly = true)
public UserNode findByUserId(int userId){
UserNode userNode = userNodeRepository.findByUserId(userId);
return userNode;
}
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void createUserNode(int userId,String nickName){
userNodeRepository.createUserNode(userId,nickName);
}
}
| [
"945023912@qq.com"
] | 945023912@qq.com |
c408ba3bad391d908ccab8f2d5107408e87bac57 | b0d6720b6b79fb6db91aea9ff7fb3e044a00f8fa | /creditcard/src/main/java/com/zyyh/CreditCardSystem.java | ebe5a04312a59790fe8bcdccd860e7dc0e05e02e | [] | no_license | shilinice0813/UnitTestOne | 35b1d5b0648aac516e073bb1bec356ea5b3afff4 | 0436b6d70c3dc7b1d2528465e4ad6bfc0b4963e8 | refs/heads/master | 2023-02-04T21:39:12.843328 | 2020-12-24T08:39:35 | 2020-12-24T08:39:35 | 272,366,379 | 2 | 0 | null | 2020-12-24T07:58:07 | 2020-06-15T07:06:03 | Java | UTF-8 | Java | false | false | 940 | java | package com.zyyh;
import java.util.ArrayList;
import java.util.List;
public class CreditCardSystem {
public List<User> clients=new ArrayList<>();
public void addUser(User user){
clients.add(user);
}
public void removeUser(User user){
clients.remove(user);
}
public void printRecord(User user) {
System.out.println("总分:"+user.getTotalPoint());
for (PayInfo info :user.getPayInfoList() ) {
System.out.println(info.getDateTime()+" "+info.getPayStyleInfo()+info.getPayAmount()+",积分+"+info.getPoint());
}
}
public void printRecordHtml(User user) {
System.out.println("<h2>总分:<b>"+user.getTotalPoint()+"</b></h2>");
for (PayInfo info :user.getPayInfoList() ) {
System.out.println("<p>"+info.getDateTime()+" "+info.getPayStyleInfo()+info.getPayAmount()+",积分<b>+"+info.getPoint()+"</b></p>");
}
}
}
| [
"shilinb@outlook.com"
] | shilinb@outlook.com |
ee318cc921ec47f886a8fec6dc3eb346d76a1615 | 270c8933b7eb032db15f5127ebbdf3420c0c4662 | /grape-rocketmq/grape-rocketmq-producer/src/main/java/com/delicacy/grape/rocketmq/producer/rocket/RocketmqSender.java | 64ea7bce4fcfe163b85f1f263794a7bc166bdee7 | [] | no_license | mozovw/delicacy-grape | c673869e6b2269ea583f091af0f2bb02075bfc2f | 5209a6dc109030b5c72f34c76f625d0ac3420688 | refs/heads/master | 2022-11-22T09:21:59.156451 | 2021-06-26T07:04:21 | 2021-06-26T07:04:21 | 134,239,519 | 8 | 8 | null | 2022-11-16T11:57:06 | 2018-05-21T08:17:33 | Java | UTF-8 | Java | false | false | 1,793 | java | package com.delicacy.grape.rocketmq.producer.rocket;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
* @author yutao
* @create 2019-11-08 14:08
**/
@Slf4j
@AllArgsConstructor
@Service
public class RocketmqSender {
static final String ipAddr = "192.168.189.142";
@PostConstruct
public void send() throws MQClientException, InterruptedException {
DefaultMQProducer producer = new DefaultMQProducer("test-group");
producer.setNamesrvAddr(ipAddr + ":9876");
producer.start();
for (int i = 0; i < 20; i++) {
try {
byte[] bytes = ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET);
Message msg = new Message("test-topic" /* Topic */,
"TagA" /* Tag */,
bytes /* Message body */
);
SendResult sendResult = producer.send(msg);
if (!sendResult.getSendStatus().equals(SendStatus.SEND_OK)){
log.info("发送失败,status:{}",sendResult);
return;
}
log.info("发送成功,status:{}",sendResult);
} catch (Exception e) {
e.printStackTrace();
Thread.sleep(1000);
}
}
producer.shutdown();
}
}
| [
"v_zhangyt@fosun.com"
] | v_zhangyt@fosun.com |
a82bbb8057795df465708ee86665ea1c0d793615 | de9968eabb2e4a7f0fa421161c13c29d112d566a | /src/main/java/br/unicap/ts830/fullstack/ts830/MultipartFormUtils.java | ea742bbd8c450ed4dcfea806bb184c6bc03a8184 | [] | no_license | eporto/MinhaMerendaServer | bd8f6e1c2927b9da76501d86c885086942642c9a | fba6ca1435d9a3bad4a88e0c7a558c264052b982 | refs/heads/master | 2021-08-30T21:51:06.342917 | 2017-12-19T14:51:07 | 2017-12-19T14:51:07 | 112,555,016 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,626 | 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.unicap.ts830.fullstack.ts830;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MultivaluedMap;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import sun.misc.IOUtils;
/**
*
* @author shido
*/
public class MultipartFormUtils {
Map<String, List<InputPart>> uploadForm;
public MultipartFormUtils(Map<String, List<InputPart>> uploadForm) {
this.uploadForm = uploadForm;
}
public String getFileName(String key) {
List<InputPart> inputParts = this.uploadForm.get(key);
if(inputParts.isEmpty())
return "";
InputPart inputPart = inputParts.get(0);
MultivaluedMap<String, String> header = inputPart.getHeaders();
String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
return finalFileName;
}
}
return "unknown";
}
/*
public byte[] readFormFile(String key) {
List<InputPart> inputParts = this.uploadForm.get(key);
byte[] bytes = new byte[0];
if(inputParts.isEmpty())
return bytes;
InputStream inputStream;
for (InputPart inputPart : inputParts) {
try {
// MultivaluedMap<String, String> header = inputPart.getHeaders();
// String fileName = getFileName(header);
//convert the uploaded file to inputstream
inputStream = inputPart.getBody(InputStream.class,null);
//byte [] bytes = IOUtils.toByteArray(inputStream);
bytes = IOUtils.readFully(inputStream, -1, false);
//Guava: byte[] bytes = ByteStreams.toByteArray(inputStream);
//Map<String, Object> imageParams = imageService.createFileParams(bytes, fileName);
//imageServiceResponse = imageService.upload(imageParams);
} catch (Exception e) {
e.printStackTrace();
}
}
return bytes;
}*/
public byte[] readFormFile(String key) {
List<InputPart> inputParts = this.uploadForm.get(key);
byte[] bytes = new byte[0];
if(inputParts.isEmpty())
return bytes;
InputPart part = inputParts.get(0);
InputStream inputStream;
try {
inputStream = part.getBody(InputStream.class,null);
//byte [] bytes = IOUtils.toByteArray(inputStream);
bytes = IOUtils.readFully(inputStream, -1, false);
//Guava: byte[] bytes = ByteStreams.toByteArray(inputStream);
//Map<String, Object> imageParams = imageService.createFileParams(bytes, fileName);
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
public String readFormString(String key) throws IOException {
List<InputPart> inputParts = this.uploadForm.get(key);
if(inputParts.isEmpty())
return "";
return inputParts.get(0).getBodyAsString();
}
}
| [
"eduardomaporto@gmail.com"
] | eduardomaporto@gmail.com |
be9e5e6829c446459521fff78311caa2cfc55f71 | e083105dd9b4a71b3559a19821f58068c356c80a | /oauth-server/src/main/java/com/guojin/oauth/server/OauthServerApplication.java | 0d6d18faab1a3eab8cbf3b0b1cc8e97d05d0af5b | [] | no_license | guojin21/api-manage-platform | 0167357e0d9be132f4ab865eb9baf4edd256bde8 | eacc16ef6c89167a126392a3e71aca23411b2a48 | refs/heads/master | 2020-03-26T23:25:46.804273 | 2018-08-21T09:37:41 | 2018-08-21T09:37:41 | 145,541,564 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 337 | java | package com.guojin.oauth.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OauthServerApplication {
public static void main(String[] args) {
SpringApplication.run(OauthServerApplication.class, args);
}
}
| [
"guojin@channelsoft.com"
] | guojin@channelsoft.com |
9fd33133ee7e6ca547af070bb7a114abb80a02d9 | 0997b48bb160933d321e8e5cb49e43cd33b4a571 | /SMGMT/src/com/servletStore/report/icardReport/model/IcardGenerateImpl.java | f7deead9a57b3e276e448dd9819894853d773042 | [] | no_license | mnborana/new_SMGMT | 02c8ef119778bc63980621a117bd3f04e444dd01 | 9728c8f5eabd78f239987d8d83e8cef43029d346 | refs/heads/HEAD | 2021-05-06T11:11:23.819846 | 2018-04-06T11:39:31 | 2018-04-06T11:39:31 | 114,216,596 | 2 | 5 | null | 2018-04-06T10:43:37 | 2017-12-14T07:22:36 | CSS | UTF-8 | Java | false | false | 2,531 | java | package com.servletStore.report.icardReport.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.dbconnect.DBConnection;
import com.servletStore.fees.feescollection.model.FeesCollectionPOJO;
public class IcardGenerateImpl implements IcardGenerateDAO {
DBConnection dbconnect=new DBConnection();
Connection connection=dbconnect.getConnection();
PreparedStatement pstmt=null;
/* (non-Javadoc)
* @see com.servletStore.fees.feescollection.model.FeesCollectionDAO#getStadardDivisionDetails()
*/
@Override
public List<IcardGeneratePOJO> getStadardDivisionDetails(String schoolId) {
List<IcardGeneratePOJO> list = new ArrayList<>();
try {
String query="SELECT classroom_master.id,std_master.name,classroom_master.division,classroom_master.shift FROM std_master,classroom_master,fk_class_master,fk_school_section_details WHERE\n" +
"fk_school_section_details.school_id="+schoolId+" AND\n" +
"fk_class_master.fk_school_sec_id=fk_school_section_details.id AND\n" +
"std_master.id=fk_class_master.std_id AND\n" +
"classroom_master.fk_class_master_id=fk_class_master.id";
pstmt = connection.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
IcardGeneratePOJO pojo=new IcardGeneratePOJO();
pojo.setClassRoomMasterId(rs.getInt("id"));
pojo.setStdName(rs.getString("name"));
pojo.setDivName(rs.getString("division"));
pojo.setShift(rs.getString("shift"));
list.add(pojo);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
@Override
public List getStudentInfo(String standard_id) {
ResultSet rs = null;
String query = "SELECT student_details.id, concat(student_details.first_name,' ',student_details.middle_name,' ',student_details.last_name) "
+ "AS full_name FROM student_details, class_allocation WHERE class_allocation.student_id = student_details.id AND "
+ "class_allocation.classroom_master="+standard_id;
List studInfo=new ArrayList<>();
try {
pstmt=connection.prepareStatement(query);
rs=pstmt.executeQuery();
while (rs.next()) {
studInfo.add(rs.getString("id"));
studInfo.add(rs.getString("full_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return studInfo;
}
}
| [
"smita@DESKTOP-AUF15M7"
] | smita@DESKTOP-AUF15M7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.