blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
700e396fdc53ac519a0dea1ffe17f7c48261e0be | 33ab79d8a038396963e36db48107370b4c83fd9c | /src/main/java/com/rameez/springbootneo4jexample1/model/User.java | c858ed9d9906ef3fc51563a205ada54f3c8aa9f0 | [] | no_license | practicalsession/spring-boot-neo4j-example-1-master | fe30f6e56dc96e50f9836e89167ff80460dc0cd9 | 6bcc207138e78ba135f6e76e9d22d5577a998078 | refs/heads/master | 2020-04-01T17:54:17.743557 | 2018-10-17T13:03:40 | 2018-10-17T13:03:40 | 153,458,130 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 813 | java | package com.rameez.springbootneo4jexample1.model;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.List;
@NodeEntity
public class User {
@GraphId
private String userid;
private String username;
private String age;
private String adress;
@Relationship(type = "USES", direction = Relationship.INCOMING)
private List<Vehicle> vehicle;
public List<Vehicle> getVehicle() {
return vehicle;
}
public User() {
}
public String getUserid() {
return userid;
}
public String getUsername() {
return username;
}
public String getAge() {
return age;
}
public String getAdress() {
return adress;
}
}
| [
"mrameezk@outlook.com"
] | mrameezk@outlook.com |
63f19dc77a53324d712ace05d788ae00482ddd1d | aa53a0f1ec8aaab82f2de0a5f828679c1792613a | /app/src/main/java/org/login/com/threadfragmentroomnavigationbar/ICallBack.java | 79ea186ec50d85822395ddbeaff247850ac341bf | [] | no_license | MonimCse/Splash-Fragment-Room-ORM- | e7cebab99226f928ef1505af19b81c02420fc6fe | 87dd8a0605da5380db08189d78f41690b895f6bf | refs/heads/master | 2020-03-19T16:00:05.684507 | 2018-07-07T14:14:32 | 2018-07-07T14:14:32 | 136,695,401 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 313 | java | package org.login.com.threadfragmentroomnavigationbar;
import org.login.com.threadfragmentroomnavigationbar.db.entities.User;
public interface ICallBack {
void replaceRegistrationFragment();
void replaceLoginFragment();
void login(String email,String password);
void registration(User user);
}
| [
"cse.monim@gmail.com"
] | cse.monim@gmail.com |
4905270a1c83a859676bfef156b07dc06c6d2a87 | 81cc4b38148ae5d11b030197014bd1eb6c1f0fc9 | /src/kasir1/Kasir1.java | 7f39e8f740cb562da82c1c0d258ed38561b7a4ae | [] | no_license | DewiNurul/KasirPenjualan | 5b7414eb2d4832d3a9ff6db8a775ccb82b21501a | f62c647cf2fb5671a88f3f07d0ba01fa7318e161 | refs/heads/master | 2020-03-28T14:20:29.007292 | 2018-09-12T12:52:26 | 2018-09-12T12:52:26 | 148,479,340 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,490 | java |
package kasir1;
import java.util.Scanner;
/**
*
* @author asus
*/
public class Kasir1 {
public static void main(String[] args) {
System.out.println ("Dewi Nurul Mahardika / X RPL 6 / 16") ;
System.out.println("--PROGRAM KASIR PENJUALAN--");
String namaBarang, namaKasir, kodeBarang;
byte lanjut = 0;
double hargaBarang, angkaDiskon, diskon, totalHarga, totalBayar = 0;
int jumlahBarang;
//membuat scanner masukan
Scanner baca = new Scanner(System.in);
do {
// input
jumlahBarang = 0;
diskon = 0;
hargaBarang = 0;
totalBayar = 0;
angkaDiskon = 0;
//kodeBarang = ''"";
System.out.println("Nama Kasir: ");
namaKasir = baca.next();
System.out.println("Nama Barang :");
namaBarang = baca.next();
System.out.println("Kode Barang :");
kodeBarang = baca.next();
System.out.println("Jumlah Barang : ");
jumlahBarang = baca.nextInt();
System.out.println("Harga Barang : ");
hargaBarang = baca.nextDouble();
System.out.println("Total Harga");
//proses
totalHarga = jumlahBarang * hargaBarang;
System.out.println(totalHarga);
if (totalHarga > 100000 && totalHarga<=200000){
angkaDiskon = 0.1;
diskon = 0.1 * totalHarga;
}
else if (totalHarga > 200000 && totalHarga<=500000) {
angkaDiskon = 0.2;
diskon = 0.2 * totalHarga;
}
else if (totalHarga > 500000) {
angkaDiskon = 0.5;
diskon = 0.5 * totalHarga;
}
else {
diskon =0;
}
totalBayar = totalHarga - diskon;
System.out.println("Angka diskon= :" + angkaDiskon);
System.out.println("Total diskon = :" + diskon);
System.out.println("Total bayar = :" + totalBayar);
//output
System.out.println("Lanjut ke costumer berikutnya ? (1/0) :");
lanjut = baca.nextByte();
} while (lanjut == 1);
System.out.println("--PROGRAM SELSESAI--");
}
}
| [
"asus@LAPTOP-79N8S16K"
] | asus@LAPTOP-79N8S16K |
75176339fdf8899e7e5e250bd775d116544f3d0d | 9f8bb6a153ca1df3cf57ed5fc49fd9c43df0d4c1 | /Chapter04-AOP/src/main/java/cn/edu/hust/aop/Person.java | 841832bfcf384d458e7e698f3ab45a4b8b0bb6da | [
"Apache-2.0"
] | permissive | lyc88/SpringLearning | f43821b8391baaeb438797dd1a4f6169d78e8c26 | 2b53d5d5bfa49b0ab6dd807ec912149d852aaa20 | refs/heads/master | 2020-06-19T09:48:20.114730 | 2018-12-01T11:41:43 | 2018-12-01T11:41:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,387 | java | package cn.edu.hust.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
*
* @Aspect注解表示将这个bean声明为一个切面
*/
@Component
@Aspect
public class Person {
/**
* @Pointcut注解表示切点,表示在哪里执行通知
* 下面这个方法并不是非必需的,只是为了减少下面的通知方法的匹配
*/
@Pointcut("execution(* cn.edu.hust.aop.*.watch(..))")
public void watch(){}
/**
* @Before注解是前置通知,在目标方法之前执行
*/
@Before( value = "watch()")
public void call()
{
System.out.println("person call phone for ticket");
}
@Before("watch()")
public void selectSeat()
{
System.out.println("person need select seats");
}
/**
* @After注解表示后置通知,目标方法执行之后在执行通知
*/
@After("watch()")
public void hclap()
{
System.out.println("the person clap");
}
/**
* @AfterThrowing表示出现异常以后执行该通知
*/
@AfterThrowing("watch()")
public void refund()
{
System.out.println("person need refund");
}
/**
* @AfterReturning注解表示方法返回之后执行该通知,
*/
@AfterReturning("watch()")
public void back()
{
System.out.println("the moive end,the person is back");
}
/**
* 环绕通知,这里通知的效果结合了所有通知的类型
* @param proceedingJoinPoint
* 参数是必须要有的,当通知被执行后才将控制权给这个参数执行目标方法
* 这里需要注意的是必须调用这个方法proceed()否则后阻塞被通知方法的调用。
*/
@Around("watch()")
public void full(ProceedingJoinPoint proceedingJoinPoint)
{
try
{
System.out.println("person call phone for ticket");
System.out.println("person need select seats");
//int a=1/0;
proceedingJoinPoint.proceed();
System.out.println("the moive end,the person is back");
}
catch (Throwable e)
{
System.out.println("person need refund");
}
finally {
System.out.println("the person clap");
}
}
}
| [
"oeljeklaus2heart@gmail.com"
] | oeljeklaus2heart@gmail.com |
b3c58abed276c9f26a32d44bed8d1e15b196deec | a333d4bf0d0fd98214949423f301363ab9fc239e | /app/src/main/java/com/coolweatherlgy/android/ChooseAreaFragment.java | afd064b3dc4b9f21f282bc9bf0f567574a831df1 | [
"Apache-2.0"
] | permissive | XC-LGY/coolweatherlgy | 3a04e2e7873f9dd4f3820d385b6ba916a0d83823 | e4558316da5964fe691746f43836a7ba1dfe374a | refs/heads/master | 2020-06-15T18:41:21.766549 | 2019-07-05T10:01:53 | 2019-07-05T10:01:53 | 195,364,923 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,570 | java | package com.coolweatherlgy.android;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.coolweatherlgy.android.db.City;
import com.coolweatherlgy.android.db.County;
import com.coolweatherlgy.android.db.Province;
import com.coolweatherlgy.android.util.HttpUtil;
import com.coolweatherlgy.android.util.Utility;
import org.litepal.LitePal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button backButton;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省份
*/
private Province selectedProvince;
/**
* 选中的城市
*/
private City selectedCity;
/**
* 当前选中的级别
*/
private int currentLevel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container, false);
titleText = (TextView) view.findViewById(R.id.title_text);
backButton = (Button) view.findViewById(R.id.back_button);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
} else if (currentLevel == LEVEL_CITY) {
queryProvinces();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryProvinces() {
titleText.setText("中国");
backButton.setVisibility(View.GONE);
provinceList = LitePal.findAll(Province.class);
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
} else {
String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
backButton.setVisibility(View.VISIBLE);
cityList = LitePal.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
backButton.setVisibility(View.VISIBLE);
countyList = LitePal.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCityCode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据
*/
private void queryFromServer(String address, final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
} else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
// 通过runOnUiThread()方法回到主线程处理逻辑
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
} | [
"7784187@qq.com"
] | 7784187@qq.com |
1e062bbc688c0b8fb421c553db79b69cc16e9eab | de897e577c2bd95abbf98b143a2ec3d8cc5b9f80 | /app/src/main/java/com/lwc/shanxiu/widget/CustomerDateView/CustomYearView.java | 6113e92d4351a30ba813fce37efa94c3bd56212d | [] | no_license | popularcloud/SHANXIU06042120 | 6b4e02c1e4c1df2cf5ac9145992125f0cf930d80 | 60cb0a4512f36fb2933009f97b6ab332d7b370bb | refs/heads/master | 2021-06-29T01:30:10.062909 | 2021-01-04T01:51:36 | 2021-01-04T01:51:36 | 199,803,391 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,640 | java | /*
* Copyright (C) 2016 huanghaibin_dev <huanghaibin_dev@163.com>
* WebSite https://github.com/MiracleTimes-Dev
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lwc.shanxiu.widget.CustomerDateView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.YearView;
/**
* 自定义年视图
* Created by huanghaibin on 2018/10/9.
*/
@SuppressWarnings("unused")
public class CustomYearView extends YearView {
private int mTextPadding;
/**
* 闰年字体
*/
private Paint mLeapYearTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CustomYearView(Context context) {
super(context);
mTextPadding = dipToPx(context, 3);
mLeapYearTextPaint.setTextSize(dipToPx(context, 12));
mLeapYearTextPaint.setColor(0xffd1d1d1);
mLeapYearTextPaint.setAntiAlias(true);
mLeapYearTextPaint.setFakeBoldText(true);
}
@Override
protected void onDrawMonth(Canvas canvas, int year, int month, int x, int y, int width, int height) {
String text = getContext()
.getResources()
.getStringArray(com.haibin.calendarview.R.array.month_string_array)[month - 1];
canvas.drawText(text,
x + mItemWidth / 2 - mTextPadding,
y + mMonthTextBaseLine,
mMonthTextPaint);
if (month == 2 && isLeapYear(year)) {
float w = getTextWidth(mMonthTextPaint, text);
canvas.drawText("闰年",
x + mItemWidth / 2 - mTextPadding + w + dipToPx(getContext(), 6),
y + mMonthTextBaseLine,
mLeapYearTextPaint);
}
}
private float getTextWidth(Paint paint, String text) {
return paint.measureText(text);
}
/**
* 是否是闰年
*
* @param year year
* @return 是否是闰年
*/
private static boolean isLeapYear(int year) {
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
@Override
protected void onDrawWeek(Canvas canvas, int week, int x, int y, int width, int height) {
String text = getContext().getResources().getStringArray(com.haibin.calendarview.R.array.year_view_week_string_array)[week];
canvas.drawText(text,
x + width / 2,
y + mWeekTextBaseLine,
mWeekTextPaint);
}
@Override
protected boolean onDrawSelected(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme) {
int cx = x + mItemWidth / 2;
int cy = y + mItemHeight / 2;
int radius = Math.min(mItemWidth, mItemHeight) / 8 * 5;
canvas.drawCircle(cx, cy, radius, mSelectedPaint);
return true;
}
@Override
protected void onDrawScheme(Canvas canvas, Calendar calendar, int x, int y) {
}
@Override
protected void onDrawText(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme, boolean isSelected) {
float baselineY = mTextBaseLine + y;
int cx = x + mItemWidth / 2;
if (isSelected) {
canvas.drawText(String.valueOf(calendar.getDay()),
cx,
baselineY,
hasScheme ? mSchemeTextPaint : mSelectTextPaint);
} else if (hasScheme) {
canvas.drawText(String.valueOf(calendar.getDay()),
cx,
baselineY,
calendar.isCurrentDay() ? mCurDayTextPaint : mSchemeTextPaint);
} else {
canvas.drawText(String.valueOf(calendar.getDay()), cx, baselineY,
calendar.isCurrentDay() ? mCurDayTextPaint : mCurMonthTextPaint);
}
}
/**
* dp转px
*
* @param context context
* @param dpValue dp
* @return px
*/
private static int dipToPx(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
| [
"liushuzhiyt@163.com"
] | liushuzhiyt@163.com |
770744ee53184c407d775e7867c9b5703a69933a | c1116c7ff8314ec43b16d455ee1aea7d8d289943 | /enderio-machines/src/main/java/crazypants/enderio/machines/config/config/SoulBinderConfig.java | 180b62af789f8ea59de8f8a2faca125454cd7c56 | [
"Unlicense",
"CC-BY-NC-3.0",
"CC0-1.0",
"CC-BY-3.0",
"LicenseRef-scancode-public-domain"
] | permissive | FinalCraftMC/EnderIO | 71054da73fe329d5d49c9a2c239b4545a8b7ed7b | a173868d1659d511154d9b195cd0d4759164029b | refs/heads/master | 2023-04-23T19:20:36.682724 | 2021-05-10T18:42:24 | 2021-05-10T18:42:24 | 298,419,938 | 0 | 0 | Unlicense | 2020-09-26T23:02:13 | 2020-09-24T23:40:35 | null | UTF-8 | Java | false | false | 708 | java | package crazypants.enderio.machines.config.config;
import info.loenwind.autoconfig.factory.IValue;
import info.loenwind.autoconfig.factory.IValueFactory;
import crazypants.enderio.machines.config.Config;
public final class SoulBinderConfig {
public static final IValueFactory F = Config.F.section("soulbinder");
public static final IValue<Integer> soulFluidInputRate = F.make("soulFluidInputRate", 50, //
"Amount of XP fluid in mB the Soul Binder can accept per tick.").setMin(1).sync();
public static final IValue<Integer> soulFluidOutputRate = F.make("soulFluidOutputRate", 50, //
"Amount of XP fluid in mB that can be extracted from the Soul Binder per tick.").setMin(1).sync();
}
| [
"henry@loenwind.info"
] | henry@loenwind.info |
fc08ca2b4af1c179e4eb5c11d8ee6d08430b5b58 | 2bd9f78d361fb5c82410600b30ef8978b382a464 | /spring-boot-ly-movie-feign2/src/main/java/com/ly/feign/FeignInterface.java | dc2cda6513afc5c2b5745caf91905a510118b41b | [] | no_license | liyangmains/spring-boot-ly-movie | 19889ae062ad7bbed4cb2a0ed90fc234eeaac665 | eff83f6366110785750edf9d84c520506b196cb8 | refs/heads/master | 2023-08-02T21:21:01.685908 | 2020-04-19T12:01:00 | 2020-04-19T12:01:00 | 163,912,338 | 0 | 0 | null | 2022-05-25T23:27:25 | 2019-01-03T02:17:39 | Java | UTF-8 | Java | false | false | 1,370 | java | package com.ly.feign;
import org.springframework.cloud.openfeign.FeignClient;
import com.ly.config.FeignConfig;
import com.ly.user.entity.User;
import com.ly.util.result.ResultBean;
import feign.Param;
import feign.RequestLine;
/**
* @FeignClient(value = "movie-controller",configuration = FeignConfig.class)
* configuration = FeignConfig.class
* 自定义默认feignConfigUration 需用feign自带请求
* @author Administrator
*
*/
@FeignClient(name = "movie-controller",configuration = FeignConfig.class)
public interface FeignInterface {
//方法一:
// @RequestMapping(value = "/user/info",method = RequestMethod.POST)
// User selectByPhonePassword(@RequestBody User user);
// @RequestMapping(value = "/user/info",method = RequestMethod.POST)
// ResultBean selectByPhonePassword(@RequestParam("userPhone") String userPhone,@RequestParam("password") String password);
// @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
// User selectUserInfoById(@PathVariable("id")Integer id);
/**
* 自定义需用feign自带默认请求方式RequestLin包括Param
* @param userPhone
* @param password
* @return
*/
@RequestLine("POST /user/info")
ResultBean selectByPhonePassword(@Param("userPhone") String userPhone,@Param("password") String password);
@RequestLine("GET /user/{id}")
User selectUserInfoById(@Param("id")Integer id);
}
| [
"1301934707.com"
] | 1301934707.com |
855937a9cea6107b1fc7eeca286a75f7ed33a3cb | a37e75c5138eec880850caaa0d1fa548f08d4e31 | /org.kevoree.extra.freePastry/src/main/java/rice/pastry/NodeIdFactory.java | e10d55348b24372ccb58509c6ab31d5df373192f | [] | no_license | dukeboard/kevoree-extra | c88806d50d23d2dcdd0d5d64d75b5e6358cdabcf | f8308f812d54d7a8ba4ae8fd2972d6fed3bc3503 | refs/heads/master | 2022-12-22T17:09:51.828299 | 2014-05-27T14:43:16 | 2014-05-27T14:43:16 | 2,067,252 | 4 | 7 | null | 2022-12-13T19:14:06 | 2011-07-18T16:15:37 | Java | UTF-8 | Java | false | false | 2,239 | java | /*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
This software is provided by RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package rice.pastry;
/**
* An interface to any object capable of generating nodeIds.
*
* @version $Id: NodeIdFactory.java 3613 2007-02-15 14:45:14Z jstewart $
*
* @author Andrew Ladd
*/
public interface NodeIdFactory {
/**
* Generates a nodeId.
*
* @return a new node id.
*/
public Id generateNodeId();
}
| [
"jedartois@gmail.com"
] | jedartois@gmail.com |
9c6596ba19a502bd4da7f3ded8e4cdba87060734 | f703ce327cf3c225005f4286c9d1d17ea1981a1f | /src/main/java/org/academiadecodigo/invictus/bolinhas/Main.java | 64f1868438981969d54336bd7e7765a0c6a68817 | [] | no_license | b4ld/bolinhasAC_21bootcamp | 7fa8225a7107d487e634c9ba293a9d3c7535f7c7 | 3348c389256ef9ae3296f3d3ea3d385fa12a1346 | refs/heads/master | 2020-04-07T22:17:32.390409 | 2018-12-27T21:17:16 | 2018-12-27T21:17:16 | 158,763,392 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 426 | java | package org.academiadecodigo.invictus.bolinhas;
import org.academiadecodigo.invictus.bolinhas.game.Game;
import org.academiadecodigo.invictus.bolinhas.user_interface.MouseListener;
public class Main {
public static void main(String[] args) {
Game game = new Game();
game.init();
MouseListener listener = new MouseListener();
listener.setHandler(game);
listener.init();
}
}
| [
"pedrocarmezim00@gmail.com"
] | pedrocarmezim00@gmail.com |
d0f4400139bf6a3cfe96f0cde8474f9230bb6382 | 21b8efc2047f04c85de825f2005c6257ff609ad2 | /Savemore/app/src/main/java/com/ximai/savingsmore/library/net/URLBuilder.java | 0ba856bf8cc6f5f3922c49883dc5147206e18d7b | [] | no_license | doudou5154858117/saveMore | 3175730b7b5d7583884cd4839bd285cef88510c9 | aac0d65f72e705a0fde1f3aa02a69a17efa9c5ff | refs/heads/master | 2021-01-12T08:48:13.387568 | 2016-12-17T06:36:15 | 2016-12-17T06:36:15 | 76,697,611 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,512 | java | package com.ximai.savingsmore.library.net;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
/**
* @author wangguodong
*/
public class URLBuilder {
public static String buildKeyValueText(Map<String, String> paramMap) {
StringBuilder sb = new StringBuilder();
getStringFromMap(paramMap, sb);
return sb.toString();
}
public static String addParameter(String baseURL, Map<String, String> paramMap) {
if (paramMap == null || paramMap.size() == 0) {
return baseURL;
}
StringBuilder sb = new StringBuilder(baseURL);
sb.append('?');
getStringFromMap(paramMap, sb);
return sb.toString();
}
public static void putPostParam(String key, String value, Map<String, String> paramMap)
throws UnsupportedEncodingException {
paramMap.put(URLEncoder.encode(key, WebRequestHelper.CHAR_SET), URLEncoder.encode(value, WebRequestHelper.CHAR_SET));
}
public static String getPostTextFromMap(Map<String, String> paraMap) {
StringBuilder builder = new StringBuilder();
if (paraMap != null) {
getStringFromMap(paraMap, builder);
}
return builder.toString();
}
/**
* @param paramMap
* @param sb
*/
private static void getStringFromMap(Map<String, String> paramMap, StringBuilder sb) {
int index = 0;
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
sb.append(entry.getKey());
sb.append('=');
sb.append(entry.getValue());
if (index != paramMap.size() - 1) {
sb.append('&');
}
++index;
}
}
}
| [
"15256585816@163.com"
] | 15256585816@163.com |
686e1c5fa1dbe2ac4bfa74dbefa5c116ddc0dca3 | c8d837dde4acd945b7b1feb16328ec7e3056f924 | /tomcat/src/main/java/com/bolly/tomcat/web/ServletWebServerInitializedEvent.java | e316d968268dc3b89fb6b7b1f88dbb7c1b31f8b0 | [
"MIT"
] | permissive | chibaolai/java_wheels | 8d6e596cfdaaa47388fbe34f5de58ffb553adda8 | 1b6e6db0bff44ff286f1a36ffb77afeea0710835 | refs/heads/master | 2022-09-13T22:33:35.123027 | 2022-08-08T09:05:25 | 2022-08-08T09:05:25 | 156,097,799 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,873 | java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bolly.tomcat.web;
import com.bolly.tomcat.embedded.WebServer;
/**
* Event to be published after the {@link ServletWebServerApplicationContext} is refreshed
* and the {@link WebServer} is ready. Useful for obtaining the local port of a running
* server.
*
* <p>
* Normally it will have been started, but listeners are free to inspect the server and
* stop and start it if they want to.
*
* @author Dave Syer
* @since 2.0.0
*/
@SuppressWarnings("serial")
public class ServletWebServerInitializedEvent extends WebServerInitializedEvent {
private final ServletWebServerApplicationContext applicationContext;
public ServletWebServerInitializedEvent(WebServer webServer,
ServletWebServerApplicationContext applicationContext) {
super(webServer);
this.applicationContext = applicationContext;
}
/**
* Access the application context that the server was created in. Sometimes it is
* prudent to check that this matches expectations (like being equal to the current
* context) before acting on the server itself.
* @return the applicationContext that the server was created from
*/
@Override
public ServletWebServerApplicationContext getApplicationContext() {
return this.applicationContext;
}
}
| [
"sunshine_bolly@163.com"
] | sunshine_bolly@163.com |
cccf0eb5a1d1804d841c253a237649b3c492215d | eb64e635bb49eb264867b6c3815de21bd7fee32e | /src/main/java/org/wildfly/security/auth/provider/RealmIdentity.java | fe8a18005f77557dd9bf857d9c8856f6d55cebb0 | [
"Apache-2.0"
] | permissive | jpkrohling/wildfly-elytron | 20580bc1f76fcebb4a55dd687dc2fccb110e25fb | 1b4471f30a511c272b15491247653e1d5f055587 | refs/heads/master | 2021-01-20T22:35:06.806003 | 2014-08-27T15:36:49 | 2014-08-27T15:42:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,468 | java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.security.auth.provider;
import java.security.Principal;
import org.wildfly.security.auth.IdentityContext;
import org.wildfly.security.auth.SecurityIdentity;
import org.wildfly.security.auth.login.AuthenticationException;
import org.wildfly.security.auth.verifier.Verifier;
/**
* A representation of a pre-authentication identity.
*
* The life of a {@code RealmIdentity} is short and is for a specific authentication attempt. A {@link SecurityRealm} creating a
* {@code RealmIdentity} does not confirm the existance of the identity.
*
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public interface RealmIdentity {
/**
* Get the {@link Principal} for this identity.
*
* Note: {@link #createSecurityIdentity()} may be sufficient to make this redundant, just retaining as we currently support
* early {@link Principal} access.
*
* @return The {@link Principal} for this identity.
*/
Principal getPrincipal();
/**
* Obtain the name of the realm this identity is associated with,
*
* @return The realm name.
*/
String getRealmName();
/**
* Determine whether a given credential is definitely supported, possibly supported, or definitely not supported for this
* identity.
*
* @param credentialType the credential type
* @return the level of support for this credential type
*/
CredentialSupport getCredentialSupport(Class<?> credentialType);
/**
* Use a verifier to acquire proof of authentication.
*
* @param verifier the verifier containing evidence of authenticity
* @param <P> the type of proof returned by the verifier, or {@link Void} if the verifier cannot return proof
* @return the proof, or {@code null} if the verifier cannot return proof
* @throws AuthenticationException if the authentication of the principal cannot be verified based on the evidence
*/
<P> P proveAuthentic(Verifier<P> verifier) throws AuthenticationException;
/**
* Acquire a credential of the given type.
*
* @param credentialType the credential type class
* @param <C> the credential type
* @return the credential, or {@code null} if the principal has no credential of that type
*/
<C> C getCredential(Class<C> credentialType);
/**
* Create the {@link SecurityIdentity} that will be associated with the {@link IdentityContext}
*
* Note: The caller is responsible for ensuring the identity is actually authenticated.
*
* TODO: Verify where authorization ID is fitting.
*
* @return The {@link SecurityIdentity} for this identity.
*/
SecurityIdentity createSecurityIdentity();
}
| [
"darran.lofthouse@jboss.com"
] | darran.lofthouse@jboss.com |
44b72945e99b6f06d5ce6bf8a0111662f3876945 | a911f926261b82ec8a2ade2d0af1a973280ceab6 | /qipai_game/src/main/java/com/anbang/qipai/game/plan/bean/historicalresult/majiang/TaizhouMajiangPanPlayerResult.java | fb4500f51734b505ac2167ded87c3cc2a151bac6 | [] | no_license | 791837060/qipai_huainanmajiang | 31325550c9db1fcb139c6f5a89d84f7deac0e3a2 | b4f17b26484bbe2840a0852156117faee9996bbb | refs/heads/master | 2023-06-26T22:31:40.822705 | 2021-07-30T07:20:49 | 2021-07-30T07:20:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,135 | java | package com.anbang.qipai.game.plan.bean.historicalresult.majiang;
import com.anbang.qipai.game.plan.bean.historicalresult.GamePanPlayerResult;
import java.util.Map;
public class TaizhouMajiangPanPlayerResult implements GamePanPlayerResult {
private String playerId;// 玩家id
private String nickname;// 玩家昵称
private int score;// 一盘总分
public TaizhouMajiangPanPlayerResult() {
}
public TaizhouMajiangPanPlayerResult(Map panPlayerResult) {
this.playerId = (String) panPlayerResult.get("playerId");
this.nickname = (String) panPlayerResult.get("nickname");
this.score = ((Double) panPlayerResult.get("score")).intValue();
}
public String getPlayerId() {
return playerId;
}
public void setPlayerId(String playerId) {
this.playerId = playerId;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
| [
"shony01@163.com"
] | shony01@163.com |
9e3fcf9bd7cec1219250a49b264ca05e5576f2e3 | 23d236793662da1fba881770d8a9a6db3c3db4ce | /app/src/main/java/com/example/zhouqiong/stackcardview/view/AnimatorAdapter.java | 3bcf127b50251d872fcf1629975207eeac3c8757 | [] | no_license | JustinLau1/StackCardView | 024e383b1c3df52ab0c52759dc9395eb215cac96 | ef0e8d02f723f17f9f99b914c26ca98e34e00012 | refs/heads/master | 2021-09-21T18:15:14.738600 | 2018-08-30T09:29:00 | 2018-08-30T09:29:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,993 | java | package com.example.zhouqiong.stackcardview.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.view.animation.AccelerateDecelerateInterpolator;
/**
* Created by ZQiong on 2018/1/19.
*/
public abstract class AnimatorAdapter {
static final int ANIMATION_DURATION = 400;
protected CardStackView mCardStackView;
protected AnimatorSet mSet;
public AnimatorAdapter(CardStackView cardStackView) {
mCardStackView = cardStackView;
}
protected void initAnimatorSet() {
mSet = new AnimatorSet();
mSet.setInterpolator(new AccelerateDecelerateInterpolator());
mSet.setDuration(getDuration());
}
public void itemClick(final CardStackView.ViewHolder viewHolder, int position) {
if (mSet != null && mSet.isRunning()) return;
initAnimatorSet();
if (mCardStackView.getSelectPosition() == position) {
onItemCollapse(viewHolder);
} else {
onItemExpand(viewHolder, position);
}
if (mCardStackView.getChildCount() == 1)
mSet.end();
}
protected abstract void itemExpandAnimatorSet(CardStackView.ViewHolder viewHolder, int position);
protected abstract void itemCollapseAnimatorSet(CardStackView.ViewHolder viewHolder);
private void onItemExpand(final CardStackView.ViewHolder viewHolder, int position) {
final int preSelectPosition = mCardStackView.getSelectPosition();
final CardStackView.ViewHolder preSelectViewHolder = mCardStackView.getViewHolder(preSelectPosition);
if (preSelectViewHolder != null) {
preSelectViewHolder.onItemExpand(false);
}
mCardStackView.setSelectPosition(position);
itemExpandAnimatorSet(viewHolder, position);
mSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
mCardStackView.setScrollEnable(false);
if (preSelectViewHolder != null) {
preSelectViewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_START, false);
}
viewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_START, true);
}
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
viewHolder.onItemExpand(true);
if (preSelectViewHolder != null) {
preSelectViewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_END, false);
}
viewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_END, true);
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
if (preSelectViewHolder != null) {
preSelectViewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_CANCEL, false);
}
viewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_CANCEL, true);
}
});
mSet.start();
}
private void onItemCollapse(final CardStackView.ViewHolder viewHolder) {
itemCollapseAnimatorSet(viewHolder);
mSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
viewHolder.onItemExpand(false);
mCardStackView.setScrollEnable(true);
viewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_START, false);
}
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mCardStackView.setSelectPosition(CardStackView.DEFAULT_SELECT_POSITION);
viewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_END, false);
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
viewHolder.onAnimationStateChange(CardStackView.ANIMATION_STATE_CANCEL, false);
}
});
mSet.start();
}
protected int getCollapseStartTop(int collapseShowItemCount) {
return mCardStackView.getOverlapGapsCollapse()
* (mCardStackView.getNumBottomShow() - collapseShowItemCount - (mCardStackView.getNumBottomShow() - (mCardStackView.getChildCount() - mCardStackView.getSelectPosition() > mCardStackView.getNumBottomShow()
? mCardStackView.getNumBottomShow()
: mCardStackView.getNumBottomShow())));
}
public int getDuration() {
return mCardStackView.getDuration();
}
}
| [
"zhouqiong@beescm.cn"
] | zhouqiong@beescm.cn |
b925f05c8309bc9ef0cf626440202519a0fdae66 | 184dcd6c71b5e2a1198601ae17756676fb7c6aa0 | /src/NER/Entity_Sent.java | 459e35eca6c0335ca9e023f9c1a1c97a7e348254 | [] | no_license | chendamon/Concept_Sentiment | 8be85fb5a8dbf8f1f908bfdf2d6195bd5c61d1eb | 8980129786e9bed094f843377294155aa8b06c16 | refs/heads/master | 2021-01-21T14:07:25.357447 | 2016-06-01T13:45:49 | 2016-06-01T13:45:49 | 46,956,005 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 641 | java | package NER;
import java.util.ArrayList;
import java.util.HashMap;
import Sentiment.Sent_enti;
/*
* 给定一组实体能够定义其情感倾向
* author biront
* date 2015/12/7
* 实体与情感绑定
*/
public class Entity_Sent
{
public HashMap<String,Integer> gule(ArrayList<String> weibo_seg_s,ArrayList<String> parse) throws Exception
{
HashMap<String,Integer> eS = new HashMap<String,Integer>();
Sent_enti se = new Sent_enti();
se.Init();
int size = weibo_seg_s.size();
for(int i = 0; i < size; i++)
{
String entity = weibo_seg_s.get(i);
eS.put(entity, se.entity_SP(entity, parse));
}
return eS;
}
}
| [
"wangchendamon@gmail.com"
] | wangchendamon@gmail.com |
9e2de8a4c5e910ebd8fa965afc0615d211088967 | 80220af71f82b7306ee8ef05a855502c2f3c0c33 | /Sara_Ubuntu/APP/sara/src/java/M_Modelo/Detalles_Area.java | 8962ac2dcd8cd840dc2353055635811a0caa5cff | [] | no_license | SaraPro52/LppConsola | 126d89a467174abfe5a735b4f42a4c4f0273950d | 1ae4ecf5ef0b1d53d1b3a072aeedec9effb7ac72 | refs/heads/master | 2020-05-21T18:11:10.337149 | 2019-05-24T11:29:37 | 2019-05-24T11:29:37 | 64,032,962 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 156 | java | package M_Modelo;
import M_Util.Elomac;
public class Detalles_Area extends Elomac{
public Detalles_Area ( ){
super("detalles_area",1);
}
} | [
"jalopez173@misena.edu.co"
] | jalopez173@misena.edu.co |
8e6bd207d416ce735f1227dc7d8e8b30b400c358 | f475dbb992f61487266384fdd6c36ab7b20fc2d0 | /src/main/java/com/tjs/common/setting/controller/SettingController.java | dcf2f3f1a3c95c730cfba74e18f7b7f254a04456 | [
"Apache-2.0"
] | permissive | tjscreators/endlos | c039405006a97452abe27e4a11651dd9b6e1d6fa | cf7819c716ac7a1a95a31ee77d60059a040a129d | refs/heads/master | 2022-12-25T04:05:45.380409 | 2020-09-24T10:23:20 | 2020-09-24T10:23:20 | 297,992,002 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,096 | java | /*******************************************************************************
* Copyright -2018 @Emotome
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.tjs.common.setting.controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.tjs.common.aop.AccessLog;
import com.tjs.common.controller.Controller;
import com.tjs.common.response.Response;
import com.tjs.common.setting.view.SettingView;
import com.tjs.endlos.exception.EndlosException;
/**
*
* @author Nirav
* @since 24/11/2018
*
*/
public interface SettingController extends Controller {
/**
* This method is used to handle view request coming from hospital for any
* module.
*
* @param id
* @return
* @throws EndlosException
*/
// TODO authorization annotation
@RequestMapping(value = "/view", method = RequestMethod.GET)
@ResponseBody
@AccessLog
Response view(@RequestParam(name = "key", required = true) String key) throws EndlosException;
/**
* This method is used to handle edit request coming from hospital for any
* module.
*
* @param id
* @return
* @throws EndlosException
*/
// TODO authorization annotation
@RequestMapping(value = "/edit", method = RequestMethod.GET)
@ResponseBody
@AccessLog
Response edit(@RequestParam(name = "key", required = true) String key) throws EndlosException;
/**
* This method is used to handle update request coming from hospital for any
* module.
*
* @param settingView
* @return
* @throws EndlosException
*/
// TODO authorization annotation
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ResponseBody
@AccessLog
Response update(@RequestBody SettingView settingView) throws EndlosException;
/**
* This method is used to handle search request coming from hospital for any
* module.
*
* @param settingView
* @return
* @throws EndlosException
*/
// TODO authorization annotation
@RequestMapping(value = "/search", method = RequestMethod.POST)
@ResponseBody
@AccessLog
Response search(@RequestBody(required = false) SettingView settingView,
@RequestParam(name = "start", required = false) Integer start,
@RequestParam(name = "recordSize", required = false) Integer recordSize) throws EndlosException;
}
| [
"tjscreators@gmail.com"
] | tjscreators@gmail.com |
09a9103195425e6123713b8a405b52937b5fada2 | 6ecf10fd3709c710d62249bea51ac9f606220b34 | /scam2020/hd_mono/src/cms_mono_objective/src/main/java/br/com/ppgi/unirio/marlon/smc/solution/algorithm/change/SolutionShift.java | 2af30846673b2a036968b352f7e661d6999b60e8 | [] | no_license | JoaoGabriel0511/draco_multi_many_experement | 3b24e06cc8a9af7989e6b3bd6abd087de16372f7 | 56de2d13a7d0e9b6e3015033aced17cac17728d8 | refs/heads/main | 2023-05-11T15:38:10.267804 | 2021-05-26T21:24:42 | 2021-05-26T21:24:42 | 368,350,703 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,263 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.ppgi.unirio.marlon.smc.solution.algorithm.change;
import br.com.ppgi.unirio.marlon.smc.mdg.ClusterMetrics;
/**
*
* @author kiko
*/
public class SolutionShift {
/**
* Transforma a solu��o deslocando todos os elementos uma quantidade para o lado (modulo[i] = modulo[i+quantidade])...
* @param target
* @param base
* @return
*/
public static ClusterMetrics ShiftSolution(ClusterMetrics solution, int offset){
int solutionLengh = solution.getSolution().length;
offset = offset % solutionLengh;//evitar desperdicio
if(offset <= 0){ return solution;}//n�o farz nada
int[] shiftedSolution = solution.cloneSolution();
for(int i=0; i< offset;i++){
int aux = shiftedSolution[0];//guarda o primeiro elemento
for(int moduleN=1; moduleN< shiftedSolution.length;moduleN++){
shiftedSolution[moduleN-1] = shiftedSolution[moduleN];
}
shiftedSolution[solutionLengh-1] = aux;
}
return new ClusterMetrics(solution.getMdg(),shiftedSolution);
}
}
| [
"43222877+apmt@users.noreply.github.com"
] | 43222877+apmt@users.noreply.github.com |
5d20143e54decfeb1f6263d1d277ac512a26e040 | 31c39bba535acb61b28e62054e7078a9ebc9dd01 | /src/test/java/br/edu/unirn/orm/EstatisticaBanda.java | d7cc2069bbf11724f86652db1f657099e57e5f69 | [] | no_license | luksrn/curso_orm | 1ea5f55ac70024e54dd461d27a49c206de582cee | 7b512499c30179263f24bc1a7790c41eadb9a3e3 | refs/heads/master | 2020-12-20T17:08:34.142090 | 2016-07-30T00:28:33 | 2016-07-30T00:28:33 | 63,461,541 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 826 | java | package br.edu.unirn.orm;
class EstatisticasBanda {
private String album;
private Long quantidadeDeMusicas;
private Long duracaoDoAlbum;
public EstatisticasBanda(String album,
Long quantidadeDeMusicas,
Long duracaoDoAlbum) {
this.album = album;
this.quantidadeDeMusicas = quantidadeDeMusicas;
this.duracaoDoAlbum = duracaoDoAlbum;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public Long getQuantidadeDeMusicas() {
return quantidadeDeMusicas;
}
public void setQuantidadeDeMusicas(Long quantidadeDeMusicas) {
this.quantidadeDeMusicas = quantidadeDeMusicas;
}
public Long getDuracaoDoAlbum() {
return duracaoDoAlbum;
}
public void setDuracaoDoAlbum(Long duracaoDoAlbum) {
this.duracaoDoAlbum = duracaoDoAlbum;
}
} | [
"luksrn@gmail.com"
] | luksrn@gmail.com |
08cb50de53f1e8e05e5ba94fdc73c43adb225f32 | ad7921acad4e291d0abdfba7c8fd6d525fb9e4dc | /application_visiteur/AppliVisiteur/app/src/main/java/com/example/marcmenard/applivisiteur/accueil_classement.java | 5c8562f9fbc057d76ee649e59baffb0cffad0510 | [] | no_license | MarcMenard/GestionDeTournoi | 92168e7d32802363c66e2fb8ff81aa4f8760139b | d1ff646381d15c9baa49850783666f9eb4f22790 | refs/heads/master | 2021-01-17T14:21:19.615827 | 2017-06-03T13:41:22 | 2017-06-03T13:41:22 | 83,666,410 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,878 | java | package com.example.marcmenard.applivisiteur;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
public class accueil_classement extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil_classement);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> items = new ArrayList<String>();
items.add("Cliquez ici pour choisir votre groupe");
items.add("Groupe 1");
items.add("Groupe 2");
items.add("Groupe 3");
items.add("Groupe 4");
items.add("Groupe 5");
items.add("Groupe 6");
items.add("Groupe 7");
items.add("Groupe 8");
// Crée l'adaptateur pour le filtre
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
// configure le style à utiliser pour la liste déroulante du filtre
dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_multiple_choice);
// assigner l'adaptateur au filtre
spinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
// switch permettant d'exécuter lancer l'activitée JSON_Classement en fonction du groupe choisi dans le filtre
switch (position) {
case 0:
break;
case 1:
JSON_Classement.setUrl(0);
Intent intent0 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent0);
break;
case 2:
JSON_Classement.setUrl(1);
Intent intent1 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent1);
break;
case 3:
JSON_Classement.setUrl(2);
Intent intent2 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent2);
break;
case 4:
JSON_Classement.setUrl(3);
Intent intent3 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent3);
break;
case 5:
JSON_Classement.setUrl(4);
Intent intent4 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent4);
break;
case 6:
JSON_Classement.setUrl(5);
Intent intent5 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent5);
break;
case 7:
JSON_Classement.setUrl(6);
Intent intent6 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent6);
break;
case 8:
JSON_Classement.setUrl(7);
Intent intent7 = new Intent(accueil_classement.this, JSON_Classement.class);
startActivity(intent7);
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
| [
"hubertpineau@hotmail.fr"
] | hubertpineau@hotmail.fr |
682e3f75512083cecab6e6bd9fb9818e0d6ccd7a | b58f2c43e22710eb729f3794ec6a766c713ce575 | /src/JavaBasicsUnit1/JavaBasicsUnit1/Lesson_1/SimplePatternJava.java | a084eab86a5c433dd6caf44bad2fe2b9bfd64890 | [] | no_license | catarinaburghi/ICS3U | 798a9894e675781339f446bf55e6120a766252b4 | 3f4df242de255f6721106284ff5ade9a95c934f4 | refs/heads/main | 2023-06-18T05:44:14.727188 | 2021-07-02T19:14:36 | 2021-07-02T19:14:36 | 336,092,364 | 0 | 0 | null | 2021-07-02T19:04:36 | 2021-02-04T21:53:21 | Java | UTF-8 | Java | false | false | 341 | java | package JavaBasicsUnit1.JavaBasicsUnit1.Lesson_1;
public class SimplePatternJava {
public static void main(String[] args) {
System.out.println(" J a V V a");
System.out.println(" J a a V V a a");
System.out.println("J J aaaaa V V aaaaa");
System.out.println(" JJ a a V a a");
}
}
| [
"cf.burghi@gmail.com"
] | cf.burghi@gmail.com |
376bd9a74015528da9a3fc7433c84aa7b62d3d89 | 13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3 | /crash-reproduction-new-fitness/results/MOCKITO-16b-3-23-Single_Objective_GGA-WeightedSum-BasicBlockCoverage/org/mockito/internal/MockitoCore_ESTest.java | 0bd11fa661418456dda4735819110a6866e7a916 | [
"MIT",
"CC-BY-4.0"
] | permissive | STAMP-project/Botsing-basic-block-coverage-application | 6c1095c6be945adc0be2b63bbec44f0014972793 | 80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da | refs/heads/master | 2022-07-28T23:05:55.253779 | 2022-04-20T13:54:11 | 2022-04-20T13:54:11 | 285,771,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | /*
* This file was automatically generated by EvoSuite
* Mon May 18 03:14:56 UTC 2020
*/
package org.mockito.internal;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
import org.mockito.internal.MockitoCore;
@RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true)
public class MockitoCore_ESTest extends MockitoCore_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
MockitoCore mockitoCore0 = new MockitoCore();
String string0 = "+nhNB";
// Undeclared exception!
mockitoCore0.when("+nhNB");
}
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
d146ce89722f63a2897e34d7d3f2ec10e242d326 | 5a5bf034a47cccd3118c647e620f19989e7fc061 | /src/main/java/com/myuki69/enderquarry/InitBlocks.java | 11342654eefbcf1b20dc007754fca62a8f9371bb | [] | no_license | shinyafro/Ender-Quarry-Mod | 782e68c91150a3867084de6c34f6f5d112af5b58 | bc654238ea40c52f4a4b2bf0304c589f370a764e | refs/heads/master | 2023-03-04T16:44:32.538044 | 2021-02-18T21:03:41 | 2021-02-18T21:03:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,918 | java | package com.myuki69.enderquarry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.common.registry.GameRegistry;
@Mod.EventBusSubscriber(modid = EnderQuarryMod.MODID)
public class InitBlocks {
public static EnderQuarry enderQuarry;
public static EnderMarker enderMarker;
public static UpgradeBlock upgradeVoid;
public static UpgradeBlock upgradeSilk;
public static UpgradeBlock upgradeFortune1;
public static UpgradeBlock upgradeFortune2;
public static UpgradeBlock upgradeFortune3;
public static UpgradeBlock upgradeSpeed1;
public static UpgradeBlock upgradeSpeed2;
public static UpgradeBlock upgradeSpeed3;
public static UpgradeBlock upgradePump;
public static ItemBlock itemEnderQuarry;
public static ItemBlock itemEnderMarker;
public static ItemBlock itemUpgradeVoid;
public static ItemBlock itemUpgradeSilk;
public static ItemBlock itemUpgradeFortune1;
public static ItemBlock itemUpgradeFortune2;
public static ItemBlock itemUpgradeFortune3;
public static ItemBlock itemUpgradeSpeed1;
public static ItemBlock itemUpgradeSpeed2;
public static ItemBlock itemUpgradeSpeed3;
public static ItemBlock itemUpgradePump;
private static void init_upgrades()
{
upgradeVoid = new UpgradeBlock("upgradevoid", 1);
ForgeRegistries.BLOCKS.register(upgradeVoid);
upgradeSilk = new UpgradeBlock("upgradesilk", 2);
ForgeRegistries.BLOCKS.register(upgradeSilk);
upgradeFortune1 = new UpgradeBlock("upgradefortunei", 3);
ForgeRegistries.BLOCKS.register(upgradeFortune1);
upgradeFortune2 = new UpgradeBlock("upgradefortuneii", 4);
ForgeRegistries.BLOCKS.register(upgradeFortune2);
upgradeFortune3 = new UpgradeBlock("upgradefortuneiii", 5);
ForgeRegistries.BLOCKS.register(upgradeFortune3);
upgradeSpeed1 = new UpgradeBlock("upgradespeedi", 6);
ForgeRegistries.BLOCKS.register(upgradeSpeed1);
upgradeSpeed2 = new UpgradeBlock("upgradespeedii", 7);
ForgeRegistries.BLOCKS.register(upgradeSpeed2);
upgradeSpeed3 = new UpgradeBlock("upgradespeediii", 8);
ForgeRegistries.BLOCKS.register(upgradeSpeed3);
upgradePump = new UpgradeBlock("upgradepump", 9);
ForgeRegistries.BLOCKS.register(upgradePump);
itemUpgradeVoid = new ItemBlock(upgradeVoid);
itemUpgradeVoid.setRegistryName(upgradeVoid.getRegistryName());
itemUpgradeSilk = new ItemBlock(upgradeSilk);
itemUpgradeSilk.setRegistryName(upgradeSilk.getRegistryName());
itemUpgradeFortune1 = new ItemBlock(upgradeFortune1);
itemUpgradeFortune1.setRegistryName(upgradeFortune1.getRegistryName());
itemUpgradeFortune2 = new ItemBlock(upgradeFortune2);
itemUpgradeFortune2.setRegistryName(upgradeFortune2.getRegistryName());
itemUpgradeFortune3 = new ItemBlock(upgradeFortune3);
itemUpgradeFortune3.setRegistryName(upgradeFortune3.getRegistryName());
itemUpgradeSpeed1 = new ItemBlock(upgradeSpeed1);
itemUpgradeSpeed1.setRegistryName(upgradeSpeed1.getRegistryName());
itemUpgradeSpeed2 = new ItemBlock(upgradeSpeed2);
itemUpgradeSpeed2.setRegistryName(upgradeSpeed2.getRegistryName());
itemUpgradeSpeed3 = new ItemBlock(upgradeSpeed3);
itemUpgradeSpeed3.setRegistryName(upgradeSpeed3.getRegistryName());
itemUpgradePump = new ItemBlock(upgradePump);
itemUpgradePump.setRegistryName(upgradePump.getRegistryName());
}
public static void init()
{
enderQuarry = new EnderQuarry();
itemEnderQuarry = new ItemBlock(enderQuarry);
itemEnderQuarry.setRegistryName(enderQuarry.getRegistryName());
enderMarker = new EnderMarker();
itemEnderMarker = new ItemBlock(enderMarker);
itemEnderMarker.setRegistryName(enderMarker.getRegistryName());
GameRegistry.registerTileEntity(TileEnderQuarry.class, enderQuarry.getRegistryName().toString());
GameRegistry.registerTileEntity(TileEnderMarker.class, enderMarker.getRegistryName().toString());
init_upgrades();
}
@SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event)
{
//event.getRegistry().registerAll(tutorialBlock);
ForgeRegistries.BLOCKS.register(enderQuarry);
ForgeRegistries.BLOCKS.register(enderMarker);
ForgeRegistries.BLOCKS.register(upgradeVoid);
ForgeRegistries.BLOCKS.register(upgradeSilk);
ForgeRegistries.BLOCKS.register(upgradeFortune1);
ForgeRegistries.BLOCKS.register(upgradeFortune2);
ForgeRegistries.BLOCKS.register(upgradeFortune3);
ForgeRegistries.BLOCKS.register(upgradeSpeed1);
ForgeRegistries.BLOCKS.register(upgradeSpeed2);
ForgeRegistries.BLOCKS.register(upgradeSpeed3);
ForgeRegistries.BLOCKS.register(upgradePump);
}
@SubscribeEvent
public static void registerItemBlocks(RegistryEvent.Register<Item> event)
{
//event.getRegistry().registerAll(new ItemBlock(tutorialBlock).setRegistryName(tutorialBlock.getRegistryName()));
ForgeRegistries.ITEMS.register(itemEnderQuarry);
ForgeRegistries.ITEMS.register(itemEnderMarker);
ForgeRegistries.ITEMS.register(itemUpgradeVoid);
ForgeRegistries.ITEMS.register(itemUpgradeSilk);
ForgeRegistries.ITEMS.register(itemUpgradeFortune1);
ForgeRegistries.ITEMS.register(itemUpgradeFortune2);
ForgeRegistries.ITEMS.register(itemUpgradeFortune3);
ForgeRegistries.ITEMS.register(itemUpgradeSpeed1);
ForgeRegistries.ITEMS.register(itemUpgradeSpeed2);
ForgeRegistries.ITEMS.register(itemUpgradeSpeed3);
ForgeRegistries.ITEMS.register(itemUpgradePump);
}
@SubscribeEvent
public static void registerRenders(ModelRegistryEvent event)
{
registerRender(itemEnderQuarry);
registerRender(itemEnderMarker);
registerRender(itemUpgradeVoid);
registerRender(itemUpgradeSilk);
registerRender(itemUpgradeFortune1);
registerRender(itemUpgradeFortune2);
registerRender(itemUpgradeFortune3);
registerRender(itemUpgradeSpeed1);
registerRender(itemUpgradeSpeed2);
registerRender(itemUpgradeSpeed3);
registerRender(itemUpgradePump);
}
public static void registerRender(Item item)
{
ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(item.getRegistryName(), "inventory"));
}
} | [
"blacklordakium@gmail.com"
] | blacklordakium@gmail.com |
19616d3b48fb68eec4f25a3c1d5dc81c8742a006 | 25d3ff2b0da6d918d4845a84bd693ecc230ae830 | /pclsystemBackE/src/main/java/com/lawyersys/pclsystembacke/entities/TiposReporte.java | cdce49a55f457aa54a50635986af8b846ed3cc59 | [] | no_license | pabloag3/pclsystem | 4dbde684a9c96a5f29c46d940de29fe2fbc782ea | 1a4ff49ce0a18e5943405bdb18516fc267c54c6c | refs/heads/master | 2022-12-21T07:40:51.625384 | 2020-06-02T19:33:43 | 2020-06-02T19:33:43 | 199,525,894 | 0 | 1 | null | 2022-11-16T09:24:28 | 2019-07-29T20:57:57 | Java | UTF-8 | Java | false | false | 3,458 | java | package com.lawyersys.pclsystembacke.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author carlo
*/
@Entity
@Table(name = "tipos_reporte")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "TiposReporte.findAll", query = "SELECT t FROM TiposReporte t")
, @NamedQuery(name = "TiposReporte.findByCodTipoReporte", query = "SELECT t FROM TiposReporte t WHERE t.codTipoReporte = :codTipoReporte")
, @NamedQuery(name = "TiposReporte.findByDescripcion", query = "SELECT t FROM TiposReporte t WHERE t.descripcion = :descripcion")})
public class TiposReporte implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "cod_tipo_reporte")
private Integer codTipoReporte;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "descripcion")
private String descripcion;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "codTipoReporte")
@JsonIgnore
private List<Reportes> reportesList;
public TiposReporte() {
}
public TiposReporte(Integer codTipoReporte) {
this.codTipoReporte = codTipoReporte;
}
public TiposReporte(Integer codTipoReporte, String descripcion) {
this.codTipoReporte = codTipoReporte;
this.descripcion = descripcion;
}
public Integer getCodTipoReporte() {
return codTipoReporte;
}
public void setCodTipoReporte(Integer codTipoReporte) {
this.codTipoReporte = codTipoReporte;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
@XmlTransient
public List<Reportes> getReportesList() {
return reportesList;
}
public void setReportesList(List<Reportes> reportesList) {
this.reportesList = reportesList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codTipoReporte != null ? codTipoReporte.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TiposReporte)) {
return false;
}
TiposReporte other = (TiposReporte) object;
if ((this.codTipoReporte == null && other.codTipoReporte != null) || (this.codTipoReporte != null && !this.codTipoReporte.equals(other.codTipoReporte))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.lawyersys.pclsystembacke.TiposReporte[ codTipoReporte=" + codTipoReporte + " ]";
}
}
| [
"Ag"
] | Ag |
d061cf09ac30ad0803f2bfddd06644d223cff30f | 7398562eedd620d5f5a2d0efa80fa73bfa2aafb1 | /src/main/java/threadex/execute/ResultByRunnableEx.java | 7cf4fe22a5c6d47e7986dd103a584ab172cea4b9 | [] | no_license | imgrowing/threadex | 3fd3235697cded5fcfc3a1f8ed16dcc09d7f7949 | f24d4186801eaaacec30b1e0f46b685fb5cd3080 | refs/heads/master | 2020-05-30T15:03:42.159939 | 2019-06-09T09:16:15 | 2019-06-09T09:16:15 | 189,810,157 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,511 | java | package threadex.execute;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
public class ResultByRunnableEx {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Result result = new Result();
Task task1 = new Task(result);
Task task2 = new Task(result);
Future<Result> future1 = executorService.submit(task1, result);
Future<Result> future2 = executorService.submit(task2, result);
try {
Result result1 = future1.get();
log.info("result1: {}", result1.getAccumulatedSum());
Result result2 = future2.get();
log.info("result2: {}", result2.getAccumulatedSum());
log.info("result: {}", result.getAccumulatedSum());
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
public static class Result {
private AtomicInteger accumulatedSum = new AtomicInteger(0);
public void add(int sum) {
accumulatedSum.addAndGet(sum);
}
public int getAccumulatedSum() {
return accumulatedSum.get();
}
}
public static class Task implements Runnable {
private Result result;
public Task(Result result) {
this.result = result;
}
@Override
public void run() {
for (int i = 1; i <= 1000; i++) {
result.add(i);
}
}
}
}
| [
"nkjang@gmail.com"
] | nkjang@gmail.com |
5bcab2e609350f1cdafc680f731e363c25bd47a5 | 0f80a187e7938175f04866fff2e2cd5bd0d4927e | /openml-utils/src/test/java/com/feedzai/util/validate/ValidationUtilsTest.java | a7db37aa69936f17940eda2067282fc69ecbe020 | [
"Apache-2.0"
] | permissive | paulojrp/feedzai-openml | c7ca9b6b7b44bcaf48fd38af27ebca6c93b6c56b | 319d4942ea9f2974c6a2105cff7d06187b35b9f9 | refs/heads/master | 2020-03-21T13:40:26.519810 | 2018-06-25T11:08:33 | 2018-06-25T11:08:33 | 138,619,342 | 0 | 0 | Apache-2.0 | 2018-06-25T16:10:52 | 2018-06-25T16:10:52 | null | UTF-8 | Java | false | false | 3,178 | java | /*
* Copyright 2018 Feedzai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.feedzai.util.validate;
import com.feedzai.openml.data.schema.CategoricalValueSchema;
import com.feedzai.openml.data.schema.DatasetSchema;
import com.feedzai.util.data.schema.TestDatasetSchemaBuilder;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests on the basic validation methods of {@link ValidationUtils}.
*
* @author Henrique Costa (henrique.costa@feedzai.com)
* @since 0.1.0
*/
public class ValidationUtilsTest {
/**
* Tests that the {@link ValidationUtils#baseLoadValidations(DatasetSchema, Map)} accepts a valid
* {@link DatasetSchema}.
*/
@Test
public void testBaseValidationOK() {
final DatasetSchema schema = TestDatasetSchemaBuilder.builder()
.withCategoricalFields(3)
.withNumericalFields(3)
.withStringFields(3)
.build();
assertThat(ValidationUtils.baseLoadValidations(schema, ImmutableMap.of("param1", "val1")))
.as("The result of validating a valid schema and params map")
.isEmpty();
}
/**
* Tests that the {@link ValidationUtils#checkNoFieldsOfType(DatasetSchema, Class)} does not return errors when
* searching for categorical fields in a schema without categoricals.
*/
@Test
public void testCheckNoFieldsOfTypeOK() {
final DatasetSchema schemaWithoutCat = TestDatasetSchemaBuilder.builder()
.withNumericalFields(3)
.withStringFields(3)
.build();
assertThat(ValidationUtils.checkNoFieldsOfType(schemaWithoutCat, CategoricalValueSchema.class))
.as("Validation of a schema without categoricals")
.isEmpty();
}
/**
* Tests that the {@link ValidationUtils#checkNoFieldsOfType(DatasetSchema, Class)} does returns an error when
* searching for categorical fields in a schema containing a categorical.
*/
@Test
public void testCheckNoFieldsOfTypeCategoricalWithInvalidSchema() {
final DatasetSchema schemaWithoutCat = TestDatasetSchemaBuilder.builder()
.withCategoricalFields(3)
.withNumericalFields(3)
.withStringFields(3)
.build();
assertThat(ValidationUtils.checkNoFieldsOfType(schemaWithoutCat, CategoricalValueSchema.class))
.as("Validation of a schema that has a forbidden field type.")
.isNotEmpty();
}
}
| [
"nuno.diegues@feedzai.com"
] | nuno.diegues@feedzai.com |
4c9ee8092d3c8268c0bfb41bc71d0d9e656114ff | 1a43e3b6826369d14a6d1591f54268516c1c0726 | /JavaEE_Code/day-13/src/com/itheima/day_13/demo_01/Demo_01.java | 76854c35bb3fd94e0cc6ac4c9a7e109a458dbc3d | [] | no_license | Jeremy-Zhang-cn/cn.itcast.naker | 758b1c7bfbeab2cc61f52612a0f21502265a93b8 | b639b957c6bade4940f3f2d62bb513a6243f64a3 | refs/heads/master | 2022-06-22T03:56:59.902627 | 2022-06-17T06:19:35 | 2022-06-17T06:19:35 | 217,838,628 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 627 | java | package com.itheima.day_13.demo_01;
public class Demo_01 {
/*
Lambda表达式
(形参): 相当于一个带形参的方法
->: jdk8的新语法,代表指向
{}: 内部为要执行的代码块
*/
public static void main(String[] args) {
/*
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello");
}
}).start();
以上代码可以通过Lambda表达式简化为下边的代码:
*/
new Thread(() -> {
System.out.println("hello");
}).start();
/*
继续简化之后如下:
new Thread( () -> System.out.println("hello")).start();
*/
}
}
| [
"1159387269@qq.com"
] | 1159387269@qq.com |
686edf72d2cf0b6c7b2b9b53624b66bf392c7f88 | 92eeb41c40309e58c6d96effa0966b77dc5c1cf5 | /src/com/minestom/Spigot/Integrations/LiteBans.java | 993c5ce3307771114a7014e611148c946346e9d5 | [] | no_license | andrewse02/BadBoy | aa1f286194ea5c714afa2faf8766b9742b49c0a8 | d05d83d2c2eed8960698de8743a35ef2d72fb277 | refs/heads/master | 2021-09-08T06:27:18.636442 | 2018-03-07T21:26:48 | 2018-03-07T21:26:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 726 | java | package com.minestom.Spigot.Integrations;
import com.minestom.Discord.Utilities.MessageSender;
import litebans.api.Entry;
import litebans.api.Events;
import org.bukkit.Bukkit;
import java.util.UUID;
public class LiteBans {
public LiteBans(MessageSender messageSender) {
Events.get().register(new Events.Listener() {
@Override
public void entryAdded(Entry entry) {
if (entry.getUuid() == null) return;
UUID uuid = UUID.fromString(entry.getUuid());
messageSender.sendPunishmentMessage(Bukkit.getPlayer(uuid).getName(), entry.getExecutorName(),
entry.getType(), entry.getReason());
}
});
}
}
| [
"tfermin1827@hotmail.com"
] | tfermin1827@hotmail.com |
75761301918b61792966fd944ecd4069a7d4fc64 | 4691ae436558ed0be66f0b9521d3d5e163055f00 | /src/com/businesscharts/data/BCSColumnData.java | eb942a92dd9eac70097ba0afb39b8a2dbc1c54c7 | [] | no_license | KartoshkaMan/BusinesCharts | c41339f092acff70d3749e06e344b690ee304f0f | 44ad22fd293c2f1c7eedace394d6c7d8c3c3967b | refs/heads/master | 2021-01-01T05:01:33.323037 | 2016-05-25T23:45:19 | 2016-05-25T23:45:19 | 59,704,651 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 719 | java | package com.businesscharts.data;
import javax.swing.table.DefaultTableModel;
public class BCSColumnData extends BCColumnData {
/**
* Creates data object for stacked chart
* @param model - def. table model
*/
public BCSColumnData(DefaultTableModel model) {
super(model);
}
/**
* finds and return biggest sum from all rows
* @return biggest sum row
*/
public float getMaxSum() {
float max = 0;
for (int i = 0; i < data.size(); i++) {
float s = 0;
for (int j = 0; j < data.get(i).size(); j++)
s += Math.abs(data.get(i).get(j));
if (s > max) max = s;
}
return max;
}
}
| [
"leshkadolg@gmail.com"
] | leshkadolg@gmail.com |
add6ddd728938195797422e34b3a03558a8f1b47 | dc870e89c8fe357febe56a13ab63441a6d69ad2c | /lab9/src/jspClasses/Constants.java | 659c49c971c248cd64f78bfc8e4e8c413edb26c5 | [] | no_license | MikeArvalor/Internet-Application | c8e42db77521a3b7422b2c1d1ef16cdfaa7ff54b | 3201b69df5bda51c8e6e6eb009c17edeaebe43ff | refs/heads/master | 2023-01-28T20:46:24.164239 | 2020-11-30T15:51:51 | 2020-11-30T15:51:51 | 316,777,222 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 563 | java | package jspClasses;
public class Constants {
public static final String URL1 = "URL1";
public static final String URL2 = "URL2";
public static final String URL_N = "URLn";
public static final String VAL_1 = "val1";
public static final String VAL_2 = "val2";
public static final String VAL_3 = "val3";
public static final String BEAN = "artCBean";
public static final String Ttt_URL = "/Ttt";
public static final String Ccc_URL = "/Ccc";
public static final String PARAMETER_URL_NOT_FOUND = "Parameter Url not found";
}
| [
"mihail14312@mail.ru"
] | mihail14312@mail.ru |
1257da3bb722bbd9ba23b99f18413d05e9d1b1a1 | 2954025c13e82d7c5d121d2604811cb25c00e494 | /src/main/java/com/quantal/exchange/users/enums/EmailType.java | 2bc40d47f7813e0c9318d498d7384800dbb49a42 | [] | no_license | quophyie/quantalex-users | 2e30df71ab690f6541b203d569114097c4f0d0d4 | a3e4db96c71956ac94f7eb2d54c08f23700765de | refs/heads/master | 2021-01-18T09:34:28.538791 | 2019-04-04T13:17:09 | 2019-04-04T13:17:09 | 84,313,862 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 142 | java | package com.quantal.exchange.users.enums;
/**
* Created by root on 12/06/2017.
*/
public enum EmailType {
PasswordReset,
Welcome
}
| [
"quophyie@yahoo.com"
] | quophyie@yahoo.com |
4378a3f460f99975a9b251a3b31209a1642995f0 | e098b054e8c6d3b165319b7cd1b8cc4d710c0960 | /template-spring4/spring4/java_src/${basepackage_dir}/service/${subpackage}/${className}Service.java | 50e4c9a5abf8aa1727ea61b7388ff078ac17ef8a | [] | no_license | liuliko/generate-springboot-vue | e5c1e33abcd3bddb31516047d78613d043df1aa0 | 3ab6934d5ffb28faf4f991e5d36a2651b7889b9a | refs/heads/master | 2022-12-08T09:46:51.283445 | 2020-04-22T09:00:32 | 2020-04-22T09:00:32 | 289,850,361 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 940 | java | <#assign className = table.className>
<#assign classNameLower = className?uncap_first>
package ${basepackage}.service.${subpackage};
import java.util.List;
import ${basepackage}.api.${subpackage}.${className};
import org.springframework.transaction.annotation.Transactional;
public interface ${className}Service {
@Transactional
int deleteByPrimaryKey(String id);
@Transactional
int insert(${className} record);
@Transactional
int insertSelective(${className} record);
@Transactional
int updateByPrimaryKeySelective(${className} record);
@Transactional
int updateByPrimaryKey(${className} record);
${className} selectByPrimaryKey(String id);
List<${className}> selectList(${className} record);
List<${className}> selectPage(${className} record);
@Transactional
int insertByBatch(List<${className}> list);
@Transactional
int deleteByBatch(List<String> list);
} | [
"liuliko@126.com"
] | liuliko@126.com |
85eb8a48d6f36138bc1359aa15454302b6d0520f | aeef520564360ca08b809a2903ce4a0d0ea1d592 | /app/src/main/java/com/email/ui/fragment/RubbishBoxFragment.java | dcd8a17f739db034ad77ae764579689bc2fde123 | [] | no_license | yinzhiyu/EmailDemoY | 7256b0f9cbf093111debab94283ebb6b439be4cc | b899a195ad3a8aa99a2712f8149584a23360f027 | refs/heads/master | 2020-03-07T23:41:57.384382 | 2018-04-26T14:48:22 | 2018-04-26T14:48:22 | 127,787,768 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,269 | java | package com.email.ui.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.application.greendao.MailDao;
import com.email.R;
import com.email.app.BaseApplication;
import com.email.app.BaseFragment;
import com.email.table.Mail;
import com.email.ui.adapter.InboxAdapter;
import com.email.ui.adapter.RubbishAdapter;
import com.email.utils.DividerListItemDecoration;
import com.email.utils.RecyclerViewClickListener;
import com.email.utils.SharePreferenceUtil;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* 垃圾箱
*/
//public class RubbishBoxFragment extends BaseFragment implements OnListener {
public class RubbishBoxFragment extends BaseFragment {
@BindView(R.id.rv_home_recycler)
RecyclerView rvHomeRecycler;
@BindView(R.id.srl_home_swipe_refresh)
SwipeRefreshLayout srlHomeSwipeRefresh;
@BindView(R.id.ll_null)
LinearLayout mLlNull;
private boolean isShowToolbar = true;
//--------------------
private static final int SCROLL_DISTANCE = 50;
private LinearLayoutManager layoutManager;
private boolean isShow = true;
private int totalScrollDistance;
private int pageNum = 1;
private RubbishAdapter mRubbishAdapter;
private int DataNum;
public static RubbishBoxFragment newInstance(String content) {
Bundle args = new Bundle();
args.putString("ARGS", content);
RubbishBoxFragment fragment = new RubbishBoxFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_inbox, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
}
private void initView() {
srlHomeSwipeRefresh.setEnabled(true);
srlHomeSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
pageNum = 1;
getData(pageNum);
}
});
// rvHomeRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
// @Override
// public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// if (newState == RecyclerView.SCROLL_STATE_IDLE) {
// //获取最后一个完全显示的ItemPosition
// int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
// int totalItemCount = layoutManager.getItemCount();
// // 判断是否滚动到底部,并且是向右滚动
// if (lastVisibleItem == (totalItemCount - 1) && !isShow) {// (totalItemCount - 1) && isSlidingToLast
// //加载更多功能的代码
// pageNum++;
// getMore(pageNum);
// }
// }
// }
//
// @Override
// public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
// super.onScrolled(recyclerView, dx, dy);
// int firstVisableItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
// if (firstVisableItem == 0) {
// return;
// }
// if ((dy > 0 && isShow) || (dy < 0 && !isShow)) {
// totalScrollDistance += dy;
// }
// if (totalScrollDistance > SCROLL_DISTANCE && isShow) {
// isShow = false;
// totalScrollDistance = 0;
// } else if (totalScrollDistance < -SCROLL_DISTANCE && !isShow) {
// isShow = true;
// totalScrollDistance = 0;
// }
// }
// });
setLayoutManager();
}
@Override
public void onResume() {
super.onResume();
getData(pageNum);
}
private void getData(int num) {
MailDao smsDao = BaseApplication.getInstance().getDaoSession().getMailDao();
//limit(int) 限制查询返回的数据条数。
//offset(int) 设置查询跳过的条数,offset(int)必须和limit(int)一起使用。
// List<Mail> smsList = smsDao.queryBuilder().where(MailDao.Properties.UsefulType.eq("0")).limit(10).offset(0).build().list();
List<Mail> smsList = smsDao.queryBuilder().where(MailDao.Properties.UsefulType.eq(0)).build().list();
if (srlHomeSwipeRefresh != null) {
srlHomeSwipeRefresh.setRefreshing(false);
}
if (pageNum == 1) {
if (smsList.size() > 0) {
mLlNull.setVisibility(View.GONE);
srlHomeSwipeRefresh.setVisibility(View.VISIBLE);
mRubbishAdapter = new RubbishAdapter(getActivity(), smsList);
rvHomeRecycler.setAdapter(mRubbishAdapter);
} else {
srlHomeSwipeRefresh.setVisibility(View.GONE);
mLlNull.setVisibility(View.VISIBLE);
}
} else {
mRubbishAdapter.notifityData(smsList);
}
}
private void getMore(int num) {
int getNum = num * 10;
if (DataNum > getNum) {
MailDao smsDao = BaseApplication.getInstance().getDaoSession().getMailDao();
//limit(int) 限制查询返回的数据条数。
//offset(int) 设置查询跳过的条数,offset(int)必须和limit(int)一起使用。
List<Mail> smsList = smsDao.queryBuilder().where(MailDao.Properties.UsefulType.eq("0")).limit(10).offset(getNum).build().list();
if (srlHomeSwipeRefresh != null) {
srlHomeSwipeRefresh.setRefreshing(false);
}
mRubbishAdapter.notifityData(smsList);
}else {
Toast.makeText(activity, "我是有底线的...", Toast.LENGTH_SHORT).show();
}
}
private void setLayoutManager() {
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvHomeRecycler.setLayoutManager(layoutManager);
rvHomeRecycler.setItemAnimator(new DefaultItemAnimator());
rvHomeRecycler.setHasFixedSize(true);
rvHomeRecycler.addItemDecoration(new DividerListItemDecoration(getActivity(), R.drawable.shape_divide_line));
}
}
| [
"513792933@qq.com"
] | 513792933@qq.com |
0844c8ae3b03269e6c825075c54798cc129afba7 | a8c41db8a94433075e3133d7a169c47e02418957 | /infosen/android/app/src/debug/java/com/infosen/ReactNativeFlipper.java | 061c17ba423f6b6bc7f958c0a36ef1089f02fe23 | [
"MIT"
] | permissive | schrsistemas/projeto-react-native-desafio_0001 | 230558d904fcfc2e9daae38983b874735fd71fc5 | f2b54bf5120cddc28454840970cb084750125774 | refs/heads/main | 2023-05-31T02:08:41.420114 | 2021-06-11T21:59:13 | 2021-06-11T21:59:13 | 376,145,338 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,262 | java | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.infosen;
import android.content.Context;
import com.facebook.flipper.android.AndroidFlipperClient;
import com.facebook.flipper.android.utils.FlipperUtils;
import com.facebook.flipper.core.FlipperClient;
import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
import com.facebook.flipper.plugins.inspector.DescriptorMapping;
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.network.NetworkingModule;
import okhttp3.OkHttpClient;
public class ReactNativeFlipper {
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (FlipperUtils.shouldEnableFlipper(context)) {
final FlipperClient client = AndroidFlipperClient.getInstance(context);
client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
client.addPlugin(new ReactFlipperPlugin());
client.addPlugin(new DatabasesFlipperPlugin(context));
client.addPlugin(new SharedPreferencesFlipperPlugin(context));
client.addPlugin(CrashReporterPlugin.getInstance());
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
new NetworkingModule.CustomClientBuilder() {
@Override
public void apply(OkHttpClient.Builder builder) {
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
}
});
client.addPlugin(networkFlipperPlugin);
client.start();
// Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
// Hence we run if after all native modules have been initialized
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
if (reactContext == null) {
reactInstanceManager.addReactInstanceEventListener(
new ReactInstanceManager.ReactInstanceEventListener() {
@Override
public void onReactContextInitialized(ReactContext reactContext) {
reactInstanceManager.removeReactInstanceEventListener(this);
reactContext.runOnNativeModulesQueueThread(
new Runnable() {
@Override
public void run() {
client.addPlugin(new FrescoFlipperPlugin());
}
});
}
});
} else {
client.addPlugin(new FrescoFlipperPlugin());
}
}
}
}
| [
"daniel@bytecom.inf.br"
] | daniel@bytecom.inf.br |
b767faaeb94253a4b3b8161d1cafeea88398ab15 | bdc08917c6967c368155ba09f2f878aa5655db1a | /GoJob/src/com/lazysong/test/LoginServlet.java | 6e0be2cd945f976ae6c990d1bdb04e71c417a637 | [] | no_license | htyaizen/GoJob | 9139ce042b426d14ae0a125d1cb8524a22e9de44 | 348e034d835b300f0d205ade211dea9fdbaf6134 | refs/heads/master | 2020-04-09T22:23:48.199469 | 2017-03-28T03:39:58 | 2017-03-28T03:39:58 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 8,641 | java | package com.lazysong.test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lazysong.test.beans.Company;
import com.lazysong.test.beans.Industry_category;
import com.lazysong.test.beans.Mark_com;
import com.lazysong.test.beans.Mark_info;
import com.lazysong.test.beans.Place;
import com.lazysong.test.beans.Resume;
import com.lazysong.test.beans.User;
import com.lazysong.test.beans.Willings;
public class LoginServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
String limit = request.getParameter("limit");
String result;
if (request.getParameter("requestcode") == null) {
return;
}
int requestCode = Integer.parseInt(request.getParameter("requestcode"));
System.out.println(requestCode);
PrintWriter out = response.getWriter();
String sql = null;
RequestMethods rm = new RequestMethods();// 建立RM对象,同时建立与数据库的连接
Object tableType = null;// 声明所需集合类型
String judgeName = null;// 此值为null时,说明result需返回详细结果
// 此值非空时,标明是哪个case需要判断结果集是否存在,以便输出RequestCode中对应字符串
String nullParament = null;
switch (requestCode) {
case RequestCode.USER_EXISTS:
// USER_EXISTS
String user_id = request.getParameter("USER_ID");
if (user_id == null) {
nullParament = ResultCode.USER_EXISTS;
}
sql = rm.getSearchSql("USER", "USER_ID", user_id);
judgeName = ResultCode.USER_EXISTS;
tableType = new User();
break;
case RequestCode.UPLOAD_USER: // UPLOAD_USER
break;
case RequestCode.CAT_BY_CATEGRY: // CAT_BY_CATEGRY
break;
case RequestCode.SEARCH: // SEARCH
break;
case RequestCode.GET_PLACES: // GET_PLACES
sql = rm.getSearchSql("PLACE");
tableType = new Place();
break;
case RequestCode.GET_INDUSTRY: // GET_INDUSTRY
sql = rm.getSearchSql("INDUSTRY_CATEGORY");
tableType = new Industry_category();
break;
case RequestCode.GET_COMPANY: // GET_COMPANY
sql = rm.getSearchSql("COMPANY");
tableType = new Company();
break;
case RequestCode.MARK_POST: // MARK_POST
break;
case RequestCode.UNMARK_POST: // UNMARK_POST
break;
case RequestCode.HIDE_POST:// HIDE_POST
break;
case RequestCode.CAT_USER:// CAT_USER
user_id=request.getParameter("USER_ID");
sql = rm.getSearchSql("USER","USER_ID",user_id);
tableType = new User();
break;
case RequestCode.EDIT_USER:// EDIT_USER
break;
case RequestCode.CAT_RESUME:// CAT_RESUME
user_id = request.getParameter("USER_ID");
sql = rm.getSearchSql("RESUME", "USER_ID", user_id);
tableType = new Resume();
break;
case RequestCode.EDIT_RESUME:// EDIT_RESUME
break;
case RequestCode.CAT_MARK_INFO:// CAT_MARK
user_id = request.getParameter("USER_ID");
sql=rm.getSearchSql("MARK_INFO","USER_ID",user_id);
tableType=new Mark_info();
break;
case RequestCode.CAT_MARK_COM:// CAT_WATCH
sql = rm.getSearchSql("MARK_COM");
tableType = new Mark_com();
break;
case RequestCode.CAT_WILLING:// CAT_WILLING
user_id = request.getParameter("USER_ID");
sql=rm.getSearchSql("MARK_INFO","USER_ID",user_id);
tableType=new Mark_info();
break;
case RequestCode.EDIT_WILLING:// EDIT_WILLING
break;
case RequestCode.WATCH_CMP:// WATCH_CMP
break;
case RequestCode.UNWATCH_CMP:// UNWATCH_CMP
break;
case RequestCode.GET_RECOMAND:// GET_RECOMAND
break;
default:
out.println("Error requestcode");
return;
}
if (limit != null)// 在sql语句添加limit
sql = sql + " limit " + limit;
else
sql = sql + " limit 10";// 到这步SQL语句生成完毕
if (nullParament == null) {
result = rm.getSearchResult(tableType, sql, judgeName);
out.println(result);
out.flush();
out.close();
}else{
out.println(nullParament+"No parament input");
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
// public void doPost(HttpServletRequest request, HttpServletResponse
// response)
// throws ServletException, IOException {
//
// response.setContentType("text/html");
// response.setCharacterEncoding("UTF-8");
// String limit = request.getParameter("limit");
// if (request.getParameter("requestcode") == null) {
// return;
// }
// int requestCode = Integer.parseInt(request.getParameter("requestcode"));
// PrintWriter out = response.getWriter();
// String sql = null;
// RequestMethods rm = new RequestMethods();
// out.println(ResultCode.USER_UNEXISTS);
// switch (requestCode) {
// case RequestCode.USER_EXISTS: // USER_EXISTS
// String user_id = request.getParameter("userid");
// if (rm.user_exists(user_id))
// out.println(ResultCode.USER_EXISTS);
// else
// out.println(ResultCode.USER_UNEXISTS);
// break;
// case RequestCode.UPLOAD_USER: // UPLOAD_USER
// break;
// case RequestCode.CAT_BY_CATEGRY: // CAT_BY_CATEGRY
// break;
// case RequestCode.SEARCH: // SEARCH
// break;
// case RequestCode.GET_PLACES: // GET_PLACES
// String result = rm.get_places();
// out.println(result);
// break;
// case RequestCode.GET_INDUSTRY: // GET_INDUSTRY
// break;
// case RequestCode.GET_COMPANY: // GET_COMPANY
// break;
// case RequestCode.MARK_POST: // MARK_POST
// break;
// case RequestCode.UNMARK_POST: // UNMARK_POST
// break;
// case RequestCode.HIDE_POST:// HIDE_POST
// break;
// case RequestCode.CAT_USER:// CAT_USER
// break;
// case RequestCode.EDIT_USER:// EDIT_USER
// break;
// case RequestCode.CAT_RESUME:// CAT_RESUME
// break;
// case RequestCode.EDIT_RESUME:// EDIT_RESUME
// break;
// case RequestCode.CAT_MARK:// CAT_MARK
// break;
// case RequestCode.CAT_WATCH:// CAT_WATCH
// break;
// case RequestCode.CAT_WILLING:// CAT_WILLING
// break;
// case RequestCode.EDIT_WILLING:// EDIT_WILLING
// break;
// case RequestCode.WATCH_CMP:// WATCH_CMP
// break;
// case RequestCode.UNWATCH_CMP:// UNWATCH_CMP
// break;
// case RequestCode.GET_RECOMAND:// GET_RECOMAND
// break;
// default:
// out.println("Error requestcode");
// break;
// }
// // 关闭RequestMethods的实例化对象
// rm.close();
// // if (limit != null && !limit.isEmpty())
// // out.println(new Demo().query(requestCode,limit));
// // else
// // out.println(new Demo().query(requestCode,"10"));
// out.flush();
// out.close();
// }
// public void doPost(HttpServletRequest request, HttpServletResponse
// response)
// throws ServletException, IOException {
//
// response.setContentType("text/html");
// response.setCharacterEncoding("UTF-8");
// String limit = request.getParameter("limit");
// PrintWriter out = response.getWriter();
// if (limit != null && !limit.isEmpty())
// out.println(new Demo().query(limit));
// else
// out.println(new Demo().query("10"));
// out.flush();
// out.close();
// }
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
| [
"wen292006955@qq.com"
] | wen292006955@qq.com |
660c16dea52bde88cd7ace241d74d4bc1066cb89 | 1e3def18799629c59b359df1c42be9c760abac37 | /app/src/main/java/com/blogspot/blogsetyaaji/moviecatalogue/fragment/FavoriteMovieFragment.java | 7c9b945ca6a12df5cfe3161e2f726a09d0c75d3b | [] | no_license | AjiSetya/Movie_Catalogue_Dicoding_MADE | 1d1fcf8afddd6fcab03c354a9d15dc4a3a87c0ba | f5219f8e8faf10b6123dd00482546b155d15ee00 | refs/heads/master | 2022-02-27T07:01:46.853629 | 2019-09-20T03:31:42 | 2019-09-20T03:31:42 | 194,355,637 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,447 | java | package com.blogspot.blogsetyaaji.moviecatalogue.fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import com.blogspot.blogsetyaaji.moviecatalogue.R;
import com.blogspot.blogsetyaaji.moviecatalogue.activity.DetailActivity;
import com.blogspot.blogsetyaaji.moviecatalogue.adapter.FavoriteMovieAdapter;
import com.blogspot.blogsetyaaji.moviecatalogue.adapter.MovieAdapter;
import com.blogspot.blogsetyaaji.moviecatalogue.db.MovieHelper;
import com.blogspot.blogsetyaaji.moviecatalogue.model.movie.MovieItem;
import java.lang.ref.WeakReference;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class FavoriteMovieFragment extends Fragment implements LoadMoviesCallback {
private ProgressBar pgFavMovie;
private MovieHelper movieHelper;
private FavoriteMovieAdapter favoriteMovieAdapter;
private static final String EXTRA_STATE = "EXTRA_STATE";
public FavoriteMovieFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return getView() != null ? getView() :
inflater.inflate(R.layout.fragment_favorite_movie, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView rvFavMovie = view.findViewById(R.id.rv_fav_movie);
rvFavMovie.setLayoutManager(new LinearLayoutManager(getActivity()));
rvFavMovie.setHasFixedSize(true);
pgFavMovie = view.findViewById(R.id.pg_fav_movie);
movieHelper = MovieHelper.getInstance(getActivity());
try {
movieHelper.open();
} catch (SQLException e) {
e.printStackTrace();
}
favoriteMovieAdapter = new FavoriteMovieAdapter(getActivity());
rvFavMovie.setAdapter(favoriteMovieAdapter);
favoriteMovieAdapter.setOnItemClickCallback(new FavoriteMovieAdapter.OnItemClickCallback() {
@Override
public void onItemClicked(MovieItem data) {
showSelectedMovie(data);
}
});
if (savedInstanceState == null) {
Log.d("favoritemovie", "onViewCreated: saved instance kosong");
new LoadMoviesAsync(movieHelper, this).execute();
} else {
Log.d("favoritemovie", "onViewCreated: saved instance ada");
ArrayList<MovieItem> list = savedInstanceState.getParcelableArrayList(EXTRA_STATE);
if (list != null) {
favoriteMovieAdapter.setListMovies(list);
}
}
}
private void showSelectedMovie(MovieItem movie) {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra(DetailActivity.KEY_DETAIL_DATA, movie);
intent.putExtra(DetailActivity.KEY_JENIS_DATA, "movie");
startActivity(intent);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(EXTRA_STATE, favoriteMovieAdapter.getListMovies());
}
@Override
public void preExecute() {
new Runnable() {
@Override
public void run() {
pgFavMovie.setVisibility(View.VISIBLE);
}
};
Log.d("favoritemovie", "preExecute: masuk");
}
@Override
public void postExecute(ArrayList<MovieItem> movieItems) {
pgFavMovie.setVisibility(View.INVISIBLE);
favoriteMovieAdapter.setListMovies(movieItems);
Log.d("favoritemovie", "postExecute: " + movieItems.toString());
}
private class LoadMoviesAsync extends AsyncTask<Void, Void, ArrayList<MovieItem>> {
private final WeakReference<MovieHelper> movieHelperWeakReference;
private final WeakReference<LoadMoviesCallback> moviesCallbackWeakReference;
LoadMoviesAsync(MovieHelper movieHelper, LoadMoviesCallback loadMoviesCallback) {
movieHelperWeakReference = new WeakReference<>(movieHelper);
moviesCallbackWeakReference = new WeakReference<>(loadMoviesCallback);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
moviesCallbackWeakReference.get().preExecute();
}
@Override
protected ArrayList<MovieItem> doInBackground(Void... voids) {
return movieHelperWeakReference.get().getAllMovies();
}
@Override
protected void onPostExecute(ArrayList<MovieItem> movieItems) {
super.onPostExecute(movieItems);
moviesCallbackWeakReference.get().postExecute(movieItems);
}
}
@Override
public void onDestroy() {
super.onDestroy();
movieHelper.close();
}
}
| [
"setyaaji07@gmail.com"
] | setyaaji07@gmail.com |
ae687f08115c5679cf3962c34ccf1c7781d37a4c | 41c365f19edca9c2e66d8261eea1b0f59016461b | /src/main/java/cn/ming/pojo/User.java | 44deae5a63c44a01f9921ed143e157739795dd2e | [] | no_license | mingyh/springboot-swagger | a157677c3dde32287a6ede1745b97486cd182932 | de098e64aabccd3eb260a49a918e9705ff09edbc | refs/heads/master | 2022-11-30T09:57:29.877361 | 2020-08-17T12:20:57 | 2020-08-17T12:20:57 | 288,172,353 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 328 | java | package cn.ming.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Created by ASUS on 2020/8/15.
*/
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("密码")
public String password;
}
| [
"741168715@qq.com"
] | 741168715@qq.com |
431e12d3c32e386cc8e34926f5167d9cb78d8e66 | bac67feb33a4778c67ab6efeb820e4fe46382607 | /src/collections/hashtablemap/Freq.java | e6d47c05918994446e337f877352c266e6eb90e4 | [] | no_license | mithun3/JavaCollections | 0452e75005378dc60b25fedf3e23b985483bb48e | 69ad4d18df94cb021883e2d1b269790c08d5c284 | refs/heads/master | 2020-05-20T11:39:46.514615 | 2014-10-31T09:07:29 | 2014-10-31T09:07:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 386 | java | package collections.hashtablemap;
import java.util.Map;
import java.util.TreeMap;
public class Freq {
private static final Integer ONE = new Integer(1);
public static void main(String args[]) {
Map m = new TreeMap();
m.put("a Key", "a Value");
m.put("Java2s", "www.java2s.com");
System.out.println(m.size() + " keys detected:");
System.out.println(m);
}
} | [
"mithun3@gmail.com"
] | mithun3@gmail.com |
8beab9d2b0d6535e34201c6956240c35421199db | bfb02cdc5b046dd201fcfc0549d88bb2f8125344 | /base_code/src/gen/java/io/swagger/api/ListApi.java | 715b241c37dbb7bd98ab8ef03fbb33987816cad1 | [] | no_license | mythre/to_do_list_backend | e4308a25ad468c11964182aa7b34e632a3c2de0b | d17e259d0b118bf5fc05ac555e08c31195f0b6d8 | refs/heads/master | 2023-05-14T11:16:34.869407 | 2020-05-21T08:42:58 | 2020-05-21T08:42:58 | 265,198,695 | 0 | 0 | null | 2021-06-07T18:46:59 | 2020-05-19T09:06:16 | Java | UTF-8 | Java | false | false | 7,185 | java | package io.swagger.api;
import io.swagger.model.*;
import io.swagger.api.ListApiService;
import io.swagger.api.factories.ListApiServiceFactory;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.model.Body;
import io.swagger.model.Body1;
import io.swagger.model.Body2;
import io.swagger.model.InlineResponse200;
import io.swagger.model.InlineResponse2001;
import io.swagger.model.InlineResponse400;
import java.util.Map;
import java.util.List;
import io.swagger.api.NotFoundException;
import java.io.InputStream;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import javax.servlet.ServletConfig;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.*;
import javax.validation.constraints.*;
@Path("/list")
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaJerseyServerCodegen", date = "2020-05-19T08:47:32.084Z[GMT]")public class ListApi {
private final ListApiService delegate;
public ListApi(@Context ServletConfig servletContext) {
ListApiService delegate = null;
if (servletContext != null) {
String implClass = servletContext.getInitParameter("ListApi.implementation");
if (implClass != null && !"".equals(implClass.trim())) {
try {
delegate = (ListApiService) Class.forName(implClass).newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
if (delegate == null) {
delegate = ListApiServiceFactory.getListApi();
}
this.delegate = delegate;
}
@GET
@Path("/{userId}")
@Produces({ "application/json" })
@Operation(summary = "", description = "", tags={ })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successful response", content = @Content(schema = @Schema(implementation = InlineResponse200.class))),
@ApiResponse(responseCode = "400", description = "Invalid userid", content = @Content(schema = @Schema(implementation = InlineResponse400.class))),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content(schema = @Schema(implementation = InlineResponse400.class))) })
public Response listUserIdGet(@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("userId") Integer userId
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.listUserIdGet(userId,securityContext);
}
@POST
@Path("/{userId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@Operation(summary = "", description = "", tags={ })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Saved successfully", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))),
@ApiResponse(responseCode = "500", description = "Error in adding notes", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))) })
public Response listUserIdPost(@Parameter(in = ParameterIn.DEFAULT, description = "List of to dos to be added" ,required=true) Body body
,@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("userId") Integer userId
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.listUserIdPost(body,userId,securityContext);
}
@DELETE
@Path("/{userId}/todo/{taskId}")
@Produces({ "application/json" })
@Operation(summary = "", description = "", tags={ })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Tasks deleted successfully", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))),
@ApiResponse(responseCode = "500", description = "Error in deleting the task", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))) })
public Response listUserIdTodoTaskIdDelete(@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("userId") Integer userId
,@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("taskId") List<Integer> taskId
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.listUserIdTodoTaskIdDelete(userId,taskId,securityContext);
}
@PATCH
@Path("/{userId}/todo/{taskId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@Operation(summary = "", description = "", tags={ })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Task status updated successfully", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))),
@ApiResponse(responseCode = "500", description = "Error in updating status of task", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))) })
public Response listUserIdTodoTaskIdPatch(@Parameter(in = ParameterIn.DEFAULT, description = "To dos content to be updated as completed" ,required=true) Body2 body
,@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("userId") Integer userId
,@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("taskId") Integer taskId
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.listUserIdTodoTaskIdPatch(body,userId,taskId,securityContext);
}
@PUT
@Path("/{userId}/todo/{taskId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@Operation(summary = "", description = "", tags={ })
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Updated successfully", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))),
@ApiResponse(responseCode = "500", description = "Error in updating notes", content = @Content(schema = @Schema(implementation = InlineResponse2001.class))) })
public Response listUserIdTodoTaskIdPut(@Parameter(in = ParameterIn.DEFAULT, description = "To dos content to be updated" ,required=true) Body1 body
,@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("userId") Integer userId
,@Parameter(in = ParameterIn.PATH, description = "",required=true) @PathParam("taskId") Integer taskId
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.listUserIdTodoTaskIdPut(body,userId,taskId,securityContext);
}
}
| [
"mythreyi1509@gmail.com"
] | mythreyi1509@gmail.com |
ee7b975f877c8d03c9f779e317241d8893004b80 | 7f4cc02dd0745fb302322f8dec945b25704b5cfa | /src/com/marcos/decorator/starbuzz/beverages/App.java | c3c2bbbf0f6e9ee83601964c6b1cead2bc8df03d | [] | no_license | MarkosAndres/design-patterns | 059b0221b4b418d576ab624edfb12c477ab294b6 | 6a30e53906bc3c35cc2b90614812eecf618d3721 | refs/heads/master | 2023-03-20T14:13:26.223659 | 2021-03-13T03:21:23 | 2021-03-13T03:21:23 | 347,258,969 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 314 | java | package com.marcos.decorator.starbuzz.beverages;
import com.marcos.decorator.starbuzz.extras.Mocha;
import com.marcos.decorator.starbuzz.extras.Whip;
public class App {
public static void main(String[] args) {
Whip whip = new Whip(new Mocha(new DarkRoast()));
System.out.println("Cost: "+whip.cost());
}
} | [
"mlerin@digitalairstrike.com"
] | mlerin@digitalairstrike.com |
f8e24b34747340abf64690e6b9a76c3c3a55b3f4 | a6a878f70380d3d8b9990eb640f5f1a1021be3ae | /src/main/java/com/bill/cookbook/Main3Activity.java | 00867b3d47b9c2241273d41f2129238c406a2e0f | [] | no_license | Bilmosh/WebView | b87ed01f5b2214aaef2f7fe66835cc3f3550d11f | a2fd97d294779f3d0fbe60aed456236d0cd9bbec | refs/heads/master | 2021-01-01T06:39:38.671345 | 2017-07-17T13:25:25 | 2017-07-17T13:25:25 | 97,476,917 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 578 | java | package com.bill.cookbook;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Button;
public class Main3Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
WebView weeeb = (WebView) findViewById(R.id.webview8);
weeeb.loadUrl("file:///android_asset/view.html");
// Button next = (Button) findViewById(R.id.buttonid);
}
}
| [
"bilmosh104@gmail.com"
] | bilmosh104@gmail.com |
4301436c573094c8523959afce6a98cb61f4801c | 7ea6460affa5b2a2fdb7099d393eb977d08122d4 | /OntologicalFramework/src/ontologyFramework/OFProcedureManagment/OFProcedureImplementation/Task2UpdaterAcc.java | f4d5ce1a819188d09378009f515f122722a8c536 | [] | no_license | buoncubi/OntologyFramework | 4daa2e4132ed3039be5ecab2345bffd293e1173c | 211bc56ad3ae731584ee83fa0806ff7b0deae963 | refs/heads/master | 2021-01-10T12:57:01.904626 | 2016-11-04T23:51:00 | 2016-11-04T23:51:00 | 43,822,117 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,951 | java | package ontologyFramework.OFProcedureManagment.OFProcedureImplementation;
import java.util.ArrayList;
import java.util.List;
import ontologyFramework.OFErrorManagement.OFDebugLogger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class Task2UpdaterAcc extends OFJobAbstract{
private static final double epsilon = 90;
public static final boolean infNorm = false; // false --> 2norm
public static final double spatioalSupportX = 51.0;
public static final double spatioalSupportY = 1.0;
public static final double spatioalSupportZ = 16.0;
public static final List< Double> thX = new ArrayList< Double>();
public static final List< Double> thY = new ArrayList< Double>();
public static final List< Double> thZ = new ArrayList< Double>();
static{
thX.add( 1.5740); thX.add( 1.7392);
thY.add( 1.9650); thY.add( 2.1871);
thZ.add( 1.2313); thZ.add( 1.4711);
}
public static final String thisOntoName = "task2Ontology";
private static OFDebugLogger logger = new OFDebugLogger( Task2UpdaterAcc.class, true);
private static boolean initialised = false;
private static TaskUpdaterAccellerometer task;
private static Integer timeOfRecognition = 0;
@Override
void runJob(JobExecutionContext context) throws JobExecutionException {
if( ! initialised){
List< Double> spatialSupport = new ArrayList< Double>( 3);
spatialSupport.add( spatioalSupportX);
spatialSupport.add( spatioalSupportY);
spatialSupport.add( spatioalSupportZ);
List< List< Double>> treshoulds = new ArrayList< List< Double>>(3);
treshoulds.add( thX);
treshoulds.add( thY);
treshoulds.add( thZ);
task = new TaskUpdaterAccellerometer( spatialSupport,
treshoulds, epsilon, infNorm, thisOntoName, this.getProcedureIndividualName(),
this.getOWLOntologyRefeferences(), logger);
} else initialised = true;
timeOfRecognition = task.updateState( timeOfRecognition);
}
}
| [
"luca.buoncompagni@edu.unige.it"
] | luca.buoncompagni@edu.unige.it |
7e5eaa8d054bab1f6e0d25c7f6a28ebb01ea3f67 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_8d7e9a853958335ef46410fa9e02087baeefa541/AbstractCursor/20_8d7e9a853958335ef46410fa9e02087baeefa541_AbstractCursor_s.java | c444e652d3814cdd41411d837feaa22b17da1d95 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 26,521 | java | /*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde 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 net.hydromatic.optiq.runtime;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.sql.*;
import java.sql.Date;
import java.util.*;
/**
* Base class for implementing a cursor.
*
* <p>Derived class needs to provide {@link Getter} and can override
* {@link Accessor} implementations if it wishes.</p>
*
* @author jhyde
*/
public abstract class AbstractCursor implements Cursor {
private static final int MILLIS_PER_DAY = 86400000;
private static final Calendar LOCAL_CALENDAR = Calendar.getInstance();
/**
* Slot into which each accessor should write whether the
* value returned was null.
*/
protected final boolean[] wasNull = {false};
protected AbstractCursor() {
}
public List<Accessor> createAccessors(List<ColumnMetaData> types) {
List<Accessor> accessors = new ArrayList<Accessor>();
for (ColumnMetaData type : types) {
accessors.add(createAccessor(type, accessors.size()));
}
return accessors;
}
protected Accessor createAccessor(ColumnMetaData type, int ordinal) {
// Create an accessor appropriate to the underlying type; the accessor
// can convert to any type in the same family.
Getter getter = createGetter(ordinal);
switch (type.type) {
case Types.TINYINT:
return new ByteAccessor(getter);
case Types.SMALLINT:
return new ShortAccessor(getter);
case Types.INTEGER:
return new IntAccessor(getter);
case Types.BIGINT:
return new LongAccessor(getter);
case Types.BOOLEAN:
return new BooleanAccessor(getter);
case Types.FLOAT:
case Types.REAL:
return new FloatAccessor(getter);
case Types.DOUBLE:
return new DoubleAccessor(getter);
case Types.DECIMAL:
return new BigDecimalAccessor(getter);
case Types.CHAR:
return new FixedStringAccessor(getter, type.displaySize);
case Types.VARCHAR:
return new StringAccessor(getter);
case Types.BINARY:
case Types.VARBINARY:
return new BinaryAccessor(getter);
case Types.DATE:
switch (Rep.of(type.internalClass)) {
case PRIMITIVE_INT:
return new DateFromIntAccessor(getter);
case JAVA_SQL_DATE:
return new DateAccessor(getter);
default:
throw new AssertionError("bad " + type.internalClass);
}
case Types.TIME:
switch (Rep.of(type.internalClass)) {
case PRIMITIVE_INT:
return new TimeFromIntAccessor(getter);
case JAVA_SQL_TIME:
return new TimeAccessor(getter);
default:
throw new AssertionError("bad " + type.internalClass);
}
case Types.TIMESTAMP:
switch (Rep.of(type.internalClass)) {
case PRIMITIVE_LONG:
return new TimestampFromLongAccessor(getter);
case JAVA_SQL_TIMESTAMP:
return new TimestampAccessor(getter);
case JAVA_UTIL_DATE:
return new TimestampFromUtilDateAccessor(getter);
default:
throw new AssertionError("bad " + type.internalClass);
}
case Types.JAVA_OBJECT:
case Types.ARRAY:
case Types.STRUCT:
case Types.OTHER: // e.g. map
return new ObjectAccessor(getter);
default:
throw new RuntimeException("unknown type " + type.type);
}
}
protected abstract Getter createGetter(int ordinal);
public abstract boolean next();
static class AccessorImpl implements Accessor {
protected final Getter getter;
public AccessorImpl(Getter getter) {
this.getter = getter;
}
public String getString() {
final Object o = getObject();
return o == null ? null : o.toString();
}
public boolean getBoolean() {
throw cannotConvert("boolean");
}
public byte getByte() {
throw cannotConvert("byte");
}
public short getShort() {
throw cannotConvert("short");
}
public int getInt() {
throw cannotConvert("int");
}
public long getLong() {
throw cannotConvert("long");
}
public float getFloat() {
throw cannotConvert("float");
}
public double getDouble() {
throw cannotConvert("double");
}
public BigDecimal getBigDecimal() {
throw cannotConvert("BigDecimal");
}
public BigDecimal getBigDecimal(int scale) {
throw cannotConvert("BigDecimal with scale");
}
public byte[] getBytes() {
throw cannotConvert("byte[]");
}
public Date getDate() {
return getDate(null);
}
public Time getTime() {
return getTime(null);
}
public Timestamp getTimestamp() {
return getTimestamp(null);
}
public InputStream getAsciiStream() {
throw cannotConvert("InputStream (ascii)");
}
public InputStream getUnicodeStream() {
throw cannotConvert("InputStream (unicode)");
}
public InputStream getBinaryStream() {
throw cannotConvert("InputStream (binary)");
}
public Object getObject() {
return getter.getObject();
}
public Reader getCharacterStream() {
throw cannotConvert("Reader");
}
private RuntimeException cannotConvert(String targetType) {
return new RuntimeException("cannot convert to " + targetType);
}
public Object getObject(Map<String, Class<?>> map) {
throw cannotConvert("Object (with map)");
}
public Ref getRef() {
throw cannotConvert("Ref");
}
public Blob getBlob() {
throw cannotConvert("Blob");
}
public Clob getClob() {
throw cannotConvert("Clob");
}
public Array getArray() {
throw cannotConvert("Array");
}
public Date getDate(Calendar cal) {
throw cannotConvert("Date");
}
public Time getTime(Calendar cal) {
throw cannotConvert("Time");
}
public Timestamp getTimestamp(Calendar cal) {
throw cannotConvert("Timestamp");
}
public URL getURL() {
throw cannotConvert("URL");
}
public NClob getNClob() {
throw cannotConvert("NClob");
}
public SQLXML getSQLXML() {
throw cannotConvert("SQLXML");
}
public String getNString() {
throw cannotConvert("NString");
}
public Reader getNCharacterStream() {
throw cannotConvert("NCharacterStream");
}
public <T> T getObject(Class<T> type) {
throw cannotConvert("Object (with type)");
}
}
/**
* Accessor of exact numeric values. The subclass must implement the
* {@link #getLong()} method.
*/
private static abstract class ExactNumericAccessor extends AccessorImpl {
public ExactNumericAccessor(Getter getter) {
super(getter);
}
public BigDecimal getBigDecimal(int scale) {
final long v = getLong();
return v == 0 && getter.wasNull()
? null
: BigDecimal.valueOf(v)
.setScale(scale, RoundingMode.DOWN);
}
public BigDecimal getBigDecimal() {
final long val = getLong();
return val == 0 && getter.wasNull()
? null
: BigDecimal.valueOf(val);
}
public double getDouble() {
return getLong();
}
public float getFloat() {
return getLong();
}
public abstract long getLong();
public int getInt() {
return (int) getLong();
}
public short getShort() {
return (short) getLong();
}
public byte getByte() {
return (byte) getLong();
}
public boolean getBoolean() {
return getLong() != 0d;
}
}
/**
* Accessor that assumes that the underlying value is a {@link Boolean};
* corresponds to {@link java.sql.Types#BOOLEAN}.
*/
private static class BooleanAccessor extends ExactNumericAccessor {
public BooleanAccessor(Getter getter) {
super(getter);
}
public boolean getBoolean() {
Boolean o = (Boolean) getObject();
return o != null && o;
}
public long getLong() {
return getBoolean() ? 1 : 0;
}
}
/**
* Accessor that assumes that the underlying value is a {@link Byte};
* corresponds to {@link java.sql.Types#TINYINT}.
*/
private static class ByteAccessor extends ExactNumericAccessor {
public ByteAccessor(Getter getter) {
super(getter);
}
public byte getByte() {
Byte o = (Byte) getObject();
return o == null ? 0 : o;
}
public long getLong() {
return getByte();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Short};
* corresponds to {@link java.sql.Types#SMALLINT}.
*/
private static class ShortAccessor extends ExactNumericAccessor {
public ShortAccessor(Getter getter) {
super(getter);
}
public short getShort() {
Short o = (Short) getObject();
return o == null ? 0 : o;
}
public long getLong() {
return getShort();
}
}
/**
* Accessor that assumes that the underlying value is an {@link Integer};
* corresponds to {@link java.sql.Types#INTEGER}.
*/
private static class IntAccessor extends ExactNumericAccessor {
public IntAccessor(Getter getter) {
super(getter);
}
public int getInt() {
Integer o = (Integer) super.getObject();
return o == null ? 0 : o;
}
public long getLong() {
return getInt();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Long};
* corresponds to {@link java.sql.Types#BIGINT}.
*/
private static class LongAccessor extends ExactNumericAccessor {
public LongAccessor(Getter getter) {
super(getter);
}
public long getLong() {
Long o = (Long) super.getObject();
return o == null ? 0 : o;
}
}
/**
* Accessor of values that are {@link Double} or null.
*/
private static abstract class ApproximateNumericAccessor
extends AccessorImpl
{
public ApproximateNumericAccessor(Getter getter) {
super(getter);
}
public BigDecimal getBigDecimal(int scale) {
final double v = getDouble();
return v == 0d && getter.wasNull()
? null
: BigDecimal.valueOf(v)
.setScale(scale, RoundingMode.DOWN);
}
public BigDecimal getBigDecimal() {
final double v = getDouble();
return v == 0 && getter.wasNull() ? null : BigDecimal.valueOf(v);
}
public abstract double getDouble();
public float getFloat() {
return (float) getDouble();
}
public long getLong() {
return (long) getDouble();
}
public int getInt() {
return (int) getDouble();
}
public short getShort() {
return (short) getDouble();
}
public byte getByte() {
return (byte) getDouble();
}
public boolean getBoolean() {
return getDouble() != 0;
}
}
/**
* Accessor that assumes that the underlying value is a {@link Float};
* corresponds to {@link java.sql.Types#FLOAT}.
*/
private static class FloatAccessor extends ApproximateNumericAccessor {
public FloatAccessor(Getter getter) {
super(getter);
}
public float getFloat() {
Float o = (Float) getObject();
return o == null ? 0f : o;
}
public double getDouble() {
return getFloat();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Float};
* corresponds to {@link java.sql.Types#FLOAT}.
*/
private static class DoubleAccessor extends ApproximateNumericAccessor {
public DoubleAccessor(Getter getter) {
super(getter);
}
public double getDouble() {
Double o = (Double) getObject();
return o == null ? 0d : o;
}
}
/**
* Accessor of exact numeric values. The subclass must implement the
* {@link #getLong()} method.
*/
private static abstract class BigNumberAccessor extends AccessorImpl {
public BigNumberAccessor(Getter getter) {
super(getter);
}
protected abstract Number getNumber();
public double getDouble() {
Number number = getNumber();
return number == null ? 0d : number.doubleValue();
}
public float getFloat() {
Number number = getNumber();
return number == null ? 0f : number.floatValue();
}
public long getLong() {
Number number = getNumber();
return number == null ? 0l : number.longValue();
}
public int getInt() {
Number number = getNumber();
return number == null ? 0 : number.intValue();
}
public short getShort() {
Number number = getNumber();
return number == null ? 0 : number.shortValue();
}
public byte getByte() {
Number number = getNumber();
return number == null ? 0 : number.byteValue();
}
public boolean getBoolean() {
Number number = getNumber();
return number != null && number.doubleValue() != 0;
}
}
/**
* Accessor that assumes that the underlying value is a {@link BigDecimal};
* corresponds to {@link java.sql.Types#DECIMAL}.
*/
private static class BigDecimalAccessor extends BigNumberAccessor {
public BigDecimalAccessor(Getter getter) {
super(getter);
}
protected Number getNumber() {
return (Number) getObject();
}
public BigDecimal getBigDecimal(int scale) {
return (BigDecimal) getObject();
}
public BigDecimal getBigDecimal() {
return (BigDecimal) getObject();
}
}
/**
* Accessor that assumes that the underlying value is a {@link String};
* corresponds to {@link java.sql.Types#CHAR} and {@link java.sql.Types#VARCHAR}.
*/
private static class StringAccessor extends AccessorImpl {
public StringAccessor(Getter getter) {
super(getter);
}
public String getString() {
return (String) getObject();
}
}
/**
* Accessor that assumes that the underlying value is a {@link String};
* corresponds to {@link java.sql.Types#CHAR}.
*/
private static class FixedStringAccessor extends StringAccessor {
private final Spacer spacer;
public FixedStringAccessor(Getter getter, int length) {
super(getter);
this.spacer = new Spacer(length);
}
public String getString() {
String s = super.getString();
if (s == null) {
return null;
}
return spacer.padRight(s);
}
}
/**
* Accessor that assumes that the underlying value is an array of
* {@code byte} values;
* corresponds to {@link java.sql.Types#BINARY} and {@link java.sql.Types#VARBINARY}.
*/
private static class BinaryAccessor extends AccessorImpl {
public BinaryAccessor(Getter getter) {
super(getter);
}
public byte[] getBytes() {
return (byte[]) getObject();
}
@Override
public String getString() {
byte[] bytes = getBytes();
return bytes == null ? null : ByteString.toString(bytes);
}
}
/**
* Accessor that assumes that the underlying value is a DATE,
* in its default representation {@code int};
* corresponds to {@link java.sql.Types#DATE}.
*/
private static class DateFromIntAccessor extends IntAccessor {
public DateFromIntAccessor(Getter getter) {
super(getter);
}
@Override
public Object getObject() {
return getDate();
}
@Override
public Date getDate(Calendar calendar) {
int vv = getInt();
if (vv == 0 && getter.wasNull()) {
return null;
}
long v = (long) vv * MILLIS_PER_DAY;
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new java.sql.Date(v);
}
@Override
public String getString() {
return getDate(LOCAL_CALENDAR).toString();
}
}
/**
* Accessor that assumes that the underlying value is a Time,
* in its default representation {@code int};
* corresponds to {@link java.sql.Types#TIME}.
*/
private static class TimeFromIntAccessor extends IntAccessor {
public TimeFromIntAccessor(Getter getter) {
super(getter);
}
@Override
public Object getObject() {
return getTime();
}
@Override
public Time getTime(Calendar calendar) {
int v = getInt();
if (v == 0 && getter.wasNull()) {
return null;
}
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new Time(v);
}
@Override
public String getString() {
return getTime(LOCAL_CALENDAR).toString();
}
}
/**
* Accessor that assumes that the underlying value is a TIMESTAMP,
* in its default representation {@code long};
* corresponds to {@link java.sql.Types#TIMESTAMP}.
*/
private static class TimestampFromLongAccessor extends LongAccessor {
public TimestampFromLongAccessor(Getter getter) {
super(getter);
}
@Override
public Object getObject() {
return getTimestamp();
}
@Override
public Timestamp getTimestamp(Calendar calendar) {
long v = getLong();
if (v == 0L && getter.wasNull()) {
return null;
}
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new Timestamp(v);
}
@Override
public String getString() {
return getTimestamp(LOCAL_CALENDAR).toString();
}
}
/**
* Accessor that assumes that the underlying value is a DATE,
* represented as a java.sql.Date;
* corresponds to {@link java.sql.Types#DATE}.
*/
private static class DateAccessor extends ObjectAccessor {
public DateAccessor(Getter getter) {
super(getter);
}
@Override
public Date getDate(Calendar calendar) {
java.sql.Date date = (Date) getObject();
if (date == null) {
return null;
}
if (calendar != null) {
long v = date.getTime();
v -= calendar.getTimeZone().getOffset(v);
date = new Date(v);
}
return date;
}
@Override
public String getString() {
return getDate(LOCAL_CALENDAR).toString();
}
}
/**
* Accessor that assumes that the underlying value is a TIME,
* represented as a java.sql.Time;
* corresponds to {@link java.sql.Types#TIME}.
*/
private static class TimeAccessor extends ObjectAccessor {
public TimeAccessor(Getter getter) {
super(getter);
}
@Override
public Time getTime(Calendar calendar) {
Time date = (Time) getObject();
if (date == null) {
return null;
}
if (calendar != null) {
long v = date.getTime();
v -= calendar.getTimeZone().getOffset(v);
date = new Time(v);
}
return date;
}
@Override
public String getString() {
return getTime(LOCAL_CALENDAR).toString();
}
}
/**
* Accessor that assumes that the underlying value is a TIMESTAMP,
* represented as a java.sql.Timestamp;
* corresponds to {@link java.sql.Types#TIMESTAMP}.
*/
private static class TimestampAccessor extends ObjectAccessor {
public TimestampAccessor(Getter getter) {
super(getter);
}
@Override
public Timestamp getTimestamp(Calendar calendar) {
Timestamp date = (Timestamp) getObject();
if (date == null) {
return null;
}
if (calendar != null) {
long v = date.getTime();
v -= calendar.getTimeZone().getOffset(v);
date = new Timestamp(v);
}
return date;
}
@Override
public String getString() {
return getTimestamp(LOCAL_CALENDAR).toString();
}
}
/**
* Accessor that assumes that the underlying value is a TIMESTAMP,
* represented as a java.util.Date;
* corresponds to {@link java.sql.Types#TIMESTAMP}.
*/
private static class TimestampFromUtilDateAccessor extends ObjectAccessor {
public TimestampFromUtilDateAccessor(Getter getter) {
super(getter);
}
@Override
public Timestamp getTimestamp(Calendar calendar) {
java.util.Date date = (java.util.Date) getObject();
if (date == null) {
return null;
}
long v = date.getTime();
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new Timestamp(v);
}
@Override
public String getString() {
return getTimestamp(LOCAL_CALENDAR).toString();
}
}
/**
* Accessor that assumes that the underlying value is an OBJECT;
* corresponds to {@link java.sql.Types#JAVA_OBJECT}.
*/
private static class ObjectAccessor extends AccessorImpl {
public ObjectAccessor(Getter getter) {
super(getter);
}
}
protected interface Getter {
Object getObject();
boolean wasNull();
}
enum Rep {
PRIMITIVE_BOOLEAN(boolean.class),
PRIMITIVE_BYTE(byte.class),
PRIMITIVE_CHAR(char.class),
PRIMITIVE_SHORT(short.class),
PRIMITIVE_INT(int.class),
PRIMITIVE_LONG(long.class),
PRIMITIVE_FLOAT(float.class),
PRIMITIVE_DOUBLE(double.class),
BOOLEAN(Boolean.class),
BYTE(Byte.class),
CHARACTER(Character.class),
SHORT(Short.class),
INTEGER(Integer.class),
LONG(Long.class),
FLOAT(Float.class),
DOUBLE(Double.class),
JAVA_SQL_TIME(Time.class),
JAVA_SQL_TIMESTAMP(Timestamp.class),
JAVA_SQL_DATE(java.sql.Date.class),
JAVA_UTIL_DATE(java.util.Date.class);
private final Class clazz;
Rep(Class clazz) {
this.clazz = clazz;
}
static Rep[] values = values();
static Rep of(Class clazz) {
for (Rep rep : values) {
if (rep.clazz == clazz) {
return rep;
}
}
throw new IllegalArgumentException("no Rep for " + clazz);
}
}
}
// End AbstractCursor.java
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
c47aca69d3cf6251deff871653d6480a50f8964e | 483bc9910ff9e4eceb80ac52ce920cc7fa33d3c6 | /app/src/main/java/com/andromeda/kunalbhatia/demo/hungamaplayer/MediaItem.java | 6feca05e4e53d739002d9a24d1cca11fc3c68ff9 | [] | no_license | vicky7230/videoplayer_using_exoplayer | b7ab8224ed1ce3325e20b1aede48c26bf1920394 | fb53ed402199a213c2217b95067652d2f386fb87 | refs/heads/master | 2021-01-19T17:22:39.920384 | 2016-10-26T06:21:04 | 2016-10-26T06:21:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,260 | java | package com.andromeda.kunalbhatia.demo.hungamaplayer;
import android.os.Bundle;
import java.util.ArrayList;
/**
* Created by kunal.bhatia on 10/4/2016.
*/
public class MediaItem {
private String mTitle;
private String mSubTitle;
private String mStudio;
private String mUrl;
private String mContentType;
private int mDuration;
private ArrayList<String> mImageList = new ArrayList<String>();
public static final String KEY_TITLE = "title";
public static final String KEY_SUBTITLE = "subtitle";
public static final String KEY_STUDIO = "studio";
public static final String KEY_URL = "movie-urls";
public static final String KEY_IMAGES = "images";
public static final String KEY_CONTENT_TYPE = "content-type";
public String getUrl() {
return mUrl;
}
public void setUrl(String url) {
mUrl = url;
}
public String getTitle() {
return mTitle;
}
public int getDuration() {
return mDuration;
}
public void setDuration(int duration) {
mDuration = duration;
}
public String getContentType() {
return mContentType;
}
public void setContentType(String contentType) {
mContentType = contentType;
}
public void setTitle(String title) {
mTitle = title;
}
public String getSubTitle() {
return mSubTitle;
}
public void setSubTitle(String subTitle) {
mSubTitle = subTitle;
}
public String getStudio() {
return mStudio;
}
public void setStudio(String studio) {
mStudio = studio;
}
public void addImage(String url) {
mImageList.add(url);
}
public void addImage(String url, int index) {
if (index < mImageList.size()) {
mImageList.set(index, url);
}
}
public String getImage(int index) {
if (index < mImageList.size()) {
return mImageList.get(index);
}
return null;
}
public boolean hasImage() {
return !mImageList.isEmpty();
}
public ArrayList<String> getImages() {
return mImageList;
}
public Bundle toBundle() {
Bundle wrapper = new Bundle();
wrapper.putString(KEY_TITLE, mTitle);
wrapper.putString(KEY_SUBTITLE, mSubTitle);
wrapper.putString(KEY_URL, mUrl);
wrapper.putString(KEY_STUDIO, mStudio);
wrapper.putStringArrayList(KEY_IMAGES, mImageList);
wrapper.putString(KEY_CONTENT_TYPE, "video/mp4");
return wrapper;
}
public static final MediaItem fromBundle(Bundle wrapper) {
if (null == wrapper) {
return null;
}
MediaItem media = new MediaItem();
media.setUrl(wrapper.getString(KEY_URL));
media.setTitle(wrapper.getString(KEY_TITLE));
media.setSubTitle(wrapper.getString(KEY_SUBTITLE));
media.setStudio(wrapper.getString(KEY_STUDIO));
media.mImageList.addAll(wrapper.getStringArrayList(KEY_IMAGES));
media.setContentType(wrapper.getString(KEY_CONTENT_TYPE));
return media;
}
}
| [
"kmasterzone@gmail.com"
] | kmasterzone@gmail.com |
d769a150bae56bcb910e080b41e2f820beb29013 | 5ce58291fac29a134ea02fa42e54d96f62adf2a6 | /src/base/BaseStep.java | 6b6f11e442bf54a0dcc8c18b4c0bd1c6460f5106 | [] | no_license | cwxb105/DailySisyphus | 9dcd8757594c3e7214b0c4287428c80574fa25ce | d8e958bd81bf35d4f7877bd3599420ae73db80a2 | refs/heads/master | 2021-01-12T20:48:02.935385 | 2014-02-11T10:37:41 | 2014-02-11T10:37:41 | 17,164,381 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 803 | java | package base;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public abstract class BaseStep {
protected final Log logger = LogFactory.getLog(this.getClass());
private static ThreadLocal<HashMap<String, Object>> storyContext = new ThreadLocal<HashMap<String, Object>>();
protected void setParameter(String name, Object value) {
HashMap<String, Object> context = storyContext.get();
if (context == null) {
context = new HashMap<String, Object>();
storyContext.set(context);
}
context.put(name, value);
}
protected Object getParameter(String name) {
HashMap<String, Object> context = storyContext.get();
if (context != null)
return context.get(name);
else
return null;
}
}
| [
"taojintianxia@126.com"
] | taojintianxia@126.com |
5581e7420396c4a17be5059d11da7a7b6b99a4d1 | 611b1a3f55f0a21a1395aa531444f02450177a02 | /src/march/practice/StepickAlgorithms/DifferentComponents.java | 9e7bfdf097824c93c770efc6aed127769c0eef79 | [] | no_license | Zhurava-Skarabahataya/Training | fb4d6ae8234020ecad5aadf0f83893f38d978fae | 9cd1fa4b9ed2bcd3177db30aa54eb18091ff428f | refs/heads/master | 2021-04-01T07:45:07.339018 | 2020-05-05T06:16:14 | 2020-05-05T06:16:14 | 248,169,151 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,238 | java | package march.practice.StepickAlgorithms;
import java.util.ArrayList;
import java.util.Scanner;
public class DifferentComponents {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextInt();
ArrayList<Long> components = findComponents(n);
System.out.println(components.size());
for (Long component : components) {
System.out.print(component + " ");
}
}
private static ArrayList<Long> findComponents(long n) {
ArrayList<Long> componenets = new ArrayList<>();
if (n == 2) {
componenets.add(2L);
return componenets;
}
long minimalComponent = 1;
while (true) {
if (n > minimalComponent) {
if ((1.0 * n / minimalComponent) > 2) {
componenets.add(minimalComponent);
n -= minimalComponent;
minimalComponent++;
} else {
componenets.add(n);
break;
}
} else {
componenets.add(minimalComponent);
break;
}
}
return componenets;
}
}
| [
"zhurova1994@gmail.com"
] | zhurova1994@gmail.com |
2953ca41000ba2c1d7f9ee4eb6a9bfe6f93507ff | cc81c6d5c55ae80eb4f6e52b9a34a305e441db2e | /src/main/java/com/eden/fxmvc/mvc/action/ActionInvocation.java | 01d9ef65dacad0e037707b0a7c2dfd9d59e15a74 | [] | no_license | chengpan168/Fxmvc | df7dc5f6e56ed333741a712ad2c5a85b605868ac | 8a0acaf1d516f9a0897c8b8f844f334cf43f1b70 | refs/heads/master | 2020-05-17T17:40:22.364105 | 2013-11-20T01:31:51 | 2013-11-20T01:31:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,424 | java | package com.eden.fxmvc.mvc.action;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.eden.fxmvc.context.AppContext;
import com.eden.fxmvc.mvc.annotation.ViewMapper;
import com.eden.fxmvc.mvc.interceptor.InterceptorChain;
import com.eden.fxmvc.ui.ModelAndView;
import com.eden.fxmvc.util.LogUtils;
@Component
public class ActionInvocation {
@Resource
private InterceptorChain interceptorChain ;
public ModelAndView invoke(ActionContext context) {
try {
//reset the interceptors
interceptorChain.reset() ;
ModelAndView mv = interceptorChain.intercept(context, interceptorChain) ;
if(mv!= null) {
return mv ;
}
return mv ;
} catch (Exception e) {
LogUtils.log4Error("execute action error ", e ) ;
}
return null ;
}
public ModelAndView executeAction(ActionContext context) throws Exception{
BaseAction action = AppContext.getBean(context.getPath()) ;
if(action != null && action instanceof BaseAction ) {
ModelAndView mv = action.execute(context.getActionMessage()) ;
ViewMapper vm = action.getClass().getDeclaredMethod("execute", ActionMessage.class).getAnnotation(ViewMapper.class) ;
if(mv != null && vm!= null ) {
String pane = vm.value() ;
mv.setViewName(pane) ;
mv.setViewTarget(vm.target()) ;
}
return mv ;
}
return null;
}
}
| [
"eden@company-PC"
] | eden@company-PC |
4d53e9f86370f33b9b3c0f61503459e38833b59d | 7e03726a356fe2eeb36ec42a5f3443db659f66c9 | /geu-cca/geu-cca-core/src/main/java/com/geu/aem/cca/core/models/HeaderModel.java | 9b326397565c51fa9348e292f9d88760faf7f66e | [] | no_license | vcarchitha/geu | 77f45955096464b244ecb0155823b87f20871439 | 48114040ae1ff91a7783fb8dfaee1aca8ffb828a | refs/heads/master | 2020-03-25T13:36:36.005764 | 2018-08-07T07:58:53 | 2018-08-07T07:58:53 | 143,834,838 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,931 | java | package com.geu.aem.cca.core.models;
import java.util.ArrayList;
import java.util.Iterator;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.jcr.AccessDeniedException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.Source;
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import org.apache.sling.models.annotations.injectorspecific.ScriptVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.designer.Style;
import com.geu.aem.cca.beans.LinkBean;
import com.geu.aem.cca.constants.ResourceConstants;
import com.geu.aem.cca.services.GroupConfigService;
import com.geu.aem.cca.util.GEUCCAUtils;
/**
* @author aimen.sania
*
*/
@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class HeaderModel {
@Inject
@Source("script-bindings")
private Style currentStyle;
@ScriptVariable
private Page currentPage;
@Inject
private ResourceResolver resourceResolver;
@ScriptVariable
private ValueMap properties;
@OSGiService
private GroupConfigService groupConfigService;
private boolean typeOfUser;
private boolean loggedInUser;
private String userID;
private ArrayList<LinkBean> topNavList = new ArrayList<LinkBean>();
protected final static Logger log = LoggerFactory
.getLogger(HeaderModel.class);
/**
* post construct method to set loggedUser,topNavList
*/
@SuppressWarnings("restriction")
@PostConstruct
public void init() {
String[] configGroup = groupConfigService.getGroupPrefix();
Session session = this.resourceResolver.adaptTo(Session.class);
this.userID = session.getUserID().toString();
this.loggedInUser = getLoggedInSession(session, userID, configGroup);
this.topNavList = getNavigationList();
}
/**
* @param session
* @param userID
* @param configGroup
* @return loggedUser
*/
private Boolean getLoggedInSession(Session session, String userID,
String[] configGroup) {
Boolean loggedInUser = false;
UserManager userManager;
try {
if (StringUtils.isNotBlank(userID)) {
userManager = ((JackrabbitSession) session).getUserManager();
Authorizable user = userManager.getAuthorizable(userID);
if (!user.isGroup()) {
Iterator<Group> groupList = user.memberOf();
if (null != groupList) {
while (groupList.hasNext()) {
Group group = groupList.next();
String groupName = group.getID().toString();
for (String configGroupItem : configGroup) {
if (groupName.startsWith(configGroupItem
.toString())) {
if (configGroupItem
.equals("geu-cca-admins")) {
typeOfUser = true;
} else {
typeOfUser = false;
}
loggedInUser = true;
break;
}
}
}
}
}
}
} catch (AccessDeniedException e) {
// TODO Auto-generated catch block
log.error("Error in HeaderModel -" + e.getMessage());
} catch (UnsupportedRepositoryOperationException e) {
// TODO Auto-generated catch block
log.error("Error in HeaderModel -" + e.getMessage());
} catch (RepositoryException e) {
// TODO Auto-generated catch block
log.error("Error in HeaderModel -" + e.getMessage());
}
return loggedInUser;
}
/**
* @param startLevel
* @return navList
*/
private ArrayList<LinkBean> getNavigationList() {
ArrayList<LinkBean> navList = new ArrayList<LinkBean>();
try {
Iterator<Page> childPages = currentPage.getAbsoluteParent(2)
.listChildren();
if (null != childPages) {
while (childPages.hasNext()) {
Page page = (Page) childPages.next();
ValueMap valuemap = page.getProperties();
String hideInNav = valuemap.get("hideInNav", "false");
if (!currentPage.equals(page)) {
if (!hideInNav.equals("true")) {
navList.add(new LinkBean(page.getTitle(), page
.getPath()
+ ResourceConstants.HTML_EXTENSION));
}
}
}
}
} catch (Exception exception) {
log.error("Error in HeaderModel -" + exception.getMessage());
}
return navList;
}
/**
* @return pageList
*/
public ArrayList<LinkBean> getPageList() {
return topNavList;
}
/**
* @return homeLogo
*/
public String getHomeLogo() {
return currentStyle.get("homeLogo", String.class);
}
/**
* @return homeURL
*/
public String getHomeURL() {
if (loggedInUser) {
if (currentPage.getPath().toString().contains("formpage.html")) {
return currentPage.getPath().toString()
+ ResourceConstants.HTML_EXTENSION;
} else {
return GEUCCAUtils.linkTransformer(currentStyle.get("homeURL",
String.class));
}
} else {
return currentPage.getPath().toString()
+ ResourceConstants.HTML_EXTENSION;
}
}
/**
* @return userID
*/
public String getUserID() {
return userID;
}
/**
* @return logoutLabel
*/
public String getLogoutLabel() {
return currentStyle.get("logoutLabel", String.class);
}
/**
* @return loggedUser
*/
public boolean getLoggedInUser() {
return loggedInUser;
}
public boolean isTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(boolean typeOfUser) {
this.typeOfUser = typeOfUser;
}
} | [
"archithavc.vc@gmail.com"
] | archithavc.vc@gmail.com |
7cf91195c89b566da065ad276a6e36efc3de0f61 | d0e579d694137545a70be3850a214b94989eb73a | /RoboRace/app/src/main/java/vishal/roborace/RoboParticipantss.java | 7790f8bdf8dfe09758e3f7b00227d19e1891a602 | [] | no_license | VishalSheth4/robo-race | ea3135a3fd47cd4ed1e8d527f75c2fa5699c0542 | 5b0ccac6e6796552966deed6f21d71ce91e8c3d1 | refs/heads/master | 2020-04-20T08:34:33.982002 | 2019-02-01T18:40:04 | 2019-02-01T18:40:04 | 168,743,341 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,940 | java | package vishal.roborace;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class RoboParticipantss extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_robo_participantss);
//
// Button adddata = (Button)findViewById(R.id.add_data);
final DatabaseHandler db = new DatabaseHandler(this);
//-----------------------------Time--------------------------
TextView tv = ((TextView)findViewById(R.id.textView4));
tv.setText(getIntent().getStringExtra("total_time"));
final String s = tv.getText().toString();
//-----------------------NAME------------------------------------
// EditText name1 = (EditText)findViewById(R.id.name);
// final String roboparticipants = name1.getText().toString();
// adddata.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Log.d("Insert: ", "Inserting ..");
// db.addContact(new RoboParticipants(roboparticipants,s));
//
// }
// });
// Inserting robopart......
//
// db.addContact(new RoboParticipants("Ravi", "9100000000"));
// db.addContact(new RoboParticipants("Srinivas", "9199999999"));
// db.addContact(new RoboParticipants("Tommy", "9522222222"));
// db.addContact(new RoboParticipants("Karthik", "9533333333"));
// Reading all contacts
// Log.d("Reading: ", "Reading all contacts..");
// List<RoboParticipants> contacts = db.getAllContacts();
//
// for (RoboParticipants cn : contacts) {
// String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
// // Writing Contacts to log
// Log.d("Name: ", log);
// }
}
} | [
"vishalsheth4@gmail.com"
] | vishalsheth4@gmail.com |
0aba8867ab91a91bdf3a7ff3e387467584a297c9 | a7bcc9dd874ee271b94fa002cde99637e79617de | /src/main/java/util/DataBaseCreator.java | 2a75854bc2dedb394bfec0f7c84d6f8f7134107f | [] | no_license | vvolodja/hiber_3.1 | a1c7734a30d8aa2845efabf297bfa23634bf4ee8 | a33ae2ad4aa8ba471129bc268e690f7e26f47041 | refs/heads/master | 2020-06-30T11:02:11.876237 | 2016-11-22T21:54:21 | 2016-11-22T21:54:21 | 74,378,359 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 94 | java | package util;
/**
* Created by vladimir on 20/11/16.
*/
public class DataBaseCreator {
}
| [
"vladimir@MacBook-Pro-Vladimir.local"
] | vladimir@MacBook-Pro-Vladimir.local |
a097d4819da831bdec550711d7a143a6e015fc2d | 175cd60676635a80a6fcbfa0ec506cc9dbcfb5da | /app/src/main/java/com/safety/android/safety/PhotoGallery/PhotoGalleryFragment.java | ff5b9c2108a518c622df5ccfc6fe976fe22ac27a | [] | no_license | wangruiwangrui/Safety | f69a77389a8cf75c1f86b3d87ce8fb81b66a3199 | cc8ec75a7d1faff6b3ad5e7a34cb94bc03f094dd | refs/heads/master | 2020-05-02T17:49:03.767405 | 2019-03-27T14:20:41 | 2019-03-27T14:20:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,631 | java | package com.safety.android.safety.PhotoGallery;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import com.safety.android.safety.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class PhotoGalleryFragment extends Fragment {
private static final String TAG = "PhotoGalleryFragment";
private RecyclerView mPhotoRecyclerView;
private List<GalleryItem> mItems = new ArrayList<>();
public static PhotoGalleryFragment newInstance() {
return new PhotoGalleryFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
new FetchItemsTask().execute();
Log.i(TAG,"Background thread started");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
mPhotoRecyclerView = (RecyclerView) v
.findViewById(R.id.fragment_photo_gallery_recycler_view);
updatePhotoView();
return v;
}
@Override
public void onDestroyView(){
super.onDestroyView();
}
@Override
public void onDestroy(){
super.onDestroy();
}
private void setupAdapter() {
if (isAdded()) {
mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
}
}
private class PhotoHolder extends RecyclerView.ViewHolder {
private ImageView mItemImageView;
public PhotoHolder(View itemView) {
super(itemView);
mItemImageView = (ImageView) itemView.findViewById(R.id.fragment_photo_gallery_image_view);
}
public void bindDrawable(Drawable drawable){
mItemImageView.setImageDrawable(drawable);
}
}
private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder> {
private List<GalleryItem> mGalleryItems;
public PhotoAdapter(List<GalleryItem> galleryItems) {
mGalleryItems = galleryItems;
}
@Override
public PhotoHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
LayoutInflater inflater= LayoutInflater.from(getActivity());
View view=inflater.inflate(R.layout.gallery_item,viewGroup,false);
return new PhotoHolder(view);
}
@Override
public void onBindViewHolder(PhotoHolder photoHolder, int position) {
GalleryItem galleryItem = mGalleryItems.get(position);
Drawable placeholder=getResources().getDrawable(R.drawable.ic_menu_gallery);
photoHolder.bindDrawable(placeholder);
Picasso.with(getActivity()).load(galleryItem.getUrl()).placeholder(placeholder).error(R.mipmap.ic_launcher).into(photoHolder.mItemImageView);
}
@Override
public int getItemCount() {
return mGalleryItems.size();
}
}
private void updatePhotoView(){
ViewTreeObserver observer=mPhotoRecyclerView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int w,h;
@Override
public void onGlobalLayout() {
mPhotoRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
w=mPhotoRecyclerView.getMeasuredWidth();
h=mPhotoRecyclerView.getMeasuredHeight();
if(w/h>=2){
mPhotoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),5));
}else {
mPhotoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
}
}
});
}
private class FetchItemsTask extends AsyncTask<Void,Void,List<GalleryItem>> {
@Override
protected List<GalleryItem> doInBackground(Void... params) {
return new FlickrFetchr().fetchItems();
}
@Override
protected void onPostExecute(List<GalleryItem> items) {
mItems = items;
setupAdapter();
}
}
}
| [
"2768911783@qq.com"
] | 2768911783@qq.com |
f56ad22d47af682a4d8fce40031cbaa6daf14d01 | cb97e412a32851d77f021e23696000dcd2fc1998 | /src/main/java/com/ljw/hibernate/test/HibernateTest2.java | 0f3c545bc2853b90c4310608d7e94422c4a26ed0 | [] | no_license | ljwaly/single-hibernate | 66d118dc7ade7e36826aacab4003197791e742fb | a13534e4e11fce8f81f2649c5f36080d91b3180c | refs/heads/master | 2020-03-22T17:04:26.429697 | 2018-07-10T03:14:06 | 2018-07-10T03:14:06 | 140,370,804 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,741 | java | package com.ljw.hibernate.test;
import org.hibernate.Session;
import org.junit.Test;
import com.ljw.hibernate.domain2.Customer2;
import com.ljw.hibernate.domain2.Order;
import com.ljw.hibernate.util.HibernateUtil;
public class HibernateTest2 {
/*
* 双向关联保存
*/
@Test
public void testSave(){
Session session = HibernateUtil.openSession();
session.beginTransaction();
Customer2 customer = new Customer2();
customer.setName("kebi");
Order order =new Order();
order.setName("dengken");
// 双向建立关系
customer.getOrders().add(order);
order.setCustomer(customer);
// 必须同时保存两个对象,否则数据库不会进行保存处理
session.save(order);
session.save(customer);
session.getTransaction().commit();
session.close();
}
@Test
public void testSave2(){
Session session = HibernateUtil.openSession();
session.beginTransaction();
Customer2 customer = new Customer2();
customer.setName("剑圣");
Order o1=new Order();
o1.setName(customer.getName()+"的订单1");
Order o2=new Order();
o2.setName(customer.getName()+"的订单2");
Order o3=new Order();
o3.setName(customer.getName()+"的订单3");
Order o4=new Order();
o4.setName(customer.getName()+"的订单3");
// 当级联保存的时候,当我们在Customer.hbm.xml中设置了级联关系的时候,
// 那么在设置关系的时候,只需要向Customer的orders集合中添加Order,就可以进行级联保存
customer.getOrders().add(o1);
customer.getOrders().add(o2);
customer.getOrders().add(o3);
customer.getOrders().add(o4);
session.save(customer);
session.getTransaction().commit();
session.close();
}
@Test
public void testDelete() {
Session session = HibernateUtil.openSession();
session.beginTransaction();
// 删除多方
// Order o1 = new Order();
// o1.setId(17);
// session.delete(o1);
// 删除一方:如果一方是一个脱管态对象,那么先将多方的外键置空(解除关系),然后在删除
// Customer c1 = new Customer();
// c1.setId(8);
// 删除一方:一方是一个持久态对象,也是先解除关系,然后在删除
// 问题:如果客户都不存在了,那么这个订单还有存在的意义吗?
// 答:订单的存在已经没有意义了,所以说我们可以通过级联删除,
// 在删除Customer的时候,自动删除与Customer相关的order
Customer2 c1 = (Customer2) session.get(Customer2.class, 3);
session.delete(c1);
session.getTransaction().commit();
session.close();
}
}
| [
"sh1025462978@sina.com"
] | sh1025462978@sina.com |
980809e4636268e7aba6398703668907e1e85bdc | 1c7a5ea43d98a5f2f5c6371c66209d9921dceb7d | /idlegame/app/src/main/java/com/ualr/idlegame/fragments/interfaces/OnProgressViewHolder.java | f9f920062161f20db3b21c1cd41eece52a6c51df | [] | no_license | agjaeger/mobile-apps-final | 16308441b25410fd28dd31128e348a905bfc7a57 | 635dd0657cef4a7d2121954c5ec2e920efff036e | refs/heads/master | 2020-09-22T05:56:01.318882 | 2019-12-09T02:07:53 | 2019-12-09T02:07:53 | 225,076,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 154 | java | package com.ualr.idlegame.fragments.interfaces;
public interface OnProgressViewHolder {
public void onComplete (String[] resource, int increment);
}
| [
"agjaeger@ualr.edu"
] | agjaeger@ualr.edu |
339706f97faa8acdc2889d85dec1b50c195a02e2 | e232c648e389fe5501a09bc5460818dbba1dc837 | /app/src/main/java/cn/linkfeeling/hankserve/constants/LinkConstant.java | c263e8091cf6cd5684be01d55c0b7bd0a5b7f86c | [] | no_license | aoklink/hank | 79e60849d9d82860baa92c030bf5cb1bbc44c176 | 95d3e6fe9feeacbc56feafddc3ead5736363be4c | refs/heads/master | 2020-09-20T20:22:27.470645 | 2019-06-11T01:35:47 | 2019-06-11T01:35:47 | 224,581,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 380 | java | package cn.linkfeeling.hankserve.constants;
/**
* @author create by zhangyong
* @time 2019/3/27
*/
public class LinkConstant {
public static final int INTERVAL_TIME=1;
public static class PermissionConstants{
public static final int REQUEST_CODE_PERMISSION_LOCATION = 0x200;
public static final int REQUEST_CODE_PERMISSION_WRITE = 0x201;
}
}
| [
"yong.zhang@linkfeeling.cn"
] | yong.zhang@linkfeeling.cn |
d616382f703d30a12dbd0a79a36b4b4d1000fb7e | 1ec73a5c02e356b83a7b867580a02b0803316f0a | /java/bj/DesignPattern/JavaAndPattern/LISKOV/VERSION4/ImmutableSquare.java | 6cb4d5b05eb8c18b213cdaf510413bfef07d0b0d | [] | no_license | jxsd0084/JavaTrick | f2ee8ae77638b5b7654c3fcf9bceea0db4626a90 | 0bb835fdac3c2f6d1a29d1e6e479b553099ece35 | refs/heads/master | 2021-01-20T18:54:37.322832 | 2016-06-09T03:22:51 | 2016-06-09T03:22:51 | 60,308,161 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 483 | java | package bj.DesignPattern.JavaAndPattern.LISKOV.VERSION4;
public class ImmutableSquare extends Rectangle {
private long side;
public void setWidth( long width ) {
// setSide(width);
}
public long getWidth() {
return getSide();
}
public void setHeight( long height ) {
// setSide(height);
}
public long getHeight() {
return getSide();
}
public long getSide() {
return side;
}
public void setSide( long side ) {
// this.side = side;
}
}
| [
"chenlong88882001@163.com"
] | chenlong88882001@163.com |
0852d3402b506aa1bdc4d9be474e2deda7d0878d | 5a10a1d4954da61a00fcba22eba97089db23e352 | /shop/com/enation/javashop/widget/member/MemberMessageWidget.java | e65f2a802d8a9595223ddcf9118010d0f10cadce | [] | no_license | jianganglu/NC | f994dbbb196665167c03c30f5e7973449bc8ab7a | 7267ddf78d7c78efa936da3ea0125d1bb0377526 | refs/heads/master | 2021-01-18T00:30:21.719668 | 2015-07-12T12:53:54 | 2015-07-12T12:53:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,801 | java | package com.enation.javashop.widget.member;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.enation.app.base.core.model.Member;
import com.enation.app.base.core.model.Message;
import com.enation.eop.sdk.user.IUserService;
import com.enation.eop.sdk.user.UserServiceFactory;
import com.enation.eop.sdk.widget.AbstractWidget;
import com.enation.framework.context.webcontext.ThreadContextHolder;
import com.enation.framework.database.Page;
import com.enation.framework.util.StringUtil;
import com.enation.javashop.core.service.IMemberManager;
import com.enation.javashop.core.service.IMessageManager;
/**
* 短信息挂件
*
* @author kingapex
*
*/
public class MemberMessageWidget extends AbstractMemberWidget {
private IMessageManager messageManager;
private IMemberManager memberManager;
protected void config(Map<String, String> params) {
}
protected void display(Map<String, String> params) {
HttpServletRequest request = ThreadContextHolder.getHttpRequest();
action = action == null ? "" : action;
if (action.equals("inbox")) {
this.setPageName("message_inbox");
String page = request.getParameter("page");
page = (page == null || page.equals("")) ? "1" : page;
int pageSize = 10;
Page inboxPage = this.messageManager.pageMessage(
Integer.valueOf(page), pageSize, "inbox");
Long totalCount = inboxPage.getTotalCount();
Long pageCount = inboxPage.getTotalPageCount();
List inboxList = (List) inboxPage.getResult();
inboxList = inboxList == null ? new ArrayList() : inboxList;
this.putData("totalCount", totalCount);
this.putData("pageSize", pageSize);
this.putData("page", page);
this.putData("inboxList", inboxList);
this.putData("pageCount", pageCount);
} else if (action.equals("outbox")) {
this.setPageName("message_outbox");
String page = request.getParameter("page");
page = (page == null || page.equals("")) ? "1" : page;
int pageSize = 10;
Page outboxPage = this.messageManager.pageMessage(
Integer.valueOf(page), pageSize, "outbox");
Long totalCount = outboxPage.getTotalCount();
Long pageCount = outboxPage.getTotalPageCount();
List outboxList = (List) outboxPage.getResult();
outboxList = outboxList == null ? new ArrayList() : outboxList;
this.putData("totalCount", totalCount);
this.putData("pageSize", pageSize);
this.putData("page", page);
this.putData("outboxList", outboxList);
this.putData("pageCount", pageCount);
} else if (action.equals("send")) {
this.setPageName("message_send");
} else if (action.equals("sendSave")) {
IUserService userService = UserServiceFactory.getUserService();
Member member = userService.getCurrentMember();
Message message = new Message();
message.setFrom_id(member.getMember_id());
message.setMsg_from(member.getUname());
String subject = request.getParameter("subject");
message.setSubject(subject);
String msg = request.getParameter("message");
message.setMessage(msg);
message.setDate_line((new Date()).getTime());
String msg_to = request.getParameter("msg_to");
msg_to = msg_to.replace(" ", ",");
String[] msg_to_array = msg_to.split(",");
String returnmessage = "";
try {
for (String uname : msg_to_array) {
Member m = memberManager.getMemberByUname(uname);
if (m != null) {
message.setTo_id(m.getMember_id());
message.setMsg_to(m.getUname());
messageManager.addMessage(message);
returnmessage += "[" + uname + "] ";
}
}
this.showSuccess("消息已发送给" + returnmessage, "发送消息",
"member_message.html?action=send");
} catch (Exception e) {
if (this.logger.isDebugEnabled()) {
logger.error(e.getStackTrace());
}
this.showError("发送失败", "发送消息",
"member_message.html?action=send");
}
} else if (action.equals("indel")) {
String[] ids = request.getParameterValues("delete");
try {
messageManager.delinbox(StringUtil.arrayToString(ids, ","));
this.showSuccess("删除成功", "收件箱",
"member_message.html?action=inbox");
} catch (Exception e) {
if (this.logger.isDebugEnabled()) {
logger.error(e.getStackTrace());
}
this.showError("删除失败", "收件箱",
"member_message.html?action=inbox");
}
} else if (action.equals("outdel")) {
String[] ids = request.getParameterValues("delete");
try {
messageManager.deloutbox(StringUtil.arrayToString(ids, ","));
this.showSuccess("删除成功", "发件箱",
"member_message.html?action=outbox");
} catch (Exception e) {
if (this.logger.isDebugEnabled()) {
logger.error(e.getStackTrace());
}
this.showError("删除失败", "发件箱",
"member_message.html?action=outbox");
}
} else if (action.equals("reply")) {
this.setPageName("message_reply");
String msg_to = request.getParameter("msg_to");
String subject = request.getParameter("subject");
this.putData("msg_to", StringUtil.to(msg_to, "utf-8"));
this.putData("subject", StringUtil.to(subject, "utf-8"));
} else if (action.equals("read")) {
this.putData("json", "{message:'ok'}");
this.setPageName("json");
Message m = new Message();
String msg_id = request.getParameter("msg_id");
messageManager.setMessage_read(Integer.valueOf(msg_id));
}
}
public IMessageManager getMessageManager() {
return messageManager;
}
public void setMessageManager(IMessageManager messageManager) {
this.messageManager = messageManager;
}
public IMemberManager getMemberManager() {
return memberManager;
}
public void setMemberManager(IMemberManager memberManager) {
this.memberManager = memberManager;
}
}
| [
"378476772@qq.com"
] | 378476772@qq.com |
8012264f1790fe08ef8019f0577ca0ab7cd8a7c4 | d35e3da61c9655999e55cfb6c17f2423d11c3133 | /feature/src/main/java/com/example/administrator/app1/feature/MainActivity.java | 8df0ce2bea937f8164861f6c142833a7d9115892 | [] | no_license | Rambo1416/App1 | a62f762236c129ddf34b7d0f5e91a2b0f518f32c | 17947dab7cbf7730a0e3e2c5f22ac94842b8282a | refs/heads/master | 2020-05-17T10:26:07.667760 | 2019-04-26T15:47:12 | 2019-04-26T15:47:12 | 183,656,828 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 351 | java | package com.example.administrator.app1.feature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"tomrambaud@hotmail.com"
] | tomrambaud@hotmail.com |
22e3ec478f455c53e868c6dea508182c3dcbcad9 | 082e26b011e30dc62a62fae95f375e4f87d9e99c | /docs/weixin_7.0.4_source/反编译源码/未反混淆/src/main/java/com/tencent/mm/plugin/appbrand/jsapi/j/g.java | f48e252ad57cca1b15c11fd61a1b9d77f406f9b8 | [] | 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 | 245 | java | package com.tencent.mm.plugin.appbrand.jsapi.j;
import com.tencent.mm.plugin.appbrand.jsapi.p;
public final class g extends p {
public static final int CTRL_INDEX = 519;
public static final String NAME = "onVoIPChatSpeakersChanged";
}
| [
"alwangsisi@163.com"
] | alwangsisi@163.com |
2380a08907db41f6ee7a9f730e1c91559aa4e0b2 | 51614300bc6e6970fb3fcc261c55ce6b3b2f944c | /app/src/main/java/com/example/lightdance/takemyadvice/model/usercenter/history/HistoryLogic.java | 5dcabfc700b6553eaddb1c301d70ff248d702c71 | [] | no_license | TakeMyAdviceAppProject/TakeMyAdvice | 6353b5767162ea8b8c44696eca85927a06d4c0ff | 5c94749ef835cfd087792c96f0c2fe20f13df247 | refs/heads/master | 2021-09-07T13:34:39.969206 | 2018-02-23T16:46:19 | 2018-02-23T16:46:19 | 120,053,553 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 311 | java | package com.example.lightdance.takemyadvice.model.usercenter.history;
/**
* 历史记录(足迹)实现类
* @author LightDance
* @date 2018/2/5.
*/
public class HistoryLogic implements HistoryInterface {
@Override
public void getHistoryById(String userId, OperateListener listener) {
}
}
| [
"773617349@qq.com"
] | 773617349@qq.com |
c7007c80d38d032c4593206553c3c1bde6d5d789 | a39c8853dc872d4833a21c6c71937097edda58cd | /src/main/java/com/prode/dto/UISaveFixtureDTO.java | 4131db12938bf2a758b554e51be5caee6586208c | [] | no_license | arielfr/prodeBrasil2014 | 96ecfe6c040cfc98869f91302485d2945b3b56d6 | 42f3ea2f7006771c6727d7bf6a95564ef1c5984a | refs/heads/master | 2021-01-18T14:49:28.602462 | 2018-05-30T18:23:48 | 2018-05-30T18:23:48 | 18,305,476 | 0 | 0 | null | 2014-05-05T20:08:25 | 2014-03-31T19:35:00 | Java | UTF-8 | Java | false | false | 1,153 | java | package com.prode.dto;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class UISaveFixtureDTO implements Serializable{
private static final long serialVersionUID = 1L;
Long groupId;
Long matchId;
Long teamAId;
Long teamBId;
int teamA_Result;
int teamB_Result;
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public Long getMatchId() {
return matchId;
}
public void setMatchId(Long matchId) {
this.matchId = matchId;
}
public Long getTeamAId() {
return teamAId;
}
public void setTeamAId(Long teamAId) {
this.teamAId = teamAId;
}
public Long getTeamBId() {
return teamBId;
}
public void setTeamBId(Long teamBId) {
this.teamBId = teamBId;
}
public int getTeamA_Result() {
return teamA_Result;
}
public void setTeamA_Result(int teamA_Result) {
this.teamA_Result = teamA_Result;
}
public int getTeamB_Result() {
return teamB_Result;
}
public void setTeamB_Result(int teamB_Result) {
this.teamB_Result = teamB_Result;
}
}
| [
"ariel.rey@openenglish.com"
] | ariel.rey@openenglish.com |
c021816b40186044de2a59b00dddbbfb1cb6052a | 50701795515f6c028a5ad30f08d1f826f4ec9c7b | /turn_right/src/bot/Map.java | ce7cbd6cac791557ce182b95d9df20208c5b9836 | [] | no_license | lleclech/PFA-Nethack-teamB | bf392f5c93ed31f3d45cc3f99efd80d4d287af44 | d355cb3febb6ebbd9a41c3ddc09715518643880b | refs/heads/master | 2021-01-19T08:10:55.144311 | 2013-04-09T09:48:25 | 2013-04-09T09:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,280 | java | package bot;
public class Map {
private Position myPosition;
private Square[][] content;
public Map(char[][] map) throws UnknownPositionException{
content = new Square[map.length][map[0].length];
for (int line = 0; line < map.length ; line++){
for (int column = 0; column < map[line].length; column++){
char c = map[line][column];
if (c == '@')
myPosition = new Position(line, column);
content[line][column] = new Square(map[line][column]);
}
}
if (myPosition == null)
throw new UnknownPositionException("Position not specified in message");
}
public boolean isAllowedMove(Direction d){
Square dest = getSquare(Position.add(myPosition, d));
// if dest is out of map, is a door or is out of sight, move is forbidden
if (dest == null ||
dest.getType() == SquareType.CLOSED_DOOR ||
dest.getType() == SquareType.UNKNOWN)
return false;
switch (d){
case NORTH:
case SOUTH:
return (dest.getType() != SquareType.HORIZONTAL_WALL);
case EAST:
case WEST:
return (dest.getType() != SquareType.VERTICAL_WALL);
case NORTH_EAST:
case NORTH_WEST:
case SOUTH_WEST:
case SOUTH_EAST:
return (dest.getType() != SquareType.VERTICAL_WALL &&
dest.getType() != SquareType.HORIZONTAL_WALL);
default: return false;
}
}
public boolean isAllowedOpen(Direction d){
Square dest = getSquare(Position.add(myPosition, d));
// if dest is out of map, is a door or is out of sight, move is forbidden
return dest.getType() == SquareType.CLOSED_DOOR;
}
public Square getSquare(Position p){
int line = p.getLine();
if (line >= content.length ||
line < 0)
return null;
int col = p.getColumn();
if (col >= content[line].length ||
col < 0)
return null;
return content[line][col];
}
public Position getPlayerPosition(){
return myPosition;
}
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("myPosition : " + myPosition);
for (int line = 0; line < content.length ; line++){
for (int column = 0; column < content[line].length; column++)
if (myPosition.getLine() == line &&
myPosition.getColumn() == column)
sb.append("@");
else
sb.append(content[line][column].toString());
sb.append('\n');
}
return sb.toString();
}
}
| [
"lleclech@enseirb-matmeca.fr"
] | lleclech@enseirb-matmeca.fr |
e92cfe3ef830d72830b2bb7afdbf4b923056e1c9 | e3f50a97b37dc5c1415b2d0348564ceb78832698 | /1909 NSA Codebreaker Challenge/terrortime_jadx/java/org/jivesoftware/smackx/filetransfer/OutgoingFileTransfer.java | a6e159f2e5eefccab1f2f965f31b1b0484283eaa | [] | no_license | sears-s/ctf | b8d13f121deb43189487b168a68f18dfc5538212 | c0e5960b1b975ba7073dae28b0c0f28a6eab563e | refs/heads/master | 2021-07-26T21:12:01.384166 | 2021-06-29T04:42:52 | 2021-06-29T04:42:52 | 145,129,430 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 23,313 | java | package org.jivesoftware.smackx.filetransfer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.IllegalStateChangeException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.packet.StanzaError;
import org.jivesoftware.smack.packet.StanzaError.Condition;
import org.jivesoftware.smackx.filetransfer.FileTransfer.Error;
import org.jivesoftware.smackx.filetransfer.FileTransfer.Status;
import org.jxmpp.jid.Jid;
public class OutgoingFileTransfer extends FileTransfer {
/* access modifiers changed from: private */
public static final Logger LOGGER = Logger.getLogger(OutgoingFileTransfer.class.getName());
private static int RESPONSE_TIMEOUT = 60000;
private NegotiationProgress callback;
private Jid initiator;
/* access modifiers changed from: private */
public OutputStream outputStream;
private Thread transferThread;
/* renamed from: org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer$4 reason: invalid class name */
static /* synthetic */ class AnonymousClass4 {
static final /* synthetic */ int[] $SwitchMap$org$jivesoftware$smack$packet$StanzaError$Condition = new int[Condition.values().length];
static {
try {
$SwitchMap$org$jivesoftware$smack$packet$StanzaError$Condition[Condition.forbidden.ordinal()] = 1;
} catch (NoSuchFieldError e) {
}
try {
$SwitchMap$org$jivesoftware$smack$packet$StanzaError$Condition[Condition.bad_request.ordinal()] = 2;
} catch (NoSuchFieldError e2) {
}
}
}
public interface NegotiationProgress {
void errorEstablishingStream(Exception exc);
void outputStreamEstablished(OutputStream outputStream);
void statusUpdated(Status status, Status status2);
}
public static int getResponseTimeout() {
return RESPONSE_TIMEOUT;
}
public static void setResponseTimeout(int responseTimeout) {
RESPONSE_TIMEOUT = responseTimeout;
}
protected OutgoingFileTransfer(Jid initiator2, Jid target, String streamID, FileTransferNegotiator transferNegotiator) {
super(target, streamID, transferNegotiator);
this.initiator = initiator2;
}
/* access modifiers changed from: protected */
public void setOutputStream(OutputStream stream) {
if (this.outputStream == null) {
this.outputStream = stream;
}
}
/* access modifiers changed from: protected */
public OutputStream getOutputStream() {
if (getStatus().equals(Status.negotiated)) {
return this.outputStream;
}
return null;
}
public synchronized OutputStream sendFile(String fileName, long fileSize, String description) throws XMPPException, SmackException, InterruptedException {
if (isDone() || this.outputStream != null) {
throw new IllegalStateException("The negotiation process has already been attempted on this file transfer");
}
try {
setFileInfo(fileName, fileSize);
this.outputStream = negotiateStream(fileName, fileSize, description);
} catch (XMPPErrorException e) {
handleXMPPException(e);
throw e;
}
return this.outputStream;
}
public synchronized void sendFile(String fileName, long fileSize, String description, NegotiationProgress progress) {
if (progress != null) {
try {
checkTransferThread();
if (isDone() || this.outputStream != null) {
throw new IllegalStateException("The negotiation process has already been attempted for this file transfer");
}
setFileInfo(fileName, fileSize);
this.callback = progress;
final String str = fileName;
final long j = fileSize;
final String str2 = description;
final NegotiationProgress negotiationProgress = progress;
AnonymousClass1 r1 = new Runnable() {
public void run() {
try {
OutgoingFileTransfer.this.outputStream = OutgoingFileTransfer.this.negotiateStream(str, j, str2);
negotiationProgress.outputStreamEstablished(OutgoingFileTransfer.this.outputStream);
} catch (XMPPErrorException e) {
OutgoingFileTransfer.this.handleXMPPException(e);
} catch (Exception e2) {
OutgoingFileTransfer.this.setException(e2);
}
}
};
StringBuilder sb = new StringBuilder();
sb.append("File Transfer Negotiation ");
sb.append(this.streamID);
this.transferThread = new Thread(r1, sb.toString());
this.transferThread.start();
} catch (Throwable th) {
throw th;
}
} else {
throw new IllegalArgumentException("Callback progress cannot be null.");
}
}
private void checkTransferThread() {
Thread thread = this.transferThread;
if ((thread != null && thread.isAlive()) || isDone()) {
throw new IllegalStateException("File transfer in progress or has already completed.");
}
}
public synchronized void sendFile(final File file, final String description) throws SmackException {
checkTransferThread();
if (file == null || !file.exists() || !file.canRead()) {
throw new IllegalArgumentException("Could not read file");
}
setFileInfo(file.getAbsolutePath(), file.getName(), file.length());
AnonymousClass2 r1 = new Runnable() {
/* JADX WARNING: Unknown top exception splitter block from list: {B:31:0x0091=Splitter:B:31:0x0091, B:18:0x005d=Splitter:B:18:0x005d, B:41:0x00bf=Splitter:B:41:0x00bf} */
/* Code decompiled incorrectly, please refer to instructions dump. */
public void run() {
/*
r8 = this;
java.lang.String r0 = "Closing input stream"
java.lang.String r1 = "Closing output stream"
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r2 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r3 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
java.io.File r4 = r5 // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
java.lang.String r4 = r4.getName() // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
java.io.File r5 = r5 // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
long r5 = r5.length() // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
java.lang.String r7 = r6 // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
java.io.OutputStream r3 = r3.negotiateStream(r4, r5, r7) // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
r2.outputStream = r3 // Catch:{ XMPPErrorException -> 0x00f8, Exception -> 0x001e }
goto L_0x0024
L_0x001e:
r2 = move-exception
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r3 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this
r3.setException(r2)
L_0x0024:
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r2 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this
java.io.OutputStream r2 = r2.outputStream
if (r2 != 0) goto L_0x002d
return
L_0x002d:
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r2 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this
org.jivesoftware.smackx.filetransfer.FileTransfer$Status r3 = org.jivesoftware.smackx.filetransfer.FileTransfer.Status.negotiated
org.jivesoftware.smackx.filetransfer.FileTransfer$Status r4 = org.jivesoftware.smackx.filetransfer.FileTransfer.Status.in_progress
boolean r2 = r2.updateStatus(r3, r4)
if (r2 != 0) goto L_0x003a
return
L_0x003a:
r2 = 0
java.io.FileInputStream r3 = new java.io.FileInputStream // Catch:{ FileNotFoundException -> 0x009b, IOException -> 0x0074 }
java.io.File r4 = r5 // Catch:{ FileNotFoundException -> 0x009b, IOException -> 0x0074 }
r3.<init>(r4) // Catch:{ FileNotFoundException -> 0x009b, IOException -> 0x0074 }
r2 = r3
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r3 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ FileNotFoundException -> 0x009b, IOException -> 0x0074 }
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ FileNotFoundException -> 0x009b, IOException -> 0x0074 }
java.io.OutputStream r4 = r4.outputStream // Catch:{ FileNotFoundException -> 0x009b, IOException -> 0x0074 }
r3.writeToStream(r2, r4) // Catch:{ FileNotFoundException -> 0x009b, IOException -> 0x0074 }
r2.close() // Catch:{ IOException -> 0x0053 }
goto L_0x005d
L_0x0053:
r3 = move-exception
java.util.logging.Logger r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.LOGGER
java.util.logging.Level r5 = java.util.logging.Level.WARNING
r4.log(r5, r0, r3)
L_0x005d:
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r0 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ IOException -> 0x0067 }
java.io.OutputStream r0 = r0.outputStream // Catch:{ IOException -> 0x0067 }
r0.close() // Catch:{ IOException -> 0x0067 }
L_0x0066:
goto L_0x00c9
L_0x0067:
r0 = move-exception
java.util.logging.Logger r3 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.LOGGER
java.util.logging.Level r4 = java.util.logging.Level.WARNING
r3.log(r4, r1, r0)
goto L_0x00c9
L_0x0072:
r3 = move-exception
goto L_0x00d3
L_0x0074:
r3 = move-exception
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ all -> 0x0072 }
org.jivesoftware.smackx.filetransfer.FileTransfer$Status r5 = org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error // Catch:{ all -> 0x0072 }
r4.setStatus(r5) // Catch:{ all -> 0x0072 }
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ all -> 0x0072 }
r4.setException(r3) // Catch:{ all -> 0x0072 }
if (r2 == 0) goto L_0x0091
r2.close() // Catch:{ IOException -> 0x0087 }
goto L_0x0091
L_0x0087:
r3 = move-exception
java.util.logging.Logger r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.LOGGER
java.util.logging.Level r5 = java.util.logging.Level.WARNING
r4.log(r5, r0, r3)
L_0x0091:
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r0 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ IOException -> 0x0067 }
java.io.OutputStream r0 = r0.outputStream // Catch:{ IOException -> 0x0067 }
r0.close() // Catch:{ IOException -> 0x0067 }
goto L_0x0066
L_0x009b:
r3 = move-exception
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ all -> 0x0072 }
org.jivesoftware.smackx.filetransfer.FileTransfer$Status r5 = org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error // Catch:{ all -> 0x0072 }
r4.setStatus(r5) // Catch:{ all -> 0x0072 }
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ all -> 0x0072 }
org.jivesoftware.smackx.filetransfer.FileTransfer$Error r5 = org.jivesoftware.smackx.filetransfer.FileTransfer.Error.bad_file // Catch:{ all -> 0x0072 }
r4.setError(r5) // Catch:{ all -> 0x0072 }
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ all -> 0x0072 }
r4.setException(r3) // Catch:{ all -> 0x0072 }
if (r2 == 0) goto L_0x00bf
r2.close() // Catch:{ IOException -> 0x00b5 }
goto L_0x00bf
L_0x00b5:
r3 = move-exception
java.util.logging.Logger r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.LOGGER
java.util.logging.Level r5 = java.util.logging.Level.WARNING
r4.log(r5, r0, r3)
L_0x00bf:
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r0 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ IOException -> 0x0067 }
java.io.OutputStream r0 = r0.outputStream // Catch:{ IOException -> 0x0067 }
r0.close() // Catch:{ IOException -> 0x0067 }
goto L_0x0066
L_0x00c9:
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r0 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this
org.jivesoftware.smackx.filetransfer.FileTransfer$Status r1 = org.jivesoftware.smackx.filetransfer.FileTransfer.Status.in_progress
org.jivesoftware.smackx.filetransfer.FileTransfer$Status r3 = org.jivesoftware.smackx.filetransfer.FileTransfer.Status.complete
r0.updateStatus(r1, r3)
return
L_0x00d3:
if (r2 == 0) goto L_0x00e3
r2.close() // Catch:{ IOException -> 0x00d9 }
goto L_0x00e3
L_0x00d9:
r4 = move-exception
java.util.logging.Logger r5 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.LOGGER
java.util.logging.Level r6 = java.util.logging.Level.WARNING
r5.log(r6, r0, r4)
L_0x00e3:
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r0 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this // Catch:{ IOException -> 0x00ed }
java.io.OutputStream r0 = r0.outputStream // Catch:{ IOException -> 0x00ed }
r0.close() // Catch:{ IOException -> 0x00ed }
goto L_0x00f7
L_0x00ed:
r0 = move-exception
java.util.logging.Logger r4 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.LOGGER
java.util.logging.Level r5 = java.util.logging.Level.WARNING
r4.log(r5, r1, r0)
L_0x00f7:
throw r3
L_0x00f8:
r0 = move-exception
org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer r1 = org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.this
r1.handleXMPPException(r0)
return
*/
throw new UnsupportedOperationException("Method not decompiled: org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer.AnonymousClass2.run():void");
}
};
StringBuilder sb = new StringBuilder();
sb.append("File Transfer ");
sb.append(this.streamID);
this.transferThread = new Thread(r1, sb.toString());
this.transferThread.start();
}
public synchronized void sendStream(InputStream in, String fileName, long fileSize, String description) {
checkTransferThread();
setFileInfo(fileName, fileSize);
final String str = fileName;
final long j = fileSize;
final String str2 = description;
final InputStream inputStream = in;
AnonymousClass3 r1 = new Runnable() {
public void run() {
try {
OutgoingFileTransfer.this.outputStream = OutgoingFileTransfer.this.negotiateStream(str, j, str2);
} catch (XMPPErrorException e) {
OutgoingFileTransfer.this.handleXMPPException(e);
return;
} catch (Exception e2) {
OutgoingFileTransfer.this.setException(e2);
}
if (OutgoingFileTransfer.this.outputStream != null && OutgoingFileTransfer.this.updateStatus(Status.negotiated, Status.in_progress)) {
try {
OutgoingFileTransfer.this.writeToStream(inputStream, OutgoingFileTransfer.this.outputStream);
try {
if (inputStream != null) {
inputStream.close();
}
OutgoingFileTransfer.this.outputStream.flush();
OutgoingFileTransfer.this.outputStream.close();
} catch (IOException e3) {
}
} catch (IOException e4) {
OutgoingFileTransfer.this.setStatus(Status.error);
OutgoingFileTransfer.this.setException(e4);
if (inputStream != null) {
inputStream.close();
}
OutgoingFileTransfer.this.outputStream.flush();
OutgoingFileTransfer.this.outputStream.close();
} catch (Throwable th) {
try {
if (inputStream != null) {
inputStream.close();
}
OutgoingFileTransfer.this.outputStream.flush();
OutgoingFileTransfer.this.outputStream.close();
} catch (IOException e5) {
}
throw th;
}
OutgoingFileTransfer.this.updateStatus(Status.in_progress, Status.complete);
}
}
};
StringBuilder sb = new StringBuilder();
sb.append("File Transfer ");
sb.append(this.streamID);
this.transferThread = new Thread(r1, sb.toString());
this.transferThread.start();
}
/* access modifiers changed from: private */
public void handleXMPPException(XMPPErrorException e) {
StanzaError error = e.getStanzaError();
if (error != null) {
int i = AnonymousClass4.$SwitchMap$org$jivesoftware$smack$packet$StanzaError$Condition[error.getCondition().ordinal()];
if (i == 1) {
setStatus(Status.refused);
return;
} else if (i != 2) {
setStatus(Status.error);
} else {
setStatus(Status.error);
setError(Error.not_acceptable);
}
}
setException(e);
}
public long getBytesSent() {
return this.amountWritten;
}
/* access modifiers changed from: private */
public OutputStream negotiateStream(String fileName, long fileSize, String description) throws SmackException, XMPPException, InterruptedException {
if (updateStatus(Status.initial, Status.negotiating_transfer)) {
StreamNegotiator streamNegotiator = this.negotiator.negotiateOutgoingTransfer(getPeer(), this.streamID, fileName, fileSize, description, RESPONSE_TIMEOUT);
if (updateStatus(Status.negotiating_transfer, Status.negotiating_stream)) {
this.outputStream = streamNegotiator.createOutgoingStream(this.streamID, this.initiator, getPeer());
if (updateStatus(Status.negotiating_stream, Status.negotiated)) {
return this.outputStream;
}
throw new IllegalStateChangeException();
}
throw new IllegalStateChangeException();
}
throw new IllegalStateChangeException();
}
public void cancel() {
setStatus(Status.cancelled);
}
/* access modifiers changed from: protected */
public boolean updateStatus(Status oldStatus, Status newStatus) {
boolean isUpdated = super.updateStatus(oldStatus, newStatus);
NegotiationProgress negotiationProgress = this.callback;
if (negotiationProgress != null && isUpdated) {
negotiationProgress.statusUpdated(oldStatus, newStatus);
}
return isUpdated;
}
/* access modifiers changed from: protected */
public void setStatus(Status status) {
Status oldStatus = getStatus();
super.setStatus(status);
NegotiationProgress negotiationProgress = this.callback;
if (negotiationProgress != null) {
negotiationProgress.statusUpdated(oldStatus, status);
}
}
/* access modifiers changed from: protected */
public void setException(Exception exception) {
super.setException(exception);
NegotiationProgress negotiationProgress = this.callback;
if (negotiationProgress != null) {
negotiationProgress.errorEstablishingStream(exception);
}
}
}
| [
"sears-s@users.noreply.github.com"
] | sears-s@users.noreply.github.com |
bb9b49d1b300d017d84f94c5a5800fee9f3484c2 | 702f8a8f0d96412f34824e7240da07e6e7203e94 | /app/src/main/java/com/logvai/logvai/ListaActivity3.java | 67fbecdd796cbdc329c71d5f17f722c35105a223 | [] | no_license | CarlosSalesNaturalTec/AndroidApp | e58fe062f3a469bdac91b1c239302149a7ec6d8a | 0f272cf288b85f927ae777a1042d6cf23d356eb2 | refs/heads/master | 2021-01-22T06:19:33.946436 | 2017-07-13T22:07:20 | 2017-07-13T22:07:20 | 92,543,894 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,524 | java | package com.logvai.logvai;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class ListaActivity3 extends ListActivity {
// ==============================================================================================================
// DECLARAÇÕES DIVERSAS
public ListView lv;
ProgressDialog progressDialog;
//Volley conectividade
public static final String JSON_URL = "http://logvaiws.azurewebsites.net/Webservice.asmx/EmAndamento?param1=" + Global.globalID ;
// ==============================================================================================================
// ==============================================================================================================
// CICLO DA ACTIVITY - onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista3);
//monta ListView
lv = (ListView) findViewById(android.R.id.list);
progressDialog = new ProgressDialog(this);
//requisita lista de entregas e preenche ListView
volleyStringRequst(JSON_URL);
//aguarda/verifica seleção do usuário
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//ID da Entrega_MASTER selecionada
String idEntrega = (String) lv.getItemAtPosition(position);
//transferencia de dados entre Activitys
Bundle b = new Bundle();
b.putString("IDauxiliar",idEntrega);
//abre nova Activity
Intent proximatela = new Intent(getApplicationContext(),ListaActivity2.class);
proximatela.putExtras(b);
startActivity(proximatela);
}
});
}
// onResume
@Override
public void onResume(){
super.onResume();
//atualiza lista de entregas em aberto e preenche ListView
volleyStringRequst(JSON_URL);
}
//======================================================================================================================
//VOLLEY CONECTIVIDADE - TROCA DE DADOS COM WEB-SERVICE - requisita Lista de Entregas (Bairro e Endereço)
//======================================================================================================================
public void volleyStringRequst(String url){
String REQUEST_TAG = "com.logvai.lista3";
progressDialog.setMessage("Aguarde...");
progressDialog.show();
StringRequest strReq = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Formata retorno obtido do web-service. Layout: [{" json string "}]
String str1 = "{\"entregas\":" + response.toString().substring(91);
int tamanho = str1.length() -9 ;
String str2 = str1.substring(0,tamanho) + "}";
//envia retorno formatado para processo de Parsing
showJSON(str2);
progressDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
}
});
// Adding String request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, REQUEST_TAG);
}
//======================================================================================================================
//JSON Parsing
private void showJSON(String json){
//monta Array String com lista de Entregas
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
ListaAdapter cl = new ListaAdapter(this, ParseJSON.IDs, ParseJSON.Titulos, ParseJSON.SubTitulos, ParseJSON.SubTitulos1);
lv.setAdapter(cl);
}
//=====================================================================================================================
} | [
"carlossalesti@gmail.com"
] | carlossalesti@gmail.com |
9620d846bb42b16639ce3e7f9a4a8cd4e25f11a7 | ad7b62bd679916921363c8f02ad7ebc4a5cd448c | /src/leetcode/lc57_InsertInterval.java | 427a86b746c28a1ab47bc1b1fd0d0a1bc21d2300 | [] | no_license | zizhengli/Algorithm | 6d1769e870ad36b0b688e153948cfa537d6bc64d | 2cd290f6d8304f025f7ff55370d2739fee15b8cc | refs/heads/master | 2021-07-17T07:06:44.680462 | 2021-06-28T20:02:17 | 2021-06-28T20:02:17 | 79,736,709 | 0 | 0 | null | 2021-06-28T20:02:18 | 2017-01-22T18:34:52 | null | UTF-8 | Java | false | false | 1,294 | java | package leetcode;
import java.util.ArrayList;
import java.util.List;
public class lc57_InsertInterval {
public class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
}
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> res = new ArrayList<>();
if (intervals == null || intervals.size() == 0) {
res.add(newInterval);
return res;
}
int index = 0;
while (index < intervals.size() && newInterval.start > intervals.get(index).end) {
res.add(intervals.get(index));
index++;
}
while (index < intervals.size() && newInterval.end >= intervals.get(index).start) {
newInterval.start = Math.min(newInterval.start, intervals.get(index).start);
newInterval.end = Math.max(newInterval.end, intervals.get(index).end);
index++;
}
res.add(new Interval(newInterval.start, newInterval.end));
while (index < intervals.size()) {
res.add(intervals.get(index));
index++;
}
return res;
}
}
| [
"Matthew.Li2@mountsinai.org"
] | Matthew.Li2@mountsinai.org |
7d431d46cfcc5864e31b66bed001a4c914bb4878 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/aosp-mirror--platform_frameworks_base/5927c9f1b12f597839a664c1c6593114175cbcd8/after/KeymasterUtils.java | 63b2a694bf93fec1c2f9aa28bb4cf869b5c6091d | [] | 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 | 13,812 | java | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.security;
import android.security.keymaster.KeymasterDefs;
import libcore.util.EmptyArray;
import java.util.Collection;
import java.util.Locale;
/**
* @hide
*/
public abstract class KeymasterUtils {
private KeymasterUtils() {}
public static int getKeymasterAlgorithmFromJcaSecretKeyAlgorithm(String jcaKeyAlgorithm) {
if ("AES".equalsIgnoreCase(jcaKeyAlgorithm)) {
return KeymasterDefs.KM_ALGORITHM_AES;
} else if (jcaKeyAlgorithm.toUpperCase(Locale.US).startsWith("HMAC")) {
return KeymasterDefs.KM_ALGORITHM_HMAC;
} else {
throw new IllegalArgumentException(
"Unsupported secret key algorithm: " + jcaKeyAlgorithm);
}
}
public static String getJcaSecretKeyAlgorithm(int keymasterAlgorithm, int keymasterDigest) {
switch (keymasterAlgorithm) {
case KeymasterDefs.KM_ALGORITHM_AES:
if (keymasterDigest != -1) {
throw new IllegalArgumentException(
"Digest not supported for AES key: " + keymasterDigest);
}
return "AES";
case KeymasterDefs.KM_ALGORITHM_HMAC:
switch (keymasterDigest) {
case KeymasterDefs.KM_DIGEST_SHA1:
return "HmacSHA1";
case KeymasterDefs.KM_DIGEST_SHA_2_224:
return "HmacSHA224";
case KeymasterDefs.KM_DIGEST_SHA_2_256:
return "HmacSHA256";
case KeymasterDefs.KM_DIGEST_SHA_2_384:
return "HmacSHA384";
case KeymasterDefs.KM_DIGEST_SHA_2_512:
return "HmacSHA512";
default:
throw new IllegalArgumentException(
"Unsupported HMAC digest: " + keymasterDigest);
}
default:
throw new IllegalArgumentException("Unsupported algorithm: " + keymasterAlgorithm);
}
}
public static String getJcaKeyPairAlgorithmFromKeymasterAlgorithm(int keymasterAlgorithm) {
switch (keymasterAlgorithm) {
case KeymasterDefs.KM_ALGORITHM_RSA:
return "RSA";
case KeymasterDefs.KM_ALGORITHM_EC:
return "EC";
default:
throw new IllegalArgumentException("Unsupported algorithm: " + keymasterAlgorithm);
}
}
public static int getKeymasterDigestfromJcaSecretKeyAlgorithm(String jcaKeyAlgorithm) {
String algorithmUpper = jcaKeyAlgorithm.toUpperCase(Locale.US);
if (algorithmUpper.startsWith("HMAC")) {
String digestUpper = algorithmUpper.substring("HMAC".length());
switch (digestUpper) {
case "MD5":
return KeymasterDefs.KM_DIGEST_MD5;
case "SHA1":
return KeymasterDefs.KM_DIGEST_SHA1;
case "SHA224":
return KeymasterDefs.KM_DIGEST_SHA_2_224;
case "SHA256":
return KeymasterDefs.KM_DIGEST_SHA_2_256;
case "SHA384":
return KeymasterDefs.KM_DIGEST_SHA_2_384;
case "SHA512":
return KeymasterDefs.KM_DIGEST_SHA_2_512;
default:
throw new IllegalArgumentException("Unsupported HMAC digest: " + digestUpper);
}
} else {
return -1;
}
}
public static int getKeymasterDigestFromJcaDigestAlgorithm(String jcaDigestAlgorithm) {
if (jcaDigestAlgorithm.equalsIgnoreCase("SHA-1")) {
return KeymasterDefs.KM_DIGEST_SHA1;
} else if (jcaDigestAlgorithm.equalsIgnoreCase("SHA-224")) {
return KeymasterDefs.KM_DIGEST_SHA_2_224;
} else if (jcaDigestAlgorithm.equalsIgnoreCase("SHA-256")) {
return KeymasterDefs.KM_DIGEST_SHA_2_256;
} else if (jcaDigestAlgorithm.equalsIgnoreCase("SHA-384")) {
return KeymasterDefs.KM_DIGEST_SHA_2_384;
} else if (jcaDigestAlgorithm.equalsIgnoreCase("SHA-512")) {
return KeymasterDefs.KM_DIGEST_SHA_2_512;
} else if (jcaDigestAlgorithm.equalsIgnoreCase("NONE")) {
return KeymasterDefs.KM_DIGEST_NONE;
} else if (jcaDigestAlgorithm.equalsIgnoreCase("MD5")) {
return KeymasterDefs.KM_DIGEST_MD5;
} else {
throw new IllegalArgumentException(
"Unsupported digest algorithm: " + jcaDigestAlgorithm);
}
}
public static String getJcaDigestAlgorithmFromKeymasterDigest(int keymasterDigest) {
switch (keymasterDigest) {
case KeymasterDefs.KM_DIGEST_NONE:
return "NONE";
case KeymasterDefs.KM_DIGEST_MD5:
return "MD5";
case KeymasterDefs.KM_DIGEST_SHA1:
return "SHA-1";
case KeymasterDefs.KM_DIGEST_SHA_2_224:
return "SHA-224";
case KeymasterDefs.KM_DIGEST_SHA_2_256:
return "SHA-256";
case KeymasterDefs.KM_DIGEST_SHA_2_384:
return "SHA-384";
case KeymasterDefs.KM_DIGEST_SHA_2_512:
return "SHA-512";
default:
throw new IllegalArgumentException(
"Unsupported digest algorithm: " + keymasterDigest);
}
}
public static String[] getJcaDigestAlgorithmsFromKeymasterDigests(
Collection<Integer> keymasterDigests) {
if (keymasterDigests.isEmpty()) {
return EmptyArray.STRING;
}
String[] result = new String[keymasterDigests.size()];
int offset = 0;
for (int keymasterDigest : keymasterDigests) {
result[offset] = getJcaDigestAlgorithmFromKeymasterDigest(keymasterDigest);
offset++;
}
return result;
}
public static int[] getKeymasterDigestsFromJcaDigestAlgorithms(String[] jcaDigestAlgorithms) {
if ((jcaDigestAlgorithms == null) || (jcaDigestAlgorithms.length == 0)) {
return EmptyArray.INT;
}
int[] result = new int[jcaDigestAlgorithms.length];
int offset = 0;
for (String jcaDigestAlgorithm : jcaDigestAlgorithms) {
result[offset] = getKeymasterDigestFromJcaDigestAlgorithm(jcaDigestAlgorithm);
offset++;
}
return result;
}
public static int getDigestOutputSizeBytes(int keymasterDigest) {
switch (keymasterDigest) {
case KeymasterDefs.KM_DIGEST_NONE:
return -1;
case KeymasterDefs.KM_DIGEST_MD5:
return 128 / 8;
case KeymasterDefs.KM_DIGEST_SHA1:
return 160 / 8;
case KeymasterDefs.KM_DIGEST_SHA_2_224:
return 224 / 8;
case KeymasterDefs.KM_DIGEST_SHA_2_256:
return 256 / 8;
case KeymasterDefs.KM_DIGEST_SHA_2_384:
return 384 / 8;
case KeymasterDefs.KM_DIGEST_SHA_2_512:
return 512 / 8;
default:
throw new IllegalArgumentException("Unknown digest: " + keymasterDigest);
}
}
public static int getKeymasterBlockModeFromJcaBlockMode(String jcaBlockMode) {
if ("ECB".equalsIgnoreCase(jcaBlockMode)) {
return KeymasterDefs.KM_MODE_ECB;
} else if ("CBC".equalsIgnoreCase(jcaBlockMode)) {
return KeymasterDefs.KM_MODE_CBC;
} else if ("CTR".equalsIgnoreCase(jcaBlockMode)) {
return KeymasterDefs.KM_MODE_CTR;
} else if ("GCM".equalsIgnoreCase(jcaBlockMode)) {
return KeymasterDefs.KM_MODE_GCM;
} else {
throw new IllegalArgumentException("Unsupported block mode: " + jcaBlockMode);
}
}
public static String getJcaBlockModeFromKeymasterBlockMode(int keymasterBlockMode) {
switch (keymasterBlockMode) {
case KeymasterDefs.KM_MODE_ECB:
return "ECB";
case KeymasterDefs.KM_MODE_CBC:
return "CBC";
case KeymasterDefs.KM_MODE_CTR:
return "CTR";
case KeymasterDefs.KM_MODE_GCM:
return "GCM";
default:
throw new IllegalArgumentException("Unsupported block mode: " + keymasterBlockMode);
}
}
public static String[] getJcaBlockModesFromKeymasterBlockModes(
Collection<Integer> keymasterBlockModes) {
if ((keymasterBlockModes == null) || (keymasterBlockModes.isEmpty())) {
return EmptyArray.STRING;
}
String[] result = new String[keymasterBlockModes.size()];
int offset = 0;
for (int keymasterBlockMode : keymasterBlockModes) {
result[offset] = getJcaBlockModeFromKeymasterBlockMode(keymasterBlockMode);
offset++;
}
return result;
}
public static int[] getKeymasterBlockModesFromJcaBlockModes(String[] jcaBlockModes) {
if ((jcaBlockModes == null) || (jcaBlockModes.length == 0)) {
return EmptyArray.INT;
}
int[] result = new int[jcaBlockModes.length];
for (int i = 0; i < jcaBlockModes.length; i++) {
result[i] = getKeymasterBlockModeFromJcaBlockMode(jcaBlockModes[i]);
}
return result;
}
public static boolean isKeymasterBlockModeIndCpaCompatible(int keymasterBlockMode) {
switch (keymasterBlockMode) {
case KeymasterDefs.KM_MODE_ECB:
return false;
case KeymasterDefs.KM_MODE_CBC:
case KeymasterDefs.KM_MODE_CTR:
case KeymasterDefs.KM_MODE_GCM:
return true;
default:
throw new IllegalArgumentException("Unsupported block mode: " + keymasterBlockMode);
}
}
public static int getKeymasterPaddingFromJcaEncryptionPadding(String jcaPadding) {
if ("NoPadding".equalsIgnoreCase(jcaPadding)) {
return KeymasterDefs.KM_PAD_NONE;
} else if ("PKCS7Padding".equalsIgnoreCase(jcaPadding)) {
return KeymasterDefs.KM_PAD_PKCS7;
} else if ("PKCS1Padding".equalsIgnoreCase(jcaPadding)) {
return KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_ENCRYPT;
} else if ("OEAPPadding".equalsIgnoreCase(jcaPadding)) {
return KeymasterDefs.KM_PAD_RSA_OAEP;
} else {
throw new IllegalArgumentException(
"Unsupported encryption padding scheme: " + jcaPadding);
}
}
public static String getJcaEncryptionPaddingFromKeymasterPadding(int keymasterPadding) {
switch (keymasterPadding) {
case KeymasterDefs.KM_PAD_NONE:
return "NoPadding";
case KeymasterDefs.KM_PAD_PKCS7:
return "PKCS7Padding";
case KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_ENCRYPT:
return "PKCS1Padding";
case KeymasterDefs.KM_PAD_RSA_OAEP:
return "OEAPPadding";
default:
throw new IllegalArgumentException(
"Unsupported encryption padding: " + keymasterPadding);
}
}
public static int getKeymasterPaddingFromJcaSignaturePadding(String jcaPadding) {
if ("PKCS#1".equalsIgnoreCase(jcaPadding)) {
return KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_SIGN;
} if ("PSS".equalsIgnoreCase(jcaPadding)) {
return KeymasterDefs.KM_PAD_RSA_PSS;
} else {
throw new IllegalArgumentException(
"Unsupported signature padding scheme: " + jcaPadding);
}
}
public static String getJcaSignaturePaddingFromKeymasterPadding(int keymasterPadding) {
switch (keymasterPadding) {
case KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_SIGN:
return "PKCS#1";
case KeymasterDefs.KM_PAD_RSA_PSS:
return "PSS";
default:
throw new IllegalArgumentException(
"Unsupported signature padding: " + keymasterPadding);
}
}
public static int[] getKeymasterPaddingsFromJcaEncryptionPaddings(String[] jcaPaddings) {
if ((jcaPaddings == null) || (jcaPaddings.length == 0)) {
return EmptyArray.INT;
}
int[] result = new int[jcaPaddings.length];
for (int i = 0; i < jcaPaddings.length; i++) {
result[i] = getKeymasterPaddingFromJcaEncryptionPadding(jcaPaddings[i]);
}
return result;
}
public static int[] getKeymasterPaddingsFromJcaSignaturePaddings(String[] jcaPaddings) {
if ((jcaPaddings == null) || (jcaPaddings.length == 0)) {
return EmptyArray.INT;
}
int[] result = new int[jcaPaddings.length];
for (int i = 0; i < jcaPaddings.length; i++) {
result[i] = getKeymasterPaddingFromJcaSignaturePadding(jcaPaddings[i]);
}
return result;
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
462144ab983af76d2798ac06a5cc1fe4b4669ea4 | 729971681f9bf97729988e7fe57d3e041cdad598 | /Advanced/src/main/java/hibernate/collection/map/MapTest.java | f7263e072cf5828de28b4a16b1853ef48d79e1fa | [] | no_license | liuchenwei2000/Hibernate | e6b90a10634e9a83f7c3d166429b5e94885d1ef3 | aa18556d56affcc68beea2628f07087b4783484b | refs/heads/master | 2021-01-10T08:12:04.378524 | 2017-04-27T07:57:38 | 2017-04-27T07:57:38 | 48,789,500 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,234 | java | /**
*
*/
package hibernate.collection.map;
import org.hibernate.Session;
import hibernate.util.AbstractHibernateTestCase;
/**
* Map示例
* <p>
* Map是一个无序集合类型,提供了键值对应关系。
*
* @author 刘晨伟
*
* 创建日期:2014年8月18日
*/
public class MapTest extends AbstractHibernateTestCase {
@Override
protected void doTest() throws Exception {
session.beginTransaction();
Product product = new Product("car");
product.getParts().put("左前轮", new Part("tire1"));
product.getParts().put("右前轮", new Part("tire2"));
product.getParts().put("左后轮", new Part("tire3"));
product.getParts().put("右后轮", new Part("tire4"));
session.save(product);
// 注意这里的Map实例已经被Hibernate替换为其自身实现,而不再是HashMap
System.out.println("【Map class is】" + product.getParts().getClass());
session.getTransaction().commit();
Session newSession = sessionFactory.openSession();
Product p = (Product) newSession.load(Product.class, 1L);
// 这里可以直接根据key值获取对应的对象
System.out.println(p.getParts().get("左前轮"));
newSession.close();
}
@Override
protected void prepareData() {
}
}
| [
"liuchenwei2000@163.com"
] | liuchenwei2000@163.com |
711a0bd3b19a219c1b39c8b1ddcc20c584f457ab | 00364c171935ea78cb1910a2445050be91b97f9b | /src/basepatterns/structural/flyweight/OperatorTubingMachine.java | fa73999e8972b0934a60d86bca941490424947e2 | [] | no_license | Bezngor/Patterns | d570131940fc8a63814f1928ca6017d0d3610072 | 806ce7b3dd0958437e15344ab9493c8c8e978649 | refs/heads/master | 2023-04-18T13:40:45.094630 | 2021-05-06T09:03:41 | 2021-05-06T09:03:41 | 361,130,792 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 325 | java | package basepatterns.structural.flyweight;
public class OperatorTubingMachine implements Employee {
@Override
public void executeFunctional() {
System.out.println("Operator of Tubing machine makes tube...");
}
@Override
public String toString() {
return "OperatorTubingMachine";
}
}
| [
"bezngor@gmail.com"
] | bezngor@gmail.com |
547fa974e47b1482cf15d1d0fb5daf371ae3041e | b7695e882b70e9be7f45a78369f34362ba295d53 | /blueblue/src/com/xinfan/blueblue/request/AnsynHttpRequest.java | 61906cc002914f9af15d77da121333a199b72b67 | [
"Apache-2.0"
] | permissive | sodoa/mbox | 15e474266d220812fe7b974a4588d9601a1c2688 | 4cd67de5b8e0c2adf43dd60ff0193796ef5dc3fc | refs/heads/master | 2020-05-19T14:59:23.091227 | 2014-10-06T10:04:33 | 2014-10-06T10:04:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,625 | java | package com.xinfan.blueblue.request;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import com.alibaba.fastjson.JSONObject;
import com.xinfan.blueblue.dao.DBHelper;
import com.xinfan.blueblue.util.LogUtil;
public class AnsynHttpRequest {
public static final int REQUEST_TIMEOUT = 30 * 1000;// 设置请求超时10秒钟
public static final int SO_TIMEOUT = 30 * 1000; // 设置等待数据超时时间10秒钟
static final int POST = 1; // post 提交
static final int GET = 2; // get 提交
static String tag = AnsynHttpRequest.class.getSimpleName();
public static DefaultHttpClient mHttpClient;
/**
*
* 访问网络初始化函数 支持GET请求方式
*
* @param callBack
* 回调执行函数 支持线程
* @param url
* 每个执行url
* @param map
* 参数
* @param isCache
* 是否本地缓存
* @param isShowDialog
* 是否弹出提示等待框
*/
public static void requestByGet(Context context, final ObserverCallBack callBack, String url, Map<String, String> map, boolean isCache, boolean isShowDialog) {
// 组织URL
StringBuffer buffer = new StringBuffer();
buffer.append(Constants.http.http_request_head)
// .append(context.getResources().getString(url))
.append("?");
boolean listData = true;
String selectUrl = "";
if (map != null && map.size() > 0) {
String value = "";
if (map.containsKey("start")) {
if (map.get("start").equals("0")) {
listData = true;
selectUrl = buffer.toString();
} else
listData = false;
value = "start=" + map.get("start") + "&";
}
for (String key : map.keySet()) {
if (key.equals("start")) {
continue;
}
buffer.append(key).append("=").append(Encoder.encode(map.get(key))).append("&");
}
buffer.append(value);
}
String requestUrl = buffer.toString();
requestUrl = requestUrl.substring(0, requestUrl.length() - 1);
LogUtil.i("httpurl", requestUrl);
String[] data = null;
if (isCache) { // 如果是缓存 取数据库缓存中数据
data = DBHelper.getInstance(context).getURLData(requestUrl);
}
switch (Network.checkNetWorkType(context)) {
case /** 网络不可用 */
Network.NONETWORK:
if (data == null) {
// sendBroadcastReceiverMessage(context,
// R.string.network_show_connectionless);
callBack.call(null);
// ((BaseActivity) context).checkNetWorkShowLog(1);
return;
}
break;
case /** 是wifi连接 */
Network.WIFI:
if (data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 3) {
// if(data != null && data.length > 0 && listData &&
// TimeCompare.compareHourTime(data[1]) > 1){
data = null;
DBHelper.getInstance(context).deleteURLData(selectUrl);
}
break;
case /** 不是wifi连接 */
Network.NOWIFI: // 是
if (data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 24 * 2) {
// if(data != null && data.length > 0 && listData &&
// TimeCompare.compareHourTime(data[1]) > 1){
data = null;
DBHelper.getInstance(context).deleteURLData(selectUrl);
}
break;
default:
break;
}
if (isCache && data != null && data.length > 0) { // 如果是缓存 取数据库缓存中数据
Response response = JSONObject.parseObject(data[0], Response.class);
callBack.call(response);
return;
}
// 异步请求数据
doAsynRequest(GET, null, context, callBack, requestUrl, isCache, isShowDialog, url);
}
/**
* 异步请求网络数据
*
* @param sendType
* 请求类型
* @param map
* 参数
* @param context
* @param callBack
* 回调对象
* @param url
* @param isCache
* 是否缓存
* @param isShowDialog
* 是否有提示框
* @param intUrl
*/
private static void doAsynRequest(final int sendType, final Map<String, String> map, final Context context, final ObserverCallBack callBack,
final String url, final boolean isCache, final boolean isShowDialog, final String intUrl) {
// if(isShowDialog) ((Activity)context).showDialog(1); // 加载对话框提示等待。。
// 请求
ThreadPoolUtils.execute(new MyRunnable(sendType, map, context, callBack, url, isCache, isShowDialog, intUrl));
}
/**
*
* 访问网络初始化函数 支持Post请求方式
*
* @param context
* @param callBack
* 回调执行函数 支持线程
* @param url
* 每个执行url
* @param map
* 参数
* @param isCache
* 是否本地缓存
* @param isShowDialog
* 是否弹出提示等待框
*/
public static void requestByPost(Context context, final ObserverCallBack callBack, String uri, Map<String, String> map, boolean isCache,
boolean isShowDialog) {
// 组织URL
StringBuffer buffer = new StringBuffer();
buffer.append(Constants.http.http_request_head);
// buffer.append(context.getResources().getString(url));
String requestUrl = buffer.toString();
// requestUrl = requestUrl.substring(0,requestUrl.length()-1);
LogUtil.i("httpurl", requestUrl);
// 异步请求数据
doAsynRequest(POST, map, context, callBack, requestUrl, isCache, isShowDialog, uri);
}
public static void requestSimpleByPost(Context context, final ObserverCallBack callBack, String uri, Map<String, String> map) {
// 组织URL
StringBuffer buffer = new StringBuffer();
buffer.append(Constants.http.http_request_head);
String requestUrl = buffer.toString();
// requestUrl = requestUrl.substring(0,requestUrl.length()-1);
LogUtil.i("httpurl", requestUrl);
// 异步请求数据
doAsynRequest(POST, map, context, callBack, requestUrl, false, true, uri);
}
/**
*
* 访问网络初始化函数 支持Post请求方式
*
* @param context
* @param http_head
* 请求头传null或者在C.http类中配置
* @param callBack
* 回调执行函数 支持线程
* @param url
* 每个执行url
* @param map
* 参数
* @param isCache
* 是否本地缓存
* @param isShowDialog
* 是否弹出提示等待框
*/
public static void requestByPost(Context context, String http_head, final ObserverCallBack callBack, String url, Map<String, String> map, boolean isCache,
boolean isShowDialog) {
// 组织URL
StringBuffer buffer = new StringBuffer();
if (http_head != null)
buffer.append(http_head);
else
buffer.append(Constants.http.http_request_head);
String requestUrl = buffer.toString();
// requestUrl = requestUrl.substring(0,requestUrl.length()-1);
LogUtil.i("httpurl", requestUrl + map.toString());
// 判断网络是否可用
if (!Network.checkNetWork(context)) { // 如果不可用 看本地否有数据
// sendBroadcastReceiverMessage(context,
// R.string.network_show_connectionless);
callBack.call(null);
return;
}
// 异步请求数据
doAsynRequest(POST, map, context, callBack, requestUrl, isCache, isShowDialog, url);
}
}
class MyRunnable implements Runnable {
final int sendType;
final Map<String, String> map;
final Context context;
final ObserverCallBack callBack;
final String url;
final boolean isCache;
final boolean isShowDialog;
final String intUrl;
public MyRunnable(final int sendType, final Map<String, String> map, final Context context, final ObserverCallBack callBack, final String url,
final boolean isCache, final boolean isShowDialog, final String intUrl) {
this.sendType = sendType;
this.map = map;
this.context = context;
this.callBack = callBack;
this.url = url;
this.isCache = isCache;
this.isShowDialog = isShowDialog;
this.intUrl = intUrl;
}
@Override
public void run() {
String data = null;
try {
// 设置请求头超时请求参数
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, AnsynHttpRequest.REQUEST_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, AnsynHttpRequest.SO_TIMEOUT);
if (AnsynHttpRequest.mHttpClient == null) {
// AnsynHttpRequest.mHttpClient = new
// DefaultHttpClient(httpParams);
DefaultHttpClient client = new DefaultHttpClient(httpParams);
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
AnsynHttpRequest.mHttpClient = client;
}
// HttpClient httpClient = HttpUtils.getNewHttpClient(context);
HttpResponse response = null;
switch (sendType) {
case AnsynHttpRequest.GET: // get 方式提交
HttpGet get = new HttpGet(url);
// get.setHeader("User-Agent", sUserAgent.toString());
response = AnsynHttpRequest.mHttpClient.execute(get);
break;
case AnsynHttpRequest.POST: // post 方式提交
HttpPost post = new HttpPost(url);
// post.setHeader("User-Agent", sUserAgent.toString());
LogUtil.i("httpurl", url + map.toString());
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (map != null && map.size() > 0)
for (String key : map.keySet()) {
params.add(new BasicNameValuePair(key, map.get(key)));
}
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
response = AnsynHttpRequest.mHttpClient.execute(post);
break;
default:
break;
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// httpClient.getCookieStore().getCookies().g
data = EntityUtils.toString(response.getEntity());
if (isCache) {// 把数据缓存到本地
DBHelper.getInstance(context).addOrUpdateURLData(url, data);
}
} else {
if (!isCache) {
// AnsynHttpRequest.sendBroadcastReceiverMessage(context,
// "11111111111");
}
data = null;
}
} catch (Exception e) {
LogUtil.e(AnsynHttpRequest.tag, e.getMessage());
if (!isCache) {
// AnsynHttpRequest.sendBroadcastReceiverMessage(context,
// R.string.network_show_error);
}
data = null;
}
try { // 回调数据
if (callBack != null) {
if (data != null && data.length() > 0) {
Response response = JSONObject.parseObject(data, Response.class);
callBack.call(response);
}
}
} catch (Exception e) {
LogUtil.e(AnsynHttpRequest.tag, e.getMessage());
}
try {
if (isShowDialog)
mHandler.sendEmptyMessage(0); // 移除加载对话框
return;
} catch (Exception e) {
LogUtil.e(AnsynHttpRequest.tag, e.getMessage());
}
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
((Activity) context).removeDialog(1);// 移除加载对话框
};
};
}
| [
"165614968@qq.com"
] | 165614968@qq.com |
4124ace87187cd7e01c50d2a0b9ea96338c9eb2f | f3a09d07a1b040c6e80de1eab27ed35338817255 | /core/src/main/java/org/training/aemcq5tutorials/core/servlets/SimpleServlet.java | 076159ca2fd1c81347ce44c327d5f7cb29151cef | [] | no_license | brianpja/aem-eclipse-setup | d354cf3872e22cf125fb410dc7e20848aebbd6e5 | 760938fefc6501d693dc34a8de2b47dda761d048 | refs/heads/master | 2020-03-24T01:46:34.210376 | 2018-07-25T20:48:40 | 2018-07-25T20:48:40 | 142,350,996 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,380 | java | /*
* Copyright 2015 Adobe Systems Incorporated
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.training.aemcq5tutorials.core.servlets;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.api.resource.ValueMap;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;
/**
* Servlet that writes some sample content into the response. It is mounted for
* all resources of a specific Sling resource type. The
* {@link SlingSafeMethodsServlet} shall be used for HTTP methods that are
* idempotent. For write operations use the {@link SlingAllMethodsServlet}.
*/
@Component(service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Simple Demo Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_GET,
"sling.servlet.resourceTypes="+ "aemtutorials/components/structure/page",
"sling.servlet.extensions=" + "txt"
})
public class SimpleServlet extends SlingSafeMethodsServlet {
private static final long serialVersionUid = 1L;
@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
final Resource resource = req.getResource();
resp.setContentType("text/plain");
resp.getWriter().write("Title = " + resource.adaptTo(ValueMap.class).get("jcr:title"));
}
}
| [
"brian.james@slalom.com"
] | brian.james@slalom.com |
a47272c4b2d6fdecc3c7a6f6df0c9a462ee39e40 | 94b132d7b3663e9c2541e1d56e083635373efe42 | /src/MainFunction/NumSubmat.java | c0150bd4f35c7341b9312288fb2349cfb01be066 | [] | no_license | daixing1/leetcode- | 62a3f82c25b4ec1e77959ee0dc3d745f64301061 | 270ce542855607dde6623245da63d21815237ef3 | refs/heads/master | 2020-11-27T11:47:53.884492 | 2020-08-24T01:52:43 | 2020-08-24T01:52:43 | 229,425,258 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,565 | java | package MainFunction;
/**
* User: 兴希
* Date: 2020/7/15
* Time: 20:34
* Description: 给你一个只包含 0 和 1 的 rows * columns 矩阵 mat ,请你返回有多少个 子矩形 的元素全部都是 1 。
*/
public class NumSubmat {
public int numSubmat(int[][] mat) {
int sum = 0;
int[][] left = new int[mat.length][mat[0].length];
int[][] up = new int[mat.length][mat[0].length];
for (int i=0;i<mat.length;i++){
for (int j=0;j<mat[0].length;j++){
if (mat[i][j]==1){
left[i][j] = left[i][Math.max(j-1,0)]+1;
up[i][j] = up[Math.max(i-1,0)][j]+1;
sum+=left[i][j]+up[i][j]-1;
}
}
}
for (int i=1;i<mat.length;i++){
for (int j=1;j<mat[0].length;j++) {
if (left[i][j]>1){
int tmp = left[i][j];
for (int k=i-1;k>=0;k--){
if (left[k][j]>1){
tmp = Math.min(tmp,left[k][j]);
sum+=tmp-1;
}else {
break;
}
}
}
}
}
return sum;
}
public static void main(String[] args) {
NumSubmat numSubmat = new NumSubmat();
int i = numSubmat.numSubmat(new int[][]{
{0,1,1,0},
{0,1,1,1},
{1,1,1,0}
});
System.out.println(i);
}
}
| [
"790976320@qq.com"
] | 790976320@qq.com |
bfee4b7dc31ff537aee70f34208886c2dbed2709 | 900d3d4e311010f6d8619e358102c8e48cf40368 | /Graphs/Graph/HamiltonianPath.java | 2a0a88f1e6d2e8223f6db4f2346188d13f37df24 | [] | no_license | Rranjan04/Problem-Solving-Using-DSA | d1dfb4af2f4dcee253847100305488adc25fba16 | c31d7e7c5ef63405f9c47e9487568c58d08c6c8e | refs/heads/main | 2023-06-12T13:48:55.655456 | 2021-07-07T07:44:47 | 2021-07-07T07:44:47 | 379,459,178 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,260 | java | package Graphs.Graph;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
public class HamiltonianPath {
static class Edge{
int v;
int n;
Edge(int v, int n){
this.v = v;
this.n = n;
}
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int k = scn.nextInt();
ArrayList<Edge>[] graph = new ArrayList[n];
for(int v=0;v< n;v++){
graph[v] = new ArrayList<>();
}
for(int e=0;e<k;e++){
int v1 = scn.nextInt();
int v2 = scn.nextInt();
graph[v1].add(new Edge(v1, v2));
graph[v2].add(new Edge(v2, v1));
}
scn.close();
int src = 0;
HashSet<Integer> visited = new HashSet<>();
hamiltonian(graph,src,visited,src+" ",src);
}
static void hamiltonian(ArrayList<Edge>[] graph, int src, HashSet<Integer> visited, String path,int osrc){
visited.add(src);
if(visited.size()==graph.length){
System.out.print(path);
for(Edge e:graph[src]){
if(e.n==osrc){
System.out.println("*");
return;
}
}
System.out.println(".");
return;
}
for(Edge e:graph[src]){
if(!visited.contains(e.n)){
hamiltonian(graph, e.n, visited, path+" "+e.n,osrc);
}
}
visited.remove(src);
}
}
| [
"rranjan1922@gmail.com"
] | rranjan1922@gmail.com |
d7d7f928e91777bfe18879bb4293bc88621c960f | c0ce58addc8d976f48475fc0cdc0114afeb61596 | /conference-web/src/main/java/com/prodyna/conference/web/rest/RESTEnabler.java | c07d8cc607ee40d21d4af897e4967f11d390194c | [] | no_license | aslakknutsen/conference | 48067b72018d9d96cff7a2e1e3a59a3ce1ec60fe | 68a4b03cd741dd1f6753cfc2c6aa470e2cbb7315 | refs/heads/master | 2020-12-25T11:31:26.565840 | 2014-06-23T08:53:51 | 2014-06-23T08:53:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 201 | java | package com.prodyna.conference.web.rest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/rest")
public class RESTEnabler extends Application {
// ok
}
| [
"darko@krizic.net"
] | darko@krizic.net |
42af1ee565eebaea5c00706a4e018b1548c1715c | a24192569a2cb6f0b423c4e32ff8753b3e496a39 | /BE/dts/src/main/java/com/microservices/dts/resources/KafkaConsumer.java | 94d33c3457698b2ed11e27649289906b3dfe976d | [] | no_license | duttasujoy/CloudDataAnalytics | 0cfcc750e055f6f55c81189ea04a29e882b98ece | 438f3976a5f829600e3d6b2b5499bc60a6547833 | refs/heads/master | 2023-01-20T22:23:48.795965 | 2019-11-06T17:06:55 | 2019-11-06T17:06:55 | 220,025,883 | 0 | 0 | null | 2023-01-07T11:28:33 | 2019-11-06T15:14:32 | Java | UTF-8 | Java | false | false | 765 | java | package com.microservices.dts.resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import com.microservice.dts.pojo.MeterReadData;
import com.microservices.dts.service.DateTransmissionService;
@Component
public class KafkaConsumer {
@Value(value ="${configuration.property.kafka.topic}")
String topic;
@Autowired
private DateTransmissionService service;
@KafkaListener(topics = "MeterReadTopic", groupId = "group-id")
public void listen(MeterReadData data)
{
System.out.println("In consumer"+Thread.currentThread().getName()+data);
service.transfer(data);
}
}
| [
"dutta.sujoy@siemens.com"
] | dutta.sujoy@siemens.com |
fddbf63165fc6bd318700ac8637b4865d44b020a | 98641d113564372d1dd76e0cc74c3b78f146543b | /ctakes-web-client/src/main/java/org/apache/ctakes/web/client/servlet/Pipeline.java | 75bc17b9ecc80f1027360a1229fd2b086e08e3cc | [
"Apache-2.0"
] | permissive | saianuroop/examples | 89e40f154018d5f80279623a297d9188160f508b | b42dd7ae6da9b845df9783e0949b38054a1f9848 | refs/heads/master | 2020-12-27T15:35:51.167219 | 2015-07-01T15:46:53 | 2015-07-01T15:46:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,043 | 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.ctakes.web.client.servlet;
import java.io.FileNotFoundException;
import org.apache.ctakes.clinicalpipeline.ClinicalPipelineFactory;
import org.apache.ctakes.core.resource.FileLocator;
import org.apache.ctakes.core.resource.FileResourceImpl;
import org.apache.ctakes.dictionary.lookup2.ae.AbstractJCasTermAnnotator;
import org.apache.ctakes.dictionary.lookup2.ae.DefaultJCasTermAnnotator;
import org.apache.ctakes.dictionary.lookup2.ae.JCasTermAnnotator;
import org.apache.uima.fit.factory.AggregateBuilder;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.fit.factory.ExternalResourceFactory;
import org.apache.uima.resource.ResourceInitializationException;
public class Pipeline {
public static AggregateBuilder getAggregateBuilder() throws Exception {
AggregateBuilder builder = new AggregateBuilder();
//builder.add(ClinicalPipelineFactory.getFastPipeline());
builder.add( ClinicalPipelineFactory.getTokenProcessingPipeline() );
try {
builder.add( AnalysisEngineFactory.createEngineDescription( DefaultJCasTermAnnotator.class,
AbstractJCasTermAnnotator.PARAM_WINDOW_ANNOT_PRP,
"org.apache.ctakes.typesystem.type.textspan.Sentence",
JCasTermAnnotator.DICTIONARY_DESCRIPTOR_KEY,
ExternalResourceFactory.createExternalResourceDescription(
FileResourceImpl.class,
FileLocator.locateFile( "org/apache/ctakes/dictionary/lookup/fast/cTakesHsql.xml" ) )
) );
} catch ( FileNotFoundException e ) {
e.printStackTrace();
throw new ResourceInitializationException( e );
}
// builder.add( PolarityCleartkAnalysisEngine.createAnnotatorDescription() );
// builder.add( UncertaintyCleartkAnalysisEngine.createAnnotatorDescription() );
// builder.add( HistoryCleartkAnalysisEngine.createAnnotatorDescription() );
// builder.add( ConditionalCleartkAnalysisEngine.createAnnotatorDescription() );
// builder.add( GenericCleartkAnalysisEngine.createAnnotatorDescription() );
// builder.add( SubjectCleartkAnalysisEngine.createAnnotatorDescription() );
return builder;
}
}
| [
"pei@Peis-MacBook-Pro.local"
] | pei@Peis-MacBook-Pro.local |
55c897eee13186e082db029c3ea289b113869f02 | 1fd8b5fc213b9f265662803fbd1217ac7527bbbd | /BearMaps/src/main/java/GraphBuildingHandler.java | 592ca991a724121ebbe1dc38a606ae591f8593c9 | [] | no_license | hdeng68/data-structures | a22c742218c96e9640630aa26110f6c11d4efc6c | 84f87726dfb4876d6e49d825c919861d4979d90c | refs/heads/master | 2020-04-02T12:37:14.200998 | 2018-10-24T05:53:06 | 2018-10-24T05:53:06 | 154,442,381 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,436 | java | import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;
/**
* Parses OSM XML files using an XML SAX parser. Used to construct the graph of roads for
* pathfinding, under some constraints.
* See OSM documentation on
* <a href="http://wiki.openstreetmap.org/wiki/Key:highway">the highway tag</a>,
* <a href="http://wiki.openstreetmap.org/wiki/Way">the way XML element</a>,
* <a href="http://wiki.openstreetmap.org/wiki/Node">the node XML element</a>,
* and the java
* <a href="https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html">SAX parser tutorial</a>.
*
* You may find the CSCourseGraphDB and CSCourseGraphDBHandler examples useful.
*
* The idea here is that some external library is going to walk through the XML
* file, and your override method tells Java what to do every time it gets to the next
* element in the file. This is a very common but strange-when-you-first-see it pattern.
* It is similar to the Visitor pattern we discussed for graphs.
*
* @author Alan Yao, Maurice Lee
*/
public class GraphBuildingHandler extends DefaultHandler {
/**
* Only allow for non-service roads; this prevents going on pedestrian streets as much as
* possible. Note that in Berkeley, many of the campus roads are tagged as motor vehicle
* roads, but in practice we walk all over them with such impunity that we forget cars can
* actually drive on them.
*/
private static final Set<String> ALLOWED_HIGHWAY_TYPES = new HashSet<>(Arrays.asList
("motorway", "trunk", "primary", "secondary", "tertiary", "unclassified",
"residential", "living_street", "motorway_link", "trunk_link", "primary_link",
"secondary_link", "tertiary_link"));
private String activeState = "";
private final GraphDB g;
private boolean validWay;
private String maxSpeed = null;
private Node lastInWay;
private Node previousNode;
private ArrayList<Node> nodesInWay;
/**
* Create a new GraphBuildingHandler.
* @param g The graph to populate with the XML data.
*/
public GraphBuildingHandler(GraphDB g) {
this.g = g;
}
/**
* Called at the beginning of an element. Typically, you will want to handle each element in
* here, and you may want to track the parent element.
* @param uri The Namespace URI, or the empty string if the element has no Namespace URI or
* if Namespace processing is not being performed.
* @param localName The local name (without prefix), or the empty string if Namespace
* processing is not being performed.
* @param qName The qualified name (with prefix), or the empty string if qualified names are
* not available. This tells us which element we're looking at.
* @param attributes The attributes attached to the element. If there are no attributes, it
* shall be an empty Attributes object.
* @throws SAXException Any SAX exception, possibly wrapping another exception.
* @see Attributes
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
/* Some example code on how you might begin to parse XML files. */
if (qName.equals("node")) {
/* We encountered a new <node...> tag. */
// System.out.println("Starting node");
activeState = "node";
// System.out.println("Node id: " + attributes.getValue("id"));
// System.out.println("Node lon: " + attributes.getValue("lon"));
// System.out.println("Node lat: " + attributes.getValue("lat"));
long id = Long.parseLong(attributes.getValue("id"));
double lat = Double.parseDouble(attributes.getValue("lat"));
double lon = Double.parseDouble(attributes.getValue("lon"));
Node current = new Node(id, lat, lon);
g.nodes.put(id, current);
previousNode = current;
/* Hint: A graph-like structure would be nice. */
} else if (qName.equals("way")) {
/* We encountered a new <way...> tag. */
lastInWay = null;
nodesInWay = new ArrayList<>();
activeState = "way";
validWay = false;
// System.out.println("Beginning a way...");
// System.out.println("Way id: " + attributes.getValue("id"));
} else if (activeState.equals("way") && qName.equals("nd")) {
/* While looking at a way, we found a <nd...> tag. */
// System.out.println("Id of a node in this way: " + attributes.getValue("ref"));
long ref = Long.parseLong(attributes.getValue("ref"));
Node currentInWay = g.nodes.get(ref);
nodesInWay.add(currentInWay);
/* Hint1: It would be useful to remember what was the last node in this way. */
/* Hint2: Not all ways are valid. So, directly connecting the nodes here would be
cumbersome since you might have to remove the connections if you later see a tag that
makes this way invalid. Instead, think of keeping a list of possible connections and
remember whether this way is valid or not. */
} else if (activeState.equals("way") && qName.equals("tag")) {
/* While looking at a way, we found a <tag...> tag. */
String k = attributes.getValue("k");
String v = attributes.getValue("v");
if (k.equals("maxspeed")) {
// System.out.println("Max Speed: " + v);
maxSpeed = v;
} else if (k.equals("highway")) {
// System.out.println("Highway type: " + v);
if (ALLOWED_HIGHWAY_TYPES.contains(v)) {
validWay = true;
}
/* Hint: Setting a "flag" is good enough! */
} else if (k.equals("name")) {
int dummy = 0;
// System.out.println("Way Name: " + v);
}
// System.out.println("Tag with k=" + k + ", v=" + v + ".");
} else if (activeState.equals("node") && qName.equals("tag") && attributes.getValue("k")
.equals("name")) {
/* While looking at a node, we found a <tag...> with k="name". */
Location loc = new Location(attributes.getValue("v"), previousNode);
/* Hint: Since we found this <tag...> INSIDE a node, we should probably remember which
node this tag belongs to. Remember XML is parsed top-to-bottom, so probably it's the
last node that you looked at (check the first if-case). */
// System.out.println("Node's name: " + attributes.getValue("v"));
}
}
/**
* Receive notification of the end of an element. You may want to take specific terminating
* actions here, like finalizing vertices or edges found.
* @param uri The Namespace URI, or the empty string if the element has no Namespace URI or
* if Namespace processing is not being performed.
* @param localName The local name (without prefix), or the empty string if Namespace
* processing is not being performed.
* @param qName The qualified name (with prefix), or the empty string if qualified names are
* not available.
* @throws SAXException Any SAX exception, possibly wrapping another exception.
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("way")) {
if (validWay) {
for (int i = 0; i < nodesInWay.size() - 1; i++) {
Node first = nodesInWay.get(i);
Node second = nodesInWay.get(i + 1);
first.addNeighbor(second);
second.addNeighbor(first);
}
}
/* We are done looking at a way. (We finished looking at the nodes, speeds, etc...)*/
/* Hint1: If you have stored the possible connections for this way, here's your
chance to actually connect the nodes together if the way is valid. */
}
}
}
| [
"hdeng68@berkeley.edu"
] | hdeng68@berkeley.edu |
81bb1487ab921bb6be3541b3d7403dd8f5d2a623 | 15db4052cb5b8b418129c982643d0b86567d7721 | /novice/03-05/localization/android/app/src/main/java/com/example/localization/MainActivity.java | 9ced8a449896a1e3d0d0c6cbf35cd9b1217ef136 | [] | no_license | m-noer/praxis-academy | 00968791588bbc9467bb2b96e6ada977aa839453 | ff9f66d40c908df3e59ba80fdf9fa738f7191a67 | refs/heads/master | 2020-06-29T19:18:14.365592 | 2019-08-29T09:49:18 | 2019-08-29T09:49:18 | 200,601,570 | 2 | 5 | null | null | null | null | UTF-8 | Java | false | false | 369 | java | package com.example.localization;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
}
}
| [
"mnoer@outlook.com"
] | mnoer@outlook.com |
7536d077617b196636a80789936463bb7d2471fc | ad3201579c051cfa51a6b7b9fedfaf6025632584 | /temp/src/minecraft_server/net/minecraft/network/play/server/S10PacketSpawnPainting.java | 1e09cc46587f490ce6ad5b3d8236df41fcb3194c | [] | no_license | 435886030/MineCraft_Warden | fd56270a6f92528649fef8b83024af8f63206274 | fe32994b07daae5255b2d6d06a4967d7704ce980 | refs/heads/master | 2016-09-01T15:58:17.531748 | 2016-04-09T17:53:43 | 2016-04-09T17:53:43 | 55,838,172 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,965 | java | package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.entity.item.EntityPainting;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
public class S10PacketSpawnPainting implements Packet {
private int field_148973_a;
private BlockPos field_179838_b;
private EnumFacing field_179839_c;
private String field_148968_f;
private static final String __OBFID = "CL_00001280";
public S10PacketSpawnPainting() {}
public S10PacketSpawnPainting(EntityPainting p_i45170_1_) {
this.field_148973_a = p_i45170_1_.func_145782_y();
this.field_179838_b = p_i45170_1_.func_174857_n();
this.field_179839_c = p_i45170_1_.field_174860_b;
this.field_148968_f = p_i45170_1_.field_70522_e.field_75702_A;
}
public void func_148837_a(PacketBuffer p_148837_1_) throws IOException {
this.field_148973_a = p_148837_1_.func_150792_a();
this.field_148968_f = p_148837_1_.func_150789_c(EntityPainting.EnumArt.field_180001_A);
this.field_179838_b = p_148837_1_.func_179259_c();
this.field_179839_c = EnumFacing.func_176731_b(p_148837_1_.readUnsignedByte());
}
public void func_148840_b(PacketBuffer p_148840_1_) throws IOException {
p_148840_1_.func_150787_b(this.field_148973_a);
p_148840_1_.func_180714_a(this.field_148968_f);
p_148840_1_.func_179255_a(this.field_179838_b);
p_148840_1_.writeByte(this.field_179839_c.func_176736_b());
}
public void func_180722_a(INetHandlerPlayClient p_180722_1_) {
p_180722_1_.func_147288_a(this);
}
// $FF: synthetic method
// $FF: bridge method
public void func_148833_a(INetHandler p_148833_1_) {
this.func_180722_a((INetHandlerPlayClient)p_148833_1_);
}
}
| [
"435886030@qq.com"
] | 435886030@qq.com |
53b9f41eca28aaf408c77cb63fb12fcdc3e89ee7 | 9a8349e3e961699c4eb582e1bc0a571fcf3d28b6 | /HomeDecoration/Desktop/src/main/java/com/giants/hd/desktop/frames/Main.java | bbc5d504c32648147c25633c0138691c50aa597b | [] | no_license | davidleen/WorkSpace | bb31ce2768b31d5e1276fc1d2eb014bd2ed57836 | 058b94c7092f531076c5bb7b629a4c028658fbc9 | refs/heads/master | 2021-09-12T07:19:45.209564 | 2021-09-05T15:49:03 | 2021-09-05T15:49:03 | 150,992,553 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 41,108 | java | package com.giants.hd.desktop.frames;
import com.giants.hd.desktop.MyDesktopManager;
import com.giants.hd.desktop.dialogs.*;
import com.giants.hd.desktop.local.HdSwingWorker;
import com.giants.hd.desktop.local.ImageLoader;
import com.giants.hd.desktop.local.LocalFileHelper;
import com.giants.hd.desktop.local.PropertyWorker;
import com.giants.hd.desktop.utils.AuthorityUtil;
import com.giants.hd.desktop.utils.Config;
import com.giants.hd.desktop.utils.ShortcutHelper;
import com.giants.hd.desktop.widget.BackgroundPainter;
import com.giants3.hd.domain.api.ApiManager;
import com.giants3.hd.domain.api.CacheManager;
import com.giants3.hd.domain.api.HttpUrl;
import com.giants3.hd.entity.AppVersion;
import com.giants3.hd.entity.User;
import com.giants3.hd.exception.HdException;
import com.giants3.hd.noEntity.BufferData;
import com.giants3.hd.noEntity.ModuleConstant;
import com.giants3.hd.noEntity.RemoteData;
import com.giants3.report.ResourceUrl;
import com.google.inject.Guice;
import com.google.inject.Inject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
//import org.apache.commons.logging.Log;
/**
* Created by davidleen29 on 2015/5/6.
*/
public class Main extends BaseFrame {
JDesktopPane desktop;
public static final String TITLE = "报价系统";
@Inject
ApiManager apiManager;
public static void setUIFont(javax.swing.plaf.FontUIResource f) {
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put(key, f);
}
}
public Main() {
super(TITLE);
//Set up the GUI.
desktop = new JDesktopPane(); //a specialized layered pane
desktop.setDesktopManager(new MyDesktopManager(desktop));
setContentPane(desktop);
//Make dragging a little faster but perhaps uglier.
desktop.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
ShortcutHelper.createShortcut();
String baseUrl = PropertyWorker.readData("BaseUrl");
if (null != baseUrl) {
HttpUrl.iniBaseUrl(baseUrl);
HttpUrl.setApiVersion(1);
ResourceUrl.setBaseUrl(baseUrl.replace("Server","Resource"));
}
Config.DEBUG = false;
try {
boolean isDebug = Boolean.parseBoolean(PropertyWorker.readData("isDebug"));
Config.DEBUG = isDebug;
} catch (Throwable t) {
t.printStackTrace();
}
int version = PropertyWorker.getVersion().versionCode;
HttpUrl.setVersionCode(version);
Guice.createInjector().injectMembers(this);
//保存全局引用
instance = this;
}
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
LocalFileHelper.printThrowable(e);
e.printStackTrace();
System.exit(1);
}
});
//throw new RuntimeException("aaaaaaaaaaaaaaaa");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
initLookAndFeel();
init();
}
});
}
/**
* 配置界面的样式
*/
private static void initLookAndFeel() {
try {
// // Set cross-platform Java L&F (also called "Metal")
// UIManager.setLookAndFeel(
// UIManager.getCrossPlatformLookAndFeelClassName());
//
// // Set System L&F
// UIManager.setLookAndFeel(
// UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel(javax.swing.plaf.nimbus.NimbusLookAndFeel.class.getName());
// setUIFont(new javax.swing.plaf.FontUIResource("宋体", Font.PLAIN, 18));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
//设置分页标签选中时候颜色为红色
// UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Enabled].backgroundPainter", new BackgroundPainter(Color.white));
// UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Enabled+MouseOver].backgroundPainter", new BackgroundPainter(Color.white));
// UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Enabled+Pressed].backgroundPainter", new BackgroundPainter(Color.white));
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Focused+MouseOver+Selected].backgroundPainter", new BackgroundPainter(Color.RED));
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Focused+Pressed+Selected].backgroundPainter", new BackgroundPainter(Color.RED));
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Focused+Selected].backgroundPainter", new BackgroundPainter(Color.RED));
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[MouseOver+Selected].backgroundPainter", new BackgroundPainter(Color.RED));
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Pressed+Selected].backgroundPainter", new BackgroundPainter(Color.RED));
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Selected].backgroundPainter", new BackgroundPainter(Color.RED));
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab[Selected].backgroundPainter", new BackgroundPainter(Color.RED));
UIManager.getLookAndFeelDefaults().put("TableHeader.cellBorder", BorderFactory.createLineBorder(Color.LIGHT_GRAY));
}
/**
* 应用程序初始化
*/
private static final void init() {
final Main frame = new Main();
;
frame.setExtendedState(MAXIMIZED_BOTH);
// frame.generateMenu();
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
//主界面 移除通用监听器 强制退出提示
for (WindowListener listener : frame.getWindowListeners())
frame.removeWindowListener(listener);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
//点击了退出系统按钮
int option = JOptionPane.showConfirmDialog(frame, "确定要退出吗?", " 提示", JOptionPane.OK_CANCEL_OPTION);
if (JOptionPane.OK_OPTION == option) {
//点击了确定按钮
frame.dispose();
System.exit(0);
}
}
});
frame.pack();
frame.setVisible(true);
//ask for login
LoginDialog dialog = new LoginDialog(frame);
dialog.setLocationRelativeTo(frame);
dialog.setModal(true);
dialog.setVisible(true);
if (dialog.getResult() == null) {
System.exit(0);
} else {
frame.preLoadData(dialog.getResult());
}
sayHello();
}
private static void sayHello() {
// Log logger= MyLogger.Logger(Main.class);
// logger.info("hello");
// logger.warn("testtesttetstt");
}
/**
* 生成菜单
*/
public void generateMenu() {
JMenuBar menuBar;
//Create the menu bar.
menuBar = new JMenuBar();
if (AuthorityUtil.getInstance().viewProductModule())
menuBar.add(createProduct());
if (AuthorityUtil.getInstance().viewQuotationModule())
menuBar.add(createQuotation());
if (AuthorityUtil.getInstance().viewOrderMenu())
menuBar.add(createOrder());
//生产流程
if (AuthorityUtil.getInstance().viewWorkFlowModule())
menuBar.add(createWorkFlowMenu());
if (AuthorityUtil.getInstance().viewStockModule())
menuBar.add(createStockManager());
if (AuthorityUtil.getInstance().viewBaseDataModule())
menuBar.add(createBaseData());
if (AuthorityUtil.getInstance().viewAuthorityModule())
menuBar.add(createAuthority());
if (AuthorityUtil.getInstance().viewSystemModule())
menuBar.add(createSysetm());
menuBar.add(createPersonal());
menuBar.add(createHelp());
//System.exit(0);
setJMenuBar(menuBar);
}
/**
* 生产流程菜单
*
* @return
*/
private JMenu createWorkFlowMenu() {
//Build second menu in the menu bar.
JMenu menu = new JMenu(ModuleConstant.TITLE_WORK_FLOW_MODULE);
if (AuthorityUtil.getInstance().viewWorkFlow()) {
JMenuItem menuItem = new JMenuItem("生产流程查看");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WorkFlowFrame frame = new WorkFlowFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewWorkFlowWorker()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_WORK_FLOW_WORKER);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WorkFlowWorkerFrame frame = new WorkFlowWorkerFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewWorkFlowLimit()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_WORK_FLOW_LIMIT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WorkFlowLimitConfigFrame frame = new WorkFlowLimitConfigFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewSubWorkFlowList()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_SUB_WORK_FLOW);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BaseInternalFrame frame = new SubWorkFlowListFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewWorkFLowEventConfig()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_WORK_FLOW_ITEM_EVENT_CONFIG);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WorkFlowEventConfigFrame frame = new WorkFlowEventConfigFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewZhilingdan()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_ZHILINGDAN);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ZhilingdanFrame frame = new ZhilingdanFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().isViewable(ModuleConstant.NAME_UNHANDLE_MESSAGE_REPORT)) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_UNHANDLE_MESSAGE_REPORT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WorkFlowMessageReportFrame frame = new WorkFlowMessageReportFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().isViewable(ModuleConstant.NAME_PRODUCER_VALUE_CONFIG)) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_PRODUCER_VALUE_CONFIG);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProducerValueConfigFrame frame = new ProducerValueConfigFrame();
addInterFrame(frame);
}
});
} if (AuthorityUtil.getInstance().isViewable(ModuleConstant.NAME_WORK_FLOW_QUERY)) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_WORK_FLOW_QUERY);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WorkFlowQueryFrame frame = new WorkFlowQueryFrame();
addInterFrame(frame);
}
});
}
return menu;
}
/**
* 库存列表
*
* @return
*/
private JMenu createStockManager() {
//Build second menu in the menu bar.
JMenu menu = new JMenu(ModuleConstant.TITLE_STOCK);
if (AuthorityUtil.getInstance().viewStockOutList()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_STOCK_OUT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StockListFrame frame = new StockListFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewStockInAndSubmit()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_STOCK_IN_AND_SUBMIT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StockInAndSubmitFrame frame = new StockInAndSubmitFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewTransportOut()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_TRANSPORT_OUT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StockXiaokuFrame frame = new StockXiaokuFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().viewXiaokuItemSearch()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_TRANSPORT_OUT_SEARCH);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StockOutSumitFrame frame = new StockOutSumitFrame();
addInterFrame(frame);
}
});
}
return menu;
}
public JMenu createProduct() {
JMenu menu;
menu = new JMenu("产品模块");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
//a group of JMenuItems
JMenuItem menuItem;
if (AuthorityUtil.getInstance().viewProductList()) {
menuItem = new JMenuItem("产品列表",
KeyEvent.VK_P);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_P, ActionEvent.ALT_MASK));
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProductListInternalFrame productListInternalFrame = new ProductListInternalFrame();
productListInternalFrame.setVisible(true); //necessary as of 1.3
desktop.add(productListInternalFrame);
try {
productListInternalFrame.setSelected(true);
} catch (java.beans.PropertyVetoException exception) {
}
// desktop.add()
// Main.this.setContentPane(new Panel_ProductList().getRoot());
}
});
// menu.addSeparator();
}
if (AuthorityUtil.getInstance().viewProductPicture()) {
menuItem = new JMenuItem("产品图片");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Main.this.setContentPane(new Panel_Material("").getRoot());
ProductPictureDialog dialog = new ProductPictureDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewMaterialList()) {
menuItem = new JMenuItem("材料列表",
KeyEvent.VK_M);
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_M, ActionEvent.ALT_MASK));
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MaterialListInternalFrame materialListInternalFrame = new MaterialListInternalFrame();
addInterFrame(materialListInternalFrame);
}
});
}
if (AuthorityUtil.getInstance().viewMaterialPicture()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_MATERIAL_PICTURE);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MaterialPictureDialog dialog = new MaterialPictureDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewProductDelete()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_PRODUCT_DELETE);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProductDeleteDialog dialog = new ProductDeleteDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewProductReport()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_PRODUCT_REPORT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProductReportInternalFrame materialListInternalFrame = new ProductReportInternalFrame();
addInterFrame(materialListInternalFrame);
}
});
}
return menu;
}
/**
* 报价模块
*
* @return
*/
private JMenu createQuotation() {
JMenu menu = new JMenu("报价管理");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"This menu does nothing");
if (AuthorityUtil.getInstance().viewQuotationList()) {
JMenuItem menuItem = new JMenuItem("报价列表"
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuotationInternalFrame quotationInternalFrame = new QuotationInternalFrame();
addInterFrame(quotationInternalFrame);
// setContentPane(new Panel_Quotation().getRoot());
}
});
}
if (AuthorityUtil.getInstance().viewQuotationDeleteList()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_QUOTATION_DELETE);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuotationDeleteDialog dialog = new QuotationDeleteDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewQuotationPictureExport()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_QUTOTATION_PICTURE_EXPORT
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
QuotationPictureExportFrame quotationInternalFrame = new QuotationPictureExportFrame();
addInterFrame(quotationInternalFrame);
}
});
}
if (AuthorityUtil.getInstance().viewAppQuotationList()) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_APP_QUOTATION
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AppQuotationInternalFrame quotationInternalFrame = new AppQuotationInternalFrame();
addInterFrame(quotationInternalFrame);
}
});
}
if (AuthorityUtil.getInstance().isViewable(ModuleConstant.NAME_APP_QUOTATION_SYNC)) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_APP_QUOTATION_SYNC
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AppQuotationSyncFrame frame = new AppQuotationSyncFrame();
addInterFrame(frame);
}
});
}
if (AuthorityUtil.getInstance().isViewable(ModuleConstant.NAME_APP_QUOTATION_REPORT)) {
JMenuItem menuItem = new JMenuItem(ModuleConstant.TITLE_APP_QUOTATION_REPORT
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AppQuotationReportFrame frame = new AppQuotationReportFrame();
addInterFrame(frame);
}
});
}
return menu;
}
/**
* 添加测试菜单
*
* @return
*/
private JMenu createBaseData() {
JMenu menu = new JMenu("基础数据");
JMenuItem menuItem;
if (AuthorityUtil.getInstance().viewCompanyInfo()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_COMPANY_INFO
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CompanyInfoDialog dialog = new CompanyInfoDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewMaterialClassList()) {
menuItem = new JMenuItem("材质类型列表"
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MaterialClassDialog dialog = new MaterialClassDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewCustomerList()) {
menuItem = new JMenuItem("客户列表");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CustomerDialog dialog = new CustomerDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewOutFactoryList()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_OUT_FACTORY);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
OutFactoryDialog dialog = new OutFactoryDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewProductArrangeType()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_PRODUCT_ARRANGE_TYPE);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProductArrangeTypeDialog dialog = new ProductArrangeTypeDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewProcessList()) {
menuItem = new JMenuItem("工序列表");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Main.this.setContentPane(new Panel_BaseData().getRoot());
ProductProcessFrame dialog = new ProductProcessFrame( );
addInterFrame(dialog);
}
});
}
if (AuthorityUtil.getInstance().viewPackMaterialClassList()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_PACK_MATERIAL_CLASS
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PackMaterialClassDialog dialog = new PackMaterialClassDialog(Main.this);
dialog.setLocationRelativeTo(getRootPane());
dialog.setVisible(true);
}
});
}
// // if(AuthorityUtil.getInstance().viewPackMaterialClassList()) {
// menuItem = new JMenuItem(Module.TITLE_PACK_MATERIAL_TEMPLATE
// );
// menu.add(menuItem);
//
//
// menuItem.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// PackMaterialTemplateDialog dialog = new PackMaterialTemplateDialog(Main.this);
// dialog.setLocationRelativeTo(getRootPane());
// dialog.setVisible(true);
// }
// });
// // }
return menu;
}
/**
* 权限菜单
*
* @return
*/
public JMenu createAuthority() {
//Build second menu in the menu bar.
JMenu menu = new JMenu("权限管理");
//
JMenuItem menuItem = new JMenuItem("用户列表");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UserDialog dialog = new UserDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
//
menuItem = new JMenuItem("模块列表");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ModuleDialog dialog = new ModuleDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
//
menuItem = new JMenuItem("权限设置");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AuthorityDialog dialog = new AuthorityDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
//
menuItem = new JMenuItem("细分权限");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AuthRelatesDialog dialog = new AuthRelatesDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
return menu;
}
/**
* 订单菜单
*
* @return
*/
public JMenu createOrder() {
JMenu menu = new JMenu(ModuleConstant.TITLE_ORDER);
//
JMenuItem menuItem = new JMenuItem("订单列表");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
OrderListInternalFrame productListInternalFrame = new OrderListInternalFrame();
addInterFrame(productListInternalFrame);
}
});
if (AuthorityUtil.getInstance().viewOrderReport()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_ORDER_REPORT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
OrderReportInternalFrame productListInternalFrame = new OrderReportInternalFrame();
addInterFrame(productListInternalFrame);
}
});
}
if (AuthorityUtil.getInstance().viewOrderWorkFlowReport()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_ORDER_WORK_FLOW_REPORT);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
OrderWorkFlowReportInternalFrame orderWorkFlowReportInternalFrame = new OrderWorkFlowReportInternalFrame();
addInterFrame(orderWorkFlowReportInternalFrame);
}
});
}
// if (AuthorityUtil.getInstance().viewOrderItemForArrange()) {
// menuItem = new JMenuItem(ModuleConstant.TITLE_ORDER_ITEM_FOR_ARRANGE);
// menu.add(menuItem);
//
// menuItem.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
//
//
// OrderItemForArrangeListFrame orderWorkFlowReportInternalFrame = new OrderItemForArrangeListFrame();
// addInterFrame(orderWorkFlowReportInternalFrame);
//
// }
// });
// }
return menu;
}
public void addInterFrame(BaseInternalFrame baseInternalFrame) {
baseInternalFrame.setVisible(true); //necessary as of 1.3
desktop.add(baseInternalFrame);
try {
baseInternalFrame.setSelected(true);
} catch (java.beans.PropertyVetoException exception) {
exception.printStackTrace();
}
}
/**
* 添加测试菜单
*
* @return
*/
private JMenu createSysetm() {
//Build second menu in the menu bar.
JMenu menu = new JMenu("系统功能");
JMenuItem menuItem;
if (AuthorityUtil.getInstance().viewSyncData()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_SYNC_DATA);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SyncDialog dialog = new SyncDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
}
if (AuthorityUtil.getInstance().viewSysParam()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_SYS_PARAM);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SysParamDialog dialog = new SysParamDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
}
//任务定时面板
if (AuthorityUtil.getInstance().viewTaskManage()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_TASK_MANAGE);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TaskListInternalFrame taskListInternalFrame = new TaskListInternalFrame();
taskListInternalFrame.setVisible(true); //necessary as of 1.3
desktop.add(taskListInternalFrame);
try {
taskListInternalFrame.setSelected(true);
} catch (java.beans.PropertyVetoException exception) {
}
// setContentPane(new Panel_Quotation().getRoot());
}
});
}
//查看公式
if (AuthorityUtil.getInstance().viewEquation()) {
menuItem = new JMenuItem(ModuleConstant.TITLE_EQUATION);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TaskListInternalFrame taskListInternalFrame = new TaskListInternalFrame();
taskListInternalFrame.setVisible(true); //necessary as of 1.3
desktop.add(taskListInternalFrame);
try {
taskListInternalFrame.setSelected(true);
} catch (java.beans.PropertyVetoException exception) {
}
// setContentPane(new Panel_Quotation().getRoot());
}
});
}
menuItem = new JMenuItem("重启");
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//启动应用程序
try {
JOptionPane.showMessageDialog(Main.this, "重新启动应用程序");
Thread.sleep(500);
Process p = Runtime.getRuntime().exec("java -Xmx1024M -jar " + "估价系统.jar");
//退出程序
System.exit(0);
} catch (IOException ex5) {
ex5.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
//
//
//
// final LoadingDialog dialog=new LoadingDialog(Main.this, new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
//
// }
// });
//
//
// UseCaseFactory.createUpdateXiankang().execute(new Subscriber() {
// @Override
// public void onCompleted() {
// dialog.setVisible(false);
// dialog.dispose();
// JOptionPane.showMessageDialog(Main.this,"调整成功");
//
//
// }
//
// @Override
// public void onError(Throwable e) {
// dialog.setVisible(false);
// dialog.dispose();
// JOptionPane.showMessageDialog(Main.this,e.getMessage());
// }
//
// @Override
// public void onNext(Object o) {
//
// }
// });
//
// dialog.setVisible(true);
// }
// });
return menu;
}
/**
* 个人设置模块
*/
private JMenu createPersonal() {
JMenu menu = new JMenu("个人模块");
//
JMenuItem menuItem = new JMenuItem("修改密码"
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UpdatePasswordDialog dialog = new UpdatePasswordDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
return menu;
}
/**
* 帮助菜单
*/
private JMenu createHelp() {
JMenu menu = new JMenu("帮助");
//
JMenuItem menuItem = new JMenuItem("检查更新"
);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UpgradeDialog dialog = new UpgradeDialog(Main.this);
dialog.pack();
dialog.setVisible(true);
}
});
return menu;
}
/**
* 预先加载数据
*/
private void preLoadData(final User user) {
new HdSwingWorker<BufferData, Object>(this, "数据预加载处理 请稍后。。。") {
@Override
protected RemoteData<BufferData> doInBackground() throws Exception {
return apiManager.loadInitData(user);
}
@Override
public void onResult(RemoteData<BufferData> data) {
CacheManager.getInstance().bufferData = data.datas.get(0);
CacheManager.getInstance().bufferData.loginUser = user;
generateMenu();
AppVersion currentVersion = PropertyWorker.getVersion();
setTitle(TITLE + " (" + user.toString() + ") " + "当前版本" + currentVersion.versionName + "(" + currentVersion.versionCode + ")");
}
@Override
public void onHandleError(HdException exception) {
JOptionPane.showMessageDialog(Main.this, "数据初始化失败,请检查网络,重新打开。" + exception.getLocalizedMessage());
System.exit(0);
}
}.go();
}
@Override
public void dispose() {
ImageLoader.getInstance().close();
super.dispose();
}
//主界面的引用
static Main instance;
public static Main getInstance() {
return instance;
}
}
| [
"davidleen29@gmail.com"
] | davidleen29@gmail.com |
182797251b8baf1698f1e584cf2e9776958a7c6c | acb7afb2f1b9e544a00185a9a5901a90d9e5cc51 | /spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java | a535d79f0eefa37447fa7e2cde606d9295054524 | [
"Apache-2.0"
] | permissive | xianwdong/spring-framework | b2d7182eb30f0e2f6593864171166b27a01b7e71 | 8725342649bcaca5e1b9561305343f61890fc83a | refs/heads/master | 2023-06-11T08:13:19.087159 | 2021-07-05T06:29:03 | 2021-07-05T06:29:03 | 255,587,456 | 0 | 0 | Apache-2.0 | 2020-04-14T11:13:14 | 2020-04-14T11:13:13 | null | UTF-8 | Java | false | false | 53,450 | java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.support;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.CachedIntrospectionResults;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.support.ResourceEditorRegistrar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.context.LifecycleProcessor;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.context.weaving.LoadTimeWeaverAware;
import org.springframework.context.weaving.LoadTimeWeaverAwareProcessor;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* Abstract implementation of the {@link org.springframework.context.ApplicationContext}
* interface. Doesn't mandate the type of storage used for configuration; simply
* implements common context functionality. Uses the Template Method design pattern,
* requiring concrete subclasses to implement abstract methods.
*
* <p>In contrast to a plain BeanFactory, an ApplicationContext is supposed
* to detect special beans defined in its internal bean factory:
* Therefore, this class automatically registers
* {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessors},
* {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessors},
* and {@link org.springframework.context.ApplicationListener ApplicationListeners}
* which are defined as beans in the context.
*
* <p>A {@link org.springframework.context.MessageSource} may also be supplied
* as a bean in the context, with the name "messageSource"; otherwise, message
* resolution is delegated to the parent context. Furthermore, a multicaster
* for application events can be supplied as an "applicationEventMulticaster" bean
* of type {@link org.springframework.context.event.ApplicationEventMulticaster}
* in the context; otherwise, a default multicaster of type
* {@link org.springframework.context.event.SimpleApplicationEventMulticaster} will be used.
*
* <p>Implements resource loading by extending
* {@link org.springframework.core.io.DefaultResourceLoader}.
* Consequently treats non-URL resource paths as class path resources
* (supporting full class path resource names that include the package path,
* e.g. "mypackage/myresource.dat"), unless the {@link #getResourceByPath}
* method is overridden in a subclass.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Mark Fisher
* @author Stephane Nicoll
* @since January 21, 2001
* @see #refreshBeanFactory
* @see #getBeanFactory
* @see org.springframework.beans.factory.config.BeanFactoryPostProcessor
* @see org.springframework.beans.factory.config.BeanPostProcessor
* @see org.springframework.context.event.ApplicationEventMulticaster
* @see org.springframework.context.ApplicationListener
* @see org.springframework.context.MessageSource
*/
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
/**
* Name of the MessageSource bean in the factory.
* If none is supplied, message resolution is delegated to the parent.
* @see MessageSource
*/
public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";
/**
* Name of the LifecycleProcessor bean in the factory.
* If none is supplied, a DefaultLifecycleProcessor is used.
* @see org.springframework.context.LifecycleProcessor
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
/**
* Name of the ApplicationEventMulticaster bean in the factory.
* If none is supplied, a default SimpleApplicationEventMulticaster is used.
* @see org.springframework.context.event.ApplicationEventMulticaster
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
static {
// Eagerly load the ContextClosedEvent class to avoid weird classloader issues
// on application shutdown in WebLogic 8.1. (Reported by Dustin Woods.)
ContextClosedEvent.class.getName();
}
/** Logger used by this class. Available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Unique id for this context, if any. */
private String id = ObjectUtils.identityToString(this);
/** Display name. */
private String displayName = ObjectUtils.identityToString(this);
/** Parent context. */
@Nullable
private ApplicationContext parent;
/** Environment used by this context. */
@Nullable
private ConfigurableEnvironment environment;
/** BeanFactoryPostProcessors to apply on refresh. */
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();
/** System time in milliseconds when this context started. */
private long startupDate;
/** Flag that indicates whether this context is currently active. */
private final AtomicBoolean active = new AtomicBoolean();
/** Flag that indicates whether this context has been closed already. */
private final AtomicBoolean closed = new AtomicBoolean();
/** Synchronization monitor for the "refresh" and "destroy". */
private final Object startupShutdownMonitor = new Object();
/** Reference to the JVM shutdown hook, if registered. */
@Nullable
private Thread shutdownHook;
/** ResourcePatternResolver used by this context. */
private ResourcePatternResolver resourcePatternResolver;
/** LifecycleProcessor for managing the lifecycle of beans within this context. */
@Nullable
private LifecycleProcessor lifecycleProcessor;
/** MessageSource we delegate our implementation of this interface to. */
@Nullable
private MessageSource messageSource;
/** Helper class used in event publishing. */
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;
/** Statically specified listeners. */
private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
/** Local listeners registered before refresh. */
@Nullable
private Set<ApplicationListener<?>> earlyApplicationListeners;
/** ApplicationEvents published before the multicaster setup. */
@Nullable
private Set<ApplicationEvent> earlyApplicationEvents;
/**
* Create a new AbstractApplicationContext with no parent.
*/
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
/**
* Create a new AbstractApplicationContext with the given parent context.
* @param parent the parent context
*/
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
//---------------------------------------------------------------------
// Implementation of ApplicationContext interface
//---------------------------------------------------------------------
/**
* Set the unique id of this application context.
* <p>Default is the object id of the context instance, or the name
* of the context bean if the context is itself defined as a bean.
* @param id the unique id of the context
*/
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getApplicationName() {
return "";
}
/**
* Set a friendly name for this context.
* Typically done during initialization of concrete context implementations.
* <p>Default is the object id of the context instance.
*/
public void setDisplayName(String displayName) {
Assert.hasLength(displayName, "Display name must not be empty");
this.displayName = displayName;
}
/**
* Return a friendly name for this context.
* @return a display name for this context (never {@code null})
*/
@Override
public String getDisplayName() {
return this.displayName;
}
/**
* Return the parent context, or {@code null} if there is no parent
* (that is, this context is the root of the context hierarchy).
*/
@Override
@Nullable
public ApplicationContext getParent() {
return this.parent;
}
/**
* Set the {@code Environment} for this application context.
* <p>Default value is determined by {@link #createEnvironment()}. Replacing the
* default with this method is one option but configuration through {@link
* #getEnvironment()} should also be considered. In either case, such modifications
* should be performed <em>before</em> {@link #refresh()}.
* @see org.springframework.context.support.AbstractApplicationContext#createEnvironment
*/
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
this.environment = environment;
}
/**
* Return the {@code Environment} for this application context in configurable
* form, allowing for further customization.
* <p>If none specified, a default environment will be initialized via
* {@link #createEnvironment()}.
*/
@Override
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}
/**
* Create and return a new {@link StandardEnvironment}.
* <p>Subclasses may override this method in order to supply
* a custom {@link ConfigurableEnvironment} implementation.
*/
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
/**
* Return this context's internal bean factory as AutowireCapableBeanFactory,
* if already available.
* @see #getBeanFactory()
*/
@Override
public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException {
return getBeanFactory();
}
/**
* Return the timestamp (ms) when this context was first loaded.
*/
@Override
public long getStartupDate() {
return this.startupDate;
}
/**
* Publish the given event to all listeners.
* <p>Note: Listeners get initialized after the MessageSource, to be able
* to access it within listener implementations. Thus, MessageSource
* implementations cannot publish events.
* @param event the event to publish (may be application-specific or a
* standard framework event)
*/
@Override
public void publishEvent(ApplicationEvent event) {
publishEvent(event, null);
}
/**
* Publish the given event to all listeners.
* <p>Note: Listeners get initialized after the MessageSource, to be able
* to access it within listener implementations. Thus, MessageSource
* implementations cannot publish events.
* @param event the event to publish (may be an {@link ApplicationEvent}
* or a payload object to be turned into a {@link PayloadApplicationEvent})
*/
@Override
public void publishEvent(Object event) {
publishEvent(event, null);
}
/**
* Publish the given event to all listeners.
* @param event the event to publish (may be an {@link ApplicationEvent}
* or a payload object to be turned into a {@link PayloadApplicationEvent})
* @param eventType the resolved event type, if known
* @since 4.2
*/
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}
// Multicast right now if possible - or lazily once the multicaster is initialized
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}
// Publish event via parent context as well...
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
this.parent.publishEvent(event);
}
}
}
/**
* Return the internal ApplicationEventMulticaster used by the context.
* @return the internal ApplicationEventMulticaster (never {@code null})
* @throws IllegalStateException if the context has not been initialized yet
*/
ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
if (this.applicationEventMulticaster == null) {
throw new IllegalStateException("ApplicationEventMulticaster not initialized - " +
"call 'refresh' before multicasting events via the context: " + this);
}
return this.applicationEventMulticaster;
}
/**
* Return the internal LifecycleProcessor used by the context.
* @return the internal LifecycleProcessor (never {@code null})
* @throws IllegalStateException if the context has not been initialized yet
*/
LifecycleProcessor getLifecycleProcessor() throws IllegalStateException {
if (this.lifecycleProcessor == null) {
throw new IllegalStateException("LifecycleProcessor not initialized - " +
"call 'refresh' before invoking lifecycle methods via the context: " + this);
}
return this.lifecycleProcessor;
}
/**
* Return the ResourcePatternResolver to use for resolving location patterns
* into Resource instances. Default is a
* {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver},
* supporting Ant-style location patterns.
* <p>Can be overridden in subclasses, for extended resolution strategies,
* for example in a web environment.
* <p><b>Do not call this when needing to resolve a location pattern.</b>
* Call the context's {@code getResources} method instead, which
* will delegate to the ResourcePatternResolver.
* @return the ResourcePatternResolver for this context
* @see #getResources
* @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
*/
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
//---------------------------------------------------------------------
// Implementation of ConfigurableApplicationContext interface
//---------------------------------------------------------------------
/**
* Set the parent of this application context.
* <p>The parent {@linkplain ApplicationContext#getEnvironment() environment} is
* {@linkplain ConfigurableEnvironment#merge(ConfigurableEnvironment) merged} with
* this (child) application context environment if the parent is non-{@code null} and
* its environment is an instance of {@link ConfigurableEnvironment}.
* @see ConfigurableEnvironment#merge(ConfigurableEnvironment)
*/
@Override
public void setParent(@Nullable ApplicationContext parent) {
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
}
}
}
@Override
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
this.beanFactoryPostProcessors.add(postProcessor);
}
/**
* Return the list of BeanFactoryPostProcessors that will get applied
* to the internal BeanFactory.
*/
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
Assert.notNull(listener, "ApplicationListener must not be null");
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.addApplicationListener(listener);
}
this.applicationListeners.add(listener);
}
/**
* Return the list of statically specified ApplicationListeners.
*/
public Collection<ApplicationListener<?>> getApplicationListeners() {
return this.applicationListeners;
}
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备刷新,对系统属性或者环境变量进行准备及验证 todo 怎么验证
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 初始化BeanFactory,并进行XML文件读取,这里得到的BeanFactory已经包含了解析出来的BeanDefinition
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 对BeanFactory进行各种功能填充
// 比如@Autowired注解和@Qualifier注解的支持
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 子类覆盖方法做额外的处理
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 激活各种BeanFactory处理器:todo 比如?
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册拦截bean创建的bean处理器,这里只是注册,真正的调用在getBean的时候 todo 怎么拦截
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 国际化处理
initMessageSource();
// Initialize event multicaster for this context.
// 初始化应用消息多播器,并放入"applicationEventMulticaster"bean中
// 逻辑很简单,先获取"applicationEventMulticaster"的bean,没有就使用默认的
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 留给子类来初始化其他的bean
onRefresh();
// Check for listener beans and register them.
// 在所有注册的bean中查找Listener bean,注册到消息广播器中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化剩下的非惰性加载的bean,不仅包括BeanFactory中的bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 完成刷新过程,通知生命周期处理器LifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
// 留给子类实现
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 验证系统变量,默认没有需要校验的环境变量,需要的话可以重写该类
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
/**
* <p>Replace any stub property sources with actual instances.
* @see org.springframework.core.env.PropertySource.StubPropertySource
* @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
*/
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
// 表达式语言相关
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 属性编辑器相关
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
/**
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
/**
* Initialize the MessageSource.
* Use parent's if none defined in this context.
*/
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
/**
* Initialize the LifecycleProcessor.
* Uses DefaultLifecycleProcessor if none defined in the context.
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
/**
* Template method which can be overridden to add context-specific refresh work.
* Called on initialization of special beans, before instantiation of singletons.
* <p>This implementation is empty.
* @throws BeansException in case of errors
* @see #refresh()
*/
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 初始化一个LifecycleProcessor,默认使用DefaultLifecycleProcessor
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
// 调用所有lifecycle的start方法
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
/**
* Cancel this context's refresh attempt, resetting the {@code active} flag
* after an exception got thrown.
* @param ex the exception that led to the cancellation
*/
protected void cancelRefresh(BeansException ex) {
this.active.set(false);
}
/**
* Reset Spring's common reflection metadata caches, in particular the
* {@link ReflectionUtils}, {@link AnnotationUtils}, {@link ResolvableType}
* and {@link CachedIntrospectionResults} caches.
* @since 4.2
* @see ReflectionUtils#clearCache()
* @see AnnotationUtils#clearCache()
* @see ResolvableType#clearCache()
* @see CachedIntrospectionResults#clearClassLoader(ClassLoader)
*/
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
/**
* Register a shutdown hook with the JVM runtime, closing this context
* on JVM shutdown unless it has already been closed at that time.
* <p>Delegates to {@code doClose()} for the actual closing procedure.
* @see Runtime#addShutdownHook
* @see #close()
* @see #doClose()
*/
@Override
public void registerShutdownHook() {
if (this.shutdownHook == null) {
// No shutdown hook registered yet.
this.shutdownHook = new Thread() {
@Override
public void run() {
synchronized (startupShutdownMonitor) {
doClose();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
/**
* Callback for destruction of this instance, originally attached
* to a {@code DisposableBean} implementation (not anymore in 5.0).
* <p>The {@link #close()} method is the native way to shut down
* an ApplicationContext, which this method simply delegates to.
* @deprecated as of Spring Framework 5.0, in favor of {@link #close()}
*/
@Deprecated
public void destroy() {
close();
}
/**
* Close this application context, destroying all beans in its bean factory.
* <p>Delegates to {@code doClose()} for the actual closing procedure.
* Also removes a JVM shutdown hook, if registered, as it's not needed anymore.
* @see #doClose()
* @see #registerShutdownHook()
*/
@Override
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
// If we registered a JVM shutdown hook, we don't need it anymore now:
// We've already explicitly closed the context.
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// ignore - VM is already shutting down
}
}
}
}
/**
* Actually performs context closing: publishes a ContextClosedEvent and
* destroys the singletons in the bean factory of this application context.
* <p>Called by both {@code close()} and a JVM shutdown hook, if any.
* @see org.springframework.context.event.ContextClosedEvent
* @see #destroyBeans()
* @see #close()
* @see #registerShutdownHook()
*/
protected void doClose() {
// Check whether an actual close attempt is necessary...
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (logger.isDebugEnabled()) {
logger.debug("Closing " + this);
}
LiveBeansView.unregisterApplicationContext(this);
try {
// Publish shutdown event.
publishEvent(new ContextClosedEvent(this));
}
catch (Throwable ex) {
logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
}
// Stop all Lifecycle beans, to avoid delays during individual destruction.
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
}
catch (Throwable ex) {
logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
}
}
// Destroy all cached singletons in the context's BeanFactory.
destroyBeans();
// Close the state of this context itself.
closeBeanFactory();
// Let subclasses do some final clean-up if they wish...
onClose();
// Reset local application listeners to pre-refresh state.
if (this.earlyApplicationListeners != null) {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Switch to inactive.
this.active.set(false);
}
}
/**
* Template method for destroying all beans that this context manages.
* The default implementation destroy all cached singletons in this context,
* invoking {@code DisposableBean.destroy()} and/or the specified
* "destroy-method".
* <p>Can be overridden to add context-specific bean destruction steps
* right before or right after standard singleton destruction,
* while the context's BeanFactory is still active.
* @see #getBeanFactory()
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons()
*/
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}
/**
* Template method which can be overridden to add context-specific shutdown work.
* The default implementation is empty.
* <p>Called at the end of {@link #doClose}'s shutdown procedure, after
* this context's BeanFactory has been closed. If custom shutdown logic
* needs to execute while the BeanFactory is still active, override
* the {@link #destroyBeans()} method instead.
*/
protected void onClose() {
// For subclasses: do nothing by default.
}
@Override
public boolean isActive() {
return this.active.get();
}
/**
* Assert that this context's BeanFactory is currently active,
* throwing an {@link IllegalStateException} if it isn't.
* <p>Invoked by all {@link BeanFactory} delegation methods that depend
* on an active context, i.e. in particular all bean accessor methods.
* <p>The default implementation checks the {@link #isActive() 'active'} status
* of this context overall. May be overridden for more specific checks, or for a
* no-op if {@link #getBeanFactory()} itself throws an exception in such a case.
*/
protected void assertBeanFactoryActive() {
if (!this.active.get()) {
if (this.closed.get()) {
throw new IllegalStateException(getDisplayName() + " has been closed already");
}
else {
throw new IllegalStateException(getDisplayName() + " has not been refreshed yet");
}
}
}
//---------------------------------------------------------------------
// Implementation of BeanFactory interface
//---------------------------------------------------------------------
@Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, requiredType);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, args);
}
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(requiredType);
}
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(requiredType, args);
}
@Override
public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) {
assertBeanFactoryActive();
return getBeanFactory().getBeanProvider(requiredType);
}
@Override
public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) {
assertBeanFactoryActive();
return getBeanFactory().getBeanProvider(requiredType);
}
@Override
public boolean containsBean(String name) {
return getBeanFactory().containsBean(name);
}
@Override
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isSingleton(name);
}
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isPrototype(name);
}
@Override
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isTypeMatch(name, typeToMatch);
}
@Override
public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isTypeMatch(name, typeToMatch);
}
@Override
@Nullable
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().getType(name);
}
@Override
public String[] getAliases(String name) {
return getBeanFactory().getAliases(name);
}
//---------------------------------------------------------------------
// Implementation of ListableBeanFactory interface
//---------------------------------------------------------------------
@Override
public boolean containsBeanDefinition(String beanName) {
return getBeanFactory().containsBeanDefinition(beanName);
}
@Override
public int getBeanDefinitionCount() {
return getBeanFactory().getBeanDefinitionCount();
}
@Override
public String[] getBeanDefinitionNames() {
return getBeanFactory().getBeanDefinitionNames();
}
@Override
public String[] getBeanNamesForType(ResolvableType type) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type);
}
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type);
}
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
}
@Override
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type);
}
@Override
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type, includeNonSingletons, allowEagerInit);
}
@Override
public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForAnnotation(annotationType);
}
@Override
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansWithAnnotation(annotationType);
}
@Override
@Nullable
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().findAnnotationOnBean(beanName, annotationType);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory interface
//---------------------------------------------------------------------
@Override
@Nullable
public BeanFactory getParentBeanFactory() {
return getParent();
}
@Override
public boolean containsLocalBean(String name) {
return getBeanFactory().containsLocalBean(name);
}
/**
* Return the internal bean factory of the parent context if it implements
* ConfigurableApplicationContext; else, return the parent context itself.
* @see org.springframework.context.ConfigurableApplicationContext#getBeanFactory
*/
@Nullable
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext ?
((ConfigurableApplicationContext) getParent()).getBeanFactory() : getParent());
}
//---------------------------------------------------------------------
// Implementation of MessageSource interface
//---------------------------------------------------------------------
@Override
public String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) {
return getMessageSource().getMessage(code, args, defaultMessage, locale);
}
@Override
public String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException {
return getMessageSource().getMessage(code, args, locale);
}
@Override
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
return getMessageSource().getMessage(resolvable, locale);
}
/**
* Return the internal MessageSource used by the context.
* @return the internal MessageSource (never {@code null})
* @throws IllegalStateException if the context has not been initialized yet
*/
private MessageSource getMessageSource() throws IllegalStateException {
if (this.messageSource == null) {
throw new IllegalStateException("MessageSource not initialized - " +
"call 'refresh' before accessing messages via the context: " + this);
}
return this.messageSource;
}
/**
* Return the internal message source of the parent context if it is an
* AbstractApplicationContext too; else, return the parent context itself.
*/
@Nullable
protected MessageSource getInternalParentMessageSource() {
return (getParent() instanceof AbstractApplicationContext ?
((AbstractApplicationContext) getParent()).messageSource : getParent());
}
//---------------------------------------------------------------------
// Implementation of ResourcePatternResolver interface
//---------------------------------------------------------------------
@Override
public Resource[] getResources(String locationPattern) throws IOException {
return this.resourcePatternResolver.getResources(locationPattern);
}
//---------------------------------------------------------------------
// Implementation of Lifecycle interface
//---------------------------------------------------------------------
@Override
public void start() {
getLifecycleProcessor().start();
publishEvent(new ContextStartedEvent(this));
}
@Override
public void stop() {
getLifecycleProcessor().stop();
publishEvent(new ContextStoppedEvent(this));
}
@Override
public boolean isRunning() {
return (this.lifecycleProcessor != null && this.lifecycleProcessor.isRunning());
}
//---------------------------------------------------------------------
// Abstract methods that must be implemented by subclasses
//---------------------------------------------------------------------
/**
* Subclasses must implement this method to perform the actual configuration load.
* The method is invoked by {@link #refresh()} before any other initialization work.
* <p>A subclass will either create a new bean factory and hold a reference to it,
* or return a single BeanFactory instance that it holds. In the latter case, it will
* usually throw an IllegalStateException if refreshing the context more than once.
* @throws BeansException if initialization of the bean factory failed
* @throws IllegalStateException if already initialized and multiple refresh
* attempts are not supported
*/
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
/**
* Subclasses must implement this method to release their internal bean factory.
* This method gets invoked by {@link #close()} after all other shutdown work.
* <p>Should never throw an exception but rather log shutdown failures.
*/
protected abstract void closeBeanFactory();
/**
* Subclasses must return their internal bean factory here. They should implement the
* lookup efficiently, so that it can be called repeatedly without a performance penalty.
* <p>Note: Subclasses should check whether the context is still active before
* returning the internal bean factory. The internal factory should generally be
* considered unavailable once the context has been closed.
* @return this application context's internal bean factory (never {@code null})
* @throws IllegalStateException if the context does not hold an internal bean factory yet
* (usually if {@link #refresh()} has never been called) or if the context has been
* closed already
* @see #refreshBeanFactory()
* @see #closeBeanFactory()
*/
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
/**
* Return information about this context.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getDisplayName());
sb.append(", started on ").append(new Date(getStartupDate()));
ApplicationContext parent = getParent();
if (parent != null) {
sb.append(", parent: ").append(parent.getDisplayName());
}
return sb.toString();
}
}
| [
"xianwdong@163.com"
] | xianwdong@163.com |
66e442734a1564607e4476df522bcb1b4ef384fa | 84ab3779e0a85d2011eccb1270df98f9cca19660 | /Tictactoe.java | d460d031a029aeef795855f73b79ec3fe76eef5e | [] | no_license | tango4567/Java | ed964b5aa04bb84a36cdaf3f3ed21cee01e2f746 | 80bf9b09499355593d22b536bfec968bd8f3439d | refs/heads/master | 2021-01-11T07:35:54.578435 | 2017-02-17T23:24:16 | 2017-02-17T23:24:16 | 31,380,194 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,577 | java | import java.io.*;
class Tictactoe
{
char matrix[][]; /* the tic tac toe matrix */
public static void main(String args[]) throws IOException
{
Tictactoe obj=new Tictactoe();
System.out.println(“This is the game of Tic Tac Toe.\n”);
System.out.println(“You will be playing against the computer.\n”);
char done = ‘ ‘;
obj.init_matrix();
do {
obj.disp_matrix();
obj.get_player_move();
done = obj.check(); /* see if winner */
if(done!= ‘ ‘) break; /* winner!*/
obj.get_computer_move();
done = obj.check(); /* see if winner */
}
while(done== ‘ ‘);
if(done==’X’) System.out.println(“You won!\n”);
else System.out.println(“I won!!!!\n”);
obj.disp_matrix(); /* show final positions */
}
/* Initialize the matrix. */
void init_matrix()
{
matrix=new char[3][3];
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++) matrix[i][j] = ‘ ‘;
}
/* Get a player’s move. */
void get_player_move() throws IOException
{
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
int x, y;
System.out.println(“Enter X,Y coordinates for your move: “);
x=Integer.parseInt(buf.readLine());
y=Integer.parseInt(buf.readLine());
x–; y–;
if(matrix[x][y]!= ‘ ‘){
System.out.println(“Invalid move, try again.\n”);
get_player_move();
}
else matrix[x][y] = ‘X';
}
/* Get a move from the computer. */
void get_computer_move()
{
int i=0, j=0;
for(i=0; i<3; i++){
for(j=0; j<3; j++)
if(matrix[i][j]==’ ‘) break;
if(matrix[i][j]==’ ‘) break;
}
if(i*j==9) {
System.out.println(“\n”);//printf(“draw\n”);
System.exit(0);
}
else
matrix[i][j] = ‘O';
}
/* Display the matrix on the screen. */
void disp_matrix()
{
int t;
for(t=0; t<3; t++) {
System.out.printf(” %c | %c | %c “,matrix[t][0],
matrix[t][1], matrix [t][2]);
if(t!=2) System.out.printf(“%n—|—|—%n”);
}
System.out.printf(“%n”);
}
/* See if there is a winner. */
char check()
{
int i;
for(i=0; i<3; i++) /* check rows */
if(matrix[i][0]==matrix[i][1] &&
matrix[i][0]==matrix[i][2]) return matrix[i][0];
for(i=0; i<3; i++) /* check columns */
if(matrix[0][i]==matrix[1][i] &&
matrix[0][i]==matrix[2][i]) return matrix[0][i];
/* test diagonals */
if(matrix[0][0]==matrix[1][1] &&
matrix[1][1]==matrix[2][2])
return matrix[0][0];
if(matrix[0][2]==matrix[1][1] &&
matrix[1][1]==matrix[2][0])
return matrix[0][2];
return ‘ ‘;
}
} | [
"tarunmahajan4567@hotmail.com"
] | tarunmahajan4567@hotmail.com |
ca0106d0b7a17d469c0199c6583ab99109e54c90 | c172062840f77fc56486da6aaa7e19a96fe9e013 | /maquinaProjectTDD/src/maquinaProjectTDD/TestVaso.java | 40ce7a2a6912178262d61c71044a26f442629cbc | [] | no_license | esparta86/scrumDeveloperTrainning | 4ee160e8c38d47d7a10163ded042b86208edcdad | 9fb4984f03ce510bc5810c47f0d0f1a00e0803ec | refs/heads/master | 2020-03-30T04:58:47.197895 | 2018-09-28T17:26:58 | 2018-09-28T17:26:58 | 150,772,443 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,594 | java | package maquinaProjectTDD;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import Entities.Vaso;
public class TestVaso {
public Vaso vasoPequeno;
public Vaso vasoGrande;
public Vaso vasoMediano;
@Before
public void setUp() throws Exception {
this.vasoPequeno =new Vaso(5);
this.vasoGrande =new Vaso(5);
this.vasoMediano =new Vaso(5);
}
@Test
public void deberiaDevolverVerdaderoSiExistenVasosPequeno(){
boolean resultado = this.vasoPequeno.tieneVaso(1, 2);
assertEquals(true, resultado);
}
@Test
public void deberiaDevolverVerdaderoSiExistenVasosMediano(){
boolean resultado = this.vasoMediano.tieneVaso(1, 2);
assertEquals(true, resultado);
}
@Test
public void deberiaDevolverVerdaderoSiExistenVasosGrande(){
boolean resultado = this.vasoGrande.tieneVaso(1, 2);
assertEquals(true, resultado);
}
@Test
public void deberiaDevolverFalsoSiNoExistenVasosPequeno(){
boolean resultado = this.vasoPequeno.tieneVaso(10, 2);
assertEquals(false, resultado);
}
@Test
public void deberiaDevolverFalsoSiNoExistenVasosMediano(){
boolean resultado = this.vasoMediano.tieneVaso(10, 2);
assertEquals(false, resultado);
}
@Test
public void deberiaDevolverFalsoSiNoExistenVasosGrande(){
boolean resultado = this.vasoGrande.tieneVaso(10, 2);
assertEquals(false, resultado);
}
public void deberiaRestarCantidadDeVasosPequenos() throws Exception {
if(this.vasoPequeno.darVaso(1)) {
assertEquals(4, this.vasoPequeno.obtenerReserva());
}else {
throw new Exception("no valid test");
}
}
}
| [
"lisandro.rafaelano@telusinternational"
] | lisandro.rafaelano@telusinternational |
512503d71c18fa7701b8839a591d1afaccf5528c | f15889af407de46a94fd05f6226c66182c6085d0 | /newrich/src/main/java/com/oreon/phonestore/navigationUsecases/package-info.java | 92bd5abaa207ed93742d86a840ab505d87faa3a1 | [] | no_license | oreon/sfcode-full | 231149f07c5b0b9b77982d26096fc88116759e5b | bea6dba23b7824de871d2b45d2a51036b88d4720 | refs/heads/master | 2021-01-10T06:03:27.674236 | 2015-04-27T10:23:10 | 2015-04-27T10:23:10 | 55,370,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 50 | java | package com.oreon.phonestore.navigationUsecases;
| [
"singhj@38423737-2f20-0410-893e-9c0ab9ae497d"
] | singhj@38423737-2f20-0410-893e-9c0ab9ae497d |
71447b0490754320fc9270cd292e1d1d66599289 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_9541fb23272f8f92634325967c48cebebaf63b18/CapabilitiesMetaData/2_9541fb23272f8f92634325967c48cebebaf63b18_CapabilitiesMetaData_s.java | b37171840bea6a3ac355a36c872095cbdf7e1cab | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 4,022 | java | /*
* JBoss, Home of Professional Open Source
* Copyright 2008, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.classloading.spi.metadata;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.jboss.classloading.plugins.metadata.ModuleCapability;
import org.jboss.classloading.plugins.metadata.PackageCapability;
/**
* CapabilitiesMetaData.
*
* @author <a href="adrian@jboss.com">Adrian Brock</a>
* @version $Revision: 1.1 $
*/
@XmlType(name="capabilties", propOrder= {"capabilities"})
@XmlRootElement(name="capabilities", namespace="urn:jboss:classloading:1.0")
public class CapabilitiesMetaData implements Serializable, Cloneable
{
/** The serialVersionUID */
private static final long serialVersionUID = -7910704924025591308L;
/** The capabilities */
private List<Capability> capabilities;
/**
* Get the capabilities.
*
* @return the capabilities.
*/
public List<Capability> getCapabilities()
{
return capabilities;
}
/**
* Set the capabilities.
*
* @param capabilities the capabilities.
*/
@XmlElements
({
@XmlElement(name="module", type=ModuleCapability.class),
@XmlElement(name="package", type=PackageCapability.class)
})
@XmlAnyElement
public void setCapabilities(List<Capability> capabilities)
{
this.capabilities = capabilities;
}
/**
* Add a capability
*
* @param capability the capability
* @throws IllegalArgumentException for a null capability
*/
public void addCapability(Capability capability)
{
if (capability == null)
throw new IllegalArgumentException("Null capability");
if (capabilities == null)
capabilities = new CopyOnWriteArrayList<Capability>();
capabilities.add(capability);
}
/**
* Remove a capability
*
* @param capability the capability
* @throws IllegalArgumentException for a null capability
*/
public void removeCapability(Capability capability)
{
if (capability == null)
throw new IllegalArgumentException("Null capability");
if (capabilities == null)
return;
capabilities.remove(capability);
}
@Override
public CapabilitiesMetaData clone()
{
try
{
CapabilitiesMetaData clone = (CapabilitiesMetaData) super.clone();
if (capabilities != null)
{
List<Capability> clonedCapabilities = new CopyOnWriteArrayList<Capability>(capabilities);
clone.setCapabilities(clonedCapabilities);
}
return clone;
}
catch (CloneNotSupportedException e)
{
throw new RuntimeException("Unexpected", e);
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
cfd12f79bf9c093249ef9736e79fbf2532904d63 | c02847de9b582ea8a0b3d174be9aaae7f81a1a9b | /app/src/main/java/com/example/testapp/MainActivity2.java | a92a14899802105984e92ac67b53dc0e09f0f5f1 | [] | no_license | yaniv1888/Form_Buddy_app_FinalP | 85abc96b9ea1aa78431551ebe94bb005bbec596a | 8391ca23c594d0ed21ff435b659fc77c957352bc | refs/heads/master | 2023-05-04T11:23:08.330965 | 2021-05-20T10:50:24 | 2021-05-20T10:50:24 | 369,173,827 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 545 | java | package com.example.testapp;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
public class MainActivity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
} | [
"34810001+yaniv1888@users.noreply.github.com"
] | 34810001+yaniv1888@users.noreply.github.com |
0b8f7a5cf1e80c3816e52a683dd7217436852e6f | ee5c90593544a5d31194d48106c28eff17a4d506 | /src/main/java/br/edu/fatecsjc/creche/repository/UsuarioRepository.java | bb54e5a9ab1d0f564f5434cbbc5494265e2081a2 | [] | no_license | giulianogimenez/vagas-creche | 56d5ed4b92e03a0a7c2b9af2db220f17a92b3102 | 16b7a53ca457514e6e074ab1c02df51b5822a728 | refs/heads/master | 2021-04-15T19:02:20.690294 | 2018-06-20T23:00:55 | 2018-06-20T23:00:55 | 126,899,568 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 397 | java | package br.edu.fatecsjc.creche.repository;
import br.edu.fatecsjc.creche.model.Usuario;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UsuarioRepository extends JpaRepository<Usuario, Long> {
Usuario findByEmail(String email);
Usuario findById(Long id);
Usuario findByNome(String nome);
}
| [
"camilo.moreira@fatec.sp.gov.br"
] | camilo.moreira@fatec.sp.gov.br |
04ab830e6e71f6fd5debd0b97ca2819a9f40b0bf | 9f6dd374049306c5756295ddabc576688da17469 | /src/es/ucm/look/ar/ar3D/core/drawables/primitives/SquarePrimitive.java | 0b0c9b0f70b2a705208d46119aeab4056e8363c4 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | jcreixell/Look | e91652844b51773df2e85224f79535e97755a08e | 81da0684f887a3301eebc99a5ce336304b9d8f88 | refs/heads/master | 2021-01-23T20:13:56.130259 | 2012-03-17T16:42:03 | 2012-03-17T16:42:03 | 3,749,036 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,462 | java | /**
*-----------------------------------------------------------------------------
* Copyright (c) 2012, Look! Development Team
* All rights reserved.
*
* Distributed under the terms of the BSD Simplified License.
*
* The full license is in the LICENSE file, distributed with this software.
*-----------------------------------------------------------------------------
*/
package es.ucm.look.ar.ar3D.core.drawables.primitives;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.microedition.khronos.opengles.GL10;
import es.ucm.look.ar.ar3D.core.drawables.Mesh3D;
import es.ucm.look.ar.math.collision.SphericalArmature;
import es.ucm.look.ar.math.geom.Point3;
public class SquarePrimitive extends Mesh3D {
public SquarePrimitive( ){
float vertices[] = new float[]{
0.0f, -1.0f, -1.0f,
0.0f, 1.0f, -1.0f,
0.0f, -1.0f, 1.0f,
0.0f, 1.0f, 1.0f
};
ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuf.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
armature = new SphericalArmature( new Point3( 0, 0, 0 ), 1.0f);
}
public void draw(GL10 gl){
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
}
| [
"jcreixell@gmail.com"
] | jcreixell@gmail.com |
e53583c267920caca95167c40aff460de87dd1be | b19b3a02b548220023d7266bc6a85a25518f3319 | /back/leetcode/page2/PascalsTriangle2.java | 9ad8dca5809e56d1ee651474af96382fc0a8127c | [] | no_license | yangseungin/algo | 40ab28734cf23515bf34fcc1da8f9ba169f54f8f | 03c96b21a79425988dc76e842f940e9e642ac1d5 | refs/heads/master | 2022-05-08T07:54:26.087728 | 2022-04-01T15:03:45 | 2022-04-01T15:03:45 | 177,534,719 | 1 | 1 | null | 2019-04-07T10:50:53 | 2019-03-25T07:20:12 | Java | UTF-8 | Java | false | false | 661 | java | package page2;
import java.util.ArrayList;
import java.util.List;
public class PascalsTriangle2 {
public static void main(String[] args) {
System.out.println(getRow(0));
}
public static List<Integer> getRow(int rowIndex) {
List<List<Integer>> cal = new ArrayList<>();
List<Integer> first = new ArrayList<>();
first.add(1);
if(rowIndex<=0){
return first;
}
cal.add(first);
for(int i=2;i<=rowIndex+1;i++){
List<Integer> tmp = new ArrayList<>();
tmp.add(1);
for(int j=0;j<first.size()-1;j++){
tmp.add(first.get(j)+first.get(j+1));
}
tmp.add(1);
cal.add(tmp);
first=tmp;
}
return first;
}
}
| [
"rhfpdk92@naver.com"
] | rhfpdk92@naver.com |
89b28219eeac8189675b50a110c6146d73b8a2e3 | 52a71f0ea809d49dc9dfeb79fea6aac3762f768b | /linkkin/app/src/main/java/com/asif/linkkin/LockActivity.java | 106d4e1c344519669c72b0047e1e34c92f290a44 | [] | no_license | mhd-asif/Android | c0ec0fba9d905d712a596473d60419a8ed9fb620 | 8f0c184fcd24a72719a41305867c319fb338d1cd | refs/heads/master | 2021-01-10T06:30:02.299642 | 2018-03-13T02:43:18 | 2018-03-13T02:43:18 | 52,959,192 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,658 | java | package com.asif.linkkin;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.asif.linkkin.utils.Font;
import com.asif.linkkin.utils.SharedDataSaveLoad;
/**
* Created by kanchan on 12/27/2015.
*/
public class LockActivity extends AppCompatActivity implements TextView.OnEditorActionListener{
LinearLayout linearRoot;
RelativeLayout relativeRoot;
EditText edtPin;
TextView txtOk;
String pin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lock);
linearRoot=(LinearLayout)findViewById(R.id.linearRoot);
relativeRoot=(RelativeLayout)findViewById(R.id.relativeRoot);
edtPin = (EditText) findViewById(R.id.edtPin);
txtOk=(TextView)findViewById(R.id.txtOk);
edtPin.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
Font.LATO_Regular.apply(this,edtPin);
Font.LATO_Bold.apply(this,txtOk);
Font.LATO_Bold.apply(this, (TextView) findViewById(R.id.txtDesc));
edtPin.setOnEditorActionListener(this);
ViewTreeObserver observer = linearRoot.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
int rootHeight = linearRoot.getHeight();
relativeRoot.getLayoutParams().height = rootHeight;
linearRoot.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
txtOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pin="";
pin=edtPin.getText().toString();
if(pin.equals("")) Toast.makeText(getApplicationContext(),"Please type your secret pin",Toast.LENGTH_SHORT).show();
else
{
String originalPin= SharedDataSaveLoad.load(LockActivity.this, getResources().getString(R.string.shared_pref_lock_pin));
if(!pin.equals(originalPin))
{
Toast.makeText(getApplicationContext(),"Wrong secret pin",Toast.LENGTH_SHORT).show();
}
else
{
finish();
}
}
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
@Override
public void onBackPressed() {
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE)
{
pin="";
pin=edtPin.getText().toString();
if(pin.equals("")) Toast.makeText(getApplicationContext(),"Please type your secret pin",Toast.LENGTH_SHORT).show();
else
{
String originalPin= SharedDataSaveLoad.load(LockActivity.this, getResources().getString(R.string.shared_pref_lock_pin));
if(!pin.equals(originalPin))
{
Toast.makeText(getApplicationContext(),"Wrong secret pin",Toast.LENGTH_SHORT).show();
}
else
{
finish();
}
}
}
return true;
}
}
| [
"mhd.asif.1988@gmail.com"
] | mhd.asif.1988@gmail.com |
3457eeb140dc2451c4c4ea79e16af224cb8d8057 | d8758c3b5495bce4ed8884063f7fdad1172b4c56 | /src/main/java/com/configuration/SecurityConfiguration.java | aca45352d82ed227dd22f61bc7cac65682ab9815 | [] | no_license | piotrekjaromin/inzynierka | 923a5d3a4fef0cf26dff29c6fb83c698a908fd91 | da9de8f345961d5063faa163f40d37bcbdf99d42 | refs/heads/master | 2021-01-11T02:31:05.019148 | 2016-12-26T22:11:40 | 2016-12-26T22:11:40 | 70,954,099 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,436 | java | package com.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new CryptWithMD5();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/index", "/rest/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/user/**").access("hasAnyRole('USER', 'ADMIN')")
.and().formLogin().loginPage("/login")
.usernameParameter("login").passwordParameter("password")
.and().exceptionHandling().accessDeniedPage("/Access_Denied")
.and().csrf().disable();
}
}
| [
"piotrek.jaromin@gmail.com"
] | piotrek.jaromin@gmail.com |
6797fc44b5bf97c49b9b4cd5b3b0a34787cb6fc3 | 937927893e3a2d47081de8e5f1344d0726ae1901 | /WeChat-Application/src/main/java/com/thoughtworks/wechat_application/services/admin/AdminResourceKey.java | a5081bcd74a83cf209ea4dd14353b05fcaa36226 | [] | no_license | BigEgg/WeChat-Platform | 758aabb98e6d4afc20f512992633a9bbd371347a | 6e5edc5934ef73b40871d7a90870f055dbdb9f68 | refs/heads/master | 2020-05-17T08:38:55.717138 | 2015-08-26T06:24:46 | 2015-08-26T06:24:46 | 41,408,074 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 256 | java | package com.thoughtworks.wechat_application.services.admin;
public enum AdminResourceKey {
WECHAT_APP_TOKEN,
WECHAT_APP_ID,
WECHAT_APP_SECRET,
WECHAT_CONNECTION_STATUS,
WECHAT_API_STATUS,
SUBSCRIBE_RESPONSE,
DEFAULT_RESPONSE
}
| [
"cd_bigegg@hotmail.com"
] | cd_bigegg@hotmail.com |
507035d165445907ec7a4e06f2bb055696e253cf | a9a302f6df51025ec13b2950e335b7d27bc93190 | /Lab4/LazyPrimMSTImproved.java | 9861c4a5d93c44390d28a8549199ca3d25240ecb | [] | no_license | henryhp17/CS2010-solutions | 577b4d25834f26180103dfe3994bf1cfeb250807 | 6bd3c1fd09cc7254cf866b1d51ce618fc84bdac8 | refs/heads/master | 2020-04-19T08:46:30.916262 | 2016-08-27T16:45:32 | 2016-08-27T16:45:32 | 66,724,537 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,923 | java | /******************************************************************************
* Compilation: javac LazyPrimMST.java
* Execution: java LazyPrimMST filename.txt
* Dependencies: EdgeWeightedGraph.java Edge.java Queue.java
* MinPQ.java UF.java In.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/43mst/tinyEWG.txt
* http://algs4.cs.princeton.edu/43mst/mediumEWG.txt
* http://algs4.cs.princeton.edu/43mst/largeEWG.txt
*
* Compute a minimum spanning forest using a lazy version of Prim's
* algorithm.
*
* % java LazyPrimMST tinyEWG.txt
* 0-7 0.16000
* 1-7 0.19000
* 0-2 0.26000
* 2-3 0.17000
* 5-7 0.28000
* 4-5 0.35000
* 6-2 0.40000
* 1.81000
*
* % java LazyPrimMST mediumEWG.txt
* 0-225 0.02383
* 49-225 0.03314
* 44-49 0.02107
* 44-204 0.01774
* 49-97 0.03121
* 202-204 0.04207
* 176-202 0.04299
* 176-191 0.02089
* 68-176 0.04396
* 58-68 0.04795
* 10.46351
*
* % java LazyPrimMST largeEWG.txt
* ...
* 647.66307
*
******************************************************************************/
/* Henry Pratama Suryadi A0105182R
Lab 4 Submission */
/**
* The <tt>LazyPrimMST</tt> class represents a data type for computing a
* <em>minimum spanning tree</em> in an edge-weighted graph.
* The edge weights can be positive, zero, or negative and need not
* be distinct. If the graph is not connected, it computes a <em>minimum
* spanning forest</em>, which is the union of minimum spanning trees
* in each connected component. The <tt>weight()</tt> method returns the
* weight of a minimum spanning tree and the <tt>edges()</tt> method
* returns its edges.
* <p>
* This implementation uses a lazy version of <em>Prim's algorithm</em>
* with a binary heap of edges.
* The constructor takes time proportional to <em>E</em> log <em>E</em>
* and extra space (not including the graph) proportional to <em>E</em>,
* where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
* Afterwards, the <tt>weight()</tt> method takes constant time
* and the <tt>edges()</tt> method takes time proportional to <em>V</em>.
* <p>
* For additional documentation,
* see <a href="http://algs4.cs.princeton.edu/43mst">Section 4.3</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* For alternate implementations, see {@link PrimMST}, {@link KruskalMST},
* and {@link BoruvkaMST}.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class LazyPrimMSTImproved {
private static final double FLOATING_POINT_EPSILON = 1E-12;
private double weight; // total weight of MST
private Queue<Edge> mst; // edges in the MST
private boolean[] marked; // marked[v] = true if v on tree
private MinPQ<Edge> pq; // edges with one endpoint in tree
private int numHeapComp, numScan; //required measurements
/**
* Compute a minimum spanning tree (or forest) of an edge-weighted graph.
* @param G the edge-weighted graph
*/
public LazyPrimMSTImproved(EdgeWeightedGraph G) {
numHeapComp = 0;
numScan = 0;
mst = new Queue<Edge>();
pq = new MinPQ<Edge>();
marked = new boolean[G.V()];
boolean isProcess = true; // stop if already found V - 1 edges
for (int v = 0; v < G.V() && isProcess; v++) { // run Prim from all vertices to
if (!marked[v]) {
isProcess = prim(G, v); // get a minimum spanning forest
}
}
numHeapComp = pq.getComp(); // get number of heap comparisons
// check optimality conditions
assert check(G);
}
// run Prim's algorithm
private boolean prim(final EdgeWeightedGraph G, int s) {
scan(G, s);
while (!pq.isEmpty() && mst.size() < G.V() - 1) { // stop if already found V - 1 edges
Edge e = pq.delMin(); // smallest edge on pq
int v = e.either(), w = e.other(v); // two endpoints
assert marked[v] || marked[w];
if (marked[v] && marked[w]) continue; // lazy, both v and w already scanned
mst.enqueue(e); // add e to MST
weight += e.weight();
if (!marked[v]) {
scan(G, v); // v becomes part of tree
}
if (!marked[w]) {
scan(G, w); // w becomes part of tree
}
}
if (mst.size() == G.V() - 1) return false;
return true;
}
// add all edges e incident to v onto pq if the other endpoint has not yet been scanned
private void scan(EdgeWeightedGraph G, int v) {
assert !marked[v];
marked[v] = true;
for (Edge e : G.adj(v)) {
if (!marked[e.other(v)]) {
pq.insert(e);
}
numScan++; // add number of scan comparisons
}
}
/**
* Returns the edges in a minimum spanning tree (or forest).
* @return the edges in a minimum spanning tree (or forest) as
* an iterable of edges
*/
public Iterable<Edge> edges() {
return mst;
}
/**
* Returns the sum of the edge weights in a minimum spanning tree (or forest).
* @return the sum of the edge weights in a minimum spanning tree (or forest)
*/
public double weight() {
return weight;
}
public int getHeapComp() {
return numHeapComp;
}
public int getScan() {
return numScan;
}
// check optimality conditions (takes time proportional to E V lg* V)
private boolean check(EdgeWeightedGraph G) {
// check weight
double totalWeight = 0.0;
for (Edge e : edges()) {
totalWeight += e.weight();
}
if (Math.abs(totalWeight - weight()) > FLOATING_POINT_EPSILON) {
System.err.printf("Weight of edges does not equal weight(): %f vs. %f\n", totalWeight, weight());
return false;
}
// check that it is acyclic
UF uf = new UF(G.V());
for (Edge e : edges()) {
int v = e.either(), w = e.other(v);
if (uf.connected(v, w)) {
System.err.println("Not a forest");
return false;
}
uf.union(v, w);
}
// check that it is a spanning forest
for (Edge e : G.edges()) {
int v = e.either(), w = e.other(v);
if (!uf.connected(v, w)) {
System.err.println("Not a spanning forest");
return false;
}
}
// check that it is a minimal spanning forest (cut optimality conditions)
for (Edge e : edges()) {
// all edges in MST except e
uf = new UF(G.V());
for (Edge f : mst) {
int x = f.either(), y = f.other(x);
if (f != e) uf.union(x, y);
}
// check that e is min weight edge in crossing cut
for (Edge f : G.edges()) {
int x = f.either(), y = f.other(x);
if (!uf.connected(x, y)) {
if (f.weight() < e.weight()) {
System.err.println("Edge " + f + " violates cut optimality conditions");
return false;
}
}
}
}
return true;
}
}
/******************************************************************************
* Copyright 2002-2015, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/ | [
"giant_mash@yahoo.co.id"
] | giant_mash@yahoo.co.id |
f1c229ece4c43840ad6f85e26526bebd8fbdd599 | bb926c4adfe3c6d868fee004670879aff15296a3 | /xantippe/xantippe-server/src/main/java/org/ozsoft/xantippe/server/Main.java | 0ed819e751737eace626c46ef16fd23d65d88cbe | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | ostigter/xantippe | 897ef35ec9991b07a1d73378dec24a7c184f7adf | 4f203caf2c30048d10651a4bb2d18a40bb9b57b6 | refs/heads/master | 2020-12-24T08:55:37.899693 | 2016-08-12T13:57:41 | 2016-08-12T13:57:41 | 41,742,875 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,778 | java | package org.ozsoft.xantippe.server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHandler;
import org.mortbay.jetty.servlet.ServletHolder;
import org.ozsoft.xantippe.Database;
import org.ozsoft.xantippe.DatabaseImpl;
import org.ozsoft.xantippe.XmldbException;
import org.ozsoft.xantippe.rest.RestServlet;
/**
* Standalone server.
*
* Uses an embedded Jetty.
*
* Connection URL: "http://localhost:8088/xantippe/".
*
* @author Oscar Stigter
*/
public class Main {
/** Port to listen to. */
private static final int PORT = 8088;
/** Servlet context. */
private static final String CONTEXT = "/xantippe";
/** Database data directory. */
private static final String DATA_DIR = "target/test-data";
/** Log. */
private static final Log LOG = LogFactory.getLog(Main.class);
private static RestServlet servlet;
/**
* The application's entry point.
*
* @param args
* Command line arguments.
*/
public static void main(String[] args) {
try {
// Start REST servlet with a running database.
Database database = new DatabaseImpl();
database.setDatabaseLocation(DATA_DIR);
servlet = new RestServlet(CONTEXT + "/rest", database);
servlet.start();
registerShutdownHook();
// Start Jetty server.
Server server = new Server(PORT);
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(new ServletHolder(servlet), CONTEXT + "/rest/*");
server.setHandler(handler);
server.start();
LOG.info(String.format("Server started, listening on port %d", PORT));
} catch (XmldbException e) {
LOG.error("Could not start REST servlet", e);
} catch (Exception e) {
LOG.error("Could not start Jetty server", e);
}
}
private static void shutdown() {
LOG.debug("Shutting down");
try {
LOG.warn("JVM shutdown detected; shutting down server");
if (servlet != null) {
servlet.shutdown();
}
} catch (XmldbException e) {
LOG.error("Could not properly shutdown servlet", e);
}
LOG.info("Server shut down");
}
private static void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
LOG.warn("JVM shutdown detected; shutting down server");
shutdown();
}
});
}
}
| [
"oscar.stigter@26dd4fee-6c50-0410-8f41-f3387f4e550c"
] | oscar.stigter@26dd4fee-6c50-0410-8f41-f3387f4e550c |
17d1ec06084c04553b694b619514dd40c98cd157 | d2df2e68ee1d0bb84243add5dcfd8920fb790333 | /modules/statistics-service-api/src/main/java/org/opencastproject/statistics/api/StatisticsUtil.java | 7392622f24b50ee57dc022103d70726a1756b780 | [
"LicenseRef-scancode-free-unknown",
"ECL-2.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-unknown"
] | permissive | rfharokh/Opencast | ec5603939759c9cc05acb4bd82b378761b9652b8 | 971702a4bbfafda9dfa1aeb0d3723b878bb693b7 | refs/heads/develop | 2021-06-18T14:43:21.193592 | 2021-01-26T08:17:30 | 2021-01-26T08:17:30 | 166,364,821 | 1 | 1 | ECL-2.0 | 2019-03-01T08:26:15 | 2019-01-18T07:40:53 | Java | UTF-8 | Java | false | false | 3,662 | java | /**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community 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://opensource.org/licenses/ecl2.txt
*
* 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.opencastproject.statistics.api;
import com.google.common.collect.Ordering;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
public final class StatisticsUtil {
private StatisticsUtil() {
}
public static List<Instant> getBuckets(final Instant from, final Instant to, final DataResolution resolution, final ZoneId zoneId) {
final List<Instant> result = new ArrayList<>();
LocalDateTime localStart = LocalDateTime.ofInstant(from, zoneId);
final LocalDateTime localEnd = LocalDateTime.ofInstant(to, zoneId);
while (!localStart.isAfter(localEnd)) {
switch (resolution) {
case MONTHLY:
final Instant currentMonthStart = YearMonth.of(localStart.getYear(), localStart.getMonth())
.atDay(1).atStartOfDay().toInstant(ZoneOffset.UTC);
result.add(Ordering.natural().max(from, currentMonthStart));
localStart = localStart.plusMonths(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
break;
case YEARLY:
final Instant currentYearStart = YearMonth.of(localStart.getYear(), 1)
.atDay(1).atStartOfDay().toInstant(ZoneOffset.UTC);
result.add(Ordering.natural().max(from, currentYearStart));
localStart = localStart.plusYears(1).withMonth(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
break;
case DAILY:
final Instant currentDayStart = localStart.withHour(0).withMinute(0).withSecond(0).withNano(0)
.toInstant(ZoneOffset.UTC);
result.add(Ordering.natural().max(from, currentDayStart));
localStart = localStart.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
break;
case WEEKLY:
final int daysOff = 1 - localStart.getDayOfWeek().getValue();
final Instant currentWeekStart = localStart.plusDays(daysOff).withHour(0).withMinute(0).withSecond(0)
.withNano(0).toInstant(ZoneOffset.UTC);
result.add(currentWeekStart); // No max here, because influx uses previous monday as bucket label
localStart = localStart.plusDays(7).plusDays(daysOff).withHour(0).withMinute(0).withSecond(0).withNano(0);
break;
case HOURLY:
final Instant currentHourStart = ZonedDateTime.of(localStart.withMinute(0).withSecond(0).withNano(0), zoneId)
.toInstant();
result.add(Ordering.natural().max(from, currentHourStart));
localStart = localStart.plusHours(1).withMinute(0).withSecond(0).withNano(0);
break;
default:
}
}
return result;
}
}
| [
"krinnewitz@plapadoo.de"
] | krinnewitz@plapadoo.de |
83379f083886463e4d21f81714e2a5ea971ddeae | 45345279ca3950748211f800333fe204f385da92 | /library/src/androidTest/java/com/bumptech/glide/GlideTest.java | 2ac40021ece8c81193de75c08e0eb4c35d2be23d | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause-Views",
"MIT"
] | permissive | cogitovsmachina/glide | 37dae7bfb2d8286534b2311f6af2fd4a6cf76539 | b23e1c479179b472ebb31ac20ec57a4284029d78 | refs/heads/master | 2021-05-27T03:01:31.835435 | 2014-09-02T13:39:08 | 2014-09-03T02:03:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 28,464 | java | package com.bumptech.glide;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.load.Encoder;
import com.bumptech.glide.load.ResourceDecoder;
import com.bumptech.glide.load.ResourceEncoder;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.engine.EngineResource;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.engine.cache.DiskCache;
import com.bumptech.glide.load.engine.cache.MemoryCache;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.stream.StreamModelLoader;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
import com.bumptech.glide.load.resource.bytes.BytesResource;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.load.resource.transcode.ResourceTranscoder;
import com.bumptech.glide.manager.Lifecycle;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.tests.GlideShadowLooper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static junit.framework.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.notNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for the {@link Glide} interface and singleton.
*/
@RunWith(RobolectricTestRunner.class)
@Config(shadows = { GlideTest.ShadowFileDescriptorContentResolver.class, GlideTest.ShadowMediaMetadataRetriever.class,
GlideShadowLooper.class })
public class GlideTest {
private Target target = null;
private ImageView imageView;
private RequestManager requestManager;
@Before
public void setUp() throws Exception {
Glide.tearDown();
// Ensure that target's size ready callback will be called synchronously.
target = mock(Target.class);
imageView = new ImageView(Robolectric.application);
imageView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));
doAnswer(new CallCallback()).when(target).getSize(any(SizeReadyCallback.class));
Handler bgHandler = mock(Handler.class);
when(bgHandler.post(any(Runnable.class))).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Runnable runnable = (Runnable) invocation.getArguments()[0];
runnable.run();
return true;
}
});
// Run all tasks on the main thread so they complete synchronously.
ExecutorService service = mock(ExecutorService.class);
when(service.submit(any(Runnable.class))).thenAnswer(new Answer<Future<?>>() {
@Override
public Future<?> answer(InvocationOnMock invocation) throws Throwable {
Runnable runnable = (Runnable) invocation.getArguments()[0];
runnable.run();
return mock(Future.class);
}
});
Glide.setup(new GlideBuilder(Robolectric.application)
.setMemoryCache(mock(MemoryCache.class))
.setDiskCache(mock(DiskCache.class))
.setResizeService(service)
.setDiskCacheService(service));
DataFetcher<InputStream> mockStreamFetcher = mock(DataFetcher.class);
when(mockStreamFetcher.getId()).thenReturn("fakeId");
when(mockStreamFetcher.loadData(any(Priority.class))).thenReturn(new ByteArrayInputStream(new byte[0]));
ModelLoader<GlideUrl, InputStream> mockUrlLoader = mock(ModelLoader.class);
when(mockUrlLoader.getResourceFetcher(any(GlideUrl.class), anyInt(), anyInt())).thenReturn(mockStreamFetcher);
ModelLoaderFactory<GlideUrl, InputStream> mockUrlLoaderFactory = mock(ModelLoaderFactory.class);
when(mockUrlLoaderFactory.build(any(Context.class), any(GenericLoaderFactory.class)))
.thenReturn(mockUrlLoader);
Glide.get(getContext()).register(GlideUrl.class, InputStream.class, mockUrlLoaderFactory);
Lifecycle lifecycle = mock(Lifecycle.class);
requestManager = new RequestManager(getContext(), lifecycle);
requestManager.resumeRequests();
}
@After
public void tearDown() {
Glide.tearDown();
}
@Test
public void testCanSetMemoryCategory() {
MemoryCache memoryCache = mock(MemoryCache.class);
BitmapPool bitmapPool = mock(BitmapPool.class);
MemoryCategory memoryCategory = MemoryCategory.NORMAL;
Glide glide = new GlideBuilder(getContext())
.setMemoryCache(memoryCache)
.setBitmapPool(bitmapPool)
.createGlide();
glide.setMemoryCategory(memoryCategory);
verify(memoryCache).setSizeMultiplier(eq(memoryCategory.getMultiplier()));
verify(bitmapPool).setSizeMultiplier(eq(memoryCategory.getMultiplier()));
}
@Test
public void testClearMemory() {
BitmapPool bitmapPool = mock(BitmapPool.class);
MemoryCache memoryCache = mock(MemoryCache.class);
Glide glide = new GlideBuilder(getContext())
.setBitmapPool(bitmapPool)
.setMemoryCache(memoryCache)
.createGlide();
glide.clearMemory();
verify(bitmapPool).clearMemory();
verify(memoryCache).clearMemory();
}
@Test
public void testTrimMemory() {
BitmapPool bitmapPool = mock(BitmapPool.class);
MemoryCache memoryCache = mock(MemoryCache.class);
Glide glide = new GlideBuilder(getContext())
.setBitmapPool(bitmapPool)
.setMemoryCache(memoryCache)
.createGlide();
final int level = 123;
glide.trimMemory(level);
verify(bitmapPool).trimMemory(eq(level));
verify(memoryCache).trimMemory(eq(level));
}
@SuppressWarnings("unchecked")
@Test
public void testGenericLoader() throws Exception {
File expected = new File("test");
Target<File> target = mock(Target.class);
doAnswer(new CallCallback()).when(target).getSize(any(SizeReadyCallback.class));
GlideUrl glideUrl = mock(GlideUrl.class);
DataFetcher<File> dataFetcher = mock(DataFetcher.class);
when(dataFetcher.loadData(any(Priority.class))).thenReturn(expected);
when(dataFetcher.getId()).thenReturn("id");
ModelLoader<GlideUrl, File> modelLoader = mock(ModelLoader.class);
when(modelLoader.getResourceFetcher(eq(glideUrl), anyInt(), anyInt()))
.thenReturn(dataFetcher);
Resource<File> expectedResource = mock(Resource.class);
when(expectedResource.get()).thenReturn(expected);
ResourceDecoder<File, File> sourceDecoder = mock(ResourceDecoder.class);
when(sourceDecoder.decode(eq(expected), anyInt(), anyInt())).thenReturn(expectedResource);
when(sourceDecoder.getId()).thenReturn("sourceDecoderId");
ResourceDecoder<File, File> cacheDecoder = mock(ResourceDecoder.class);
when(cacheDecoder.getId()).thenReturn("cacheDecoderId");
ResourceEncoder<File> encoder = mock(ResourceEncoder.class);
when(encoder.getId()).thenReturn("encoderId");
Encoder<File> sourceEncoder = mock(Encoder.class);
when(sourceEncoder.getId()).thenReturn("sourceEncoderId");
requestManager
.using(modelLoader, File.class)
.load(glideUrl)
.as(File.class)
.decoder(sourceDecoder)
.cacheDecoder(cacheDecoder)
.encoder(encoder)
.sourceEncoder(sourceEncoder)
.into(target);
verify(target).onResourceReady(eq(expected), any(GlideAnimation.class));
}
@Test
public void testFileDefaultLoaderWithInputStream() throws Exception {
registerFailFactory(File.class, ParcelFileDescriptor.class);
runTestFileDefaultLoader();
}
@Test
public void testFileDefaultLoaderWithFileDescriptor() throws Exception {
registerFailFactory(File.class, InputStream.class);
runTestFileDefaultLoader();
}
@Test
public void testFileDefaultLoader() {
runTestFileDefaultLoader();
}
private void runTestFileDefaultLoader() {
File file = new File("fake");
mockUri(Uri.fromFile(file));
requestManager.load(file).into(target);
requestManager.load(file).into(imageView);
verify(target).onResourceReady(any(EngineResource.class), any(GlideAnimation.class));
verify(target).setRequest((Request) notNull());
assertNotNull(imageView.getDrawable());
}
@Test
public void testUrlDefaultLoader() throws MalformedURLException {
URL url = new URL("http://www.google.com");
requestManager.load(url).into(target);
requestManager.load(url).into(imageView);
verify(target).onResourceReady(any(Resource.class), any(GlideAnimation.class));
verify(target).setRequest((Request) notNull());
assertNotNull(imageView.getDrawable());
}
@Test
public void testAsBitmapOption() {
Uri uri = Uri.parse("content://something/else");
mockUri(uri);
requestManager.load(uri).asBitmap().into(target);
verify(target).onResourceReady(any(Bitmap.class), any(GlideAnimation.class));
}
@Test
public void testTranscodeOption() {
Uri uri = Uri.parse("content://something/else");
mockUri(uri);
final byte[] bytes = new byte[0];
ResourceTranscoder<Bitmap, byte[]> transcoder = mock(ResourceTranscoder.class);
when(transcoder.getId()).thenReturn("bytes");
when(transcoder.transcode(any(Resource.class))).thenReturn(new BytesResource(bytes));
requestManager
.load(uri)
.asBitmap()
.transcode(transcoder, byte[].class)
.into(target);
verify(target).onResourceReady(eq(bytes), any(GlideAnimation.class));
}
@Test
public void testToBytesOption() {
Uri uri = Uri.parse("content://something/else");
mockUri(uri);
requestManager.load(uri).asBitmap().toBytes().into(target);
verify(target).onResourceReady(any(byte[].class), any(GlideAnimation.class));
}
@Test
public void testUriDefaultLoaderWithInputStream() throws Exception {
registerFailFactory(Uri.class, ParcelFileDescriptor.class);
runTestUriDefaultLoader();
}
@Test
public void testUriDefaultLoaderWithFileDescriptor() throws Exception {
registerFailFactory(Uri.class, InputStream.class);
runTestUriDefaultLoader();
}
@Test
public void testUriDefaultLoader() {
runTestUriDefaultLoader();
}
private void runTestUriDefaultLoader() {
Uri uri = Uri.parse("content://test/something");
mockUri(uri);
requestManager.load(uri).into(target);
requestManager.load(uri).into(imageView);
verify(target).onResourceReady(anyObject(), any(GlideAnimation.class));
verify(target).setRequest((Request) notNull());
assertNotNull(imageView.getDrawable());
}
@Test
public void testStringDefaultLoaderWithUrl() {
runTestStringDefaultLoader("http://www.google.com");
}
@Test
public void testFileStringDefaultLoaderWithInputStream() throws Exception {
registerFailFactory(String.class, ParcelFileDescriptor.class);
runTestFileStringDefaultLoader();
}
@Test
public void testFileStringDefaultLoaderWithFileDescriptor() throws Exception {
registerFailFactory(String.class, ParcelFileDescriptor.class);
runTestFileStringDefaultLoader();
}
@Test
public void testFileStringDefaultLoader() {
runTestFileStringDefaultLoader();
}
private void runTestFileStringDefaultLoader() {
String path = "/some/random/path";
mockUri(Uri.fromFile(new File(path)));
runTestStringDefaultLoader(path);
}
@Test
public void testUriStringDefaultLoaderWithInputStream() throws Exception {
registerFailFactory(String.class, ParcelFileDescriptor.class);
runTestUriStringDefaultLoader();
}
@Test
public void testUriStringDefaultLoaderWithFileDescriptor() throws Exception {
registerFailFactory(String.class, InputStream.class);
runTestUriStringDefaultLoader();
}
@Test
public void testUriStringDefaultLoader() {
runTestUriStringDefaultLoader();
}
private void runTestUriStringDefaultLoader() {
String stringUri = "content://some/random/uri";
mockUri(Uri.parse(stringUri));
runTestStringDefaultLoader(stringUri);
}
private void runTestStringDefaultLoader(String string) {
requestManager
.load(string)
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String model, Target target, boolean isFirstResource) {
if (!(e instanceof IOException)) {
throw new RuntimeException(e);
}
return false;
}
@Override
public boolean onResourceReady(GlideDrawable resource, String model, Target target,
boolean isFromMemoryCache,
boolean isFirstResource) {
return false;
}
})
.into(target);
requestManager.load(string).into(imageView);
verify(target).onResourceReady(any(Resource.class), any(GlideAnimation.class));
verify(target).setRequest((Request) notNull());
assertNotNull(imageView.getDrawable());
}
@Test
public void testIntegerDefaultLoaderWithInputStream() throws Exception {
registerFailFactory(Integer.class, ParcelFileDescriptor.class);
runTestIntegerDefaultLoader();
}
@Test
public void testIntegerDefaultLoaderWithFileDescriptor() throws Exception {
registerFailFactory(Integer.class, InputStream.class);
runTestIntegerDefaultLoader();
}
@Test
public void testIntegerDefaultLoader() {
runTestIntegerDefaultLoader();
}
private void runTestIntegerDefaultLoader() {
int integer = 1234;
mockUri("android.resource://" + getContext().getPackageName() + "/" + integer);
requestManager.load(integer).into(target);
requestManager.load(integer).into(imageView);
verify(target).onResourceReady(any(Resource.class), any(GlideAnimation.class));
verify(target).setRequest((Request) notNull());
assertNotNull(imageView.getDrawable());
}
@Test
public void testByteArrayDefaultLoader() {
byte[] bytes = new byte[10];
requestManager.load(bytes).into(target);
requestManager.load(bytes).into(imageView);
verify(target).onResourceReady(any(Resource.class), any(GlideAnimation.class));
verify(target).setRequest((Request) notNull());
assertNotNull(imageView.getDrawable());
}
@Test
public void testByteArrayWithIdDefaultLoader() {
byte[] bytes = new byte[10];
String id = "test";
requestManager.load(bytes, id).into(target);
requestManager.load(bytes, id).into(imageView);
verify(target).onResourceReady(any(Resource.class), any(GlideAnimation.class));
verify(target).setRequest((Request) notNull());
assertNotNull(imageView.getDrawable());
}
@Test(expected = Exception.class)
public void testUnregisteredModelThrowsException() {
Float unregistered = 0.5f;
requestManager.load(unregistered).into(target);
}
@Test
@SuppressWarnings("unchecked")
public void testUnregisteredModelWithGivenLoaderDoesNotThrow() {
Float unregistered = 0.5f;
StreamModelLoader<Float> mockLoader = mockStreamModelLoader(Float.class);
requestManager
.using(mockLoader)
.load(unregistered)
.into(target);
}
@Test
@SuppressWarnings("unchecked")
public void testNonDefaultModelWithRegisteredFactoryDoesNotThrow() {
registerMockStreamModelLoader(Float.class);
requestManager.load(0.5f).into(target);
}
@Test
public void testReceivesGif() throws IOException {
String fakeUri = "content://fake";
InputStream testGifData = openResource("test.gif");
mockUri(Uri.parse(fakeUri), testGifData);
requestManager
.load(fakeUri)
.asGif()
.into(target);
verify(target).onResourceReady(any(GifDrawable.class), any(GlideAnimation.class));
}
@Test
public void testReceivesGifBytes() throws IOException {
String fakeUri = "content://fake";
InputStream testGifData = openResource("test.gif");
mockUri(Uri.parse(fakeUri), testGifData);
requestManager
.load(fakeUri)
.asGif()
.toBytes()
.into(target);
verify(target).onResourceReady(any(byte[].class), any(GlideAnimation.class));
}
@Test
public void testReceivesBitmapBytes() {
String fakeUri = "content://fake";
mockUri(fakeUri);
requestManager
.load(fakeUri)
.asBitmap()
.toBytes()
.into(target);
verify(target).onResourceReady(any(byte[].class), any(GlideAnimation.class));
}
@Test
public void testReceivesTranscodedData() {
String fakeUri = "content://fake";
mockUri(fakeUri);
final Bitmap expected = Bitmap.createBitmap(1234, 6432, Bitmap.Config.ALPHA_8);
requestManager
.load(fakeUri)
.asBitmap()
.transcode(new ResourceTranscoder<Bitmap, Bitmap>() {
@Override
public Resource<Bitmap> transcode(Resource<Bitmap> toTranscode) {
return new BitmapResource(expected, mock(BitmapPool.class));
}
@Override
public String getId() {
return "id";
}
}, Bitmap.class)
.into(target);
verify(target).onResourceReady(eq(expected), any(GlideAnimation.class));
}
@Test
public void testNullModelInGenericImageLoadDoesNotThrow() {
requestManager.load((Double) null).into(target);
}
@Test
public void testNullModelInGenericVideoLoadDoesNotThrow() {
requestManager.load((Float) null).into(target);
}
@Test
public void testNullModelInGenericLoadDoesNotThrow() {
requestManager.load((Double) null).into(target);
}
@Test
public void testNullModelDoesNotThrow() {
String nullString = null;
Drawable drawable = new ColorDrawable(Color.RED);
requestManager
.load(nullString)
.placeholder(drawable)
.into(target);
verify(target).onLoadFailed(any(Exception.class), eq(drawable));
}
@Test
public void testNullModelPrefersErrorDrawable() {
String nullString = null;
Drawable placeholder = new ColorDrawable(Color.GREEN);
Drawable error = new ColorDrawable(Color.RED);
requestManager
.load(nullString)
.placeholder(placeholder)
.error(error)
.into(target);
verify(target).onLoadFailed(any(Exception.class), eq(error));
}
@Test
public void testNullModelWithModelLoaderDoesNotThrow() {
String nullString = null;
Drawable drawable = new ColorDrawable(Color.RED);
StreamModelLoader<String> modelLoader = mock(StreamModelLoader.class);
requestManager
.using(modelLoader)
.load(nullString)
.placeholder(drawable)
.into(target);
verify(target).onLoadFailed(any(Exception.class), eq(drawable));
}
@Test
public void testByteData() {
byte[] data = new byte[] { 1, 2, 3, 4, 5, 6 };
requestManager.load(data).into(target);
}
@SuppressWarnings("unchecked")
private <T, Z> void registerFailFactory(Class<T> failModel, Class<Z> failResource) throws Exception {
DataFetcher<Z> failFetcher = mock(DataFetcher.class);
when(failFetcher.loadData(any(Priority.class))).thenThrow(new IOException("test"));
when(failFetcher.getId()).thenReturn("fakeId");
ModelLoader<T, Z> failLoader = mock(ModelLoader.class);
when(failLoader.getResourceFetcher(any(failModel), anyInt(), anyInt())).thenReturn(failFetcher);
ModelLoaderFactory<T, Z> failFactory = mock(ModelLoaderFactory.class);
when(failFactory.build(any(Context.class), any(GenericLoaderFactory.class))).thenReturn(failLoader);
Glide.get(getContext()).register(failModel, failResource, failFactory);
}
private void mockUri(String uriString) {
mockUri(Uri.parse(uriString), null);
}
private void mockUri(Uri uri) {
mockUri(uri, null);
}
private void mockUri(Uri uri, InputStream is) {
if (is == null) {
is = new ByteArrayInputStream(new byte[0]);
}
ContentResolver contentResolver = Robolectric.application.getContentResolver();
ShadowFileDescriptorContentResolver shadowContentResolver = Robolectric.shadowOf_(contentResolver);
shadowContentResolver.registerInputStream(uri, is);
AssetFileDescriptor assetFileDescriptor = mock(AssetFileDescriptor.class);
ParcelFileDescriptor parcelFileDescriptor = mock(ParcelFileDescriptor.class);
when(assetFileDescriptor.getParcelFileDescriptor()).thenReturn(parcelFileDescriptor);
shadowContentResolver.registerAssetFileDescriptor(uri, assetFileDescriptor);
}
private Context getContext() {
return Robolectric.application;
}
@SuppressWarnings("unchecked")
private <T> void registerMockStreamModelLoader(final Class<T> modelClass) {
StreamModelLoader<T> modelLoader = mockStreamModelLoader(modelClass);
ModelLoaderFactory<T, InputStream> modelLoaderFactory = mock(ModelLoaderFactory.class);
when(modelLoaderFactory.build(any(Context.class), any(GenericLoaderFactory.class)))
.thenReturn(modelLoader);
Glide.get(Robolectric.application).register(modelClass, InputStream.class, modelLoaderFactory);
}
@SuppressWarnings("unchecked")
private <T> StreamModelLoader<T> mockStreamModelLoader(final Class<T> modelClass) {
StreamModelLoader<T> modelLoader = mock(StreamModelLoader.class);
DataFetcher<InputStream> fetcher = mock(DataFetcher.class);
try {
when(fetcher.loadData(any(Priority.class))).thenReturn(new ByteArrayInputStream(new byte[0]));
} catch (Exception e) {
// Do nothing.
}
when(fetcher.getId()).thenReturn(UUID.randomUUID().toString());
when(modelLoader.getResourceFetcher(any(modelClass), anyInt(), anyInt()))
.thenReturn(fetcher);
return modelLoader;
}
private InputStream openResource(String imageName) throws IOException {
return getClass().getResourceAsStream("/" + imageName);
}
private static class CallCallback implements Answer<Void> {
private int width;
private int height;
public CallCallback() {
this(100, 100);
}
public CallCallback(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
SizeReadyCallback cb = (SizeReadyCallback) invocation.getArguments()[0];
cb.onSizeReady(width, height);
return null;
}
}
// TODO: Extending ShadowContentResolver results in exceptions because of some state issues where we seem to get
// one content resolver shadow in one part of the test and a different one in a different part of the test. Each
// one ends up with different registered uris, which causes tests to fail. We shouldn't need to do this, but
// using static maps seems to fix the issue.
@Implements(value = ContentResolver.class, resetStaticState = true)
public static class ShadowFileDescriptorContentResolver {
private static final Map<Uri, AssetFileDescriptor> URI_TO_FILE_DESCRIPTOR =
new HashMap<Uri, AssetFileDescriptor>();
private static final Map<Uri, InputStream> URI_TO_INPUT_STREAMS = new HashMap<Uri, InputStream>();
public void registerInputStream(Uri uri, InputStream inputStream) {
URI_TO_INPUT_STREAMS.put(uri, inputStream);
}
public void registerAssetFileDescriptor(Uri uri, AssetFileDescriptor assetFileDescriptor) {
URI_TO_FILE_DESCRIPTOR.put(uri, assetFileDescriptor);
}
@Implementation
public InputStream openInputStream(Uri uri) {
if (!URI_TO_INPUT_STREAMS.containsKey(uri)) {
throw new IllegalArgumentException("You must first register an InputStream for uri: " + uri);
}
return URI_TO_INPUT_STREAMS.get(uri);
}
@Implementation
public AssetFileDescriptor openAssetFileDescriptor(Uri uri, String type) {
if (!URI_TO_FILE_DESCRIPTOR.containsKey(uri)) {
throw new IllegalArgumentException("You must first register an AssetFileDescriptor for uri: " + uri);
}
return URI_TO_FILE_DESCRIPTOR.get(uri);
}
public static void reset() {
URI_TO_INPUT_STREAMS.clear();
URI_TO_FILE_DESCRIPTOR.clear();
}
}
@Implements(MediaMetadataRetriever.class)
public static class ShadowMediaMetadataRetriever {
@Implementation
@SuppressWarnings("unused")
public Bitmap getFrameAtTime() {
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Robolectric.shadowOf(bitmap).appendDescription(" from MediaMetadataRetriever");
return bitmap;
}
}
}
| [
"judds@google.com"
] | judds@google.com |
7dfeebfde68ae1db8052dbc27cddecf31fcdb99a | ad92584540205caf9c9baeae920756d3b156cd23 | /FriendServer/src/com/nho/friend/data/FriendMongoBean.java | 8fefd05c18932eb5818e92b11240ab989016a0e8 | [] | no_license | nguyenvanthu/nho-messenger | c8efc96b42c0fcd77517767dbd299dd1c9f5fed9 | 891d73b936305da2263d6419ceaf75a53ee48e29 | refs/heads/master | 2021-06-26T06:27:33.433596 | 2017-09-13T17:40:12 | 2017-09-13T17:40:12 | 103,430,772 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,713 | java | package com.nho.friend.data;
import org.bson.Document;
import com.nhb.common.db.beans.AbstractMongoBean;
import com.nho.friend.statics.FriendDbFields;
import com.nho.statics.F;
public class FriendMongoBean extends AbstractMongoBean {
private static final long serialVersionUID = 1L;
private String user;
private String buddy;
private String createdTime = String.valueOf(System.currentTimeMillis());
private int status;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getBuddy() {
return buddy;
}
public void setBuddy(String buddy) {
this.buddy = buddy;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
/**
* status == 0 : accepted status == 1 : pending status == 2 : ignored status
* == 3 : canceled status == 4 : blocked
*
* @return status
*/
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Document toDocument() {
Document document = new Document();
document.put(F.STATUS, this.status);
document.put(F.CREATED_TIME, this.createdTime);
document.put(F.USER, this.user);
document.put(F.BUDDY, this.buddy);
return document;
}
public static FriendMongoBean fromDocument(Document document) {
FriendMongoBean bean = new FriendMongoBean();
bean.setObjectId(document.getObjectId(FriendDbFields._ID));
bean.setCreatedTime(document.getString(F.CREATED_TIME));
bean.setStatus(document.getInteger(F.STATUS));
bean.setUser(document.getString(F.USER));
bean.setBuddy(document.getString(F.BUDDY));
return bean;
}
}
| [
"thunv@puppetteam.com"
] | thunv@puppetteam.com |
0623d5a4d15cb63ce26228ecb8de8250e52968c4 | ac3c3ff15bca7638c2f11b9d384dfb5755ab6d99 | /algo_hj/src/정올/Main_정올_1515_구슬찾기.java | 53190722e8bab98707354164788cfc6fe999c180 | [] | no_license | schw240/Algorithmn_Java | 75c22f728fb292a1362e4429f9b641fc1dd10f85 | 8c0f2b182b173aca23c02e96cfcf6c8ac7b518c0 | refs/heads/master | 2023-09-02T18:20:27.108646 | 2021-10-17T14:52:45 | 2021-10-17T14:52:45 | 392,349,271 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,688 | java | package 정올;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main_정올_1515_구슬찾기 {
public static void main(String[] args) throws Exception {
// 무게가 모두 다른 N개의 구슬 1 ~ N번까지
// 이 구슬 중 무게가 전체의 중간인 (무게 순서로 (N+1) / 2 번째
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken()); // 구슬 개수
int M = Integer.parseInt(st.nextToken()); // M개의 쌍
int[][] arr = new int[N + 1][N + 1];
// 반의 값을 구함
int half = (N + 1) / 2;
// 양팔저울이 주어지고 한쌍의 구슬을 골라서 양팔 저울의 양쪽에 하나씩 올려보면 어느쪽이 무거운가를 알 수 있다.
// 이렇게 M 개의 쌍을 골라서 각각 양팔저울에 올려서 어느 것이 무거운 가를 모두 알아냈다.
// 이 결과를 이용하여 무게가 중간이 될 가능성이 없는 구슬 제외시키기
// M개의 쌍에 대한 결과를 보고 무게가 중간인 구슬이 될 수 없는 구슬의 개수를 구하기
int ans = 0;
for(int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
// 앞번호의 구슬이 뒤 번호의 구슬보다 무겁다.
// a는 b보다 큼
arr[a][b] = 1;
arr[b][a] = -1;
}
for (int i = 1; i <= N; i++) {// 거쳐가는 구슬
for (int j = 1; j <= N; j++) {// 출발 구슬
for (int k = 1; k <= N; k++) {// 도착 구슬
// 구슬의 연결관계가 있을때
// 출발 구슬-> 거쳐가는 구슬 , 거쳐가는 구슬-> 출발 구슬
// 이런식으로 위치가 정렬되어 출발구슬이 도착구슬과 직접적인 연결이 아니어도
// 위치가 지정되는 조건이 하나 더 성립됨
if (arr[k][i] != 0 && arr[j][i] == arr[i][k])
arr[j][k] = arr[j][i];
}
}
}
int[] big = new int[N + 1];
int[] small = new int[N + 1];
// 뒤에 오는 조건, 앞에 오는 조건의 개수를 각각 세어 저장
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (arr[i][j] == 1)
big[i]++;
if (arr[i][j] == -1)
small[i]++;
}
}
// 조건이 총구슬의 반이 넘으면 답의 개수를 늘려준다
for (int i = 1; i <= N; i++) {
if (big[i] >= half)
ans++;
if (small[i] >= half)
ans++;
}
System.out.println(ans);
} // end of main
} // end of class
| [
"schw240@gmail.com"
] | schw240@gmail.com |
31c72475a72dcf4212e308c952f5dd9032e1ea63 | c0e689e7cc98f970dd85c6d06c0c0a643bd76764 | /src/main/java/com/weiss/j2se/date/TestDate.java | 3fe7488e7f83b991e0db113587bb33602b843438 | [] | no_license | weissxu/java_test | eeed457bf559bb38789c17a2ff23a94d67ff5c8d | 38aeb92d28b0d8f0c1be24532834d2d7a1f1195e | refs/heads/master | 2023-01-09T14:16:40.553292 | 2020-02-26T05:12:04 | 2020-02-26T05:12:04 | 4,494,404 | 0 | 0 | null | 2023-01-02T21:51:40 | 2012-05-30T12:20:46 | Java | UTF-8 | Java | false | false | 1,661 | java | package com.weiss.j2se.date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
public class TestDate {
// 11173339 89eaf0865cl
// 11319136 3450b8a716l
// 11319136 361c9186bel
// 11319136 5133e4af83l
// 11319136 60a41b8b2al
public static long[] nos = { 1300499511404L, 1300499517551L, 1300499538900L };
@Test
public void testLong2Date() {
Date date = new Date(1337823260816L);
System.out.println(date);
}
@Test
public void testGetTimestamp() throws ParseException {
Date now = new Date();
System.out.println("now: " + now);
System.out.println(now.getTime());
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-05-24 08:00:17");
System.out.println("2012-05-24 08:00:17: " + date);
System.out.println(date.getTime());
System.out.println("currentTimeMillis: " + System.currentTimeMillis());
}
@Test
public void testNOs() {
for (long num : nos) {
System.out.println(new Date(num));
}
}
@Test
public void testNO() {
System.out.println(System.nanoTime());
System.out.println(System.currentTimeMillis());
}
public static void main(String[] args) throws ParseException {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
System.out.println(format.parse("2009-09-09 12:21:12"));
System.out.println(format.format(date));
System.out.println(new java.sql.Date(date.getTime()));
System.out.println(new Timestamp(date.getTime()));
}
}
| [
"xusiwei@mitao.cn"
] | xusiwei@mitao.cn |
7e6d7ea351d1ba03707aafe54ee6b79945878f2f | 32d158e2a2e649cf2200c21a1cdcad6bf9f44142 | /A5_Evaluation/src/com/ir/global/Properties.java | faddf066f96f6a8d2af6f34521f66fc820d953bd | [] | no_license | asadshahabuddin/CS6200 | 306e1f51dc12f8982b08283ae80ef7e0cd1ca9f9 | ab565eadf97fda12ad65d7c3e74f6c7603f87304 | refs/heads/master | 2021-01-10T13:58:07.987969 | 2015-08-14T05:20:51 | 2015-08-14T05:20:51 | 36,598,288 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 848 | java | package com.ir.global;
/**
* Author : Asad Shahabuddin
* Created: Jul 19, 2015
*/
public class Properties
{
/* Numerical constants. */
public static final int KEY_TRECEVAL = 0;
public static final int KEY_IREVAL = 1;
public static final int COUNT_DOC = 45608;
public static final double K1 = 1.2;
public static final double K2 = 1000; /* 0 - 1000 */
public static final double B = 0.75;
/* Directories and files. */
public static final String FILE_DOCLEN = "doclen.txt";
public static final String FILE_PRDATA = "pr-data.txt";
/* ElasticSearch properties. */
public static final String CLUSTER_NAME = "leoscluster";
public static final String INDEX_NAME = "ras_dataset";
public static final String INDEX_TYPE = "document";
}
/* End of Properties.java */ | [
"asad.shahabuddin@gmail.com"
] | asad.shahabuddin@gmail.com |
06b5c47c4e456c528c9313898ffd8de5092b33d4 | ef53180401ab45556823ebefef945009416d94c3 | /src/main/java/com/lacsystem/pedido/repositories/EstadoRepository.java | 70cd6cc6ea41891d78c95a15422a8e7b31c96a14 | [] | no_license | LuizC3s4r1o/pedido | c2011a6765078221f1d463c8593da00785ee42b3 | 7fc39d0fa4993b84ac77155450bce0da040c757d | refs/heads/master | 2020-04-01T07:53:29.043810 | 2018-12-16T20:26:57 | 2018-12-16T20:26:57 | 153,008,563 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 491 | java | package com.lacsystem.pedido.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.lacsystem.pedido.domain.Estado;
/**
* @author Luiz.Cesario
*
*/
@Repository
public interface EstadoRepository extends JpaRepository<Estado, Long>{
@Transactional(readOnly=true)
public List<Estado> findAllByOrderByNome();
}
| [
"luiz.cesario@yahoo.com.br"
] | luiz.cesario@yahoo.com.br |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.