blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
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
689M
⌀ | 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 131
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 32
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e2c38b41007085a61672ad5488847f040797096b | fd745eae45e812d65668b5a7f3d5179acce9e950 | /app/src/main/java/com/njx/mvvmhabit/data/source/http/service/DemoApiService.java | 1548bcae45fd21a3879a22b0d7db4fc3a49c816d | [
"Apache-2.0"
]
| permissive | marydeng/njx | d5da0402df560d06ebd16ef580288c587d533a40 | b171dd4135003de1fc83a4fff591b01b9ca7f200 | refs/heads/master | 2020-06-23T22:58:01.341045 | 2019-12-12T12:10:04 | 2019-12-12T12:10:04 | 198,777,544 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,565 | java | package com.njx.mvvmhabit.data.source.http.service;
import com.njx.mvvmhabit.entity.BackDepotResultEntity;
import com.njx.mvvmhabit.entity.BackRecordResultEntity;
import com.njx.mvvmhabit.entity.BusiLocationEntity;
import com.njx.mvvmhabit.entity.BusiOrderResultEntity;
import com.njx.mvvmhabit.entity.BusinessOutRecordEntity;
import com.njx.mvvmhabit.entity.BusinessStorageRecordEntity;
import com.njx.mvvmhabit.entity.DemoEntity;
import com.njx.mvvmhabit.entity.MenuEntity;
import com.njx.mvvmhabit.entity.OrderEntity;
import com.njx.mvvmhabit.entity.OrderListEntity;
import com.njx.mvvmhabit.entity.OutOrderEntity;
import com.njx.mvvmhabit.entity.OutPartRecordEntity;
import com.njx.mvvmhabit.entity.ReturnDataEntity;
import com.njx.mvvmhabit.entity.SMTRecordEntity;
import com.njx.mvvmhabit.entity.SteelEntity;
import com.njx.mvvmhabit.entity.TransferPartRecordEntity;
import com.njx.mvvmhabit.entity.UserEntity;
import java.util.List;
import io.reactivex.Observable;
import me.goldze.mvvmhabit.http.BaseResponse;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
/**
* Created by goldze on 2017/6/15.
*/
public interface DemoApiService {
@GET("action/apiv2/banner?catalog=1")
Observable<BaseResponse<DemoEntity>> demoGet();
@FormUrlEncoded
@POST("action/apiv2/banner")
Observable<BaseResponse<DemoEntity>> demoPost(@Field("catalog") String catalog);
//登录
@GET("api/login/loginByUserName")
Observable<BaseResponse<UserEntity>> login(@Query("userName") String username, @Query("password") String password);
//菜单
@GET("api/user/getMenuList")
Observable<BaseResponse<List<MenuEntity>>> getMenuList(@Query("userId") String userId);
//上机台
@POST("api/production/edit")
Observable<BaseResponse<DemoEntity>> uplineSteelPlate(@Query("partNum") String partNum, @Query("lineClass") String lineClass, @Query("steelPlateType") String steelPlateType, @Query("jobNum") String jobNum);
//下机台
@POST("api/production/leaveEditSave")
Observable<BaseResponse<DemoEntity>> downlineSteelPlate(@Query("lineClass") String lineClass, @Query("steelPlateType") String steelPlateType);
//根据工单号查询线体
@POST("api/production/selectWorkorderList")
Observable<BaseResponse<OrderEntity>> queryOrder(@Query("workorderNumber") String workorderNumber);
//获取在线钢板和刮刀
@POST("api/production/scSteelPlateUplineList")
Observable<BaseResponse<List<SteelEntity>>> getSteelList(@Query("lineClass") String lineClass);
//查询所有线体
@POST("api/production/selectScProductLineList")
Observable<BaseResponse<List<String>>> queryAllLine();
//fqc 上传生产条码
@POST("api/fqc/add")
Observable<BaseResponse<String>> commitProduceCode(@Query("checkResult") String testType, @Query("productBarcode") String produceCode, @Query("operator") String operator);
//SMT 清除工单
@POST("api/production/clearLoadMaterial")
Observable<BaseResponse<Object>> clearWorkItem(@Query("workorderNumber") String workItem, @Query("loadStatus") String loadStatus);
//SMT 检查状态
@POST("api/production/checkStatus")
Observable<BaseResponse<Object>> checkSMTStatus(@Query("materialRack") String materialGun, @Query("materialRoll") String materialRoll, @Query("materialStation") String materialStation);
//SMT 上传上料扫码记录
@POST("api/production/insertLoadmaterial")
Observable<BaseResponse<Object>> uploadScanRecord(@Query("loadType") String loadType, @Query("loadStatus") String loadStatus, @Query("workorderNumber") String workItem, @Query("materialRack") String materialGun, @Query("materialRoll") String materialRoll, @Query("materialStation") String materialStation, @Query("loadPeople") String loadPeople);
//SMT 上传接料扫码记录
@POST("api/production/ReLoadmaterial")
Observable<BaseResponse<Object>> uploadMaterChangeScanRecord(@Query("loadType") String loadType, @Query("loadStatus") String loadStatus, @Query("workorderNumber") String workItem, @Query("materialRack") String materialGun, @Query("materialRoll") String materialRoll, @Query("materialRollNew") String materialRollNew, @Query("materialStation") String materialStation, @Query("loadPeople") String loadPeople);
//SMT 上传料枪变更扫码记录
@POST("api/production/changeMaterialRack")
Observable<BaseResponse<Object>> uploadGunChangeScanRecord(@Query("loadType") String loadType, @Query("loadStatus") String loadStatus, @Query("workorderNumber") String workItem, @Query("materialRack") String materialGun, @Query("materialRackNew") String materialGunNew, @Query("materialRoll") String materialRoll, @Query("materialStation") String materialStation, @Query("loadPeople") String loadPeople);
//SMT查询扫码记录
@POST("api/production/selectLoadMaterial")
Observable<BaseResponse<List<SMTRecordEntity>>> queryScanRecord(@Query("loadType") String loadType, @Query("workorderNumber") String workItem);
//SMT 确认完毕
@POST("api/production/comfirmLoadmaterial")
Observable<BaseResponse<List<String>>> confirmEnd(@Query("loadStatus") String loadType, @Query("workorderNumber") String workItem);
//查询工单列表
@POST("api/production/selectWorkorderByPresetLine")
Observable<BaseResponse<OrderListEntity>> queryWorkItem(@Query("presetLine") String lineClass, @Query("pageNum") int pageNum, @Query("pageSize") int pageSize);
//质检 上传扫码记录
@POST("api/production/insertPqc")
Observable<BaseResponse<Object>> uploadQualityScanRecord(@Query("loadType") String loadType, @Query("workorderNumber") String workItem, @Query("materialRack") String materialGun, @Query("materialRoll") String materialRoll, @Query("materialStation") String materialStation, @Query("loadPeople") String loadPeople);
//质检 查询扫码记录
@POST("api/production/selectPqc")
Observable<BaseResponse<List<SMTRecordEntity>>> queryQualityScanRecord(@Query("loadType") String loadType, @Query("workorderNumber") String workItem);
//SMT input
@POST("api/production/addSmtInput")
Observable<BaseResponse<String>> addSMTInput(@Query("remark") String orderID, @Query("operator") String operator, @Query("productBarcode") String productBarcode, @Query("lastWorkOrder") String lastWorkOrder);
//************仓库开始***************
//出库订单查询
@POST("api/ckMaterialOutputTable/selectWorkorderNumberList")
Observable<BaseResponse<List<OutOrderEntity>>> queryOutOrder();
//查询出库记录列表
@POST("api/ckMaterialOutputTable/selectCkMaterialOutputTableList")
Observable<BaseResponse<List<OutPartRecordEntity>>> queryOutList(@Query("workorderNumber") String workorderNumber, @Query("warehouseName") String warehouseName);
//出库扫码
@POST("api/ckMaterialOutputTable/addCkScanningOutRecordTable")
Observable<BaseResponse<String>> outScan(@Query("workorderNumber") String workorderNumber, @Query("materialCoilNum") String materialCoilNum, @Query("confirmPerson") String confirmPerson, @Query("coilNum") String coilNum);
//调拨转仓单号模糊查询
@POST("api/ckTransferWareRecord/selectLikeTransferWareNum")
Observable<BaseResponse<List<String>>> queryTransferOrder(@Query("transferWareNum") String transferWareNum);
//根据转仓单号查询目标仓库
@POST("api/ckTransferWareRecord/selectTargetWarehouseNameByTransferWareNum")
Observable<BaseResponse<List<String>>> queryTransferDepat(@Query("transferWareNum") String transferWareNum);
//查询调拨记录
@POST("api/ckTransferWareRecord/transferWareRecordList")
Observable<BaseResponse<List<TransferPartRecordEntity>>> queryTransferList(@Query("transferWareNum") String transferWareNum,@Query("targetWarehouseName") String targetWarehouseName);
//根据仓库查询储位列表
@POST("api/ckTransferWareRecord/selectCkLocationListByCkWarehouse")
Observable<BaseResponse<List<String>>> queryTransferLocation(@Query("ckWarehouse") String ckWarehouse);
//调拨扫码
@POST("api/ckTransferWareRecord/scanSubinventoryTransfer")
Observable<BaseResponse<String>> transferScan(@Query("transferWareNum") String transferWareNum, @Query("targetWarehouseName") String targetWarehouseName, @Query("locationNo") String locationNo, @Query("materialCoilNum") String materialCoilNum);
//查询退货订单
@POST("api/ckReturnOrder/selectCgReturnNoteList")
Observable<BaseResponse<List<String>>> queryReturnOrderList();
//查询退货记录
@POST("api/ckReturnOrder/ckReturnOrderList")
Observable<BaseResponse<ReturnDataEntity>> queryReturnRecordList(@Query("correlationOrder") String correlationOrder);
//退货扫码
@POST("api/ckReturnOrder/addCkReturnOrder")
Observable<BaseResponse<String>> returnScan(@Query("correlationOrder") String correlationOrder, @Query("materialCoilNum") String materialCoilNum);
//查询退库订单
@POST("api/ckWithdrawalForm/selectCorrelationOrderList")
Observable<BaseResponse<List<String>>> queryBackOrderList();
//查询退库仓库
@POST("api/ckWithdrawalForm/ckWarehouseList")
Observable<BaseResponse<BackDepotResultEntity>> queryBackDepot(@Query("pageNum") int pageNum, @Query("pageSize") int pageSize);
//查询退库储位
@POST("api/ckWithdrawalForm/selectCkLocationListByCkWarehouse")
Observable<BaseResponse<List<String>>> queryBackLocation(@Query("ckWarehouse") String ckWarehouse);
//查询退库记录
@POST("api/ckWithdrawalForm/ckWithdrawalFormlist")
Observable<BaseResponse<BackRecordResultEntity>> queryBackRecordList(@Query("correlationOrder") String correlationOrder);
//退库扫码
@POST("api/ckWithdrawalForm/saveCkWithdrawalForm")
Observable<BaseResponse<String>> backScan(@Query("correlationOrder") String correlationOrder, @Query("materialCoilNum") String materialCoilNum,@Query("materialNo") String materialNo, @Query("warehouseName") String warehouseName, @Query("locationNo") String locationNo);
// ************仓库结束***************
// ************成品开始***************
//查询成品库位
@POST("api/ckMaterialOutputTable/selectProductWareHouseTable")
Observable<BaseResponse<List<BusiLocationEntity>>> queryBusinessLocation();
//成品入库扫码
@POST("api/ckMaterialOutputTable/addProductInputTable")
Observable<BaseResponse<String>> businessStorageScan(@Query("productLocation") String locationId, @Query("boxBarcode") String boxId);
//成品入库记录
@POST("api/ckMaterialOutputTable/selectProductInputTable")
Observable<BaseResponse<List<BusinessStorageRecordEntity>>> queryBusinessStorageRecord();
//成品出库单号查询
@POST("api/ckMaterialOutputTable/selectProductOut")
Observable<BaseResponse<BusiOrderResultEntity>> queryBusinessOutOrder(@Query("pageNum") int pageNum, @Query("pageSize") int pageSize);
//成品出库扫码
@POST("api/ckMaterialOutputTable/addProductOutDetailTable")
Observable<BaseResponse<String>> businessOutScan(@Query("outNumber") String orderId,@Query("boxBarcode") String boxId);
//成品出库库记录
@POST("api/ckMaterialOutputTable/selectProductOutDetailTable")
Observable<BaseResponse<List<BusinessOutRecordEntity>>> queryBusinessOutRecord(@Query("outNumber") String orderId);
// ************成品结束***************
}
| [
"[email protected]"
]
| |
49fefbaa3771c123f4acbfe57b177aa70863b907 | 3f547ec22d0c2904ab74e8b09ea357ba49c3d1fb | /base/src/main/java/com/example/base/net/RxCreator.java | bbf18c5277a74f3d03a254aaac46b7c9c422019d | []
| no_license | wsfAAA/PlayAndroidWork | b254af23cde3247fa8067f860e1792822ae3c9f0 | fde522bcfd8cc4c988adef2abbab1804ec82bc94 | refs/heads/master | 2022-12-26T18:14:21.502622 | 2020-09-29T08:40:08 | 2020-09-29T08:40:08 | 287,870,848 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,135 | java | package com.example.base.net;
import com.example.base.MyAppliction;
import com.example.base.net.api.ApiService;
import java.io.File;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public final class RxCreator {
/**
* 构建OkHttp
*/
private static final class OKHttpHolder {
private static final int CONNECT_TIME_OUT = 10;
private static final int READ_TIME_OUT = 5;
private static final OkHttpClient.Builder getOkhttpBuilder() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS);
builder.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
return builder;
}
}
public static OkHttpClient.Builder getOkhttpBuilder() {
return OKHttpHolder.getOkhttpBuilder();
}
private static final class OKHttpCacheHolder {
private static final Cache getCache() {
File mHttpCacheDirectory = new File(MyAppliction.getApplication().getCacheDir(), "tamic_cache");
try {
Cache cache = new Cache(mHttpCacheDirectory, 10 * 1024 * 1024);
return cache;
} catch (Exception e) {
throw new RuntimeException("Cache Exception!");
}
}
}
public static final Cache getCache() {
return OKHttpCacheHolder.getCache();
}
/**
* 构建全局Retrofit Builder
*/
private static final class RetrofitHolder {
public static final Retrofit.Builder RETROFIT_BUILDER = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create()) // 解析工厂
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()); //支持rxjava
}
public static Retrofit.Builder getRetrofitBuilde() {
return RetrofitHolder.RETROFIT_BUILDER;
}
}
| [
"[email protected]"
]
| |
bc2cd4adad14edbd0da3e22143ecc4da14282e79 | 4fd3a499ce87003aaf284636b99f8c94137993c1 | /mantis-tests/src/test/java/krasnikova/mantis/appmanager/SoapHelper.java | e0f576aee5212df881d2c92944e30368855d98ef | []
| no_license | xkrasnikova/java4qa | 5bbbdc73e5efca735d1fe884cc209ec255b0e052 | 0c07755028bf923a109e17fb0b1cbd24289bd2ac | refs/heads/master | 2020-04-20T15:29:13.469658 | 2019-04-08T09:31:34 | 2019-04-08T09:31:34 | 168,931,600 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,521 | java | package krasnikova.mantis.appmanager;
import biz.futureware.mantis.rpc.soap.client.*;
import krasnikova.mantis.model.Issue;
import krasnikova.mantis.model.Project;
import javax.xml.rpc.ServiceException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class SoapHelper {
private final ApplicationManager app;
public SoapHelper(ApplicationManager app) {
this.app = app;
}
public Set<Project> getProjects() throws MalformedURLException, ServiceException, RemoteException {
MantisConnectPortType mc = getMantisConnect();
ProjectData[] projects = mc.mc_projects_get_user_accessible(app.getProperty("web.adminLogin"), app.getProperty("web.adminPassword"));
return Arrays.asList(projects).stream().map((p) -> new Project()
.withId(p.getId().intValue()).withName(p.getName()))
.collect(Collectors.toSet());
}
public MantisConnectPortType getMantisConnect() throws ServiceException, MalformedURLException {
return new MantisConnectLocator()
.getMantisConnectPort(new URL(app.getProperty("web.baseUrl")+"/api/soap/mantisconnect.php"));
}
public Issue addIssue(Issue issue) throws MalformedURLException, ServiceException, RemoteException {
MantisConnectPortType mc = getMantisConnect();
String adminLogin = app.getProperty("web.adminLogin");
String adminPassword = app.getProperty("web.adminPassword");
String[] categories = mc.mc_project_get_categories(adminLogin, adminPassword, BigInteger.valueOf(issue.getProject().getId()));
IssueData issueData = new IssueData();
issueData.setSummary(issue.getSummary());
issueData.setDescription(issue.getDescription());
issueData.setProject(new ObjectRef(BigInteger.valueOf(issue.getProject().getId()),issue.getProject().getName()));
issueData.setCategory(categories[0]);
BigInteger issueId = mc.mc_issue_add(adminLogin, adminPassword, issueData);
IssueData createdIssueData = mc.mc_issue_get(adminLogin, adminPassword, issueId);
return new Issue().withId(createdIssueData.getId().intValue())
.withSummary(createdIssueData.getSummary()).withDescription(createdIssueData.getDescription())
.withProject(new Project().withId(createdIssueData.getProject().getId().intValue())
.withName(createdIssueData.getProject().getName()));
}
}
| [
"[email protected]"
]
| |
1bc39878ab7133294b28862221b79005f8128d58 | 1e30540a857c750480419aa94f7a41c8e2d62a4c | /app/src/main/java/com/lt/myapplication/MainActivity.java | e737cd2ab0d5ee0e85518346a74c90e802eaefae | []
| no_license | HILOLT/ndk-sample | 067d8bcb83234c197924737e81a6469d3eb10ec8 | 869f5ba9e5885668471d8e267deb83d5bb6f3f0c | refs/heads/master | 2022-11-27T10:51:16.676408 | 2020-08-07T14:42:33 | 2020-08-07T14:42:33 | 285,850,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 625 | java | package com.lt.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
/**
* @author liutao15
* @version 4.2.0
* @since 2020/8/7
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
NDKTool tool = new NDKTool();
TextView textView = findViewById(R.id.TextView);
textView.setText(tool.getStringFromNDK());
}
}
| [
"[email protected]"
]
| |
e0ecbc630b30a25859a27c2b14be43a579594403 | fda0c83e971d2a66c717e83b75a34da737209570 | /src/uibe/ldy/balance/EnergyFunction.java | 20afb478e6526fc1be09cfa0cd88f15681fdd4a6 | []
| no_license | dongyuanlu/CommentAnalysis | 3a642f3b3dc4219f1c695645ad9f0d348190e63b | 415ef466756dbed892636b3ec6f698f015d50093 | refs/heads/master | 2020-05-07T15:59:59.303329 | 2015-07-22T09:11:02 | 2015-07-22T09:11:02 | 36,923,552 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 153 | java | package uibe.ldy.balance;
public class EnergyFunction implements FitnessFunction
{
public int evaluate( Chromosome subject) {
return 0;
}
}
| [
"[email protected]"
]
| |
0651e56f9e5ae455620b1c892fc21e713e13aaaf | a11ba1b53c0e1e978b5f4f55a38b4ff5b13d5e36 | /engine/src/main/java/org/apache/hop/trans/steps/sort/SortRows.java | 0cf5afadcf36aaaaad2b6bc27722936bf74108a4 | [
"Apache-2.0"
]
| permissive | lipengyu/hop | 157747f4da6d909a935b4510e01644935333fef9 | 8afe35f0705f44d78b5c33c1ba3699f657f8b9dc | refs/heads/master | 2020-09-12T06:31:58.176011 | 2019-11-11T21:17:59 | 2019-11-11T21:17:59 | 222,341,727 | 1 | 0 | Apache-2.0 | 2019-11-18T01:50:19 | 2019-11-18T01:50:18 | null | UTF-8 | Java | false | false | 23,929 | java | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.apache.hop.trans.steps.sort;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.hop.core.Const;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.exception.HopFileException;
import org.apache.hop.core.exception.HopValueException;
import org.apache.hop.core.row.RowMetaInterface;
import org.apache.hop.core.row.ValueMetaInterface;
import org.apache.hop.core.vfs.HopVFS;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.trans.Trans;
import org.apache.hop.trans.TransMeta;
import org.apache.hop.trans.step.BaseStep;
import org.apache.hop.trans.step.StepDataInterface;
import org.apache.hop.trans.step.StepInterface;
import org.apache.hop.trans.step.StepMeta;
import org.apache.hop.trans.step.StepMetaInterface;
/**
* Sort the rows in the input-streams based on certain criteria
*
* @author Matt
* @since 29-apr-2003
*/
public class SortRows extends BaseStep implements StepInterface {
private static Class<?> PKG = SortRows.class; // for i18n
private SortRowsMeta meta;
private SortRowsData data;
public SortRows( StepMeta stepMeta, StepDataInterface stepDataInterface,
int copyNr, TransMeta transMeta, Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
meta = (SortRowsMeta) getStepMeta().getStepMetaInterface();
data = (SortRowsData) stepDataInterface;
}
void addBuffer( RowMetaInterface rowMeta, Object[] r ) throws HopException {
// we need convert some keys?
if ( data.convertKeysToNative != null ) {
for ( int i = 0; i < data.convertKeysToNative.length; i++ ) {
int index = data.convertKeysToNative[i];
r[index] = rowMeta.getValueMeta( index ).convertBinaryStringToNativeType( (byte[]) r[index] );
}
}
// Save row
data.buffer.add( r );
// Check the free memory every 1000 rows...
//
data.freeCounter++;
if ( data.sortSize <= 0 && data.freeCounter >= 1000 ) {
data.freeMemoryPct = Const.getPercentageFreeMemory();
data.freeCounter = 0;
if ( log.isDetailed() ) {
data.memoryReporting++;
if ( data.memoryReporting >= 10 ) {
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "SortRows.Detailed.AvailableMemory", data.freeMemoryPct ) );
}
data.memoryReporting = 0;
}
}
}
// Buffer is full: sort & dump to disk
boolean doSort = data.buffer.size() == data.sortSize;
doSort |=
data.freeMemoryPctLimit > 0 && data.freeMemoryPct < data.freeMemoryPctLimit
&& data.buffer.size() >= data.minSortSize;
if ( log.isDebug() ) {
this.logDebug( BaseMessages.getString( PKG, "SortRows.Debug.StartDumpToDisk", data.freeMemoryPct, data.buffer
.size() ) );
}
// time to sort the buffer and write the data to disk...
if ( doSort ) {
sortExternalRows();
}
}
// dump sorted rows from in-memory buffer to fs file
// clean current buffer
void sortExternalRows() throws HopException {
// we just recently dump buffer - but there is no new rows came.
if ( data.buffer.isEmpty() ) {
return;
}
// First sort the rows in buffer[]
quickSort( data.buffer );
// Then write them to disk...
DataOutputStream dos;
GZIPOutputStream gzos;
int p;
try {
FileObject fileObject =
HopVFS.createTempFile( meta.getPrefix(), ".tmp", environmentSubstitute( meta.getDirectory() ),
getTransMeta() );
data.files.add( fileObject ); // Remember the files!
OutputStream outputStream = HopVFS.getOutputStream( fileObject, false );
if ( data.compressFiles ) {
gzos = new GZIPOutputStream( new BufferedOutputStream( outputStream ) );
dos = new DataOutputStream( gzos );
} else {
dos = new DataOutputStream( new BufferedOutputStream( outputStream, 500000 ) );
gzos = null;
}
// Just write the data, nothing else
List<Integer> duplicates = new ArrayList<Integer>();
Object[] previousRow = null;
if ( meta.isOnlyPassingUniqueRows() ) {
int index = 0;
while ( index < data.buffer.size() ) {
Object[] row = data.buffer.get( index );
if ( previousRow != null ) {
int result = data.outputRowMeta.compare( row, previousRow, data.fieldnrs );
if ( result == 0 ) {
duplicates.add( index );
if ( log.isRowLevel() ) {
logRowlevel( BaseMessages.getString( PKG, "SortRows.RowLevel.DuplicateRowRemoved", data.outputRowMeta
.getString( row ) ) );
}
}
}
index++;
previousRow = row;
}
}
// How many records do we have left?
data.bufferSizes.add( data.buffer.size() - duplicates.size() );
int duplicatesIndex = 0;
for ( p = 0; p < data.buffer.size(); p++ ) {
boolean skip = false;
if ( duplicatesIndex < duplicates.size() ) {
if ( p == duplicates.get( duplicatesIndex ) ) {
skip = true;
duplicatesIndex++;
}
}
if ( !skip ) {
data.outputRowMeta.writeData( dos, data.buffer.get( p ) );
}
}
if ( data.sortSize < 0 ) {
if ( data.buffer.size() > data.minSortSize ) {
data.minSortSize = data.buffer.size(); // if we did it once, we can do
// it again.
// Memory usage goes up over time, even with garbage collection
// We need pointers, file handles, etc.
// As such, we're going to lower the min sort size a bit
//
data.minSortSize = (int) Math.round( data.minSortSize * 0.90 );
}
}
// Clear the list
data.buffer.clear();
// Close temp-file
dos.close(); // close data stream
if ( gzos != null ) {
gzos.close(); // close gzip stream
}
outputStream.close(); // close file stream
// How much memory do we have left?
//
data.freeMemoryPct = Const.getPercentageFreeMemory();
data.freeCounter = 0;
if ( data.sortSize <= 0 ) {
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "SortRows.Detailed.AvailableMemory", data.freeMemoryPct ) );
}
}
} catch ( Exception e ) {
throw new HopException( "Error processing temp-file!", e );
}
data.getBufferIndex = 0;
}
private DataInputStream getDataInputStream( GZIPInputStream gzipInputStream ) {
DataInputStream result = new DataInputStream( gzipInputStream );
data.gzis.add( gzipInputStream );
return result;
}
// get sorted rows from available files in iterative manner.
// that means call to this method will continue to return rows
// till all temp files will not be read to the end.
Object[] getBuffer() throws HopValueException {
Object[] retval;
// Open all files at once and read one row from each file...
if ( data.files.size() > 0 && ( data.dis.size() == 0 || data.fis.size() == 0 ) ) {
if ( log.isBasic() ) {
logBasic( BaseMessages.getString( PKG, "SortRows.Basic.OpeningTempFiles", data.files.size() ) );
}
try {
for ( int f = 0; f < data.files.size() && !isStopped(); f++ ) {
FileObject fileObject = data.files.get( f );
String filename = HopVFS.getFilename( fileObject );
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "SortRows.Detailed.OpeningTempFile", filename ) );
}
InputStream fi = HopVFS.getInputStream( fileObject );
DataInputStream di;
data.fis.add( fi );
if ( data.compressFiles ) {
di = getDataInputStream( new GZIPInputStream( new BufferedInputStream( fi ) ) );
} else {
di = new DataInputStream( new BufferedInputStream( fi, 50000 ) );
}
data.dis.add( di );
// How long is the buffer?
int buffersize = data.bufferSizes.get( f );
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "SortRows.Detailed.FromFileExpectingRows",
filename, buffersize ) );
}
if ( buffersize > 0 ) {
Object[] row = data.outputRowMeta.readData( di );
data.rowbuffer.add( row ); // new row from input stream
data.tempRows.add( new RowTempFile( row, f ) );
}
}
// Sort the data row buffer
Collections.sort( data.tempRows, data.comparator );
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "SortRows.Error.ErrorReadingBackTempFiles" ), e );
}
}
if ( data.files.size() == 0 ) {
// read from in-memory processing
if ( data.getBufferIndex < data.buffer.size() ) {
retval = data.buffer.get( data.getBufferIndex );
data.getBufferIndex++;
} else {
retval = null;
}
} else {
// read from disk processing
if ( data.rowbuffer.size() == 0 ) {
retval = null;
} else {
// We now have "filenr" rows waiting: which one is the smallest?
//
if ( log.isRowLevel() ) {
for ( int i = 0; i < data.rowbuffer.size() && !isStopped(); i++ ) {
Object[] b = data.rowbuffer.get( i );
logRowlevel( BaseMessages
.getString( PKG, "SortRows.RowLevel.PrintRow", i, data.outputRowMeta.getString( b ) ) );
}
}
RowTempFile rowTempFile = data.tempRows.remove( 0 );
retval = rowTempFile.row;
int smallest = rowTempFile.fileNumber;
// now get another Row for position smallest
FileObject file = data.files.get( smallest );
DataInputStream di = data.dis.get( smallest );
InputStream fi = data.fis.get( smallest );
try {
Object[] row2 = data.outputRowMeta.readData( di );
RowTempFile extra = new RowTempFile( row2, smallest );
int index = Collections.binarySearch( data.tempRows, extra, data.comparator );
if ( index < 0 ) {
data.tempRows.add( index * ( -1 ) - 1, extra );
} else {
data.tempRows.add( index, extra );
}
} catch ( HopFileException fe ) { // empty file or EOF mostly
GZIPInputStream gzfi = ( data.compressFiles ) ? data.gzis.get( smallest ) : null;
try {
di.close();
fi.close();
if ( gzfi != null ) {
gzfi.close();
}
file.delete();
} catch ( IOException e ) {
logError( BaseMessages.getString( PKG, "SortRows.Error.UnableToCloseFile", smallest, file.toString() ) );
setErrors( 1 );
stopAll();
return null;
}
data.files.remove( smallest );
data.dis.remove( smallest );
data.fis.remove( smallest );
if ( gzfi != null ) {
data.gzis.remove( smallest );
}
// Also update all file numbers in in data.tempRows if they are larger
// than smallest.
//
for ( RowTempFile rtf : data.tempRows ) {
if ( rtf.fileNumber > smallest ) {
rtf.fileNumber--;
}
}
} catch ( SocketTimeoutException e ) {
throw new HopValueException( e ); // should never happen on local files
}
}
}
return retval;
}
@Override
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws HopException {
// wait for first for is available
Object[] r = getRow();
List<String> groupFields = null;
if ( first ) {
this.first = false;
// do we have any row at start processing?
if ( r == null ) {
// seems that we don't
this.setOutputDone();
return false;
}
RowMetaInterface inputRowMeta = getInputRowMeta();
// do we have group numbers?
if ( meta.isGroupSortEnabled() ) {
data.newBatch = true;
// we do set exact list instead of null
groupFields = meta.getGroupFields();
data.groupnrs = new int[groupFields.size()];
for ( int i = 0; i < groupFields.size(); i++ ) {
data.groupnrs[i] = inputRowMeta.indexOfValue( groupFields.get( i ) );
if ( data.groupnrs[i] < 0 ) {
logError( BaseMessages.getString( PKG, "SortRows.Error.PresortedFieldNotFound", groupFields.get( i ) ) );
setErrors( 1 );
stopAll();
return false;
}
}
}
String[] fieldNames = meta.getFieldName();
data.fieldnrs = new int[fieldNames.length];
List<Integer> toConvert = new ArrayList<Integer>();
// Metadata
data.outputRowMeta = inputRowMeta.clone();
meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore );
data.comparator = new RowTemapFileComparator( data.outputRowMeta, data.fieldnrs );
for ( int i = 0; i < fieldNames.length; i++ ) {
data.fieldnrs[i] = inputRowMeta.indexOfValue( fieldNames[i] );
if ( data.fieldnrs[i] < 0 ) {
throw new HopException( BaseMessages.getString( PKG, "SortRowsMeta.CheckResult.StepFieldNotInInputStream",
meta.getFieldName()[i], getStepname() ) );
}
// do we need binary conversion for this type?
if ( inputRowMeta.getValueMeta( data.fieldnrs[i] ).isStorageBinaryString() ) {
toConvert.add( data.fieldnrs[i] );
}
}
data.convertKeysToNative = toConvert.isEmpty() ? null : new int[toConvert.size()];
int i = 0;
for ( Integer in : toConvert ) {
data.convertKeysToNative[i] = in;
i++;
}
data.rowComparator = new RowObjectArrayComparator( data.outputRowMeta, data.fieldnrs );
} // end if first
// it is not first row and it is null
if ( r == null ) {
// flush result and set output done.
this.preSortBeforeFlush();
this.passBuffer();
this.setOutputDone();
return false;
}
// if Group Sort is not enabled then do the normal sort.
if ( !meta.isGroupSortEnabled() ) {
this.addBuffer( getInputRowMeta(), r );
} else {
// Otherwise do grouping sort
if ( data.newBatch ) {
data.newBatch = false;
setPrevious( r );
// this enables Sort stuff to initialize it's state.
this.addBuffer( getInputRowMeta(), r );
} else {
if ( this.sameGroup( data.previous, r ) ) {
// setPrevious( r ); // we are not need to set it every time
// this performs SortRows normal row collection functionality.
this.addBuffer( getInputRowMeta(), r );
} else {
this.preSortBeforeFlush();
// flush sorted block to next step:
this.passBuffer();
// new sorted block beginning
setPrevious( r );
data.newBatch = true;
this.addBuffer( getInputRowMeta(), r );
}
}
}
if ( checkFeedback( getLinesRead() ) ) {
if ( log.isBasic() ) {
logBasic( "Linenr " + getLinesRead() );
}
}
return true;
}
/**
* This method passes all rows in the buffer to the next steps. Usually call to this method indicates that this
* particular step finishing processing.
*
*/
void passBuffer() throws HopException {
// Now we can start the output!
//
Object[] r = getBuffer();
Object[] previousRow = null;
// log time spent for external merge (expected time consuming operation)
if ( log.isDebug() && !data.files.isEmpty() ) {
this.logDebug( BaseMessages.getString( PKG, "SortRows.Debug.ExternalMergeStarted" ) );
}
while ( r != null && !isStopped() ) {
if ( log.isRowLevel() ) {
logRowlevel( BaseMessages.getString( PKG, "SortRows.RowLevel.ReadRow", data.outputRowMeta.getString( r ) ) );
}
// Do another verification pass for unique rows...
//
if ( meta.isOnlyPassingUniqueRows() ) {
if ( previousRow != null ) {
// See if this row is the same as the previous one as far as the keys
// are concerned.
// If so, we don't put forward this row.
int result = data.outputRowMeta.compare( r, previousRow, data.fieldnrs );
if ( result != 0 ) {
putRow( data.outputRowMeta, r ); // copy row to possible alternate
// rowset(s).
}
} else {
putRow( data.outputRowMeta, r ); // copy row to next steps
}
previousRow = r;
} else {
putRow( data.outputRowMeta, r ); // copy row to possible alternate
// rowset(s).
}
r = getBuffer();
}
if ( log.isDebug() && !data.files.isEmpty() ) {
this.logDebug( BaseMessages.getString( PKG, "SortRows.Debug.ExternalMergeFinished" ) );
}
// Clear out the buffer for the next batch
//
clearBuffers();
}
@Override
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (SortRowsMeta) smi;
data = (SortRowsData) sdi;
if ( !super.init( smi, sdi ) ) {
return false;
}
//Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
if ( getTransMeta().getNamedClusterEmbedManager() != null ) {
getTransMeta().getNamedClusterEmbedManager()
.passEmbeddedMetastoreKey( getTransMeta(), getTransMeta().getEmbeddedMetastoreProviderKey() );
}
data.sortSize = Const.toInt( environmentSubstitute( meta.getSortSize() ), -1 );
data.freeMemoryPctLimit = Const.toInt( meta.getFreeMemoryLimit(), -1 );
if ( data.sortSize <= 0 && data.freeMemoryPctLimit <= 0 ) {
// Prefer the memory limit as it should never fail
//
data.freeMemoryPctLimit = 25;
}
// In memory buffer
//
data.buffer = new ArrayList<Object[]>( 5000 );
// Buffer for reading from disk
//
data.rowbuffer = new ArrayList<Object[]>( 5000 );
data.compressFiles = getBooleanValueOfVariable( meta.getCompressFilesVariable(), meta.getCompressFiles() );
data.tempRows = new ArrayList<RowTempFile>();
data.minSortSize = 5000;
return true;
}
@Override
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
clearBuffers();
super.dispose( smi, sdi );
}
private void clearBuffers() {
// Clean out the sort buffer
data.buffer.clear();
data.getBufferIndex = 0;
data.rowbuffer.clear();
// close any open DataInputStream objects
if ( ( data.dis != null ) && ( data.dis.size() > 0 ) ) {
for ( DataInputStream dis : data.dis ) {
BaseStep.closeQuietly( dis );
}
}
// close any open InputStream objects
if ( ( data.fis != null ) && ( data.fis.size() > 0 ) ) {
for ( InputStream is : data.fis ) {
BaseStep.closeQuietly( is );
}
}
// remove temp files
for ( int f = 0; f < data.files.size(); f++ ) {
FileObject fileToDelete = data.files.get( f );
try {
if ( fileToDelete != null && fileToDelete.exists() ) {
fileToDelete.delete();
}
} catch ( FileSystemException e ) {
logError( e.getLocalizedMessage(), e );
}
}
}
/**
* Sort the entire vector, if it is not empty.
*/
void quickSort( List<Object[]> elements ) throws HopException {
if ( elements.size() > 0 ) {
Collections.sort( elements, data.rowComparator );
long nrConversions = 0L;
for ( ValueMetaInterface valueMeta : data.outputRowMeta.getValueMetaList() ) {
nrConversions += valueMeta.getNumberOfBinaryStringConversions();
valueMeta.setNumberOfBinaryStringConversions( 0L );
}
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "SortRows.Detailed.ReportNumberOfBinaryStringConv", nrConversions ) );
}
}
}
/**
* Calling this method will alert the step that we finished passing records to the step. Specifically for steps like
* "Sort Rows" it means that the buffered rows can be sorted and passed on.
*/
@Override
public void batchComplete() throws HopException {
preSortBeforeFlush();
passBuffer();
setOutputDone();
}
private void preSortBeforeFlush() throws HopException {
if ( data.files.size() > 0 ) {
// dump to dist and then read from disk
sortExternalRows();
} else {
// sort in memory
quickSort( data.buffer );
}
}
/*
* Group Fields Implementation heroic
*/
// Is the row r of the same group as previous?
private boolean sameGroup( Object[] previous, Object[] r ) throws HopValueException {
if ( r == null ) {
return false;
}
return getInputRowMeta().compare( previous, r, data.groupnrs ) == 0;
}
private void setPrevious( Object[] r ) throws HopException {
if ( r != null ) {
this.data.previous = getInputRowMeta().cloneRow( r );
}
}
private class SortRowsComparator {
protected RowMetaInterface rowMeta;
protected int[] fieldNrs;
SortRowsComparator( RowMetaInterface rowMeta, int[] fieldNrs ) {
this.rowMeta = rowMeta;
this.fieldNrs = fieldNrs;
}
}
private class RowTemapFileComparator extends SortRowsComparator implements Comparator<RowTempFile> {
RowTemapFileComparator( RowMetaInterface rowMeta, int[] fieldNrs ) {
super( rowMeta, fieldNrs );
}
@Override
public int compare( RowTempFile o1, RowTempFile o2 ) {
try {
return rowMeta.compare( o1.row, o2.row, fieldNrs );
} catch ( HopValueException e ) {
logError( "Error comparing rows: " + e.toString() );
return 0;
}
}
}
private class RowObjectArrayComparator extends SortRowsComparator implements Comparator<Object[]> {
RowObjectArrayComparator( RowMetaInterface rowMeta, int[] fieldNrs ) {
super( rowMeta, fieldNrs );
}
@Override
public int compare( Object[] o1, Object[] o2 ) {
try {
return rowMeta.compare( o1, o2, fieldNrs );
} catch ( HopValueException e ) {
logError( "Error comparing rows: " + e.toString() );
return 0;
}
}
}
}
| [
"[email protected]"
]
| |
92186f7bd40651765bf095051579283b20636d26 | 617dc2fc3f147f9c1400178ebdffe85981ccced5 | /src/main/java/br/com/projeto/projeto/projetoempresa/controllers/ControllerSetor.java | 75b80058447bedf39cf03656e9ec14aa8b106f01 | []
| no_license | EllenJoyce/Projeto-Empresa | e692b653a9f3ddc547535cb38334e38e7fbb28f1 | 09692afdbde3160f7d9a84699307643887d7099c | refs/heads/master | 2021-09-01T15:36:29.448599 | 2017-12-27T18:52:50 | 2017-12-27T18:52:50 | 115,546,569 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,517 | java | package br.com.projeto.projeto.projetoempresa.controllers;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import br.com.projeto.projeto.projetoempresa.dao.TesteConection;
import br.com.projeto.projeto.projetoempresa.models.Projeto;
import br.com.projeto.projeto.projetoempresa.models.SetorEmpresa;
public class ControllerSetor {
//função para adicionar setor na base de dados
public static void adicionaSetor(String nomeSetor, String nomeGerente)
throws SQLException, InstantiationException {
String sql;
String table = "PROJETO_EMPRESA.dbo.Setor_empresa";
sql = "INSERT INTO " + table + "(Nome_do_setor, Gerente) values (?,?)";
Connection conn = TesteConection.connect();
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, nomeSetor);
pstm.setString(2, nomeGerente);
pstm.executeUpdate();
conn.close();
}
//função para alterar setor na base de dados
public static void alterarSetor(SetorEmpresa s)
throws SQLException, InstantiationException {
String sql;
String table = "PROJETO_EMPRESA.dbo.Setor_empresa";
sql = "UPDATE " + table + " SET Nome_do_setor=?, Gerente=? WHERE id=?";
Connection conn = TesteConection.connect();
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setString(1, s.getnomesetor());
pstm.setString(2, s.getgerente());
pstm.setInt(3, s.getid());
pstm.executeUpdate();
conn.close();
}
//função para deletar setor na base de dados
public static void deleteSetor(int id)
throws SQLException, InstantiationException {
String sql;
String table = "PROJETO_EMPRESA.dbo.Setor_empresa";
sql = "DELETE FROM " + table + " WHERE id=?";
Connection conn = TesteConection.connect();
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setInt(1, id);
pstm.executeUpdate();
conn.close();
}
//função para consultar setor na base de dados
public static SetorEmpresa consultaSetorEmp(int id)
throws SQLException, InstantiationException {
String sql;
String table = "PROJETO_EMPRESA.dbo.Setor_empresa";
sql = "SELECT * FROM " + table + " WHERE id = ?";
Connection conn = TesteConection.connect();
PreparedStatement pstm = conn.prepareStatement(sql);
pstm.setInt(1, id);
ResultSet resultado = (pstm.executeQuery());
SetorEmpresa s = null;
if (resultado.next()) {
int resId = resultado.getInt("id");
String resNomeSetor = resultado.getString("Nome_do_setor");
String resGerente = resultado.getString("Gerente");
s = new SetorEmpresa(resId, resNomeSetor, resGerente);
}
return s;
}
//Função para listar todos os funcionários
/*public static ArrayList<SetorEmpresa> consultaSetores()
throws SQLException, InstantiationException {
String sql;
String table = "PROJETO_EMPRESA.dbo.Setor_empresa";
sql = "SELECT * FROM " + table;
Connection conn = TesteConection.connect();
PreparedStatement pstm = conn.prepareStatement(sql);
ResultSet resultado = (pstm.executeQuery());
ArrayList<SetorEmpresa> p = new ArrayList<SetorEmpresa>();
while (resultado.next()) {
int resId = resultado.getInt("id");
String resNomeSetor = resultado.getString("Nome_do_setor");
String resGerente = resultado.getString("Gerente");
p.add(new SetorEmpresa(resId, resNomeSetor, resGerente));
}
return p;
}*/
}
| [
"[email protected]"
]
| |
c0305777b561b4fc9c28aa7d356bc8c718a08cd8 | b40a9ce69a555eb250975b341f98c76476b7574e | /thirdstage.mcon/src/main/java/thirdstage/mcon/meta/FieldFacetType.java | b6ca932b2e3241d279fc48ad3137bae92e92546d | []
| no_license | 3rdstage/prototypes | 07965b2f0b90140b2fb8b8ec93c71e1e47b73f3c | 70a5f5213c2e6d786a494367824f5b43832e995d | refs/heads/master | 2020-12-24T09:24:13.180727 | 2017-03-03T17:06:26 | 2017-03-03T17:06:26 | 73,292,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 533 | java | package thirdstage.mcon.meta;
/**
* Overall concept of facet is based on the facet of XML schema.
* Facet is said to be a single defining aspect of a value space.
* For more, read http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#facets
*
* @author 3rdstage
*
*/
public enum FieldFacetType {
LENGTH,
MIN_LENGTH,
MAX_LENGTH,
PATTERN,
ENUMERATION,
MAX, // max inclusive, equal or less than
MIN, // min inclusive, equal or more than
MAX_EXCLUSIVE, //less than
MIN_EXCLUSIVE, //more than
}
| [
"[email protected]"
]
| |
aa4350f409d3128d59b163b5aa4f2067f10021b0 | fdfb0862805e2a861128a308bed64c875ca3f754 | /UniversalVesAdapter/src/test/java/org/onap/dcaegen2/ves/domain/ves54/ThresholdCrossingAlertFieldsTest.java | 314de6fdb8bf820625b38694534122c83b1d8bf7 | [
"Apache-2.0"
]
| permissive | onap/dcaegen2-services-mapper | 94c7caa74686fe4816dfd721fb8ea8ca1fcffd0f | 092862010cd3a878340bf2aa05f936d0fb2776eb | refs/heads/master | 2023-08-31T18:07:13.469351 | 2023-03-31T09:36:38 | 2023-03-31T09:36:54 | 159,415,494 | 2 | 1 | NOASSERTION | 2021-06-29T18:13:56 | 2018-11-27T23:37:06 | Java | UTF-8 | Java | false | false | 12,689 | java | /*-
* ============LICENSE_START=======================================================
* ONAP : DCAE
* ================================================================================
* Copyright 2019 TechMahindra
* ================================================================================
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.dcaegen2.ves.domain.ves54;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class ThresholdCrossingAlertFieldsTest {
private ThresholdCrossingAlertFields createTestSubject() {
return new ThresholdCrossingAlertFields();
}
@Test
public void testGetAdditionalFields() throws Exception {
ThresholdCrossingAlertFields testSubject;
List<AlarmAdditionalInformation> result;
// default test
testSubject = createTestSubject();
result = testSubject.getAdditionalFields();
}
@Test
public void testSetAdditionalFields() throws Exception {
ThresholdCrossingAlertFields testSubject;
List<AlarmAdditionalInformation> additionalFields = null;
// default test
testSubject = createTestSubject();
testSubject.setAdditionalFields(additionalFields);
}
@Test
public void testGetAdditionalParameters() throws Exception {
ThresholdCrossingAlertFields testSubject;
List<AdditionalParameter> result;
// default test
testSubject = createTestSubject();
result = testSubject.getAdditionalParameters();
}
@Test
public void testSetAdditionalParameters() throws Exception {
ThresholdCrossingAlertFields testSubject;
List<AdditionalParameter> additionalParameters = null;
// default test
testSubject = createTestSubject();
testSubject.setAdditionalParameters(additionalParameters);
}
@Test
public void testGetAlertAction() throws Exception {
ThresholdCrossingAlertFields testSubject;
ThresholdCrossingAlertFields.AlertAction result;
// default test
testSubject = createTestSubject();
result = testSubject.getAlertAction();
}
@Test
public void testSetAlertAction() throws Exception {
ThresholdCrossingAlertFields testSubject;
ThresholdCrossingAlertFields.AlertAction alertAction = null;
// default test
testSubject = createTestSubject();
testSubject.setAlertAction(alertAction);
}
@Test
public void testGetAlertDescription() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getAlertDescription();
}
@Test
public void testSetAlertDescription() throws Exception {
ThresholdCrossingAlertFields testSubject;
String alertDescription = "";
// default test
testSubject = createTestSubject();
testSubject.setAlertDescription(alertDescription);
}
@Test
public void testGetAlertType() throws Exception {
ThresholdCrossingAlertFields testSubject;
ThresholdCrossingAlertFields.AlertType result;
// default test
testSubject = createTestSubject();
result = testSubject.getAlertType();
}
@Test
public void testSetAlertType() throws Exception {
ThresholdCrossingAlertFields testSubject;
ThresholdCrossingAlertFields.AlertType alertType = null;
// default test
testSubject = createTestSubject();
testSubject.setAlertType(alertType);
}
@Test
public void testGetAlertValue() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getAlertValue();
}
@Test
public void testSetAlertValue() throws Exception {
ThresholdCrossingAlertFields testSubject;
String alertValue = "";
// default test
testSubject = createTestSubject();
testSubject.setAlertValue(alertValue);
}
@Test
public void testGetAssociatedAlertIdList() throws Exception {
ThresholdCrossingAlertFields testSubject;
List<String> result;
// default test
testSubject = createTestSubject();
result = testSubject.getAssociatedAlertIdList();
}
@Test
public void testSetAssociatedAlertIdList() throws Exception {
ThresholdCrossingAlertFields testSubject;
List<String> associatedAlertIdList = null;
// default test
testSubject = createTestSubject();
testSubject.setAssociatedAlertIdList(associatedAlertIdList);
}
@Test
public void testGetCollectionTimestamp() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getCollectionTimestamp();
}
@Test
public void testSetCollectionTimestamp() throws Exception {
ThresholdCrossingAlertFields testSubject;
String collectionTimestamp = "";
// default test
testSubject = createTestSubject();
testSubject.setCollectionTimestamp(collectionTimestamp);
}
@Test
public void testGetDataCollector() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getDataCollector();
}
@Test
public void testSetDataCollector() throws Exception {
ThresholdCrossingAlertFields testSubject;
String dataCollector = "";
// default test
testSubject = createTestSubject();
testSubject.setDataCollector(dataCollector);
}
@Test
public void testGetElementType() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getElementType();
}
@Test
public void testSetElementType() throws Exception {
ThresholdCrossingAlertFields testSubject;
String elementType = "";
// default test
testSubject = createTestSubject();
testSubject.setElementType(elementType);
}
@Test
public void testGetEventSeverity() throws Exception {
ThresholdCrossingAlertFields testSubject;
ThresholdCrossingAlertFields.EventSeverity result;
// default test
testSubject = createTestSubject();
result = testSubject.getEventSeverity();
}
@Test
public void testSetEventSeverity() throws Exception {
ThresholdCrossingAlertFields testSubject;
ThresholdCrossingAlertFields.EventSeverity eventSeverity = null;
// default test
testSubject = createTestSubject();
testSubject.setEventSeverity(eventSeverity);
}
@Test
public void testGetEventStartTimestamp() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getEventStartTimestamp();
}
@Test
public void testSetEventStartTimestamp() throws Exception {
ThresholdCrossingAlertFields testSubject;
String eventStartTimestamp = "";
// default test
testSubject = createTestSubject();
testSubject.setEventStartTimestamp(eventStartTimestamp);
}
@Test
public void testGetInterfaceName() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getInterfaceName();
}
@Test
public void testSetInterfaceName() throws Exception {
ThresholdCrossingAlertFields testSubject;
String interfaceName = "";
// default test
testSubject = createTestSubject();
testSubject.setInterfaceName(interfaceName);
}
@Test
public void testGetNetworkService() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getNetworkService();
}
@Test
public void testSetNetworkService() throws Exception {
ThresholdCrossingAlertFields testSubject;
String networkService = "";
// default test
testSubject = createTestSubject();
testSubject.setNetworkService(networkService);
}
@Test
public void testGetPossibleRootCause() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getPossibleRootCause();
}
@Test
public void testSetPossibleRootCause() throws Exception {
ThresholdCrossingAlertFields testSubject;
String possibleRootCause = "";
// default test
testSubject = createTestSubject();
testSubject.setPossibleRootCause(possibleRootCause);
}
@Test
public void testGetThresholdCrossingFieldsVersion() throws Exception {
ThresholdCrossingAlertFields testSubject;
Double result;
// default test
testSubject = createTestSubject();
result = testSubject.getThresholdCrossingFieldsVersion();
}
@Test
public void testSetThresholdCrossingFieldsVersion() throws Exception {
ThresholdCrossingAlertFields testSubject;
Double thresholdCrossingFieldsVersion = null;
// default test
testSubject = createTestSubject();
testSubject.setThresholdCrossingFieldsVersion(thresholdCrossingFieldsVersion);
}
@Test
public void testToString() throws Exception {
ThresholdCrossingAlertFields testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.toString();
}
@Test
public void testGetAdditionalProperties() throws Exception {
ThresholdCrossingAlertFields testSubject;
Map<String, Object> result;
// default test
testSubject = createTestSubject();
result = testSubject.getAdditionalProperties();
}
@Test
public void testSetAdditionalProperty() throws Exception {
ThresholdCrossingAlertFields testSubject;
String name = "";
Object value = null;
// default test
testSubject = createTestSubject();
testSubject.setAdditionalProperty(name, value);
}
@Test
public void testHashCode() throws Exception {
ThresholdCrossingAlertFields testSubject;
int result;
// default test
testSubject = createTestSubject();
result = testSubject.hashCode();
}
}
| [
"[email protected]"
]
| |
f1c9ca0b27f7ac22738ac8507afc1354e49cc1b3 | 9887cdee978edadb5981852697d01118e524678a | /PSS/src/main/java/com/websystique/springmvc/model/Tipocontratacion.java | f7c0026239484983760d05348b621b6b1b424958 | []
| no_license | wvargasg/PROYS | 414bc777deb8590f339bd9d306d057b62d1be1f1 | 7ecb163d67446dd7f7e4a8fd6281f30f1124ce3a | refs/heads/master | 2020-07-20T19:02:17.123329 | 2016-09-02T16:56:08 | 2016-09-02T16:56:08 | 67,241,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,192 | java | package com.websystique.springmvc.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the "TIPOCONTRATACION" database table.
*
*/
@Entity
@Table(name="\"TIPOCONTRATACION\"")
@NamedQuery(name="Tipocontratacion.findAll", query="SELECT t FROM Tipocontratacion t")
public class Tipocontratacion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="\"ID_TIPOCONTRATACION\"")
private Integer idTipocontratacion;
@Column(name="\"DESCRIPCION\"")
private String descripcion;
@Column(name="\"ESTADO_TIPOCONTRATACION\"")
private Integer estadoTipocontratacion;
//bi-directional many-to-one association to Ofrecimientosalarial
@OneToMany(mappedBy="tipocontratacion")
private List<Ofrecimientosalarial> ofrecimientosalarials;
//bi-directional many-to-one association to Pretensionsalarial
@OneToMany(mappedBy="tipocontratacion")
private List<Pretensionsalarial> pretensionsalarials;
public Tipocontratacion() {
}
public Integer getIdTipocontratacion() {
return this.idTipocontratacion;
}
public void setIdTipocontratacion(Integer idTipocontratacion) {
this.idTipocontratacion = idTipocontratacion;
}
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Integer getEstadoTipocontratacion() {
return this.estadoTipocontratacion;
}
public void setEstadoTipocontratacion(Integer estadoTipocontratacion) {
this.estadoTipocontratacion = estadoTipocontratacion;
}
public List<Ofrecimientosalarial> getOfrecimientosalarials() {
return this.ofrecimientosalarials;
}
public void setOfrecimientosalarials(List<Ofrecimientosalarial> ofrecimientosalarials) {
this.ofrecimientosalarials = ofrecimientosalarials;
}
public Ofrecimientosalarial addOfrecimientosalarial(Ofrecimientosalarial ofrecimientosalarial) {
getOfrecimientosalarials().add(ofrecimientosalarial);
ofrecimientosalarial.setTipocontratacion(this);
return ofrecimientosalarial;
}
public Ofrecimientosalarial removeOfrecimientosalarial(Ofrecimientosalarial ofrecimientosalarial) {
getOfrecimientosalarials().remove(ofrecimientosalarial);
ofrecimientosalarial.setTipocontratacion(null);
return ofrecimientosalarial;
}
public List<Pretensionsalarial> getPretensionsalarials() {
return this.pretensionsalarials;
}
public void setPretensionsalarials(List<Pretensionsalarial> pretensionsalarials) {
this.pretensionsalarials = pretensionsalarials;
}
public Pretensionsalarial addPretensionsalarial(Pretensionsalarial pretensionsalarial) {
getPretensionsalarials().add(pretensionsalarial);
pretensionsalarial.setTipocontratacion(this);
return pretensionsalarial;
}
public Pretensionsalarial removePretensionsalarial(Pretensionsalarial pretensionsalarial) {
getPretensionsalarials().remove(pretensionsalarial);
pretensionsalarial.setTipocontratacion(null);
return pretensionsalarial;
}
} | [
"[email protected]"
]
| |
d247f0420242d255bf7bd6f3d32aa81373ce679e | 4787d91d6b1e0895f241586f210a53452907af59 | /lambda.clementine-player.org/src/main/java/SslExpiry.java | dc97021417bc57d0b352a93bda2e02b57c03afae | []
| no_license | seanpm2001/Clementine-player_Website | bc3f0efe7da354f2f3c40e2bafe66c9eb83cb057 | 1a6c650e59f4561bdcc1be21c5f5877f6c547560 | refs/heads/master | 2023-06-04T06:32:08.182523 | 2021-06-23T12:28:33 | 2021-06-23T12:29:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,407 | java | package org.clementineplayer.lambda;
import com.google.auto.value.AutoValue;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
public class SslExpiry {
private static final String SNS_ARN = "arn:aws:sns:us-east-1:165405240372:ssl_expiry";
private static final List<String> DOMAINS = ImmutableList.of(
"clementine-player.org",
"buildbot.clementine-player.org",
"builds.clementine-player.org",
"data.clementine-player.org",
"images.clementine-player.org",
"spotify.clementine-player.org",
"www.clementine-player.org");
private final ListeningExecutorService executor = MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(2));
private final AmazonSNSClient snsClient =
new AmazonSNSClient(new DefaultAWSCredentialsProviderChain());
private CertificateFactory certFactory;
public SslExpiry() {
snsClient.setRegion(Region.getRegion(Regions.US_EAST_1));
try {
certFactory = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
Throwables.propagate(e);
}
}
public String verifyAll(final Context context) throws Exception {
String ret = verifyAllImpl(new AmazonLogger(context));
executor.shutdown();
return ret;
}
public String verifyAllImpl(final Logger logger)
throws InterruptedException, ExecutionException, IOException {
final ArrayList<ListenableFuture<Result>> futures = new ArrayList<>();
for (final String domain : DOMAINS) {
ListenableFuture<Result> future = executor.submit(
new Callable<Result>() {
@Override
public Result call() throws Exception {
return Result.create(domain, verifyOpenSSL(domain, logger));
}
});
futures.add(future);
}
List<Result> results = Futures.allAsList(futures).get();
StringBuilder sb = new StringBuilder();
Instant expiryDateWarning = Instant.now().plus(14, ChronoUnit.DAYS);
for (Result result : results) {
sb.append(
result.domain() + " expires on: " + result.expires().toString() + "\n");
// If it expires in the next two weeks, print a warning.
if (result.expires().isBefore(expiryDateWarning)) {
sb.append("WARNING!!! Domain " + result.domain() + " expires in " +
result.expires().until(expiryDateWarning, ChronoUnit.DAYS) + " days");
}
}
publishToSNS(sb.toString(), logger);
return "ok";
}
/** Fetch SSL certs using the openssl command line. */
public Instant verifyOpenSSL(String domain, Logger logger)
throws IOException, CertificateException {
Process certFetcher = new ProcessBuilder(
"openssl", "s_client", "-connect", domain + ":" + 443, "-servername", domain)
.start();
try {
certFetcher.getOutputStream().close();
LineNumberReader reader =
new LineNumberReader(new InputStreamReader(certFetcher.getInputStream()));
String line = null;
StringBuilder certBuilder = new StringBuilder();
boolean inCert = false;
while ((line = reader.readLine()) != null) {
if (line.equals("-----BEGIN CERTIFICATE-----")) {
inCert = true;
}
if (inCert) {
certBuilder.append(line);
certBuilder.append('\n');
}
if (line.equals("-----END CERTIFICATE-----")) {
break;
}
}
String cert = certBuilder.toString();
X509Certificate x509cert = (X509Certificate) certFactory.generateCertificate(
new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8)));
return x509cert.getNotAfter().toInstant();
} finally {
certFetcher.destroyForcibly();
}
}
private void publishToSNS(String message, Logger logger) {
PublishRequest publishRequest = new PublishRequest()
.withTopicArn(SNS_ARN)
.withMessage(message)
.withSubject("Clementine Domain Certificates Expiry");
logger.log("created request\n" + publishRequest.toString());
PublishResult publishResult = snsClient.publish(publishRequest);
logger.log("Message published: " + publishResult.getMessageId() + "\n");
logger.log(publishRequest.toString());
}
@AutoValue
abstract static class Result {
static Result create(String domain, Instant expires) {
return new AutoValue_SslExpiry_Result(domain, expires);
}
abstract String domain();
abstract Instant expires();
}
private interface Logger {
void log(String msg);
}
private static class AmazonLogger implements Logger {
private final LambdaLogger logger;
AmazonLogger(Context context) {
this.logger = context.getLogger();
}
public void log(String msg) {
logger.log(msg);
}
}
private static class LocalLogger implements Logger {
public void log(String msg) {
System.out.println(msg);
}
}
public static void main(String[] args) {
SslExpiry expiry = new SslExpiry();
try {
System.out.println(expiry.verifyAllImpl(new LocalLogger()));
} catch (Exception e) {
e.printStackTrace();
}
expiry.executor.shutdown();
}
}
| [
"[email protected]"
]
| |
8de054f4d3c2eb1399138d0f6dd8e6773e29ade8 | 12d86908a7d81d46acb3d25a25a3ecd14db14123 | /app/src/main/java/fr/wcs/bataillenavale/PlayerClass.java | 8fae3565e60ee93ebe9c77d12a1f9a18fd255df9 | []
| no_license | lebiam/BatailleNavale | 1a94e4a8b96a26f08621d4b0787764d8b113cc6e | 44d3a088343d885d0575b682de8053df5bbd37f4 | refs/heads/master | 2021-01-20T03:39:51.598545 | 2017-04-28T13:38:42 | 2017-04-28T13:38:42 | 89,570,821 | 0 | 0 | null | 2017-04-28T11:05:00 | 2017-04-27T07:49:30 | Java | UTF-8 | Java | false | false | 295 | java | package fr.wcs.bataillenavale;
/**
* Created by apprenti on 27/04/17.
*/
public class PlayerClass {
private ArmadaClass mArmada;
private String mUserName;
public PlayerClass(ArmadaClass armada, String username){
mArmada = armada;
mUserName = username;
}
}
| [
"[[email protected]]"
]
| |
9e902cbb75c5ea8d4ece3780e1878b9d733a8d75 | 4bb757836e55714eb28ae0130aeac0b22172f858 | /src/main/java/springboot_12/demo/ActorRepository.java | 9ba6f9c4b5df113d9a8184c882a71d45530163bf | []
| no_license | sarojineerathor/SpringBoot_12 | e92c8be88d63fe19caae024ee3d380bfbb690b0a | 1d53aeb851c5764e09b6ed4309ab3eb9b5dd25ea | refs/heads/master | 2021-04-06T13:40:22.417249 | 2018-03-14T19:58:32 | 2018-03-14T19:58:32 | 125,266,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 161 | java | package springboot_12.demo;
import org.springframework.data.repository.CrudRepository;
public interface ActorRepository extends CrudRepository<Actor, Long> {
}
| [
"[email protected]"
]
| |
357b204acff4d2513d56dae8916d9f68948e116c | 4a41a93f8b2251989a32680d08b1f80828f67ac8 | /Command/src/main/java/by/bsu/patterncommand/logic/ClearCartLogic.java | e3beea06ab4f9e5be522aedfb15680eb777c992e | []
| no_license | elena-vizgalova/bsuSCRepository | 2b7cde87bb84515f34dcf6f8fe29349ef8d0adb5 | db6a83c4c9a6c8fc245e788ef7c20f1074e9a412 | refs/heads/master | 2021-01-10T19:05:39.301854 | 2013-10-31T20:48:22 | 2013-10-31T20:48:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,011 | java | package by.bsu.patterncommand.logic;
import by.bsu.patterncommand.entity.Cart;
import by.bsu.patterncommand.entity.Order;
/**
* Provides logic for clearing cart operation.
* @author Elena Vizgaloca
*/
public class ClearCartLogic {
private static volatile ClearCartLogic instance;
private static final boolean IS_PAYED = false;
private ClearCartLogic() {
}
public static ClearCartLogic getInstance() {
if ( null == instance ) {
synchronized( ClearCartLogic.class ) {
if ( null == instance ) {
instance = new ClearCartLogic();
}
}
}
return instance;
}
public Cart makeNewCart( Cart cart ) {
cart = new Cart();
return cart;
}
public Order clearCart( Order order ) {
order.setCart( new Cart() );
order.setIsPayed( IS_PAYED );
return order;
}
}
| [
"[email protected]"
]
| |
de5abd567126d7dd5a8329b1fe11bf6d6c85d961 | a2ed6c0f98fd7e2dbdb73e1b9fa229c553b8a429 | /app/src/androidTest/java/io/dwak/multiitemrecyclerview/ApplicationTest.java | 9725fffb332ccbde7450d1151b1d261bf50d848a | [
"MIT"
]
| permissive | wherego/multiitemrecyclerview | 619d920e4469395804ecb83a5a40346ac360e6f4 | 78db4e13d2f499e04878d6ccaac201604c4cf12b | refs/heads/master | 2020-04-18T22:19:07.050574 | 2015-07-12T20:27:42 | 2015-07-12T20:27:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 360 | java | package io.dwak.multiitemrecyclerview;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"[email protected]"
]
| |
bbf1add6b0364df6bc1442ec9be4ecb7a68dcf92 | 77a788678ba5c1c42fdb7372850732fadd81382e | /Servidor/branches/PruebasHibernateCasino/src/Beans/Clientes.java | aad66459af89c7f6b7c15c4030b066b6239aa5b5 | []
| no_license | gruize/is0809casino | 6165c60402f498ac219e9cdfb37af8abdd698009 | 10637627c5e153bb376362c59b47514e665bc136 | refs/heads/master | 2021-01-19T11:20:53.909460 | 2009-05-28T07:01:09 | 2009-05-28T07:01:09 | 40,656,814 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,837 | java | package Beans;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Clientes generated by hbm2java
*/
public class Clientes implements java.io.Serializable {
private int codigo;
private String nombre;
private String apellidos;
private String dni;
private String usuario;
private String password;
private String direccion;
private Date fechaingreso;
private String numerocuenta;
private int recargas;
private String telefono;
private Set partidases = new HashSet(0);
public Clientes() {
}
public Clientes(int codigo, String nombre, String apellidos, String dni, String usuario, String password, String direccion, Date fechaingreso, String numerocuenta, int recargas) {
this.codigo = codigo;
this.nombre = nombre;
this.apellidos = apellidos;
this.dni = dni;
this.usuario = usuario;
this.password = password;
this.direccion = direccion;
this.fechaingreso = fechaingreso;
this.numerocuenta = numerocuenta;
this.recargas = recargas;
}
public Clientes(int codigo, String nombre, String apellidos, String dni, String usuario, String password, String direccion, Date fechaingreso, String numerocuenta, int recargas, String telefono, Set partidases) {
this.codigo = codigo;
this.nombre = nombre;
this.apellidos = apellidos;
this.dni = dni;
this.usuario = usuario;
this.password = password;
this.direccion = direccion;
this.fechaingreso = fechaingreso;
this.numerocuenta = numerocuenta;
this.recargas = recargas;
this.telefono = telefono;
this.partidases = partidases;
}
public int getCodigo() {
return this.codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidos() {
return this.apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getDni() {
return this.dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getUsuario() {
return this.usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDireccion() {
return this.direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public Date getFechaingreso() {
return this.fechaingreso;
}
public void setFechaingreso(Date fechaingreso) {
this.fechaingreso = fechaingreso;
}
public String getNumerocuenta() {
return this.numerocuenta;
}
public void setNumerocuenta(String numerocuenta) {
this.numerocuenta = numerocuenta;
}
public int getRecargas() {
return this.recargas;
}
public void setRecargas(int recargas) {
this.recargas = recargas;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Set getPartidases() {
return this.partidases;
}
public void setPartidases(Set partidases) {
this.partidases = partidases;
}
}
| [
"asct86@cc0f0ba8-a479-11dd-a8c6-677c70d10fe4"
]
| asct86@cc0f0ba8-a479-11dd-a8c6-677c70d10fe4 |
ad46384d3f7172ec0a72d8d6a5d23994d795f0bb | 1ae35d0425552b8b89ab37712f4a9ec7ff78047b | /app/src/main/java/com/example/jackty/duan_futurehospital_app/BacSi/view/activity/Bacsi_chitietkhambenh_Activity.java | 7ebe327fec920ca0baf5160e8d934524b60a73ff | []
| no_license | TyFancaoHuynh/duantotnghiep | b25e5a3ff80f65adcde88ae687781ab50c3f1640 | e3a08398ef04c46e1f324398112cd52b9bd5c565 | refs/heads/master | 2021-08-19T07:49:50.858138 | 2017-11-25T01:44:39 | 2017-11-25T01:44:39 | 111,988,954 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 569 | java | package com.example.jackty.duan_futurehospital_app.BacSi.view.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.jackty.duan_futurehospital_app.R;
public class Bacsi_chitietkhambenh_Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// animation for activity
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
setContentView(R.layout.bacsi_chitietkhambenh_activity_);
}
}
| [
"[email protected]"
]
| |
22b4cb3215d760f7715fb8f3e082e5667ce640e5 | 6a1354f8b2271ce3897d3236615e469aca370436 | /src/main/java/com/twistresources/MaintenanceProject/controllers/BookController.java | f976b5aa50ba74a986da73115f49f461426b2eec | []
| no_license | francisianaquino/MaintenanceProject-API | 1c6f59b3b4268ecca3972f2b24ba34b4e95228c1 | bd6be558c0dedc90ee69c117f9443530254b652b | refs/heads/master | 2020-05-31T21:33:03.829811 | 2019-06-11T03:59:46 | 2019-06-11T03:59:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,133 | java | package com.twistresources.MaintenanceProject.controllers;
import com.twistresources.MaintenanceProject.entities.Book;
import com.twistresources.MaintenanceProject.exceptions.InvalidRequestBodyException;
import com.twistresources.MaintenanceProject.pojo.ApiResponse;
import com.twistresources.MaintenanceProject.services.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hibernate.annotations.SQLDelete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.function.Function;
import java.util.stream.Collectors;
@CrossOrigin(origins = "*", allowedHeaders = "*")
@Api(description = "Book Service")
@RestController
@RequestMapping("books")
public class BookController {
private BookService bookService;
@Autowired
public BookController(BookService booksService) {
this.bookService = booksService;
}
@ApiOperation( "find all books" )
@GetMapping
public ResponseEntity findAllBooks(){
return ResponseEntity.status(200).body(bookService.findAllBooks());
}
@ApiOperation( "add books" )
@PostMapping
public ResponseEntity addBook(@RequestBody @Valid Book book, Errors errors){
if (errors.hasErrors())
throw new InvalidRequestBodyException( getValidationErrors.apply(errors) );
return ResponseEntity.status(201)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(bookService.addBook(book));
}
@ApiOperation( "find book by id" )
@GetMapping("/{id}")
public ResponseEntity findBook(@PathVariable Long id){
return ResponseEntity.status(200).body(bookService.findBook(id));
}
@ApiOperation( "update book by id")
@PutMapping("/{id}")
public ResponseEntity updateBook(@PathVariable Long id, @RequestBody @Valid Book books, Errors errors){
if (errors.hasErrors())
throw new InvalidRequestBodyException( getValidationErrors.apply(errors) );
return ResponseEntity.status(200).body(bookService.updateBook(id, books));
}
@ApiOperation( "delete book by id")
@DeleteMapping("/{id}")
public ResponseEntity deleteBook(@PathVariable Long id){
if (bookService.deleteBook(id))
return ResponseEntity.status(200).body(ApiResponse.builder().code(200)
.status("OK").message("data at id "+id+" successfully deleted").build());
return ResponseEntity.status(400).body(ApiResponse.builder().code(400).
status("BAD REQUEST").message("something went wrong").build());
}
private Function<Errors,String> getValidationErrors = err ->
err.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.joining(", "));
} | [
"[email protected]"
]
| |
484b95bbeba10bb6be344a234e5991113ca24e72 | eba77a11fd0e41fef7f63c12df1119b8d4518928 | /app/src/main/java/com/geekhive/foodey/Cakes/adapter/CakeShopStoreRecyclerAdapter.java | 708c1f9531f8fb44ab7252043d6283dbb5af11de | []
| no_license | dprasad554/FoodeyResurant | 0a64f014c504c945aadf7c1fa8cfc465a6b836de | 40fa1753567ec15f4d47f71f45b917b18b314fcb | refs/heads/master | 2023-04-03T15:41:55.851709 | 2021-05-03T08:39:01 | 2021-05-03T08:39:01 | 363,862,272 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,087 | java | package com.geekhive.foodey.Cakes.adapter;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.geekhive.foodey.Cakes.activities.CakeShopSubCategoryActivity;
import com.geekhive.foodey.Cakes.beans.cakestore.CakeStoreList;
import com.geekhive.foodey.Cakes.utils.WebServices;
import com.geekhive.foodey.R;
import com.squareup.picasso.Picasso;
public class CakeShopStoreRecyclerAdapter extends RecyclerView.Adapter<CakeShopStoreRecyclerAdapter.ViewHolder> {
//Variables
private Context mcontext;
CakeStoreList cakeStoreList;
String url = "";
public CakeShopStoreRecyclerAdapter(Context context, CakeStoreList cakeStoreList) {
this.mcontext = context;
this.cakeStoreList = cakeStoreList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cake_layout_shopstore, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
holder.shopname.setText(cakeStoreList.getCakeStore().get(position).getCakeStore().getName());
holder.shopAddress.setText(cakeStoreList.getCakeStore().get(position).getCakeStore().getAddress());
holder.tv_shopTime.setText(cakeStoreList.getCakeStore().get(position).getCakeStore().getDate());
if (cakeStoreList.getCakeStore().get(position).getCakeStore().getImage() != null) {
url = WebServices.Foodey_Cakes_Image_Store + cakeStoreList.getCakeStore().get(position).getCakeStore().getImage();
}
if (!url.equals("")) {
Picasso.get()
.load(url)//download URL
.error(R.drawable.foodey_logo_)//if failed
.into(holder.shopimage);
}
holder.shopimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mcontext, CakeShopSubCategoryActivity.class);
intent.putExtra("url", cakeStoreList.getCakeStore().get(position).getCakeStore().getImage());
intent.putExtra("title", cakeStoreList.getCakeStore().get(position).getCakeStore().getName());
intent.putExtra("storeid", cakeStoreList.getCakeStore().get(position).getCakeStore().getId());
mcontext.startActivity(intent);
}
});
if (cakeStoreList.getCakeStore().get(position).getCakeOffer().size() != 0){
holder.tv_offer.setVisibility(View.VISIBLE);
holder.tv_offer.setText(cakeStoreList.getCakeStore().get(position).getCakeOffer().get(0).getDiscount() + " % Discount " + cakeStoreList.getCakeStore().get(position).getCakeOffer().get(0).getName());
} else {
holder.tv_offer.setVisibility(View.GONE);
holder.vI_cpn.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return cakeStoreList.getCakeStore().size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView shopimage,vI_cpn;
TextView shopname, shopAddress, tv_shopTime, tv_offer;
public ViewHolder(@NonNull View itemView) {
super(itemView);
shopimage = (ImageView) itemView.findViewById(R.id.iv_shopImage);
shopname = (TextView) itemView.findViewById(R.id.tv_shopName);
shopAddress = (TextView) itemView.findViewById(R.id.tv_shopDelivery);
tv_shopTime = (TextView) itemView.findViewById(R.id.tv_shopTime);
tv_offer = (TextView) itemView.findViewById(R.id.vT_offer_txt);
vI_cpn = (ImageView)itemView.findViewById(R.id.vI_cpn);
}
}
}
| [
"[email protected]"
]
| |
5adae03d93432ccd4090d0431f8f6507662e0a11 | e942f8e5c6c5691d4ea34a1864466a89eeb0dcda | /Task2/Product.java | 83c34b3f66c3e68e77b3548db61f28604ad2ccf1 | []
| no_license | nikita788/PolytechJavaEx_2019 | 4315abf54b760f54f32ea968cac2a515e8f730bf | a374db5e3b8632a1f1be5558b52349181e31a0de | refs/heads/master | 2020-05-16T06:24:34.260210 | 2019-05-12T09:23:20 | 2019-05-12T09:23:20 | 182,847,107 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 72 | java | package com.company;
public interface Product {
String whoAmI();
}
| [
"[email protected]"
]
| |
05e7c0fcdc2b1966ab38aaae1db2e142766f8d15 | 705879dc61c41198fb2c4f4f6328bba190c8a465 | /src/main/java/org/virtualbox/IMachineGetRTCUseUTCResponse.java | 2297de611aca7fad7b7c52a240ca439e362c227b | []
| no_license | abiquo/hypervisor-mock | dcd1d6c8a2fdbc4db01c7a6e9a64edd101e8ed42 | e49e4ca84930415eca72ab6c73140a0f2eea4bbe | refs/heads/master | 2021-01-19T09:40:57.840712 | 2013-08-23T08:54:17 | 2013-08-23T08:54:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,256 | java |
package org.virtualbox;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="returnval" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"returnval"
})
@XmlRootElement(name = "IMachine_getRTCUseUTCResponse")
public class IMachineGetRTCUseUTCResponse {
protected boolean returnval;
/**
* Gets the value of the returnval property.
*
*/
public boolean isReturnval() {
return returnval;
}
/**
* Sets the value of the returnval property.
*
*/
public void setReturnval(boolean value) {
this.returnval = value;
}
}
| [
"[email protected]"
]
| |
e0c53a96d6e9ddf88023c5b4487b3dbd1ec517b2 | 4381593d9eae617c9453de351d6e7201baa4c2f8 | /bundles/core/src/main/java/com/adobe/cq/commerce/core/components/internal/servlets/PageTypeRenderConditionServlet.java | f5cd120759fd88bae0566d92226527b83e2fbc9a | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | sandyaggarwal/aem-core-cif-components | f069cf6384f979f3d20590a537897f0a9a401d79 | 6f8de0fd125de6bf2339e833d183020dd21f79cd | refs/heads/master | 2021-10-23T19:33:06.874233 | 2021-10-19T08:26:15 | 2021-10-19T08:26:15 | 207,541,576 | 0 | 0 | Apache-2.0 | 2019-09-10T11:31:11 | 2019-09-10T11:31:11 | null | UTF-8 | Java | false | false | 5,363 | java | /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright 2020 Adobe
~
~ 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.adobe.cq.commerce.core.components.internal.servlets;
import java.util.Arrays;
import javax.annotation.Nonnull;
import javax.servlet.Servlet;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adobe.cq.commerce.core.components.utils.SiteNavigation;
import com.adobe.granite.ui.components.rendercondition.RenderCondition;
import com.adobe.granite.ui.components.rendercondition.SimpleRenderCondition;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
/**
* {@code PageTypeRenderConditionServlet} implements a {@code granite:rendercondition} used which evaluates to true for catalog pages,
* custom category pages and custom product pages.
* It requires the {@code pageType} parameter which should have one of the values: {@code catalog}, {@code category}, {@code product}.
*/
@Component(
service = { Servlet.class },
property = {
"sling.servlet.resourceTypes=" + PageTypeRenderConditionServlet.RESOURCE_TYPE,
"sling.servlet.methods=GET",
"sling.servlet.extensions=html"
})
public class PageTypeRenderConditionServlet extends SlingSafeMethodsServlet {
public final static String RESOURCE_TYPE = "core/cif/components/renderconditions/pagetype";
private static final Logger LOGGER = LoggerFactory.getLogger(PageTypeRenderConditionServlet.class);
private static final String PAGE_PROPERTIES = "wcm/core/content/sites/properties";
private static final String PAGE_TYPE_PROPERTY = "pageType";
private static final String PRODUCT_PAGE_TYPE = "product";
private static final String CATEGORY_PAGE_TYPE = "category";
private static final String CATALOG_PAGE_TYPE = "catalog";
private static final String LANDING_PAGE_TYPE = "landing";
private static final String CATALOG_PAGE_RESOURCE_TYPE = "core/cif/components/structure/catalogpage/v1/catalogpage";
private static final String PN_NAV_ROOT = "navRoot";
@Override
protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response) {
String pageType = request.getResource().getValueMap().get(PAGE_TYPE_PROPERTY, "");
request.setAttribute(RenderCondition.class.getName(), new SimpleRenderCondition(checkPageType(request, pageType)));
}
private boolean checkPageType(SlingHttpServletRequest slingRequest, String pageType) {
if (StringUtils.isBlank(pageType)) {
LOGGER.error("{} property is not defined at {}", PAGE_TYPE_PROPERTY, slingRequest.getResource().getPath());
return false;
}
if (!Arrays.asList(new String[] { CATALOG_PAGE_TYPE, CATEGORY_PAGE_TYPE, PRODUCT_PAGE_TYPE, LANDING_PAGE_TYPE }).contains(
pageType)) {
LOGGER.error("{} property has invalid value at {}: {}", PAGE_TYPE_PROPERTY, slingRequest.getResource().getPath(), pageType);
return false;
}
// the caller is a page properties dialog
if (!StringUtils.contains(slingRequest.getPathInfo(), PAGE_PROPERTIES)) {
return false;
}
PageManager pageManager = slingRequest.getResourceResolver().adaptTo(PageManager.class);
// the page path is in the "item" request parameter
String pagePath = slingRequest.getParameter("item");
Page page = pageManager.getPage(pagePath);
if (page == null) {
return false;
}
if (LANDING_PAGE_TYPE.equals(pageType)) {
ValueMap properties = page.getContentResource().getValueMap();
return properties.get(PN_NAV_ROOT, false);
}
if (CATALOG_PAGE_TYPE.equals(pageType)) {
return page.hasContent() && page.getContentResource().isResourceType(CATALOG_PAGE_RESOURCE_TYPE);
}
// perform the appropriate checks according to the pageType property
if (PRODUCT_PAGE_TYPE.equals(pageType)) {
Page productPage = SiteNavigation.getProductPage(page);
return productPage != null && pagePath.contains(productPage.getPath());
} else if (CATEGORY_PAGE_TYPE.equals(pageType)) {
Page categoryPage = SiteNavigation.getCategoryPage(page);
return categoryPage != null && pagePath.contains(categoryPage.getPath());
}
return false;
}
}
| [
"[email protected]"
]
| |
3c4753c60f84418ca5ce22bac92625c32239eb5f | 19b32ef27c017e0e549ec3235c022609e5d20eb3 | /src/dev/igorartsoft/hierarchical/data/xml/jasperreports/model/GraphicElement.java | 9e2cbabcdcee0125a387ab2096e9b9ab4cbbab79 | [
"MIT"
]
| permissive | IgorArtSoft/hierarchicaldatatransformations | 54769280d1b569e2b7c6d074844f4f4636a763be | 27894b2ee8f33a36aeba4852d87ad432a32c594c | refs/heads/master | 2022-05-27T09:46:43.764284 | 2020-04-30T16:25:14 | 2020-04-30T16:25:14 | 260,020,906 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,969 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.12.04 at 03:04:02 PM EST
//
package dev.igorartsoft.hierarchical.data.xml.jasperreports.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* <attribute name="stretchType">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="NoStretch"/>
* <enumeration value="RelativeToTallestObject"/>
* <enumeration value="RelativeToBandHeight"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="pen">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="None"/>
* <enumeration value="Thin"/>
* <enumeration value="1Point"/>
* <enumeration value="2Point"/>
* <enumeration value="4Point"/>
* <enumeration value="Dotted"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="fill">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Solid"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "graphicElement")
public class GraphicElement {
@XmlAttribute(name = "stretchType")
protected String stretchType;
@XmlElement(name = "pen")
protected Pen pen;
@XmlAttribute(name = "fill")
protected String fill;
/**
* Gets the value of the stretchType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStretchType() {
return stretchType;
}
/**
* Sets the value of the stretchType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStretchType(String value) {
this.stretchType = value;
}
/**
* Gets the value of the pen property.
*
* @return
* possible object is
* {@link String }
*
*/
public Pen getPen() {
return pen;
}
/**
* Sets the value of the pen property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPen(Pen value) {
this.pen = value;
}
/**
* Gets the value of the fill property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFill() {
return fill;
}
/**
* Sets the value of the fill property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFill(String value) {
this.fill = value;
}
}
| [
"[email protected]"
]
| |
3dc12cec448e711acdd5ad1c95adb6cb715fd80f | 3ee3d7fe67db7dfa00ea073b439efd539cf9a135 | /src/main/java/web/model/User.java | d29076ffb3407b06b1352b7d5c98fcd44e54f70c | []
| no_license | VladSmr/Spring-Security-CRUD | a7fcc42353d72977d6720f1bb0b14c5bd2383c95 | 7a5d6a76f462fb0a5803e364678aa27c2b9313b5 | refs/heads/main | 2023-01-04T12:37:51.161052 | 2020-10-09T09:26:59 | 2020-10-09T09:26:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,126 | java | package web.model;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Set;
@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
public User() {
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return name;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User: " +
"id = " + id +
", name = '" + name + '\'' +
", role = '" + roles;
}
} | [
"[email protected]"
]
| |
4b00194a29f270370c68905794b5d866fb8862c0 | 1192323fd6ba9a269d8405b474604287a7f766af | /back-End/src/main/java/br/com/lojatech/services/validation/ClienteInsertValidator.java | c06e5e610ba087e866981df1fb93c06d05f9dd69 | []
| no_license | matheus-henr/Spring_Boot--Ionic-Sistema-De-Pedidos | fef2ccc221da7da4b5b21a6e6732e83237ebf4df | a08aa63b345266880a81f3b36e81dbb1de615d4a | refs/heads/master | 2020-03-15T17:58:47.149679 | 2018-10-03T23:29:22 | 2018-10-03T23:29:22 | 132,273,441 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,708 | java | package br.com.lojatech.services.validation;
import java.util.ArrayList;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import br.com.lojatech.domain.Cliente;
import br.com.lojatech.domain.enums.TipoCliente;
import br.com.lojatech.dto.ClienteNewDTO;
import br.com.lojatech.repository.ClienteRepository;
import br.com.lojatech.resources.exception.FieldMessage;
import br.com.lojatech.services.validation.utils.BR;
public class ClienteInsertValidator implements ConstraintValidator<ClienteInsert, ClienteNewDTO> {
@Autowired
private ClienteRepository repository;
@Override
public void initialize(ClienteInsert ann) {
}
@Override
public boolean isValid(ClienteNewDTO objDto, ConstraintValidatorContext context) {
List<FieldMessage> list = new ArrayList<>();
if(objDto.getTipo().equals(TipoCliente.PESSOAFISICA.getCod()) && !BR.isValidCPF(objDto.getCpfOuCnpj())) {
list.add(new FieldMessage("cpfOuCnpj","CPF invalido"));
}
if(objDto.getTipo().equals(TipoCliente.PESSOA_JURIDICA.getCod()) && !BR.isValidCNPJ(objDto.getCpfOuCnpj())) {
list.add(new FieldMessage("cpfOuCnpj","CNPJ invalido"));
}
Cliente aux = repository.findByEmail(objDto.getEmail());
if(aux != null) {
list.add(new FieldMessage("email", "Email já existente"));
}
// inclua os testes aqui, inserindo erros na lista
for (FieldMessage e : list) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(e.getMessage()).addPropertyNode(e.getFieldName())
.addConstraintViolation();
}
return list.isEmpty();
}
}
| [
"[email protected]"
]
| |
c4655347b64c10e0b46054d181434a8e496fe11c | 0a31c5780c2f1bf8e659d27de101dbbb5cdbb50a | /src/test/java/com/jmtebar/wordcounter/WordCounterApplicationTestSuite.java | b7f9e4e9451f5cecc9e9149cf7cd4dff01e86ac8 | []
| no_license | JosemyAB/josemitd-word-counter | ac2b7336357c916478759d997c24f6f386f4bb94 | db993f3541780e7c842666a13966db8a47955822 | refs/heads/master | 2021-06-24T05:21:07.228364 | 2019-07-03T07:49:19 | 2019-07-03T07:49:19 | 177,982,203 | 0 | 0 | null | 2021-06-07T18:23:51 | 2019-03-27T11:42:38 | Java | UTF-8 | Java | false | false | 403 | java | package com.jmtebar.wordcounter;
import com.jmtebar.wordcounter.service.WordCounterServiceTest;
import com.jmtebar.wordcounter.validator.WordCounterValidatorTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
WordCounterValidatorTest.class,
WordCounterServiceTest.class
})
public class WordCounterApplicationTestSuite {
}
| [
"[email protected]"
]
| |
bee8eb1f053feb754fbb6f4f262559323c31294e | 68fb4a313146be33cd0cf718c274db34932537ff | /src/main/java/com/iad/courseProject/data/services/SectorStateToWorkingTypeService.java | 8e839a63477eed183d7301b22d12d975d6d056f3 | []
| no_license | V4lonforth/IADCP | 7cdc7820875d1d16149835714d04b72a4202d3de | 9dfbb64fa45dddba262ca46e8435f49b523626b0 | refs/heads/master | 2020-04-29T11:02:02.093307 | 2019-03-17T09:51:35 | 2019-03-17T09:51:37 | 176,082,481 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,353 | java | package com.iad.courseProject.data.services;
import com.iad.courseProject.data.entities.SectorStateToWorkingType;
import com.iad.courseProject.data.entities.types.SectorState;
import com.iad.courseProject.data.entities.types.WorkingType;
import com.iad.courseProject.data.repositories.SectorStateToWorkingTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SectorStateToWorkingTypeService {
private final SectorStateToWorkingTypeRepository sectorStateToWorkingTypeRepository;
@Autowired
public SectorStateToWorkingTypeService(SectorStateToWorkingTypeRepository sectorStateToWorkingTypeRepository) {
this.sectorStateToWorkingTypeRepository = sectorStateToWorkingTypeRepository;
}
public List<WorkingType> getWorkingTypesBySectorState(SectorState sectorState) {
return sectorStateToWorkingTypeRepository.getWorkingTypeBySectorState(sectorState);
}
public SectorStateToWorkingType save(SectorStateToWorkingType sectorStateToWorkingType) {
return sectorStateToWorkingTypeRepository.save(sectorStateToWorkingType);
}
public void delete(SectorStateToWorkingType sectorStateToWorkingType) {
sectorStateToWorkingTypeRepository.delete(sectorStateToWorkingType);
}
}
| [
"[email protected]"
]
| |
3235622ef05d80370f29816c5bc30b5571bdf254 | 58da62dfc6e145a3c836a6be8ee11e4b69ff1878 | /src/main/java/com/alipay/api/domain/DeviceTradeResponse.java | 66551ebb8f5b3cfcd9a75a5cfe952fc041194738 | [
"Apache-2.0"
]
| permissive | zhoujiangzi/alipay-sdk-java-all | 00ef60ed9501c74d337eb582cdc9606159a49837 | 560d30b6817a590fd9d2c53c3cecac0dca4449b3 | refs/heads/master | 2022-12-26T00:27:31.553428 | 2020-09-07T03:39:05 | 2020-09-07T03:39:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,224 | java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* iot交易设备信息
*
* @author auto create
* @since 1.0, 2019-02-25 16:47:04
*/
public class DeviceTradeResponse extends AlipayObject {
private static final long serialVersionUID = 8726593144669328199L;
/**
* 设备唯一标识
*/
@ApiField("biz_tid")
private String bizTid;
/**
* 设备sn,通常置于设备标签中
*/
@ApiField("device_sn")
private String deviceSn;
/**
* 交易错误提示
例如:未收录设备的SDK交易
*/
@ApiField("iot_trade_error_type")
private String iotTradeErrorType;
/**
* 物料id,由支付宝同学提供
*/
@ApiField("item_id")
private String itemId;
/**
* SDK加签名信息
*/
@ApiField("terminal_sdk_sign_info")
private String terminalSdkSignInfo;
/**
* 交易完成时间
*/
@ApiField("trade_finish_time")
private String tradeFinishTime;
/**
* 交易流水号
*/
@ApiField("trade_no")
private String tradeNo;
public String getBizTid() {
return this.bizTid;
}
public void setBizTid(String bizTid) {
this.bizTid = bizTid;
}
public String getDeviceSn() {
return this.deviceSn;
}
public void setDeviceSn(String deviceSn) {
this.deviceSn = deviceSn;
}
public String getIotTradeErrorType() {
return this.iotTradeErrorType;
}
public void setIotTradeErrorType(String iotTradeErrorType) {
this.iotTradeErrorType = iotTradeErrorType;
}
public String getItemId() {
return this.itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getTerminalSdkSignInfo() {
return this.terminalSdkSignInfo;
}
public void setTerminalSdkSignInfo(String terminalSdkSignInfo) {
this.terminalSdkSignInfo = terminalSdkSignInfo;
}
public String getTradeFinishTime() {
return this.tradeFinishTime;
}
public void setTradeFinishTime(String tradeFinishTime) {
this.tradeFinishTime = tradeFinishTime;
}
public String getTradeNo() {
return this.tradeNo;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
}
| [
"[email protected]"
]
| |
8145b155d5c4914200f1696495db240d21a348a4 | 89c30287e3bf82789ecebf4f436905a92335927c | /gmall-search/src/main/java/com/atguigu/gmall/search/feign/GmallWmsClient.java | 185442fc961839dc259babf04a8e598931009df8 | [
"Apache-2.0"
]
| permissive | fjy-lwj/gmall | 6dfd14324c0275dd5e3c78ec40ece203c8aec0e2 | ef5f9265369d031c9f9d054a48bd08530ff0b418 | refs/heads/master | 2022-12-12T08:44:37.896581 | 2020-09-07T11:23:38 | 2020-09-07T11:23:38 | 289,158,164 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 250 | java | package com.atguigu.gmall.search.feign;
import com.atguigu.gmall.wms.api.GmallWmsApi;
import org.springframework.cloud.openfeign.FeignClient;
//继承接口即可
@FeignClient("wms-service")
public interface GmallWmsClient extends GmallWmsApi {
}
| [
"[email protected]"
]
| |
7de3962ee100e0bdefde94994ae7f538c0f32b3e | 16a81ebf7427767b5da9ab14a80b9e750135ba52 | /line-bot-cli/src/main/java/com/linecorp/bot/cli/RichMenuDeleteCommand.java | 11133b836bfa17eee8712184efa138c0a59844d3 | [
"Apache-2.0"
]
| permissive | sa-s-ga/line-call-back | 7fb12838a37e079f721d1bf6fc9b3786adcffbce | 03ef769642ca279b25da5396fc44e4c463e44ab9 | refs/heads/master | 2020-11-30T18:18:13.193150 | 2019-12-27T14:17:25 | 2019-12-27T14:17:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,884 | java | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.bot.cli;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Futures.getUnchecked;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import com.linecorp.bot.cli.arguments.Arguments;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.response.BotApiResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
@ConditionalOnProperty(name = "command", havingValue = "richmenu-delete")
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class RichMenuDeleteCommand implements CliCommand {
private LineMessagingClient lineMessagingClient;
private Arguments arguments;
@Override
public void execute() {
final String richMenuId = checkNotNull(arguments.getRichMenuId(), "--rich-menu-id= is not set.");
final BotApiResponse botApiResponse = getUnchecked(lineMessagingClient.deleteRichMenu(richMenuId));
log.info("Successfully finished. {}", botApiResponse);
}
}
| [
"[email protected]"
]
| |
e19300dcd8fcbc2a811e6abd74127fbbddabb7f8 | 87875e820c5bdf6b12b3b50760f508ec293cc355 | /AddProjectMember.java | 4b6556a778cedc67236ff0b11a10d26c140c9b9f | []
| no_license | AmanKharoud/ResourceManagement | 0897192759c41d65d25fe9c48467ff5750941491 | a2d7ac044185440f747b3260f1b5e8a598e81ee3 | refs/heads/master | 2020-03-28T23:56:43.994124 | 2017-06-17T15:45:47 | 2017-06-17T15:45:47 | 94,633,270 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,886 | java | package com.example.aman.finalproject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.aman.finalproject.Adapter.MemberAdapter;
import com.example.aman.finalproject.HttpRequestProcessor.HttpRequestProcessor;
import com.example.aman.finalproject.HttpRequestProcessor.Response;
import com.example.aman.finalproject.apiConfiguration.ApiConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Aman on 4/29/2017.
*/
public class AddProjectMember extends Fragment {
private EditText edt_project_id, edt_start_date,edt_end_date,edt_desc,edt_member_id,edt_status;
private Button add_member;
private String projectId,startDate,endDate,Desc,memberId,status;
private HttpRequestProcessor httpRequestProcessor;
private Response response;
private ApiConfiguration apiConfiguration;
private String baseURL, urlLogin, jsonStringToPost, jsonResponseString,urlRegister;
private boolean success;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
int responseData;
String message;
private CheckBoxSingle memberList;
private ArrayList<CheckBoxSingle> memberListArrayList;
private int memberid;
private MemberAdapter memberAdapter;
public AddProjectMember() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.add_new_project_member, container, false);
edt_project_id= (EditText) v.findViewById(R.id.edt_project_id);
edt_start_date= (EditText) v.findViewById(R.id.edt_satrt_date);
edt_end_date= (EditText) v.findViewById(R.id.edt_end_date);
edt_desc= (EditText) v.findViewById(R.id.edt_descc);
add_member= (Button) v.findViewById(R.id.add_member);
edt_member_id= (EditText) v.findViewById(R.id.edt_member_id);
edt_status= (EditText) v.findViewById(R.id.edt_status);
ListView lv8= (ListView) v.findViewById(R.id.lv8);
//Initialization
httpRequestProcessor = new HttpRequestProcessor();
response = new Response();
apiConfiguration = new ApiConfiguration();
//Getting base url
baseURL = apiConfiguration.getApi();
urlLogin = baseURL + "ProjectMemberAssociationAPI/AddNewAssociation";
urlRegister = baseURL + "MemberAPI/GetApplicationMemberList";
memberListArrayList=new ArrayList<>();
// memberAdapter=new MemberAdapter(this,memberListArrayList);
lv8.setAdapter(memberAdapter);
// registerForContextMenu(lv3);
new RegistrationTask().execute();
add_member.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
projectId=edt_project_id.getText().toString();
startDate=edt_start_date.getText().toString();
endDate=edt_end_date.getText().toString();
Desc=edt_desc.getText().toString();
memberId=edt_member_id.getText().toString();
status=edt_status.getText().toString();
boolean invalid=false;
if (projectId.equals("")) {
invalid = true;
Toast.makeText(AddProjectMember.this.getActivity(), "Enter Project Id", Toast.LENGTH_LONG).show();
}else if (startDate.equals("")) {
invalid = true;
Toast.makeText(AddProjectMember.this.getActivity(), "Enter Start Date", Toast.LENGTH_LONG).show();
}else if (endDate.equals("")) {
invalid = true;
Toast.makeText(AddProjectMember.this.getActivity(), "Enter End Date", Toast.LENGTH_LONG).show();
}else if (Desc.equals("")) {
invalid = true;
Toast.makeText(AddProjectMember.this.getActivity(), "Enter Description", Toast.LENGTH_LONG).show();
}else if (memberId.equals("")) {
invalid = true;
Toast.makeText(AddProjectMember.this.getActivity(), "Enter Member Id", Toast.LENGTH_LONG).show();
}
new addProjectMemberTask().execute(projectId,startDate,endDate,Desc,memberId,status);
}
});
return v;
}
public class addProjectMemberTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
projectId=params[0];
startDate = params[1];
endDate = params[2];
Desc=params[3];
memberId=params[4];
status=params[5];
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("ProjectId","");
jsonObject.put("StartDate", startDate);
jsonObject.put("EndDate", endDate);
jsonObject.put("Description", Desc);
jsonObject.put("CreatedBy","");
jsonObject.put("ModifiedBy", "");
jsonObject.put("MemberId","");
jsonObject.put("Status","");
jsonStringToPost = jsonObject.toString();
response = httpRequestProcessor.pOSTRequestProcessor(jsonStringToPost, urlLogin);
jsonResponseString = response.getJsonResponseString();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonResponseString;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Log.d("Response String", s);
try {
JSONObject jsonObject = new JSONObject(s);
success = jsonObject.getBoolean("success");
Log.d("Success", String.valueOf(success));
message = jsonObject.getString("message");
responseData = jsonObject.getInt("responseData");
if (responseData == 1) {
Toast.makeText(AddProjectMember.this.getActivity(), "Records saved successfully !!", Toast.LENGTH_LONG).show();
//3startActivity(new Intent(AddProjectMember.this.getActivity(), ProjectFragment.class));
} else if (responseData == 2) {
Toast.makeText(AddProjectMember.this.getActivity(), "Record saved Unsuccessfully.Please Try Again...", Toast.LENGTH_LONG).show();
}
// Log.d("message", message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class RegistrationTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
jsonResponseString = httpRequestProcessor.gETRequestProcessor( urlRegister);
return jsonResponseString;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("Response String", s);
sharedPreferences=getActivity().getSharedPreferences(MyPref.Pref_Name, Context.MODE_PRIVATE);
String lID=sharedPreferences.getString(MyPref.UserIdentityKey, String.valueOf(memberid));
int loggedInUserID=Integer.parseInt(lID);
try {
JSONObject jsonObject = new JSONObject(s);
success = jsonObject.getBoolean("success");
Log.d("Success", String.valueOf(success));
message = jsonObject.getString("message");
if(success){
JSONArray responseData=jsonObject.getJSONArray("responseData");
for (int i=0;i<responseData.length();i++) {
JSONObject object = (JSONObject) responseData.get(i);
String fname= object.getString("FName");
Log.d("FName", fname);
// if (loggedInUserID==memberId){
memberList = new CheckBoxSingle(fname);
memberListArrayList.add(memberList);
// }
}
memberAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
// public class GetProfileTask extends AsyncTask<String,String,String>
// {
//
// @Override
// protected String doInBackground(String... params) {
// jsonResponseString = httpRequestProcessor.gETRequestProcessor( urlRegister);
//
// return jsonResponseString;
// }
//
// @Override
// protected void onPostExecute(String s) {
// Log.d("Response String", s);
// sharedPreferences=getActivity().getSharedPreferences(MyPref.Pref_Name, Context.MODE_PRIVATE);
// String lID=sharedPreferences.getString(MyPref.UserIdentityKey, String.valueOf(memberid));
// int loggedInUserID=Integer.parseInt(lID);
// String fname=sharedPreferences.getString(MyPref.FName,null);
//
// try {
// JSONObject jsonObject = new JSONObject(s);
// success = jsonObject.getBoolean("success");
// Log.d("Success", String.valueOf(success));
// message = jsonObject.getString("message");
// if(success){
// JSONArray responseData=jsonObject.getJSONArray("responseData");
// for (int i=0;i<responseData.length();i++) {
// JSONObject object = (JSONObject) responseData.get(i);
// // String fname= object.getString("FName");
// Log.d("FName", fname);
//
//
// // if (loggedInUserID==memberId){
// memberList = new CheckBoxSingle(fname);
// memberListArrayList.add(memberList);
// // }
//
// }
// memberAdapter.notifyDataSetChanged();
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
// super.onPostExecute(s);
// }
// }
}
| [
"[email protected]"
]
| |
b6aeb333c17e83201a2be2c151cdefdb1e959423 | bbc42646d24002abb5db8265415b1442efdd129c | /Java/JavaPatternsAndOther/0others/no_now/src/main/java/dev/gaudnik/no_now/FixedTimeProvider.java | 6a300903ca92774ec690f6e3fee6912ff2225911 | []
| no_license | wojciechGaudnik/Learning | 223a162ddddc59aa4cfe49471ce08ba25587cf1b | dfffd4ddd453edf7667fe94b0fb4367235579424 | refs/heads/master | 2023-03-09T02:21:47.975665 | 2023-01-22T16:09:51 | 2023-01-22T16:09:51 | 201,742,343 | 0 | 0 | null | 2023-03-01T05:35:15 | 2019-08-11T09:10:46 | C | UTF-8 | Java | false | false | 686 | java | package dev.gaudnik.no_now;
import dev.gaudnik.no_now.SystemTime.TimeProvider;
import java.time.ZonedDateTime;
import static com.google.common.base.Preconditions.checkNotNull;
public class FixedTimeProvider implements TimeProvider {
private ZonedDateTime currentZonedDateTime;
public FixedTimeProvider(ZonedDateTime zonedDateTime) {
checkNotNull(zonedDateTime);
this.currentZonedDateTime = zonedDateTime;
}
@Override
public ZonedDateTime provideCurrentZoneDateTime() {
return currentZonedDateTime;
}
public void updateCurrentZoneDateTime(final ZonedDateTime newZonedDateTime) {
checkNotNull(newZonedDateTime);
this.currentZonedDateTime = newZonedDateTime;
}
}
| [
"[email protected]"
]
| |
b157b9114c2d1d84edb1ab79b732b48824e62afe | 582b3b233d9c979323aabed1749d83d7b9fa0228 | /OBS/src/java/com/myapp/struts/ListChqServ.java | d5b7f721718e2f1c12a9b1b1fcfd58ba95229750 | []
| no_license | PadminiNancy/Hiberuts | 227abd500c6732327d7db190056161f901c9c336 | db7991ccd548b0bfb936f1f290d4e95137da6d0d | refs/heads/master | 2020-04-13T00:02:42.708308 | 2018-12-22T19:23:18 | 2018-12-22T19:23:18 | 162,836,329 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,523 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.util.*;
import javax.servlet.http.HttpSession;
/**
*
* @author dell
*/
public class ListChqServ extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private String s = "success";
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session=request.getSession();
ArrayList al=new ChqModel().ChqReqDetails();
if(al.size()>0)
{
session.setAttribute("id","yes");
request.setAttribute("al",al);
s="success";
}else
{
s="failure";
}
return mapping.findForward(s);
}
}
| [
"[email protected]"
]
| |
6713d8752e1211b0ff85eaccf3228ce3cf37ce8c | 0c914e80941b083d2500c59ed134e99ecf999cf7 | /ontop-cli/src/test/java/org/semanticweb/ontop/cli/OntopBootstrapTest.java | 0b9988e68b91bab4630ebf2e6c32a9217753c1a6 | [
"Apache-2.0",
"CC-BY-4.0"
]
| permissive | mgskjaeveland/ontop | 441963c64b3f4c555fbeb2345ff2b2812b1012ec | 8b7e7c31b6b20d4291a9043e1125cb1d39447f27 | refs/heads/master | 2021-01-18T13:12:35.255588 | 2015-06-25T14:05:33 | 2015-06-25T14:07:00 | 37,968,316 | 1 | 0 | null | 2015-06-24T07:06:42 | 2015-06-24T07:06:42 | null | UTF-8 | Java | false | false | 651 | java | package org.semanticweb.ontop.cli;
import org.junit.Test;
public class OntopBootstrapTest {
@Test
public void testOntopHelp(){
Ontop.main("help", "bootstrap");
}
@Test
public void testOntopBootstrap (){
String[] argv = {"bootstrap",
"-b", "http://www.example.org/",
"-m", "/tmp/bootstrapped-univ-benchQL.obda",
"-t", "/tmp/bootstrapped-univ-benchQL.owl",
"-l", "jdbc:mysql://10.7.20.39/lubm1",
"-u", "fish",
"-p", "fish",
"-d", "com.mysql.jdbc.Driver"
};
Ontop.main(argv);
}
}
| [
"[email protected]"
]
| |
023b097d34d74204929b2d4150c1ca4d963197ec | 7263f2bc0067b6d373a1cb4d008a11810b650909 | /src/main/java/natan/io/projeto1/entity/User.java | dc9a5787a8115df414d12632ab1b9b610d9b2a8c | []
| no_license | river-estudo/projeto1 | 737662110025175ba93e96b605ed041bb982496a | 8b97d293b96dee68fa7f6a77345c5e59a1b26a3a | refs/heads/master | 2023-02-20T20:18:38.153959 | 2021-01-25T23:07:50 | 2021-01-25T23:07:50 | 331,132,569 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | package natan.io.projeto1.entity;
import java.util.Set;
import javax.persistence.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class User {
@Id
private String id;
private String email;
private String name;
private Set<Role> roles;
public User() {
}
public User(String name, String email) {
super();
this.email = email;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
]
| |
c2bc42222c6e15833a8bf1c419380fc4d6ef4e0b | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/JetBrains--intellij-community/638129650d71c9df8f8f0be1e15819cef21ea4ea/after/AddToFavoritesAction.java | 76d097298fd1831c36093e4c78776b0b6f3d43fd | []
| 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 | 11,976 | java | package com.intellij.ide.favoritesTreeView;
import com.intellij.ide.favoritesTreeView.smartPointerPsiNodes.ClassSmartPointerNode;
import com.intellij.ide.favoritesTreeView.smartPointerPsiNodes.FieldSmartPointerNode;
import com.intellij.ide.favoritesTreeView.smartPointerPsiNodes.MethodSmartPointerNode;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.AbstractProjectViewPane;
import com.intellij.ide.projectView.impl.ModuleGroup;
import com.intellij.ide.projectView.impl.PackageViewPane;
import com.intellij.ide.projectView.impl.nodes.*;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.lang.properties.ResourceBundle;
import com.intellij.lang.properties.projectView.ResourceBundleNode;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.DataConstantsEx;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* User: anna
* Date: Feb 15, 2005
*/
public class AddToFavoritesAction extends AnAction {
private static final Logger LOG = Logger.getInstance("com.intellij.ide.favoritesTreeView.AddToFavoritesAction");
private String myFavoritesListName;
public AddToFavoritesAction(String choosenList) {
super(choosenList);
myFavoritesListName = choosenList;
}
public void actionPerformed(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
Collection<AbstractTreeNode> nodesToAdd = getNodesToAdd(dataContext, true);
if (nodesToAdd != null && !nodesToAdd.isEmpty()) {
Project project = (Project)dataContext.getData(DataConstants.PROJECT);
FavoritesManager.getInstance(project).addRoots(myFavoritesListName, nodesToAdd);
}
}
public static Collection<AbstractTreeNode> getNodesToAdd(final DataContext dataContext, final boolean inProjectView) {
Project project = (Project)dataContext.getData(DataConstants.PROJECT);
if (project == null) return null;
Module moduleContext = (Module)dataContext.getData(DataConstants.MODULE_CONTEXT);
Collection<AbstractTreeNode> nodesToAdd = null;
FavoriteNodeProvider[] providers = ApplicationManager.getApplication().getComponents(FavoriteNodeProvider.class);
for(FavoriteNodeProvider provider: providers) {
nodesToAdd = provider.getFavoriteNodes(dataContext, ViewSettings.DEFAULT);
if (nodesToAdd != null) {
break;
}
}
if (nodesToAdd == null) {
Object elements = collectSelectedElements(dataContext);
if (elements != null) {
nodesToAdd = createNodes(project, moduleContext, elements, inProjectView, ViewSettings.DEFAULT);
}
}
return nodesToAdd;
}
public void update(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
Project project = (Project)dataContext.getData(DataConstants.PROJECT);
if (project == null) {
e.getPresentation().setEnabled(false);
}
else {
e.getPresentation().setEnabled(canCreateNodes(dataContext, e));
}
}
public static boolean canCreateNodes(final DataContext dataContext, final AnActionEvent e) {
final boolean inProjectView = e.getPlace().equals(ActionPlaces.J2EE_VIEW_POPUP) ||
e.getPlace().equals(ActionPlaces.STRUCTURE_VIEW_POPUP) ||
e.getPlace().equals(ActionPlaces.PROJECT_VIEW_POPUP);
return getNodesToAdd(dataContext, inProjectView) != null;
}
static Object retrieveData(Object object, Object data) {
return object == null ? data : object;
}
private static Object collectSelectedElements(final DataContext dataContext) {
Object elements = retrieveData(null, dataContext.getData(DataConstantsEx.RESOURCE_BUNDLE_ARRAY));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.PSI_ELEMENT_ARRAY));
elements = retrieveData(elements, dataContext.getData(DataConstants.PSI_ELEMENT));
elements = retrieveData(elements, dataContext.getData(DataConstants.PSI_FILE));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.VIRTUAL_FILE_ARRAY));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.VIRTUAL_FILE));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.MODULE_GROUP_ARRAY));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.MODULE_CONTEXT_ARRAY));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.MODULE));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.LIBRARY_GROUP_ARRAY));
elements = retrieveData(elements, dataContext.getData(DataConstantsEx.NAMED_LIBRARY_ARRAY));
return elements;
}
public static
@NotNull
Collection<AbstractTreeNode> createNodes(Project project, Module moduleContext, Object object, boolean inProjectView, ViewSettings favoritesConfig) {
ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
if (project == null) return Collections.emptyList();
final PsiManager psiManager = PsiManager.getInstance(project);
final String currentViewId = ProjectView.getInstance(project).getCurrentViewId();
AbstractProjectViewPane pane = ProjectView.getInstance(project).getProjectViewPaneById(currentViewId);
//on bundles nodes
if (object instanceof ResourceBundle[]) {
for (ResourceBundle bundle : (ResourceBundle[])object) {
result.add(new ResourceBundleNode(project, bundle, favoritesConfig));
}
return result;
}
//on psi elements
if (object instanceof PsiElement[]) {
for (PsiElement psiElement : (PsiElement[])object) {
addPsiElementNode(psiElement, project, result, favoritesConfig, moduleContext);
}
return result;
}
if (object instanceof PackageElement) {
PackageElementNode node = new PackageElementNode(project, object, favoritesConfig);
result.add(node);
return result;
}
//on psi element
if (object instanceof PsiElement) {
Module containingModule = null;
if (inProjectView && ProjectView.getInstance(project).isShowModules(currentViewId)) {
if (pane != null && pane.getSelectedDescriptor() != null && pane.getSelectedDescriptor().getElement() instanceof AbstractTreeNode) {
AbstractTreeNode abstractTreeNode = ((AbstractTreeNode)pane.getSelectedDescriptor().getElement());
while (abstractTreeNode != null && !(abstractTreeNode.getParent() instanceof AbstractModuleNode)) {
abstractTreeNode = abstractTreeNode.getParent();
}
if (abstractTreeNode != null) {
containingModule = ((AbstractModuleNode)abstractTreeNode.getParent()).getValue();
}
}
}
addPsiElementNode((PsiElement)object, project, result, favoritesConfig, containingModule);
return result;
}
if (object instanceof VirtualFile[]) {
for (VirtualFile vFile : (VirtualFile[])object) {
PsiElement element = psiManager.findFile(vFile);
if (element == null) element = psiManager.findDirectory(vFile);
addPsiElementNode(element,
project,
result,
favoritesConfig,
moduleContext);
}
return result;
}
//on form in editor
if (object instanceof VirtualFile) {
final VirtualFile vFile = (VirtualFile)object;
final PsiFile psiFile = psiManager.findFile(vFile);
addPsiElementNode(psiFile,
project,
result,
favoritesConfig,
moduleContext);
return result;
}
//on module groups
if (object instanceof ModuleGroup[]) {
boolean isPackageView = false;
if (currentViewId.equals(PackageViewPane.ID)) {
isPackageView = true;
}
for (ModuleGroup moduleGroup : (ModuleGroup[])object) {
if (isPackageView) {
result.add(new PackageViewModuleGroupNode(project, moduleGroup, favoritesConfig));
}
else {
result.add(new ProjectViewModuleGroupNode(project, moduleGroup, favoritesConfig));
}
}
return result;
}
//on module nodes
if (object instanceof Module) object = new Module[]{(Module)object};
if (object instanceof Module[]) {
for (Module module1 : (Module[])object) {
if (currentViewId.equals(PackageViewPane.ID)) {
result.add(new PackageViewModuleNode(project, module1, favoritesConfig));
}
else {
result.add(new ProjectViewModuleNode(project, module1, favoritesConfig));
}
}
return result;
}
//on library group node
if (object instanceof LibraryGroupElement[]) {
for (LibraryGroupElement libraryGroup : (LibraryGroupElement[])object) {
result.add(new LibraryGroupNode(project, libraryGroup, favoritesConfig));
}
return result;
}
//on named library node
if (object instanceof NamedLibraryElement[]) {
for (NamedLibraryElement namedLibrary : (NamedLibraryElement[])object) {
result.add(new NamedLibraryElementNode(project, namedLibrary, favoritesConfig));
}
return result;
}
return result;
}
private static void addPsiElementNode(PsiElement psiElement,
final Project project,
final ArrayList<AbstractTreeNode> result,
final ViewSettings favoritesConfig,
Module module) {
Class<? extends AbstractTreeNode> klass = getPsiElementNodeClass(psiElement);
if (klass == null) {
psiElement = PsiTreeUtil.getParentOfType(psiElement, PsiFile.class);
if (psiElement != null) {
klass = PsiFileNode.class;
}
}
final Object value = getPsiElementNodeValue(psiElement, project, module);
try {
if (klass != null && value != null) {
result.add(ProjectViewNode.createTreeNode(klass, project, value, favoritesConfig));
}
}
catch (Exception e) {
LOG.error(e);
}
}
private static Class<? extends AbstractTreeNode> getPsiElementNodeClass(PsiElement psiElement) {
Class<? extends AbstractTreeNode> klass = null;
if (psiElement instanceof PsiClass) {
klass = ClassSmartPointerNode.class;
}
else if (psiElement instanceof PsiMethod) {
klass = MethodSmartPointerNode.class;
}
else if (psiElement instanceof PsiField) {
klass = FieldSmartPointerNode.class;
}
else if (psiElement instanceof PsiFile) {
klass = PsiFileNode.class;
}
else if (psiElement instanceof PsiDirectory) {
klass = PsiDirectoryNode.class;
}
else if (psiElement instanceof PsiPackage) {
klass = PackageElementNode.class;
}
return klass;
}
private static Object getPsiElementNodeValue(PsiElement psiElement, Project project, Module module) {
if (psiElement instanceof PsiPackage) {
final PsiPackage psiPackage = (PsiPackage)psiElement;
final PsiDirectory[] directories = psiPackage.getDirectories();
if (directories.length > 0) {
final VirtualFile firstDir = directories[0].getVirtualFile();
final boolean isLibraryRoot = PackageUtil.isLibraryRoot(firstDir, project);
return new PackageElement(module, psiPackage, isLibraryRoot);
}
}
return psiElement;
}
} | [
"[email protected]"
]
| |
e5f586d226c5e4992c94caf3555cdb5a6bce297c | e2d90b159f6203d5fd7fdaae3887e06ce85cd438 | /app/src/main/java/com/example/pc/assignment3/Calculator.java | 4217ca325a7aa7b3bba10218159b7182a0b4f965 | []
| no_license | rkaydivergent/Assignment3 | 7854f466fa4db5c7fe24abaa75168ce11277725f | 919b33a59082144eef68d7f0eea4a1a0cb46ad29 | refs/heads/master | 2021-01-19T06:10:29.258153 | 2017-08-17T17:35:51 | 2017-08-17T17:35:51 | 100,627,856 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,319 | java | package com.example.pc.assignment3;
/**
* Created by pc on 8/17/2017.
*/
public class Calculator {
// Available operations
public enum Operator {ADD, SUB, DIV, MUL, POW}
/**
* Addition operation
*/
public double add(double firstOperand, double secondOperand) {
return firstOperand + secondOperand;
}
/**
* Subtract operation
*/
public double sub(double firstOperand, double secondOperand) {
return firstOperand - secondOperand;
}
/**
* Divide operation
*/
public double div(double firstOperand, double secondOperand) {
if (secondOperand == 0 ) {
throw new IllegalArgumentException("You cannot divide by zero");
}
return firstOperand / secondOperand;
}
/**
* Multiply operation
*/
public double mul(double firstOperand, double secondOperand) {
return firstOperand * secondOperand;
}
/**
* Power operation
*/
public double pow (double firstOperand, double secondOperand) {
if(firstOperand ==0 && secondOperand<0){throw new ArithmeticException ("Infinite Value");}
if(firstOperand ==-0 && secondOperand<0){throw new ArithmeticException ("Infinite Value");}
return Math.pow(firstOperand, secondOperand);
}
}
| [
"[email protected]"
]
| |
076717c24ae629078989cd0bb80d2c728c3dd036 | 81784e2752a7ec2de8ed5ee8da3a716bb385d855 | /app/src/main/java/com/example/david/matibabu/account/signup/SignupContract.java | 92c9f93cbbf6511e907e00f838bec61bfe8a2cef | []
| no_license | davidkathoh/Matibabu | 0908a5df3e3e6af7f1b9af7a82dbfd1be87b7ebc | 2d6f5570c19552607c1ec6eca64b5f18270e72aa | refs/heads/master | 2020-04-28T00:10:11.739880 | 2018-06-28T07:49:30 | 2018-06-28T07:49:30 | 174,805,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 922 | java | package com.example.david.matibabu.account.signup;
import android.widget.Spinner;
import com.example.david.matibabu.utils.BasePresenter;
import com.example.david.matibabu.utils.BaseView;
/**
* Created by david on 12/5/17.
*/
public interface SignupContract {
interface View extends BaseView<Presenter>{
void showLoadingIndicator();
void showErrorMessage();
void openActivity();
void saveHospitalInfo();
}
interface Presenter extends BasePresenter{
void registerHospital(String province,
String zoneSante,
String aireDeSante,
String arreteMinisteriel,
String nomHopital,
String addressHopital,
String nomResponsable,
String telephoneResposable);
}
}
| [
"[email protected]"
]
| |
f082d88bc6d62cd5e1ea33cabdb548ac8de30df1 | 83da0df22cbbeb36ffad7c55a995cc19b60ce9c1 | /auth/src/app1/java/com/dryganets/auth/AuthenticatorProvider.java | 503a3d576f72f29bdfd28d6ca91c31a225d0f534 | [
"MIT"
]
| permissive | dryganets/gradle-multi-app | a237057901af0588999ca4e3f64983621d4c0a62 | b5919f343db0902565a906df216f0c75fe51ed51 | refs/heads/master | 2020-04-18T10:20:48.482152 | 2019-01-25T04:52:29 | 2019-01-25T18:56:43 | 167,465,051 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 228 | java | package com.dryganets.auth;
import javax.inject.Provider;
public class AuthenticatorProvider implements Provider<Authenticator> {
@Override
public Authenticator get() {
return new App1Authenticator();
}
}
| [
"[email protected]"
]
| |
7164edd3b5c1933bf82d696f717506df82c38462 | 64c7960e0b7cffddf262d77a12b21c12d2105464 | /src/main/java/com/rightandabove/utils/validators/FileValidator.java | 64179f5795591b1986a3e93953f4ed659ebe504b | []
| no_license | zosyk/raa_parse_xml_doc | 9001c75a54442bc6efc1296fb4e3966090c88b18 | b257dc2cd19e89306d9109c4389fb0607ce7eaac | refs/heads/master | 2020-05-24T00:40:11.773026 | 2017-03-13T09:18:29 | 2017-03-13T09:18:29 | 84,806,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 678 | java | package com.rightandabove.utils.validators;
import com.rightandabove.models.UploadedFile;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* Created by alex on 28.02.17.
*/
@Component
public class FileValidator implements Validator {
public boolean supports(Class<?> clazz) {
return false;
}
public void validate(Object target, Errors errors) {
UploadedFile file = (UploadedFile) target;
if(file.getFile().getSize() == 0) {
errors.rejectValue("file", "uploadForm.selectFile", "Please select a file!");
}
}
}
| [
"[email protected]"
]
| |
89b83350cc6e4eecd470c7bf466ba6e883820246 | ddad00e17acbca9498c8bc91b0d02f88012d31f5 | /src/main/java/com/homethy/util/ReturnJacksonUtil.java | 3d9ca040f35380363af23c7e401a2969105bf2c4 | []
| no_license | yuchaozhou/web-DB-tools | 7119125009f4345971e68649986f3907cb3d1a55 | d532701509fd56d5490a039f32a7172e0b14080d | refs/heads/master | 2020-11-30T11:58:52.301086 | 2019-10-16T15:26:25 | 2019-10-16T15:26:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,833 | java | /**
* Copyright ©2016Renren. All rights reserved.
*/
package com.homethy.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.homethy.constant.Constant;
import com.homethy.constant.WebCodeEnum;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* @ClassName: ReturnJacksonUtil
* @Description: 定制Controller返回值工具类
*/
public class ReturnJacksonUtil {
/**
* 返回不带数据的成功的串
*/
public static String resultOk(Locale locale) throws JsonProcessingException {
WebCodeEnum webCodeEnum = WebCodeEnum.OK;
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), null, null);
}
public static String resultOk() throws JsonProcessingException {
WebCodeEnum webCodeEnum = WebCodeEnum.OK;
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(Locale.ENGLISH), null, null);
}
public static String resultFail() throws JsonProcessingException {
WebCodeEnum webCodeEnum = WebCodeEnum.QUERY_SQL_FAIL;
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(Locale.ENGLISH), null, null);
}
/**
* 返回特定成功文案
*/
public static String resultOkWithEnum(WebCodeEnum webCodeEnum, Locale locale) throws
JsonProcessingException {
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), null, null);
}
/**
* 返回成功的数据
*/
public static String resultOk(Object data, Locale locale) throws JsonProcessingException {
WebCodeEnum webCodeEnum = WebCodeEnum.OK;
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), data, null);
}
public static String resultOk(Object data) {
WebCodeEnum webCodeEnum = WebCodeEnum.OK;
try{
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(Locale.ENGLISH), data, null);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
public static String resultFail(Object data) {
WebCodeEnum webCodeEnum = WebCodeEnum.QUERY_SQL_ERROR;
try{
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(Locale.ENGLISH), data, null);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 成功时,在data中返回key value对
*/
public static String resultOk(String key, Object value, Locale locale) throws
JsonProcessingException {
Map<String, Object> data = new HashMap<String, Object>();
data.put(key, value);
WebCodeEnum webCodeEnum = WebCodeEnum.OK;
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), data, null);
}
/**
* 成功时,在data中返回key value对
*/
public static String resultFail(String key, Object value, Locale locale) {
Map<String, Object> data = new HashMap<String, Object>();
data.put(key, value);
WebCodeEnum webCodeEnum = WebCodeEnum.QUERY_SQL_ERROR;
try{
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), data, null);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 返回成功的数据,并指定相应的类型应该排除的字段
*
* @param data 返回的数据
* @param clazz 指定的类型
* @param excludeFileds 需要排除的字段
*/
@SuppressWarnings("rawtypes")
public static String resultOkWithExclude(Object data, Class clazz, Locale locale, String...
excludeFileds) throws JsonProcessingException {
Map<Class, Set<String>> exclude = new HashMap<Class, Set<String>>();
exclude.put(clazz, new HashSet<String>(Arrays.asList(excludeFileds)));
WebCodeEnum webCodeEnum = WebCodeEnum.OK;
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), data, null, exclude);
}
/**
* 返回表示操作成功的数据,并指定相应类型及其需要包含的输出字段
*
* @param data 返回的数据
* @param clazz 指定类型
* @param includeFileds 指定类型需要包含的字段
*/
@SuppressWarnings("rawtypes")
public static String resultOkWithInclude(Object data, Class clazz, Locale locale, String...
includeFileds) throws JsonProcessingException {
Map<Class, Set<String>> include = new HashMap<Class, Set<String>>();
include.put(clazz, new HashSet<String>(Arrays.asList(includeFileds)));
WebCodeEnum webCodeEnum = WebCodeEnum.OK;
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), data, include, null);
}
/**
* 返回带错误码的数据
*/
public static String resultWithFailed(WebCodeEnum webCodeEnum, Locale locale) throws
JsonProcessingException {
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(locale), null, null);
}
public static String resultWithFailed(WebCodeEnum webCodeEnum) throws JsonProcessingException {
return result(webCodeEnum.getErrorCode(), webCodeEnum.getErrorMsg(Locale.ENGLISH), null, null);
}
public static String returnResult(int code, String msg, Object object) throws
JsonProcessingException {
Map<String, Object> map = new HashMap<>();
map.put("msg", msg);
map.put(Constant.RESULT_CODE, code);
map.put("object", object);
return JacksonUtils.map2Json(map);
}
/**
* 根据提供的view对data中的对象中的字段进行定制输出
*/
public static <T> String result(int resultCode, String resultMsg, Object data, Class<T>
jsonViewClazz) throws JsonProcessingException {
Map<String, Object> status = new HashMap<String, Object>();
status.put(Constant.RESULT_CODE, resultCode);
status.put(Constant.RESULT_MSG, String.valueOf(resultMsg));
Map<String, Object> result = new HashMap<String, Object>();
result.put(Constant.RESULT_STATUS, status);
if (null != data) {
result.put(Constant.RESULT_DATA, data);
}
if (null == jsonViewClazz) {
return JacksonUtils.toJson(result);
} else {
return JacksonUtils.toJson(result, jsonViewClazz);
}
}
/**
* 返回表示成功与否的resultCode, resultMsg的数据,并指定多个类型及其包含的需要包含的字段、多个类型及其需要包含的字段
*
* @param resultCode 成功与否的代码
* @param resultMsg 成功与否的输出信息
* @param data 返回数据
* @param include 多个类型及其需要包含的输出字段
* @param exclude 多个类型及其对应的需要排除的字段
*/
@SuppressWarnings("rawtypes")
public static String result(int resultCode, String resultMsg, Object data, Map<Class,
Set<String>> include, Map<Class, Set<String>> exclude) throws JsonProcessingException {
Map<String, Object> status = new HashMap<String, Object>();
status.put(Constant.RESULT_CODE, resultCode);
status.put(Constant.RESULT_MSG, String.valueOf(resultMsg));
Map<String, Object> result = new HashMap<String, Object>();
result.put(Constant.RESULT_STATUS, status);
if (null != data) {
result.put(Constant.RESULT_DATA, data);
}
return JacksonUtils.toJson(result, include, exclude);
}
/**
* 返回封装后的json
*/
public static String resultWithException(int resultCode, String resultMsg, String data) throws
JsonProcessingException {
Map<String, Object> status = new HashMap<String, Object>();
status.put(Constant.RESULT_CODE, resultCode);
status.put(Constant.RESULT_MSG, String.valueOf(resultMsg));
Map<String, Object> result = new HashMap<String, Object>();
result.put(Constant.RESULT_STATUS, status);
if (null != data) {
result.put(Constant.RESULT_DATA, data);
}
return JacksonUtils.toJson(result);
}
}
| [
"[email protected]"
]
| |
916d1f3108da9576dd3d2790e029c060c7e36d30 | 5509da5a7aec9fc8e6b5be269e8d8e50197bb76f | /app/src/androidTest/java/com/example/akbaresa/prd/ExampleInstrumentedTest.java | 6e068fa689c34c4efc3f884ce63e85703689de04 | []
| no_license | dewanggaesa/tugas-PRD-akbaresa | b68eff50d4aa2c59dbd8c91c5d3fb6060a76a546 | c37818992432dc86ead2394ebaa80c2a1d85b301 | refs/heads/master | 2020-06-15T08:36:45.332024 | 2016-12-01T16:00:54 | 2016-12-01T16:00:54 | 75,308,511 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 752 | java | package com.example.akbaresa.prd;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.akbaresa.prd", appContext.getPackageName());
}
}
| [
"[email protected]"
]
| |
5f6feaa218670546f27cdb010f75801ff9c47772 | 1f0fdec241a5f6688177fcd2caeafec01317fb3c | /src/main/com/intro/PrimeFactors.java | 9b898cf120b76639e43d5c3708a835f0c38d803d | []
| no_license | Lnfra/IntroProgramingExercises | c2fd602de35b28805f838d1ed83274b2b1f41016 | b49d1160c4d0355c5ab14fa4bd66df12baacc273 | refs/heads/master | 2021-01-12T10:24:56.964303 | 2016-12-23T06:51:58 | 2016-12-23T06:51:58 | 76,450,958 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,349 | java | package com.intro;
/*
Prime Factors Exercise
Write a method generate(int n) that given an integer N will return a list
of integers such that the numbers are the factors of N and are arranged in
increasing numerical order.
For example, generate(1) should return an empty list and generate(30) should return the numbers: 2,3,5.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PrimeFactors {
/*
* Prime factorization or integer factorization of a number is finding out
* the set of prime numbers which multiply together to give the original integer.
*
* A prime number is a whole number greater than 1,
* which can only be exactly divided by 1 and itself.
*/
public List<Integer> generate(int inputNum ) {
int n = inputNum;
List<Integer> factorsFound = new ArrayList<>();
//from 2 till n
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
//if any num can divide the input exactly it is a factor. Add it to list.
factorsFound.add(i);
//divide the input by that factor, and find the next factor
n = n / i;
}
} //end for loop
Collections.sort( factorsFound );
//returns the list of all factors which when multiplied together will get the original integer.
return factorsFound;
}
}
| [
"[email protected]"
]
| |
bd1637b96593eb6d763bc9fb75a65f20f1090b6d | 2c8ee36768f51fce4a673e3aaf6328d14780d511 | /src/main/java/smb/ZjQp.java | f53bab82e3b24622ed3138186852fdbe3e3002c7 | []
| no_license | jonasJiang/qp | 3d4771e7280127c9fe2a0e067bcfd7b0e9155da9 | 9d9e343e0228258cf116a15f3f549304839e43db | refs/heads/master | 2020-05-31T15:56:21.991455 | 2017-06-25T23:01:40 | 2017-06-25T23:01:40 | 94,037,859 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 340 | java | package smb;
public class ZjQp extends AbstractQP {
@Override
protected void login() {
// TODO Auto-generated method stub
}
@Override
protected void getIndex() {
// TODO Auto-generated method stub
}
@Override
protected void doqp() {
// TODO Auto-generated method stub
}
}
| [
"[email protected]"
]
| |
02bbce0d89dc7fc0b7415fa178cfd57ba2672f61 | 4f8d3aa45d465dc3443c814e7a25e028b6082446 | /src/main/java/com/amstech/demo/convertor/RestBranchViewToEntityConvertor.java | 1520738f128b37d5f1a4d5f298f104ffee8dc430 | []
| no_license | anshulsharma31/Spring-Hibernate-JPA | e8ad9d218a3534c7dfb0461750156b2667ff5e90 | 96e9bd5d99ec881ca0a5ba82a4a114bf707ee8ab | refs/heads/master | 2021-05-04T16:59:11.035314 | 2018-02-05T06:10:02 | 2018-02-05T06:10:02 | 120,262,237 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,318 | java | /*
* Copyright 2017 AMSTECH INCORPORATION PRIVATE LIMITED.
* (www.amstechinc.com)
* 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.amstech.demo.convertor;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.spi.MappingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.amstech.demo.entity.RestBranch;
import com.amstech.demo.entity.Restaurant;
import com.amstech.demo.service.RestaurantService;
import com.amstech.demo.view.RestBranchView;
@Component
public class RestBranchViewToEntityConvertor implements Converter<RestBranchView, RestBranch>
{
private static final Logger logger = LoggerFactory.getLogger(RestBranchViewToEntityConvertor.class);
@Autowired
private RestaurantService restaurantService;
@Autowired
@Qualifier("modelMapper")
private ModelMapper modelMapper;
@Override
public RestBranch convert(MappingContext<RestBranchView, RestBranch> context) {
RestBranch destination = null;
try {
RestBranchView source = context.getSource();
logger.info("source - RestBranchView's : branch-id={}, branch-address={} ", source.getId(),
source.getAddress());
logger.info("Fetching entity for Restaurant-id:{}", source.getRestaurantId());
Restaurant restaurant = restaurantService.findOne(source.getRestaurantId());
logger.info("Fetched entity restaurant-id={}", restaurant.getId());
destination = modelMapper.map(source, RestBranch.class);
destination.setRestaurant(restaurant);
} catch (Exception e) {
logger.error("failed to convert RestBranchViewToEntity due to :{}", e, e);
}
return destination;
}
}
| [
"[email protected]"
]
| |
26390e003c047fe5e08f2497aa27c8cf9ff5618a | 9f487cd2647e6865113dc3f407d4c61ac2751517 | /Brent/app/utilities/UrlSniffer.java | 94dadbb10579dfae89d4a18bd2beb46a564c58a6 | [
"Apache-2.0"
]
| permissive | Indigenuity/Brent | 605c394cfdec8e8f0760334e402756b34072f0b9 | 373dedb9ebea71aa6782bcc20991bf2c931b5f88 | refs/heads/master | 2021-01-10T17:51:39.006004 | 2015-12-09T21:20:51 | 2015-12-09T21:20:51 | 47,719,179 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,066 | java | package utilities;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlSniffer {
private static final int DEFAULT_REDIRECT_RECURSION_LEVEL = 10;
private static final String DEFAULT_USER_AGENT_STRING = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
//Visits a url and returns the
public static String getRedirectedUrl(String urlString) throws MalformedURLException, IOException{
return getFinalUrl(urlString, DEFAULT_REDIRECT_RECURSION_LEVEL);
}
public static String getFinalUrl(String urlString, int numRecursions) throws IOException {
System.out.println("Checking redirected url of : " + urlString);
URL url = new URL(urlString);
String domain = url.getHost();
HttpURLConnection con = (HttpURLConnection)(url.openConnection());
con.setInstanceFollowRedirects(false);
con.setConnectTimeout(15 * 1000);
con.setRequestProperty("User-Agent", DEFAULT_USER_AGENT_STRING);
con.connect();
int responseCode = con.getResponseCode();
if(responseCode >= 300 && responseCode < 400) {
System.out.println("*********redirected to url (" + responseCode + "): " + con.getHeaderField("Location"));
String location = con.getHeaderField("Location");
String redirectUrl;
if(location.startsWith("/")){
redirectUrl = url.getProtocol() + "://" + url.getHost() + location;
}
else {
redirectUrl = location;
}
if(numRecursions < 1)
throw new IOException("Number of redirects has exceeded the limit for url : " + urlString);
return getFinalUrl(redirectUrl, --numRecursions);
}
else if(responseCode != 200) {
throw new IllegalStateException("Unexpected response code : " + responseCode);
}
System.out.println("no redirect, returning this string : " + con.getURL().toString());
return con.getURL().toString().replace(":80", "");
}
public static boolean isGenericRedirect(String redirectUrl, String original) {
if(redirectUrl == null || original == null)
return false;
if(redirectUrl.equals(original))
return true;
String sansRedirectUrl = DSFormatter.removeWww(redirectUrl);
String sansOriginal = DSFormatter.removeWww(original);
if(sansRedirectUrl.equals(sansOriginal))
return true;
String comRedirectUrl = DSFormatter.toCom(sansRedirectUrl);
String comOriginal = DSFormatter.toCom(sansOriginal);
if(comRedirectUrl.equals(comOriginal))
return true;
String langRedirectUrl = DSFormatter.removeLanguage(comRedirectUrl);
String langOriginal = DSFormatter.removeLanguage(comOriginal);
if(langRedirectUrl.equals(langOriginal))
return true;
try {
URL validRedirectUrl = new URL(comRedirectUrl);
URL validOriginal = new URL(comOriginal);
String hostRedirectUrl = validRedirectUrl.getHost();
String hostOriginal = validOriginal.getHost();
if(hostRedirectUrl.equals(hostOriginal))
return true;
} catch (MalformedURLException e) {
return false;
}
return false;
}
}
| [
"[email protected]"
]
| |
4ec7cb52d2a4acebade5c2bd8eca1c3fbc11758d | 61993b3e3efa3fa3c01107fa03f4e5245edf1c8d | /Project200225/src/service/MemberViewService.java | d718ebde6e059d9a1dd32dc4ffbaab3e24a91854 | []
| no_license | lhw9387/Individual_Project | ca48f298ec54a4e24eff4839505b2b0ebb089fd5 | 037a7a4b02fe7827cac2118e608f5d9191630c14 | refs/heads/master | 2022-04-28T16:42:35.330724 | 2020-05-06T01:46:25 | 2020-05-06T01:46:25 | 261,624,324 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package service;
import static db.JdbcUtil.*;
import java.sql.Connection;
import dao.DAO;
import dto.MemberDTO;
public class MemberViewService {
public MemberDTO memberView(String id) {
DAO dao = DAO.getInstance();
Connection con = getConnection();
dao.setConnection(con);
MemberDTO member = dao.memberView(id);
close(con);
return member;
}
}
| [
"2@2-PC"
]
| 2@2-PC |
4d6c20c99c4a3324e78c34021039da13413d96db | da1f09e97a12578efa865591f87efaee0fa7ff2e | /app/src/main/java/com/company/securebike/NewTaskAct.java | 988af920c9095cb0355a60e14f574529e23ba96a | []
| no_license | estebancasas9817/SecureBike | 06d6800329608ca6d08e3fbbb40efa61c0f5f8d1 | 151d0a8f1cdc3c35a13d259370b33f1150487da3 | refs/heads/master | 2023-05-06T19:17:22.864945 | 2021-05-31T22:13:52 | 2021-05-31T22:13:52 | 337,149,019 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,050 | java | package com.company.securebike;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.company.securebike.auxiliares.MyDoes;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Random;
public class NewTaskAct extends AppCompatActivity {
TextView titlepage, addtitle, adddesc, adddate;
EditText titledoes, descdoes, datedoes,rasgosDoes,nombreDoes;
Button btnSaveTask, btnCancel;
DatabaseReference reference;
Integer doesNum = new Random().nextInt();
String keydoes = Integer.toString(doesNum);
String usuario;
// Button btnImg;
private Uri imagenUri;
final int IMAGE_PICK_CODE = 1000;
final int PERMISSION_CODE = 1001;
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
ImageView imagen;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
titlepage = findViewById(R.id.titlepage);
addtitle = findViewById(R.id.addtitle);
adddesc = findViewById(R.id.adddesc);
adddate = findViewById(R.id.adddate);
rasgosDoes = findViewById(R.id.rasgosDoes);
nombreDoes = findViewById(R.id.nombreDoes);
imagen = findViewById(R.id.addFoto);
// btnImg = findViewById(R.id.btnImg);
titledoes = findViewById(R.id.titledoes);
descdoes = findViewById(R.id.descdoes);
datedoes = findViewById(R.id.datedoes);
// progressBar.setVisibility(View.INVISIBLE);
btnSaveTask = findViewById(R.id.btnSaveTask);
btnCancel = findViewById(R.id.btnCancel);
Intent intent = getIntent();
usuario = intent.getStringExtra("usuario");
imagen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
String [] permiso = {Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permiso,1001);
}
else{
escogerImagenGaleria();
}
}
else {
escogerImagenGaleria();
}
}
});
btnSaveTask.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// insert data to database
reference = FirebaseDatabase.getInstance().getReference().child("DoesApp").child(usuario);
String titulo = titledoes.getText().toString();
String descrip = descdoes.getText().toString();
String fechas = datedoes.getText().toString();
String key = keydoes;
String username = usuario;
String nombre = nombreDoes.getText().toString();
String rasgos = rasgosDoes.getText().toString();
if(imagenUri != null) {
AgregarFirebase(titulo,descrip,fechas,key,username,nombre,rasgos,imagenUri);
}else{
Toast.makeText(NewTaskAct.this,"Porfa Selecciona una imagen...",Toast.LENGTH_LONG).show();
}
// MyDoes myDoesAux = new MyDoes(titulo,descrip,fechas,key,username,nombre,rasgos);
// reference.child("Does" + doesNum).setValue(myDoesAux);
// Intent ir = new Intent(NewTaskAct.this,AgregarBicicleta.class);
// ir.putExtra("usuario",usuario);
// Toast.makeText(NewTaskAct.this,"Creado con exito....",Toast.LENGTH_SHORT).show();
// startActivity(ir);
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent devolver = new Intent(NewTaskAct.this,AgregarBicicleta.class);
devolver.putExtra("usuario",usuario);
startActivity(devolver);
}
});
}
private void AgregarFirebase(final String titulo, final String descrip, final String fechas, final String key, final String username, final String nombre, final String rasgos, Uri uri){
final StorageReference archivo = storageReference.child(username).child("Does"+ doesNum);
// MyDoes myDoesAux = new MyDoes(titulo,descrip,fechas,key,username,nombre,rasgos,uri.toString());
//
// reference.child("Does" + doesNum).setValue(myDoesAux);
// progressBar.setVisibility(View.INVISIBLE);
// Toast.makeText(NewTaskAct.this,"Añadido satisfactoriamente....",Toast.LENGTH_LONG).show();
archivo.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(NewTaskAct.this,"ENTRAAAA",Toast.LENGTH_LONG).show();
archivo.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
MyDoes myDoesAux = new MyDoes(titulo,descrip,fechas,key,username,nombre,rasgos,uri.toString());
reference.child("Does" + doesNum).setValue(myDoesAux);
// progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(NewTaskAct.this,"Añadido satisfactoriamente....",Toast.LENGTH_LONG).show();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
// progressBar.setVisibility(View.VISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(NewTaskAct.this,"Error....",Toast.LENGTH_LONG).show();
}
});
}
private String getFileExt(Uri uri) {
ContentResolver cr = getContentResolver();
MimeTypeMap mine = MimeTypeMap.getSingleton();
return mine.getExtensionFromMimeType(cr.getType(uri));
}
private void escogerImagenGaleria() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,1000);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 1001:{
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
escogerImagenGaleria();
}
else{
Toast.makeText(NewTaskAct.this,"Permiso denegado....",Toast.LENGTH_LONG).show();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 1000) {
imagenUri = data.getData();
imagen.setImageURI(imagenUri);
}
else if(requestCode == 1 && resultCode == RESULT_OK && data !=null){
Bundle bundle = data.getExtras();
Bitmap foto = (Bitmap) bundle.get("data");
imagen.setImageBitmap(foto);
}
}
} | [
"[email protected]"
]
| |
b99e1b208e5c72a75d5d8c9c9c60b49c5dd80067 | b28907c706f6bb44db79ef7c528c1c5f2a6f9dfb | /src/main/java/com/controllers/Cart.java | 6ef8e1ff835f8b416d8c8ab6eb63b200b0c47fbc | []
| no_license | gorlesaikumar/spring_project | fa573a97b2fc649e472e85739a42cefb44d3034e | c3d3b4740f6343161079e07e4e945640aa9f9a67 | refs/heads/master | 2023-03-21T20:10:40.076880 | 2021-03-02T05:38:13 | 2021-03-02T05:38:13 | 343,415,360 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,773 | java | package com.controllers;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class Cart {
@RequestMapping("/cart")
public ModelAndView cartsession(HttpServletRequest request , HttpServletResponse response) throws IOException, SQLException
{
UserConnection uc = new UserConnection();
Session session = uc.register();
HttpSession httpSession = request.getSession();
ModelAndView model = new ModelAndView();
if(httpSession.getAttribute("valid")!=null)
{
CartData cd = new CartData();
String str= request.getParameter("items");
org.hibernate.query.Query<Products> query = session.createQuery("from Products where id = '"+str+"'");
List<Products> cart=query.list();
cd.setId(cart.get(0).getId());
cd.setName(cart.get(0).getName());
cd.setPrice(cart.get(0).getPrice());
cd.setPassword((String) httpSession.getAttribute("valid"));
Transaction txt=session.beginTransaction();
session.save(cd);
txt.commit();
model.setViewName("Homepage.jsp");
}
else {
model.setViewName("loginform.jsp");
}
return model;
// cart addition
}
}
| [
"[email protected]"
]
| |
9a1636a7f621fbc2ade33b5672db51231f722e06 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/5/5_bfd376d8fe911bebae904862d3ec50feadbc3df4/UserColumnFactory/5_bfd376d8fe911bebae904862d3ec50feadbc3df4_UserColumnFactory_s.java | 73facbb47991a64f4d6b56e86aaa7de7db6ad1ef | []
| 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 | 30,767 | java | package de.hattrickorganizer.gui.model;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.table.TableColumn;
import plugins.IEPVData;
import plugins.IMatchKurzInfo;
import plugins.ISpieler;
import plugins.ISpielerPosition;
import de.hattrickorganizer.gui.playeroverview.SpielerStatusLabelEntry;
import de.hattrickorganizer.gui.templates.ColorLabelEntry;
import de.hattrickorganizer.gui.templates.DoppelLabelEntry;
import de.hattrickorganizer.gui.templates.RatingTableEntry;
import de.hattrickorganizer.gui.templates.SpielerLabelEntry;
import de.hattrickorganizer.gui.templates.TableEntry;
import de.hattrickorganizer.model.HOModel;
import de.hattrickorganizer.model.HOVerwaltung;
import de.hattrickorganizer.model.Spieler;
import de.hattrickorganizer.model.SpielerPosition;
import de.hattrickorganizer.model.matches.MatchKurzInfo;
import de.hattrickorganizer.model.matches.Matchdetails;
import de.hattrickorganizer.tools.Helper;
import de.hattrickorganizer.tools.HelperWrapper;
import de.hattrickorganizer.tools.PlayerHelper;
/**
* Create the userColumns
* @author Thorsten Dietz
*
*/
final public class UserColumnFactory {
//~ Static fields/initializers -----------------------------------------------------------------
/** id from the column NAME **/
public static final int NAME = 1;
/** id from the column BEST_POSITION **/
public static final int BEST_POSITION = 40;
/** id from the column LINUP **/
public static final int LINUP = 50;
/** id from the column GROUP **/
public static final int GROUP = 60;
/** id from the column ID **/
public static final int ID = 440;
/** id from the column DATUM **/
public static final int DATUM = 450;
/** id from the column RATING **/
public static final int RATING = 435;
/** id from the column DATUM **/
public static final int AUTO_LINEUP = 510;
/**
*
* @return PlayerCBItem[]
*/
protected static PlayerCBItem[] createPlayerCBItemArray(){
final PlayerCBItem[] playerCBItemArray = new PlayerCBItem[4];
playerCBItemArray[0] = new PlayerCBItem(590,"Stimmung"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new ColorLabelEntry(spielerCBItem.getStimmung(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
playerCBItemArray[1] = new PlayerCBItem(600,"Selbstvertrauen"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new ColorLabelEntry(spielerCBItem.getSelbstvertrauen(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
playerCBItemArray[2] = new PlayerCBItem(601,"Position"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
ColorLabelEntry colorLabelEntry = new ColorLabelEntry(Helper
.getImage4Position(SpielerPosition
.getHTPosidForHOPosition4Image((byte) spielerCBItem
.getPosition()),
(byte) 0, 0),
-SpielerPosition.getSortId((byte) spielerCBItem
.getPosition(), false),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
colorLabelEntry.setText(SpielerPosition.getNameForPosition((byte) spielerCBItem
.getPosition())
+ " ("
+ spielerCBItem.getSpieler().calcPosValue((byte) spielerCBItem
.getPosition(),
true) + ")");
return colorLabelEntry;
}
};
playerCBItemArray[3] = new PlayerCBItem(RATING,"Bewertung"){
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new RatingTableEntry(spielerCBItem.getRating(), false);
}
};
return playerCBItemArray;
}
/**
*
* @return MatchDetailsColumn[]
*/
protected static MatchDetailsColumn[] createMatchDetailsColumnsArray(){
final MatchDetailsColumn[] matchDetailsColumnsArray = new MatchDetailsColumn[4];
matchDetailsColumnsArray[0] = new MatchDetailsColumn(550,"Wetter",30){
public TableEntry getTableEntry(Matchdetails matchdetails){
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImageIcon4Wetter(matchdetails.getWetterId()),
matchdetails.getWetterId(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.RIGHT);
}
};// Wetter
matchDetailsColumnsArray[1] = new MatchDetailsColumn(560,"Einstellung"){
public TableEntry getTableEntry(Matchdetails matchdetails){
final int teamid = HOVerwaltung.instance().getModel()
.getBasics().getTeamId();
int einstellung = (matchdetails.getHeimId() == teamid)?matchdetails.getHomeEinstellung():matchdetails.getGuestEinstellung();
return new ColorLabelEntry(Matchdetails.getNameForEinstellung(einstellung), ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
matchDetailsColumnsArray[2] = new MatchDetailsColumn(570,"Taktik"){
public TableEntry getTableEntry(Matchdetails matchdetails){
final int teamid = HOVerwaltung.instance().getModel()
.getBasics().getTeamId();
int tactic = (matchdetails.getHeimId() == teamid)?matchdetails.getHomeTacticType():matchdetails.getGuestTacticType();
return new ColorLabelEntry(Matchdetails.getNameForTaktik(tactic), ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
matchDetailsColumnsArray[3] = new MatchDetailsColumn(580,"Taktikstaerke"){
public TableEntry getTableEntry(Matchdetails matchdetails){
final int teamid = HOVerwaltung.instance().getModel()
.getBasics().getTeamId();
int tacticSkill = (matchdetails.getHeimId() == teamid)?matchdetails.getHomeTacticSkill():matchdetails.getGuestTacticSkill();
return new ColorLabelEntry(PlayerHelper.getNameForSkill(tacticSkill), ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
}
};
return matchDetailsColumnsArray;
}
/**
*
* @return PlayerColumn[]
*/
protected static PlayerColumn[] createGoalsColumnsArray(){
final PlayerColumn[] playerGoalsArray = new PlayerColumn[4];
playerGoalsArray[0] = new PlayerColumn(380,"TG","ToreGesamt",20){
public int getValue(Spieler player){
return player.getToreGesamt();
}
};
playerGoalsArray[1] = new PlayerColumn(390,"TF","ToreFreund",20){
public int getValue(Spieler player){
return player.getToreFreund();
}
};
playerGoalsArray[2] = new PlayerColumn(400,"TL","ToreLiga",20){
public int getValue(Spieler player){
return player.getToreLiga();
}
};
playerGoalsArray[3] = new PlayerColumn(410,"TP","TorePokal",20){
public int getValue(Spieler player){
return player.getTorePokal();
}
};
return playerGoalsArray;
}
/**
*
* @return PlayerSkillColumn []
*/
protected static PlayerSkillColumn[] createPlayerSkillArray(){
final PlayerSkillColumn[] playerSkillArray = new PlayerSkillColumn[11];
playerSkillArray[0] = new PlayerSkillColumn( 80, "FUE", "Fuehrung", ISpieler.SKILL_LEADERSHIP);
playerSkillArray[1] = new PlayerSkillColumn( 90, "ER", "Erfahrung", ISpieler.SKILL_EXPIERIENCE);
playerSkillArray[2] = new PlayerSkillColumn( 100, "FO", "Form", ISpieler.SKILL_FORM);
playerSkillArray[3] = new PlayerSkillColumn( 110, "KO", "Kondition", ISpieler.SKILL_KONDITION);
playerSkillArray[4] = new PlayerSkillColumn( 120, "TW", "Torwart", ISpieler.SKILL_TORWART);
playerSkillArray[5] = new PlayerSkillColumn( 130, "VE", "Verteidigung", ISpieler.SKILL_VERTEIDIGUNG);
playerSkillArray[6] = new PlayerSkillColumn( 140, "SA", "Spielaufbau", ISpieler.SKILL_SPIELAUFBAU);
playerSkillArray[7] = new PlayerSkillColumn( 150, "PS", "Passpiel", ISpieler.SKILL_PASSSPIEL);
playerSkillArray[8] = new PlayerSkillColumn( 160, "FL", "Fluegelspiel", ISpieler.SKILL_FLUEGEL);
playerSkillArray[9] = new PlayerSkillColumn( 170, "TS", "Torschuss", ISpieler.SKILL_TORSCHUSS);
playerSkillArray[10] = new PlayerSkillColumn( 180, "ST", "Standards", ISpieler.SKILL_STANDARDS);
return playerSkillArray;
}
/**
*
* @return PlayerColumn []
*/
protected static PlayerColumn[] createPlayerBasicArray(){
final PlayerColumn[] playerBasicArray = new PlayerColumn[2];
playerBasicArray[0] = new PlayerColumn(NAME,"Name",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new SpielerLabelEntry(player,
HOVerwaltung.instance().getModel()
.getAufstellung()
.getPositionBySpielerId(player.getSpielerID()),
0f, false, false);
}
public boolean isEditable(){
return false;
}
};
playerBasicArray[1] = new PlayerColumn(ID,"ID",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new ColorLabelEntry(player.getSpielerID(),
player.getSpielerID() + "",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.RIGHT);
}
public boolean isEditable(){
return false;
}
public void setSize(TableColumn column){
column.setMinWidth(0);
column.setPreferredWidth(0);
}
};
return playerBasicArray;
}
/**
*
* @return PlayerPositionColumn[]
*/
protected static PlayerPositionColumn[] createPlayerPositionArray(){
final PlayerPositionColumn[] playerPositionArray = new PlayerPositionColumn[19];
playerPositionArray[0] = new PlayerPositionColumn( 190, "TORW", "Torwart", ISpielerPosition.TORWART );
playerPositionArray[1] = new PlayerPositionColumn( 200, "IV", "Innenverteidiger", ISpielerPosition.INNENVERTEIDIGER );
playerPositionArray[2] = new PlayerPositionColumn( 210, "IVA", "Innenverteidiger_Aus", ISpielerPosition.INNENVERTEIDIGER_AUS );
playerPositionArray[3] = new PlayerPositionColumn( 220, "IVO", "Innenverteidiger_Off", ISpielerPosition.INNENVERTEIDIGER_OFF );
playerPositionArray[4] = new PlayerPositionColumn( 230, "AV", "Aussenverteidiger", ISpielerPosition.AUSSENVERTEIDIGER );
playerPositionArray[5] = new PlayerPositionColumn( 240, "AVI", "Aussenverteidiger_In", ISpielerPosition.AUSSENVERTEIDIGER_IN );
playerPositionArray[6] = new PlayerPositionColumn( 250, "AVO", "Aussenverteidiger_Off",ISpielerPosition.AUSSENVERTEIDIGER_OFF );
playerPositionArray[7] = new PlayerPositionColumn( 260, "AVD", "Aussenverteidiger_Def",ISpielerPosition.AUSSENVERTEIDIGER_DEF );
playerPositionArray[8] = new PlayerPositionColumn( 270, "MIT", "Mittelfeld", ISpielerPosition.MITTELFELD );
playerPositionArray[9] = new PlayerPositionColumn( 280, "MITA", "Mittelfeld_Aus", ISpielerPosition.MITTELFELD_AUS );
playerPositionArray[10] = new PlayerPositionColumn( 290, "MITO", "Mittelfeld_Off", ISpielerPosition.MITTELFELD_OFF );
playerPositionArray[11] = new PlayerPositionColumn( 300, "MITD", "Mittelfeld_Def", ISpielerPosition.MITTELFELD_DEF );
playerPositionArray[12] = new PlayerPositionColumn( 310, "FLG", "Fluegelspiel", ISpielerPosition.FLUEGELSPIEL );
playerPositionArray[13] = new PlayerPositionColumn( 320, "FLGI", "Fluegelspiel_In", ISpielerPosition.FLUEGELSPIEL_IN );
playerPositionArray[14] = new PlayerPositionColumn( 330, "FLGO", "Fluegelspiel_Off", ISpielerPosition.FLUEGELSPIEL_OFF );
playerPositionArray[15] = new PlayerPositionColumn( 340, "FLGD", "Fluegelspiel_Def", ISpielerPosition.FLUEGELSPIEL_DEF );
playerPositionArray[16] = new PlayerPositionColumn( 350, "STU", "Sturm", ISpielerPosition.STURM );
playerPositionArray[17] = new PlayerPositionColumn( 360, "STUA", "Sturm_Aus", ISpielerPosition.STURM_AUS );
playerPositionArray[18] = new PlayerPositionColumn( 370, "STUD", "Sturm_Def", ISpielerPosition.STURM_DEF );
return playerPositionArray;
}
/**
*
* @return MatchKurzInfoColumn[]
*/
protected static MatchKurzInfoColumn[] createMatchesArray(){
final MatchKurzInfoColumn[] matchesArray = new MatchKurzInfoColumn[6];
matchesArray[0] = new MatchKurzInfoColumn(450,"Datum",70){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(match.getMatchDateAsTimestamp().getTime(),
java.text.DateFormat.getDateTimeInstance().format(match
.getMatchDateAsTimestamp()),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.LEFT);
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
return new ColorLabelEntry(spielerCBItem.getMatchdate(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.CENTER);
}
};
matchesArray[1] = new MatchKurzInfoColumn(460," ","Spielart",20){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImageIcon4Spieltyp(match.getMatchTyp()),
match.getMatchTyp(), ColorLabelEntry.FG_STANDARD,
background, SwingConstants.CENTER);
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImageIcon4Spieltyp(spielerCBItem.getMatchTyp()),
spielerCBItem.getMatchTyp(),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.CENTER);
}
};
matchesArray[2] = new MatchKurzInfoColumn(470,"Heim",60){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(match.getHeimName(), ColorLabelEntry.FG_STANDARD,
background, SwingConstants.LEFT);
entry.setFGColor((match.getHeimID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
if (match.getMatchStatus() != IMatchKurzInfo.FINISHED)
entry.setIcon(Helper.NOIMAGEICON);
else if (match.getHeimTore() > match.getGastTore())
entry.setIcon(Helper.YELLOWSTARIMAGEICON);
else if (match.getHeimTore() < match.getGastTore())
entry.setIcon(Helper.NOIMAGEICON);
else
entry.setIcon(Helper.GREYSTARIMAGEICON);
return entry;
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(spielerCBItem.getHeimteam() + "",
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.LEFT);
entry.setFGColor((spielerCBItem.getHeimID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
return entry;
}
public void setSize(TableColumn column){
column.setMinWidth(60);
column.setPreferredWidth((preferredWidth==0)?160:preferredWidth);
}
};
matchesArray[3] = new MatchKurzInfoColumn(480,"Gast",60){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(match.getGastName(), ColorLabelEntry.FG_STANDARD,
background, SwingConstants.LEFT);
entry.setFGColor((match.getGastID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
if (match.getMatchStatus() != IMatchKurzInfo.FINISHED)
entry.setIcon(Helper.NOIMAGEICON);
else if (match.getHeimTore() > match.getGastTore())
entry.setIcon(Helper.NOIMAGEICON);
else if (match.getHeimTore() < match.getGastTore())
entry.setIcon(Helper.YELLOWSTARIMAGEICON);
else
entry.setIcon(Helper.GREYSTARIMAGEICON);
return entry;
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
ColorLabelEntry entry = new ColorLabelEntry(spielerCBItem.getGastteam() + "",
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.LEFT);
entry.setFGColor((spielerCBItem.getGastID() == HOVerwaltung.instance().getModel().getBasics()
.getTeamId())?MatchesColumnModel.FG_EIGENESTEAM:Color.black);
return entry;
}
public void setSize(TableColumn column){
column.setMinWidth(60);
column.setPreferredWidth((preferredWidth==0)?160:preferredWidth);
}
};
matchesArray[4] = new MatchKurzInfoColumn(490,"Ergebnis",45){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(createTorString(match.getHeimTore(),
match.getGastTore()),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.CENTER);
}
public TableEntry getTableEntry(SpielerMatchCBItem spielerCBItem){
final Color background = getColor4Matchtyp(spielerCBItem.getMatchTyp());
return new ColorLabelEntry(createTorString(spielerCBItem.getMatchdetails().getHomeGoals(),
spielerCBItem.getMatchdetails().getGuestGoals()),
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.CENTER);
}
};
matchesArray[5] = new MatchKurzInfoColumn(500,"ID",55){
public TableEntry getTableEntry(MatchKurzInfo match){
final Color background = getColor4Matchtyp(match.getMatchTyp());
return new ColorLabelEntry(match.getMatchID(), match.getMatchID() + "",
ColorLabelEntry.FG_STANDARD, background,
SwingConstants.RIGHT);
}
};
return matchesArray;
}
/**
* creates an array of various player columns
* @return PlayerColumn[]
*/
protected static PlayerColumn[] createPlayerAdditionalArray(){
final PlayerColumn [] playerAdditionalArray = new PlayerColumn[11];
playerAdditionalArray[0] =new PlayerColumn(10," "," ",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
int sort = player.getTrikotnummer();
if (sort <= 0) {
//Damit die Spieler ohne Trickot nach den andern kommen
sort = 10000;
}
return new ColorLabelEntry(Helper.getImageIcon4Trickotnummer(player
.getTrikotnummer()),
sort, java.awt.Color.black, java.awt.Color.white,
SwingConstants.LEFT);
}
public boolean isEditable(){
return false;
}
};
playerAdditionalArray[1] =new PlayerColumn(20," ","Nationalitaet",25){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
return new ColorLabelEntry(Helper.getImageIcon4Country(player.getNationalitaet()),
player.getNationalitaet(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_FLAGGEN, SwingConstants.CENTER);
}
};
playerAdditionalArray[2] = new PlayerColumn(30, "Alter", 40){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
String ageString = player.getAlterWithAgeDaysAsString();
int birthdays = 0;
boolean playerExists;
if(playerCompare == null){
// Birthdays since last HRF
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - player.getAlter());
playerExists = false;
} else {
// Birthdays since compare
birthdays = (int) (Math.floor(player.getAlterWithAgeDays()) - Math.floor(playerCompare.getAlterWithAgeDays()));
if (playerCompare.isOld())
// Player was not in our team at compare date
playerExists = false;
else
// Player was in our team at compare date
playerExists = true;
}
return new ColorLabelEntry(
birthdays,
ageString,
player.getAlterWithAgeDays(),
playerExists,
ColorLabelEntry.BG_STANDARD,
true);
}
};
playerAdditionalArray[3] =new PlayerColumn(40,"BestePosition",100){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
ColorLabelEntry tmp = new ColorLabelEntry(-SpielerPosition.getSortId(player
.getIdealPosition(),
false)
- (player.getIdealPosStaerke(true) / 100.0f),
SpielerPosition.getNameForPosition(player
.getIdealPosition())
+ " ("
+ player.calcPosValue(player
.getIdealPosition(),
true) + ")",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.LEFT);
tmp.setIcon((player.getUserPosFlag() < 0)?Helper.ZAHNRAD:Helper.MANUELL);
return tmp;
}
public boolean isEditable(){
return false;
}
};
// Position
playerAdditionalArray[4] =new PlayerColumn(LINUP," ","Aufgestellt",28){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final HOModel model = HOVerwaltung.instance().getModel();
if (model.getAufstellung().isSpielerAufgestellt(player
.getSpielerID())
&& (model.getAufstellung().getPositionBySpielerId(player
.getSpielerID()) != null)) {
return new ColorLabelEntry(Helper.getImage4Position(model.getAufstellung()
.getPositionBySpielerId(player.getSpielerID()),
player.getTrikotnummer()),
-model.getAufstellung()
.getPositionBySpielerId(player
.getSpielerID())
.getSortId(),
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD, SwingConstants.CENTER);
}
return new ColorLabelEntry(de.hattrickorganizer.tools.Helper
.getImage4Position(null,
player
.getTrikotnummer()),
-player.getTrikotnummer() - 1000,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.CENTER);
}
};
playerAdditionalArray[5] = new PlayerColumn(GROUP,"Gruppe",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SmilieEntry smilieEntry = new SmilieEntry();
smilieEntry.setSpieler(player);
return smilieEntry;
}
};
playerAdditionalArray[6] = new PlayerColumn(70,"Status",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
SpielerStatusLabelEntry entry = new SpielerStatusLabelEntry();
entry.setSpieler(player);
return entry;
}
};
playerAdditionalArray[7] = new PlayerColumn(420,"Gehalt",10){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String bonus = "";
final int gehalt = (int) (player.getGehalt() / gui.UserParameter.instance().faktorGeld);
final String gehalttext = Helper.getNumberFormat(true, 0).format(gehalt);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
final int gehalt2 = (int) (playerCompare.getGehalt() / gui.UserParameter
.instance().faktorGeld);
return new DoppelLabelEntry(new ColorLabelEntry(gehalt,
gehalttext + bonus,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(gehalt - gehalt2,
ColorLabelEntry.BG_STANDARD,
true, false, 0));
}
};
playerAdditionalArray[8] = new PlayerColumn(430,"TSI",0){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
final String text = Helper.getNumberFormat(false, 0).format(player.getTSI());
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
return new DoppelLabelEntry(new ColorLabelEntry(player
.getTSI(),
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry(player.getTSI()
- playerCompare.getTSI(), ColorLabelEntry.BG_STANDARD,
false, false, 0));
}
public void setSize(TableColumn column){
column.setMinWidth(Helper.calcCellWidth(90));
}
};
playerAdditionalArray[9] = new PlayerColumn(RATING,"Bewertung",50){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
if (player.getBewertung() > 0) {
//Hat im letzen Spiel gespielt
return new RatingTableEntry(player.getBewertung(), true);
}
return new RatingTableEntry(player.getLetzteBewertung(), false);
}
};
playerAdditionalArray[10] = new PlayerColumn(436,"Marktwert",10){
public TableEntry getTableEntry(Spieler player,Spieler playerCompare){
IEPVData data = HOVerwaltung.instance().getModel().getEPV().getEPVData(player);
double price = HOVerwaltung.instance().getModel().getEPV().getPrice(data);
final String text = Helper.getNumberFormat(true, 0).format(price);
if(playerCompare == null){
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry("",
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT));
}
IEPVData comparedata = HOVerwaltung.instance().getModel().getEPV().getEPVData(playerCompare);
int htweek = HelperWrapper.instance().getHTWeek(playerCompare.getHrfDate());
double compareepv = HOVerwaltung.instance().getModel().getEPV().getPrice(comparedata, htweek);
return new DoppelLabelEntry(new ColorLabelEntry(price,
text,
ColorLabelEntry.FG_STANDARD,
ColorLabelEntry.BG_STANDARD,
SwingConstants.RIGHT),
new ColorLabelEntry((float)(price-compareepv),
ColorLabelEntry.BG_STANDARD,
true, false, 0)
);
}
};
return playerAdditionalArray;
}
}
| [
"[email protected]"
]
| |
5df9a085c816890228df5c46ac3a9cb8ec7f7207 | a1742ef6c77499b669a5b23d2a79bac0c9b12179 | /src/com/ob/base/designpattern/observer/ObserverMain.java | 430e4d0e3f7f51eaae3fb94fee5bb2b947d82410 | []
| no_license | oubin17/java_base | de04617ec8e5dba168f04036c84077c29292017b | 5e4e1b7abbe6382e62669985af2f2cbc27825435 | refs/heads/master | 2021-07-08T15:49:15.688101 | 2020-09-23T03:34:10 | 2020-09-23T03:34:10 | 187,944,000 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 383 | java | package com.ob.base.designpattern.observer;
/**
* @Author: oubin
* @Date: 2020/9/23 11:03
* @Description:
*/
public class ObserverMain {
public static void main(String[] args) {
WechatObserver wechatObserver = new WechatObserver();
Subject subject = new SubjectSubscribe();
wechatObserver.register(subject);
wechatObserver.update();
}
}
| [
"[email protected]"
]
| |
1c6243a8011fd488fd5b041a728cd68261878fbe | 52593a18d5d538eee30bc20237ba9833fa4b67bd | /android/app/src/main/java/com/twisac/helloworld/test_app/MainActivity.java | 8520bfcba47b40e23d7b073b247de93dda904ee1 | []
| no_license | ElvinEga/flutter_test | dba133b7c918ed3a55663ef72b52407a37bb2bdb | 8c72dc017e964b239eb4a5fad76ef070bf29775b | refs/heads/master | 2020-09-14T09:40:47.833678 | 2019-11-21T05:10:13 | 2019-11-21T05:10:13 | 223,093,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 375 | java | package com.twisac.helloworld.test_app;
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);
}
}
| [
"[email protected]"
]
| |
3015d6b8eed413135b4b4f15d27c3ff18a76b92f | 26b7f30c6640b8017a06786e4a2414ad8a4d71dd | /src/number_of_direct_superinterfaces/i29723.java | c8be4b641a938562b659f38da6e0fbc0269bf7a0 | []
| no_license | vincentclee/jvm-limits | b72a2f2dcc18caa458f1e77924221d585f23316b | 2fd1c26d1f7984ea8163bc103ad14b6d72282281 | refs/heads/master | 2020-05-18T11:18:41.711400 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 69 | java | package number_of_direct_superinterfaces;
public interface i29723 {} | [
"[email protected]"
]
| |
80b98fa9f27e286b7458e1864f68206e9a725513 | 2080c68a85c404e5680ec82793bae4eef235d9bf | /src/main/java/hxc/manage/service/UserService.java | 6e5e31e32692d6f9c118e621788028de6c7e6b69 | []
| no_license | 1104935833/manage_server | 426d6545a81a84695575dd25ced6f56c02680a0a | 9ea2424e421d5750a1487fce29db0346275b65d6 | refs/heads/master | 2022-07-31T13:13:40.009677 | 2020-06-27T21:19:20 | 2020-06-27T21:19:20 | 229,913,357 | 0 | 0 | null | 2020-06-06T05:53:48 | 2019-12-24T09:32:36 | Java | UTF-8 | Java | false | false | 762 | java | package hxc.manage.service;
import hxc.manage.model.Office;
import hxc.manage.model.UserDetail;
import java.util.List;
import java.util.Map;
/**
* @author hxc
* @version 1.0
* @date 2020/1/19 16:38
*/
public interface UserService {
boolean delByUserId(String ids);
List<Map<String, Object>> getAllTreePeople(String name);
List<Map<String, Object>> getAllTreePeople1(String name);
List<UserDetail> getAllEmployees();
List<UserDetail> getUserByPage(Map<String, Object> map);
Integer getUserByCount(Map<String, Object> map);
int addUser(List<UserDetail> emps);
void editUser(UserDetail userDetail);
List<UserDetail> searchInfo(Map<String, Object> map, UserDetail userDetail);
List<Office> getAllOffice();
}
| [
"[email protected]"
]
| |
53d1bfcd237f7ecb9562ce1ecbdaeab8d3674807 | e07b42d9ce305cbe3488b78a6eafe952980cdd8a | /app/src/main/java/com/example/yeelin/homework/weatherberry/loader/FavoritesLoaderCallbacks.java | e6c7dddc906847b299fc0eb626137edb6e87dd16 | [
"MIT"
]
| permissive | yeelin/weatherberry | 7e4593cb446f9e86f6a43eafb6982e45357096a6 | 681c91d9d2a0377e54c6bde36a58b8a3681e4ab9 | refs/heads/master | 2021-01-20T07:51:05.605300 | 2015-07-11T07:13:09 | 2015-07-11T07:13:09 | 38,337,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,897 | java | package com.example.yeelin.homework.weatherberry.loader;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import com.example.yeelin.homework.weatherberry.provider.BaseWeatherContract;
import com.example.yeelin.homework.weatherberry.provider.CurrentWeatherContract;
import java.lang.ref.WeakReference;
/**
* Created by ninjakiki on 5/27/15.
*/
public class FavoritesLoaderCallbacks implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = FavoritesLoaderCallbacks.class.getCanonicalName();
//bundle args to init loader
private static final String ARG_URI = FavoritesLoaderCallbacks.class.getSimpleName() + ".uri";
private static final String ARG_PROJECTION = FavoritesLoaderCallbacks.class.getSimpleName() + ".projection";
private static final String ARG_SELECTION = FavoritesLoaderCallbacks.class.getSimpleName() + ".selection";
private static final String ARG_SELECTION_ARGS = FavoritesLoaderCallbacks.class.getSimpleName() + ".selectionArgs";
private static final String ARG_SORT_ORDER = FavoritesLoaderCallbacks.class.getSimpleName() + ".sortOrder";
//member variables
private Context applicationContext;
private WeakReference<FavoritesLoaderListener> listenerWeakReference;
/**
* Listener interface for those interested in callbacks from this loader
*/
public interface FavoritesLoaderListener {
public void onLoadComplete(LoaderIds loaderId, @Nullable Cursor cursor);
}
/**
* Private constructor. Use initLoader instead
* @param context
* @param listener
*/
private FavoritesLoaderCallbacks(Context context, FavoritesLoaderListener listener) {
applicationContext = context.getApplicationContext();
listenerWeakReference = new WeakReference<>(listener);
}
/**
*
* @param context
* @param loaderManager
* @param listener
* @param projection
*/
public static void initLoader(Context context,
LoaderManager loaderManager,
FavoritesLoaderListener listener,
String[] projection) {
Bundle args = new Bundle();
args.putParcelable(ARG_URI, CurrentWeatherContract.URI);
args.putStringArray(ARG_PROJECTION, projection);
//call loader manager's initLoader
loaderManager.initLoader(LoaderIds.FAVORITES_LOADER.getValue(), args, new FavoritesLoaderCallbacks(context, listener));
}
/**
*
* @param context
* @param loaderManager
* @param listener
* @param projection
*/
public static void restartLoader(Context context,
LoaderManager loaderManager,
FavoritesLoaderListener listener,
String[] projection) {
Bundle args = new Bundle();
args.putStringArray(ARG_PROJECTION, projection);
loaderManager.restartLoader(LoaderIds.FAVORITES_LOADER.getValue(), args, new FavoritesLoaderCallbacks(context, listener));
}
/**
* Destroys the loader
* @param loaderManager
*/
public static void destroyLoader(LoaderManager loaderManager) {
loaderManager.destroyLoader(LoaderIds.FAVORITES_LOADER.getValue());
}
/**
* Creates a new loader
* @param id
* @param args
* @return
*/
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = args.getParcelable(ARG_URI);
String[] projection = args.getStringArray(ARG_PROJECTION);
return new CursorLoader(applicationContext,
uri,
projection,
BaseWeatherContract.whereClauseEquals(CurrentWeatherContract.Columns.USER_FAVORITE),
BaseWeatherContract.whereArgs(BaseWeatherContract.USER_FAVORITE_YES),
CurrentWeatherContract.Columns.CITY_NAME + " asc");
}
/**
* Loader has finished, notify listeners
* @param loader
* @param cursor
*/
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
//let the listener know
FavoritesLoaderListener listener = listenerWeakReference.get();
if (listener != null) {
listener.onLoadComplete(LoaderIds.getLoaderIdForInt(loader.getId()), cursor);
}
}
/**
* Loader has been reset, notify listeners
* @param loader
*/
@Override
public void onLoaderReset(Loader<Cursor> loader) {
//let the listener know
onLoadFinished(loader, null);
}
}
| [
"[email protected]"
]
| |
d6019f37368440a4ea27e71151dee6f1c3d7fc4e | f744c9e01a0fb57a3bbc1d48de4ee0069ca33ca1 | /Week6/第二题____银行系统/BankAccount.java | 38fff99f7d8d799de23782393d68f056cb9b3ee8 | []
| no_license | ygwOrange/JavaHWork | 39b5262fb837754940b2778f9bf013c8b17357c4 | d3586bd3d0e79d6c73809c9b2fabba624398c574 | refs/heads/main | 2023-05-14T04:36:54.617345 | 2021-05-30T01:53:31 | 2021-05-30T01:53:31 | 344,832,017 | 1 | 1 | null | 2021-03-05T15:49:58 | 2021-03-05T14:14:35 | null | GB18030 | Java | false | false | 861 | java | package Week602_BankingApplication;
public class BankAccount {
// 定义数据
private String accountNum; // 帐号
private double balance; // 余额
// 构造
public BankAccount() {
super();
this.accountNum = "";
this.balance = 0;
}
public BankAccount(String accountNum, double balance) {
this.accountNum = accountNum;
this.balance = balance;
}
// get与set
public String getAccountNum() {
return accountNum;
}
public void setAccountNum(String accountNum) {
this.accountNum = accountNum;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
// toString
public String toString() {
String msg = "";
msg += "帐号:" + this.accountNum + "\n";
msg += "余额" + this.balance + "\n";
return msg;
}
}
| [
"[email protected]"
]
| |
0ea6d68dcdf2d98293eacb604dc29b0a5c890c4b | a9f9fd0a9cfe2e4ff5ad89eaaa9f9eb4f8ae38ee | /redis-demo/src/main/java/com/bjtu/redis/CounterFunc.java | b9d932b8de9487893e5e63ec8dcd3d867cead627 | [
"MIT"
]
| permissive | Wang-Lei-2020/Non-SQL | 6733c5fdb49ba024630f67a9c23f74b7bac7368c | 557b4a49979f1b42107d8e0023d0b7e8949b149b | refs/heads/main | 2023-01-28T10:16:22.477287 | 2020-12-09T14:31:26 | 2020-12-09T14:31:26 | 303,067,354 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,476 | java | package com.bjtu.redis;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
** Function: 实现每个counter的具体功能,仅向外暴露一个count函数接口
** Author: 王磊 18301137
** Date: 2020年12月6日
*/
enum counterID{
incr,incrBy,decr,decrBy,showUserNum,showUserInFREQ,showUserOutFREQ,showUserInOutFREQ
}
public class CounterFunc {
RedisOperation ro = new RedisOperation();
public CounterFunc(){ }
//根据counter的名字选择运行以下哪一个函数,仅暴露这一个函数接口
public void count(Counter counter){
String name = counter.getName();
System.out.println(counterID.valueOf(name));
switch(counterID.valueOf(name)){
case incr:
incr(counter);
break;
case incrBy:
incrBy(counter);
break;
case decr:
decr(counter);
break;
case decrBy:
decrBy(counter);
break;
case showUserNum:
showUserNum(counter);
break;
case showUserInFREQ:
showUserInFREQ(counter);
break;
case showUserOutFREQ:
showUserOutFREQ(counter);
break;
case showUserInOutFREQ:
showUserInOutFREQ(counter);
break;
default:
break;
}
}
//user增加1,并往userInList中添加当前时间
private boolean incr(Counter counter){
//获取user和userInList在Redis数据库中的key值
String user = counter.getKey().get(0);
String userInList = counter.getKey().get(1);
//若没有创建user或者已过期,则要设置
if(ro.ttl(user)==-2){
ro.set(user,"1");
}else{
ro.incr(user);
}
//将现在的时间变为字符串以及yyyyMMddHHmm格式
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmm");
Date date = new Date();
String sDate=f.format(date);
ro.lpush(userInList,sDate);
System.out.println("有用户在"+sDate.substring(0,4)+"年"+sDate.substring(4,6)+"月"+sDate.substring(6,8)
+"日"+sDate.substring(8,10)+":"+sDate.substring(10,12)+"进入了直播间。");
ro.closeJedis();
return true;
}
//user增加任意值,并往userInList中添加当前时间
private boolean incrBy(Counter counter){
//获取user和userInList在Redis数据库中的key值
String user = counter.getKey().get(0);
String userInList = counter.getKey().get(1);
long value = Long.parseLong(counter.getValue());
//若没有创建user或者已过期,则要设置
if(ro.ttl(user)==-2){
ro.set(user,String.valueOf(value));
}else{
ro.incrBy(user,value);
}
//将现在的时间变为字符串以及yyyyMMddHHmm格式
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmm");
Date date = new Date();
String sDate=f.format(date);
//存入value个user到列表中
for(int i = 0; i<value; i++){
ro.lpush(userInList,sDate);
System.out.println("有用户在"+sDate.substring(0,4)+"年"+sDate.substring(4,6)+"月"+sDate.substring(6,8)
+"日"+sDate.substring(8,10)+":"+sDate.substring(10,12)+"进入了直播间。");
}
ro.closeJedis();
return true;
}
//user减少1,并往userOutList中添加当前时间
private boolean decr(Counter counter){
//获取user和userOutList在Redis数据库中的key值
String user = counter.getKey().get(0);
String userOutList = counter.getKey().get(1);
//若没有创建user或者已过期,则提示信息
if(ro.ttl(user)==-2){
System.out.println("当前无user数据,不能减少用户数量!");
return false;
}else if(Long.parseLong(ro.get(user)) == 0){//用户数量已经为0
System.out.println("user数量不够,不支持减少1个用户");
return false;
}
else {
ro.decr(user);
//将现在的时间变为字符串以及yyyyMMddHHmm格式
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmm");
Date date = new Date();
String sDate=f.format(date);
ro.lpush(userOutList,sDate);
System.out.println("有用户在"+sDate.substring(0,4)+"年"+sDate.substring(4,6)+"月"+sDate.substring(6,8)
+"日"+sDate.substring(8,10)+":"+sDate.substring(10,12)+"离开了直播间。");
}
ro.closeJedis();
return true;
}
//user减少任意值,并往userOutList中添加当前时间
private boolean decrBy(Counter counter){
//获取user和userOutList在Redis数据库中的key值
String user = counter.getKey().get(0);
String userOutList = counter.getKey().get(1);
long value = Long.parseLong(counter.getValue());
//若没有创建user或者已过期,则提示信息
if(ro.ttl(user)==-2){
System.out.println("当前无user数据,不能减少用户数量!");
return false;
}else if(Long.parseLong(ro.get(user))<value){
System.out.println("user数量不够,不支持减少这些数量的用户");
return false;
}else{
ro.decrBy(user,value);
//将现在的时间变为字符串以及yyyyMMddHHmm格式
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmm");
Date date = new Date();
String sDate=f.format(date);
for(int i = 0; i<value; i++) {
ro.lpush(userOutList, sDate);
System.out.println("有用户在"+sDate.substring(0,4)+"年"+sDate.substring(4,6)+"月"+sDate.substring(6,8)
+"日"+sDate.substring(8,10)+":"+sDate.substring(10,12)+"离开了直播间。");
}
}
ro.closeJedis();
return true;
}
//展示现在的user数量
private long showUserNum(Counter counter){
String num;
String user = counter.getKey().get(0);
if(ro.ttl(user) == -2){
System.out.println("当前无user数据,不支持查看user数量!");
return -1;
}else{
num = ro.get(user);
SimpleDateFormat f = new SimpleDateFormat("yyyy年-MM月dd日-HH:mm");
Date date = new Date();
String sDate=f.format(date);
System.out.println("当前时间:"+sDate+",直播间共有 "+num+" 名用户。");
}
ro.closeJedis();
return Long.parseLong(num);
}
//按周期显示用户进入直播间的时间与总进入用户量
private long showUserInFREQ(Counter counter){
String userInList = counter.getKey().get(0);
String start = counter.getStart();
String end = counter.getEnd();
long sum = 0;
if(start==null||end==null){
System.out.println("没有开始与结束时间,错误的计数器!");
ro.closeJedis();
return -1 ;
}
if(start.compareTo(end)>0){
System.out.println("开始时间晚于结束时间,错误的计数器!");
ro.closeJedis();
return -1 ;
}
if(ro.ttl(userInList)==-2){
System.out.println("不存在userInList列表,无法显示用户进入周期计数!");
return -1 ;
}else {
//userInList列表中的时间数据
long i = 0;
String userInTime = ro.lindex(userInList, i);
while(userInTime.compareTo(start)>=0 && userInTime.compareTo(end)<=0){
System.out.println("有用户在"+userInTime.substring(0,4)+"年"+userInTime.substring(4,6)+"月"+userInTime.substring(6,8)
+"日"+userInTime.substring(8,10)+":"+userInTime.substring(10,12)+"进入了直播间。");
sum++;
//取下一个用户进入的时间
i++;
//判断下标是否超过了列表总数(否则导致越界)
if(i<ro.getLen(userInList)) {
userInTime = ro.lindex(userInList, i);
}else{
break;
}
}
System.out.println(start.substring(0,4)+"年"+start.substring(4,6)+"月"+start.substring(6,8)+"日"+start.substring(8,10)+":"+start.substring(10,12)+"——"
+end.substring(0,4)+"年"+end.substring(4,6)+"月"+end.substring(6,8)+"日"+end.substring(8,10)+":"+end.substring(10,12)+" 时间段内共有 "+sum+" 名用户进入直播间。");
}
ro.closeJedis();
return sum;
}
//按周期显示用户离开直播间的时间与总离开用户量
private long showUserOutFREQ(Counter counter){
String userOutList = counter.getKey().get(0);
String start = counter.getStart();
String end = counter.getEnd();
long sum = 0;
if(start==null||end==null){
System.out.println("没有开始与结束时间,错误的计数器!");
ro.closeJedis();
return -1;
}
if(start.compareTo(end)>0){
System.out.println("开始时间晚于结束时间,错误的计数器!");
ro.closeJedis();
return -1;
}
if(ro.ttl(userOutList)==-2){
System.out.println("不存在userOutList列表,无法显示用户进入周期计数!");
return -1;
}else {
//userOutList列表中的时间数据
long i = 0;
String userOutTime = ro.lindex(userOutList, i);
while(userOutTime.compareTo(start)>=0 && userOutTime.compareTo(end)<=0){
System.out.println("有用户在"+userOutTime.substring(0,4)+"年"+userOutTime.substring(4,6)+"月"+userOutTime.substring(6,8)
+"日"+userOutTime.substring(8,10)+":"+userOutTime.substring(10,12)+"离开了直播间。");
sum++;
//取下一个用户进入的时间
i++;
//判断下标是否超过了列表总数(否则导致越界)
if(i<ro.getLen(userOutList)) {
userOutTime = ro.lindex(userOutList, i);
}else{
break;
}
}
System.out.println(start.substring(0,4)+"年"+start.substring(4,6)+"月"+start.substring(6,8)+"日"+start.substring(8,10)+":"+start.substring(10,12)+"——"
+end.substring(0,4)+"年"+end.substring(4,6)+"月"+end.substring(6,8)+"日"+end.substring(8,10)+":"+end.substring(10,12)+" 时间段内共有 "+sum+" 名用户离开直播间。");
}
ro.closeJedis();
return sum;
}
//**按周期显示用户进入离开直播间的实时数据**
private boolean showUserInOutFREQ(Counter counter){
String userInList = counter.getKey().get(0);
String userOutList = counter.getKey().get(1);
//FREQ的开始与结束时间
String start = counter.getStart();
String end = counter.getEnd();
if(ro.ttl(userInList)==-2){
System.out.println("没有userInList列表数据,无法查看用户进入数据!");
ro.closeJedis();
return false;
}else if(ro.ttl(userOutList)==-2){
System.out.println("没有userOutList列表数据,无法查看用户离开数据!");
ro.closeJedis();
return false;
} else if(start==null||end==null){
System.out.println("没有周期的开始与结束时间,错误的计数器!");
ro.closeJedis();
return false;
} else if(start.compareTo(end)>0){
System.out.println("开始时间晚于结束时间,错误的计数器!");
ro.closeJedis();
return false;
}else{
//用来表示两个列表的下标
long in=0;
long out=0;
//分别统计在时间段内进入和离开直播间的人数
int inSum = 0;
int outSum = 0;
//存放两个列表中的时间数据
String inTime = ro.lindex(userInList,in);
String outTime = ro.lindex(userOutList,out);
//将In列表中数据落在FREQ范围内
while(!(inTime.compareTo(start)>=0&&inTime.compareTo(end)<=0)){
in++;
//判断下标是否超过了列表总数(否则导致越界)
if(in<ro.getLen(userInList)) {
inTime = ro.lindex(userInList, in);
}else{
break;
}
}
//将Out列表中数据落在FREQ范围内
while(!(outTime.compareTo(start)>=0&&outTime.compareTo(end)<=0)){
out++;
//判断下标是否超过了列表总数(否则导致越界)
if(out<ro.getLen(userOutList)) {
outTime = ro.lindex(userOutList, out);
}else{
break;
}
}
//循环取两个列表中的值并比较时间早晚,时间晚的先进行操作
while(true){
//取时间结束,判断条件为时间早于start和取完列表两个条件进行笛卡尔积
if((inTime.compareTo(start)<0&&outTime.compareTo(start)<0)||(((in>=ro.getLen(userInList))&&(out>=ro.getLen(userOutList))))
||(inTime.compareTo(start)<0&&out>=ro.getLen(userOutList))||(outTime.compareTo(start)<0&&in>=ro.getLen(userInList))){
//打印总的用户进出量
System.out.println(start.substring(0,4)+"年"+start.substring(4,6)+"月"+start.substring(6,8)+"日"+start.substring(8,10)+":"+start.substring(10,12)+"——"
+end.substring(0,4)+"年"+end.substring(4,6)+"月"+end.substring(6,8)+"日"+end.substring(8,10)+":"+end.substring(10,12)+" 时间段内共有 "+inSum+" 名用户进入直播间。");
System.out.println(start.substring(0,4)+"年"+start.substring(4,6)+"月"+start.substring(6,8)+"日"+start.substring(8,10)+":"+start.substring(10,12)+"——"
+end.substring(0,4)+"年"+end.substring(4,6)+"月"+end.substring(6,8)+"日"+end.substring(8,10)+":"+end.substring(10,12)+" 时间段内共有 "+outSum+" 名用户离开直播间。");
//跳出循环
break;
}
//System.out.println(in+" "+out);
//in时间晚,或者out列表已经取完,并且in列表没有取完
if((inTime.compareTo(outTime)>=0||out>=ro.getLen(userOutList))&&in<ro.getLen(userInList)){
System.out.println("有用户在"+inTime.substring(0,4)+"年"+inTime.substring(4,6)+"月"+inTime.substring(6,8)+"日"+
inTime.substring(8,10)+":"+inTime.substring(10,12)+"进入了直播间。");
//in的数量+1
inSum++;
//取in列表下一个时间
in++;
//避免下标越界
if(in<ro.getLen(userInList)) {
inTime = ro.lindex(userInList, in);
}
//如果out列表没有取完
}else if(!(out>=ro.getLen(userOutList))){
System.out.println("有用户在"+outTime.substring(0,4)+"年"+outTime.substring(4,6)+"月"+outTime.substring(6,8)+"日"+
outTime.substring(8,10)+":"+outTime.substring(10,12)+"离开了直播间。");
//out的数量+1
outSum++;
//取out列表的下一个时间
out++;
//避免下标越界
if(out<ro.getLen(userOutList)) {
outTime = ro.lindex(userOutList, out);
}
}
}
}
//关闭jedis连接
ro.closeJedis();
return true;
}
/*
//测试成功
public static void main(String[] args){
CounterFunc c = new CounterFunc();
Map<String,Object> counters = ReadJson.getCounters();
//Counter c1 = (Counter)counters.get("incr");
// c.incr(c1);
//Counter c2 = (Counter)counters.get("incrBy");
//c.incrBy(c2);
//Counter c3 = (Counter)counters.get("decr");
//c.decr(c3);
//Counter c4 = (Counter)counters.get("decrBy");
//c.decrBy(c4);
//Counter c5 = (Counter)counters.get("showUserNum");
//c.showUserNum(c5);
//Counter c6 = (Counter)counters.get("showUserInFREQ");
//c.showUserInFREQ(c6);
//Counter c7 = (Counter)counters.get("showUserOutFREQ");
//c.showUserOutFREQ(c7);
//Counter c8 = (Counter)counters.get("showUserInOutFREQ");
//c.showUserInOutFREQ(c8);
Counter c9 = (Counter)counters.get("showUserInOutFREQ");
c.count(c9);
}
*/
}
| [
"[email protected]"
]
| |
e65ff96a45203937d6dfb63c45f2ed4c76dabdd7 | 6dc65713c5b751e9aca36710a2251e7673825a78 | /gulimall-product/src/main/java/com/wubaba/gulimallproduct/service/impl/PmsCategoryServiceImpl.java | fed6531f511aa558f62a1eaf013059064eea3d99 | []
| no_license | wujuxuan/mall-demo | 4de64f82a96f9368ef8689b9c4c2c2a419becd91 | da58931a903c6e4c7d613f0e3f905fa5f563e6ea | refs/heads/master | 2023-06-02T01:54:21.310949 | 2021-06-25T09:11:59 | 2021-06-25T09:11:59 | 379,196,373 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 641 | java | package com.wubaba.gulimallproduct.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wubaba.gulimallproduct.dao.PmsCategoryDao;
import com.wubaba.gulimallproduct.entity.PmsCategoryEntity;
import com.wubaba.gulimallproduct.service.PmsCategoryService;
@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {
} | [
"[email protected]"
]
| |
0f14ffc2b464aafb513fabfcb97ea16ad99fecd9 | b90ba5b30fe52df713b98488be347ec774ed28ae | /Akula/src/bootstrap_DB.java | 9941d86d3c5d62123e36ea76863d47d8f9ef8e06 | [
"Apache-2.0"
]
| permissive | evgenyvinnik/Akula | 16ff64f74192f4505899cbf384fa86e3faf67dfb | ba2768ac6eea9d8e771153db2091f669cf995782 | refs/heads/master | 2020-04-05T23:05:22.353858 | 2014-05-06T18:48:47 | 2014-05-06T18:48:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,479 | java | /*
* An instance of the bootstrap data base keeps and serves one
* info matrix.
*/
public class bootstrap_DB extends helper{
private double[][] data_matrix;
private int nb_entries;
private int pointer_array[];
public bootstrap_DB(int nb_benchmarks, int nb_neighbors)
{
nb_entries = (int)Math.pow((double)nb_benchmarks, (double)nb_neighbors);
data_matrix = new double[nb_benchmarks][nb_entries];
pointer_array = new int[nb_neighbors];
pointer_array[0] = 1;
for(int i = 1; i < nb_neighbors; i++)
{
pointer_array[i] = pointer_array[i-1]*nb_benchmarks;
}
}
/*
* This is the function which is called by the bootstrap module
* requesting a lookup.
*/
public double table_lookup(int target_id, int[] neighbor_ids)
{
//Translate the benchmark IDs into table IDS;
int pointer = get_pointer(neighbor_ids);
return data_matrix[target_id][pointer];
}
private int get_pointer(int[] neighbor_ids)
{
//Needed for one-dimension tables.
if(neighbor_ids == null)
{
return 0;
}
//Calculates a pointer into a 1-d array based on
int pointer = 0;
for(int i = 0; i < neighbor_ids.length; i++)
{
pointer += neighbor_ids[i]*pointer_array[i];
}
return pointer;
}
//Read in a file to fill the table.
public void input_data(int benchmark_id, int[] neighbors, double data)
{
int pointer = get_pointer(neighbors);
data_matrix[benchmark_id][pointer] = data;
}
}
| [
"evgeny@evgeny-PC.(none)"
]
| evgeny@evgeny-PC.(none) |
b5a5449ae4973702a9b38d7f0882378313418245 | 2a9a0009bbea8391c58da3031ad0f5db4a34fc80 | /app/src/main/java/com/lcarino/bucketlist/common/BaseFragment.java | e7a8d00b0cf63381d86a14c5060d16c39a19f557 | []
| no_license | luiscarino/listy | a6f2a0e6281a1584c07d5baef1d0e22d6ba83efe | 39a25e22e322ed239f8ba8860dc2e1e05a6250cf | refs/heads/master | 2021-01-11T10:20:36.436473 | 2017-03-22T02:27:34 | 2017-03-22T02:27:34 | 72,301,760 | 0 | 0 | null | 2017-03-22T02:27:35 | 2016-10-29T18:16:42 | Java | UTF-8 | Java | false | false | 1,849 | java | package com.lcarino.bucketlist.common;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lcarino.bucketlist.mvp.MvpPresenter;
import com.lcarino.bucketlist.mvp.MvpView;
import com.lcarino.bucketlist.ui.list.di.ListComponent;
/**
* Base fragment that uses MVP.
*
* @author Luis Carino.
*/
public abstract class BaseFragment<V extends MvpView, P extends MvpPresenter<V>> extends Fragment {
protected P presenter;
/**
* Instantiate a getListPresenter instance
*
* @return The {@link MvpPresenter} for this view
*/
public abstract P createPresenter();
protected ActivityActions activityActions;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = createPresenter();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof ActivityActions) {
activityActions = (ActivityActions) context;
} else {
throw new IllegalStateException("Activity must implement activity actions");
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(getLayoutRes(), container, false);
// ButterKnife.bind(this, view);
// return view;
}
@LayoutRes
public abstract int getLayoutRes();
public interface ActivityActions {
void setToolbarTitle(String title);
ListComponent getListComponent();
}
}
| [
"[email protected]"
]
| |
cf2d29ed5d8e8e3369b7d589cca3ca5262751997 | 7931f822df373f5db72fe819f1d9099ecbfca4d4 | /app/src/main/java/com/example/yvtc/yvtc2011110902/ZooDetail.java | ad11222e85530a9d777f2f4d0ed3c71152915641 | []
| no_license | Shaojung/YVTC2011110902 | 1313d8fb17646ccbc20477914cfac5da1aadedf0 | e0c3e43798b8f6b90631af59364de0951e2ab07c | refs/heads/master | 2021-08-08T00:46:19.688167 | 2017-11-09T07:54:26 | 2017-11-09T07:54:26 | 110,078,739 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 141 | java | package com.example.yvtc.yvtc2011110902;
/**
* Created by yvtc on 2017/11/9.
*/
public class ZooDetail {
public ZooInfo[] results;
}
| [
"[email protected]"
]
| |
9a73a5c70b8153f1d95587c6d2166b093ee137f4 | ad25a42836d12a81295ef063cca056903f5f724d | /src/datastructure/greedy/Greedy_04_lessMoney.java | 693c013be86b25e7753200f5bfa811063bb7e531 | []
| no_license | lining-flying/algorithm-data-structure | 07532654d97f6234d909b1f383ba69b8d5a0733f | 6059c7f4541bb587515bb65dc8f4bdd652548b19 | refs/heads/master | 2023-03-31T07:36:42.545093 | 2021-04-05T10:05:23 | 2021-04-05T10:05:23 | 294,738,934 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,678 | java | package datastructure.greedy;
import java.util.Arrays;
import java.util.PriorityQueue;
/**
* 哈夫曼树原理
* 给定一个金条,拆分的花费就是金条的长度,
* 给定目标长度数组,求如何拆分可以使用花费最小
*/
public class Greedy_04_lessMoney {
/**
* 暴力穷举
* 全排列
* @param arr
* @return
*/
public static int lessMoney_01(int[] arr){
//TODO
return 0 ;
}
/**
* 贪心算法 -- 堆实现
* @param arr
* @return
*/
public static int lessMoney_02(int[] arr){
if(arr == null || arr.length == 0){
return 0 ;
}
//PrioryQueue底层实现就是一个小顶堆
PriorityQueue<Integer> queue = new PriorityQueue<>();
for(int ele : arr){
queue.add(ele);
}
int cost = 0;
while(queue.size()>1){
int cur = queue.poll() + queue.poll() ;
cost += cur ;
queue.add(cur);
}
return cost;
}
/**
* 贪心算法 -- 实现2
* @param arr
* @return
*/
public static int lessMoney_03(int[] arr){
if(arr == null || arr.length == 0){
return 0 ;
}
Arrays.sort(arr);
int sum = 0 ;
for(int i=0;i<arr.length;i++){
sum += arr[i];
}
int cost = 0 ;
for(int i=arr.length-1;i>0;i--){
cost += sum ;
sum -= arr[i];
}
return cost ;
}
public static void main(String[] args) {
int[] arr = new int[]{10,20,30};
System.out.println(lessMoney_03(arr));
}
}
| [
"[email protected]"
]
| |
dbe788a105a6cf9e1b009d027ae9ce3031dcfe90 | 394a1e211fb5975cca5a79b15570bb5e022b7563 | /src/main/java/com/fred/homeapp/web/rest/VilleResource.java | d08925f0f4203875df814aedbce0c04b0994f86c | []
| no_license | FredPi17/home-application-jhipster | adf6766973f7462a3493d0a23342fb3568302a61 | 227d1f9c94f745479b9c24cb7f792b7b2b621789 | refs/heads/master | 2020-04-29T15:11:47.256277 | 2019-04-04T09:01:24 | 2019-04-04T09:01:24 | 176,220,443 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,202 | java | package com.fred.homeapp.web.rest;
import com.fred.homeapp.domain.Ville;
import com.fred.homeapp.service.VilleService;
import com.fred.homeapp.web.rest.errors.BadRequestAlertException;
import com.fred.homeapp.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing Ville.
*/
@RestController
@RequestMapping("/api")
public class VilleResource {
private final Logger log = LoggerFactory.getLogger(VilleResource.class);
private static final String ENTITY_NAME = "ville";
private final VilleService villeService;
public VilleResource(VilleService villeService) {
this.villeService = villeService;
}
/**
* POST /villes : Create a new ville.
*
* @param ville the ville to create
* @return the ResponseEntity with status 201 (Created) and with body the new ville, or with status 400 (Bad Request) if the ville has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/villes")
public ResponseEntity<Ville> createVille(@RequestBody Ville ville) throws URISyntaxException {
log.debug("REST request to save Ville : {}", ville);
if (ville.getId() != null) {
throw new BadRequestAlertException("A new ville cannot already have an ID", ENTITY_NAME, "idexists");
}
Ville result = villeService.save(ville);
return ResponseEntity.created(new URI("/api/villes/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /villes : Updates an existing ville.
*
* @param ville the ville to update
* @return the ResponseEntity with status 200 (OK) and with body the updated ville,
* or with status 400 (Bad Request) if the ville is not valid,
* or with status 500 (Internal Server Error) if the ville couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/villes")
public ResponseEntity<Ville> updateVille(@RequestBody Ville ville) throws URISyntaxException {
log.debug("REST request to update Ville : {}", ville);
if (ville.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
Ville result = villeService.save(ville);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, ville.getId().toString()))
.body(result);
}
/**
* GET /villes : get all the villes.
*
* @return the ResponseEntity with status 200 (OK) and the list of villes in body
*/
@GetMapping("/villes")
public List<Ville> getAllVilles() {
log.debug("REST request to get all Villes");
return villeService.findAll();
}
/**
* GET /villes/:id : get the "id" ville.
*
* @param id the id of the ville to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the ville, or with status 404 (Not Found)
*/
@GetMapping("/villes/{id}")
public ResponseEntity<Ville> getVille(@PathVariable Long id) {
log.debug("REST request to get Ville : {}", id);
Optional<Ville> ville = villeService.findOne(id);
return ResponseUtil.wrapOrNotFound(ville);
}
/**
* DELETE /villes/:id : delete the "id" ville.
*
* @param id the id of the ville to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/villes/{id}")
public ResponseEntity<Void> deleteVille(@PathVariable Long id) {
log.debug("REST request to delete Ville : {}", id);
villeService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* GET /villes/getVille/{latitude}/{longitude} : get data for the city with those coordinates
* @param latitude latitude of the city
* @param longitude longitude of the city
* @return the string of api call
* @throws Exception
*/
@GetMapping("/villes/getVille/{latitude}/{longitude}")
public String getDataFromVille(@PathVariable String latitude, @PathVariable String longitude) throws Exception {
log.debug("REST request to get data for a city");
return villeService.getDataFromVille(latitude, longitude, "");
}
/**
* GET /villes/getVille/{cityName} : get data for the city
* @param cityName city name
* @return data for the city
* @throws Exception
*/
@GetMapping("/villes/getVille/cityName/{cityName}")
public String getDataFromCityName(@PathVariable String cityName) throws Exception {
log.debug("REST request to get weather for: {}", cityName);
return villeService.getDataFromVille("", "", cityName);
}
}
| [
"[email protected]"
]
| |
02f0d03c67c3d5727cb9e7b224b8433aa0f554b8 | af08e33a4fd958d8a24a8b09f3d51cfeaf74088e | /pricechart/src/androidTest/java/com/georgevik/pricechart/ExampleInstrumentedTest.java | 3715ca8f907ba03e0d4e85b090a6ba562891bc72 | []
| no_license | Georgevik/blockchain_chart | 87fa272235aba629bef8b98bc162ff9f8595e989 | a9fa04a24df1aaaba4d089e6762bba29b9c35456 | refs/heads/master | 2020-05-24T17:25:27.259514 | 2019-05-20T21:17:14 | 2019-05-20T21:17:14 | 187,384,964 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 733 | java | package com.georgevik.pricechart;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.georgevik.pricechart.test", appContext.getPackageName());
}
}
| [
"[email protected]"
]
| |
6788a74a86a01a6b9bda542d802ab4ebad85ad43 | bcf7fe0a8cbd277750040236ed99c8029de78138 | /tutorial/src/tutorial/step4/Program04.java | 4f206a46b3f2f4fc968bce51e43f5e9b5d4d78c8 | []
| no_license | masanobuimai/tower-game | b08fd351721baa4af139d833ed19a17cb8489dee | b4f00b04c8cd36834d7986239ecb0d9af7a16ef4 | refs/heads/master | 2020-06-24T10:11:03.198352 | 2019-08-07T03:25:45 | 2019-08-07T03:25:45 | 198,936,184 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 479 | java | package tutorial.step4;
import tower.Soldier;
import tower.Tower;
import tower.TowerGame;
import java.util.logging.Logger;
public class Program04 {
private static final Logger log = Logger.getLogger(Program04.class.getName());
public static void main(String[] args) {
Tower tower = new MyTower();
// Tower tower = new MyTowerEx();
TowerGame.start(tower);
for (Soldier soldier : tower.getSoldierList()) {
log.info("soldier = " + soldier);
}
}
}
| [
"[email protected]"
]
| |
b812cc77941147a9e87ea64287f422178c036669 | d79032f84bdc2fede89383bc589123487d9d37d9 | /Scratch/Loui/GMSIS/src11/JavafxGUI/ObservableList.java | 9316139d0452d6a231373a5faa1da0cd72a6b753 | []
| no_license | musabadam95/GMSIS-Software-engineering-Group-project | 3d486eff275a2fd4b96e477b0fc0940a209c1403 | 6226b25ab5b23a0e70adfed40c09666915cc3b79 | refs/heads/master | 2020-03-23T22:20:04.020301 | 2018-07-24T14:22:37 | 2018-07-24T14:22:37 | 142,169,420 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 434 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package JavafxGUI;
/**
*
* @author louiraj
*/
class ObservableList<T> {
Object getName() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| [
"[email protected]"
]
| |
674e999a5f6b3128909518676f4563f3acf1c7cd | 1bc4f3ae6cef3e89f45eb4be7eada030df0c5ad7 | /ProcBuilder/src/procBuilder/engine/ProcessGenerator.java | 115a8071c07c0d109783d874c7e30043e2c04b02 | []
| no_license | liango2/ProcessManager-1 | 5c018e760f363912a780ada0581ad934459ebc94 | 6874a66c33d14380d3fc3724bfb57248e51e5cd4 | refs/heads/master | 2020-04-08T12:50:21.037985 | 2014-11-14T14:47:57 | 2014-11-14T14:47:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,866 | java | package procBuilder.engine;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ProcessGenerator {
public static List<ProcessWrapper> generateProcesses(Path dir, List<String> commands, Map<String, String> env, String extension) throws IOException {
ProcessWalker walker = new ProcessWalker(commands, env, extension);
Files.walkFileTree(dir, walker);
return walker.getWrappers();
}
private static class ProcessWalker extends SimpleFileVisitor<Path>{
List<ProcessWrapper> processes;
String extension;
List<String> commands;
Map<String, String> env;
public ProcessWalker(List<String> commands, Map<String, String> env, String extension) {
this.commands = commands;
this.env = env;
this.extension = extension;
processes = new ArrayList<ProcessWrapper>();
}
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (valid(file)) {
List<String> commandsCopy = new ArrayList<String>(commands);
commandsCopy.add(file.getFileName().toString());
System.out.println(commandsCopy);
ProcessWrapper wrapper = new ProcessWrapper();
wrapper.setName(file.getFileName().toString());
wrapper.setWorkingDirectory(file.getParent());
wrapper.setItems(commandsCopy);
wrapper.setEnv(env);
processes.add(wrapper);
}
return FileVisitResult.CONTINUE;
}
private boolean valid(Path p) {
if (p.toString().toLowerCase().endsWith(extension)) {
return true;
}
return false;
}
public List<ProcessWrapper> getWrappers() {
return processes;
}
}
} | [
"[email protected]"
]
| |
6be30dded0dfa0eddff6feb058e0d33e7e24794b | deb2e1da26b5ca4e0e53828bde731cf95b7936a7 | /src/main/java/com/edulima/service/IProductoService.java | 1df914dff8b4da052a198c5c0db567e60cc1997e | []
| no_license | edulima1989/VentasApp-backend | f72dc453676df158203605efe6457f8d154eec6d | 7a6708da079f4dd1164aeb58fea9b5a46ddaf84b | refs/heads/master | 2020-03-11T06:25:19.435558 | 2018-04-17T01:49:25 | 2018-04-17T01:49:25 | 129,829,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 303 | java | package com.edulima.service;
import java.util.List;
import com.edulima.model.Producto;
public interface IProductoService {
Producto registrar(Producto producto);
void modificar(Producto producto);
void eliminar(int idProducto);
Producto listarId(int idProducto);
List<Producto> listar();
}
| [
"[email protected]"
]
| |
8613dc27609b18427853d860511543505cc6a812 | f736da89c75b0833deec52e14fd9ad4113086706 | /src/main/java/com/example/blogapi/Services/BlogUserService.java | e83a5e4a4572eaffc10280f1b2dffabc262aa5f6 | []
| no_license | HeyItsF1/Week-9-BlogAPI | 423fa3db69c7e677b504ea1e642377011ab9626b | bf74504781074513c7663748e3a37425d2590c65 | refs/heads/main | 2023-08-14T22:15:06.902682 | 2021-09-20T12:11:10 | 2021-09-20T12:11:10 | 408,421,337 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 793 | java | package com.example.blogapi.Services;
import com.example.blogapi.Dto.UserDto;
import com.example.blogapi.Models.BlogPost;
import com.example.blogapi.Models.BlogUser;
import com.example.blogapi.Models.Comments;
import com.example.blogapi.Models.FavouritePost;
import java.util.List;
public interface BlogUserService {
String addNewUser(BlogUser blogUser);
Boolean login(UserDto userDto);
BlogPost makeNewBlogPost(BlogPost blogPost);
String addToFavouritesPost(FavouritePost favouritePost);
List<BlogUser> getAllBlogUsers ();
String getFavouriteBlogPost();
Comments makeNewcomment(Comments comments);
List<BlogPost> getAllBlogPost();
// void deactivateBlogUser(String blogUserUsername);
String deactivateBlogUser(BlogUser blogUser);
}
| [
"[email protected]"
]
| |
4b878444970cac57f51ffab9522335e244dde99d | f11e3848ca8cf16b69794659dbf4cb94397ce52f | /proiectare-aplicatii-orientate/lab5/p2.java | 474f502fcff2ed811d289ed4c013d77ca9072cef | []
| no_license | thirdless/faculta | cf4e0625675e55ac4923ed572ac2d2003df69730 | 6f4dc70dc0d24892c51f469dee378a6fcc45914d | refs/heads/master | 2023-03-16T05:42:01.633488 | 2021-03-03T11:56:36 | 2021-03-03T11:56:36 | 173,925,074 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 753 | java | package com.company;
import java.util.*;
class SortedVector extends Vector{
public void addElement(Object param){
super.add(param);
Collections.sort(this);
}
public void insertElementAt(Object param, int index){
super.insertElementAt(param, index);
Collections.sort(this);
}
}
public class P2 {
public static void main(String[] args) {
SortedVector ceva = new SortedVector();
ceva.addElement(1);
System.out.println(ceva.toString());
ceva.addElement(5);
System.out.println(ceva.toString());
ceva.addElement(3);
System.out.println(ceva.toString());
ceva.insertElementAt(69, 1);
System.out.println(ceva.toString());
}
}
| [
"[email protected]"
]
| |
daae16687fd9903ccc07fe6f986f1f2862bf20de | b46f6500b3f68262df0376fce44112afa7a66a55 | /rewrite-body/src/main/java/com/github/edgar615/spring/cloud/gateway/rewrite/Test.java | eea1f8ccd28a6610dd6f0a6f0000d11ece390a24 | []
| no_license | edgar615/spring-cloud-gateway-example | 4983cb70a7051929c1ae78738a9a8889d29d6d8a | 36b5e5e8628bedd9ba3c32b682ba8cf10e7d395a | refs/heads/main | 2023-01-25T01:09:11.757090 | 2020-12-03T02:59:53 | 2020-12-03T02:59:53 | 315,630,673 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 254 | java | package com.github.edgar615.spring.cloud.gateway.rewrite;
import java.util.Base64;
public class Test {
public static void main(String[] args) {
System.out.println(Base64.getEncoder().encodeToString("{\"foo\":\"bar\"}".getBytes()));
}
}
| [
"[email protected]"
]
| |
8a75c4c85691240a39a5b4d474fab5e956f43992 | 62eecd70a11d42b9a576dd2f9a321346eb2415cb | /classes/src_shared/lejos/nxt/addon/MMXMotor.java | eff726119ed91c7101fd9197957881deb9a0297a | []
| no_license | erikmartino/lejos | eb082ca0a2ce42f9230d82768f7eed94a9bcee71 | 950edc30a8278cd07a72e8649e81f1127237f897 | refs/heads/master | 2022-02-04T00:51:53.255345 | 2022-01-05T19:41:39 | 2022-01-05T19:41:39 | 109,509,475 | 0 | 0 | null | 2017-11-04T16:14:22 | 2017-11-04T16:07:16 | Java | UTF-8 | Java | false | false | 3,451 | java | package lejos.nxt.addon;
import lejos.robotics.EncoderMotor;
/**
* Abstraction to drive a basic encoder motor with the NXTMMX motor multiplexer. The
* NXTMMX motor multiplexer device allows you to connect two
* additional motors to your robot using a sensor port. Multiple NXTMMXs can be chained together.
* <p>
* Use the <code>NXTMMX.getBasicMotor()</code> factory method to retrieve an instance of this class.
*
* @see NXTMMX
* @see MMXRegulatedMotor
* @author Kirk P. Thompson
*
*/
public class MMXMotor implements EncoderMotor {
NXTMMX mmx;
int channel;
MMXMotor(NXTMMX mmx, int channel) {
this.mmx=mmx;
this.channel=channel;
setPower(100);
}
public void setPower(int power) {
power=Math.abs(power);
if (power>100) power=100;
mmx.doCommand(NXTMMX.CMD_SETPOWER, power, channel);
}
/**
* Sets speed ramping is enabled/disabled for this motor. Default at instantiation is ramping enabled.
* @param doRamping <code>true</code> to enable, <code>false </code>to disable
*/
public void setRamping(boolean doRamping) {
int operand=NXTMMX.MOTPARAM_OP_FALSE;
if (doRamping) operand=NXTMMX.MOTPARAM_OP_TRUE;
mmx.doCommand(NXTMMX.CMD_SETRAMPING, operand, channel);
}
public int getPower() {
return mmx.doCommand(NXTMMX.CMD_GETPOWER, 0, channel);
}
public void forward() {
mmx.doCommand(NXTMMX.CMD_FORWARD, 0, channel);
}
public void backward() {
mmx.doCommand(NXTMMX.CMD_BACKWARD, 0, channel);
}
public void stop() {
mmx.doCommand(NXTMMX.CMD_STOP, 0, channel);
}
public void flt() {
mmx.doCommand(NXTMMX.CMD_FLT, 0, channel);
}
/**
* Return <code>true</code> if the motor is moving. Note that this method reports based on the current control
* state (i.e. commanded to move) and not if the motor is actually moving. This means a motor may be stalled but this
* method would return <code>true</code>.
*
* @return <code>true</code> if the motor is executing a movement command, <code>false</code> if stopped.
*/
public boolean isMoving() {
return NXTMMX.MOTPARAM_OP_TRUE==mmx.doCommand(NXTMMX.CMD_ISMOVING, 0, channel);
}
/* (non-Javadoc)
* @see lejos.robotics.Encoder#getTachoCount()
*/
public int getTachoCount() {
return mmx.doCommand(NXTMMX.CMD_GETTACHO, 0, channel);
}
/**
* Reset the the tachometer count. TODO verify => Calling this method will stop any current motor action. This is imposed by the HiTechic
* Motor Controller firmware.
*/
public synchronized void resetTachoCount() {
mmx.doCommand(NXTMMX.CMD_RESETTACHO, 0, channel);
}
/**
* Disable or Enable internal motor controller speed regulation. Setting this to <code>true</code> will cause
* the motor controller firmware to adjust the motor power to compensate for changing loads in order to maintain
* a constant motor speed. Default at instantiation is <code>false</code>.
*
* @param regulate <code>true</code> to enable regulation, <code>true</code> otherwise.
*/
public void setRegulate(boolean regulate){
int operand=NXTMMX.MOTPARAM_OP_FALSE;
if (regulate) operand=NXTMMX.MOTPARAM_OP_TRUE;
mmx.doCommand(NXTMMX.CMD_SETREGULATE, operand, channel);
}
}
| [
"skoehler@06c8f799-c779-4783-8af7-179afedb67c8"
]
| skoehler@06c8f799-c779-4783-8af7-179afedb67c8 |
d974e26101551b34d105204bd248ea4235ff3047 | 3d2706aedb74cebdba0736cfa2970e7c18aa706d | /app/src/main/java/com/example/lbodnyk/elapsed/MyTextWatcher.java | 26e7d5f0e420b4bd56e37972210f5af9c5170f15 | []
| no_license | superelitist/Elapsed | be78b802c5ec3da22bd79297745be98210192f71 | c253a324ee393e69cebda53a75d46c20845dab8a | refs/heads/master | 2021-01-18T17:56:20.831256 | 2017-08-07T22:09:22 | 2017-08-07T22:09:22 | 86,826,916 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,005 | java | // watches for changes in text fields, and updates the MyElapsedTimeObject accordingly
package com.example.lbodnyk.elapsed;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.util.Log;
public class MyTextWatcher implements TextWatcher {
private View view;
private MyElapsedTimeObject ElapsedTimeObject;
public MyTextWatcher(View view, MyElapsedTimeObject ElapsedTimeObject) {
this.view = view;
this.ElapsedTimeObject = ElapsedTimeObject;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) {
//Log.d("MyTextWatcher", "afterTextChanged s.toString(): " + s.toString());
ElapsedTimeObject.setTitle(s.toString());
//Log.d("MyTextWatcher", "afterTextChanged ElapsedTimeObject.getTitle(): " + ElapsedTimeObject.getTitle());
}
} | [
"[email protected]"
]
| |
71f41abc1ecd65e5a606ca877ba75559a4c12042 | 57297311e71c45b0ca44c5ca91fb5c8beefb0cd8 | /chinese.go.user/src/main/java/org/chinese/go/user/App.java | 23a5cb2ea5a72e019b57049a3dd92af672bae57c | [
"Apache-2.0"
]
| permissive | QQ430042/chinese.go | 97d9670b9bd5b913d9f843155dd93f948ff4a889 | 8a5e272fe21d70e535339ed4d1df0e1696dc6642 | refs/heads/master | 2021-09-08T05:57:53.455795 | 2020-01-31T14:55:45 | 2020-01-31T14:55:45 | 229,438,932 | 3 | 0 | Apache-2.0 | 2020-10-13T18:33:41 | 2019-12-21T14:27:50 | Java | UTF-8 | Java | false | false | 195 | java | package org.chinese.go.user;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| [
"[email protected]"
]
| |
3de228e581399ab8f50af5ef99873805667d3832 | b741f665f4852983185e0486bb290278fe43616e | /src/test/java/com/common/BaseCrossBrowser.java | 661d2c917a74ff81e68b4cd0e16bdcc3f7035a8a | []
| no_license | minhaj6969/Now_Document | ead80b620c131dfdead3aa0110d33a94b70bee54 | 6dd802373cc15794b83900d41236a5481aaa98fe | refs/heads/master | 2023-03-27T02:57:01.112012 | 2021-03-22T17:00:30 | 2021-03-22T17:00:30 | 350,422,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,165 | java | package com.common;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.opera.OperaDriver;
public class BaseCrossBrowser {
private static String getURL = "https://www.amazon.com";
public static String getGetURL(){
return getURL;
}
WebDriver driver;
public static WebDriver getBrowser (String BrowserName, WebDriver driver){
if (BrowserName.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "driver/chromedriver");
driver = new ChromeDriver();
}
if (BrowserName.equalsIgnoreCase("opera")){
System.setProperty("webdriver.opera.driver", "Driver/operadriver");
driver = new OperaDriver();
}
else if (BrowserName.equalsIgnoreCase("geckodriver")){
System.setProperty("webdriver.gecko.driver", "Driver/geckodriver");
driver = new FirefoxDriver();
}
driver.get("https://www.amazon.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return driver;
}
}
| [
"minhajahmed@localhost"
]
| minhajahmed@localhost |
77ac425c5f44d2787233eb5aca260c07e3276272 | e3d486b486a198ef53f14e8eb34d54ca7c26739f | /src/main/java/com/casadocodigo/casadocodigo/buscarlivros/LivroBuscadoAutorDto.java | 82d926b31f8267fe473ca8fd5be2dfe0fad0e1b1 | [
"Apache-2.0"
]
| permissive | brunotetsuo/orange-talents-02-template-casa-do-codigo | 450fd7787695c4103a0449387c4ce253f0ddc34d | 143656ef1a6350a70b15e39e6849ab2037813720 | refs/heads/main | 2023-03-08T01:08:42.514510 | 2021-02-25T20:31:50 | 2021-02-25T20:31:50 | 342,365,657 | 0 | 0 | Apache-2.0 | 2021-02-25T20:07:08 | 2021-02-25T20:07:07 | null | UTF-8 | Java | false | false | 549 | java | package com.casadocodigo.casadocodigo.buscarlivros;
import com.casadocodigo.casadocodigo.novoautor.Autor;
public class LivroBuscadoAutorDto {
private String nome;
private String descricao;
public LivroBuscadoAutorDto(Autor autor) {
nome = autor.getNome();
descricao = autor.getDescricao();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
| [
"[email protected]"
]
| |
e56196eb2b763bff15d5ca5f7f035fe6b7dd648b | f8e5aeeeee0ca934dc31d925d43c5cf31e93e7e8 | /src/java/com/abcindustries/websockets/ProductsWebSocket.java | 7e59e1fe45593d5532785b6c9234216d66a21ba5 | []
| no_license | georgyKurian/jee_assignment_9 | ab92da99bec70459c83e1adbf539e831c49247af | 76d0725fd9dca57865f4512dc982a6b5ff83ef3c | refs/heads/master | 2021-01-19T22:33:58.230551 | 2017-04-21T22:43:14 | 2017-04-21T22:43:14 | 88,824,231 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,540 | java | /*
* Copyright 2016 Len Payne <[email protected]>.
*
* 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.abcindustries.websockets;
import com.abcindustries.controllers.ProductsController;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.OnMessage;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
*
* @author Georgi
*/
@ServerEndpoint("/productsSocket")
@ApplicationScoped
public class ProductsWebSocket {
List<Session> sessionList = new ArrayList<>();
@Inject
ProductsController products;
// TODO: Inject the VendorsController as well
@OnMessage
public void onMessage(String message, Session session) throws IOException {
if (!sessionList.contains(session)) {
sessionList.add(session);
}
String output = "";
JsonObject json = Json.createReader(new StringReader(message)).readObject();
if (json.containsKey("get") && json.getString("get").equals("products")) {
if (json.containsKey("id")) {
output = products.getById(json.getInt("id")).toJson().toString();
} else if (json.containsKey("search")) {
output = products.getBySearchJson(json.getString("search")).toString();
} else {
output = products.getAllJson().toString();
}
} else if (json.containsKey("post") && json.getString("post").equals("products")) {
JsonObject productJson = json.getJsonObject("data");
products.addJson(productJson);
output = products.getAllJson().toString();
} else if (json.containsKey("put") && json.getString("put").equals("products")) {
JsonObject productJson = json.getJsonObject("data");
int id = productJson.getInt("productId");
if(products.getById(id)== null){
products.addJson(productJson);
}
else {
products.editJson(id, productJson);
}
output = products.getAllJson().toString();
} else if (json.containsKey("delete") && json.getString("delete").equals("products")) {
if (json.containsKey("id")) {
products.delete(json.getInt("id"));
output = products.getAllJson().toString();
}
} else {
output = Json.createObjectBuilder()
.add("error", "Invalid Request")
.add("original", json)
.build().toString();
}
// TODO: Return the output string to the user that sent the message
RemoteEndpoint.Basic basic = session.getBasicRemote();
basic.sendText(output);
}
}
| [
"[email protected]"
]
| |
931c8356e4d5442dfbd4633f3f9fb5672b523331 | 3cde8ec189696d8d2a689aa88f57759f83ee4da3 | /java game engine/src/rendergame/renderer.java | d154024015b0236d3aebdc073e3e863d191b672a | []
| no_license | nooaandersson/javagameenginelwglj | 1a63379bdfdad59183e28a76d8520a04c97b1420 | a05311bbda0ec5d79870a03729bfc44a73e17161 | refs/heads/master | 2020-05-01T12:53:50.436569 | 2019-04-28T23:38:06 | 2019-04-28T23:38:06 | 177,476,941 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,569 | java | package rendergame;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.util.vector.Matrix4f;
import entities.Entity;
import models.TextureModel;
import models.rawModel;
import toolBox.Maths;
public class renderer {
private static final float FOV = 70;
private static final float NEAR_PLANE = 0.1f;
private static final float FAR_PLANE = 1000;
private Matrix4f projectionMatrix;
public renderer(staticShader shader) {
createProjectionMatrix();
shader.start();
shader.loadProjectionMatrix(projectionMatrix);
shader.stop();
}
public void prepare() {
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glClearColor(0,0.3f,0.0f,1);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT|GL11.GL_DEPTH_BUFFER_BIT);
}
public void render(Entity entity, staticShader shader) {
TextureModel model = entity.getModel();
rawModel rawmodel = model.getRawModel();
GL30.glBindVertexArray(rawmodel.getVaoID());
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
GL20.glEnableVertexAttribArray(2);
Matrix4f transformationMatrix = Maths.createTransformationMatrix(entity.getPosistion(), entity.getRotX(), entity.getRotY(), entity.getRotZ(), entity.getScale());
shader.loadTransformationMatrix(transformationMatrix);
ModelTexture texture = model.getTexture();
shader.loadShineVariables(texture.getShineDamper(), texture.getReflectivity());
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, model.getTexture().getID());
GL11.glDrawElements(GL11.GL_TRIANGLES, rawmodel.getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
GL20.glDisableVertexAttribArray(2);
GL30.glBindVertexArray(0);
}
private void createProjectionMatrix() {
float aspectRatio = (float) Display.getWidth() / (float) Display.getHeight();
float y_scale = (float) (1f / Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio;
float x_scale = y_scale / aspectRatio;
float frustum_length = FAR_PLANE - NEAR_PLANE;
projectionMatrix = new Matrix4f();
projectionMatrix.m00 = x_scale;
projectionMatrix.m11 = y_scale;
projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustum_length);
projectionMatrix.m23 = -1;
projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length);
projectionMatrix.m33 = 0;
}
}
| [
"[email protected]"
]
| |
9a45b279f3d3e550b5c4e210f4f9328fb61e2535 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/4/4_00c6f8730eaa3dee011f079e9b6e41c9c8287e6e/StandardVMType/4_00c6f8730eaa3dee011f079e9b6e41c9c8287e6e_StandardVMType_t.java | 080a4adffec4efc32939256608a2c6efc8115d74 | []
| 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 | 16,987 | java | package org.eclipse.jdt.internal.launching;
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
This file is made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
**********************************************************************/
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jdt.launching.AbstractVMInstallType;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.LibraryLocation;
/**
* A VM install type for VMs the conform to the standard
* JDK installion layout.
*/
public class StandardVMType extends AbstractVMInstallType {
/**
* The root path for the attached src
*/
private String fDefaultRootPath;
/**
* The libraries that comprise the standard classes for IBM 1.4 VMs. The order
* is significant.
*/
private final static String[] fgIBM14LibraryNames = {"core.jar", //$NON-NLS-1$
"graphics.jar", //$NON-NLS-1$
"security.jar", //$NON-NLS-1$
"server.jar", //$NON-NLS-1$
"xml.jar", //$NON-NLS-1$
"charsets.jar"}; //$NON-NLS-1$
/**
* Convenience handle to the system-specific file separator character
*/
private static final char fgSeparator = File.separatorChar;
/**
* The list of locations in which to look for the java executable in candidate
* VM install locations, relative to the VM install location.
*/
private static final String[] fgCandidateJavaLocations = {
"bin" + fgSeparator + "javaw", //$NON-NLS-2$ //$NON-NLS-1$
"bin" + fgSeparator + "javaw.exe", //$NON-NLS-2$ //$NON-NLS-1$
"jre" + fgSeparator + "bin" + fgSeparator + "javaw", //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
"jre" + fgSeparator + "bin" + fgSeparator + "javaw.exe", //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
"bin" + fgSeparator + "java", //$NON-NLS-2$ //$NON-NLS-1$
"bin" + fgSeparator + "java.exe", //$NON-NLS-2$ //$NON-NLS-1$
"jre" + fgSeparator + "bin" + fgSeparator + "java", //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
"jre" + fgSeparator + "bin" + fgSeparator + "java.exe"}; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
/**
* Starting in the specified VM install location, attempt to find the 'java' executable
* file. If found, return the corresponding <code>File</code> object, otherwise return
* <code>null</code>.
*/
protected File findJavaExecutable(File vmInstallLocation) {
// Try each candidate in order. The first one found wins. Thus, the order
// of fgCandidateJavaLocations is significant.
for (int i = 0; i < fgCandidateJavaLocations.length; i++) {
File javaFile = new File(vmInstallLocation, fgCandidateJavaLocations[i]);
if (javaFile.isFile()) {
return javaFile;
}
}
return null;
}
/**
* @see IVMInstallType#getName()
*/
public String getName() {
return LaunchingMessages.getString("StandardVMType.Standard_VM_3"); //$NON-NLS-1$
}
protected IVMInstall doCreateVMInstall(String id) {
return new StandardVM(this, id);
}
/**
* Return Java version information corresponding to the specified Java executable.
*/
protected JavaVersionInfo getJavaVersion(File javaHome, File javaExecutable) {
// See if we already know the version info for the requested VM. If not, generate it.
String installPath = javaHome.getAbsolutePath();
JavaVersionInfo versionResults = (JavaVersionInfo) LaunchingPlugin.getJavaVersionInfo(installPath);
if (versionResults == null) {
versionResults = generateJavaVersionResults(javaExecutable);
LaunchingPlugin.setJavaVersionInfo(installPath, versionResults);
}
return versionResults;
}
/**
* Invoke the specified Java executable with the '-version' option, parse the results
* and return them in a JavaVersionInfo object.
*/
protected JavaVersionInfo generateJavaVersionResults(File javaExecutable) {
JavaVersionInfo versionResults = null;
String javaExecutablePath = javaExecutable.getAbsolutePath();
String[] cmdLine = new String[] {javaExecutablePath, "-version"}; //$NON-NLS-1$
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdLine);
IProcess process = DebugPlugin.newProcess(new Launch(null, ILaunchManager.RUN_MODE, null), p, "Java -version");
while (!process.isTerminated()) {
// wait for process to terminate
}
versionResults= determineVersion(process);
} catch (IOException ioe) {
LaunchingPlugin.log(ioe);
} finally {
if (p != null) {
p.destroy();
}
}
if (versionResults == null) {
versionResults = JavaVersionInfo.getEmptyJavaVersionInfo();
}
return versionResults;
}
/**
* Returns the version information polled from the
* error and output streams of the specified process
* or <code>null</code> if no version information
* is found.
*/
protected JavaVersionInfo determineVersion(IProcess process) throws IOException {
// Some VMs put their '-version' output on stderr, some put it on stdout
JavaVersionInfo versionResults;
String text = process.getStreamsProxy().getErrorStreamMonitor().getContents();
if (text != null && text.length() > 0) {
versionResults= parseJavaVersionOutput(text);
if (versionResults != null) {
return versionResults;
}
}
text = process.getStreamsProxy().getOutputStreamMonitor().getContents();
if (text != null && text.length() > 0) {
versionResults= parseJavaVersionOutput(text);
if (versionResults != null) {
return versionResults;
}
}
return null;
}
/**
* Parse the output of a 'java -version' command residing in the specified InputStream
* and put the results in the specified JavaVersionInfo object.
*/
protected JavaVersionInfo parseJavaVersionOutput(String text) {
int index = text.indexOf("java version"); //$NON-NLS-1$
String javaVersion = ""; //$NON-NLS-1$
if (index >= 0) {
javaVersion = parseVersionNumber(text, index);
}
return new JavaVersionInfo(javaVersion, ibmDetected(text));
}
protected String parseVersionNumber(String string, int pos) {
int firstQuote = string.indexOf('"', pos);
int lastQuote = string.indexOf('"', firstQuote + 1);
if (firstQuote > -1 && lastQuote > -1 && firstQuote != lastQuote) {
return string.substring(firstQuote + 1, lastQuote);
}
return ""; //$NON-NLS-1$
}
protected boolean ibmDetected(String string) {
int ibmIndex = string.indexOf("IBM"); //$NON-NLS-1$
if (ibmIndex != -1) {
return true;
}
return false;
}
/**
* Return <code>true</code> if the appropriate system libraries can be found for the
* specified java executable, <code>false</code> otherwise.
*/
protected boolean canDetectDefaultSystemLibraries(File javaHome, File javaExecutable) {
JavaVersionInfo versionResults = getJavaVersion(javaHome, javaExecutable);
if (versionResults != null) {
return canDetectDefaultSystemLibraries(javaHome, versionResults);
}
return false;
}
/**
* Return <code>true</code> if the system libraries appropriate to the specified java version
* results can be found underneath the specified directory, <code>false</code> otherwise.
*/
protected boolean canDetectDefaultSystemLibraries(File javaHome, JavaVersionInfo versionResults) {
if (versionResults.getVersionString().startsWith("1.1")) { //$NON-NLS-1$
return false;
}
if (versionResults.ibm14Found()) {
return canDetectIBM14SystemLibraries(javaHome);
} else {
return canDetectSystemLibraries(javaHome);
}
}
protected boolean canDetectSystemLibraries(File javaHome) {
IPath path = getDefaultSystemLibrary(javaHome);
if (path.toFile().exists()) {
return true;
}
return false;
}
protected boolean canDetectIBM14SystemLibraries(File javaHome) {
IPath[] paths = getDefaultIBM14SystemLibraries(javaHome);
for (int i = 0; i < paths.length; i++) {
if (!paths[i].toFile().exists()) {
return false;
}
}
return true;
}
/**
* @see IVMInstallType#detectInstallLocation()
*/
public File detectInstallLocation() {
// Retrieve the 'java.home' system property. If that directory doesn't exist,
// return null.
File javaHome = new File (System.getProperty("java.home")); //$NON-NLS-1$
if (!javaHome.exists()) {
return null;
}
// Find the 'java' executable file under the java home directory. If it can't be
// found, return null.
File javaExecutable = findJavaExecutable(javaHome);
if (javaExecutable == null) {
return null;
}
// If the reported java home directory terminates with 'jre', first see if
// the parent directory contains the required libraries
boolean foundLibraries = false;
if (javaHome.getName().equalsIgnoreCase("jre")) { //$NON-NLS-1$
File parent= new File(javaHome.getParent());
if (canDetectDefaultSystemLibraries(parent, javaExecutable)) {
javaHome = parent;
foundLibraries = true;
}
}
// If we haven't already found the libraries, look in the reported java home dir
if (!foundLibraries) {
if (!canDetectDefaultSystemLibraries(javaHome, javaExecutable)) {
return null;
}
}
// bug 26724
// Don't get fooled by a J9 VM
// if ("J9".equals(System.getProperty("java.vm.name"))) {//$NON-NLS-2$ //$NON-NLS-1$
// return null;
// }
return javaHome;
}
/**
* Return an <code>IPath</code> corresponding to the single library file containing the
* standard Java classes for most VMs version 1.2 and above.
*/
protected IPath getDefaultSystemLibrary(File javaHome) {
IPath jreLibPath= new Path(javaHome.getPath()).append("lib").append("rt.jar"); //$NON-NLS-2$ //$NON-NLS-1$
if (jreLibPath.toFile().isFile()) {
return jreLibPath;
}
return new Path(javaHome.getPath()).append("jre").append("lib").append("rt.jar"); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
}
/**
* Return an array of <code>IPath</code> objects corresponding to the library files
* containing the standard Java classes for IBM VMs version 1.4 and above.
*/
protected IPath[] getDefaultIBM14SystemLibraries(File javaHome) {
IPath[] paths = new Path[fgIBM14LibraryNames.length];
for (int i = 0; i < fgIBM14LibraryNames.length; i++) {
paths[i] = new Path(javaHome.getPath());
if (!javaHome.getName().equalsIgnoreCase("jre")) { //$NON-NLS-1$
paths[i] = paths[i].append("jre"); //$NON-NLS-1$
}
paths[i] = paths[i].append("lib").append(fgIBM14LibraryNames[i]); //$NON-NLS-1$
}
return paths;
}
protected IPath getDefaultSystemLibrarySource(File installLocation) {
File parent= installLocation.getParentFile();
if (parent != null) {
File parentsrc= new File(parent, "src.jar"); //$NON-NLS-1$
if (parentsrc.isFile()) {
setDefaultRootPath("src");//$NON-NLS-1$
return new Path(parentsrc.getPath());
}
parentsrc= new File(parent, "src.zip"); //$NON-NLS-1$
if (parentsrc.isFile()) {
setDefaultRootPath(""); //$NON-NLS-1$
return new Path(parentsrc.getPath());
}
parentsrc= new File(installLocation, "src.jar"); //$NON-NLS-1$
if (parentsrc.isFile()) {
setDefaultRootPath("src"); //$NON-NLS-1$
return new Path(parentsrc.getPath());
}
parentsrc= new File(installLocation, "src.zip"); //$NON-NLS-1$
if (parentsrc.isFile()) {
setDefaultRootPath(""); //$NON-NLS-1$
return new Path(parentsrc.getPath());
}
}
setDefaultRootPath(""); //$NON-NLS-1$
return Path.EMPTY; //$NON-NLS-1$
}
protected IPath getDefaultPackageRootPath() {
return new Path(getDefaultRootPath());
}
/**
* @see IVMInstallType#getDefaultSystemLibraryDescription(File)
*/
public LibraryLocation[] getDefaultLibraryLocations(File installLocation) {
// Determine the java executable that corresponds to the specified install location
// and use this to generate java version info. If no java executable was found,
// just create empty results. This will cause the 'standard' libraries to be
// returned.
File javaExecutable = findJavaExecutable(installLocation);
JavaVersionInfo versionResults;
if (javaExecutable != null) {
versionResults = getJavaVersion(installLocation, javaExecutable);
} else {
versionResults = JavaVersionInfo.getEmptyJavaVersionInfo();
}
// For IBM 1.4 and above VMs, get their particular libraries. For all other VMs,
// just get the single standard library
LibraryLocation[] libs = null;
if (versionResults.ibm14Found()) {
IPath[] paths = getDefaultIBM14SystemLibraries(installLocation);
libs = new LibraryLocation[paths.length];
for (int i = 0; i < paths.length; i++) {
libs[i] = new LibraryLocation(paths[i],
getDefaultSystemLibrarySource(installLocation),
getDefaultPackageRootPath());
}
} else {
libs = new LibraryLocation[1];
libs[0] = new LibraryLocation(getDefaultSystemLibrary(installLocation),
getDefaultSystemLibrarySource(installLocation),
getDefaultPackageRootPath());
}
// Determine all extension directories and add them to the standard libraries
List extensions = getExtensionLibraries(installLocation);
LibraryLocation[] allLibs = new LibraryLocation[libs.length + extensions.size()];
System.arraycopy(libs, 0, allLibs, 0, libs.length);
for (int i = 0; i < extensions.size(); i++) {
allLibs[i + libs.length] = (LibraryLocation)extensions.get(i);
}
return allLibs;
}
/**
* Returns a list of default extension jars that should be placed on the build
* path and runtime classpath, by default.
*
* @param installLocation
* @return List
*/
protected List getExtensionLibraries(File installLocation) {
File extDir = getDefaultExtensionDirectory(installLocation);
List extensions = new ArrayList();
if (extDir != null && extDir.exists() && extDir.isDirectory()) {
String[] names = extDir.list();
for (int i = 0; i < names.length; i++) {
String name = names[i];
File jar = new File(extDir, name);
if (jar.isFile()) {
int length = name.length();
if (length > 4) {
String suffix = name.substring(length - 4);
if (suffix.equalsIgnoreCase(".zip") || suffix.equalsIgnoreCase(".jar")) { //$NON-NLS-1$ //$NON-NLS-2$
try {
IPath libPath = new Path(jar.getCanonicalPath());
LibraryLocation library = new LibraryLocation(libPath, Path.EMPTY, Path.EMPTY);
extensions.add(library);
} catch (IOException e) {
LaunchingPlugin.log(e);
}
}
}
}
}
}
return extensions;
}
/**
* Returns the default location of the extension directory, based on the given
* install location. The resulting file may not exist, or be <code>null</code>
* if an extension directory is not supported.
*
* @param installLocation
* @return default extension directory or <code>null</code>
*/
protected File getDefaultExtensionDirectory(File installLocation) {
File jre = null;
if (installLocation.getName().equalsIgnoreCase("jre")) { //$NON-NLS-1$
jre = installLocation;
} else {
jre = new File(installLocation, "jre"); //$NON-NLS-1$
}
File lib = new File(jre, "lib"); //$NON-NLS-1$
File ext = new File(lib, "ext"); //$NON-NLS-1$
return ext;
}
protected String getDefaultRootPath() {
return fDefaultRootPath;
}
protected void setDefaultRootPath(String defaultRootPath) {
fDefaultRootPath = defaultRootPath;
}
/**
* @see org.eclipse.jdt.launching.IVMInstallType#validateInstallLocation(java.io.File)
*/
public IStatus validateInstallLocation(File javaHome) {
IStatus status = null;
File javaExecutable = findJavaExecutable(javaHome);
if (javaExecutable == null) {
status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), 0, LaunchingMessages.getString("StandardVMType.Not_a_JDK_Root;_Java_executable_was_not_found_1"), null); //$NON-NLS-1$
} else {
if (canDetectDefaultSystemLibraries(javaHome, javaExecutable)) {
status = new Status(IStatus.OK, LaunchingPlugin.getUniqueIdentifier(), 0, LaunchingMessages.getString("StandardVMType.ok_2"), null); //$NON-NLS-1$
} else {
status = new Status(IStatus.ERROR, LaunchingPlugin.getUniqueIdentifier(), 0, LaunchingMessages.getString("StandardVMType.Not_a_JDK_root._System_library_was_not_found._1"), null); //$NON-NLS-1$
}
}
return status;
}
}
| [
"[email protected]"
]
| |
c72ba8b508779e88a7c94cae3517923825662afa | 7021c67b4afa3aa9b3fd0f94ec009e6b5628ee3b | /Expenses.AndroidClient/app/src/main/java/net/azurewebsites/expenses_by_klaudia/expensesapp/validation/BindRulesToActivityHelper.java | 072bacdd5447c307dbc66e87a650e89a5b5d8a52 | []
| no_license | klaudia-augustynska/expenses | f835e8a11967cabd41be4da99442b0cb3cb013ba | 0deb2a728daa2263df00ec54e135d1961d4959b8 | refs/heads/master | 2020-03-18T01:30:29.223466 | 2018-10-17T07:54:19 | 2018-10-17T07:54:19 | 134,145,042 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,011 | java | package net.azurewebsites.expenses_by_klaudia.expensesapp.validation;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import net.azurewebsites.expenses_by_klaudia.expensesapp.AddExpensesActivity;
import net.azurewebsites.expenses_by_klaudia.expensesapp.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class BindRulesToActivityHelper {
private HashMap<TextView, Function<String,ValidationResult>> mBindings;
private List<Function<Object,ValidationResult>> mCheckAfter;
private Button mButton;
private Context mContext;
public BindRulesToActivityHelper(Button button, Context context){
mBindings = new HashMap<>();
mCheckAfter = new ArrayList<>();
mButton = button;
mContext = context;
}
public void add(TextView textView, Function<String,ValidationResult> rules) {
textView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
validateForm(true);
}
});
// textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// @Override
// public void onFocusChange(View v, boolean hasFocus) {
// if (!hasFocus)
// validateForm(true);
// }
// });
mBindings.put(textView, rules);
}
public ValidationResult validateField(TextView textView, boolean showErrors) {
Function<String,ValidationResult> function = mBindings.get(textView);
ValidationResult validationResult = function.apply(textView.getText().toString());
if (showErrors){
textView.setError(null);
if (!validationResult.getSuccess()) {
textView.setError(validationResult.getErrorMsg());
}
}
return validationResult;
}
public void validateForm() {
validateForm(false);
}
public void validateForm(boolean showErrors) {
boolean success = true;
boolean allEmpty = true;
for (TextView key : mBindings.keySet()) {
key.setError(null);
if (!TextUtils.isEmpty(key.getText())) {
allEmpty = false;
break;
}
}
if (allEmpty)
showErrors = false;
for (TextView key : mBindings.keySet()) {
ValidationResult result = validateField(key, showErrors);
if (!result.getSuccess()) {
success = false;
if (!showErrors)
break;
}
}
if (success) {
mButton.setError(null);
if (mCheckAfter != null) {
for (Function<Object,ValidationResult> func : mCheckAfter) {
ValidationResult result = func.apply(null);
if (!result.getSuccess() && showErrors) {
success = false;
if (showErrors) {
mButton.setError(result.getErrorMsg());
Toast.makeText(mContext, result.getErrorMsg(), Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
mButton.setEnabled(success);
}
public void addRule(Function<Object,ValidationResult> func) {
mCheckAfter.add(func);
}
} | [
"[email protected]"
]
| |
595aae8e8b642c77b1012c794f45cbefc70c964c | ee9787624d9e36771af39e872ea472483c76239d | /src/main/java/com/nedap/archie/rules/evaluation/evaluators/functions/Max.java | 63047d3d9ca38236bea589438a94a9674b3d347a | [
"Apache-2.0"
]
| permissive | nedap/archie | 03f7401ec196fcba1ed3243d27e53c52ef9f4adf | 245d290e44e8f4969872a247dae3860304b4ae0b | refs/heads/master | 2021-01-17T20:02:14.383208 | 2019-07-11T12:55:50 | 2019-07-11T12:55:50 | 44,318,571 | 13 | 9 | Apache-2.0 | 2019-02-23T20:33:06 | 2015-10-15T13:16:16 | Java | UTF-8 | Java | false | false | 2,056 | java | package com.nedap.archie.rules.evaluation.evaluators.functions;
import com.nedap.archie.rules.PrimitiveType;
import com.nedap.archie.rules.evaluation.FunctionCallException;
import com.nedap.archie.rules.evaluation.FunctionImplementation;
import com.nedap.archie.rules.evaluation.Value;
import com.nedap.archie.rules.evaluation.ValueList;
import java.util.ArrayList;
import java.util.List;
import static com.nedap.archie.rules.evaluation.evaluators.FunctionUtil.castToDouble;
import static com.nedap.archie.rules.evaluation.evaluators.FunctionUtil.checkAndHandleNull;
import static com.nedap.archie.rules.evaluation.evaluators.FunctionUtil.checkEqualLength;
/**
* Created by pieter.bos on 07/04/2017.
*/
public class Max implements FunctionImplementation {
@Override
public String getName() {
return "max";
}
@Override
public ValueList evaluate(List<ValueList> arguments) throws FunctionCallException {
//if one of the values is null, return null.
ValueList possiblyNullResult = checkAndHandleNull(arguments);
if(possiblyNullResult != null) {
possiblyNullResult.setType(PrimitiveType.Real);
return possiblyNullResult;
}
//check that all valueList are equal length or 1 length
int length = checkEqualLength(arguments);
if(length == -1) {
throw new FunctionCallException("value lists of min operator not the same length");
}
ValueList result = new ValueList();
result.setType(PrimitiveType.Real);
for(int i = 0; i < length; i++) {
Double max = null;
List<String> paths = new ArrayList<>();
for(ValueList list: arguments) {
Value value = list.get(i);
if(!value.isNull() && ((max == null) || castToDouble(value) > max)) {
max = castToDouble(value);
}
paths.addAll(value.getPaths());
}
result.addValue(max, paths);
}
return result;
}
}
| [
"[email protected]"
]
| |
bb93ac26ef8ab214a9f921fd66d2756e636e0c3c | 461619a84c6617ceaf2b7913ef58c99ff32c0fb5 | /java/Button/Button/src/Button/Button/src/MainClass.java | 77d344d9b3234d5b638107fe9753fa3a1e94ccb3 | [
"MIT"
]
| permissive | bg1bgst333/Sample | cf066e48facac8ecd203c56665251fa1aa103844 | 298a4253dd8123b29bc90a3569f2117d7f6858f8 | refs/heads/master | 2023-09-02T00:46:31.139148 | 2023-09-01T02:41:42 | 2023-09-01T02:41:42 | 27,908,184 | 9 | 10 | MIT | 2023-09-06T20:49:55 | 2014-12-12T06:22:49 | Java | UTF-8 | Java | false | false | 2,384 | java | // パッケージ・クラスのインポート
import java.awt.Button; // Buttonクラス(java.awtパッケージ)
import java.awt.Frame; // Frameクラス(java.awtパッケージ)
import java.awt.event.WindowAdapter; // WindowAdapterクラス(java.awt.eventパッケージ)
import java.awt.event.WindowEvent; // WindowEventクラス(java.awt.eventパッケージ)
// メインクラス
public class MainClass { // MainClassの定義
// Javaのエントリポイント
public static void main(String[] args){ // mainメソッドの定義
// フレームの生成
Frame frame = new Frame(); // Frameオブジェクトを生成し, frameに格納.
// サイズのセット.
frame.setSize(640, 480); // setSizeでサイズを(640, 480)にセット.
// デフォルトのレイアウトを無効にする.
frame.setLayout(null); // frameにセットされている既定のレイアウトをsetLayout(null)で無効にする.
// ボタンの生成
Button button = new Button("button"); // "button"と表示するButtonオブジェクトを生成し, インスタンスをbuttonに格納.
// ボタンの位置とサイズをセット.
button.setBounds(200, 200, 120, 80); // button.setBoundsでボタンの位置を(200, 200), サイズを(120, 80)にセット.
// フレームにボタンを配置.
frame.add(button); // frame.addでbuttonを追加.
// 表示状態のセット.
frame.setVisible(true); // setVisibleで表示状態をtrueにセット.
// ウィンドウリスナーのセット.
frame.addWindowListener(new WindowAdapter(){ // WindowAdapterを継承した匿名クラスとしてアダプタを定義し, 引数としてaddWindowListenerに渡す.
// windowClosedとwindowClosingのみオーバーライド. それ以外はWindowAdapterに既定の動作が定義されている.
// ウィンドウが閉じられた時.
public void windowClosed(WindowEvent e){ // windowClosedの定義
// アプリケーションの終了
System.exit(0); // System.exit(0)でアプリケーションを終了.
}
// ウィンドウが閉じられている時.
public void windowClosing(WindowEvent e){ // windowClosingの定義
// ウィンドウリソースの開放
e.getWindow().dispose(); // e.getWindowでWindowが取得できるので, そのWindowをdisposeで破棄する.
}
});
}
} | [
"[email protected]"
]
| |
96a4b7b8d0b935cabfdc8f4c3be5f3ff1d6cd0b3 | e471c3990167e8674a943ad519cf33b3ef7a5c0f | /network/com/ankamagames/dofus/network/messages/game/context/mount/MountSetXpRatioRequestMessage.java | f2833e6199b6390e6b3a5a09bdfa326666d26875 | []
| no_license | Romain-P/Dofus-2.44.0-JProtocol | 379f4008acc5a15cd536ce2a23458f5a57348215 | db79dab05c3bacc6ec67b40d83741a16328a1fae | refs/heads/master | 2021-05-15T17:33:24.510521 | 2017-10-20T08:24:03 | 2017-10-20T08:24:03 | 107,510,404 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,089 | java | // Created by Heat the 2017-10-20 01:53:24+02:00
package com.ankamagames.dofus.network.messages.game.context.mount;
import org.heat.dofus.network.NetworkType;
import org.heat.dofus.network.NetworkMessage;
import org.heat.shared.io.DataWriter;
import org.heat.shared.io.DataReader;
import org.heat.shared.io.BooleanByteWrapper;
import com.ankamagames.dofus.network.InternalProtocolTypeManager;
@SuppressWarnings("all")
public class MountSetXpRatioRequestMessage extends NetworkMessage {
public static final int PROTOCOL_ID = 5989;
// i8
public byte xpRatio;
public MountSetXpRatioRequestMessage() {}
public MountSetXpRatioRequestMessage(byte xpRatio) {
this.xpRatio = xpRatio;
}
@Override
public int getProtocolId() {
return 5989;
}
@Override
public void serialize(DataWriter writer) {
writer.write_i8(this.xpRatio);
}
@Override
public void deserialize(DataReader reader) {
this.xpRatio = reader.read_i8();
}
@Override
public String toString() {
return "MountSetXpRatioRequestMessage(" + "xpRatio=" + this.xpRatio + ')';
}
}
| [
"[email protected]"
]
| |
42a717496e22559099e73be54df68b3fc395a7a5 | a3a64bb1a1548543fb124831af585cb63435f8d8 | /HeadFirstPatternStrategy/src/org/headfirst/pattern/Ducks/RubberDuck.java | a796696bbbf6e4275a6239c2c66ed5acbf5e3ef8 | []
| no_license | chinaq/HeadFirstPattern | 5316d3bdc244486f79f0b3c43ca13ec7b98324b7 | 6541e6554353e64c3f381b926190aa34ce73dcb0 | refs/heads/master | 2016-09-06T19:38:21.547406 | 2014-07-25T08:44:17 | 2014-07-25T08:44:17 | 22,244,749 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 356 | java | package org.headfirst.pattern.Ducks;
import org.headfirst.pattern.Flys.FlyNoWay;
import org.headfirst.pattern.Quacks.MuteQuack;
public class RubberDuck extends Duck {
public RubberDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new MuteQuack();
}
public void display() {
System.out.println("I'm a Rubber duck.");
}
}
| [
"[email protected]"
]
| |
a387521626f2824fb4039d14574caeecefbb07f4 | 6bf2ce7911aa086cbc3b8cd2e9d2c58252f2c283 | /AndroidApp/app/src/main/java/com/misrotostudio/www/myapplication/helper/EditTextCustom.java | daa05d91a6db2f1cff4904b2ca5f562f0c76c249 | []
| no_license | Nanakix/Allert | 1437464c2dd2997a01f079da17f0237f21c30c55 | c6846fb4bdffd2391f70a517a342570ea7309ae8 | refs/heads/master | 2021-01-10T15:52:08.072557 | 2016-01-11T20:48:42 | 2016-01-11T20:48:42 | 47,363,549 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 862 | java | package com.misrotostudio.www.myapplication.helper;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
/**
* Created by othmaneelmassari on 04/12/2015.
*/
public class EditTextCustom extends EditText{
public EditTextCustom(Context context) {
super(context);
}
public EditTextCustom(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditTextCustom(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_ENTER)
{
// Just ignore the [Enter] key
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| [
"[email protected]"
]
| |
db9b65416ad1a8b9c91d8a8f4bda036315628b01 | 10048a9f869261fc568f94a050be453b9770b83d | /resources/src/main/java/com/infra/resources/adapter/gateway/deployment/DeploymentGateway.java | 09b4e36bdba2c63ff88581894181417fcc6bf3a2 | []
| no_license | hmalatini/microservices-infrastructure | be765a313c8c9ba687d4099a72d7f2b670c608e3 | 2e4a36478db9965186264c7e9fb8e3f393ab5107 | refs/heads/main | 2023-06-15T11:32:20.101064 | 2021-07-09T14:36:34 | 2021-07-09T14:36:34 | 371,738,292 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,118 | java | package com.infra.resources.adapter.gateway.deployment;
import com.infra.resources.adapter.controller.environment.dto.EnvironmentCreation;
import com.infra.resources.adapter.gateway.deployment.client.DeploymentClient;
import com.infra.resources.adapter.gateway.deployment.dto.Deployment;
import com.infra.resources.adapter.gateway.deployment.mapper.DeploymentMapper;
import com.infra.resources.core.domain.Microservice;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@RequiredArgsConstructor
@Component
public class DeploymentGateway {
private final DeploymentClient deploymentClient;
public void createDeploymentFiles(Microservice microservice, EnvironmentCreation environment) {
Deployment deployment = DeploymentMapper.getDeploymentFromMicroserviceAndEnvironment(microservice, environment);
deploymentClient.createDeploymentFiles(deployment);
}
public void updateConfig(String microserviceName, String environmentName, String description) {
deploymentClient.UpdateConfig(microserviceName, environmentName, description);
}
}
| [
"[email protected]"
]
| |
89bbe850b96e8dd515121f3c3129f05272b0ab62 | 4c6596bdef4f1bdf94f4d6c9ca8bbbf4e1bd5295 | /TicketPurchase/src/main/java/com/revature/aspect/LoggingAspect.java | e0a798f2157631aa83f41f2c59a3c412978cb99f | []
| no_license | 2102Mule-Nick/gael_gohoungo_p1 | 8985d8ff103c498f0e5c347c26e0fb534253dae2 | 43130eeabd92c69e477805664151265a4d940cd6 | refs/heads/main | 2023-03-20T19:38:50.352476 | 2021-03-19T03:38:55 | 2021-03-19T03:38:55 | 348,547,126 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,789 | java | package com.revature.aspect;
import java.util.Arrays;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.revature.pojo.User;
@Component
@Aspect
public class LoggingAspect {
private Logger log;
public Logger getLog() {
return log;
}
@Autowired
public void setLog(Logger log) {
this.log = log;
}
@Pointcut("execution(public * com.revature.service.AuthServiceImpl.*(..))")
public void pointcutForAllMethods() {
//Hook - empty method to hold an annotation
}
/*
* @Before("execution(* com.revature.service.AuthServiceImpl.authenticateUser(..))"
* ) public void logBeforeAuthServiceMethods(JoinPoint jp) { String methodName =
* jp.getSignature().getName(); log.trace("Just called AuthService " +
* methodName + " Method"); }
*/
@Around("pointcutForAllMethods()")
public Object loggingAllAdvice(ProceedingJoinPoint pjp) throws Throwable {
log.trace("Method called: "+ pjp.getSignature().getClass() + "." + pjp.getSignature().getName());
log.trace("Real class: " + pjp.getTarget().getClass());
log.info("Parameters passed: " + Arrays.toString(pjp.getArgs()));
Object returnObject = pjp.proceed();
log.trace("Value returned: " + returnObject);
if (returnObject instanceof User) {
User returnUser = (User)returnObject;
returnUser.setPassword("*********");
log.info("User password being hidden.");
return returnUser;
}
return returnObject;
}
} | [
"[email protected]"
]
| |
370326392af007aabca7e9bc7b19c17d0a3b67a0 | 5bd37ca010567d1917f07b540bf48a9c7057e2f3 | /src/mave/minecraftjs/material/JS_RedstoneWire.java | 5cf80987896a276bbfbb3a24faa0475915a3336b | []
| no_license | kestereverts/minecraft-javascript | 3fb8fe2edf1d3a737266010044847213ee874d8e | 88478746873ab899f0e7e7b3117ccb8713f9e314 | refs/heads/master | 2016-09-10T00:24:43.190387 | 2011-06-13T19:44:06 | 2011-06-13T19:44:06 | 1,884,381 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 651 | java | package mave.minecraftjs.material;
import mave.minecraftjs.MinecraftJS;
import org.bukkit.material.RedstoneWire;
import org.mozilla.javascript.*;
public class JS_RedstoneWire extends JS_MaterialData<RedstoneWire>
{
private static final long serialVersionUID = -4403484561023154666L;
public JS_RedstoneWire()
{
}
public void jsConstructor()
{
if (!MinecraftJS.m_bInternalConstruction)
{
throw Context.reportRuntimeError("This internal class cannot be instantiated");
}
}
@Override
public String getClassName()
{
return "RedstoneWire";
}
public final boolean jsGet_powered()
{
return getDelegate().isPowered();
}
}
| [
"[email protected]"
]
| |
ce0c2d9adb6b0202df5f3daf1763ff14b3a39769 | a9914626c19f4fbcb5758a1953a4efe4c116dfb9 | /L2JTW_Datapack_HighFive/dist/game/data/scripts/instances/ChamberOfDelusionNort/ChamberOfDelusionNort.java | 2f9d0cb2fbfca0e78803322e293ed4fa1f57231a | []
| no_license | mjsxjy/l2jtw_datapack | ba84a3bbcbae4adbc6b276f9342c248b6dd40309 | c6968ae0475a076080faeead7f94bda1bba3def7 | refs/heads/master | 2021-01-19T18:21:37.381390 | 2015-08-03T00:20:39 | 2015-08-03T00:20:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,191 | java | /**
* @author by d0S
*/
package instances.ChamberOfDelusionNort;
import com.l2jserver.gameserver.ai.CtrlIntention;
import com.l2jserver.gameserver.instancemanager.InstanceManager;
import com.l2jserver.gameserver.instancemanager.InstanceManager.InstanceWorld;
import com.l2jserver.gameserver.model.L2Party;
import com.l2jserver.gameserver.model.actor.L2Npc;
import com.l2jserver.gameserver.model.actor.L2Summon;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.model.quest.Quest;
import com.l2jserver.gameserver.model.quest.QuestState;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
import com.l2jserver.gameserver.util.Util;
import com.l2jserver.util.Rnd;
public class ChamberOfDelusionNort extends Quest
{
private class CDWorld extends InstanceWorld
{
private L2Npc manager,managera,managerb,managerc,managerd,managere,managerf,managerg,managerh,_aenkinel;
public CDWorld()
{
//InstanceManager.getInstance().super();
}
}
private static final String qn = "ChamberOfDelusionNort";
private static final int INSTANCEID = 130; // this is the client number
//NPCs
private static final int GKSTART = 32661;
private static final int GKFINISH = 32667;
private static final int AENKINEL = 25693;
private static final int ROOMRB = 4;
private int rb = 0;
private int a;
public int instId = 0;
private int b;
private int g = 0;
private int h = 0;
private int c;
private class teleCoord {int instanceId; int x; int y; int z;}
private static final int[][] TELEPORT =
{
{ -122368,-152624,-6752},
{ -122368,-153504,-6752},
{ -120496,-154304,-6752},
{ -120496,-155184,-6752},
{ -121440,-154688,-6752},
{ -121440,-151328,-6752},
{ -120496,-153008,-6752},
{ -122368,-154800,-6752},
{ -121440,-153008,-6752}
};
private boolean checkConditions(L2PcInstance player)
{
L2Party party = player.getParty();
if (party == null)
{
player.sendPacket(SystemMessage.getSystemMessage(2101));
return false;
}
if (party.getLeader() != player)
{
player.sendPacket(SystemMessage.getSystemMessage(2185));
return false;
}
for (L2PcInstance partyMember : party.getMembers())
{
if (partyMember.getLevel() < 80)
{
SystemMessage sm = SystemMessage.getSystemMessage(2097);
sm.addPcName(partyMember);
party.broadcastPacket(sm);
return false;
}
if (!Util.checkIfInRange(1000, player, partyMember, true))
{
SystemMessage sm = SystemMessage.getSystemMessage(2096);
sm.addPcName(partyMember);
party.broadcastPacket(sm);
return false;
}
}
return true;
}
private void teleportplayer(L2PcInstance player, teleCoord teleto)
{
player.getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
player.setInstanceId(teleto.instanceId);
player.teleToLocation(teleto.x, teleto.y, teleto.z);
return;
}
private void teleportrnd(L2PcInstance player, CDWorld world)
{
int tp = Rnd.get(TELEPORT.length);
if (rb == 1 && tp == ROOMRB)
{
tp = Rnd.get(TELEPORT.length);
for (int i = 0; i < TELEPORT.length; i++)
{
if (i == tp)
{
for (L2PcInstance partyMember : player.getParty().getMembers())
{
partyMember.getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
partyMember.setInstanceId(instId);
partyMember.teleToLocation(TELEPORT[i][0], TELEPORT[i][1], TELEPORT[i][2]);
}
}
}
a = player.getX();
b = player.getY();
c = player.getZ();
}
else
{
for (int i = 0; i < TELEPORT.length; i++)
{
if (i == tp)
{
for (L2PcInstance partyMember : player.getParty().getMembers())
{
partyMember.getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
partyMember.setInstanceId(instId);
partyMember.teleToLocation(TELEPORT[i][0], TELEPORT[i][1], TELEPORT[i][2]);
}
}
}
a = player.getX();
b = player.getY();
c = player.getZ();
}
return;
}
protected void spawnState(CDWorld world)
{
world._aenkinel = addSpawn(AENKINEL,-121463,-155094,-6752,0,false,0,false,world.instanceId);
world._aenkinel.setIsNoRndWalk(false);
world.manager = addSpawn(32667,-121440,-154688,-6752,0,false,0,false,world.instanceId);
world.manager.setIsNoRndWalk(true);
world.managerb = addSpawn(32667,-122368,-153504,-6752,0,false,0,false,world.instanceId);
world.managerb.setIsNoRndWalk(true);
world.managerc = addSpawn(32667,-120496,-154304,-6752,0,false,0,false,world.instanceId);
world.managerc.setIsNoRndWalk(true);
world.managerd = addSpawn(32667,-120496,-155184,-6752,0,false,0,false,world.instanceId);
world.managerd.setIsNoRndWalk(true);
world.managere = addSpawn(32667,-121440,-151328,-6752,0,false,0,false,world.instanceId);
world.managere.setIsNoRndWalk(true);
world.managerf = addSpawn(32667,-120496,-153008,-6752,0,false,0,false,world.instanceId);
world.managerf.setIsNoRndWalk(true);
world.managerg = addSpawn(32667,-122368,-154800,-6752,0,false,0,false,world.instanceId);
world.managerg.setIsNoRndWalk(true);
world.managerh = addSpawn(32667,-121440,-153008,-6752,0,false,0,false,world.instanceId);
world.managerh.setIsNoRndWalk(true);
world.managera = addSpawn(32667,-122368,-152624,-6752,0,false,0,false,world.instanceId);
world.managera.setIsNoRndWalk(true);
}
protected int enterInstance(L2PcInstance player, String template)
{
int instanceId = 0;
//check for existing instances for this player
InstanceWorld world = InstanceManager.getInstance().getPlayerWorld(player);
//existing instance
if (world != null)
{
if (!(world instanceof CDWorld))
{
player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.ALREADY_ENTERED_ANOTHER_INSTANCE_CANT_ENTER));
return 0;
}
teleCoord tele = new teleCoord();
tele.x = a;
tele.y = b;
tele.z = c;
tele.instanceId = world.instanceId;
teleportplayer(player,tele);
return instanceId;
}
//New instance
if (!checkConditions(player))
return 0;
L2Party party = player.getParty();
instanceId = InstanceManager.getInstance().createDynamicInstance(template);
world = new CDWorld();
world.instanceId = instanceId;
world.templateId = INSTANCEID;
world.status = 0;
InstanceManager.getInstance().addWorld(world);
_log.info("Chamber Of Delusion started " + template + " Instance: " + instanceId + " created by player: " + player.getName());
spawnState((CDWorld)world);
instId = world.instanceId;
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
world.allowed.add(partyMember.getObjectId());
}
return instanceId;
}
protected void exitInstance(L2PcInstance player, teleCoord tele)
{
player.setInstanceId(0);
player.teleToLocation(tele.x, tele.y, tele.z);
L2Summon pet = player.getPet();
if (pet != null)
{
pet.setInstanceId(0);
pet.teleToLocation(tele.x, tele.y, tele.z);
}
}
@SuppressWarnings("cast")
@Override
public String onAdvEvent (String event, L2Npc npc, L2PcInstance player)
{
InstanceWorld tmpworld = InstanceManager.getInstance().getPlayerWorld(player);
if (tmpworld instanceof CDWorld)
{
CDWorld world = (CDWorld) tmpworld;
L2Party party = player.getParty();
instId = player.getInstanceId();
if (event.equalsIgnoreCase("tproom"))
{
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
startQuestTimer("tproom1",480000,null,player);
h++;
}
else if (event.equalsIgnoreCase("tproom1"))
{
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
startQuestTimer("tproom2",480000,null,player);
h++;
}
else if (event.equalsIgnoreCase("tproom2"))
{
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
startQuestTimer("tproom3",480000,null,player);
h++;
}
else if (event.equalsIgnoreCase("tproom3"))
{
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
}
else if ("7".equalsIgnoreCase(event))
{
if (g == 0)
{
if (h == 0)
{
cancelQuestTimers("tproom");
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
startQuestTimer("tproom1",480000,null,player);
g = 1;
}
else if (h == 1)
{
cancelQuestTimers("tproom1");
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
startQuestTimer("tproom2",480000,null,player);
g = 1;
}
else if (h == 2)
{
cancelQuestTimers("tproom2");
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
startQuestTimer("tproom3",480000,null,player);
g = 1;
}
else if (h == 3)
{
cancelQuestTimers("tproom3");
for (L2PcInstance partyMember : party.getMembers())
{
teleportrnd(partyMember,(CDWorld)world);
}
g = 1;
}
}
}
}
return "";
}
public String onKill( L2Npc npc, L2PcInstance player)
{
int npcId = npc.getNpcId();
if (rb == 0 && npcId == AENKINEL)
{
_log.info("kill");
rb = 1;
}
return "";
}
@Override
public final String onFirstTalk (L2Npc npc, L2PcInstance player)
{
return npc.getNpcId() + ".htm";
}
@Override
public String onTalk (L2Npc npc, L2PcInstance player)
{
int npcId = npc.getNpcId();
QuestState st = player.getQuestState(qn);
if (st == null)
st = newQuestState(player);
if (npcId == GKSTART)
{
enterInstance(player,"ChamberofDelusionNort.xml");
startQuestTimer("tproom",480000,null,player);
return "";
}
else if (npcId == GKFINISH)
{
InstanceWorld world = InstanceManager.getInstance().getPlayerWorld(player);
world.allowed.remove(world.allowed.indexOf(player.getObjectId()));
teleCoord tele = new teleCoord();
tele.instanceId = 0;
tele.x = -114592;
tele.y = -152509;
tele.z = -6723;
cancelQuestTimers("tproom");
cancelQuestTimers("tproom1");
cancelQuestTimers("tproom2");
cancelQuestTimers("tproom3");
for (L2PcInstance partyMember : player.getParty().getMembers())
{
exitInstance(partyMember,tele);
}
}
return "";
}
public ChamberOfDelusionNort(int questId, String name, String descr)
{
super(questId, name, descr);
addStartNpc(GKSTART);
addTalkId(GKSTART);
addStartNpc(GKFINISH);
addFirstTalkId(GKFINISH);
addTalkId(GKFINISH);
addKillId(AENKINEL);
}
public static void main(String[] args)
{
new ChamberOfDelusionNort(-1,qn,"instances");
}
} | [
"rocknow@9bd44e3e-6552-0410-907e-a6ca40b856b6"
]
| rocknow@9bd44e3e-6552-0410-907e-a6ca40b856b6 |
8a33d5da1d57cd15bc421ce0056fd7adbc829fd7 | 349d2a156b8351a9da4c9532fb858eb4d2a851e1 | /src/main/java/Prosite.java | 82b8b5499075e81587b3b1fcd0a1fdc33941aecd | []
| no_license | magkwidz/Prosite | e53c1692198f7868d97a2debf1289d756cfc72bc | 04dea217fc9c9b103f1fc5fb57c6e46706a7f2cc | refs/heads/master | 2021-01-13T14:38:33.807101 | 2016-12-19T01:03:12 | 2016-12-19T01:03:12 | 76,723,802 | 0 | 0 | null | 2016-12-19T01:03:12 | 2016-12-17T12:50:09 | Java | UTF-8 | Java | false | false | 444 | java | import java.util.Collection;
class Prosite {
private final ProteinSearcher searcher;
private final ProteinParser parser;
Prosite(ProteinSearcher searcher, ProteinParser parser) {
this.searcher = searcher;
this.parser = parser;
}
Collection<Integer> searchIndex(String protein, String pattern) {
Sequence sequence = parser.parse(pattern);
return searcher.search(protein, sequence);
}
} | [
"[email protected]"
]
| |
e97eb2d5336bf8f4fc8b5083616d9bb402362de9 | a748317a02c0896c1298575ab237d4ee29c4f548 | /src/DAO/CoursDAO.java | 0b7be20bfbbb68f13f727b16774ea567438a2e7c | []
| no_license | Noonank/ProjetPOOJAVA | 0530d3ccbbc10983d459d2dccafcb534ed872699 | c7c4e445f8034e43555d29b83728e6b352513f97 | refs/heads/master | 2022-09-30T10:54:36.442599 | 2020-06-07T21:47:50 | 2020-06-07T21:47:50 | 267,959,213 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,249 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import modele.Cours;
/**
*
* @author noork
*/
public class CoursDAO extends DAO<Cours> {
public CoursDAO(Connection conn) {
super(conn);
}
public boolean create(Cours obj, Connection conn) throws SQLException {
String sql = "INSERT INTO cours(ID,Nom) VALUES ('" + obj.getId()+"','"+ obj.getNom();
conn.createStatement().executeUpdate(sql) ;
return false;
}
public boolean delete(Cours obj, Connection conn) throws SQLException {
String sql = " DELETE FROM cours WHERE Nom='" + obj.getNom() +"'";
conn.createStatement().executeUpdate(sql) ;
return false;
}
//ON ASSOCIE LE NOM DE DROIT DU TRAVAIL QUAND Nom
public boolean update(Cours obj, Connection conn) throws SQLException {
//String sql = "UPDATE cours SET Nom ='Droit du travail' WHERE"+ obj.getNom + " "();
String sql = "UPDATE cours SET Nom ='Droit du travail' WHERE"+ obj.getNom();
conn.createStatement().executeUpdate(sql) ;
return false;
}
@Override
public boolean create(Cours obj) {
return false;
}
@Override
public boolean delete(Cours obj) {
return false;
}
@Override
public boolean update(Cours obj) {
return false;
}
/**
*https://stackoverflow.com/questions/7886462/how-to-get-row-count-using-resultset-in-java
* @param conn
* @return
* @throws SQLException
*/
@Override
public int SizeTab(Connection conn){
ResultSet rs;
try {
rs = stDAO(conn).executeQuery("select * from cours");
int size = 0;
try {
rs.last();
size = rs.getRow();
rs.beforeFirst();
}
catch(Exception ex) {
return 0;
}
return size;
} catch (SQLException ex) {
Logger.getLogger(UtilisateurDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return 0;
}
@Override
public Cours find(int id) {
Cours cours = new Cours();
try {
Statement st = this.connect.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet result = st.executeQuery("SELECT * FROM cours WHERE ID = " + id);
if(result.first())
cours = new Cours(id, result.getString("Nom"));
} catch (SQLException e) {
e.printStackTrace();
}
return cours;
}
public static Cours find(int id, Connection conne) {
Cours cours = new Cours();
try {
Statement st = conne.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet result = st.executeQuery("SELECT * FROM cours WHERE ID = " + id);
if(result.first())
cours = new Cours(id, result.getString("Nom"));
} catch (SQLException e) {
e.printStackTrace();
}
return cours; }
} | [
"[email protected]"
]
| |
125dae01d7ff8be0f9eae7440ce3d9d1078b04b5 | 020765d9809f4276bdb03b3130ef27df4eda33cd | /structurizr-core/src/com/structurizr/view/ContainerView.java | 3f828efedcca44a948f4b7402364838818a8df18 | [
"Apache-2.0"
]
| permissive | devnoo/java | 258d17c5a63e3d65e7f0f3c80a59d96de02234f0 | 99aefa9ba2bba451d2f606a74e3ad9bdebf86f66 | refs/heads/master | 2021-01-18T15:14:59.370682 | 2016-03-30T13:04:33 | 2016-03-30T13:04:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,526 | java | package com.structurizr.view;
import com.structurizr.model.Container;
import com.structurizr.model.Element;
import com.structurizr.model.Person;
import com.structurizr.model.SoftwareSystem;
public class ContainerView extends StaticView {
ContainerView() {
}
ContainerView(SoftwareSystem softwareSystem, String description) {
super(softwareSystem, description);
}
@Override
public void add(SoftwareSystem softwareSystem) {
if (softwareSystem != null && !softwareSystem.equals(getSoftwareSystem())) {
addElement(softwareSystem, true);
}
}
/**
* Adds all containers in the software system to this view.
*/
public void addAllContainers() {
getSoftwareSystem().getContainers().forEach(this::add);
}
/**
* Adds an individual container to this view.
*
* @param container the Container to add
*/
public void add(Container container) {
addElement(container, true);
}
@Override
public String getName() {
return getSoftwareSystem().getName() + " - Containers";
}
@Override
public void addAllElements() {
addAllSoftwareSystems();
addAllPeople();
addAllContainers();
}
@Override
public void addNearestNeighbours(Element element) {
super.addNearestNeighbours(element, SoftwareSystem.class);
super.addNearestNeighbours(element, Person.class);
super.addNearestNeighbours(element, Container.class);
}
} | [
"[email protected]"
]
| |
acbf9f830b2bb10b16f5b1e305fb5f4370de5454 | c93c89a7963a656d4b1a5457bbcdb3c8b0e1a415 | /src/main/java/ru/turlyunef/core/MergeSort.java | 4ac7d94383a3569253ebeed4c2668e897027a01b | []
| no_license | PolnySkvorets/Task_2 | a7843c116f1e737e612ea16dcb5204d2dc1e9f59 | dd7237fe8a16498c7ef9049fb33703888bb9fb2d | refs/heads/master | 2020-05-01T09:28:31.995618 | 2019-03-24T09:16:06 | 2019-03-24T09:16:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,135 | java | package ru.turlyunef.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import static java.lang.Integer.parseInt;
public class MergeSort {
private static Logger log = LoggerFactory.getLogger(Handler.class);
//Merge two string arrays "a" and "b" into one array "result"
public static String[] doMerge(String[] a, String[] b, boolean sortingTypeIsDecrease, boolean fileTypeIsCharacters) {
String[] result = new String[a.length + b.length];
for (int i = 0, j = 0, k = 0; k < a.length + b.length; k++) {
if (i == a.length) {
result[k] = b[j];
j++;
} else if (j == b.length) {
result[k] = a[i];
i++;
} else if (fileTypeIsCharacters) { //Work with characters
if ((a[i].length() > 1) | ((b[j].length() > 1))) {
log.warn("The data in the line contains more than one character, sorting done by the first character in the string");
}
char aChar = a[i].charAt(0);
char bChar = b[j].charAt(0);
if (((int) aChar) >= ((int) bChar) ^ sortingTypeIsDecrease) {
result[k] = b[j];
j++;
} else {
result[k] = a[i];
i++;
}
} else { //Work with numbers
try {
parseInt(a[i]);
} catch (NumberFormatException e) {
log.warn("The data in file is not a number, " + e.getMessage() + ". It is changed to 0");
a[i] = "0";
}
try {
parseInt(b[j]);
} catch (NumberFormatException e) {
log.warn("The data in file is not a number, " + e.getMessage() + ". It is changed to 0");
b[j] = "0";
}
if ((parseInt(a[i]) >= parseInt(b[j])) ^ sortingTypeIsDecrease) {
result[k] = b[j];
j++;
} else {
result[k] = a[i];
i++;
}
}
}
return result;
}
//Sorting an unsorted array. It used the method doMerge for sorting
public static String[] doSort(String[] array, boolean sortingTypeIsDecrease, boolean fileTypeIsCharacters) {
if (array.length < 2) return array;
else {
int rightA = (int) array.length / 2 - 1; //right border of the first subarray "A"
int leftB = rightA + 1; //left border of the second subarray "B"
String A[] = new String[rightA + 1];
String B[] = new String[array.length - A.length];
A = Arrays.copyOfRange(array, 0, rightA + 1);
B = Arrays.copyOfRange(array, rightA + 1, array.length);
return doMerge(doSort(A, sortingTypeIsDecrease, fileTypeIsCharacters), doSort(B, sortingTypeIsDecrease, fileTypeIsCharacters), sortingTypeIsDecrease, fileTypeIsCharacters);
}
}
}
| [
"[email protected]"
]
| |
b0845af9ef5429cd4102f3e25cecdecff8d3e796 | e37f6346ff3732bfef29f2a5487bd5addc00c730 | /src/com/pojo/ReceiptPOJO.java | 312b982f593b9ce58f6420d5b5b2141fa770c490 | []
| no_license | jafrax/cps | 068c9adc379ed1e34c24d4f48410275b01be7f22 | 2cefc82e8e0858a32db93b673bce507ca7a6b31f | refs/heads/master | 2020-04-05T09:55:37.722535 | 2017-07-13T03:45:01 | 2017-07-13T03:45:01 | 81,633,574 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,386 | java | package com.pojo;
/**
* Created by faizal on 12/18/13.
*/
public class ReceiptPOJO {
private String internalNumber;
private String receiptNumber;
private String date;
private String providerCompanyName;
private String inputDate;
private String proposed;
public String getInternalNumber() {
return internalNumber;
}
public void setInternalNumber(String internalNumber) {
this.internalNumber = internalNumber;
}
public String getReceiptNumber() {
return receiptNumber;
}
public void setReceiptNumber(String receiptNumber) {
this.receiptNumber = receiptNumber;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getProviderCompanyName() {
return providerCompanyName;
}
public void setProviderCompanyName(String providerCompanyName) {
this.providerCompanyName = providerCompanyName;
}
public String getInputDate() {
return inputDate;
}
public void setInputDate(String inputDate) {
this.inputDate = inputDate;
}
public String getProposed() {
return proposed;
}
public void setProposed(String proposed) {
this.proposed = proposed;
}
}
| [
"[email protected]"
]
| |
240970db8b8f4656687c18f1c5973e9d342f270d | 812759f8552f95405d2462d26191af43d9956e66 | /facade/HardDrive.java | 775d77aa8868752c0cbc9fe2975b841e9c9529c9 | []
| no_license | dkuikka/suunnittelumallit | ad522753df1a82313279593b3fc5fa43b138de64 | 67169932dfbf6fc5c148c302d6f83c3361b42d08 | refs/heads/master | 2020-09-07T12:38:23.765092 | 2019-12-09T19:41:44 | 2019-12-09T19:41:44 | 220,783,542 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 367 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package facade;
/**
*
* @author user
*/
public class HardDrive {
public void read(long lba, int size) {
System.out.println("reading hard drive"); }
}
| [
"[email protected]"
]
| |
4d02a4cb7149e16df50fd4d76aad53519b5f2a3c | b476eeb45134ff7f5282e05c5d8d9b336f881583 | /shop/src/main/java/org/sky/check/action/BaseCheckPlanController.java | 731617e37811676c9d8712dffebcb86bdc393978 | []
| no_license | weifengxiang/shop | 0e735a7317abd3dbebcab737b2497e1e0f52591f | ee272af01415165f4f3da76c588f1e6c54dcff29 | refs/heads/master | 2022-12-22T04:10:34.564853 | 2019-11-21T13:56:03 | 2019-11-21T13:56:03 | 122,185,780 | 0 | 0 | null | 2022-12-16T09:45:15 | 2018-02-20T10:46:20 | JavaScript | UTF-8 | Java | false | false | 6,093 | java | package org.sky.check.action;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.sky.sys.action.BaseController;
import org.sky.sys.exception.ServiceException;
import org.sky.check.model.BaseCheckPlan;
import org.sky.check.model.BaseCheckPlanExample;
import org.sky.check.model.BaseCheckPlanExample.Criteria;
import org.sky.check.service.BaseCheckPlanService;
import org.sky.sys.utils.JsonUtils;
import org.sky.sys.utils.Page;
import org.sky.sys.utils.PageListData;
import org.sky.sys.utils.ResultData;
import org.sky.sys.utils.StringUtils;
import org.sky.sys.utils.TreeStru;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ModelAttribute;
@Controller
public class BaseCheckPlanController extends BaseController{
@Autowired
private BaseCheckPlanService basecheckplanService;
public BaseCheckPlanController() {
// TODO Auto-generated constructor stub
}
/**
*显示检查计划列表页面
**/
@RequestMapping(value = "/base/BaseCheckPlan/initBaseCheckPlanListPage", method = { RequestMethod.GET })
public String initBaseCheckPlanListPage(
HttpServletRequest request, HttpServletResponse response) {
return "jsp/check/listbasecheckplan";
}
/**
* 检查计划分页查询
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/base/BaseCheckPlan/getBaseCheckPlanByPage", method =RequestMethod.POST,produces = "application/json;charset=UTF-8")
public @ResponseBody String getBaseCheckPlanByPage(
HttpServletRequest request,
HttpServletResponse response){
String filter = request.getParameter("filter");
Map filterMap = JsonUtils.json2map(filter);
String sortfield=request.getParameter("sortfield");
Page p= super.getPage(request);
BaseCheckPlanExample pote= new BaseCheckPlanExample();
if(null!=filterMap){
pote.createCriteria();
pote.integratedQuery(filterMap);
}
if(!StringUtils.isNull(sortfield)){
pote.setOrderByClause(sortfield);
}
pote.setPage(p);
PageListData pageData = basecheckplanService.getBaseCheckPlanByPage(pote);
return JsonUtils.obj2json(pageData);
}
/**
* 检查计划商品门类树
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/base/BaseCheckPlan/getBaseCheckPlanCateTree", method =RequestMethod.POST,produces = "application/json;charset=UTF-8")
public @ResponseBody List<TreeStru> getBaseCheckPlanCateTree(HttpServletRequest request,
HttpServletResponse response){
String data= request.getParameter("data");
Map dataMap=null;
if(!StringUtils.isNull(data)){
dataMap = JsonUtils.json2map(data);
}
return basecheckplanService.getBaseCheckPlanCateTree(dataMap);
}
/**
*显示检查计划新增页面
**/
@RequestMapping(value = "/base/BaseCheckPlan/initAddBaseCheckPlanPage", method = { RequestMethod.GET })
public String initAddBaseCheckPlanPage(
HttpServletRequest request, HttpServletResponse response) {
return "jsp/check/editbasecheckplan";
}
/**
*显示检查计划修改页面
**/
@RequestMapping(value = "/base/BaseCheckPlan/initEditBaseCheckPlanPage", method = { RequestMethod.GET })
public String initEditBaseCheckPlanPage(
HttpServletRequest request, HttpServletResponse response) {
return "jsp/check/editbasecheckplan";
}
/**
*显示检查计划详细页面
**/
@RequestMapping(value = "/base/BaseCheckPlan/initDetailBaseCheckPlanPage", method = { RequestMethod.GET })
public String initDetailBaseCheckPlanPage(
HttpServletRequest request, HttpServletResponse response) {
return "jsp/check/detailbasecheckplan";
}
/**
*保存新增/修改检查计划
**/
@RequestMapping(value = "/base/BaseCheckPlan/saveAddEditBaseCheckPlan", method =RequestMethod.POST,produces = "application/json;charset=UTF-8")
public @ResponseBody String saveAddEditBaseCheckPlan(
HttpServletRequest request,
HttpServletResponse response){
ResultData rd= new ResultData();
try {
BaseCheckPlan edit = (BaseCheckPlan) getEntityBean(request,BaseCheckPlan.class);
basecheckplanService.saveAddEditBaseCheckPlan(edit);
rd.setCode(ResultData.code_success);
rd.setName("保存成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
rd.setCode(ResultData.code_error);
rd.setName("保存失败<br>"+e.getMessage());
}
return JsonUtils.obj2json(rd);
}
/**
*删除检查计划
**/
@RequestMapping(value = "/base/BaseCheckPlan/delBaseCheckPlan", method =RequestMethod.POST,produces = "application/json;charset=UTF-8")
public @ResponseBody String delBaseCheckPlan(
HttpServletRequest request,
HttpServletResponse response){
ResultData rd= new ResultData();
try {
String delRows=request.getParameter("delRows");
List de=JsonUtils.json2list(delRows, BaseCheckPlan.class);
basecheckplanService.delBaseCheckPlanById(de);
rd.setCode(ResultData.code_success);
rd.setName("删除成功");
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
rd.setCode(ResultData.code_error);
rd.setName("删除失败<br>"+e.getMessage());
}
return JsonUtils.obj2json(rd);
}
/**
*根据主键查询检查计划
**/
@RequestMapping(value = "/base/BaseCheckPlan/getBaseCheckPlanById", method =RequestMethod.GET,produces = "application/json;charset=UTF-8")
public @ResponseBody String getBaseCheckPlanById(
HttpServletRequest request,
HttpServletResponse response){
String id = request.getParameter("id");
BaseCheckPlan bean = basecheckplanService.getBaseCheckPlanById(id);
return JsonUtils.obj2json(bean);
}
} | [
"weifx@LAPTOP-TMI3P0LS"
]
| weifx@LAPTOP-TMI3P0LS |
40ac17e70c39bed05cd5501ddacf25485510536f | 342906d8cb9643307e17a12023a61331939e9293 | /src/sample/Controllers/ConfigurationController.java | 1fc8d737186cca83ca9465069b397564cc6c9e31 | []
| no_license | karimaxov/Transit_Facturation_Mangment_System | 05126ffe11dca25d07d783b78e66604dcde51290 | b97706619895e0c587056a025449c31ad90354f3 | refs/heads/master | 2021-07-23T17:13:35.186654 | 2017-11-02T16:52:29 | 2017-11-02T16:52:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,489 | java | package sample.Controllers;
import com.jfoenix.controls.*;
import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.stage.Stage;
import javafx.util.Callback;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
public class ConfigurationController implements Initializable{
Connection conn = null;
Statement stmt =null;
// JDBC driver name and database URL
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
ObservableList<Camion> camionList=null;
ObservableList<Chauffeur> chauffeurList=null;
ObservableList<Douane> douaneList=null;
public ObservableList<Chauffeur> getChauffeurList()
{
ObservableList<Chauffeur> ch= FXCollections.observableArrayList();
try
{String sqll="select idChauffeur,nom,numero from chauffeur";
ResultSet res;
Statement stmt=conn.createStatement();
res=stmt.executeQuery(sqll);
Chauffeur chauffeur;
while(res.next())
{
chauffeur= new Chauffeur();
chauffeur.id=new SimpleStringProperty(String.valueOf(res.getInt("idChauffeur")));
chauffeur.nom=new SimpleStringProperty(res.getString("nom"));
chauffeur.tel=new SimpleStringProperty(String.valueOf(res.getInt("numero")));
ch.add(chauffeur);
}}
catch (SQLException ex) {
}
return ch;
}
@FXML
private JFXTextField fraisDos;
@FXML
private JFXTextField suivi;
@FXML
private JFXTextField manutention;
@FXML
private JFXTextField transport;
@FXML
private JFXTextField immo;
@FXML
private JFXTextField dech20;
@FXML
private JFXTextField dech40;
@FXML
private JFXTextField accesCam;
@FXML
private JFXTextField vis20;
@FXML
private JFXTextField vis40;
@FXML
private JFXTextField visD20;
@FXML
private JFXTextField visD40;
@FXML
private JFXTextField char20;
@FXML
private JFXTextField char40;
@FXML
private JFXTextField mag120;
@FXML
private JFXTextField mag140;
@FXML
private JFXTextField mag220;
@FXML
private JFXTextField mag240;
@FXML
private JFXTextField tel;
@FXML
private JFXTextField fraisExpertise;
@FXML
private JFXTextField magPort;
@FXML
private JFXTextField scanner;
@FXML
private JFXTextField plombage;
@FXML
private JFXTreeTableView<Chauffeur> tableChauffeur;
@FXML
private JFXTreeTableView<Camion> tableCamion;
@FXML
private JFXTextField nomChauffeur;
@FXML
private JFXTextField numChauffeur;
@FXML
private JFXTextField nomAgentField;
@FXML
private JFXTextField badgeField;
@FXML
private JFXButton ajouterCamion;
@FXML
private JFXButton supprimerCamion;
@FXML
private JFXTextField matricule;
@FXML
private JFXButton ajouter;
@FXML
private JFXButton ajour;
@FXML
private JFXTreeTableView<Douane> tableDouane;
@FXML
private JFXButton supprimer;
@FXML
private JFXButton clear;
@FXML
private JFXButton ajouterdouane;
@FXML
private JFXButton supprimerdouane;
static Stage menu,current;
static public void getStage(Stage menuu,Stage currentt)
{
menu=menuu;
current=currentt;
}
boolean recherche(String s)
{
for(int i=0;i<douaneList.size();i++)
{
if(douaneList.get(i).badge.get().equals(s))
{
return true;
}
}
return false;
}
@FXML
void ajouterdouane(ActionEvent event) {
if(!nomAgentField.getText().isEmpty() && !badgeField.getText().isEmpty())
{
try {
if(!recherche(badgeField.getText())) {
Statement s = conn.createStatement();
s.executeUpdate("INSERT into douane(nom,Badge) values('" + nomAgentField.getText() + "','" + badgeField.getText() + "')");
douaneList.add(new Douane(nomAgentField.getText(), badgeField.getText()));
tableDouane.getSelectionModel().select(null);
nomAgentField.clear();
badgeField.clear();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@FXML
void retour2(ActionEvent event) {
current.close();
System.out.print("retour");
menu.show();
}
@FXML
void supprimerdouane(ActionEvent event) {
try {
Statement s=conn.createStatement();
if(tableDouane.getSelectionModel()!=null)
{
Douane d=tableDouane.getSelectionModel().getSelectedItem().getValue();
s.executeUpdate("delete from douane where Badge='"+d.badge.get()+"'");
douaneList.remove(d);
tableDouane.getSelectionModel().select(null);
nomAgentField.clear();
badgeField.clear();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@FXML
void ajour(ActionEvent event) {
if(tableChauffeur.getSelectionModel().getSelectedItem()!=null && numChauffeur.getText().matches("[0-9]+"))
{
try {
Statement s=conn.createStatement();
s.executeUpdate("update chauffeur Set nom='"+nomChauffeur.getText()+"',numero='"+numChauffeur.getText()+"' where idChauffeur='"+tableChauffeur.getSelectionModel().getSelectedItem().getValue().id.get()+"'");
chauffeurList.get(tableChauffeur.getSelectionModel().getSelectedIndex()).tel.set(numChauffeur.getText());
chauffeurList.get(tableChauffeur.getSelectionModel().getSelectedIndex()).nom.set(nomChauffeur.getText());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@FXML
private JFXButton retour;
@FXML
void retour(ActionEvent event) {
current.close();
System.out.print("retour");
menu.show();
}
@FXML
void retour1(ActionEvent event) {
current.close();
System.out.print("retour");
menu.show();
}
@FXML
void appliquer(ActionEvent event) {
PrixUnitaires pu = new PrixUnitaires();
try {
pu.setAccesCam(new SimpleDoubleProperty(Double.parseDouble(accesCam.getText())));
pu.setVisite20(new SimpleDoubleProperty(Double.parseDouble(vis20.getText())));
pu.setVisite40(new SimpleDoubleProperty(Double.parseDouble(vis40.getText())));
pu.setVisD20(new SimpleDoubleProperty(Double.parseDouble(visD20.getText())));
pu.setVisD40(new SimpleDoubleProperty(Double.parseDouble(visD40.getText())));
pu.setCh20(new SimpleDoubleProperty(Double.parseDouble(char20.getText())));
pu.setCh40(new SimpleDoubleProperty(Double.parseDouble(char40.getText())));
pu.setDech20(new SimpleDoubleProperty(Double.parseDouble(dech20.getText())));
pu.setDech40(new SimpleDoubleProperty(Double.parseDouble(dech40.getText())));
pu.setMag120(new SimpleDoubleProperty(Double.parseDouble(mag120.getText())));
pu.setMag140(new SimpleDoubleProperty(Double.parseDouble(mag140.getText())));
pu.setMag220(new SimpleDoubleProperty(Double.parseDouble(mag220.getText())));
pu.setMag240(new SimpleDoubleProperty(Double.parseDouble(mag240.getText())));
pu.setManutention(new SimpleDoubleProperty(Double.parseDouble(manutention.getText())));
pu.setImmo(new SimpleDoubleProperty(Double.parseDouble(immo.getText())));
pu.setTransport(new SimpleDoubleProperty(Double.parseDouble(transport.getText())));
pu.setSuivi(new SimpleDoubleProperty(Double.parseDouble(suivi.getText())));
pu.setTel(new SimpleDoubleProperty(Double.parseDouble(tel.getText())));
pu.setMagPort(new SimpleDoubleProperty(Double.parseDouble(magPort.getText())));
pu.setScanner(new SimpleDoubleProperty(Double.parseDouble(scanner.getText())));
pu.setFraisExpertise(new SimpleDoubleProperty(Double.parseDouble(fraisExpertise.getText())));
pu.setFraisDos(new SimpleDoubleProperty(Double.parseDouble(fraisDos.getText())));
pu.setPlombage(new SimpleDoubleProperty(Double.parseDouble(plombage.getText())));
conn = (com.mysql.jdbc.Connection) DriverManager.getConnection(DB_CNX.getDbUrl(), DB_CNX.getUSER(), DB_CNX.getPASS());
stmt = conn.createStatement();
System.out.println(pu.getSuivi().getValue().toString());
String sql = "update prixunitaires set accesCamion="+ pu.getAccesCam().getValue().toString() + ",suivi ="+pu.getSuivi().getValue().toString()+",immobilisation ="+pu.getImmo().getValue().toString()+",manutention ="+pu.getManutention().getValue().toString()+",transport ="+pu.getTransport().getValue().toString()+",dechargement20 ="+pu.getDech20().getValue().toString()+",dechargement40 ="+pu.getDech40().getValue().toString()+",fraisDossier ="+pu.getFraisDos().getValue().toString()+",visite20 ="+pu.getVisite20().getValue().toString()+",visite40 ="+pu.getVisite40().getValue().toString()+",visDouane20 ="+pu.getVisD20().getValue().toString()+",visDouane40 ="+pu.getVisD40().getValue().toString()+",char20 ="+pu.getCh20().getValue().toString()+",char40 ="+pu.getCh40().getValue().toString()+",mag120 ="+pu.getMag120().getValue().toString()+",mag140 ="+pu.getMag140().getValue().toString()+",mag220 ="+pu.getMag220().getValue().toString()+",mag240 ="+pu.getMag240().getValue().toString()+",tel ="+pu.getTel().getValue().toString()+",fraisExpertise ="+pu.getFraisExpertise().getValue().toString()+ "where 1" ;
System.out.println(sql);
System.out.println(stmt.executeUpdate(sql));
ResultSet set=stmt.executeQuery("select * from prixunitaires ");
set.next();
int traite=set.getInt("traite");
String sql1;
System.out.println(sql);
if(traite==0 ) {
String noms = set.getString("userr");
sql1 = "update prixunitaires set userr='" + noms + ", " + MenuController.getUserName() + "',plombage =" + pu.getPlombage().getValue().toString() + ",magPort =" + pu.getMagPort().getValue().toString() + ",scanner =" + pu.getScanner().getValue().toString() + "where 1";
System.out.println(sql1);
}else{
sql1 = "update prixunitaires set traite='"+0+"',userr='"+ MenuController.getUserName() + "',plombage =" + pu.getPlombage().getValue().toString() + ",magPort =" + pu.getMagPort().getValue().toString() + ",scanner =" + pu.getScanner().getValue().toString() + "where 1";
}
System.out.println(stmt.executeUpdate(sql1));
}catch (SQLException e){System.out.println("exception");}
}
@FXML
void ajouter(ActionEvent event) {
if(!nomChauffeur.getText().isEmpty() && !numChauffeur.getText().isEmpty() && numChauffeur.getText().matches("[0-9]+"))
{
try {
Statement s=conn.createStatement();
s.executeUpdate("insert into chauffeur(nom,numero) values ('"+nomChauffeur.getText()+"','"+numChauffeur.getText()+"')",Statement.RETURN_GENERATED_KEYS);
//s=conn.createStatement();
ResultSet r=s.getGeneratedKeys();
// r.last();
int id=0;
while( r.next() )
{
id=r.getInt(1);
}
chauffeurList.add(new Chauffeur(String.valueOf(id),nomChauffeur.getText(),numChauffeur.getText()));
int i=0;
while(i<camionList.size())
{
Statement st=conn.createStatement();
st.executeUpdate("insert into camion(matricule,idChauffeur) values('"+camionList.get(i).matricule.get()+"','"+id+"')");
i++;
}
tableChauffeur.getSelectionModel().select(null);
camionList.clear();
nomChauffeur.clear();
numChauffeur.clear();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@FXML
void ajouterCamion(ActionEvent event) {
if(!matricule.getText().isEmpty())
{
try {
Statement s=conn.createStatement();
camionList.add(new Camion(matricule.getText()));
if(tableChauffeur.getSelectionModel().getSelectedItem()!=null) {
s.executeUpdate("INSERT into camion(matricule,idChauffeur) values ('" + matricule.getText() + "','" + Integer.parseInt(tableChauffeur.getSelectionModel().getSelectedItem().getValue().id.get()) + "')");
}
matricule.clear();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@FXML
void clear(ActionEvent event) {
nomChauffeur.clear();
numChauffeur.clear();
matricule.clear();
camionList.clear();
tableChauffeur.getSelectionModel().select(null);
tableCamion.getSelectionModel().select(null);
}
@FXML
void supprimer(ActionEvent event) {
if(tableChauffeur.getSelectionModel().getSelectedItem()!=null)
{
Chauffeur c=tableChauffeur.getSelectionModel().getSelectedItem().getValue();
try {
Statement st=conn.createStatement();
st.executeUpdate("delete from chauffeur where numero='"+c.tel.get()+"'");
chauffeurList.remove(c);
tableChauffeur.getSelectionModel().select(null);
camionList.clear();
nomChauffeur.clear();
numChauffeur.clear();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@FXML
void supprimerCamion(ActionEvent event) {
if(tableCamion.getSelectionModel().getSelectedItem()!=null) {
Camion cam = tableCamion.getSelectionModel().getSelectedItem().getValue();
if (cam != null) {
try {
Statement s = conn.createStatement();
s.executeUpdate("delete from camion where matricule='" + cam.matricule.get() + "'");
camionList.remove(cam);
matricule.clear();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
menu.close();
try { Class.forName("com.mysql.jdbc.Driver");
conn = (com.mysql.jdbc.Connection) DriverManager.getConnection(DB_CNX.getDbUrl(), DB_CNX.getUSER(), DB_CNX.getPASS());
stmt = (Statement) conn.createStatement();}
catch (ClassNotFoundException ex) {
}catch (SQLException ex) {
}
camionList=FXCollections.observableArrayList();
chauffeurList=getChauffeurList();
// System.out.println(chauffeurList.get(0).nom.get());
JFXTreeTableColumn<Chauffeur,String> user=new JFXTreeTableColumn<>("Chauffeur");
user.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Chauffeur, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Chauffeur, String> param) {
return param.getValue().getValue().nom;
}
});
JFXTreeTableColumn<Chauffeur,String> pass=new JFXTreeTableColumn<>("Numero de telephone");
pass.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Chauffeur, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Chauffeur, String> param) {
return param.getValue().getValue().tel;
}
});
JFXTreeTableColumn<Chauffeur,String> idd=new JFXTreeTableColumn<>("id");
idd.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Chauffeur, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Chauffeur, String> param) {
return param.getValue().getValue().id;
}
});
user.setPrefWidth(136);
pass.setPrefWidth(136);
idd.setPrefWidth(60);
final TreeItem<Chauffeur> root =new RecursiveTreeItem<Chauffeur>(chauffeurList, RecursiveTreeObject::getChildren);
tableChauffeur.getColumns().addAll(idd,user,pass);
tableChauffeur.setRoot(root);
tableChauffeur.setShowRoot(false);
JFXTreeTableColumn<Camion,String> cam=new JFXTreeTableColumn<>("Matricule");
cam.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Camion, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Camion, String> param) {
return param.getValue().getValue().matricule;
}
});
cam.setPrefWidth(248);
final TreeItem<Camion> root2 =new RecursiveTreeItem<Camion>(camionList, RecursiveTreeObject::getChildren);
tableCamion.getColumns().add(cam);
tableCamion.setRoot(root2);
tableCamion.setShowRoot(false);
douaneList=FXCollections.observableArrayList();
JFXTreeTableColumn<Douane,String> nomAgent=new JFXTreeTableColumn<>("Nom de l'agent");
nomAgent.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Douane, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Douane, String> param) {
return param.getValue().getValue().nomAgent;
}
});
JFXTreeTableColumn<Douane,String> badge=new JFXTreeTableColumn<>("Badge");
badge.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Douane, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Douane, String> param) {
return param.getValue().getValue().badge;
}
});
final TreeItem<Douane> root3 =new RecursiveTreeItem<Douane>(douaneList, RecursiveTreeObject::getChildren);
tableDouane.getColumns().addAll(nomAgent,badge);
tableDouane.setRoot(root3);
tableDouane.setShowRoot(false);
try {
Statement sd=conn.createStatement();
ResultSet set=sd.executeQuery("select nom,Badge from douane");
while(set.next())
{
douaneList.add(new Douane(set.getString("nom"),set.getString("Badge")));
}
} catch (SQLException e) {
e.printStackTrace();
}
tableChauffeur.getSelectionModel().selectedItemProperty().addListener((Observable, oldValue, newValue)
-> {
if(newValue!=null) {
try {
nomChauffeur.setText(newValue.getValue().nom.get());
numChauffeur.setText(newValue.getValue().tel.get());
String sql="select matricule from camion where idChauffeur='"+newValue.getValue().id.get()+"'";
Statement st=conn.createStatement();
ResultSet s=st.executeQuery(sql);
Camion camion;
camionList.clear();
while(s.next())
{
camion=new Camion();
camion.matricule=new SimpleStringProperty(s.getString("matricule"));
camionList.add(camion);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (com.mysql.jdbc.Connection) DriverManager.getConnection(DB_CNX.getDbUrl(), DB_CNX.getUSER(), DB_CNX.getPASS());
stmt = (java.sql.Statement) conn.createStatement();
Class.forName(JDBC_DRIVER);
conn =(com.mysql.jdbc.Connection) DriverManager.getConnection(DB_CNX.getDbUrl(), DB_CNX.getUSER(), DB_CNX.getPASS());
String sql = "select fraisDossier,suivi,transport,immobilisation,manutention,mag120,mag140,mag220,mag240,dechargement20,dechargement40,visite20,visite40,visDouane20,visDouane40,char20,char40,tel,fraisExpertise,accesCamion,magPort,scanner,plombage from prixunitaires ";
ResultSet res;
stmt = conn.createStatement();
res = stmt.executeQuery(sql);
res.next();
fraisDos.setText(res.getString("fraisDossier"));
suivi.setText(res.getString("suivi"));
manutention.setText(res.getString("manutention"));
transport.setText(res.getString("transport"));
immo.setText(res.getString("immobilisation"));
vis20.setText(res.getString("visite20"));
vis40.setText(res.getString("visite40"));
visD20.setText(res.getString("visDouane20"));
visD40.setText(res.getString("visDouane40"));
char20.setText(res.getString("char20"));
char40.setText(res.getString("char40"));
dech20.setText(res.getString("dechargement20"));
dech40.setText(res.getString("dechargement40"));
accesCam.setText(res.getString("accesCamion"));
mag120.setText(res.getString("mag120"));
mag140.setText(res.getString("mag140"));
mag220.setText(res.getString("mag220"));
mag240.setText(res.getString("mag240"));
tel.setText(res.getString("tel"));
fraisExpertise.setText(res.getString("fraisExpertise"));
scanner.setText(res.getString("scanner"));
magPort.setText(res.getString("magPort"));
plombage.setText(res.getString("plombage"));
} catch (SQLException e) {
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ajouterdouane.setTooltip(new Tooltip("Entrer le nom et le badge du declarant puis cliquer sur moi"));
supprimerdouane.setTooltip(new Tooltip("Selectionner une ligne de la table puis cliquer sur moi pour supprimer ce declarant"));
ajour.setTooltip(new Tooltip("Selectioner une ligne de la table est modifier le numero du chauffeur ou bien supprimer/ajouter des camion (a gauche) puis cliquer sur moi"));
ajouter.setTooltip(new Tooltip("Entrer un nouveau chauffeur avec ces camions puis cliquer sur moi "));
ajouterCamion.setTooltip(new Tooltip("Ajouter le matricule du camion"));
ajouterCamion.setTooltip(new Tooltip("selectionner un camion pour le supprimer"));
clear.setTooltip(new Tooltip("vider tout les champs pour pouvoir entrer un nouveau chauffeur"));
}
class Douane extends RecursiveTreeObject<Douane>{
StringProperty nomAgent=new SimpleStringProperty();
StringProperty badge=new SimpleStringProperty();
public Douane(String nomAgent, String badge) {
this.nomAgent.set(nomAgent);
this.badge.set(badge);
}
}
}
| [
"[email protected]"
]
| |
edd2f3f8444383669f0bd4091a1407e4d637a214 | 6696a0d6ecfb354f6b8b60171e91abd55c5ee6a5 | /spring-boot-multi-datasource-demo/src/main/java/com/mytest/demo/entity/db2/Country.java | 95423fc450fb00e87f7026ad6afe4f5028131ce9 | []
| no_license | lyz170/spring-boot-demo | 174e17ad03edddbb0825b56701da4420933b5916 | bf3f3c33547e78440df0aa1dd08d062c9c4b4e74 | refs/heads/master | 2020-03-20T10:03:35.009822 | 2018-08-01T14:59:29 | 2018-08-01T14:59:29 | 137,357,675 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,369 | java | package com.mytest.demo.entity.db2;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class Country implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 32, nullable = false)
private String name;
@Column(nullable = false)
private Double area;
@Column(length = 32, nullable = false)
private String capital;
public Country() {
}
public Country(String name, Double area, String capital) {
super();
this.name = name;
this.area = area;
this.capital = capital;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getArea() {
return area;
}
public void setArea(Double area) {
this.area = area;
}
public String getCapital() {
return capital;
}
public void setCapital(String capital) {
this.capital = capital;
}
@Override
public String toString() {
return "Country [id=" + id + ", name=" + name + ", area=" + area + ", capital=" + capital + "]";
}
}
| [
"[email protected]"
]
| |
9b7b63c4fe37ad08627809064e9cfb401ecaa781 | db206e419e92711c0ad9f61e842f0f030485e0ce | /server/common/thrift/src/main/thrift-java/org/kaaproject/kaa/server/common/thrift/gen/operations/UserRouteInfo.java | 792765cccfe447373a0108feb8d847f58bba0388 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | pushdown99/kaa-iot | a4526f55673b1c8e6912c5eb00a14c8641166deb | c3bdc44ca35fa0eae892256e2bf7edcb90f7b7ed | refs/heads/master | 2022-11-30T10:33:02.504741 | 2019-11-18T03:10:15 | 2019-11-18T03:10:15 | 220,415,693 | 1 | 0 | Apache-2.0 | 2022-11-24T04:46:38 | 2019-11-08T07:55:34 | HTML | UTF-8 | Java | false | true | 22,863 | java | /**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*
* @generated
*/
package org.kaaproject.kaa.server.common.thrift.gen.operations;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2016-4-19")
public class UserRouteInfo implements org.apache.thrift.TBase<UserRouteInfo, UserRouteInfo._Fields>, java.io.Serializable, Cloneable, Comparable<UserRouteInfo> {
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("UserRouteInfo");
private static final org.apache.thrift.protocol.TField USER_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("userId", org.apache.thrift.protocol.TType.STRING, (short) 1);
private static final org.apache.thrift.protocol.TField TENANT_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("tenantId", org.apache.thrift.protocol.TType.STRING, (short) 2);
private static final org.apache.thrift.protocol.TField OPERATIONS_SERVER_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("operationsServerId", org.apache.thrift.protocol.TType.STRING, (short) 3);
private static final org.apache.thrift.protocol.TField UPDATE_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("updateType", org.apache.thrift.protocol.TType.I32, (short) 4);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new UserRouteInfoStandardSchemeFactory());
schemes.put(TupleScheme.class, new UserRouteInfoTupleSchemeFactory());
}
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.USER_ID, new org.apache.thrift.meta_data.FieldMetaData("userId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING, "user_id")));
tmpMap.put(_Fields.TENANT_ID, new org.apache.thrift.meta_data.FieldMetaData("tenantId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING, "tenant_id")));
tmpMap.put(_Fields.OPERATIONS_SERVER_ID, new org.apache.thrift.meta_data.FieldMetaData("operationsServerId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.UPDATE_TYPE, new org.apache.thrift.meta_data.FieldMetaData("updateType", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, EventRouteUpdateType.class)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(UserRouteInfo.class, metaDataMap);
}
public String userId; // required
public String tenantId; // required
public String operationsServerId; // required
/**
* @see EventRouteUpdateType
*/
public EventRouteUpdateType updateType; // required
public UserRouteInfo() {
}
public UserRouteInfo(
String userId,
String tenantId,
String operationsServerId,
EventRouteUpdateType updateType) {
this();
this.userId = userId;
this.tenantId = tenantId;
this.operationsServerId = operationsServerId;
this.updateType = updateType;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public UserRouteInfo(UserRouteInfo other) {
if (other.isSetUserId()) {
this.userId = other.userId;
}
if (other.isSetTenantId()) {
this.tenantId = other.tenantId;
}
if (other.isSetOperationsServerId()) {
this.operationsServerId = other.operationsServerId;
}
if (other.isSetUpdateType()) {
this.updateType = other.updateType;
}
}
public UserRouteInfo deepCopy() {
return new UserRouteInfo(this);
}
@Override
public void clear() {
this.userId = null;
this.tenantId = null;
this.operationsServerId = null;
this.updateType = null;
}
public String getUserId() {
return this.userId;
}
public UserRouteInfo setUserId(String userId) {
this.userId = userId;
return this;
}
public void unsetUserId() {
this.userId = null;
}
/**
* Returns true if field userId is set (has been assigned a value) and false otherwise
*/
public boolean isSetUserId() {
return this.userId != null;
}
public void setUserIdIsSet(boolean value) {
if (!value) {
this.userId = null;
}
}
public String getTenantId() {
return this.tenantId;
}
public UserRouteInfo setTenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
public void unsetTenantId() {
this.tenantId = null;
}
/**
* Returns true if field tenantId is set (has been assigned a value) and false otherwise
*/
public boolean isSetTenantId() {
return this.tenantId != null;
}
public void setTenantIdIsSet(boolean value) {
if (!value) {
this.tenantId = null;
}
}
public String getOperationsServerId() {
return this.operationsServerId;
}
public UserRouteInfo setOperationsServerId(String operationsServerId) {
this.operationsServerId = operationsServerId;
return this;
}
public void unsetOperationsServerId() {
this.operationsServerId = null;
}
/**
* Returns true if field operationsServerId is set (has been assigned a value) and false otherwise
*/
public boolean isSetOperationsServerId() {
return this.operationsServerId != null;
}
public void setOperationsServerIdIsSet(boolean value) {
if (!value) {
this.operationsServerId = null;
}
}
/**
* @see EventRouteUpdateType
*/
public EventRouteUpdateType getUpdateType() {
return this.updateType;
}
/**
* @see EventRouteUpdateType
*/
public UserRouteInfo setUpdateType(EventRouteUpdateType updateType) {
this.updateType = updateType;
return this;
}
public void unsetUpdateType() {
this.updateType = null;
}
/**
* Returns true if field updateType is set (has been assigned a value) and false otherwise
*/
public boolean isSetUpdateType() {
return this.updateType != null;
}
public void setUpdateTypeIsSet(boolean value) {
if (!value) {
this.updateType = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case USER_ID:
if (value == null) {
unsetUserId();
} else {
setUserId((String) value);
}
break;
case TENANT_ID:
if (value == null) {
unsetTenantId();
} else {
setTenantId((String) value);
}
break;
case OPERATIONS_SERVER_ID:
if (value == null) {
unsetOperationsServerId();
} else {
setOperationsServerId((String) value);
}
break;
case UPDATE_TYPE:
if (value == null) {
unsetUpdateType();
} else {
setUpdateType((EventRouteUpdateType) value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case USER_ID:
return getUserId();
case TENANT_ID:
return getTenantId();
case OPERATIONS_SERVER_ID:
return getOperationsServerId();
case UPDATE_TYPE:
return getUpdateType();
}
throw new IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been assigned a value) and false
* otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case USER_ID:
return isSetUserId();
case TENANT_ID:
return isSetTenantId();
case OPERATIONS_SERVER_ID:
return isSetOperationsServerId();
case UPDATE_TYPE:
return isSetUpdateType();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof UserRouteInfo)
return this.equals((UserRouteInfo) that);
return false;
}
public boolean equals(UserRouteInfo that) {
if (that == null)
return false;
boolean this_present_userId = true && this.isSetUserId();
boolean that_present_userId = true && that.isSetUserId();
if (this_present_userId || that_present_userId) {
if (!(this_present_userId && that_present_userId))
return false;
if (!this.userId.equals(that.userId))
return false;
}
boolean this_present_tenantId = true && this.isSetTenantId();
boolean that_present_tenantId = true && that.isSetTenantId();
if (this_present_tenantId || that_present_tenantId) {
if (!(this_present_tenantId && that_present_tenantId))
return false;
if (!this.tenantId.equals(that.tenantId))
return false;
}
boolean this_present_operationsServerId = true && this.isSetOperationsServerId();
boolean that_present_operationsServerId = true && that.isSetOperationsServerId();
if (this_present_operationsServerId || that_present_operationsServerId) {
if (!(this_present_operationsServerId && that_present_operationsServerId))
return false;
if (!this.operationsServerId.equals(that.operationsServerId))
return false;
}
boolean this_present_updateType = true && this.isSetUpdateType();
boolean that_present_updateType = true && that.isSetUpdateType();
if (this_present_updateType || that_present_updateType) {
if (!(this_present_updateType && that_present_updateType))
return false;
if (!this.updateType.equals(that.updateType))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_userId = true && (isSetUserId());
list.add(present_userId);
if (present_userId)
list.add(userId);
boolean present_tenantId = true && (isSetTenantId());
list.add(present_tenantId);
if (present_tenantId)
list.add(tenantId);
boolean present_operationsServerId = true && (isSetOperationsServerId());
list.add(present_operationsServerId);
if (present_operationsServerId)
list.add(operationsServerId);
boolean present_updateType = true && (isSetUpdateType());
list.add(present_updateType);
if (present_updateType)
list.add(updateType.getValue());
return list.hashCode();
}
@Override
public int compareTo(UserRouteInfo other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetUserId()).compareTo(other.isSetUserId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetUserId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.userId, other.userId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetTenantId()).compareTo(other.isSetTenantId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTenantId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.tenantId, other.tenantId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetOperationsServerId()).compareTo(other.isSetOperationsServerId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetOperationsServerId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.operationsServerId, other.operationsServerId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetUpdateType()).compareTo(other.isSetUpdateType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetUpdateType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.updateType, other.updateType);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("UserRouteInfo(");
boolean first = true;
sb.append("userId:");
if (this.userId == null) {
sb.append("null");
} else {
sb.append(this.userId);
}
first = false;
if (!first) sb.append(", ");
sb.append("tenantId:");
if (this.tenantId == null) {
sb.append("null");
} else {
sb.append(this.tenantId);
}
first = false;
if (!first) sb.append(", ");
sb.append("operationsServerId:");
if (this.operationsServerId == null) {
sb.append("null");
} else {
sb.append(this.operationsServerId);
}
first = false;
if (!first) sb.append(", ");
sb.append("updateType:");
if (this.updateType == null) {
sb.append("null");
} else {
sb.append(this.updateType);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
/**
* The set of fields this struct contains, along with convenience methods for finding and
* manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
USER_ID((short) 1, "userId"),
TENANT_ID((short) 2, "tenantId"),
OPERATIONS_SERVER_ID((short) 3, "operationsServerId"),
/**
* @see EventRouteUpdateType
*/
UPDATE_TYPE((short) 4, "updateType");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 1: // USER_ID
return USER_ID;
case 2: // TENANT_ID
return TENANT_ID;
case 3: // OPERATIONS_SERVER_ID
return OPERATIONS_SERVER_ID;
case 4: // UPDATE_TYPE
return UPDATE_TYPE;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
private static class UserRouteInfoStandardSchemeFactory implements SchemeFactory {
public UserRouteInfoStandardScheme getScheme() {
return new UserRouteInfoStandardScheme();
}
}
private static class UserRouteInfoStandardScheme extends StandardScheme<UserRouteInfo> {
public void read(org.apache.thrift.protocol.TProtocol iprot, UserRouteInfo struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // USER_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.userId = iprot.readString();
struct.setUserIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // TENANT_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.tenantId = iprot.readString();
struct.setTenantIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // OPERATIONS_SERVER_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.operationsServerId = iprot.readString();
struct.setOperationsServerIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // UPDATE_TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.updateType = org.kaaproject.kaa.server.common.thrift.gen.operations.EventRouteUpdateType.findByValue(iprot.readI32());
struct.setUpdateTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, UserRouteInfo struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.userId != null) {
oprot.writeFieldBegin(USER_ID_FIELD_DESC);
oprot.writeString(struct.userId);
oprot.writeFieldEnd();
}
if (struct.tenantId != null) {
oprot.writeFieldBegin(TENANT_ID_FIELD_DESC);
oprot.writeString(struct.tenantId);
oprot.writeFieldEnd();
}
if (struct.operationsServerId != null) {
oprot.writeFieldBegin(OPERATIONS_SERVER_ID_FIELD_DESC);
oprot.writeString(struct.operationsServerId);
oprot.writeFieldEnd();
}
if (struct.updateType != null) {
oprot.writeFieldBegin(UPDATE_TYPE_FIELD_DESC);
oprot.writeI32(struct.updateType.getValue());
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class UserRouteInfoTupleSchemeFactory implements SchemeFactory {
public UserRouteInfoTupleScheme getScheme() {
return new UserRouteInfoTupleScheme();
}
}
private static class UserRouteInfoTupleScheme extends TupleScheme<UserRouteInfo> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, UserRouteInfo struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetUserId()) {
optionals.set(0);
}
if (struct.isSetTenantId()) {
optionals.set(1);
}
if (struct.isSetOperationsServerId()) {
optionals.set(2);
}
if (struct.isSetUpdateType()) {
optionals.set(3);
}
oprot.writeBitSet(optionals, 4);
if (struct.isSetUserId()) {
oprot.writeString(struct.userId);
}
if (struct.isSetTenantId()) {
oprot.writeString(struct.tenantId);
}
if (struct.isSetOperationsServerId()) {
oprot.writeString(struct.operationsServerId);
}
if (struct.isSetUpdateType()) {
oprot.writeI32(struct.updateType.getValue());
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, UserRouteInfo struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(4);
if (incoming.get(0)) {
struct.userId = iprot.readString();
struct.setUserIdIsSet(true);
}
if (incoming.get(1)) {
struct.tenantId = iprot.readString();
struct.setTenantIdIsSet(true);
}
if (incoming.get(2)) {
struct.operationsServerId = iprot.readString();
struct.setOperationsServerIdIsSet(true);
}
if (incoming.get(3)) {
struct.updateType = org.kaaproject.kaa.server.common.thrift.gen.operations.EventRouteUpdateType.findByValue(iprot.readI32());
struct.setUpdateTypeIsSet(true);
}
}
}
}
| [
"[email protected]"
]
| |
45c698e93b2e09f9b330e5da90c8846c3e1db50d | 924fd10c3ae9aa4be14bb2eca4326297504bcd61 | /Library/LibraryHibernateBestPractices/src/main/java/config/HibernateUtil.java | 25fb1e6269ebf6f32140a54034deac64365c7406 | []
| no_license | CristianIlie39/JavaAdvancedExercises | 02d66b816367ca96bd2d7c23afb224da3dc5a598 | eb935cf231907f246bb3c1ea429f43f7424c7946 | refs/heads/master | 2023-05-30T10:03:06.202844 | 2021-06-20T14:26:30 | 2021-06-20T14:26:30 | 266,324,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 670 | java | package config;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
public static SessionFactory getSessionFactory() {
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
return sessionFactory;
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.