blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
610f7dba925a443778610b7d226f06a4091bd2af
| 8,229,157,401,180 |
0ee9cf551a4f220b207e1d3b74bf973b64947871
|
/lp-server-loanapp-write/src/main/java/com/promontech/loanapp/domain/loantransaction/JasperReportService.java
|
6599ff4d21392383229df44c27f5477db542a1f0
|
[] |
no_license
|
promontech/release-testing-server
|
https://github.com/promontech/release-testing-server
|
6b7080f77dd15d8dafc5cc9349a2e803ef2ccea8
|
3ad235789cafc5ba61a2dbdc9542bd470ca54004
|
refs/heads/develop
| 2020-06-24T06:04:29.784000 | 2020-04-14T06:08:00 | 2020-04-14T06:08:00 | 197,842,505 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.promontech.loanapp.domain.loantransaction;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import com.promontech.loanapp.common.config.JasperProperties;
import com.promontech.common.core.domain.document.DocumentDataRequest;
import com.promontech.common.core.domain.document.FileOriginType;
import com.promontech.common.core.domain.income.SourceDocumentType;
import com.promontech.common.spring.spring2.docmanagement.DocManagementHelper;
import com.promontech.common.util.GlobalConstants;
import com.promontech.common.util.HeaderHelper;
import com.promontech.loanapp.common.Client;
import com.promontech.loanapp.common.ClientConfigService;
import com.promontech.loanapp.common.EventNotProcessedException;
import com.promontech.loanapp.common.documentDescriptor.viewmodel.DocumentDescriptorDto;
import com.promontech.loanapp.common.esign.AnalyticsEventStatus;
import com.promontech.loanapp.common.esign.CreateEsignTrackingReportMessage;
import com.promontech.loanapp.common.loanTransaction.LoanTransactionId;
import com.promontech.loanapp.common.user.TenantId;
import com.promontech.loanapp.iamtenantadmin.service.IamTenantAdminService;
import com.promontech.loanapp.common.rest.RestClient;
import com.promontech.loanapp.service.documentdescriptor.DocumentDescriptorService;
@Service
public class JasperReportService {
private static final Logger logger = LoggerFactory.getLogger(JasperReportService.class);
public static final String TRACKING_FILE_NAME = "eDisclosurePackageTracking";
private final RestClient restClient;
private final DocumentDescriptorService documentDescriptorService;
private final DocManagementHelper docManagementHelper;
private final IamTenantAdminService iamTenantAdminService;
private final ClientConfigService config;
private final JasperProperties jasperProperties;
@Autowired
public JasperReportService(
RestClient restClient,
DocumentDescriptorService documentDescriptorService,
DocManagementHelper docManagementHelper,
IamTenantAdminService iamTenantAdminService,
ClientConfigService config,
JasperProperties jasperProperties) {
this.restClient = restClient;
this.documentDescriptorService = documentDescriptorService;
this.docManagementHelper = docManagementHelper;
this.iamTenantAdminService = iamTenantAdminService;
this.config = config;
this.jasperProperties = jasperProperties;
}
public void createEsignTrackingReport(CreateEsignTrackingReportMessage message) {
Map<String, String> headers = HeaderHelper.getReqHeadersFromSecurityContext();
TenantId tenantId = new TenantId(headers.get(GlobalConstants.TENANT_ID));
String correlationId = headers.get(GlobalConstants.CORRELATION_ID);
final Client client = config.getClientByTenantId(tenantId.getId());
// check analytics
if (!checkAnalyticsEventStatus(message.getEventId(), client)) {
throw new EventNotProcessedException("Analytics has not processed eventId " + message.getEventId());
}
// get service account token
String serviceAccountAccessToken = iamTenantAdminService.getServiceAccountAccessToken(tenantId, correlationId);
byte[] pdfReportData;
try {
// get pdf report from jasper
pdfReportData = getTrackingPdfReportFromJasper(message,
serviceAccountAccessToken,
headers.get(GlobalConstants.CORRELATION_ID),
client);
} catch (RestClientException rce) {
logger.error(String.format("Requesting eDisclosures Report from Jaspersoft failed due to exception. " +
"[loanTransactionId=%s, loanId=%s]",
message.getLoanTransactionId().getId().toString(),
message.getLoanId().getId().toString()),
rce);
return;
}
// Handle Jaspersoft report request failure, as API doesn't return HTTP 404 or another reasonable status code.
if (isDocumentBlank(pdfReportData.length, MediaType.APPLICATION_PDF)) {
logger.error(String.format("Requesting eDisclosures Report from Jaspersoft failed -- blank document " +
"returned. [loanTransactionId=%s, loanId=%s]",
message.getLoanTransactionId().getId().toString(),
message.getLoanId().getId().toString()));
return;
}
// Create Instant (UTC) timestamp formatter.
DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern(jasperProperties.getReportTimestampFormat())
.withZone(ZoneId.of(ZoneOffset.UTC.getId()));
// construct filename
String timestamp = timestampFormatter.format(message.getPackageDateTime());
String completed = message.getAllSignersCompleted() ? "_Complete" : "";
String filename = String.format("%s_%s%s", TRACKING_FILE_NAME, timestamp, completed);
// upload to S3 and attach to loan
uploadReportAndCreateDocDescriptor(message.getLoanTransactionId(), SourceDocumentType.E_DISCLOSURE_TRACKER,
filename, pdfReportData, headers, client);
}
private byte[] getTrackingPdfReportFromJasper(CreateEsignTrackingReportMessage message,
String serviceAccountAccessToken,
String correlationId, Client client) {
StringBuilder sb = new StringBuilder();
sb.append("loan_id=" + message.getLoanId());
sb.append("&esign_id=" + message.getEsignId());
sb.append("&event_id=" + message.getEventId());
String disclosureTrackingReportPath = String.format("%s/%s", jasperProperties.getSystemReports().getCommonPath(),
jasperProperties.getSystemReports().getDisclosureTrackingReportFilename());
String url = String.format("%s/%s?%s", jasperProperties.getUrl(), disclosureTrackingReportPath, sb.toString());
HttpHeaders headers = new HttpHeaders();
headers.add(GlobalConstants.X_AUTH_TOKEN, serviceAccountAccessToken);
headers.add(GlobalConstants.CORRELATION_ID, correlationId);
return restClient.get(url, byte[].class, headers);
}
// ---- shared helper methods
private void uploadReportAndCreateDocDescriptor(LoanTransactionId loanTransactionId,
SourceDocumentType documentType,
String filename,
byte[] pdfReportData,
Map<String, String> headers,
Client client) {
List<MediaType> acceptedTypes = new ArrayList<>();
acceptedTypes.add(MediaType.APPLICATION_JSON);
Optional<List<MediaType>> acceptHeaders = Optional.of(acceptedTypes);
ResponseEntity<DocumentDataRequest.DocumentFileReference> response =
docManagementHelper.uploadDocument(
client.getSettings().getDocManagementUrl(),
pdfReportData,
filename,
"pdf", // only pdf is assumed, no file ext is returned
loanTransactionId.toString(),
headers,
acceptHeaders,
FileOriginType.GENERATED);
DocumentDataRequest.DocumentFileReference docFileRef = response.getBody();
DocumentDescriptorDto documentDescriptorDto = new DocumentDescriptorDto(documentType,
Collections.singletonList(docFileRef),
Collections.emptyMap());
documentDescriptorService.createDocumentDescriptor(loanTransactionId, documentDescriptorDto);
}
private boolean checkAnalyticsEventStatus(String eventId, Client client) {
String url = String.format("%s/events/%s/status", client.getSettings().getAnalyticsUrl(), eventId);
AnalyticsEventStatus status = restClient.get(url, AnalyticsEventStatus.class);
logger.info("Analytics event status {} for eventId {}", status.getProcessed(), eventId);
return status.getProcessed();
}
/**
* Simple check for whether a (report) document is considered blank, a check that depends on the MIME content-type.
*
* @param fileSize document's file size in bytes.
* @param contentType document's MIME content-type.
* @return whether the document is blank, according to its content-type.
*/
private boolean isDocumentBlank(long fileSize, MediaType contentType) {
switch (contentType.toString()) {
case MediaType.APPLICATION_PDF_VALUE:
return fileSize < 1024; // Must account for a blank PDFs' metadata.
default:
return fileSize == 0;
}
}
}
|
UTF-8
|
Java
| 10,089 |
java
|
JasperReportService.java
|
Java
|
[] | null |
[] |
package com.promontech.loanapp.domain.loantransaction;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import com.promontech.loanapp.common.config.JasperProperties;
import com.promontech.common.core.domain.document.DocumentDataRequest;
import com.promontech.common.core.domain.document.FileOriginType;
import com.promontech.common.core.domain.income.SourceDocumentType;
import com.promontech.common.spring.spring2.docmanagement.DocManagementHelper;
import com.promontech.common.util.GlobalConstants;
import com.promontech.common.util.HeaderHelper;
import com.promontech.loanapp.common.Client;
import com.promontech.loanapp.common.ClientConfigService;
import com.promontech.loanapp.common.EventNotProcessedException;
import com.promontech.loanapp.common.documentDescriptor.viewmodel.DocumentDescriptorDto;
import com.promontech.loanapp.common.esign.AnalyticsEventStatus;
import com.promontech.loanapp.common.esign.CreateEsignTrackingReportMessage;
import com.promontech.loanapp.common.loanTransaction.LoanTransactionId;
import com.promontech.loanapp.common.user.TenantId;
import com.promontech.loanapp.iamtenantadmin.service.IamTenantAdminService;
import com.promontech.loanapp.common.rest.RestClient;
import com.promontech.loanapp.service.documentdescriptor.DocumentDescriptorService;
@Service
public class JasperReportService {
private static final Logger logger = LoggerFactory.getLogger(JasperReportService.class);
public static final String TRACKING_FILE_NAME = "eDisclosurePackageTracking";
private final RestClient restClient;
private final DocumentDescriptorService documentDescriptorService;
private final DocManagementHelper docManagementHelper;
private final IamTenantAdminService iamTenantAdminService;
private final ClientConfigService config;
private final JasperProperties jasperProperties;
@Autowired
public JasperReportService(
RestClient restClient,
DocumentDescriptorService documentDescriptorService,
DocManagementHelper docManagementHelper,
IamTenantAdminService iamTenantAdminService,
ClientConfigService config,
JasperProperties jasperProperties) {
this.restClient = restClient;
this.documentDescriptorService = documentDescriptorService;
this.docManagementHelper = docManagementHelper;
this.iamTenantAdminService = iamTenantAdminService;
this.config = config;
this.jasperProperties = jasperProperties;
}
public void createEsignTrackingReport(CreateEsignTrackingReportMessage message) {
Map<String, String> headers = HeaderHelper.getReqHeadersFromSecurityContext();
TenantId tenantId = new TenantId(headers.get(GlobalConstants.TENANT_ID));
String correlationId = headers.get(GlobalConstants.CORRELATION_ID);
final Client client = config.getClientByTenantId(tenantId.getId());
// check analytics
if (!checkAnalyticsEventStatus(message.getEventId(), client)) {
throw new EventNotProcessedException("Analytics has not processed eventId " + message.getEventId());
}
// get service account token
String serviceAccountAccessToken = iamTenantAdminService.getServiceAccountAccessToken(tenantId, correlationId);
byte[] pdfReportData;
try {
// get pdf report from jasper
pdfReportData = getTrackingPdfReportFromJasper(message,
serviceAccountAccessToken,
headers.get(GlobalConstants.CORRELATION_ID),
client);
} catch (RestClientException rce) {
logger.error(String.format("Requesting eDisclosures Report from Jaspersoft failed due to exception. " +
"[loanTransactionId=%s, loanId=%s]",
message.getLoanTransactionId().getId().toString(),
message.getLoanId().getId().toString()),
rce);
return;
}
// Handle Jaspersoft report request failure, as API doesn't return HTTP 404 or another reasonable status code.
if (isDocumentBlank(pdfReportData.length, MediaType.APPLICATION_PDF)) {
logger.error(String.format("Requesting eDisclosures Report from Jaspersoft failed -- blank document " +
"returned. [loanTransactionId=%s, loanId=%s]",
message.getLoanTransactionId().getId().toString(),
message.getLoanId().getId().toString()));
return;
}
// Create Instant (UTC) timestamp formatter.
DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern(jasperProperties.getReportTimestampFormat())
.withZone(ZoneId.of(ZoneOffset.UTC.getId()));
// construct filename
String timestamp = timestampFormatter.format(message.getPackageDateTime());
String completed = message.getAllSignersCompleted() ? "_Complete" : "";
String filename = String.format("%s_%s%s", TRACKING_FILE_NAME, timestamp, completed);
// upload to S3 and attach to loan
uploadReportAndCreateDocDescriptor(message.getLoanTransactionId(), SourceDocumentType.E_DISCLOSURE_TRACKER,
filename, pdfReportData, headers, client);
}
private byte[] getTrackingPdfReportFromJasper(CreateEsignTrackingReportMessage message,
String serviceAccountAccessToken,
String correlationId, Client client) {
StringBuilder sb = new StringBuilder();
sb.append("loan_id=" + message.getLoanId());
sb.append("&esign_id=" + message.getEsignId());
sb.append("&event_id=" + message.getEventId());
String disclosureTrackingReportPath = String.format("%s/%s", jasperProperties.getSystemReports().getCommonPath(),
jasperProperties.getSystemReports().getDisclosureTrackingReportFilename());
String url = String.format("%s/%s?%s", jasperProperties.getUrl(), disclosureTrackingReportPath, sb.toString());
HttpHeaders headers = new HttpHeaders();
headers.add(GlobalConstants.X_AUTH_TOKEN, serviceAccountAccessToken);
headers.add(GlobalConstants.CORRELATION_ID, correlationId);
return restClient.get(url, byte[].class, headers);
}
// ---- shared helper methods
private void uploadReportAndCreateDocDescriptor(LoanTransactionId loanTransactionId,
SourceDocumentType documentType,
String filename,
byte[] pdfReportData,
Map<String, String> headers,
Client client) {
List<MediaType> acceptedTypes = new ArrayList<>();
acceptedTypes.add(MediaType.APPLICATION_JSON);
Optional<List<MediaType>> acceptHeaders = Optional.of(acceptedTypes);
ResponseEntity<DocumentDataRequest.DocumentFileReference> response =
docManagementHelper.uploadDocument(
client.getSettings().getDocManagementUrl(),
pdfReportData,
filename,
"pdf", // only pdf is assumed, no file ext is returned
loanTransactionId.toString(),
headers,
acceptHeaders,
FileOriginType.GENERATED);
DocumentDataRequest.DocumentFileReference docFileRef = response.getBody();
DocumentDescriptorDto documentDescriptorDto = new DocumentDescriptorDto(documentType,
Collections.singletonList(docFileRef),
Collections.emptyMap());
documentDescriptorService.createDocumentDescriptor(loanTransactionId, documentDescriptorDto);
}
private boolean checkAnalyticsEventStatus(String eventId, Client client) {
String url = String.format("%s/events/%s/status", client.getSettings().getAnalyticsUrl(), eventId);
AnalyticsEventStatus status = restClient.get(url, AnalyticsEventStatus.class);
logger.info("Analytics event status {} for eventId {}", status.getProcessed(), eventId);
return status.getProcessed();
}
/**
* Simple check for whether a (report) document is considered blank, a check that depends on the MIME content-type.
*
* @param fileSize document's file size in bytes.
* @param contentType document's MIME content-type.
* @return whether the document is blank, according to its content-type.
*/
private boolean isDocumentBlank(long fileSize, MediaType contentType) {
switch (contentType.toString()) {
case MediaType.APPLICATION_PDF_VALUE:
return fileSize < 1024; // Must account for a blank PDFs' metadata.
default:
return fileSize == 0;
}
}
}
| 10,089 | 0.652889 | 0.6517 | 192 | 51.546875 | 34.676899 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.807292 | false | false |
9
|
e3f389e99e18862f7117c55ee16ec15d3b4595b6
| 34,617,436,418,743 |
2f22a3c9361d91b6bdf55aa0fa76d73409c138b4
|
/Prova 02/app/src/main/java/com/maxwel/prova2v2/ItemGerenciar.java
|
5f58b7ae34e47f3fc6b0836a9ae52063ccd021bc
|
[] |
no_license
|
Maxwel-Araujo-Costa/Programacao-para-Dispositivos-Moveis---2020_1
|
https://github.com/Maxwel-Araujo-Costa/Programacao-para-Dispositivos-Moveis---2020_1
|
71a8e778153c254d43ba53872c2a968b0ed25605
|
bd22fd8b1b8682ad14f04621adf8c3d9d463641c
|
refs/heads/main
| 2023-04-25T11:30:11.882000 | 2021-05-22T21:58:00 | 2021-05-22T21:58:00 | 369,901,825 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.maxwel.prova2v2;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class ItemGerenciar implements Serializable {
DBHelper db;
public String nome;
public int imagem;
public double preco;
public int quantidade;
public int id;
public ItemGerenciar (int id, String nome, double preco, int quantidade, int imagem){
this.nome=nome;
this.id=id;
this.preco=preco;
this.quantidade=quantidade;
this.imagem= imagem;
}
public static List<ItemGerenciar> getGerenciar(){
List<ItemGerenciar> gerenciar=new ArrayList<ItemGerenciar>();
/*SQLiteDatabase database = db.getWritableDatabase();
Cursor cursor = database.query("restaurante", new String[] {"_id","nome","valor","quantidade","imagem"},
null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
ItemGerenciar item = new ItemGerenciar(
cursor.getInt(0),
cursor.getString(1),
cursor.getDouble(2),
cursor.getInt(3),
cursor.getInt(4));
gerenciar.add(item);
} while (cursor.moveToNext());
}*/
ItemGerenciar item = new ItemGerenciar(0,"Batata Frita",2.19,1,R.drawable.batata_frita);
gerenciar.add(item);
return gerenciar;
}
public static List<ItemGerenciar> carrinho;
public static List<ItemGerenciar> getCarrinho(){
return carrinho;
}
public static void setCarrinho(List<ItemGerenciar> newCarrinho){
carrinho=new ArrayList<ItemGerenciar>();
carrinho = newCarrinho;
}
}
|
UTF-8
|
Java
| 1,903 |
java
|
ItemGerenciar.java
|
Java
|
[] | null |
[] |
package com.maxwel.prova2v2;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class ItemGerenciar implements Serializable {
DBHelper db;
public String nome;
public int imagem;
public double preco;
public int quantidade;
public int id;
public ItemGerenciar (int id, String nome, double preco, int quantidade, int imagem){
this.nome=nome;
this.id=id;
this.preco=preco;
this.quantidade=quantidade;
this.imagem= imagem;
}
public static List<ItemGerenciar> getGerenciar(){
List<ItemGerenciar> gerenciar=new ArrayList<ItemGerenciar>();
/*SQLiteDatabase database = db.getWritableDatabase();
Cursor cursor = database.query("restaurante", new String[] {"_id","nome","valor","quantidade","imagem"},
null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
ItemGerenciar item = new ItemGerenciar(
cursor.getInt(0),
cursor.getString(1),
cursor.getDouble(2),
cursor.getInt(3),
cursor.getInt(4));
gerenciar.add(item);
} while (cursor.moveToNext());
}*/
ItemGerenciar item = new ItemGerenciar(0,"Batata Frita",2.19,1,R.drawable.batata_frita);
gerenciar.add(item);
return gerenciar;
}
public static List<ItemGerenciar> carrinho;
public static List<ItemGerenciar> getCarrinho(){
return carrinho;
}
public static void setCarrinho(List<ItemGerenciar> newCarrinho){
carrinho=new ArrayList<ItemGerenciar>();
carrinho = newCarrinho;
}
}
| 1,903 | 0.600105 | 0.593799 | 56 | 32.017857 | 24.113194 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.946429 | false | false |
9
|
0a8bc757a0b50f4b8cd24ff9ba018ae0db3941e4
| 28,381,143,918,293 |
ba41b1f108afddca283109ab3864d6228a763aeb
|
/src/main/java/com/shangxin/demo/pojo/ActivityContent.java
|
6ec2127099618f69dd6b490d4ec15246ff1479b8
|
[] |
no_license
|
guochao4869/index
|
https://github.com/guochao4869/index
|
a9acaf4839760623c029a80ac6597159986a2b1b
|
93a40591ef76252c5132bd3673fed78d91833bc8
|
refs/heads/master
| 2023-03-07T20:43:53.584000 | 2021-02-24T02:57:20 | 2021-02-24T02:58:18 | 341,515,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.shangxin.demo.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Table(name = "index_activitycontent")
public class ActivityContent implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private String id; //主键id
@Column(name = "starttime")
private String starttime; //活动开始时间
@Column(name = "endtime")
private String endtime; //活动结束世界
@Column(name = "site")
private String site; //活动地址
@Column(name = "content")
private String content; //活动内容
@Column(name = "title")
private String title; //活动标题
@Column(name = "img")
private String img; //图片
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getStarttime() {
return starttime;
}
public void setStarttime(String starttime) {
this.starttime = starttime;
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
UTF-8
|
Java
| 1,751 |
java
|
ActivityContent.java
|
Java
|
[] | null |
[] |
package com.shangxin.demo.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Table(name = "index_activitycontent")
public class ActivityContent implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private String id; //主键id
@Column(name = "starttime")
private String starttime; //活动开始时间
@Column(name = "endtime")
private String endtime; //活动结束世界
@Column(name = "site")
private String site; //活动地址
@Column(name = "content")
private String content; //活动内容
@Column(name = "title")
private String title; //活动标题
@Column(name = "img")
private String img; //图片
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getStarttime() {
return starttime;
}
public void setStarttime(String starttime) {
this.starttime = starttime;
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
| 1,751 | 0.584071 | 0.584071 | 87 | 18.482759 | 16.221075 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275862 | false | false |
9
|
7db1c8d3555fc1ee29935b0ba9719255119fe91d
| 188,978,620,287 |
e9e7156fe4837ceb3a68509a4e81c44dc301a8a7
|
/StarwarsAPIFramework/src/test/java/com/sparta/ben/Framework/Utility/URLChanger.java
|
17e71079d1a848a8b29518f4175ba6c528cb9f47
|
[] |
no_license
|
Benmiddlehurst/StarwarsAPIFramework
|
https://github.com/Benmiddlehurst/StarwarsAPIFramework
|
b13db6cb8566af3103359b7ecc1b04a0001682f5
|
4a27d93ff0578d9875ff43c5d571fcdd6bc15b7c
|
refs/heads/main
| 2023-02-18T10:53:00.186000 | 2021-01-18T09:07:15 | 2021-01-18T09:07:15 | 330,003,682 | 0 | 0 | null | false | 2021-01-18T09:02:50 | 2021-01-15T19:29:08 | 2021-01-15T19:29:12 | 2021-01-18T09:02:49 | 32 | 0 | 0 | 0 | null | false | false |
package com.sparta.ben.Framework.Utility;
public class URLChanger {
public static String URLChanger(String url){
url = url.replaceAll("http://", "https://");
return url;
}
}
|
UTF-8
|
Java
| 199 |
java
|
URLChanger.java
|
Java
|
[] | null |
[] |
package com.sparta.ben.Framework.Utility;
public class URLChanger {
public static String URLChanger(String url){
url = url.replaceAll("http://", "https://");
return url;
}
}
| 199 | 0.638191 | 0.638191 | 8 | 23.875 | 19.814373 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
9
|
187b324b57d5402f66e325aad5514514c2343669
| 14,869,176,798,924 |
3e216823d0f0bae563d1b51d91b1adb3627a765f
|
/comm-layer-demo/proxy/src/main/java/com/weisong/test/comm/impl/CWebSocketServer.java
|
c77f3d56af87f9a5a338e10f558ce8e90f13a686
|
[
"Apache-2.0"
] |
permissive
|
weisong44/archived-projects
|
https://github.com/weisong44/archived-projects
|
d5af1ff45be1198ddfd2a459df1d5bbb92bb6f81
|
88dacb47b38e9e28d43df440ed6dcd46707ef4fb
|
refs/heads/master
| 2021-01-21T22:26:20.347000 | 2017-11-08T06:54:40 | 2017-11-08T06:54:40 | 31,051,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.weisong.test.comm.impl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;
public class CWebSocketServer {
private class WebSocketInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
public WebSocketInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new CWebSocketServerHandler(proxy));
}
}
static public boolean useSsl;
private Channel channel;
private CBaseWebSocketProxy proxy;
public CWebSocketServer(CBaseWebSocketProxy proxy)
throws Exception {
this(proxy, false);
}
public CWebSocketServer(CBaseWebSocketProxy proxy, boolean useSsl)
throws Exception {
this(proxy, 8080, useSsl);
}
public CWebSocketServer(CBaseWebSocketProxy proxy, int port, boolean useSsl)
throws Exception {
this.proxy = proxy;
CWebSocketServer.useSsl = useSsl;
// Configure SSL.
final SslContext sslCtx;
if (useSsl) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
} else {
sslCtx = null;
}
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new WebSocketInitializer(sslCtx));
channel = b.bind(port).sync().channel();
System.out.println(String.format("Listening at %s://127.0.0.1:%d",
useSsl? "https" : "http", port));
channel.closeFuture().sync();
}
finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public void shutdown() {
if(channel != null) {
channel.close();
channel = null;
}
}
}
|
UTF-8
|
Java
| 3,017 |
java
|
CWebSocketServer.java
|
Java
|
[
{
"context": "stem.out.println(String.format(\"Listening at %s://127.0.0.1:%d\",\n useSsl? \"https\" : \"http\"",
"end": 2679,
"score": 0.9997375011444092,
"start": 2670,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null |
[] |
package com.weisong.test.comm.impl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;
public class CWebSocketServer {
private class WebSocketInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
public WebSocketInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new CWebSocketServerHandler(proxy));
}
}
static public boolean useSsl;
private Channel channel;
private CBaseWebSocketProxy proxy;
public CWebSocketServer(CBaseWebSocketProxy proxy)
throws Exception {
this(proxy, false);
}
public CWebSocketServer(CBaseWebSocketProxy proxy, boolean useSsl)
throws Exception {
this(proxy, 8080, useSsl);
}
public CWebSocketServer(CBaseWebSocketProxy proxy, int port, boolean useSsl)
throws Exception {
this.proxy = proxy;
CWebSocketServer.useSsl = useSsl;
// Configure SSL.
final SslContext sslCtx;
if (useSsl) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
} else {
sslCtx = null;
}
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new WebSocketInitializer(sslCtx));
channel = b.bind(port).sync().channel();
System.out.println(String.format("Listening at %s://127.0.0.1:%d",
useSsl? "https" : "http", port));
channel.closeFuture().sync();
}
finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public void shutdown() {
if(channel != null) {
channel.close();
channel = null;
}
}
}
| 3,017 | 0.680146 | 0.674843 | 99 | 29.474747 | 23.689636 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.151515 | false | false |
9
|
6664527f8f96b496059feea8ffae774e18018d2f
| 1,005,022,386,207 |
4c4c0a3a4ca4c3f112209b2fa29054bc5dd8b762
|
/Dependency-Injection/Car.java
|
121c9e7f30f0b5901b526701be81b7fa7ad76ebe
|
[] |
no_license
|
bc850/Design-Patterns
|
https://github.com/bc850/Design-Patterns
|
0300c519d7e602ec75b2a84823f4c8398b8816c0
|
b9ae8f7a7727c253da63b7053163160456713bd7
|
refs/heads/master
| 2021-04-12T12:08:53.383000 | 2018-04-05T05:59:28 | 2018-04-05T05:59:28 | 126,833,114 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package injection.dependency;
public class Car {
//dependency
//Ford fordCar = new Ford("This is a Ford Mustang car.");
Ford fordCar; // removed the "new" operator
public Car(Ford fordCar) {
this.fordCar = fordCar;
}
public String viewCars() {
System.out.println(fordCar.getTypeCar());
return fordCar.getTypeCar();
}
}
|
UTF-8
|
Java
| 342 |
java
|
Car.java
|
Java
|
[] | null |
[] |
package injection.dependency;
public class Car {
//dependency
//Ford fordCar = new Ford("This is a Ford Mustang car.");
Ford fordCar; // removed the "new" operator
public Car(Ford fordCar) {
this.fordCar = fordCar;
}
public String viewCars() {
System.out.println(fordCar.getTypeCar());
return fordCar.getTypeCar();
}
}
| 342 | 0.687135 | 0.687135 | 18 | 18 | 17.716909 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false |
9
|
4a3d890de3f07e83bb1e55b096f47a0e674100b5
| 33,913,061,788,115 |
926b53c9fa812f945cf842b6fefb4217e4a41571
|
/app/src/main/java/com/example/conexionhttp/MainActivity.java
|
4ad7dd86b61f0df29b07fa9e082a049a460d2d06
|
[] |
no_license
|
EnriqueCasado/ConexionHttp
|
https://github.com/EnriqueCasado/ConexionHttp
|
4c3895c2a27331a3a560db0991b22adb37e097d2
|
5d672447d9035047f09f820c831800f9886c74c6
|
refs/heads/master
| 2020-04-19T23:33:34.399000 | 2019-01-31T17:27:33 | 2019-01-31T17:27:33 | 168,499,207 | 0 | 0 | null | false | 2019-01-31T10:12:32 | 2019-01-31T09:33:50 | 2019-01-31T09:39:45 | 2019-01-31T10:12:32 | 0 | 0 | 0 | 0 |
Java
| false | null |
package com.example.conexionhttp;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;
Button btnIr;
//Nos hacemos cargo de la interfaz de usuario captando sus elementos
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= findViewById(R.id.editText);
textView=findViewById(R.id.textView);
btnIr=findViewById(R.id.button);
}
//Cuando pulse el botón, iniciamos la AsyncTask que se encarga del trabajo sin bloquear la UI. Le enviamos como argumento un string con la url que el usuario ha introducido en el editText
@Override
protected void onStart() {
super.onStart();
btnIr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AsyncTaskDescarga().execute(editText.getText().toString());
}
});
}
//Definimos la clase AsyncTask
private class AsyncTaskDescarga extends AsyncTask<String,Void,String>{
//No tenemos onPreExecute(), por lo primero que se ejecutará sera el doInBackground. A ese le llegan los params que llegan a través de strings (url).
@Override
protected String doInBackground(String... strings) {
try{
return descargaUrl(strings[0]); //Llamamos al método descargaUrl envíandole como argumento un string con la url
}catch (IOException e){
return "No se puede cargar la página web";
}
}
//Cuando doInBackground haya terminado con la lectura, nos devolvera un string con el texto que debemos presentar en el textView
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
//Este método recibe un string con la url a la que queremos conectar y tiene que devolver un string con el contenido del la web leída
private String descargaUrl(String miUrl)throws IOException{
InputStream is=null;
try{
URL url=new URL(miUrl); //crea un objeto URL que tiene como argumento el string que ha introducido el usuario
HttpURLConnection conn=(HttpURLConnection) url.openConnection(); //creamos un objeto para abrir la conexión con la url indicada
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET"); //indicamos que vamos a traer elementos
conn.setDoInput(true);
conn.connect(); //conectamos con la url
is=conn.getInputStream(); //obtenemos un flujo de datos de entrada desde la conexión establecida
return Leer(is); //llamamos a este método que se encargará de tomar el flujo de entrada y convertirlo en un string, que devolveremos a doInBackground
}
finally{
if (is!=null){
is.close();
}
}
}
private String Leer(InputStream is){
try{
ByteArrayOutputStream bo= new ByteArrayOutputStream(); //creamos un array de bytes en el que escribir
int i=is.read(); //leemos un byte de el flujo de entrada
while (i!=-1){ //mientras haya bytes los escribimos en el array de bytes. Cuando se acabe, la lectura nos devuelve -1 para indicar que no hay más
bo.write(i);
i=is.read();
}
return bo.toString(); //devolvemos un string a descargaUrl que a su vez lo devolverá a doInBackground que se lo dará a onPostExecute que lo escribirá en el textView
}catch (IOException e){
return"";
}
}
}
}
|
UTF-8
|
Java
| 4,437 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.example.conexionhttp;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;
Button btnIr;
//Nos hacemos cargo de la interfaz de usuario captando sus elementos
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText= findViewById(R.id.editText);
textView=findViewById(R.id.textView);
btnIr=findViewById(R.id.button);
}
//Cuando pulse el botón, iniciamos la AsyncTask que se encarga del trabajo sin bloquear la UI. Le enviamos como argumento un string con la url que el usuario ha introducido en el editText
@Override
protected void onStart() {
super.onStart();
btnIr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AsyncTaskDescarga().execute(editText.getText().toString());
}
});
}
//Definimos la clase AsyncTask
private class AsyncTaskDescarga extends AsyncTask<String,Void,String>{
//No tenemos onPreExecute(), por lo primero que se ejecutará sera el doInBackground. A ese le llegan los params que llegan a través de strings (url).
@Override
protected String doInBackground(String... strings) {
try{
return descargaUrl(strings[0]); //Llamamos al método descargaUrl envíandole como argumento un string con la url
}catch (IOException e){
return "No se puede cargar la página web";
}
}
//Cuando doInBackground haya terminado con la lectura, nos devolvera un string con el texto que debemos presentar en el textView
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
textView.setText(s);
}
//Este método recibe un string con la url a la que queremos conectar y tiene que devolver un string con el contenido del la web leída
private String descargaUrl(String miUrl)throws IOException{
InputStream is=null;
try{
URL url=new URL(miUrl); //crea un objeto URL que tiene como argumento el string que ha introducido el usuario
HttpURLConnection conn=(HttpURLConnection) url.openConnection(); //creamos un objeto para abrir la conexión con la url indicada
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET"); //indicamos que vamos a traer elementos
conn.setDoInput(true);
conn.connect(); //conectamos con la url
is=conn.getInputStream(); //obtenemos un flujo de datos de entrada desde la conexión establecida
return Leer(is); //llamamos a este método que se encargará de tomar el flujo de entrada y convertirlo en un string, que devolveremos a doInBackground
}
finally{
if (is!=null){
is.close();
}
}
}
private String Leer(InputStream is){
try{
ByteArrayOutputStream bo= new ByteArrayOutputStream(); //creamos un array de bytes en el que escribir
int i=is.read(); //leemos un byte de el flujo de entrada
while (i!=-1){ //mientras haya bytes los escribimos en el array de bytes. Cuando se acabe, la lectura nos devuelve -1 para indicar que no hay más
bo.write(i);
i=is.read();
}
return bo.toString(); //devolvemos un string a descargaUrl que a su vez lo devolverá a doInBackground que se lo dará a onPostExecute que lo escribirá en el textView
}catch (IOException e){
return"";
}
}
}
}
| 4,437 | 0.628817 | 0.62565 | 115 | 36.443478 | 42.598671 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46087 | false | false |
9
|
765683e017fa02aee93751cccce163c4e05372df
| 29,841,432,810,526 |
4e29677e881a69b1f8eabcb99ea6993c410cf33b
|
/SweetCakeBackEnd/src/main/java/com/niit/sweetcake/dao/CustomerDao.java
|
e68f47400e652cb53e579fbba45db8f99301b6de
|
[] |
no_license
|
HRRamya/Tutorial
|
https://github.com/HRRamya/Tutorial
|
ab55049f3766b0a31951b07fc7356c0ba0fc9ae9
|
61ca8ce29f944703db6ac71afcebc6e99d4de56b
|
refs/heads/master
| 2020-06-10T17:38:23.938000 | 2016-12-08T09:03:08 | 2016-12-08T09:03:08 | 75,920,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.niit.sweetcake.dao;
import java.util.List;
import com.niit.sweetcake.model.Customer;
public interface CustomerDao {
public boolean save(Customer customer);
public boolean delete(String customer_Id);
public Customer get(String userId);
public List<Customer> list();
public boolean update(Customer customer);
}
|
UTF-8
|
Java
| 338 |
java
|
CustomerDao.java
|
Java
|
[] | null |
[] |
package com.niit.sweetcake.dao;
import java.util.List;
import com.niit.sweetcake.model.Customer;
public interface CustomerDao {
public boolean save(Customer customer);
public boolean delete(String customer_Id);
public Customer get(String userId);
public List<Customer> list();
public boolean update(Customer customer);
}
| 338 | 0.766272 | 0.766272 | 14 | 23.142857 | 18.043032 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.928571 | false | false |
9
|
786b9ad07e785c37af42bae50d7a74b47f2c9a8b
| 20,151,986,583,845 |
047bbd7b9a4eb6c1f236f9face0bf9ace1260783
|
/AndroidWorks/EugiTaskList/app/src/main/java/com/backbone/dwida/eugitasklist/ProviderAccessClass.java
|
b13140c0d14300ae3d3c8363a29e4da47fa8a5ba
|
[] |
no_license
|
dwida/PastWork
|
https://github.com/dwida/PastWork
|
381dcb69343a661ab4c7596c4fd07d2ec44f76eb
|
ccc140cf36eadbd6ba53505fc7ef4c3a76d2203c
|
refs/heads/master
| 2020-05-20T02:50:20.312000 | 2019-05-07T21:49:48 | 2019-05-07T21:49:48 | 185,338,969 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.backbone.dwida.eugitasklist;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by dwida on 29/7/2015.
*/
public class ProviderAccessClass extends AsyncTask<Void, Integer, ArrayList<String>> {
Context mContext;
String mOperationMode;
ApplicationData applicationData;
public static final String UPDATE = "update";
public static final String LOAD = "load";
Uri loggedinUri = Uri.parse("content://com.backbone.dwida.eugiprovider/loggedin");
public ProviderAccessClass(Context context, String operationmode) {
this.mContext = context;
this.mOperationMode = operationmode;
applicationData = (ApplicationData)mContext.getApplicationContext();
}
@Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> tempArray = new ArrayList<String>();
Cursor loggedinCursor = mContext.getContentResolver().query(loggedinUri, null, null, null, null);
loggedinCursor.moveToLast();
String userId = String.valueOf(loggedinCursor.getInt(0));
loggedinCursor.close();
switch(mOperationMode) {
case LOAD :
tempArray = LoadUserData(userId);
break;
case UPDATE :
UpdateUserData(userId);
break;
}
return tempArray;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.d("Progress", String.valueOf(values));
}
@Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
}
ArrayList<String> LoadUserData(String userId) {
ArrayList<String> tempLoadArray = new ArrayList<String>();
Uri userDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/" + userId);
Uri mathDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/math/" + userId);
Uri englishDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/english/" + userId);
Uri moralDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/moral/" + userId);
Uri scienceDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/science/" + userId);
Cursor userDataCursor = mContext.getContentResolver().query(userDataUri, null, null, null, null);
Cursor mathDataCursor = mContext.getContentResolver().query(mathDataUri, null, null, null, null);
Cursor englishDataCursor = mContext.getContentResolver().query(englishDataUri, null, null, null, null);
Cursor moralDataCursor = mContext.getContentResolver().query(moralDataUri, null, null, null, null);
Cursor scienceDataCursor = mContext.getContentResolver().query(scienceDataUri, null, null, null, null);
userDataCursor.moveToFirst();
mathDataCursor.moveToFirst();
englishDataCursor.moveToFirst();
moralDataCursor.moveToFirst();
scienceDataCursor.moveToFirst();
tempLoadArray.add(String.valueOf(userDataCursor.getInt(0))); //id 0
tempLoadArray.add(userDataCursor.getString(1)); //firstname 1
tempLoadArray.add(userDataCursor.getString(2)); //lastname 2
tempLoadArray.add(userDataCursor.getString(3)); //username 3
tempLoadArray.add(userDataCursor.getString(4)); //password 4
tempLoadArray.add(userDataCursor.getString(5)); //photo 5
tempLoadArray.add(userDataCursor.getString(6)); //total point 6
//get math data
tempLoadArray.add(mathDataCursor.getString(1)); //math_pr 7
tempLoadArray.add(mathDataCursor.getString(2)); //math_point1 8
tempLoadArray.add(mathDataCursor.getString(3)); //math_point2 9
tempLoadArray.add(mathDataCursor.getString(4)); //math_point3 10
tempLoadArray.add(mathDataCursor.getString(5)); //math_point4 11
tempLoadArray.add(mathDataCursor.getString(6)); //math_point5 12
tempLoadArray.add(mathDataCursor.getString(7)); //math_complete 13
//get english data
tempLoadArray.add(englishDataCursor.getString(1)); //english_pr 14
tempLoadArray.add(englishDataCursor.getString(2)); //english_point1 15
tempLoadArray.add(englishDataCursor.getString(3)); //english_point2 16
tempLoadArray.add(englishDataCursor.getString(4)); //english_point3 17
tempLoadArray.add(englishDataCursor.getString(5)); //english_point4 18
tempLoadArray.add(englishDataCursor.getString(6)); //english_point5 19
tempLoadArray.add(englishDataCursor.getString(7)); //english_complete 20
//get moral data
tempLoadArray.add(moralDataCursor.getString(1)); //moral_pr 21
tempLoadArray.add(moralDataCursor.getString(2)); //moral_point1 22
tempLoadArray.add(moralDataCursor.getString(3)); //moral_point2 23
tempLoadArray.add(moralDataCursor.getString(4)); //moral_point3 24
tempLoadArray.add(moralDataCursor.getString(5)); //moral_point4 25
tempLoadArray.add(moralDataCursor.getString(6)); //moral_point5 26
tempLoadArray.add(moralDataCursor.getString(7)); //moral_complete 27
//get science data
tempLoadArray.add(scienceDataCursor.getString(1)); //science_pr 28
tempLoadArray.add(scienceDataCursor.getString(2)); //science_point1 29
tempLoadArray.add(scienceDataCursor.getString(3)); //science_point2 30
tempLoadArray.add(scienceDataCursor.getString(4)); //science_point3 31
tempLoadArray.add(scienceDataCursor.getString(5)); //science_point4 32
tempLoadArray.add(scienceDataCursor.getString(6)); //science_point5 33
tempLoadArray.add(scienceDataCursor.getString(7)); //science_complete 34
userDataCursor.close();
mathDataCursor.close();
englishDataCursor.close();
moralDataCursor.close();
scienceDataCursor.close();
return tempLoadArray;
}
void UpdateUserData(String userId) {
String subject = applicationData.mSubject;
Uri userDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/" + userId);
Uri mathDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/math/" + userId);
Uri englishDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/english/" + userId);
Uri moralDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/moral/" + userId);
Uri scienceDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/science/" + userId);
ContentValues values = new ContentValues();
ContentValues userValues = new ContentValues();
userValues.put("total_point", applicationData.mTotalPoint);
mContext.getContentResolver().update(userDataUri, userValues, null, null);
switch (subject) {
case "math":
values.put("math_pr", applicationData.mMathPr);
values.put("math_point1", applicationData.mMathPoint1);
values.put("math_point2", applicationData.mMathPoint2);
values.put("math_point3", applicationData.mMathPoint3);
values.put("math_point4", applicationData.mMathPoint4);
values.put("math_point5", applicationData.mMathPoint5);
values.put("math_complete", applicationData.mMathComplete);
mContext.getContentResolver().update(mathDataUri, values, null, null);
break;
case "english":
values.put("english_pr", applicationData.mEnglishPr);
values.put("english_point1", applicationData.mEnglishPoint1);
values.put("english_point2", applicationData.mEnglishPoint2);
values.put("english_point3", applicationData.mEnglishPoint3);
values.put("english_point4", applicationData.mEnglishPoint4);
values.put("english_point5", applicationData.mEnglishPoint5);
values.put("english_complete", applicationData.mEnglishComplete);
mContext.getContentResolver().update(englishDataUri, values, null, null);
break;
case "moral":
values.put("culture_pr", applicationData.mMoralPr);
values.put("culture_point1", applicationData.mMoralPoint1);
values.put("culture_point2", applicationData.mMoralPoint2);
values.put("culture_point3", applicationData.mMoralPoint3);
values.put("culture_point4", applicationData.mMoralPoint4);
values.put("culture_point5", applicationData.mMoralPoint5);
values.put("culture_complete", applicationData.mMoralComplete);
mContext.getContentResolver().update(moralDataUri, values, null, null);
break;
case "science":
values.put("science_pr", applicationData.mSciencePr);
values.put("science_point1", applicationData.mSciencePoint1);
values.put("science_point2", applicationData.mSciencePoint2);
values.put("science_point3", applicationData.mSciencePoint3);
values.put("science_point4", applicationData.mSciencePoint4);
values.put("science_point5", applicationData.mSciencePoint5);
values.put("science_complete", applicationData.mScienceComplete);
mContext.getContentResolver().update(scienceDataUri, values, null, null);
break;
}
}
}
|
UTF-8
|
Java
| 10,226 |
java
|
ProviderAccessClass.java
|
Java
|
[
{
"context": "\nimport java.util.ArrayList;\r\n\r\n/**\r\n * Created by dwida on 29/7/2015.\r\n */\r\npublic class ProviderAccessCl",
"end": 287,
"score": 0.9994067549705505,
"start": 282,
"tag": "USERNAME",
"value": "dwida"
},
{
"context": "DataCursor.getString(4)); //password 4\r\n tempLoadArray.add(userDataCursor.getStri",
"end": 3713,
"score": 0.9274280667304993,
"start": 3712,
"tag": "PASSWORD",
"value": "4"
}
] | null |
[] |
package com.backbone.dwida.eugitasklist;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by dwida on 29/7/2015.
*/
public class ProviderAccessClass extends AsyncTask<Void, Integer, ArrayList<String>> {
Context mContext;
String mOperationMode;
ApplicationData applicationData;
public static final String UPDATE = "update";
public static final String LOAD = "load";
Uri loggedinUri = Uri.parse("content://com.backbone.dwida.eugiprovider/loggedin");
public ProviderAccessClass(Context context, String operationmode) {
this.mContext = context;
this.mOperationMode = operationmode;
applicationData = (ApplicationData)mContext.getApplicationContext();
}
@Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> tempArray = new ArrayList<String>();
Cursor loggedinCursor = mContext.getContentResolver().query(loggedinUri, null, null, null, null);
loggedinCursor.moveToLast();
String userId = String.valueOf(loggedinCursor.getInt(0));
loggedinCursor.close();
switch(mOperationMode) {
case LOAD :
tempArray = LoadUserData(userId);
break;
case UPDATE :
UpdateUserData(userId);
break;
}
return tempArray;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.d("Progress", String.valueOf(values));
}
@Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
}
ArrayList<String> LoadUserData(String userId) {
ArrayList<String> tempLoadArray = new ArrayList<String>();
Uri userDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/" + userId);
Uri mathDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/math/" + userId);
Uri englishDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/english/" + userId);
Uri moralDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/moral/" + userId);
Uri scienceDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/science/" + userId);
Cursor userDataCursor = mContext.getContentResolver().query(userDataUri, null, null, null, null);
Cursor mathDataCursor = mContext.getContentResolver().query(mathDataUri, null, null, null, null);
Cursor englishDataCursor = mContext.getContentResolver().query(englishDataUri, null, null, null, null);
Cursor moralDataCursor = mContext.getContentResolver().query(moralDataUri, null, null, null, null);
Cursor scienceDataCursor = mContext.getContentResolver().query(scienceDataUri, null, null, null, null);
userDataCursor.moveToFirst();
mathDataCursor.moveToFirst();
englishDataCursor.moveToFirst();
moralDataCursor.moveToFirst();
scienceDataCursor.moveToFirst();
tempLoadArray.add(String.valueOf(userDataCursor.getInt(0))); //id 0
tempLoadArray.add(userDataCursor.getString(1)); //firstname 1
tempLoadArray.add(userDataCursor.getString(2)); //lastname 2
tempLoadArray.add(userDataCursor.getString(3)); //username 3
tempLoadArray.add(userDataCursor.getString(4)); //password 4
tempLoadArray.add(userDataCursor.getString(5)); //photo 5
tempLoadArray.add(userDataCursor.getString(6)); //total point 6
//get math data
tempLoadArray.add(mathDataCursor.getString(1)); //math_pr 7
tempLoadArray.add(mathDataCursor.getString(2)); //math_point1 8
tempLoadArray.add(mathDataCursor.getString(3)); //math_point2 9
tempLoadArray.add(mathDataCursor.getString(4)); //math_point3 10
tempLoadArray.add(mathDataCursor.getString(5)); //math_point4 11
tempLoadArray.add(mathDataCursor.getString(6)); //math_point5 12
tempLoadArray.add(mathDataCursor.getString(7)); //math_complete 13
//get english data
tempLoadArray.add(englishDataCursor.getString(1)); //english_pr 14
tempLoadArray.add(englishDataCursor.getString(2)); //english_point1 15
tempLoadArray.add(englishDataCursor.getString(3)); //english_point2 16
tempLoadArray.add(englishDataCursor.getString(4)); //english_point3 17
tempLoadArray.add(englishDataCursor.getString(5)); //english_point4 18
tempLoadArray.add(englishDataCursor.getString(6)); //english_point5 19
tempLoadArray.add(englishDataCursor.getString(7)); //english_complete 20
//get moral data
tempLoadArray.add(moralDataCursor.getString(1)); //moral_pr 21
tempLoadArray.add(moralDataCursor.getString(2)); //moral_point1 22
tempLoadArray.add(moralDataCursor.getString(3)); //moral_point2 23
tempLoadArray.add(moralDataCursor.getString(4)); //moral_point3 24
tempLoadArray.add(moralDataCursor.getString(5)); //moral_point4 25
tempLoadArray.add(moralDataCursor.getString(6)); //moral_point5 26
tempLoadArray.add(moralDataCursor.getString(7)); //moral_complete 27
//get science data
tempLoadArray.add(scienceDataCursor.getString(1)); //science_pr 28
tempLoadArray.add(scienceDataCursor.getString(2)); //science_point1 29
tempLoadArray.add(scienceDataCursor.getString(3)); //science_point2 30
tempLoadArray.add(scienceDataCursor.getString(4)); //science_point3 31
tempLoadArray.add(scienceDataCursor.getString(5)); //science_point4 32
tempLoadArray.add(scienceDataCursor.getString(6)); //science_point5 33
tempLoadArray.add(scienceDataCursor.getString(7)); //science_complete 34
userDataCursor.close();
mathDataCursor.close();
englishDataCursor.close();
moralDataCursor.close();
scienceDataCursor.close();
return tempLoadArray;
}
void UpdateUserData(String userId) {
String subject = applicationData.mSubject;
Uri userDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/" + userId);
Uri mathDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/math/" + userId);
Uri englishDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/english/" + userId);
Uri moralDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/moral/" + userId);
Uri scienceDataUri = Uri.parse("content://com.backbone.dwida.eugiprovider/users/science/" + userId);
ContentValues values = new ContentValues();
ContentValues userValues = new ContentValues();
userValues.put("total_point", applicationData.mTotalPoint);
mContext.getContentResolver().update(userDataUri, userValues, null, null);
switch (subject) {
case "math":
values.put("math_pr", applicationData.mMathPr);
values.put("math_point1", applicationData.mMathPoint1);
values.put("math_point2", applicationData.mMathPoint2);
values.put("math_point3", applicationData.mMathPoint3);
values.put("math_point4", applicationData.mMathPoint4);
values.put("math_point5", applicationData.mMathPoint5);
values.put("math_complete", applicationData.mMathComplete);
mContext.getContentResolver().update(mathDataUri, values, null, null);
break;
case "english":
values.put("english_pr", applicationData.mEnglishPr);
values.put("english_point1", applicationData.mEnglishPoint1);
values.put("english_point2", applicationData.mEnglishPoint2);
values.put("english_point3", applicationData.mEnglishPoint3);
values.put("english_point4", applicationData.mEnglishPoint4);
values.put("english_point5", applicationData.mEnglishPoint5);
values.put("english_complete", applicationData.mEnglishComplete);
mContext.getContentResolver().update(englishDataUri, values, null, null);
break;
case "moral":
values.put("culture_pr", applicationData.mMoralPr);
values.put("culture_point1", applicationData.mMoralPoint1);
values.put("culture_point2", applicationData.mMoralPoint2);
values.put("culture_point3", applicationData.mMoralPoint3);
values.put("culture_point4", applicationData.mMoralPoint4);
values.put("culture_point5", applicationData.mMoralPoint5);
values.put("culture_complete", applicationData.mMoralComplete);
mContext.getContentResolver().update(moralDataUri, values, null, null);
break;
case "science":
values.put("science_pr", applicationData.mSciencePr);
values.put("science_point1", applicationData.mSciencePoint1);
values.put("science_point2", applicationData.mSciencePoint2);
values.put("science_point3", applicationData.mSciencePoint3);
values.put("science_point4", applicationData.mSciencePoint4);
values.put("science_point5", applicationData.mSciencePoint5);
values.put("science_complete", applicationData.mScienceComplete);
mContext.getContentResolver().update(scienceDataUri, values, null, null);
break;
}
}
}
| 10,226 | 0.642089 | 0.626149 | 205 | 47.882927 | 35.301987 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
9
|
ecd74800deff56ae03bda87c5f831c388ba54077
| 27,453,430,990,377 |
2a5d78aafe662b3a8c4a7686a5a1eaf9ed5af046
|
/src/main/java/ru/job4j/ood/food/rule/DiscountRule.java
|
c5f8c01c5a681a5728d7039b2ebd94275bbb8c5e
|
[] |
no_license
|
kalenikov/job4j_grabber
|
https://github.com/kalenikov/job4j_grabber
|
8d0324f8188e365131ba8addeef64f980888d783
|
610f362440679c32ee8d22f5da041e6798be0452
|
refs/heads/master
| 2023-09-04T10:37:17.895000 | 2021-11-16T07:20:32 | 2021-11-16T07:20:39 | 368,253,454 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.job4j.ood.food.rule;
import java.util.function.Predicate;
/**
* класс, описывающий условия применение скидок
*/
public class DiscountRule extends AbstractRule<Integer, Integer> {
public DiscountRule(Predicate<Integer> predicate, Integer result) {
super(predicate, result);
}
}
|
UTF-8
|
Java
| 348 |
java
|
DiscountRule.java
|
Java
|
[] | null |
[] |
package ru.job4j.ood.food.rule;
import java.util.function.Predicate;
/**
* класс, описывающий условия применение скидок
*/
public class DiscountRule extends AbstractRule<Integer, Integer> {
public DiscountRule(Predicate<Integer> predicate, Integer result) {
super(predicate, result);
}
}
| 348 | 0.734628 | 0.731392 | 13 | 22.76923 | 25.201202 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false |
9
|
6f847cde9d743162bb2533a3e5cce3bb66b0d074
| 15,522,011,830,511 |
f17688ad55c76cf8aee8e02330248d2fcc572078
|
/src/org/nutz/walnut/web/WnMainModule.java
|
8fabca8fa7c403cc1fb72e0aa410657ae0a71f62
|
[
"Apache-2.0"
] |
permissive
|
zozoh/ess
|
https://github.com/zozoh/ess
|
806cb0e709b668279acb6d2fb5f7a3f735adf9c3
|
2c366ca833ebdfbfd44ca5765317d1df781179db
|
refs/heads/master
| 2016-09-07T05:25:00.068000 | 2015-05-07T08:44:01 | 2015-05-07T08:44:01 | 21,301,303 | 1 | 0 | null | false | 2015-03-05T14:49:36 | 2014-06-28T11:22:58 | 2015-03-05T14:26:03 | 2015-03-05T14:42:35 | 3,384 | 0 | 0 | 2 |
Java
| null | null |
package org.nutz.walnut.web;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.ChainBy;
import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Localization;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.SetupBy;
import org.nutz.mvc.annotation.Views;
import org.nutz.mvc.ioc.provider.ComboIocProvider;
import org.nutz.walnut.api.usr.ZSession;
import org.nutz.walnut.util.Wn;
import org.nutz.walnut.web.module.AbstractWnModule;
import org.nutz.walnut.web.view.WnViewMaker;
import org.nutz.web.WebException;
import org.nutz.web.ajax.AjaxViewMaker;
@SetupBy(WnSetup.class)
@IocBy(type = ComboIocProvider.class,
args = {"*org.nutz.ioc.loader.json.JsonLoader",
"ioc",
"*org.nutz.ioc.loader.annotation.AnnotationIocLoader",
"org.nutz.walnut",
"$dynamic"})
@Modules(scanPackage = true, packages = {"org.nutz.walnut.web.module", "$dynamic"})
@Localization("msg")
@Views({AjaxViewMaker.class, WnViewMaker.class})
@ChainBy(args = {"chain/walnut-chain.js"})
@IocBean
public class WnMainModule extends AbstractWnModule {
@Inject("java:$conf.get('main-app', 'console')")
private String mainApp;
@At("/version")
@Ok("jsp:jsp.show_text")
public String version() {
return "1.0" + io.toString();
}
@At("/")
@Ok(">>:${obj}")
public String doCheck() {
String seid = Wn.WC().SEID();
if (null == seid)
return "/u/login";
try {
ZSession se = sess.check(seid);
// 记录到上下文
Wn.WC().SE(se);
Wn.WC().me(se.me());
// 查看会话环境变量,看看需要转到哪个应用
String appPath = se.envs().getString("OPEN", mainApp);
// 那么 Session 木有问题了
return "/a/open/" + appPath;
}
catch (WebException e) {
return "/u/login";
}
}
}
|
UTF-8
|
Java
| 2,108 |
java
|
WnMainModule.java
|
Java
|
[] | null |
[] |
package org.nutz.walnut.web;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.ChainBy;
import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Localization;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.SetupBy;
import org.nutz.mvc.annotation.Views;
import org.nutz.mvc.ioc.provider.ComboIocProvider;
import org.nutz.walnut.api.usr.ZSession;
import org.nutz.walnut.util.Wn;
import org.nutz.walnut.web.module.AbstractWnModule;
import org.nutz.walnut.web.view.WnViewMaker;
import org.nutz.web.WebException;
import org.nutz.web.ajax.AjaxViewMaker;
@SetupBy(WnSetup.class)
@IocBy(type = ComboIocProvider.class,
args = {"*org.nutz.ioc.loader.json.JsonLoader",
"ioc",
"*org.nutz.ioc.loader.annotation.AnnotationIocLoader",
"org.nutz.walnut",
"$dynamic"})
@Modules(scanPackage = true, packages = {"org.nutz.walnut.web.module", "$dynamic"})
@Localization("msg")
@Views({AjaxViewMaker.class, WnViewMaker.class})
@ChainBy(args = {"chain/walnut-chain.js"})
@IocBean
public class WnMainModule extends AbstractWnModule {
@Inject("java:$conf.get('main-app', 'console')")
private String mainApp;
@At("/version")
@Ok("jsp:jsp.show_text")
public String version() {
return "1.0" + io.toString();
}
@At("/")
@Ok(">>:${obj}")
public String doCheck() {
String seid = Wn.WC().SEID();
if (null == seid)
return "/u/login";
try {
ZSession se = sess.check(seid);
// 记录到上下文
Wn.WC().SE(se);
Wn.WC().me(se.me());
// 查看会话环境变量,看看需要转到哪个应用
String appPath = se.envs().getString("OPEN", mainApp);
// 那么 Session 木有问题了
return "/a/open/" + appPath;
}
catch (WebException e) {
return "/u/login";
}
}
}
| 2,108 | 0.632094 | 0.631115 | 69 | 28.623188 | 18.654837 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.550725 | false | false |
9
|
258aefcb85cf56b6018032d55c96bedfcbae9f29
| 9,131,100,483,748 |
c55749a5a6341485a8e432e475ff40fe7b4d3027
|
/src/main/java/com/demo/Main.java
|
4b2798a6eb38d19df3ce3b9546d2fe844bdeb27c
|
[] |
no_license
|
deepak-8i/IntersectionsTask
|
https://github.com/deepak-8i/IntersectionsTask
|
0a778054438b72ba82731e7d70381c43670ce661
|
417c743be5001842b58a4e7cccab22cfbe55739a
|
refs/heads/master
| 2022-12-25T17:29:07.440000 | 2020-07-23T06:43:41 | 2020-07-23T06:43:41 | 281,675,230 | 0 | 0 | null | false | 2020-10-13T23:50:03 | 2020-07-22T12:45:45 | 2020-07-23T06:43:44 | 2020-10-13T23:50:02 | 5 | 0 | 0 | 1 |
Java
| false | false |
package com.demo;
import com.demo.intersection.Intersection;
import com.demo.reader.InputReader;
public class Main {
public static void main(String args[]) {
InputReader reader = new InputReader();
int[][] lines = reader.readInput(); // Read input from the console
Intersection intersection = new Intersection();
System.out.println("Max intersections : " + intersection.findMaxIntersection(lines));
}
}
|
UTF-8
|
Java
| 449 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package com.demo;
import com.demo.intersection.Intersection;
import com.demo.reader.InputReader;
public class Main {
public static void main(String args[]) {
InputReader reader = new InputReader();
int[][] lines = reader.readInput(); // Read input from the console
Intersection intersection = new Intersection();
System.out.println("Max intersections : " + intersection.findMaxIntersection(lines));
}
}
| 449 | 0.690423 | 0.690423 | 16 | 27.0625 | 28.929804 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false |
9
|
2f6720dc3b246bf741c8b9d387fdb5f3c795d40f
| 1,537,598,337,356 |
bdeb36ad2becf46c31fd75d6353ec09bd73c62f4
|
/part-0/src/main/java/com/example/basic/D05Array/arrays/ArraysTest.java
|
d33cd040c89af9a17b41b5107672808d7d04e3e9
|
[] |
no_license
|
xd1810232299/study
|
https://github.com/xd1810232299/study
|
d5442df98828c1d08efbd7d6c74694365433dec7
|
82222f8ae2f410d8e406da6c25dc205d7b3cb5dd
|
refs/heads/master
| 2020-08-23T07:59:07.456000 | 2020-08-03T03:17:39 | 2020-08-03T03:17:39 | 216,575,009 | 0 | 0 | null | false | 2020-10-15T03:16:59 | 2019-10-21T13:27:33 | 2020-10-15T03:06:34 | 2020-10-15T03:16:58 | 82,813 | 0 | 0 | 0 |
Java
| false | false |
package com.example.basic.D05Array.arrays;
import java.util.Arrays;
/**
* 操作数组的工具类
*/
public class ArraysTest {
public static void main(String[] args) {
//equals
int[] arr1 = new int[]{1, 2, 3};
int[] arr2 = new int[]{1, 3, 2};
boolean equals = Arrays.equals(arr1, arr2);
System.out.println(equals);//必须顺序相同才相等
//toString [1, 2, 3]
System.out.println(Arrays.toString(arr1));
//fill:将指定的值放入数组中,所有值都被替换 [10, 10, 10]
Arrays.fill(arr1, 10);
System.out.println(Arrays.toString(arr1));
//sort:排序
Arrays.sort(arr2);
System.out.println(Arrays.toString(arr2));
//binarySearch
int[] arr = new int[]{-89, -45, -33, 2, 45, 74};
int i = Arrays.binarySearch(arr, -33);
System.out.println(i);//返回是负数 就是未找到
}
}
|
UTF-8
|
Java
| 954 |
java
|
ArraysTest.java
|
Java
|
[] | null |
[] |
package com.example.basic.D05Array.arrays;
import java.util.Arrays;
/**
* 操作数组的工具类
*/
public class ArraysTest {
public static void main(String[] args) {
//equals
int[] arr1 = new int[]{1, 2, 3};
int[] arr2 = new int[]{1, 3, 2};
boolean equals = Arrays.equals(arr1, arr2);
System.out.println(equals);//必须顺序相同才相等
//toString [1, 2, 3]
System.out.println(Arrays.toString(arr1));
//fill:将指定的值放入数组中,所有值都被替换 [10, 10, 10]
Arrays.fill(arr1, 10);
System.out.println(Arrays.toString(arr1));
//sort:排序
Arrays.sort(arr2);
System.out.println(Arrays.toString(arr2));
//binarySearch
int[] arr = new int[]{-89, -45, -33, 2, 45, 74};
int i = Arrays.binarySearch(arr, -33);
System.out.println(i);//返回是负数 就是未找到
}
}
| 954 | 0.563084 | 0.515187 | 38 | 21.526316 | 20.337593 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false |
9
|
86f225419e8e224c47949ab66277579ab2639249
| 1,864,015,852,526 |
8a73028cf0fafdaba8e40c6f6607b58c6da99ef3
|
/type/MethodType.java
|
9c186bce9e3f018d33b3353f8a18f691670b25da
|
[] |
no_license
|
jkirkwin/Custom-Compiler
|
https://github.com/jkirkwin/Custom-Compiler
|
9c12f3569b04103672e8c276b494d04e9357ec6b
|
2ed7170142961bc1e7c913e5e2f83d676a94765a
|
refs/heads/master
| 2023-06-29T16:31:49.044000 | 2021-08-02T21:00:41 | 2021-08-02T21:00:41 | 365,043,556 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents the type of a method.
* Contains a return type and zero or more ordered argument types.
*/
public class MethodType {
/**
* Used to more easily construct a MethodType.
*/
public static class Builder {
private Type returnType = VoidType.INSTANCE;
private final List<Type> argumentTypes = new ArrayList<Type>();
/**
* Creates a new Builder for a MethodType with
* return type void and no arguments.
*/
public Builder withReturnType(Type retType) {
returnType = retType;
return this;
}
public Builder addArgumentType(Type argType) {
argumentTypes.add(argType);
return this;
}
public MethodType build() {
return new MethodType(returnType, argumentTypes);
}
}
public final Type returnType;
public final List<Type> argumentTypes; // Immutable so can be public
/**
* Construct a new MethodType with no arguments.
*/
public MethodType(Type returnType) {
assert returnType != null;
this.returnType = returnType;
argumentTypes = new ArrayList<Type>();
}
public MethodType(Type returnType, List<Type> argTypes) {
assert returnType != null;
assert argTypes != null;
this.returnType = returnType;
argumentTypes = Collections.unmodifiableList(new ArrayList<Type>(argTypes));
}
public String toString() {
return toJasminString();
}
public String toIRString() {
StringBuilder sb = new StringBuilder("(");
for (var t : argumentTypes) {
sb.append(t.toIRString());
}
sb.append(')')
.append(returnType.toIRString());
return sb.toString();
}
public String toJasminString() {
StringBuilder sb = new StringBuilder("(");
for (var t : argumentTypes) {
sb.append(t.toJasminString());
}
sb.append(')')
.append(returnType.toJasminString());
return sb.toString();
}
}
|
UTF-8
|
Java
| 2,205 |
java
|
MethodType.java
|
Java
|
[] | null |
[] |
package type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents the type of a method.
* Contains a return type and zero or more ordered argument types.
*/
public class MethodType {
/**
* Used to more easily construct a MethodType.
*/
public static class Builder {
private Type returnType = VoidType.INSTANCE;
private final List<Type> argumentTypes = new ArrayList<Type>();
/**
* Creates a new Builder for a MethodType with
* return type void and no arguments.
*/
public Builder withReturnType(Type retType) {
returnType = retType;
return this;
}
public Builder addArgumentType(Type argType) {
argumentTypes.add(argType);
return this;
}
public MethodType build() {
return new MethodType(returnType, argumentTypes);
}
}
public final Type returnType;
public final List<Type> argumentTypes; // Immutable so can be public
/**
* Construct a new MethodType with no arguments.
*/
public MethodType(Type returnType) {
assert returnType != null;
this.returnType = returnType;
argumentTypes = new ArrayList<Type>();
}
public MethodType(Type returnType, List<Type> argTypes) {
assert returnType != null;
assert argTypes != null;
this.returnType = returnType;
argumentTypes = Collections.unmodifiableList(new ArrayList<Type>(argTypes));
}
public String toString() {
return toJasminString();
}
public String toIRString() {
StringBuilder sb = new StringBuilder("(");
for (var t : argumentTypes) {
sb.append(t.toIRString());
}
sb.append(')')
.append(returnType.toIRString());
return sb.toString();
}
public String toJasminString() {
StringBuilder sb = new StringBuilder("(");
for (var t : argumentTypes) {
sb.append(t.toJasminString());
}
sb.append(')')
.append(returnType.toJasminString());
return sb.toString();
}
}
| 2,205 | 0.595918 | 0.595918 | 89 | 23.77528 | 21.565554 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.348315 | false | false |
9
|
a732a8e8a47f2436037c97243f8b438f6aba05eb
| 16,389,595,266,372 |
1a9fb245b385d22ad5d3cd1408263f8b831ef140
|
/Solver/Block.java
|
f0360640589866819f60fb94bad464776bfdb941
|
[] |
no_license
|
wakahiu/SLIDING_BLOCKS
|
https://github.com/wakahiu/SLIDING_BLOCKS
|
f26cd3ae4bafe368d48638ff6afe2b308659635a
|
65ddbf3626b9118db4d383ce1010f1599d683052
|
refs/heads/master
| 2020-12-24T14:35:35.249000 | 2013-01-23T19:02:37 | 2013-01-23T19:02:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Block
{
private int myC;
private int myR;
private int length;
private int width;
public Block()
{
}
public Block( int L , int W , int R , int C )
{
this.myC = C;
this.myR = R;
this.length = L;
this.width = W;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getR(){
return myR;
}
public int getC(){
return myC;
}
public int hashCode()
{
return this.length << 24 | this.myR << 16 | this.myC << 8 | this.width;
}
public String toString()
{
return "" + this.length + "*" + this.width + " (" + this.myR + "," + this.myC + ")";
}
public boolean equals( Object Obj)
{
if( Obj instanceof Block )
{
Block temp = (Block)Obj;
return temp.length == this.length && temp.width == this.width
&& temp.myC == this.myC && temp.myR == this.myR;
}else
{
return false;
}
}
}
|
UTF-8
|
Java
| 892 |
java
|
Block.java
|
Java
|
[] | null |
[] |
public class Block
{
private int myC;
private int myR;
private int length;
private int width;
public Block()
{
}
public Block( int L , int W , int R , int C )
{
this.myC = C;
this.myR = R;
this.length = L;
this.width = W;
}
public int getLength(){
return length;
}
public int getWidth(){
return width;
}
public int getR(){
return myR;
}
public int getC(){
return myC;
}
public int hashCode()
{
return this.length << 24 | this.myR << 16 | this.myC << 8 | this.width;
}
public String toString()
{
return "" + this.length + "*" + this.width + " (" + this.myR + "," + this.myC + ")";
}
public boolean equals( Object Obj)
{
if( Obj instanceof Block )
{
Block temp = (Block)Obj;
return temp.length == this.length && temp.width == this.width
&& temp.myC == this.myC && temp.myR == this.myR;
}else
{
return false;
}
}
}
| 892 | 0.585202 | 0.579596 | 57 | 14.666667 | 18.644724 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.631579 | false | false |
9
|
ed107a0235ea98db74c28da29e19b686d1369ec4
| 18,210,661,339,459 |
ed0261afd3d7af2a2c7c226c1ea8577ce5ff5c58
|
/src/Task/PrintProductInfo.java
|
754106b17207610b6572f05bc61ed897a1bc3ae4
|
[] |
no_license
|
Mukaddes06/JavaPractice2020
|
https://github.com/Mukaddes06/JavaPractice2020
|
c7be9367af64178767a886d4f4ff3854c73cbd5f
|
fd92e845e6cc95764117ab74ae44c0899583c372
|
refs/heads/master
| 2020-12-03T22:26:47.732000 | 2020-02-29T18:01:58 | 2020-02-29T18:01:58 | 231,504,657 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Task;
public class PrintProductInfo {
public static void main(String[] args) {
printProductInfo("Fire","HD",8,79.99f);
}
public static void printProductInfo(String productName, String model, int version, float price) {
System.out.println("I saw " + productName + " " + model + version + " hands-free with Alexa for " + price);
}
}
|
UTF-8
|
Java
| 364 |
java
|
PrintProductInfo.java
|
Java
|
[] | null |
[] |
package Task;
public class PrintProductInfo {
public static void main(String[] args) {
printProductInfo("Fire","HD",8,79.99f);
}
public static void printProductInfo(String productName, String model, int version, float price) {
System.out.println("I saw " + productName + " " + model + version + " hands-free with Alexa for " + price);
}
}
| 364 | 0.673077 | 0.659341 | 11 | 32.18182 | 38.930752 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false |
9
|
9f41978130641a9cc80478a6026af1f21d2f5e77
| 18,210,661,338,011 |
055db3c52b3568b1ab0da95544791673a533d985
|
/src/me/Darrionat/LobbyPlus/Listeners/RainbowArmorClick.java
|
369a0a2b6c971a9bad70207c4bc7bb28876f95fb
|
[] |
no_license
|
Darrionat/LobbyPlus
|
https://github.com/Darrionat/LobbyPlus
|
2b37cb127778b8ec7418fe8c0196ce0714977319
|
199a4c4dee9a01caefd28123576c84a0a01179a4
|
refs/heads/master
| 2020-06-20T06:35:59.542000 | 2020-03-24T15:15:15 | 2020-03-24T15:15:15 | 197,027,848 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package me.Darrionat.LobbyPlus.Listeners;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.Darrionat.LobbyPlus.Main;
import me.Darrionat.LobbyPlus.Utils;
public class RainbowArmorClick implements Listener {
private Main plugin;
public RainbowArmorClick(Main plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onClick(InventoryClickEvent e) {
// Rainbow Helmet
Player p = (Player) e.getWhoClicked();
if (e.getCurrentItem() == null) {
return;
}
ItemStack rainbowhelmet = new ItemStack(Material.LEATHER_HELMET, 1);
ItemMeta rainbowhelmmeta = rainbowhelmet.getItemMeta();
ArrayList<String> rainbowhelmlore = new ArrayList<String>();
rainbowhelmmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowhelmmeta.setLore(rainbowhelmlore);
rainbowhelmet.setItemMeta(rainbowhelmmeta);
// Chestplate
ItemStack rainbowchestplate = new ItemStack(Material.LEATHER_CHESTPLATE, 1);
ItemMeta rainbowchestmeta = rainbowchestplate.getItemMeta();
ArrayList<String> rainbowchestlore = new ArrayList<String>();
rainbowchestmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowchestmeta.setLore(rainbowchestlore);
rainbowchestplate.setItemMeta(rainbowchestmeta);
// Leggings
ItemStack rainbowleggings = new ItemStack(Material.LEATHER_LEGGINGS, 1);
ItemMeta rainbowleggingsmeta = rainbowleggings.getItemMeta();
ArrayList<String> rainbowleggingslore = new ArrayList<String>();
rainbowleggingsmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowleggingsmeta.setLore(rainbowleggingslore);
rainbowleggings.setItemMeta(rainbowleggingsmeta);
// Boots
ItemStack rainbowboots = new ItemStack(Material.LEATHER_BOOTS, 1);
ItemMeta rainbowbootsmeta = rainbowboots.getItemMeta();
ArrayList<String> rainbowbootslore = new ArrayList<String>();
rainbowbootsmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowbootsmeta.setLore(rainbowbootslore);
rainbowboots.setItemMeta(rainbowbootsmeta);
if (e.getCurrentItem().getItemMeta() == null) {
return;
}
if (p.getGameMode() == GameMode.CREATIVE) {
return;
}
String clickname = e.getCurrentItem().getItemMeta().getDisplayName();
if (clickname.equalsIgnoreCase(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r"))) {
e.setCancelled(true);
}
}
@EventHandler
public void onDrop(PlayerDropItemEvent e) {
Player p = e.getPlayer();
Item item = e.getItemDrop();
ItemMeta itemmeta = item.getItemStack().getItemMeta();
String name = itemmeta.getDisplayName();
String rainbowarmorname = Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r");
if (!name.equalsIgnoreCase(rainbowarmorname)) {
return;
}
e.setCancelled(true);
}
}
|
UTF-8
|
Java
| 3,290 |
java
|
RainbowArmorClick.java
|
Java
|
[] | null |
[] |
package me.Darrionat.LobbyPlus.Listeners;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import me.Darrionat.LobbyPlus.Main;
import me.Darrionat.LobbyPlus.Utils;
public class RainbowArmorClick implements Listener {
private Main plugin;
public RainbowArmorClick(Main plugin) {
this.plugin = plugin;
Bukkit.getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onClick(InventoryClickEvent e) {
// Rainbow Helmet
Player p = (Player) e.getWhoClicked();
if (e.getCurrentItem() == null) {
return;
}
ItemStack rainbowhelmet = new ItemStack(Material.LEATHER_HELMET, 1);
ItemMeta rainbowhelmmeta = rainbowhelmet.getItemMeta();
ArrayList<String> rainbowhelmlore = new ArrayList<String>();
rainbowhelmmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowhelmmeta.setLore(rainbowhelmlore);
rainbowhelmet.setItemMeta(rainbowhelmmeta);
// Chestplate
ItemStack rainbowchestplate = new ItemStack(Material.LEATHER_CHESTPLATE, 1);
ItemMeta rainbowchestmeta = rainbowchestplate.getItemMeta();
ArrayList<String> rainbowchestlore = new ArrayList<String>();
rainbowchestmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowchestmeta.setLore(rainbowchestlore);
rainbowchestplate.setItemMeta(rainbowchestmeta);
// Leggings
ItemStack rainbowleggings = new ItemStack(Material.LEATHER_LEGGINGS, 1);
ItemMeta rainbowleggingsmeta = rainbowleggings.getItemMeta();
ArrayList<String> rainbowleggingslore = new ArrayList<String>();
rainbowleggingsmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowleggingsmeta.setLore(rainbowleggingslore);
rainbowleggings.setItemMeta(rainbowleggingsmeta);
// Boots
ItemStack rainbowboots = new ItemStack(Material.LEATHER_BOOTS, 1);
ItemMeta rainbowbootsmeta = rainbowboots.getItemMeta();
ArrayList<String> rainbowbootslore = new ArrayList<String>();
rainbowbootsmeta.setDisplayName(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r")); // Rainbow Armor
rainbowbootsmeta.setLore(rainbowbootslore);
rainbowboots.setItemMeta(rainbowbootsmeta);
if (e.getCurrentItem().getItemMeta() == null) {
return;
}
if (p.getGameMode() == GameMode.CREATIVE) {
return;
}
String clickname = e.getCurrentItem().getItemMeta().getDisplayName();
if (clickname.equalsIgnoreCase(Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r"))) {
e.setCancelled(true);
}
}
@EventHandler
public void onDrop(PlayerDropItemEvent e) {
Player p = e.getPlayer();
Item item = e.getItemDrop();
ItemMeta itemmeta = item.getItemStack().getItemMeta();
String name = itemmeta.getDisplayName();
String rainbowarmorname = Utils.chat("&cR&6a&ei&an&2b&9o&3w &cA&6r&em&ao&2r");
if (!name.equalsIgnoreCase(rainbowarmorname)) {
return;
}
e.setCancelled(true);
}
}
| 3,290 | 0.759878 | 0.74772 | 88 | 36.397728 | 27.609509 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.090909 | false | false |
9
|
41b453ccb2acd1b168986b0979244555d744cb6c
| 24,215,025,682,345 |
43824d34fa5e9ee77ed5e27d12510a01ca85e882
|
/ParserDriver.java
|
aec109cbf5b4e96b0ada0feb7b15d7cdca2c8940
|
[
"Apache-2.0"
] |
permissive
|
gatripat/InsAdjustment
|
https://github.com/gatripat/InsAdjustment
|
51c2a6cf4619059125bd4ba42931f59ef28f683a
|
cd85d3c127e6cd8ab24a3c0f641d6d5bb4879754
|
refs/heads/master
| 2021-01-10T11:12:41.320000 | 2016-05-03T11:54:17 | 2016-05-03T11:54:17 | 51,715,452 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.barclays.ifrs9;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
/**
*
* @author gatripat
*/
public class ParserDriver {
public static void main(String[] args) {
try {
runJob(args[0], args[1]);
} catch (IOException ex) {
Logger.getLogger(ParserDriver.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void runJob(String input, String output) throws IOException {
Configuration conf = new Configuration();
conf.set("xmlinput.start", "<CompactData>");
conf.set("xmlinput.end", "</CompactData>");
conf.set("io.serializations",
"org.apache.hadoop.io.serializer.JavaSerialization,org.apache.hadoop.io.serializer.WritableSerialization");
Job job = new Job(conf, "IFRS9");
FileInputFormat.setInputPaths(job, input);
job.setJarByClass(ParserDriver.class);
job.setMapperClass(ParserMapper.class);
job.setNumReduceTasks(0);
job.setInputFormatClass(XmlInputFormat.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
Path outPath = new Path(output);
FileOutputFormat.setOutputPath(job, outPath);
FileSystem dfs = FileSystem.get(outPath.toUri(), conf);
if (dfs.exists(outPath)) {
dfs.delete(outPath, true);
}
try {
job.waitForCompletion(true);
} catch (InterruptedException ex) {
Logger.getLogger(ParserDriver.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ParserDriver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
UTF-8
|
Java
| 1,988 |
java
|
ParserDriver.java
|
Java
|
[
{
"context": "ib.output.FileOutputFormat;\r\n\r\n/**\r\n *\r\n * @author gatripat\r\n */\r\npublic class ParserDriver {\r\n\r\n\tpublic stat",
"end": 526,
"score": 0.9993139505386353,
"start": 518,
"tag": "USERNAME",
"value": "gatripat"
}
] | null |
[] |
package com.barclays.ifrs9;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
/**
*
* @author gatripat
*/
public class ParserDriver {
public static void main(String[] args) {
try {
runJob(args[0], args[1]);
} catch (IOException ex) {
Logger.getLogger(ParserDriver.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void runJob(String input, String output) throws IOException {
Configuration conf = new Configuration();
conf.set("xmlinput.start", "<CompactData>");
conf.set("xmlinput.end", "</CompactData>");
conf.set("io.serializations",
"org.apache.hadoop.io.serializer.JavaSerialization,org.apache.hadoop.io.serializer.WritableSerialization");
Job job = new Job(conf, "IFRS9");
FileInputFormat.setInputPaths(job, input);
job.setJarByClass(ParserDriver.class);
job.setMapperClass(ParserMapper.class);
job.setNumReduceTasks(0);
job.setInputFormatClass(XmlInputFormat.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
Path outPath = new Path(output);
FileOutputFormat.setOutputPath(job, outPath);
FileSystem dfs = FileSystem.get(outPath.toUri(), conf);
if (dfs.exists(outPath)) {
dfs.delete(outPath, true);
}
try {
job.waitForCompletion(true);
} catch (InterruptedException ex) {
Logger.getLogger(ParserDriver.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ParserDriver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| 1,988 | 0.719819 | 0.717304 | 68 | 27.264706 | 24.900164 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.823529 | false | false |
9
|
4a36c7f72a6041aee3219e32106d7ae246ff57ec
| 32,555,852,143,252 |
0ca3d88f0d33dbff386ead1104c73480d818aebc
|
/src/main/java/com/example/demo/Models/Payment.java
|
b714deb86174d36372a3c387aa298625b2ceb8d6
|
[] |
no_license
|
red-vs/Application_2.0
|
https://github.com/red-vs/Application_2.0
|
e9104c581f0bdf1e435aa793d7f0b2be6e06fd7f
|
ec60de75ea9c2f6ba2f4bc2a9441af97688a015d
|
refs/heads/master
| 2021-01-04T02:04:43.889000 | 2019-04-18T02:06:35 | 2019-04-18T02:06:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.demo.Models;
import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.Objects;
@Entity
public class Payment {
private int pmtId;
private BigDecimal amt;
private Date datePaid;
// M:1 with Service Order
private ServiceOrder serviceOrder;
@ManyToOne
@JoinColumn(name="svo_id")
public ServiceOrder getServiceOrder() {
return serviceOrder;
}
public void setServiceOrder(ServiceOrder serviceOrder) {
this.serviceOrder = serviceOrder;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pmt_id", nullable = false)
public int getPmtId() {
return pmtId;
}
public void setPmtId(int pmtId) {
this.pmtId = pmtId;
}
@Basic
@Column(name = "amt", nullable = false, precision = 2)
public BigDecimal getAmt() {
return amt;
}
public void setAmt(BigDecimal amt) {
this.amt = amt;
}
@Basic
@Column(name = "date_paid", nullable = false)
public Date getDatePaid() {
return datePaid;
}
public void setDatePaid(Date datePaid) {
this.datePaid = datePaid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Payment payment = (Payment) o;
return pmtId == payment.pmtId &&
Objects.equals(amt, payment.amt) &&
Objects.equals(datePaid, payment.datePaid);
}
@Override
public int hashCode() {
return Objects.hash(pmtId, amt, datePaid);
}
}
|
UTF-8
|
Java
| 1,666 |
java
|
Payment.java
|
Java
|
[] | null |
[] |
package com.example.demo.Models;
import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.Objects;
@Entity
public class Payment {
private int pmtId;
private BigDecimal amt;
private Date datePaid;
// M:1 with Service Order
private ServiceOrder serviceOrder;
@ManyToOne
@JoinColumn(name="svo_id")
public ServiceOrder getServiceOrder() {
return serviceOrder;
}
public void setServiceOrder(ServiceOrder serviceOrder) {
this.serviceOrder = serviceOrder;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pmt_id", nullable = false)
public int getPmtId() {
return pmtId;
}
public void setPmtId(int pmtId) {
this.pmtId = pmtId;
}
@Basic
@Column(name = "amt", nullable = false, precision = 2)
public BigDecimal getAmt() {
return amt;
}
public void setAmt(BigDecimal amt) {
this.amt = amt;
}
@Basic
@Column(name = "date_paid", nullable = false)
public Date getDatePaid() {
return datePaid;
}
public void setDatePaid(Date datePaid) {
this.datePaid = datePaid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Payment payment = (Payment) o;
return pmtId == payment.pmtId &&
Objects.equals(amt, payment.amt) &&
Objects.equals(datePaid, payment.datePaid);
}
@Override
public int hashCode() {
return Objects.hash(pmtId, amt, datePaid);
}
}
| 1,666 | 0.613445 | 0.612245 | 72 | 22.138889 | 18.459644 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
9
|
72eea035f322c8040da46f366b72ae12864c64ea
| 33,715,493,276,260 |
a3c2e31d2b6ec8d54a3ae7f18622471c1187e0d8
|
/src/com/company/Fenetre2.java
|
1c803ffeff7cfe24613a65b54c56512b6a116ac7
|
[] |
no_license
|
Jinkieu/JavaTP2
|
https://github.com/Jinkieu/JavaTP2
|
ffa3504d1c70fea6250834786d0a5f8d70797314
|
3e0475954ca1503b60f882603bc09e84de773355
|
refs/heads/master
| 2020-04-23T14:40:39.529000 | 2019-03-11T07:37:23 | 2019-03-11T07:37:23 | 171,239,546 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Fenetre2 {
private JLabel title = new JLabel("Calcul de factorielle");
private JTextField textField = new JTextField(10);
private JButton button = new JButton("ADD");
private JButton button2 = new JButton("RESET");
private JButton resultat = new JButton("new");
private JPanel container = new JPanel();
private JPanel panTitle = new JPanel();
private JPanel panTextField = new JPanel();
private JPanel panButton = new JPanel();
private JPanel panButton2 = new JPanel();
private String text;
private JPanel panResultat = new JPanel();
private GridBagConstraints c = new GridBagConstraints();
int numero_button = 0;
public Fenetre2() {
JFrame fenetre = new JFrame();
fenetre.setTitle("TP Java exo 4");
fenetre.setSize(400, 400);
fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fenetre.setVisible(true);
fenetre.setLocationRelativeTo(null);
container.setLayout(new GridBagLayout());
panButton.add(button);
panButton2.add(button2);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
container.add(panTitle, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
container.add(panTextField, c);
/* c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 2;
container.add(panResultat,c);
*/
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 3;
container.add(panButton, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 5;
container.add(panButton2, c);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//remove
container.removeAll();
container.repaint();
container.revalidate();
//processes user's input
add();
//update Jpanel of the result
container.add(button2);
container.add(button);
container.repaint();
container.revalidate();
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//remove
container.removeAll();
container.repaint();
container.revalidate();
//processes user's input
reset();
//update Jpanel of the result
container.add(button);
container.repaint();
container.revalidate();
}
});
fenetre.setContentPane(container);
fenetre.setVisible(true);
}
public void add()
{
String name = Integer.toString(numero_button++);
JButton nouveau = new JButton(name);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = numero_button;
panButton.add(nouveau);
container.add(panButton,c);
}
public void reset()
{
numero_button =0;
container.removeAll();
panButton.removeAll();
panButton.add(button);
panButton2.add(button2);
container.add(panButton);
container.add(panButton2);
}
}
|
UTF-8
|
Java
| 3,740 |
java
|
Fenetre2.java
|
Java
|
[] | null |
[] |
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Fenetre2 {
private JLabel title = new JLabel("Calcul de factorielle");
private JTextField textField = new JTextField(10);
private JButton button = new JButton("ADD");
private JButton button2 = new JButton("RESET");
private JButton resultat = new JButton("new");
private JPanel container = new JPanel();
private JPanel panTitle = new JPanel();
private JPanel panTextField = new JPanel();
private JPanel panButton = new JPanel();
private JPanel panButton2 = new JPanel();
private String text;
private JPanel panResultat = new JPanel();
private GridBagConstraints c = new GridBagConstraints();
int numero_button = 0;
public Fenetre2() {
JFrame fenetre = new JFrame();
fenetre.setTitle("TP Java exo 4");
fenetre.setSize(400, 400);
fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fenetre.setVisible(true);
fenetre.setLocationRelativeTo(null);
container.setLayout(new GridBagLayout());
panButton.add(button);
panButton2.add(button2);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
container.add(panTitle, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
container.add(panTextField, c);
/* c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 2;
container.add(panResultat,c);
*/
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 3;
container.add(panButton, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 5;
container.add(panButton2, c);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//remove
container.removeAll();
container.repaint();
container.revalidate();
//processes user's input
add();
//update Jpanel of the result
container.add(button2);
container.add(button);
container.repaint();
container.revalidate();
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//remove
container.removeAll();
container.repaint();
container.revalidate();
//processes user's input
reset();
//update Jpanel of the result
container.add(button);
container.repaint();
container.revalidate();
}
});
fenetre.setContentPane(container);
fenetre.setVisible(true);
}
public void add()
{
String name = Integer.toString(numero_button++);
JButton nouveau = new JButton(name);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = numero_button;
panButton.add(nouveau);
container.add(panButton,c);
}
public void reset()
{
numero_button =0;
container.removeAll();
panButton.removeAll();
panButton.add(button);
panButton2.add(button2);
container.add(panButton);
container.add(panButton2);
}
}
| 3,740 | 0.555615 | 0.54385 | 154 | 23.292208 | 18.842451 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597403 | false | false |
9
|
93d33958a59b2d4ae4e24e742e640be690532d35
| 11,373,073,416,928 |
e95c490856f5981a6b17bc532d77c1b05f6ced55
|
/src/main/java/dada/brick/com/util/ExcelMaker.java
|
c8b71a0344357c85e0c143f7f87826ac34f57fa5
|
[] |
no_license
|
quirinal36/DadaBrick
|
https://github.com/quirinal36/DadaBrick
|
6470645e9c87658329fdfee5c91bf094638e73b6
|
f6c52f895c2a6f76c8a5db057241c4bf371bf54a
|
refs/heads/master
| 2023-03-09T07:19:41.411000 | 2022-04-25T06:44:33 | 2022-04-25T06:44:33 | 248,978,146 | 0 | 0 | null | false | 2023-02-22T07:43:30 | 2020-03-21T13:08:38 | 2021-12-28T07:05:56 | 2023-02-22T07:43:30 | 84,282 | 0 | 0 | 14 |
Java
| false | false |
package dada.brick.com.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import dada.brick.com.vo.ApplyVO;
import dada.brick.com.vo.ProductsVO;
import dada.brick.com.vo.UserVO;
import lombok.Getter;
@Getter
public class ExcelMaker {
Workbook wb;
Sheet sheet;
final static Logger logger = Logger.getLogger(ExcelMaker.class.getSimpleName());
public ExcelMaker() {
}
public List<ProductsVO> getExcelFileToProductsVO() {
String filePath = "D:\\dada.xlsx";
List<ProductsVO> list = new ArrayList<ProductsVO>();
try {
InputStream inputStream = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(inputStream); // 시트 로드 0, 첫번째 시트 로드
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator(); // 행만큼 반복
while(rowItr.hasNext()) {
Row row = rowItr.next();
if(row.getRowNum() == 0)continue;
Iterator<Cell> cellItr = row.cellIterator(); // 한행이 한열씩 읽기 (셀 읽기)
ProductsVO product = new ProductsVO();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
int index = cell.getColumnIndex();
switch(index) {
case 1:
product.setMenuId(((Double)getValueFromCell(cell)).intValue());
break;
case 2:
product.setOrderNum(((Double)getValueFromCell(cell)).intValue());
break;
case 3:
product.setName((String)getValueFromCell(cell));
break;
case 4:
product.setPrimaryId((String)getValueFromCell(cell));
break;
case 5:
product.setSize((String)getValueFromCell(cell));
break;
case 6:
product.setPackaging((String)getValueFromCell(cell));
break;
case 7:
product.setDelivery((String)getValueFromCell(cell));
break;
}
}
list.add(product);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
private Object getValueFromCell(Cell cell) {
switch(cell.getCellTypeEnum()) {
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return cell.getBooleanCellValue();
case NUMERIC:
return cell.getNumericCellValue();
case FORMULA:
return cell.getCellFormula();
case BLANK:
return "";
default:
return "";
}
}
public void makeSheet(final String title) {
this.wb = new HSSFWorkbook();
this.sheet = this.wb.createSheet(title);
}
private CellStyle getBodyStyle() {
// 데이터용 경계 스타일 테두리
CellStyle bodyStyle = this.wb.createCellStyle();
bodyStyle.setBorderTop(BorderStyle.THIN);
bodyStyle.setBorderBottom(BorderStyle.THIN);
bodyStyle.setBorderLeft(BorderStyle.THIN);
bodyStyle.setBorderRight(BorderStyle.THIN);
return bodyStyle;
}
private CellStyle getHeadStyle() {
// table header style
CellStyle headStyle = this.wb.createCellStyle();
// 가는 경계선
headStyle.setBorderTop(BorderStyle.THIN);
headStyle.setBorderBottom(BorderStyle.THICK);
headStyle.setBorderLeft(BorderStyle.THIN);
headStyle.setBorderRight(BorderStyle.THIN);
// 베경색
headStyle.setFillForegroundColor(HSSFColorPredefined.GREY_25_PERCENT.getIndex());
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 데이터 가운데정렬
headStyle.setAlignment(HorizontalAlignment.CENTER);
return headStyle;
}
public void makeHead(final String[] headers) {
CellStyle headStyle = getHeadStyle();
int rowNo = this.sheet.getLastRowNum();
Row row = this.sheet.createRow(++rowNo);
for(int i = 0; i<headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(headStyle);
cell.setCellValue(headers[i]);
}
}
public void makeApplicationBody(List<ApplyVO> applyList, final String[] headers) {
CellStyle bodyStyle = getBodyStyle();
Iterator<ApplyVO> iter = applyList.iterator();
while(iter.hasNext()) {
ApplyVO item = iter.next();
int rowNo = this.sheet.getLastRowNum();
Row row = this.sheet.createRow(++rowNo);
for(int i = 0; i<headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(bodyStyle);
cell.setCellValue(getApplyItem(item, i));
}
}
}
public void makeUserBody(List<UserVO> userList, final String[] headers) {
CellStyle bodyStyle = getBodyStyle();
Iterator<UserVO> iter = userList.iterator();
while(iter.hasNext()) {
UserVO item = iter.next();
int rowNo = this.sheet.getLastRowNum();
Row row = this.sheet.createRow(++rowNo);
for(int i = 0; i<headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(bodyStyle);
cell.setCellValue(getUserItem(item, i));
}
}
}
private String getUserItem(UserVO user, int i) {
switch(i) {
case 0:
return String.valueOf(user.getId());
case 1:
return user.getRole_name_kr();
case 2:
return user.getUsername();
case 3:
return user.getClassification();
case 4:
return user.getLevel();
case 5:
if(user.getEmail() != null && user.getEmail().length()>0) {
return user.getEmail() +"@" + user.getDomain();
}
case 6:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(user.getMdate());
}
return null;
}
private String getApplyItem(ApplyVO item, int i) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
switch(i) {
case 0:
return dateFormat.format(item.getMdate());
case 1:
if(item.getMemberType() == 2) {
return "일반";
}else if(item.getMemberType() == 3) {
return "기업";
}else if(item.getMemberType() == 4) {
return "학생";
}
break;
case 2:
if(item.getIsSpeaker() == 1) {
return "O";
}else if(item.getIsSpeaker() == 2){
return "X";
}
break;
case 3:
if(item.getNational() == 1) {
return "대한민국";
}else if(item.getNational() == 2) {
return "중국";
}else if(item.getNational() == 3) {
return "일본";
}
break;
case 4:
return item.getUsername();
case 5:
return item.getClassification();
case 6:
return item.getLevel();
case 7:
return item.getTelephone();
case 8:
if(item.getEmail() != null && item.getEmail().length()>0) {
return item.getEmail() +"@" + item.getDomain();
}
}
return null;
}
}
|
UTF-8
|
Java
| 7,704 |
java
|
ExcelMaker.java
|
Java
|
[] | null |
[] |
package dada.brick.com.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import dada.brick.com.vo.ApplyVO;
import dada.brick.com.vo.ProductsVO;
import dada.brick.com.vo.UserVO;
import lombok.Getter;
@Getter
public class ExcelMaker {
Workbook wb;
Sheet sheet;
final static Logger logger = Logger.getLogger(ExcelMaker.class.getSimpleName());
public ExcelMaker() {
}
public List<ProductsVO> getExcelFileToProductsVO() {
String filePath = "D:\\dada.xlsx";
List<ProductsVO> list = new ArrayList<ProductsVO>();
try {
InputStream inputStream = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(inputStream); // 시트 로드 0, 첫번째 시트 로드
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator(); // 행만큼 반복
while(rowItr.hasNext()) {
Row row = rowItr.next();
if(row.getRowNum() == 0)continue;
Iterator<Cell> cellItr = row.cellIterator(); // 한행이 한열씩 읽기 (셀 읽기)
ProductsVO product = new ProductsVO();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
int index = cell.getColumnIndex();
switch(index) {
case 1:
product.setMenuId(((Double)getValueFromCell(cell)).intValue());
break;
case 2:
product.setOrderNum(((Double)getValueFromCell(cell)).intValue());
break;
case 3:
product.setName((String)getValueFromCell(cell));
break;
case 4:
product.setPrimaryId((String)getValueFromCell(cell));
break;
case 5:
product.setSize((String)getValueFromCell(cell));
break;
case 6:
product.setPackaging((String)getValueFromCell(cell));
break;
case 7:
product.setDelivery((String)getValueFromCell(cell));
break;
}
}
list.add(product);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
private Object getValueFromCell(Cell cell) {
switch(cell.getCellTypeEnum()) {
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return cell.getBooleanCellValue();
case NUMERIC:
return cell.getNumericCellValue();
case FORMULA:
return cell.getCellFormula();
case BLANK:
return "";
default:
return "";
}
}
public void makeSheet(final String title) {
this.wb = new HSSFWorkbook();
this.sheet = this.wb.createSheet(title);
}
private CellStyle getBodyStyle() {
// 데이터용 경계 스타일 테두리
CellStyle bodyStyle = this.wb.createCellStyle();
bodyStyle.setBorderTop(BorderStyle.THIN);
bodyStyle.setBorderBottom(BorderStyle.THIN);
bodyStyle.setBorderLeft(BorderStyle.THIN);
bodyStyle.setBorderRight(BorderStyle.THIN);
return bodyStyle;
}
private CellStyle getHeadStyle() {
// table header style
CellStyle headStyle = this.wb.createCellStyle();
// 가는 경계선
headStyle.setBorderTop(BorderStyle.THIN);
headStyle.setBorderBottom(BorderStyle.THICK);
headStyle.setBorderLeft(BorderStyle.THIN);
headStyle.setBorderRight(BorderStyle.THIN);
// 베경색
headStyle.setFillForegroundColor(HSSFColorPredefined.GREY_25_PERCENT.getIndex());
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 데이터 가운데정렬
headStyle.setAlignment(HorizontalAlignment.CENTER);
return headStyle;
}
public void makeHead(final String[] headers) {
CellStyle headStyle = getHeadStyle();
int rowNo = this.sheet.getLastRowNum();
Row row = this.sheet.createRow(++rowNo);
for(int i = 0; i<headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(headStyle);
cell.setCellValue(headers[i]);
}
}
public void makeApplicationBody(List<ApplyVO> applyList, final String[] headers) {
CellStyle bodyStyle = getBodyStyle();
Iterator<ApplyVO> iter = applyList.iterator();
while(iter.hasNext()) {
ApplyVO item = iter.next();
int rowNo = this.sheet.getLastRowNum();
Row row = this.sheet.createRow(++rowNo);
for(int i = 0; i<headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(bodyStyle);
cell.setCellValue(getApplyItem(item, i));
}
}
}
public void makeUserBody(List<UserVO> userList, final String[] headers) {
CellStyle bodyStyle = getBodyStyle();
Iterator<UserVO> iter = userList.iterator();
while(iter.hasNext()) {
UserVO item = iter.next();
int rowNo = this.sheet.getLastRowNum();
Row row = this.sheet.createRow(++rowNo);
for(int i = 0; i<headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(bodyStyle);
cell.setCellValue(getUserItem(item, i));
}
}
}
private String getUserItem(UserVO user, int i) {
switch(i) {
case 0:
return String.valueOf(user.getId());
case 1:
return user.getRole_name_kr();
case 2:
return user.getUsername();
case 3:
return user.getClassification();
case 4:
return user.getLevel();
case 5:
if(user.getEmail() != null && user.getEmail().length()>0) {
return user.getEmail() +"@" + user.getDomain();
}
case 6:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(user.getMdate());
}
return null;
}
private String getApplyItem(ApplyVO item, int i) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
switch(i) {
case 0:
return dateFormat.format(item.getMdate());
case 1:
if(item.getMemberType() == 2) {
return "일반";
}else if(item.getMemberType() == 3) {
return "기업";
}else if(item.getMemberType() == 4) {
return "학생";
}
break;
case 2:
if(item.getIsSpeaker() == 1) {
return "O";
}else if(item.getIsSpeaker() == 2){
return "X";
}
break;
case 3:
if(item.getNational() == 1) {
return "대한민국";
}else if(item.getNational() == 2) {
return "중국";
}else if(item.getNational() == 3) {
return "일본";
}
break;
case 4:
return item.getUsername();
case 5:
return item.getClassification();
case 6:
return item.getLevel();
case 7:
return item.getTelephone();
case 8:
if(item.getEmail() != null && item.getEmail().length()>0) {
return item.getEmail() +"@" + item.getDomain();
}
}
return null;
}
}
| 7,704 | 0.663759 | 0.658208 | 260 | 27.1 | 19.696877 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.996154 | false | false |
9
|
66ccfe839c12f2a253914e4f351a28fe2b1529c4
| 7,576,322,337,567 |
c34c37f9179d7da3bf749312dac2d2dcd3009aa7
|
/src/main/java/com/colorhole/RunnerConstants.java
|
b22973d7d999e5d68c2110012824aa1b8d951142
|
[] |
no_license
|
NikitaDestrain/color-hole-creator
|
https://github.com/NikitaDestrain/color-hole-creator
|
ad913f11a4821b5715e5673cfa56d31415af03ef
|
311f72de3b8ed118e9deedf5b133256f8fece40e
|
refs/heads/master
| 2021-08-07T10:39:25.425000 | 2020-05-17T23:50:00 | 2020-05-17T23:50:00 | 178,684,455 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.colorhole;
public class RunnerConstants {
public static final String IMG_PATH_FILE_NAME = "img/";
public static final String DESCRIPTOR_FILE_NAME = "descriptor.properties";
public static final String FLIST_FILE_NAME = "flist";
public static final String FLIST_HOLE_FILE_NAME = "flist_hole";
}
|
UTF-8
|
Java
| 322 |
java
|
RunnerConstants.java
|
Java
|
[] | null |
[] |
package com.colorhole;
public class RunnerConstants {
public static final String IMG_PATH_FILE_NAME = "img/";
public static final String DESCRIPTOR_FILE_NAME = "descriptor.properties";
public static final String FLIST_FILE_NAME = "flist";
public static final String FLIST_HOLE_FILE_NAME = "flist_hole";
}
| 322 | 0.736025 | 0.736025 | 8 | 39.25 | 28.203501 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
9
|
dfdbf700aeab265a9f3b4efb30800715e8ccd068
| 30,545,807,428,717 |
b445068452b0712dd9c608f09175749427b708bd
|
/src/main/java/org/trax/form/SelectionForm.java
|
031534cd58bfad51469b181037e0f5b50ba0600f
|
[] |
no_license
|
jeffchevy/jefftrax
|
https://github.com/jeffchevy/jefftrax
|
b0b81f0e766e9cb0873fcd75bfef68b26a017a96
|
b8ed05f3f561fbe06cef7c44bb7331729a79442a
|
refs/heads/master
| 2021-09-03T07:30:29.050000 | 2018-01-07T02:18:11 | 2018-01-07T02:18:11 | 30,765,972 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.trax.form;
import java.util.Collection;
public class SelectionForm
{
private Collection<Long> selections;
public Collection<Long> getSelections()
{
return selections;
}
public void setSelections(Collection<Long> selections)
{
this.selections = selections;
}
}
|
UTF-8
|
Java
| 289 |
java
|
SelectionForm.java
|
Java
|
[] | null |
[] |
package org.trax.form;
import java.util.Collection;
public class SelectionForm
{
private Collection<Long> selections;
public Collection<Long> getSelections()
{
return selections;
}
public void setSelections(Collection<Long> selections)
{
this.selections = selections;
}
}
| 289 | 0.750865 | 0.750865 | 18 | 15.055555 | 17.144718 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.944444 | false | false |
9
|
0a48baa61b04932f109410a0de8f91b41fe23b63
| 19,885,698,612,646 |
434e8bf68c304489e04a6bf3063a58b6edfe8e15
|
/src/main/java/by/bsu/diplom/newshub/web/controller/RestExceptionHandler.java
|
973fb0179c142c9424fe1cace6372d73d9121ff8
|
[] |
no_license
|
absence23/news-app-be
|
https://github.com/absence23/news-app-be
|
89e82ab3c5d9202565dcc258f5edf70f102a39f9
|
4808dad9b65b59b45ac2cd49e993168fd2877283
|
refs/heads/master
| 2021-04-29T04:28:57.720000 | 2017-01-04T09:07:37 | 2017-01-04T09:07:37 | 77,995,004 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package by.bsu.diplom.newshub.web.controller;
import by.bsu.diplom.newshub.domain.dto.error.ErrorResponse;
import by.bsu.diplom.newshub.domain.dto.error.ValidationError;
import by.bsu.diplom.newshub.exception.EntityAlreadyExistsException;
import by.bsu.diplom.newshub.exception.EntityNotFoundException;
import by.bsu.diplom.newshub.web.util.ErrorMessageCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import javax.persistence.EntityExistsException;
import javax.persistence.PersistenceException;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.List;
@RestControllerAdvice
public class RestExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);
private static final String INTERNAL_ERROR_MESSAGE = "Internal error";
private static final String INVALID_BODY_MESSAGE = "Invalid body of request";
private static final String VALIDATION_ERROR_MESSAGE = "Entity validation error";
private static final String WRONG_ARGUMENT_MESSAGE = "Wrong request argument";
private static final String ALREADY_EXISTS_MESSAGE = "Such entity already exists";
@ExceptionHandler({PersistenceException.class, DataAccessException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse processServiceException(Exception ex) {
LOGGER.error("Internal error", ex);
return new ErrorResponse(ErrorMessageCode.INTERNAL, INTERNAL_ERROR_MESSAGE);
}
@ExceptionHandler({EntityNotFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse processNotFoundException(EntityNotFoundException ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler({ValidationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processValidationException(ValidationException ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.INVALID_BODY, INVALID_BODY_MESSAGE);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processArgumentValidationError(MethodArgumentNotValidException ex) {
LOGGER.error(ex.getMessage());
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
List<ValidationError> validationErrors = new ArrayList<>();
fieldErrors.forEach(error -> validationErrors.add(new ValidationError(error.getField(), error.getDefaultMessage())));
return new ErrorResponse<>(ErrorMessageCode.NOT_VALID, VALIDATION_ERROR_MESSAGE, validationErrors);
}
@ExceptionHandler({MethodArgumentTypeMismatchException.class, IllegalArgumentException.class, HttpMessageNotReadableException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processArgumentTypeValidationError(Exception ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.ARGUMENT_MISMATCH, WRONG_ARGUMENT_MESSAGE);
}
@ExceptionHandler({EntityAlreadyExistsException.class, EntityExistsException.class, DataIntegrityViolationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processEntityAlreadyExistsError() {
return new ErrorResponse(ErrorMessageCode.ALREADY_EXISTS, ALREADY_EXISTS_MESSAGE);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.HEADERS_NOT_ALLOWED, "Media type not supported");
}
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
public void process(HttpMediaTypeNotAcceptableException ex) {
LOGGER.error("Not acceptable headers", ex);
}
}
|
UTF-8
|
Java
| 4,924 |
java
|
RestExceptionHandler.java
|
Java
|
[] | null |
[] |
package by.bsu.diplom.newshub.web.controller;
import by.bsu.diplom.newshub.domain.dto.error.ErrorResponse;
import by.bsu.diplom.newshub.domain.dto.error.ValidationError;
import by.bsu.diplom.newshub.exception.EntityAlreadyExistsException;
import by.bsu.diplom.newshub.exception.EntityNotFoundException;
import by.bsu.diplom.newshub.web.util.ErrorMessageCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import javax.persistence.EntityExistsException;
import javax.persistence.PersistenceException;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.List;
@RestControllerAdvice
public class RestExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);
private static final String INTERNAL_ERROR_MESSAGE = "Internal error";
private static final String INVALID_BODY_MESSAGE = "Invalid body of request";
private static final String VALIDATION_ERROR_MESSAGE = "Entity validation error";
private static final String WRONG_ARGUMENT_MESSAGE = "Wrong request argument";
private static final String ALREADY_EXISTS_MESSAGE = "Such entity already exists";
@ExceptionHandler({PersistenceException.class, DataAccessException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse processServiceException(Exception ex) {
LOGGER.error("Internal error", ex);
return new ErrorResponse(ErrorMessageCode.INTERNAL, INTERNAL_ERROR_MESSAGE);
}
@ExceptionHandler({EntityNotFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse processNotFoundException(EntityNotFoundException ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler({ValidationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processValidationException(ValidationException ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.INVALID_BODY, INVALID_BODY_MESSAGE);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processArgumentValidationError(MethodArgumentNotValidException ex) {
LOGGER.error(ex.getMessage());
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
List<ValidationError> validationErrors = new ArrayList<>();
fieldErrors.forEach(error -> validationErrors.add(new ValidationError(error.getField(), error.getDefaultMessage())));
return new ErrorResponse<>(ErrorMessageCode.NOT_VALID, VALIDATION_ERROR_MESSAGE, validationErrors);
}
@ExceptionHandler({MethodArgumentTypeMismatchException.class, IllegalArgumentException.class, HttpMessageNotReadableException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processArgumentTypeValidationError(Exception ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.ARGUMENT_MISMATCH, WRONG_ARGUMENT_MESSAGE);
}
@ExceptionHandler({EntityAlreadyExistsException.class, EntityExistsException.class, DataIntegrityViolationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processEntityAlreadyExistsError() {
return new ErrorResponse(ErrorMessageCode.ALREADY_EXISTS, ALREADY_EXISTS_MESSAGE);
}
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse processMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex) {
LOGGER.error(ex.getMessage());
return new ErrorResponse(ErrorMessageCode.HEADERS_NOT_ALLOWED, "Media type not supported");
}
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
public void process(HttpMediaTypeNotAcceptableException ex) {
LOGGER.error("Not acceptable headers", ex);
}
}
| 4,924 | 0.800366 | 0.799959 | 96 | 50.291668 | 32.541294 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false |
9
|
9379cd6f549d419525945b77142d09e4718b4b2f
| 20,057,497,287,011 |
78608de074512471fc7551eaea9c1f0579eb8664
|
/class-teachingplatform/src/main/java/com/school/utils/BhsfInterfaceUtil.java
|
e2c797fc310402ff20752c10bd5186fa33335e9f
|
[] |
no_license
|
qihasihi/RollStone
|
https://github.com/qihasihi/RollStone
|
312e53c60f9c36ebc41886704d7d99590ce5bd93
|
754c2eefbbc91a7d2aa7dbd6d7bf6e46ba98a228
|
refs/heads/master
| 2021-01-16T20:57:18.178000 | 2015-02-16T03:05:12 | 2015-02-16T03:05:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.school.utils;
import com.etiantian.unite.utils.UrlSigUtil;
import com.school.entity.ClassInfo;
import com.school.entity.UserInfo;
import com.school.entity.teachpaltform.TpGroupInfo;
import com.school.util.LZX_MD5;
import com.school.util.UtilTool;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
/**
* 调用四中接口用户工具类
* Created by qihaishi on 15-1-26.
*/
public class BhsfInterfaceUtil {
/**
* 按角色类型 操作用户数据
* 角色类型 1=班主任 2=任课教师 3=学生
* @param uentity 用户List集合
* @param optype 操作类型: add update delete
* @return
*/
private static boolean OperateUserBase(final List<UserInfo> uentity,final String optype){
System.out.println("BhsfInterfaceUtil operateUserBase ....");
String BHSF_URL=UtilTool.utilproperty.getProperty("BHSF_BASE_URL").toString();
if(BHSF_URL==null||BHSF_URL.length()<1)return false;
BHSF_URL+="foreignFace!"+optype+".action";
/**
* Object sxUserId = j.get("sx_user_id");
Object userName = j.get("user_name");
Object roleId = j.get("role_id");
Object teacherId = j.get("teacher_no");
Object teacherName = j.get("teacher_name");
Object teacherSex = j.get("teacher_sex");
Object headImgUrl = j.get("headimgurl");
Object stuName = j.get("stu_name");
Object stuSex = j.get("stu_sex");
Object stuNo = j.get("stu_no");
*/
if(uentity==null||uentity.size()<1)return false;
System.out.println("uentity:"+uentity.toString());
HashMap<String,String> paramMap=new HashMap<String,String>();
String time=new Date().getTime()+"";
paramMap.put("timestamp",time);
List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();
for(UserInfo u:uentity){
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("sx_user_id",u.getUserid());
tmpMap.put("user_name",u.getUsername());
tmpMap.put("role_id",u.getRoleIdStr());
tmpMap.put("headimgurl",u.getHeadimage());
String[]roleArray=u.getRoleIdStr().split(",");
if(roleArray.length>0){
for(String rid:roleArray){
if(rid.equals("18")){
tmpMap.put("teacher_name",u.getRealname());
tmpMap.put("teacher_sex",u.getUsersex());
tmpMap.put("teacher_no",u.getTeacherno());
}else if(rid.equals("36")){
tmpMap.put("stu_name",u.getRealname());
tmpMap.put("stu_sex",u.getUsersex());
tmpMap.put("stu_no",u.getStuno());
}else{
System.out.println("InValidate Role!");
return false;
}
}
}else{
System.out.println("RoleId is empty!");
return false;
}
mapList.add(tmpMap);
}
JSONArray jsonArray=JSONArray.fromObject(mapList);
System.out.print("message:"+jsonArray.toString());
paramMap.put("message",jsonArray.toString());
String md5key=time+"SX_OA";
md5key= LZX_MD5.getMD5Str(md5key);//生成md5加密
paramMap.put("sign",md5key);
JSONObject jo=UtilTool.sendPostUrl(BHSF_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("type")&&jo.get("type").toString().trim().equals("success")){
return true;
}
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 批量添加用户信息
* @param uentity 用户信息
* @return
*/
public static boolean addUserBase(final List<UserInfo> uentity){
return OperateUserBase(uentity, "addUser");
}
/**
* 批量删除用户信息
* @param uentity 用户信息
* @return
*/
public static boolean delUserBase(final List<UserInfo> uentity){
return OperateUserBase(uentity, "delUser");
}
/**
* 批量修改用户信息
* @param uentity 用户信息
* @return
*/
public static boolean updateUserBase(final List<UserInfo> uentity){
return OperateUserBase(uentity, "addUser");
}
/********************SCH2-WEB. 数校小组基础信息数据接口******************************/
/**
* 同步小组信息操作
* @param entity 小组信息实体
* @param optype 操作类型: add update delete
* @return
*/
private static boolean OperateGroupBase(final TpGroupInfo entity,final Integer schoolid,final String optype){
String addToEtt_URL=UtilTool.utilproperty.getProperty("TO_ETT_GROUP_INTERFACE").toString();
if(entity==null||schoolid==null||optype==null)return false;
HashMap<String,String> paramMap=new HashMap<String,String>();
paramMap.put("time",new Date().getTime()+"");
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("action",optype);
tmpMap.put("classId",entity.getClassid());
tmpMap.put("groupId",entity.getGroupid());
tmpMap.put("groupName",entity.getGroupname());
tmpMap.put("subjectId",entity.getSubjectid());
tmpMap.put("schoolId",schoolid);
JSONObject jsonObject=JSONObject.fromObject(tmpMap);
paramMap.put("data",jsonObject.toString());
String val = UrlSigUtil.makeSigSimple("groupInterFace.do", paramMap);
paramMap.put("sign",val);
JSONObject jo=UtilTool.sendPostUrl(addToEtt_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("result")&&jo.get("result").toString().trim().equals("1"))
return true;
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 添加小组信息表
* @param entity
* @param schoolid
* @return
*/
public static boolean addGroupBase(final TpGroupInfo entity,final Integer schoolid){
return OperateGroupBase(entity,schoolid,"add");
}
/**
* 删除小组信息表
* @param entity
* @param schoolid
* @return
*/
public static boolean delGroupBase(final TpGroupInfo entity,final Integer schoolid){
return OperateGroupBase(entity,schoolid,"delete");
}
/**
* 修改小组信息表
* @param entity
* @param schoolid
* @return
*/
public static boolean updateGroupBase(final TpGroupInfo entity,final Integer schoolid){
return OperateGroupBase(entity,schoolid,"update");
}
/********************************SCH1-WEB.数校班级基础信息数据接口*****************************************/
/**
* 同步班级信息操作
* @param entity 班级信息实体
* @param optype 操作类型: add update delete
* @return
*/
private static boolean OperateClassBase(final ClassInfo entity,final String optype){
String BHSF_URL=UtilTool.utilproperty.getProperty("BHSF_BASE_URL").toString();
if(BHSF_URL==null||BHSF_URL.length()<1)return false;
BHSF_URL+="foreignFace!"+optype+".action";
if(entity==null||optype==null)return false;
HashMap<String,String> paramMap=new HashMap<String,String>();
String time=new Date().getTime()+"";
paramMap.put("timestamp",time);
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("sx_classid",entity.getClassid());
tmpMap.put("class_name",entity.getClassname());
String classGrade=entity.getClassgrade();
tmpMap.put("type",entity.getType());
tmpMap.put("class_grade",classGrade);
tmpMap.put("year",entity.getYear());
tmpMap.put("pattern",entity.getPattern());
JSONArray jsonArray=JSONArray.fromObject(tmpMap);
paramMap.put("message",jsonArray.toString());
String md5key=time+"SX_OA";
md5key= LZX_MD5.getMD5Str(md5key);//生成md5加密
paramMap.put("sign",md5key);
JSONObject jo=UtilTool.sendPostUrl(BHSF_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("type")&&jo.get("type").toString().trim().equals("success"))
return true;
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 添加或修改班级信息
* @param entity 班级信息
* @return
*/
public static boolean addOrModifyClassBase(final ClassInfo entity){
return OperateClassBase(entity,"addOrModifyClass");
}
/**
* 添加班级信息
* @param entity 班级信息
* @return
*/
public static boolean delClassBase(final ClassInfo entity){
return OperateClassBase(entity,"delClass");
}
/**
* 操作用户与班级数据
* @param cuMapList 必带 userId,userType,subjectId 的三个key
* @param optype
* @return
*/
public static boolean OperateClassUser(List<Map<String,Object>> cuMapList,String optype,Integer classid){
String BHSF_URL=UtilTool.utilproperty.getProperty("BHSF_BASE_URL").toString();
if(BHSF_URL==null||BHSF_URL.length()<1)return false;
BHSF_URL+="foreignFace!"+optype+".action";
HashMap<String,String> paramMap=new HashMap<String,String>();
String time=new Date().getTime()+"";
paramMap.put("timestamp",time);
//存入
if(cuMapList!=null&&cuMapList.size()>0)
paramMap.put("message",JSONArray.fromObject(cuMapList).toString());
if(classid!=null)
paramMap.put("sx_class_id",classid.toString());
System.out.println("BhsfInterfaceUtil OperateClassUser:"+JSONArray.fromObject(cuMapList).toString());
String md5key=time+"SX_OA";
md5key= LZX_MD5.getMD5Str(md5key);//生成md5加密
paramMap.put("sign",md5key);
JSONObject jo=UtilTool.sendPostUrl(BHSF_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("type")&&jo.get("type").toString().trim().equals("success")){
return true;
}
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 删除班级人员
* @param cuMapList
* @return
*/
public static boolean delClassUser(List<Map<String,Object>> cuMapList,Integer classid){
return OperateClassUser(cuMapList, "delClassUser",classid);
}
/**
* 添加班级人员
* @param cuMapList
* @return
*/
public static boolean addClassUser(List<Map<String,Object>> cuMapList){
return OperateClassUser(cuMapList, "addClassUser",null);
}
/**
* 操作用户与小组数据
* @param cuMapList 必带 userId,userType 的key
* @param groupId
* @param schoolid
* @return
*/
public static boolean OperateGroupUser(List<Map<String,Object>> cuMapList,Integer classid,Long groupId,Integer schoolid){
String addToEtt_URL=UtilTool.utilproperty.getProperty("TO_ETT_GROUPUSER_INTERFACE").toString();
if(groupId==null||schoolid==null||classid==null)return false;
HashMap<String,String> paramMap=new HashMap<String,String>();
paramMap.put("time",new Date().getTime()+"");
//得到data JSONObject
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("groupId",groupId);
tmpMap.put("classId",classid);
tmpMap.put("schoolId",schoolid);
if(cuMapList!=null&&cuMapList.size()>0)
tmpMap.put("userList",JSONArray.fromObject(cuMapList).toString());
//存入
paramMap.put("data",JSONObject.fromObject(tmpMap).toString());
// JSONObject jb=JSONObject.fromObject(paramMap);
String val = UrlSigUtil.makeSigSimple("jionGroupUserInterFace.do", paramMap);
paramMap.put("sign",val);
JSONObject jo=UtilTool.sendPostUrl(addToEtt_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("result")&&jo.get("result").toString().trim().equals("1")){
return true;
}
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
public static boolean ModifyUser(UserInfo u,String identity){
if(u==null||identity==null)
return false;
String ettUrl=UtilTool.utilproperty.get("ETT_INTER_IP").toString()+"modifyUser.do";
//String ettUrl="http://192.168.10.59/study-im-service-1.0/modifyUser.do";
if(ettUrl==null)return false;
HashMap<String,String> tmpMap=new HashMap<String, String>();
tmpMap.put("timestamp",new Date().getTime()+"");
tmpMap.put("dcSchoolId",u.getDcschoolid().toString());
tmpMap.put("jid",u.getEttuserid().toString());
tmpMap.put("dcUserId",u.getUserid().toString());
tmpMap.put("userName",u.getUsername());
tmpMap.put("password",u.getPassword());
tmpMap.put("email",u.getMailaddress());
tmpMap.put("identity",identity);
String sign=UrlSigUtil.makeSigSimple("modifyUser.do",tmpMap);
tmpMap.put("sign",sign);
JSONObject jo=UtilTool.sendPostUrl(ettUrl,tmpMap,"UTF-8");
System.out.println(UtilTool.decode(jo.get("msg").toString()));
if(jo!=null&&jo.containsKey("result")&&jo.get("result").toString().trim().equals("1")){
return true;
}
return false;
}
//main方法
public static void main(String[] args){
}
}
|
GB18030
|
Java
| 14,013 |
java
|
BhsfInterfaceUtil.java
|
Java
|
[
{
"context": "java.util.*;\r\n\r\n/**\r\n * 调用四中接口用户工具类\r\n * Created by qihaishi on 15-1-26.\r\n */\r\npublic class BhsfInterfaceUtil ",
"end": 399,
"score": 0.9994124174118042,
"start": 391,
"tag": "USERNAME",
"value": "qihaishi"
},
{
"context": "onArray.toString());\r\n String md5key=time+\"SX_OA\";\r\n md5key= LZX_MD5.getMD5Str(md5key);//生成",
"end": 3371,
"score": 0.8588154315948486,
"start": 3366,
"tag": "KEY",
"value": "SX_OA"
},
{
"context": "ge\",jsonArray.toString());\r\n String md5key=time+\"SX_OA\";\r\n md5key= LZX_MD5.getMD5Str(md5key);//生成",
"end": 8010,
"score": 0.9361623525619507,
"start": 7999,
"tag": "KEY",
"value": "time+\"SX_OA"
},
{
"context": "ct(cuMapList).toString());\r\n String md5key=time+\"SX_OA\";\r\n md5key= LZX_MD5.getMD5Str(md5key);//生成",
"end": 9809,
"score": 0.8912097811698914,
"start": 9798,
"tag": "KEY",
"value": "time+\"SX_OA"
},
{
"context": "\"modifyUser.do\";\r\n //String ettUrl=\"http://192.168.10.59/study-im-service-1.0/modifyUser.do\";\r\n if(",
"end": 12466,
"score": 0.9980538487434387,
"start": 12453,
"tag": "IP_ADDRESS",
"value": "192.168.10.59"
},
{
"context": ",u.getUsername());\r\n tmpMap.put(\"password\",u.getPassword());\r\n tmpMap.put(\"email\",u.getMailaddress(",
"end": 12942,
"score": 0.9117333292961121,
"start": 12929,
"tag": "PASSWORD",
"value": "u.getPassword"
}
] | null |
[] |
package com.school.utils;
import com.etiantian.unite.utils.UrlSigUtil;
import com.school.entity.ClassInfo;
import com.school.entity.UserInfo;
import com.school.entity.teachpaltform.TpGroupInfo;
import com.school.util.LZX_MD5;
import com.school.util.UtilTool;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
/**
* 调用四中接口用户工具类
* Created by qihaishi on 15-1-26.
*/
public class BhsfInterfaceUtil {
/**
* 按角色类型 操作用户数据
* 角色类型 1=班主任 2=任课教师 3=学生
* @param uentity 用户List集合
* @param optype 操作类型: add update delete
* @return
*/
private static boolean OperateUserBase(final List<UserInfo> uentity,final String optype){
System.out.println("BhsfInterfaceUtil operateUserBase ....");
String BHSF_URL=UtilTool.utilproperty.getProperty("BHSF_BASE_URL").toString();
if(BHSF_URL==null||BHSF_URL.length()<1)return false;
BHSF_URL+="foreignFace!"+optype+".action";
/**
* Object sxUserId = j.get("sx_user_id");
Object userName = j.get("user_name");
Object roleId = j.get("role_id");
Object teacherId = j.get("teacher_no");
Object teacherName = j.get("teacher_name");
Object teacherSex = j.get("teacher_sex");
Object headImgUrl = j.get("headimgurl");
Object stuName = j.get("stu_name");
Object stuSex = j.get("stu_sex");
Object stuNo = j.get("stu_no");
*/
if(uentity==null||uentity.size()<1)return false;
System.out.println("uentity:"+uentity.toString());
HashMap<String,String> paramMap=new HashMap<String,String>();
String time=new Date().getTime()+"";
paramMap.put("timestamp",time);
List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();
for(UserInfo u:uentity){
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("sx_user_id",u.getUserid());
tmpMap.put("user_name",u.getUsername());
tmpMap.put("role_id",u.getRoleIdStr());
tmpMap.put("headimgurl",u.getHeadimage());
String[]roleArray=u.getRoleIdStr().split(",");
if(roleArray.length>0){
for(String rid:roleArray){
if(rid.equals("18")){
tmpMap.put("teacher_name",u.getRealname());
tmpMap.put("teacher_sex",u.getUsersex());
tmpMap.put("teacher_no",u.getTeacherno());
}else if(rid.equals("36")){
tmpMap.put("stu_name",u.getRealname());
tmpMap.put("stu_sex",u.getUsersex());
tmpMap.put("stu_no",u.getStuno());
}else{
System.out.println("InValidate Role!");
return false;
}
}
}else{
System.out.println("RoleId is empty!");
return false;
}
mapList.add(tmpMap);
}
JSONArray jsonArray=JSONArray.fromObject(mapList);
System.out.print("message:"+jsonArray.toString());
paramMap.put("message",jsonArray.toString());
String md5key=time+"SX_OA";
md5key= LZX_MD5.getMD5Str(md5key);//生成md5加密
paramMap.put("sign",md5key);
JSONObject jo=UtilTool.sendPostUrl(BHSF_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("type")&&jo.get("type").toString().trim().equals("success")){
return true;
}
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 批量添加用户信息
* @param uentity 用户信息
* @return
*/
public static boolean addUserBase(final List<UserInfo> uentity){
return OperateUserBase(uentity, "addUser");
}
/**
* 批量删除用户信息
* @param uentity 用户信息
* @return
*/
public static boolean delUserBase(final List<UserInfo> uentity){
return OperateUserBase(uentity, "delUser");
}
/**
* 批量修改用户信息
* @param uentity 用户信息
* @return
*/
public static boolean updateUserBase(final List<UserInfo> uentity){
return OperateUserBase(uentity, "addUser");
}
/********************SCH2-WEB. 数校小组基础信息数据接口******************************/
/**
* 同步小组信息操作
* @param entity 小组信息实体
* @param optype 操作类型: add update delete
* @return
*/
private static boolean OperateGroupBase(final TpGroupInfo entity,final Integer schoolid,final String optype){
String addToEtt_URL=UtilTool.utilproperty.getProperty("TO_ETT_GROUP_INTERFACE").toString();
if(entity==null||schoolid==null||optype==null)return false;
HashMap<String,String> paramMap=new HashMap<String,String>();
paramMap.put("time",new Date().getTime()+"");
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("action",optype);
tmpMap.put("classId",entity.getClassid());
tmpMap.put("groupId",entity.getGroupid());
tmpMap.put("groupName",entity.getGroupname());
tmpMap.put("subjectId",entity.getSubjectid());
tmpMap.put("schoolId",schoolid);
JSONObject jsonObject=JSONObject.fromObject(tmpMap);
paramMap.put("data",jsonObject.toString());
String val = UrlSigUtil.makeSigSimple("groupInterFace.do", paramMap);
paramMap.put("sign",val);
JSONObject jo=UtilTool.sendPostUrl(addToEtt_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("result")&&jo.get("result").toString().trim().equals("1"))
return true;
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 添加小组信息表
* @param entity
* @param schoolid
* @return
*/
public static boolean addGroupBase(final TpGroupInfo entity,final Integer schoolid){
return OperateGroupBase(entity,schoolid,"add");
}
/**
* 删除小组信息表
* @param entity
* @param schoolid
* @return
*/
public static boolean delGroupBase(final TpGroupInfo entity,final Integer schoolid){
return OperateGroupBase(entity,schoolid,"delete");
}
/**
* 修改小组信息表
* @param entity
* @param schoolid
* @return
*/
public static boolean updateGroupBase(final TpGroupInfo entity,final Integer schoolid){
return OperateGroupBase(entity,schoolid,"update");
}
/********************************SCH1-WEB.数校班级基础信息数据接口*****************************************/
/**
* 同步班级信息操作
* @param entity 班级信息实体
* @param optype 操作类型: add update delete
* @return
*/
private static boolean OperateClassBase(final ClassInfo entity,final String optype){
String BHSF_URL=UtilTool.utilproperty.getProperty("BHSF_BASE_URL").toString();
if(BHSF_URL==null||BHSF_URL.length()<1)return false;
BHSF_URL+="foreignFace!"+optype+".action";
if(entity==null||optype==null)return false;
HashMap<String,String> paramMap=new HashMap<String,String>();
String time=new Date().getTime()+"";
paramMap.put("timestamp",time);
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("sx_classid",entity.getClassid());
tmpMap.put("class_name",entity.getClassname());
String classGrade=entity.getClassgrade();
tmpMap.put("type",entity.getType());
tmpMap.put("class_grade",classGrade);
tmpMap.put("year",entity.getYear());
tmpMap.put("pattern",entity.getPattern());
JSONArray jsonArray=JSONArray.fromObject(tmpMap);
paramMap.put("message",jsonArray.toString());
String md5key=time+"SX_OA";
md5key= LZX_MD5.getMD5Str(md5key);//生成md5加密
paramMap.put("sign",md5key);
JSONObject jo=UtilTool.sendPostUrl(BHSF_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("type")&&jo.get("type").toString().trim().equals("success"))
return true;
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 添加或修改班级信息
* @param entity 班级信息
* @return
*/
public static boolean addOrModifyClassBase(final ClassInfo entity){
return OperateClassBase(entity,"addOrModifyClass");
}
/**
* 添加班级信息
* @param entity 班级信息
* @return
*/
public static boolean delClassBase(final ClassInfo entity){
return OperateClassBase(entity,"delClass");
}
/**
* 操作用户与班级数据
* @param cuMapList 必带 userId,userType,subjectId 的三个key
* @param optype
* @return
*/
public static boolean OperateClassUser(List<Map<String,Object>> cuMapList,String optype,Integer classid){
String BHSF_URL=UtilTool.utilproperty.getProperty("BHSF_BASE_URL").toString();
if(BHSF_URL==null||BHSF_URL.length()<1)return false;
BHSF_URL+="foreignFace!"+optype+".action";
HashMap<String,String> paramMap=new HashMap<String,String>();
String time=new Date().getTime()+"";
paramMap.put("timestamp",time);
//存入
if(cuMapList!=null&&cuMapList.size()>0)
paramMap.put("message",JSONArray.fromObject(cuMapList).toString());
if(classid!=null)
paramMap.put("sx_class_id",classid.toString());
System.out.println("BhsfInterfaceUtil OperateClassUser:"+JSONArray.fromObject(cuMapList).toString());
String md5key=time+"SX_OA";
md5key= LZX_MD5.getMD5Str(md5key);//生成md5加密
paramMap.put("sign",md5key);
JSONObject jo=UtilTool.sendPostUrl(BHSF_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("type")&&jo.get("type").toString().trim().equals("success")){
return true;
}
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
/**
* 删除班级人员
* @param cuMapList
* @return
*/
public static boolean delClassUser(List<Map<String,Object>> cuMapList,Integer classid){
return OperateClassUser(cuMapList, "delClassUser",classid);
}
/**
* 添加班级人员
* @param cuMapList
* @return
*/
public static boolean addClassUser(List<Map<String,Object>> cuMapList){
return OperateClassUser(cuMapList, "addClassUser",null);
}
/**
* 操作用户与小组数据
* @param cuMapList 必带 userId,userType 的key
* @param groupId
* @param schoolid
* @return
*/
public static boolean OperateGroupUser(List<Map<String,Object>> cuMapList,Integer classid,Long groupId,Integer schoolid){
String addToEtt_URL=UtilTool.utilproperty.getProperty("TO_ETT_GROUPUSER_INTERFACE").toString();
if(groupId==null||schoolid==null||classid==null)return false;
HashMap<String,String> paramMap=new HashMap<String,String>();
paramMap.put("time",new Date().getTime()+"");
//得到data JSONObject
Map<String,Object> tmpMap=new HashMap<String, Object>();
tmpMap.put("groupId",groupId);
tmpMap.put("classId",classid);
tmpMap.put("schoolId",schoolid);
if(cuMapList!=null&&cuMapList.size()>0)
tmpMap.put("userList",JSONArray.fromObject(cuMapList).toString());
//存入
paramMap.put("data",JSONObject.fromObject(tmpMap).toString());
// JSONObject jb=JSONObject.fromObject(paramMap);
String val = UrlSigUtil.makeSigSimple("jionGroupUserInterFace.do", paramMap);
paramMap.put("sign",val);
JSONObject jo=UtilTool.sendPostUrl(addToEtt_URL,paramMap,"UTF-8");
if(jo!=null&&jo.containsKey("result")&&jo.get("result").toString().trim().equals("1")){
return true;
}
if(jo!=null)
System.out.println(jo.get("msg"));
return false;
}
public static boolean ModifyUser(UserInfo u,String identity){
if(u==null||identity==null)
return false;
String ettUrl=UtilTool.utilproperty.get("ETT_INTER_IP").toString()+"modifyUser.do";
//String ettUrl="http://192.168.10.59/study-im-service-1.0/modifyUser.do";
if(ettUrl==null)return false;
HashMap<String,String> tmpMap=new HashMap<String, String>();
tmpMap.put("timestamp",new Date().getTime()+"");
tmpMap.put("dcSchoolId",u.getDcschoolid().toString());
tmpMap.put("jid",u.getEttuserid().toString());
tmpMap.put("dcUserId",u.getUserid().toString());
tmpMap.put("userName",u.getUsername());
tmpMap.put("password",<PASSWORD>());
tmpMap.put("email",u.getMailaddress());
tmpMap.put("identity",identity);
String sign=UrlSigUtil.makeSigSimple("modifyUser.do",tmpMap);
tmpMap.put("sign",sign);
JSONObject jo=UtilTool.sendPostUrl(ettUrl,tmpMap,"UTF-8");
System.out.println(UtilTool.decode(jo.get("msg").toString()));
if(jo!=null&&jo.containsKey("result")&&jo.get("result").toString().trim().equals("1")){
return true;
}
return false;
}
//main方法
public static void main(String[] args){
}
}
| 14,010 | 0.583759 | 0.579025 | 354 | 36.194916 | 27.739992 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.864407 | false | false |
9
|
f8ee1a372953696c6e7f344d4441d0627098e27b
| 20,057,497,288,785 |
86bbc196aad5da571ded2999be956c5dfc9c49fb
|
/src/main/java/robot/estimation/StockEstimationUpdator.java
|
9d38fc7adaa7c4ecf775d86af7d4ce2e9d08227d
|
[] |
no_license
|
kpyopark/stock-value-tracer
|
https://github.com/kpyopark/stock-value-tracer
|
454ae31d0e06f3ffa444b479cc750ce593b3943d
|
db4d401354ce2012fe2f891133785af80959993e
|
refs/heads/master
| 2022-09-15T23:40:32.761000 | 2020-11-17T08:40:49 | 2020-11-17T08:40:49 | 32,115,916 | 0 | 0 | null | false | 2022-02-16T01:14:41 | 2015-03-13T01:29:29 | 2020-11-17T08:41:07 | 2022-02-16T01:14:37 | 12,347 | 0 | 0 | 2 |
Java
| false | false |
package robot.estimation;
import java.util.ArrayList;
import common.PeriodUtil;
import common.StringUtil;
import dao.CompanyExDao;
import dao.CompanyStockEstimationDao;
import estimator.StockValueEstimator;
import post.Company;
import post.CompanyEx;
import post.KrxSecurityType;
import post.StockEstimated;
import robot.DataUpdator;
/**
* 저장되어 있는 주식정보를 활용하여 기초 자료를 생성한다.
*
* @author Administrator
*
*/
public class StockEstimationUpdator extends DataUpdator {
ArrayList<CompanyEx> companyList = null;
String standardDate = null;
public StockEstimationUpdator() {
this(StringUtil.convertToStandardDate(new java.util.Date()));
}
public StockEstimationUpdator(String standardDate) {
this.standardDate = standardDate;
init();
}
public void init() {
try {
CompanyExDao dao = new CompanyExDao();
companyList = dao.selectAllList(this.standardDate, KrxSecurityType.STOCK);
} catch ( Exception e ) {
e.printStackTrace();
}
}
public StockEstimated estimate(Company company, String registeredDate) {
StockValueEstimator estimator = new StockValueEstimator(registeredDate);
StockEstimated cse = estimator.caculateCompanyStockEstimation(company);
return cse;
}
public void updateAllStockEstimation() {
for(Company company:companyList) {
updateStockEstimated(company, StringUtil.convertToStandardDate(new java.util.Date()));
}
}
/**
*
* 주가 추산치 정보를 수정한다.
*
* @param cse
* @return
*/
public int updateStockEstimated(Company company, String registeredDate) {
CompanyStockEstimationDao stockEstimDao = new CompanyStockEstimationDao();
StockEstimated cse = estimate(company, registeredDate);
Throwable err = null;
int totCnt = 0;
try {
if ( stockEstimDao.select(cse.getCompany(), registeredDate ) != null ) {
stockEstimDao.delete(cse);
}
totCnt = stockEstimDao.insert(cse) ? 1 : 0;
} catch ( Exception e ) {
System.out.println("updateStockEstimated failed:" + company.getId() + ":" + company.getName() + ":" + registeredDate);;
err = e;
}
fireStockEstimationChanged(cse, err);
return totCnt;
}
public static void main(String[] args) {
updateAllStockAndPeriods();
}
public static void testStockEsitmation() {
try {
StockEstimationUpdator updator = new StockEstimationUpdator();
Company company = new Company();
company.setId("A006390");
updator.updateStockEstimated(company, StringUtil.convertToStandardDate(new java.util.Date()));
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static void updateAllStockAndPeriods() {
ArrayList<String> monthlyPeriods = PeriodUtil.getMonthlyPeriodList(2003, 2014);
CompanyExDao companyDao = new CompanyExDao();
try {
for( String monthString : monthlyPeriods ) {
ArrayList<CompanyEx> companies = companyDao.selectAllList(monthString, KrxSecurityType.STOCK);
StockEstimationUpdator updator = new StockEstimationUpdator();
for( Company company : companies ) {
System.out.println("update stock esitmated:" + company.getId() + ":" + company.getName() + ":" + monthString );
updator.updateStockEstimated(company, monthString);
}
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 3,396 |
java
|
StockEstimationUpdator.java
|
Java
|
[
{
"context": "* 저장되어 있는 주식정보를 활용하여 기초 자료를 생성한다.\r\n * \r\n * @author Administrator\r\n *\r\n */\r\npublic class StockEstimationUpdator ext",
"end": 422,
"score": 0.799472451210022,
"start": 409,
"tag": "USERNAME",
"value": "Administrator"
}
] | null |
[] |
package robot.estimation;
import java.util.ArrayList;
import common.PeriodUtil;
import common.StringUtil;
import dao.CompanyExDao;
import dao.CompanyStockEstimationDao;
import estimator.StockValueEstimator;
import post.Company;
import post.CompanyEx;
import post.KrxSecurityType;
import post.StockEstimated;
import robot.DataUpdator;
/**
* 저장되어 있는 주식정보를 활용하여 기초 자료를 생성한다.
*
* @author Administrator
*
*/
public class StockEstimationUpdator extends DataUpdator {
ArrayList<CompanyEx> companyList = null;
String standardDate = null;
public StockEstimationUpdator() {
this(StringUtil.convertToStandardDate(new java.util.Date()));
}
public StockEstimationUpdator(String standardDate) {
this.standardDate = standardDate;
init();
}
public void init() {
try {
CompanyExDao dao = new CompanyExDao();
companyList = dao.selectAllList(this.standardDate, KrxSecurityType.STOCK);
} catch ( Exception e ) {
e.printStackTrace();
}
}
public StockEstimated estimate(Company company, String registeredDate) {
StockValueEstimator estimator = new StockValueEstimator(registeredDate);
StockEstimated cse = estimator.caculateCompanyStockEstimation(company);
return cse;
}
public void updateAllStockEstimation() {
for(Company company:companyList) {
updateStockEstimated(company, StringUtil.convertToStandardDate(new java.util.Date()));
}
}
/**
*
* 주가 추산치 정보를 수정한다.
*
* @param cse
* @return
*/
public int updateStockEstimated(Company company, String registeredDate) {
CompanyStockEstimationDao stockEstimDao = new CompanyStockEstimationDao();
StockEstimated cse = estimate(company, registeredDate);
Throwable err = null;
int totCnt = 0;
try {
if ( stockEstimDao.select(cse.getCompany(), registeredDate ) != null ) {
stockEstimDao.delete(cse);
}
totCnt = stockEstimDao.insert(cse) ? 1 : 0;
} catch ( Exception e ) {
System.out.println("updateStockEstimated failed:" + company.getId() + ":" + company.getName() + ":" + registeredDate);;
err = e;
}
fireStockEstimationChanged(cse, err);
return totCnt;
}
public static void main(String[] args) {
updateAllStockAndPeriods();
}
public static void testStockEsitmation() {
try {
StockEstimationUpdator updator = new StockEstimationUpdator();
Company company = new Company();
company.setId("A006390");
updator.updateStockEstimated(company, StringUtil.convertToStandardDate(new java.util.Date()));
} catch ( Exception e ) {
e.printStackTrace();
}
}
public static void updateAllStockAndPeriods() {
ArrayList<String> monthlyPeriods = PeriodUtil.getMonthlyPeriodList(2003, 2014);
CompanyExDao companyDao = new CompanyExDao();
try {
for( String monthString : monthlyPeriods ) {
ArrayList<CompanyEx> companies = companyDao.selectAllList(monthString, KrxSecurityType.STOCK);
StockEstimationUpdator updator = new StockEstimationUpdator();
for( Company company : companies ) {
System.out.println("update stock esitmated:" + company.getId() + ":" + company.getName() + ":" + monthString );
updator.updateStockEstimated(company, monthString);
}
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
| 3,396 | 0.702166 | 0.697052 | 115 | 26.904348 | 27.895138 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.034783 | false | false |
9
|
e74b5ef10707bd9cfebf59e5a1642bf290b11674
| 30,374,008,742,870 |
524bd425eb4cd5506b4cb9224e1512707803b168
|
/src/fr/tsadeo/app/gwt/modulehelper/server/model/Permutation.java
|
ee00ee5c96a408e3168170aa4369552849a7f8b0
|
[] |
no_license
|
gishshir/GwtModuleHelper
|
https://github.com/gishshir/GwtModuleHelper
|
7eb35a9b6fe6008e31108cf5ac7d54676117e36e
|
182a18b3a3826e90c73e86a6156be9e847ed78fa
|
refs/heads/master
| 2021-01-22T04:02:24.682000 | 2017-09-03T12:18:47 | 2017-09-03T12:20:18 | 102,262,661 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fr.tsadeo.app.gwt.modulehelper.server.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Permutation implements Serializable {
private static final long serialVersionUID = 1L;
private final Compilation _compilation;
// liste de property no conditionnelles (set) ou conditionnelles
// une seule Property mono_valeur par clé
private final List<Property> _propertyList = new ArrayList<Property>();
//calculé
private Map<KeyProperty, Property> _mapSetProperties;
//------------------------------------------------ accessors
public Compilation getCompilation() {
return _compilation;
}
public List<Property> getPropertyList() {
return this._propertyList;
}
//------------------------------------------------ public method
public Permutation clone() {
final Permutation permutation = new Permutation(this._compilation);
permutation.getPropertyList().addAll(this._propertyList);
return permutation;
}
public boolean hasProperties() {
return this._propertyList != null && !this._propertyList.isEmpty();
}
public Property getProperty(final KeyProperty keyProperty) {
if (!this.hasProperties()) return null;
if (this._mapSetProperties == null) {
this.populateMapSetProperies();
}
return this._mapSetProperties.get(keyProperty);
}
public void removeProperty (final Property propertyToRemove) {
if(!this.hasProperties()) return;
this._propertyList.remove(propertyToRemove);
if (this._mapSetProperties == null) {
this._mapSetProperties.remove(propertyToRemove.getKey());
}
}
//------------------------------------------------ constructor
public Permutation() {
this(null);
}
public Permutation(final Compilation compilation) {
this(compilation, null);
}
public Permutation(final Compilation compilation, final Property property) {
this._compilation = compilation;
if (property != null) {
this._propertyList.add(property);
}
}
//---------------------------------------------------- private methods
private void populateMapSetProperies() {
if (!this.hasProperties()) return;
if (this._mapSetProperties == null) {
this._mapSetProperties = new HashMap<KeyProperty, Property>(this._propertyList.size());
}
else {
this._mapSetProperties.clear();
}
for (Property property : this._propertyList) {
this._mapSetProperties.put(property.getKey(), property);
}
}
}
|
UTF-8
|
Java
| 2,472 |
java
|
Permutation.java
|
Java
|
[] | null |
[] |
package fr.tsadeo.app.gwt.modulehelper.server.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Permutation implements Serializable {
private static final long serialVersionUID = 1L;
private final Compilation _compilation;
// liste de property no conditionnelles (set) ou conditionnelles
// une seule Property mono_valeur par clé
private final List<Property> _propertyList = new ArrayList<Property>();
//calculé
private Map<KeyProperty, Property> _mapSetProperties;
//------------------------------------------------ accessors
public Compilation getCompilation() {
return _compilation;
}
public List<Property> getPropertyList() {
return this._propertyList;
}
//------------------------------------------------ public method
public Permutation clone() {
final Permutation permutation = new Permutation(this._compilation);
permutation.getPropertyList().addAll(this._propertyList);
return permutation;
}
public boolean hasProperties() {
return this._propertyList != null && !this._propertyList.isEmpty();
}
public Property getProperty(final KeyProperty keyProperty) {
if (!this.hasProperties()) return null;
if (this._mapSetProperties == null) {
this.populateMapSetProperies();
}
return this._mapSetProperties.get(keyProperty);
}
public void removeProperty (final Property propertyToRemove) {
if(!this.hasProperties()) return;
this._propertyList.remove(propertyToRemove);
if (this._mapSetProperties == null) {
this._mapSetProperties.remove(propertyToRemove.getKey());
}
}
//------------------------------------------------ constructor
public Permutation() {
this(null);
}
public Permutation(final Compilation compilation) {
this(compilation, null);
}
public Permutation(final Compilation compilation, final Property property) {
this._compilation = compilation;
if (property != null) {
this._propertyList.add(property);
}
}
//---------------------------------------------------- private methods
private void populateMapSetProperies() {
if (!this.hasProperties()) return;
if (this._mapSetProperties == null) {
this._mapSetProperties = new HashMap<KeyProperty, Property>(this._propertyList.size());
}
else {
this._mapSetProperties.clear();
}
for (Property property : this._propertyList) {
this._mapSetProperties.put(property.getKey(), property);
}
}
}
| 2,472 | 0.676518 | 0.676113 | 80 | 29.875 | 24.599987 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.7625 | false | false |
9
|
f9ae813439939b4c13774d4216db2590f1f391b6
| 14,920,716,390,952 |
2c20c413590b378d0a9b714658b3fd6a948aa270
|
/app/src/main/java/com/example/no0ne/ears/JobActivity.java
|
696aa096db841fe494bc43900018d1953f259322
|
[] |
no_license
|
Tusar0003/EARS
|
https://github.com/Tusar0003/EARS
|
4c68e3e8a95fb2cef911df3f0709c36b9f41b1b4
|
e65f201bb3026e0435c4ace8b656ce7e133f7b12
|
refs/heads/master
| 2018-11-14T12:49:56.633000 | 2018-09-01T19:16:48 | 2018-09-01T19:16:48 | 114,012,256 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.no0ne.ears;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import com.google.firebase.auth.FirebaseAuth;
public class JobActivity extends AppCompatActivity {
private RelativeLayout mJobPostLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job);
mJobPostLayout = (RelativeLayout) findViewById(R.id.job_post);
mJobPostLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(JobActivity.this, JobDetailsActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.job_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.menu_log_out) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(JobActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
}
|
UTF-8
|
Java
| 1,850 |
java
|
JobActivity.java
|
Java
|
[
{
"context": "package com.example.no0ne.ears;\n\nimport android.content.Intent;\nimport andr",
"end": 25,
"score": 0.9630879759788513,
"start": 20,
"tag": "USERNAME",
"value": "no0ne"
}
] | null |
[] |
package com.example.no0ne.ears;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import com.google.firebase.auth.FirebaseAuth;
public class JobActivity extends AppCompatActivity {
private RelativeLayout mJobPostLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job);
mJobPostLayout = (RelativeLayout) findViewById(R.id.job_post);
mJobPostLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(JobActivity.this, JobDetailsActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.job_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.menu_log_out) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(JobActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);
}
}
| 1,850 | 0.657838 | 0.656216 | 67 | 26.61194 | 22.821798 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522388 | false | false |
9
|
46b28cc709e1f6822ffca585889b1c9440d31da8
| 10,642,928,974,419 |
2576960f86ee39388e00395693c6ef28f3cadb6c
|
/src/com/day17zuoye/work3/Dian.java
|
9b0947ea7c92ad5d5e103c5e3ac63c8290913557
|
[] |
no_license
|
ppapzzhCSDN/day17
|
https://github.com/ppapzzhCSDN/day17
|
62042991feab0f6f47c2ad3db91a6d175bcebdfe
|
94230ebfda926d73291ebaeada1ff4a23db2562a
|
refs/heads/master
| 2023-02-20T23:39:28.675000 | 2021-01-26T09:03:47 | 2021-01-26T09:03:47 | 332,726,039 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.day17zuoye.work3;
public class Dian implements Runnable {
private Object obj = new Object();
Integer num = 100;
int shiti=0;
int guangwang =0;
public Dian(Object obj) {
}
public Dian(Object obj, Integer num) {
this.obj = obj;
this.num = num;
}
@Override
public void run() {
while (true) {
synchronized (this) {
if (num <= 0) {
System.out.println("卖完啦");
if(("实体店").equals(Thread.currentThread().getName())){ //Thread可能为空 所以放后面
shiti++;
System.out.println("实体店卖了:" + shiti);
}
guangwang++;
System.out.println("官网卖了:" + guangwang);
break;
}
System.out.println("店名为:" + Thread.currentThread().getName() + " 剩余水杯" + num);
num--;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
UTF-8
|
Java
| 1,200 |
java
|
Dian.java
|
Java
|
[] | null |
[] |
package com.day17zuoye.work3;
public class Dian implements Runnable {
private Object obj = new Object();
Integer num = 100;
int shiti=0;
int guangwang =0;
public Dian(Object obj) {
}
public Dian(Object obj, Integer num) {
this.obj = obj;
this.num = num;
}
@Override
public void run() {
while (true) {
synchronized (this) {
if (num <= 0) {
System.out.println("卖完啦");
if(("实体店").equals(Thread.currentThread().getName())){ //Thread可能为空 所以放后面
shiti++;
System.out.println("实体店卖了:" + shiti);
}
guangwang++;
System.out.println("官网卖了:" + guangwang);
break;
}
System.out.println("店名为:" + Thread.currentThread().getName() + " 剩余水杯" + num);
num--;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 1,200 | 0.439046 | 0.428445 | 38 | 28.789474 | 21.135101 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false |
9
|
2a00883adea81a1f331540af1ed92fc545aa308c
| 18,322,330,496,651 |
8eaecebc9c926e3ca6cf8b39bfe20811cbbd7a19
|
/src/org/intellij/erlang/psi/impl/ErlangPsiPolyVariantCachingReferenceBase.java
|
b588a3916d208789bd87ed32f8d2bb43b56f8160
|
[
"Apache-2.0"
] |
permissive
|
ignatov/intellij-erlang
|
https://github.com/ignatov/intellij-erlang
|
95ff7aedb1e8931efb8c466917dd335b42c0a545
|
a8fd0adf35549408e20e8434a0d6f3cfbb2eec39
|
refs/heads/master
| 2023-08-31T00:13:40.695000 | 2023-07-31T08:12:35 | 2023-07-31T08:12:35 | 5,168,907 | 512 | 134 |
NOASSERTION
| false | 2023-07-31T08:12:37 | 2012-07-24T17:41:30 | 2023-07-18T07:12:24 | 2023-07-31T08:12:35 | 71,005 | 711 | 115 | 244 |
Java
| false | false |
/*
* Copyright 2012-2016 Sergey Ignatov
*
* 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.intellij.erlang.psi.impl;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPolyVariantReferenceBase;
import com.intellij.psi.impl.source.resolve.ResolveCache;
import org.jetbrains.annotations.Nullable;
public abstract class ErlangPsiPolyVariantCachingReferenceBase<T extends PsiElement> extends PsiPolyVariantReferenceBase<T> {
public ErlangPsiPolyVariantCachingReferenceBase(T element, TextRange range) {
super(element, range);
}
private static final ResolveCache.AbstractResolver<ErlangPsiPolyVariantCachingReferenceBase<?>, PsiElement> MY_RESOLVER =
(base, incompleteCode) -> base.resolveInner();
@Nullable
@Override
public final PsiElement resolve() {
return getElement().isValid()
? ResolveCache.getInstance(getElement().getProject()).resolveWithCaching(this, MY_RESOLVER, false, false)
: null;
}
@Nullable
public abstract PsiElement resolveInner();
@Override
public boolean equals(Object o) {
return this == o || o instanceof ErlangPsiPolyVariantCachingReferenceBase
&& getElement() == ((ErlangPsiPolyVariantCachingReferenceBase<?>) o).getElement();
}
@Override
public int hashCode() {
return getElement().hashCode();
}
}
|
UTF-8
|
Java
| 1,901 |
java
|
ErlangPsiPolyVariantCachingReferenceBase.java
|
Java
|
[
{
"context": "/*\n * Copyright 2012-2016 Sergey Ignatov\n *\n * Licensed under the Apache License, Version ",
"end": 40,
"score": 0.9998199343681335,
"start": 26,
"tag": "NAME",
"value": "Sergey Ignatov"
}
] | null |
[] |
/*
* Copyright 2012-2016 <NAME>
*
* 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.intellij.erlang.psi.impl;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPolyVariantReferenceBase;
import com.intellij.psi.impl.source.resolve.ResolveCache;
import org.jetbrains.annotations.Nullable;
public abstract class ErlangPsiPolyVariantCachingReferenceBase<T extends PsiElement> extends PsiPolyVariantReferenceBase<T> {
public ErlangPsiPolyVariantCachingReferenceBase(T element, TextRange range) {
super(element, range);
}
private static final ResolveCache.AbstractResolver<ErlangPsiPolyVariantCachingReferenceBase<?>, PsiElement> MY_RESOLVER =
(base, incompleteCode) -> base.resolveInner();
@Nullable
@Override
public final PsiElement resolve() {
return getElement().isValid()
? ResolveCache.getInstance(getElement().getProject()).resolveWithCaching(this, MY_RESOLVER, false, false)
: null;
}
@Nullable
public abstract PsiElement resolveInner();
@Override
public boolean equals(Object o) {
return this == o || o instanceof ErlangPsiPolyVariantCachingReferenceBase
&& getElement() == ((ErlangPsiPolyVariantCachingReferenceBase<?>) o).getElement();
}
@Override
public int hashCode() {
return getElement().hashCode();
}
}
| 1,893 | 0.746975 | 0.740663 | 54 | 34.203705 | 34.259026 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false |
9
|
323b12495a2f1c63d689c1d83130ce24703d7d30
| 18,322,330,496,788 |
1c3e82ea2b62ab6cdab9805098975d578ff401fb
|
/leetcode/src/algorithms/P053/Solution.java
|
50df75a36e7900ad06f0692e9dc6d2b84572a8f5
|
[] |
no_license
|
sgirabin/coding
|
https://github.com/sgirabin/coding
|
c05436190193e44c3fd8cdaa189453139e7db16d
|
407542a914183768123ae6d0b1d1ba8a8bdb4f8a
|
refs/heads/master
| 2022-11-14T14:38:15.949000 | 2022-10-29T14:45:15 | 2022-10-29T14:47:38 | 57,686,269 | 0 | 0 | null | false | 2022-10-29T14:47:39 | 2016-05-01T17:22:35 | 2022-02-19T09:45:40 | 2022-10-29T14:47:38 | 47 | 0 | 0 | 0 |
Java
| false | false |
public class Solution {
public int maxSubArray(int[] nums) {
int[] total = new int[nums.length];
int max=0;
total[0]=nums[0];
max=total[0];
for (int i=1;i<nums.length;i++) {
total[i] = Math.max(nums[i],total[i-1]+nums[i]);
max=Math.max(total[i],max);
}
return max;
}
}
|
UTF-8
|
Java
| 376 |
java
|
Solution.java
|
Java
|
[] | null |
[] |
public class Solution {
public int maxSubArray(int[] nums) {
int[] total = new int[nums.length];
int max=0;
total[0]=nums[0];
max=total[0];
for (int i=1;i<nums.length;i++) {
total[i] = Math.max(nums[i],total[i-1]+nums[i]);
max=Math.max(total[i],max);
}
return max;
}
}
| 376 | 0.465426 | 0.449468 | 16 | 22.5 | 17.077032 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false |
9
|
aa4014eb901218192b5abc953c199872603eb483
| 4,260,607,588,841 |
ca030864a3a1c24be6b9d1802c2353da4ca0d441
|
/classes4.dex_source_from_JADX/com/fasterxml/jackson/datatype/guava/deser/GuavaMapDeserializer.java
|
8838cdc9cab1918487b69046e30cb6d6cec13856
|
[] |
no_license
|
pxson001/facebook-app
|
https://github.com/pxson001/facebook-app
|
87aa51e29195eeaae69adeb30219547f83a5b7b1
|
640630f078980f9818049625ebc42569c67c69f7
|
refs/heads/master
| 2020-04-07T20:36:45.758000 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fasterxml.jackson.datatype.guava.deser;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.type.MapType;
/* compiled from: getOtherSharedDirty */
public abstract class GuavaMapDeserializer<T> extends JsonDeserializer<T> implements ContextualDeserializer {
protected final MapType f11105a;
protected KeyDeserializer f11106b;
protected JsonDeserializer<?> f11107c;
protected final TypeDeserializer f11108d;
public abstract GuavaMapDeserializer<T> mo830a(KeyDeserializer keyDeserializer, TypeDeserializer typeDeserializer, JsonDeserializer<?> jsonDeserializer);
protected abstract T mo832b(JsonParser jsonParser, DeserializationContext deserializationContext);
protected GuavaMapDeserializer(MapType mapType, KeyDeserializer keyDeserializer, TypeDeserializer typeDeserializer, JsonDeserializer<?> jsonDeserializer) {
this.f11105a = mapType;
this.f11106b = keyDeserializer;
this.f11108d = typeDeserializer;
this.f11107c = jsonDeserializer;
}
public final JsonDeserializer<?> mo833a(DeserializationContext deserializationContext, BeanProperty beanProperty) {
KeyDeserializer keyDeserializer = this.f11106b;
JsonDeserializer jsonDeserializer = this.f11107c;
TypeDeserializer typeDeserializer = this.f11108d;
if (keyDeserializer != null && jsonDeserializer != null && typeDeserializer == null) {
return this;
}
if (keyDeserializer == null) {
keyDeserializer = deserializationContext.b(this.f11105a.q(), beanProperty);
}
if (jsonDeserializer == null) {
jsonDeserializer = deserializationContext.a(this.f11105a.r(), beanProperty);
}
if (typeDeserializer != null) {
typeDeserializer = typeDeserializer.a(beanProperty);
}
return mo830a(keyDeserializer, typeDeserializer, jsonDeserializer);
}
public final Object m11559a(JsonParser jsonParser, DeserializationContext deserializationContext, TypeDeserializer typeDeserializer) {
return typeDeserializer.b(jsonParser, deserializationContext);
}
public T m11558a(JsonParser jsonParser, DeserializationContext deserializationContext) {
JsonToken g = jsonParser.g();
if (g == JsonToken.START_OBJECT) {
g = jsonParser.c();
if (!(g == JsonToken.FIELD_NAME || g == JsonToken.END_OBJECT)) {
throw deserializationContext.b(this.f11105a._class);
}
} else if (g != JsonToken.FIELD_NAME) {
throw deserializationContext.b(this.f11105a._class);
}
return mo832b(jsonParser, deserializationContext);
}
}
|
UTF-8
|
Java
| 3,125 |
java
|
GuavaMapDeserializer.java
|
Java
|
[] | null |
[] |
package com.fasterxml.jackson.datatype.guava.deser;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.type.MapType;
/* compiled from: getOtherSharedDirty */
public abstract class GuavaMapDeserializer<T> extends JsonDeserializer<T> implements ContextualDeserializer {
protected final MapType f11105a;
protected KeyDeserializer f11106b;
protected JsonDeserializer<?> f11107c;
protected final TypeDeserializer f11108d;
public abstract GuavaMapDeserializer<T> mo830a(KeyDeserializer keyDeserializer, TypeDeserializer typeDeserializer, JsonDeserializer<?> jsonDeserializer);
protected abstract T mo832b(JsonParser jsonParser, DeserializationContext deserializationContext);
protected GuavaMapDeserializer(MapType mapType, KeyDeserializer keyDeserializer, TypeDeserializer typeDeserializer, JsonDeserializer<?> jsonDeserializer) {
this.f11105a = mapType;
this.f11106b = keyDeserializer;
this.f11108d = typeDeserializer;
this.f11107c = jsonDeserializer;
}
public final JsonDeserializer<?> mo833a(DeserializationContext deserializationContext, BeanProperty beanProperty) {
KeyDeserializer keyDeserializer = this.f11106b;
JsonDeserializer jsonDeserializer = this.f11107c;
TypeDeserializer typeDeserializer = this.f11108d;
if (keyDeserializer != null && jsonDeserializer != null && typeDeserializer == null) {
return this;
}
if (keyDeserializer == null) {
keyDeserializer = deserializationContext.b(this.f11105a.q(), beanProperty);
}
if (jsonDeserializer == null) {
jsonDeserializer = deserializationContext.a(this.f11105a.r(), beanProperty);
}
if (typeDeserializer != null) {
typeDeserializer = typeDeserializer.a(beanProperty);
}
return mo830a(keyDeserializer, typeDeserializer, jsonDeserializer);
}
public final Object m11559a(JsonParser jsonParser, DeserializationContext deserializationContext, TypeDeserializer typeDeserializer) {
return typeDeserializer.b(jsonParser, deserializationContext);
}
public T m11558a(JsonParser jsonParser, DeserializationContext deserializationContext) {
JsonToken g = jsonParser.g();
if (g == JsonToken.START_OBJECT) {
g = jsonParser.c();
if (!(g == JsonToken.FIELD_NAME || g == JsonToken.END_OBJECT)) {
throw deserializationContext.b(this.f11105a._class);
}
} else if (g != JsonToken.FIELD_NAME) {
throw deserializationContext.b(this.f11105a._class);
}
return mo832b(jsonParser, deserializationContext);
}
}
| 3,125 | 0.73312 | 0.70112 | 66 | 46.348484 | 37.763016 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.787879 | false | false |
9
|
82a1d76d618c0d9a65462bb479401a32ec9a5802
| 18,657,337,974,653 |
4732df6b2a42534a8553d38af3bbcf8220a41695
|
/src/main/java/com/design/pattern/迭代/黑箱聚集与内禀迭代子/ConcreteAggregate.java
|
4f8405750376507f915d25b18004ad40127ec565
|
[] |
no_license
|
huangyueranbbc/JavaDesignPattern
|
https://github.com/huangyueranbbc/JavaDesignPattern
|
f23f1621a4c6c7d43ee0e05b629d572427dc3945
|
438128abed47fadb71880897e1abc121de3f439c
|
refs/heads/master
| 2021-07-19T11:50:57.818000 | 2019-01-28T05:48:45 | 2019-01-28T05:48:45 | 153,722,916 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.design.pattern.迭代.黑箱聚集与内禀迭代子;
/*******************************************************************************
* @date 2018-10-19 上午 11:03
* @author: <a href=mailto:huangyr>黄跃然</a>
* @Description: 黑箱聚集与内禀迭代子
******************************************************************************/
public class ConcreteAggregate extends Aggregate {
private Object[] datas;
public ConcreteAggregate(Object[] datas) {
this.datas = datas;
}
@Override
public Iterator iterator() {
return new ConcreteIterator();
}
class ConcreteIterator implements Iterator {
private Integer index;
private Integer size;
public ConcreteIterator() {
this.size = datas.length;
this.index = 0;
}
@Override
public void first() {
index = 0;
}
@Override
public Object next() {
return datas[index++];
}
@Override
public Boolean hasNext() {
return index < size;
}
}
}
|
UTF-8
|
Java
| 1,122 |
java
|
ConcreteAggregate.java
|
Java
|
[
{
"context": "te 2018-10-19 上午 11:03\n * @author: <a href=mailto:huangyr>黄跃然</a>\n * @Description: 黑箱聚集与内禀迭代子\n ************",
"end": 187,
"score": 0.9953327775001526,
"start": 180,
"tag": "USERNAME",
"value": "huangyr"
},
{
"context": "10-19 上午 11:03\n * @author: <a href=mailto:huangyr>黄跃然</a>\n * @Description: 黑箱聚集与内禀迭代子\n ****************",
"end": 191,
"score": 0.9997458457946777,
"start": 188,
"tag": "NAME",
"value": "黄跃然"
}
] | null |
[] |
package com.design.pattern.迭代.黑箱聚集与内禀迭代子;
/*******************************************************************************
* @date 2018-10-19 上午 11:03
* @author: <a href=mailto:huangyr>黄跃然</a>
* @Description: 黑箱聚集与内禀迭代子
******************************************************************************/
public class ConcreteAggregate extends Aggregate {
private Object[] datas;
public ConcreteAggregate(Object[] datas) {
this.datas = datas;
}
@Override
public Iterator iterator() {
return new ConcreteIterator();
}
class ConcreteIterator implements Iterator {
private Integer index;
private Integer size;
public ConcreteIterator() {
this.size = datas.length;
this.index = 0;
}
@Override
public void first() {
index = 0;
}
@Override
public Object next() {
return datas[index++];
}
@Override
public Boolean hasNext() {
return index < size;
}
}
}
| 1,122 | 0.473783 | 0.460674 | 47 | 21.723404 | 19.831955 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.234043 | false | false |
9
|
43ddad9cba9f943fceae1eabd2decabf9bf286be
| 16,544,214,057,987 |
f9c88137921b1e6cba027cf4056f72ccf0a5b37b
|
/app/src/main/java/com/ggy/babybed/basic/MessageAdapter.java
|
099c57f6023cd220c33302e1a9b02cb93fcb2e3b
|
[] |
no_license
|
ggygh/BabyBedn
|
https://github.com/ggygh/BabyBedn
|
cccbee0f7d64ba40bc78ce256fac7b53247dc2e5
|
345e63335bd522776a5decff4f6343518de94f3c
|
refs/heads/master
| 2016-06-10T22:45:00.567000 | 2016-05-12T12:59:02 | 2016-05-12T12:59:02 | 58,636,049 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ggy.babybed.basic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.ggy.babybed.R;
import com.ggy.babybed.model.MessageModel;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ggy on 2016/3/15.
*/
public class MessageAdapter extends BaseAdapter{
private LayoutInflater inflater;
private List<MessageModel> messages;
public MessageAdapter(Context context , List<MessageModel> messages) {
this.inflater = LayoutInflater.from(context);
if(null == messages){
this.messages = new ArrayList<>();
}else {
this.messages = messages;
}
}
@Override
public int getCount() {
return messages.size();
}
@Override
public Object getItem(int position) {
return messages.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.msg_listitem, null);
viewHolder.msg_head = (TextView) convertView.findViewById(R.id.msg_head);
viewHolder.msg_content = (TextView) convertView.findViewById(R.id.msg_content);
viewHolder.msg_time = (TextView) convertView.findViewById(R.id.msg_time);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.msg_head.setText(messages.get(position).getMsgHead());
viewHolder.msg_content.setText(messages.get(position).getMessage());
viewHolder.msg_time.setText(messages.get(position).getTime());
return convertView;
}
static class ViewHolder{
TextView msg_head;
TextView msg_content;
TextView msg_time;
}
}
|
UTF-8
|
Java
| 2,109 |
java
|
MessageAdapter.java
|
Java
|
[
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by ggy on 2016/3/15.\n */\npublic class MessageAdapter ext",
"end": 368,
"score": 0.9995556473731995,
"start": 365,
"tag": "USERNAME",
"value": "ggy"
}
] | null |
[] |
package com.ggy.babybed.basic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.ggy.babybed.R;
import com.ggy.babybed.model.MessageModel;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ggy on 2016/3/15.
*/
public class MessageAdapter extends BaseAdapter{
private LayoutInflater inflater;
private List<MessageModel> messages;
public MessageAdapter(Context context , List<MessageModel> messages) {
this.inflater = LayoutInflater.from(context);
if(null == messages){
this.messages = new ArrayList<>();
}else {
this.messages = messages;
}
}
@Override
public int getCount() {
return messages.size();
}
@Override
public Object getItem(int position) {
return messages.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.msg_listitem, null);
viewHolder.msg_head = (TextView) convertView.findViewById(R.id.msg_head);
viewHolder.msg_content = (TextView) convertView.findViewById(R.id.msg_content);
viewHolder.msg_time = (TextView) convertView.findViewById(R.id.msg_time);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.msg_head.setText(messages.get(position).getMsgHead());
viewHolder.msg_content.setText(messages.get(position).getMessage());
viewHolder.msg_time.setText(messages.get(position).getTime());
return convertView;
}
static class ViewHolder{
TextView msg_head;
TextView msg_content;
TextView msg_time;
}
}
| 2,109 | 0.65908 | 0.655761 | 72 | 28.291666 | 24.273579 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527778 | false | false |
9
|
e2064517bb1894a334d97714bb2cd24ce6a13375
| 32,152,125,226,956 |
54766741c148a439a408c150e1d2af6624ba8e16
|
/09-Pilas-Vehiculo/Principal.java
|
203a71102ffeeb9df24e16f29e2dcdbf86699d27
|
[] |
no_license
|
pxnditxyr/Practicas-Estructura-de-Datos
|
https://github.com/pxnditxyr/Practicas-Estructura-de-Datos
|
d8cb50957f66a672242e54ad8c873e20fe8b6b20
|
0ccba561e3ce3a0ab86d4f4b619da84f9316d6ad
|
refs/heads/main
| 2023-06-11T19:16:09.724000 | 2021-07-06T15:12:58 | 2021-07-06T15:12:58 | 353,492,387 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Principal {
public static void main (String[] args) {
Operaciones op = new Operaciones();
Pila pila = new Pila();
String marca, placa;
op.insertarN(pila);
op.mostrar(pila);
//op.contarMarca(pila);
System.out.println("Se contaran los vehiculos mas antiguos");
op.cantidadVehiculosAntuguos(pila);
op.mostrar(pila);
System.out.println("Se eliminara una marca dada con modelo < a 1990");
System.out.println("Inserte la marca");
marca = Leer.dato();
op.eliminarMarca(pila, marca);
op.mostrar(pila);
System.out.println("Se Insertara nuevo vehiculo despues de la placa dada");
System.out.println("Inserte la placa");
placa = Leer.dato();
op.insertarNuevo(pila, placa);
op.mostrar(pila);
}
}
|
UTF-8
|
Java
| 739 |
java
|
Principal.java
|
Java
|
[] | null |
[] |
public class Principal {
public static void main (String[] args) {
Operaciones op = new Operaciones();
Pila pila = new Pila();
String marca, placa;
op.insertarN(pila);
op.mostrar(pila);
//op.contarMarca(pila);
System.out.println("Se contaran los vehiculos mas antiguos");
op.cantidadVehiculosAntuguos(pila);
op.mostrar(pila);
System.out.println("Se eliminara una marca dada con modelo < a 1990");
System.out.println("Inserte la marca");
marca = Leer.dato();
op.eliminarMarca(pila, marca);
op.mostrar(pila);
System.out.println("Se Insertara nuevo vehiculo despues de la placa dada");
System.out.println("Inserte la placa");
placa = Leer.dato();
op.insertarNuevo(pila, placa);
op.mostrar(pila);
}
}
| 739 | 0.7023 | 0.696888 | 24 | 29.75 | 19.279198 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.583333 | false | false |
9
|
a3fe4cfce95143658af1334525ddd03e705d6d73
| 11,072,425,751,432 |
b7c9c4b246278064fbc1fc6e9bca52f7d3e7e283
|
/Phonebook/SpringMVC/src/main/java/org/banani/dao/ContactDAOImpl.java
|
a304356d9a09a24b032ef98a641a06c84af91c51
|
[] |
no_license
|
Unan/Git-project
|
https://github.com/Unan/Git-project
|
4478fad4e301a7e331ea78c3ec80f56cf2da9e86
|
3462ee40aefebd96025dcc87e787b179f99c0935
|
refs/heads/master
| 2020-03-25T03:48:25.913000 | 2019-02-04T00:25:07 | 2019-02-04T00:25:07 | 143,361,025 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.banani.dao;
import com.sun.corba.se.impl.orbutil.ObjectStreamClassUtil_1_3;
import org.banani.model.Contact;
import org.banani.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public class ContactDAOImpl implements ContactDAO {
public static final String sqlUser = "select * from users where username = ?";
public static final String sqlCont = "select * from contact where phoneNumber = ?";
public static final String sqlAuth = "select authority from authorities where username = ?";
public static final String sqlContList = "select * from contact";
public static final String sqlUserList = "select * from users";
@Autowired
private JdbcTemplate jdbcTemplate;
public ContactDAOImpl(){}
public ContactDAOImpl(JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
public boolean DBUpdate(Contact contact) {
try {
jdbcTemplate.update("INSERT INTO contact (firstName, lastName, age, email, phoneNumber) VALUES (?,?,?,?,?)",
contact.getFirstName(),
contact.getLastName(),
contact.getAge(),
contact.getEmail(),
contact.getPhoneNumber());
return true;
} catch (Throwable s) {return false;}
}
public boolean DBUpdate(User user){
try {
jdbcTemplate.update("INSERT INTO users (username, password, firstName, lastName, age, phoneNumber) VALUES (?,?,?,?,?,?)",
user.getUsername(),
user.getPassword(),
user.getFirstName(),
user.getLastName(),
user.getAge(),
user.getPhoneNumber());
jdbcTemplate.update("insert into authorities (username, authority) value (?,?)",
user.getUsername(), "ROLE_USER");
return true;
}catch (Throwable s) {return false;}
}
public User getUserData(String username){
User user = new User();
List<Map<String, Object>> stringObjectMap = jdbcTemplate.queryForList(sqlUser, username);
user.setUsername((String)stringObjectMap.get(0).get("username"));
user.setPassword((String)stringObjectMap.get(0).get("password"));
user.setFirstName((String)stringObjectMap.get(0).get("firstName"));
user.setLastName((String)stringObjectMap.get(0).get("lastName"));
user.setAge((String)stringObjectMap.get(0).get("age"));
user.setEmail((String)stringObjectMap.get(0).get("email"));
user.setPhoneNumber((String)stringObjectMap.get(0).get("phoneNumber"));
return user;
}
public void deleteUser(User user){
jdbcTemplate.update("delete from users where username = ?", user.getUsername());
}
public List<User> getUserList(){
List<User> userList = new ArrayList<>();
List<Map<String, Object>> stringObjectMap = jdbcTemplate.queryForList(sqlUserList);
stringObjectMap.size();
for (int i = 0; i < stringObjectMap.size(); i++) {
User user = new User();
user.setUsername((String)stringObjectMap.get(i).get("username"));
user.setPassword((String)stringObjectMap.get(i).get("password"));
user.setFirstName((String)stringObjectMap.get(i).get("firstName"));
user.setLastName((String)stringObjectMap.get(i).get("lastName"));
user.setAge((String)stringObjectMap.get(i).get("age"));
user.setEmail((String)stringObjectMap.get(i).get("email"));
user.setPhoneNumber((String)stringObjectMap.get(i).get("phoneNumber"));
userList.add(user);
}
return userList;
}
public boolean Admin(String username){
boolean ifAdmin = false;
if (jdbcTemplate.queryForObject(sqlAuth, String.class, username).equals("ROLE_ADMIN"))
ifAdmin = true;
return ifAdmin;
}
public List<Contact> getContactList(){
List<String> list = new ArrayList<>();
List<Map<String, Object>> stringObjectMap = jdbcTemplate.queryForList(sqlContList);
for(Map<String, Object> listValue : stringObjectMap){
for(String key: listValue.keySet()){
//System.out.print(" " + key + ": " + listValue.get(key) + " ");
list.add((String)listValue.get(key));
}
//System.out.println();
}
List<Contact> ContactList = new ArrayList<>();
System.out.println(list.size());
for (int i = 0; i < list.size() - 1; i++) {
Contact contact = new Contact();
contact.setFirstName(list.get(i++));
contact.setLastName(list.get(i++));
contact.setAge(list.get(i++));
contact.setEmail(list.get(i++));
contact.setPhoneNumber(list.get(i));
ContactList.add(contact);
}
return ContactList;
}
}
|
UTF-8
|
Java
| 5,127 |
java
|
ContactDAOImpl.java
|
Java
|
[
{
"context": "r.setUsername((String)stringObjectMap.get(i).get(\"username\"));\n user.setPassword((String)stringOb",
"end": 3354,
"score": 0.9878909587860107,
"start": 3346,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package org.banani.dao;
import com.sun.corba.se.impl.orbutil.ObjectStreamClassUtil_1_3;
import org.banani.model.Contact;
import org.banani.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public class ContactDAOImpl implements ContactDAO {
public static final String sqlUser = "select * from users where username = ?";
public static final String sqlCont = "select * from contact where phoneNumber = ?";
public static final String sqlAuth = "select authority from authorities where username = ?";
public static final String sqlContList = "select * from contact";
public static final String sqlUserList = "select * from users";
@Autowired
private JdbcTemplate jdbcTemplate;
public ContactDAOImpl(){}
public ContactDAOImpl(JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
public boolean DBUpdate(Contact contact) {
try {
jdbcTemplate.update("INSERT INTO contact (firstName, lastName, age, email, phoneNumber) VALUES (?,?,?,?,?)",
contact.getFirstName(),
contact.getLastName(),
contact.getAge(),
contact.getEmail(),
contact.getPhoneNumber());
return true;
} catch (Throwable s) {return false;}
}
public boolean DBUpdate(User user){
try {
jdbcTemplate.update("INSERT INTO users (username, password, firstName, lastName, age, phoneNumber) VALUES (?,?,?,?,?,?)",
user.getUsername(),
user.getPassword(),
user.getFirstName(),
user.getLastName(),
user.getAge(),
user.getPhoneNumber());
jdbcTemplate.update("insert into authorities (username, authority) value (?,?)",
user.getUsername(), "ROLE_USER");
return true;
}catch (Throwable s) {return false;}
}
public User getUserData(String username){
User user = new User();
List<Map<String, Object>> stringObjectMap = jdbcTemplate.queryForList(sqlUser, username);
user.setUsername((String)stringObjectMap.get(0).get("username"));
user.setPassword((String)stringObjectMap.get(0).get("password"));
user.setFirstName((String)stringObjectMap.get(0).get("firstName"));
user.setLastName((String)stringObjectMap.get(0).get("lastName"));
user.setAge((String)stringObjectMap.get(0).get("age"));
user.setEmail((String)stringObjectMap.get(0).get("email"));
user.setPhoneNumber((String)stringObjectMap.get(0).get("phoneNumber"));
return user;
}
public void deleteUser(User user){
jdbcTemplate.update("delete from users where username = ?", user.getUsername());
}
public List<User> getUserList(){
List<User> userList = new ArrayList<>();
List<Map<String, Object>> stringObjectMap = jdbcTemplate.queryForList(sqlUserList);
stringObjectMap.size();
for (int i = 0; i < stringObjectMap.size(); i++) {
User user = new User();
user.setUsername((String)stringObjectMap.get(i).get("username"));
user.setPassword((String)stringObjectMap.get(i).get("password"));
user.setFirstName((String)stringObjectMap.get(i).get("firstName"));
user.setLastName((String)stringObjectMap.get(i).get("lastName"));
user.setAge((String)stringObjectMap.get(i).get("age"));
user.setEmail((String)stringObjectMap.get(i).get("email"));
user.setPhoneNumber((String)stringObjectMap.get(i).get("phoneNumber"));
userList.add(user);
}
return userList;
}
public boolean Admin(String username){
boolean ifAdmin = false;
if (jdbcTemplate.queryForObject(sqlAuth, String.class, username).equals("ROLE_ADMIN"))
ifAdmin = true;
return ifAdmin;
}
public List<Contact> getContactList(){
List<String> list = new ArrayList<>();
List<Map<String, Object>> stringObjectMap = jdbcTemplate.queryForList(sqlContList);
for(Map<String, Object> listValue : stringObjectMap){
for(String key: listValue.keySet()){
//System.out.print(" " + key + ": " + listValue.get(key) + " ");
list.add((String)listValue.get(key));
}
//System.out.println();
}
List<Contact> ContactList = new ArrayList<>();
System.out.println(list.size());
for (int i = 0; i < list.size() - 1; i++) {
Contact contact = new Contact();
contact.setFirstName(list.get(i++));
contact.setLastName(list.get(i++));
contact.setAge(list.get(i++));
contact.setEmail(list.get(i++));
contact.setPhoneNumber(list.get(i));
ContactList.add(contact);
}
return ContactList;
}
}
| 5,127 | 0.612249 | 0.609908 | 132 | 37.848484 | 30.221275 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.825758 | false | false |
9
|
da3f07200d5ccff6d4adbb8c19c0c3912325e118
| 11,072,425,752,407 |
203ec34b810281b7502c81369663e63e4bdc39fb
|
/PartitionList.java
|
3f87d1183e694f09fb054835b23065539438467b
|
[] |
no_license
|
yunhao539/LeetCodePeriod
|
https://github.com/yunhao539/LeetCodePeriod
|
0cfe16752203d88c77600323f764bd8090fc56c6
|
6e1688ac25c0d000a9e26e1b698c6a5263b07e39
|
refs/heads/master
| 2021-01-24T00:33:02.078000 | 2014-07-26T01:46:40 | 2014-07-26T01:46:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head == null) return null;
// !!! don't forget to initial the value "0" !!!
ListNode small = new ListNode(0);
ListNode large = new ListNode(0);
ListNode sHead = small;
ListNode lHead = large;
// !!! not head.next == null, but head !!!
while(head != null) {
if(head.val < x){
small.next = head;
small = small.next;
} else {
large.next = head;
large = large.next;
}
// !!! don't forget to move head !!!
head = head.next;
// !!! have to close the listnode !!!
// otherwise there may create a linkedlist cycle
small.next = null;
large.next = null;
}
// !!! equals to lHead.next, not lHead (both Head equals to 0) !!!
small.next = lHead.next;
return sHead.next;
}
}
|
UTF-8
|
Java
| 1,208 |
java
|
PartitionList.java
|
Java
|
[] | null |
[] |
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head == null) return null;
// !!! don't forget to initial the value "0" !!!
ListNode small = new ListNode(0);
ListNode large = new ListNode(0);
ListNode sHead = small;
ListNode lHead = large;
// !!! not head.next == null, but head !!!
while(head != null) {
if(head.val < x){
small.next = head;
small = small.next;
} else {
large.next = head;
large = large.next;
}
// !!! don't forget to move head !!!
head = head.next;
// !!! have to close the listnode !!!
// otherwise there may create a linkedlist cycle
small.next = null;
large.next = null;
}
// !!! equals to lHead.next, not lHead (both Head equals to 0) !!!
small.next = lHead.next;
return sHead.next;
}
}
| 1,208 | 0.479305 | 0.475993 | 40 | 29.200001 | 16.612043 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false |
9
|
e7fc3f09e369aa67deb59fb7d7f8ec23886a2004
| 35,897,336,672,643 |
3f1018f1f8f6f5a691e06d4e92690fe9d84c14f4
|
/src/main/java/sremy/Discount.java
|
0ef640501e8caa0037933e4a9f9929ed320a5bd0
|
[] |
no_license
|
sremy/cucumber-example
|
https://github.com/sremy/cucumber-example
|
88be525dbde4d35cfc2feab7fb8e7314c8a9546c
|
9944e0a62cb74b3995cc666f4fdd92a2f98759b2
|
refs/heads/master
| 2021-07-07T02:01:00.976000 | 2019-07-15T00:36:38 | 2019-07-15T00:36:38 | 195,311,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sremy;
public class Discount {
String name;
Long discount_cts;
public Discount() {
}
public Discount(String name, Long discount_cts) {
this.name = name;
this.discount_cts = discount_cts;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getDiscount_cts() {
return discount_cts;
}
public void setDiscount_cts(Long discount_cts) {
this.discount_cts = discount_cts;
}
@Override
public String toString() {
return "Discount{" +
"name='" + name + '\'' +
", dicount_cts=" + discount_cts +
'}';
}
}
|
UTF-8
|
Java
| 741 |
java
|
Discount.java
|
Java
|
[] | null |
[] |
package sremy;
public class Discount {
String name;
Long discount_cts;
public Discount() {
}
public Discount(String name, Long discount_cts) {
this.name = name;
this.discount_cts = discount_cts;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getDiscount_cts() {
return discount_cts;
}
public void setDiscount_cts(Long discount_cts) {
this.discount_cts = discount_cts;
}
@Override
public String toString() {
return "Discount{" +
"name='" + name + '\'' +
", dicount_cts=" + discount_cts +
'}';
}
}
| 741 | 0.529015 | 0.529015 | 40 | 17.525 | 16.551416 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false |
9
|
aeaa7c3d53bf2b0a731cbaedf718d8dedb573bd8
| 29,025,389,051,247 |
99b6ee9d659eae89551dadde78b8fff32f154764
|
/src/thesixPag/ActionListenerTest.java
|
fa9115e803de649bb4edc82cfb54bf3b0a8d0ede
|
[] |
no_license
|
liulu961126/newDemoGit
|
https://github.com/liulu961126/newDemoGit
|
80022b82eed68471f7862de44aca919dc7683de4
|
2f0899798a4faed35715f2c94c7e5da3564f6e5b
|
refs/heads/master
| 2020-05-23T01:11:33.119000 | 2019-07-15T14:26:02 | 2019-07-15T14:26:02 | 186,584,256 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package thesixPag;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class ActionListenerTest {
public static void listener(String text, int delay) {
ActionListener listener = e -> {
System.out.println(text);
Toolkit.getDefaultToolkit().beep();
};
new Timer(delay, listener).start();
}
public static void main(String[] args) {
listener("helloworld",1000);
}
}
|
UTF-8
|
Java
| 471 |
java
|
ActionListenerTest.java
|
Java
|
[] | null |
[] |
package thesixPag;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class ActionListenerTest {
public static void listener(String text, int delay) {
ActionListener listener = e -> {
System.out.println(text);
Toolkit.getDefaultToolkit().beep();
};
new Timer(delay, listener).start();
}
public static void main(String[] args) {
listener("helloworld",1000);
}
}
| 471 | 0.630573 | 0.622081 | 19 | 23.789474 | 18.429321 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false |
9
|
ade90c1fb1b81f6539dc640b8be81a197595809e
| 28,063,316,381,042 |
023518478c760fbf7a5c97407e7043569ea1e66d
|
/src/main/java/Principles/SRP/Violation/ViolateClass1.java
|
5fe95406d57126f58ef536b494676e67d0f58f3b
|
[] |
no_license
|
Vernon01/VernonAssignmentChapter4
|
https://github.com/Vernon01/VernonAssignmentChapter4
|
046e7e84e517618bbbe98ca99f2da5012ceaedb9
|
ad0eef037c05853c99a7156aec26739bee068684
|
refs/heads/master
| 2016-08-12T10:21:56.822000 | 2016-03-27T16:32:17 | 2016-03-27T16:32:17 | 54,837,580 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Principles.SRP.Violation;
/**
* Created by VERNON on 2016/03/27.
*/
public class ViolateClass1 implements ViolateInterface{
public String name()
{
String nm = "valmi";
return nm;
}
public String surname()
{
String sur = "carlo";
return sur;
}
public int age()
{
int age1 = 98;
return age1;
}
}
|
UTF-8
|
Java
| 395 |
java
|
ViolateClass1.java
|
Java
|
[
{
"context": "ckage Principles.SRP.Violation;\n\n/**\n * Created by VERNON on 2016/03/27.\n */\npublic class ViolateClass1 imp",
"end": 59,
"score": 0.8991929888725281,
"start": 53,
"tag": "NAME",
"value": "VERNON"
},
{
"context": " public String name()\n {\n String nm = \"valmi\";\n return nm;\n }\n\n\n public String su",
"end": 194,
"score": 0.9982232451438904,
"start": 189,
"tag": "NAME",
"value": "valmi"
},
{
"context": "blic String surname()\n {\n String sur = \"carlo\";\n return sur;\n }\n\n\n public int age(",
"end": 285,
"score": 0.9995375275611877,
"start": 280,
"tag": "NAME",
"value": "carlo"
}
] | null |
[] |
package Principles.SRP.Violation;
/**
* Created by VERNON on 2016/03/27.
*/
public class ViolateClass1 implements ViolateInterface{
public String name()
{
String nm = "valmi";
return nm;
}
public String surname()
{
String sur = "carlo";
return sur;
}
public int age()
{
int age1 = 98;
return age1;
}
}
| 395 | 0.541772 | 0.508861 | 28 | 13.107142 | 14.137941 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
9
|
a672b2aa06e9f58f4050756422f258d8bd517a08
| 33,758,442,966,350 |
48a5827b0ac67a1d4da50e339561e4c33ee10e6e
|
/src/main/java/com/warren/knickknacks/eclipse/jdt/core/prefs/UserLibraryMemberItemSearchParms.java
|
5da520152673b8b3d240ad4d71a9789af6c348c8
|
[] |
no_license
|
whennemuth/KnickKnacks
|
https://github.com/whennemuth/KnickKnacks
|
7a2bc26b53b48bb5412d9569252b387b95c2906b
|
a65ae2472b4c6b3553fa2b7c8b35e55be9b15d77
|
refs/heads/master
| 2021-01-16T22:17:29.358000 | 2016-03-22T03:29:35 | 2016-03-22T03:29:35 | 52,834,544 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.warren.knickknacks.eclipse.jdt.core.prefs;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This file represents the parameters for conducting a search.
* The search starts in a top level directory for files whose name match a specified pattern and are to be
* included as part of an eclipse user library of a specified name.
*
* @author Warren
*
*/
public class UserLibraryMemberItemSearchParms {
private String libName;
private String workspace;
private File workspaceDir;
private String rootDirPathname;
private File rootDir;
private Boolean includeSubDirs;
private Pattern pattern;
public static final String VALID = "All parameters are valid";
/**
* All parameter except for regex must be present.
* @return
*/
public String getValidationMessage() {
StringBuilder s = new StringBuilder();
if(workspace == null || !workspaceDir.isDirectory())
s.append("Invalid workspace directory: " + workspace + "\r\n");
if(rootDirPathname == null || !rootDir.isDirectory())
s.append("Invalid root directory: " + rootDirPathname + "\r\n");
if(includeSubDirs == null)
s.append("Include subdirectories not specified\r\n");
if(libName == null)
s.append("Library name not specified\r\n");
if(s.length() == 0) {
s.append(VALID);
}
else {
s.insert(0, "WARNING - INVALID PARAMETERS: \r\n");
}
return s.toString();
}
public boolean isValid() {
return VALID.equals(getValidationMessage());
}
public File getWorkspaceDir() {
return workspaceDir;
}
public void setWorkspaceDir(String workspace) {
this.workspace = workspace;
this.workspaceDir = new File(workspace);
}
public File getRootDir() {
return rootDir;
}
public void setRootDir(String root) {
this.rootDirPathname = root;
this.rootDir = new File(root);
}
public Boolean getIncludeSubDirs() {
return includeSubDirs;
}
public void setIncludeSubDirs(Boolean includeSubDirs) {
this.includeSubDirs = includeSubDirs;
}
public Matcher getMatcher(String s) {
if(pattern == null)
return null;
return pattern.matcher(s);
}
public void setRegex(String regex) {
this.pattern = Pattern.compile(regex);
}
public String getLibName() {
return libName;
}
public void setLibName(String libName) {
this.libName = libName;
}
}
|
UTF-8
|
Java
| 2,328 |
java
|
UserLibraryMemberItemSearchParms.java
|
Java
|
[
{
"context": "e user library of a specified name.\n * \n * @author Warren\n *\n */\npublic class UserLibraryMemberItemSearchPa",
"end": 406,
"score": 0.9979627132415771,
"start": 400,
"tag": "NAME",
"value": "Warren"
}
] | null |
[] |
package com.warren.knickknacks.eclipse.jdt.core.prefs;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This file represents the parameters for conducting a search.
* The search starts in a top level directory for files whose name match a specified pattern and are to be
* included as part of an eclipse user library of a specified name.
*
* @author Warren
*
*/
public class UserLibraryMemberItemSearchParms {
private String libName;
private String workspace;
private File workspaceDir;
private String rootDirPathname;
private File rootDir;
private Boolean includeSubDirs;
private Pattern pattern;
public static final String VALID = "All parameters are valid";
/**
* All parameter except for regex must be present.
* @return
*/
public String getValidationMessage() {
StringBuilder s = new StringBuilder();
if(workspace == null || !workspaceDir.isDirectory())
s.append("Invalid workspace directory: " + workspace + "\r\n");
if(rootDirPathname == null || !rootDir.isDirectory())
s.append("Invalid root directory: " + rootDirPathname + "\r\n");
if(includeSubDirs == null)
s.append("Include subdirectories not specified\r\n");
if(libName == null)
s.append("Library name not specified\r\n");
if(s.length() == 0) {
s.append(VALID);
}
else {
s.insert(0, "WARNING - INVALID PARAMETERS: \r\n");
}
return s.toString();
}
public boolean isValid() {
return VALID.equals(getValidationMessage());
}
public File getWorkspaceDir() {
return workspaceDir;
}
public void setWorkspaceDir(String workspace) {
this.workspace = workspace;
this.workspaceDir = new File(workspace);
}
public File getRootDir() {
return rootDir;
}
public void setRootDir(String root) {
this.rootDirPathname = root;
this.rootDir = new File(root);
}
public Boolean getIncludeSubDirs() {
return includeSubDirs;
}
public void setIncludeSubDirs(Boolean includeSubDirs) {
this.includeSubDirs = includeSubDirs;
}
public Matcher getMatcher(String s) {
if(pattern == null)
return null;
return pattern.matcher(s);
}
public void setRegex(String regex) {
this.pattern = Pattern.compile(regex);
}
public String getLibName() {
return libName;
}
public void setLibName(String libName) {
this.libName = libName;
}
}
| 2,328 | 0.716924 | 0.716065 | 88 | 25.454546 | 21.48885 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.715909 | false | false |
9
|
db5c26db2c9390ee1b9bfac731907f6a385665e8
| 36,180,804,507,137 |
a6af49d35d33a3dfb32dbbcad2176bb52b479eec
|
/app/src/main/java/jp/hanatoya/ipcam/utils/MyFileUtils.java
|
aacfb49f3ec38b362e1c02fd82d964925a72332b
|
[] |
no_license
|
inmyth/hanatoya-ipstream
|
https://github.com/inmyth/hanatoya-ipstream
|
8408788eecdd4343f69ec52b128bb14791db2fbc
|
194cca198059984f8bf87216f946af9fc2615b90
|
refs/heads/master
| 2021-01-12T04:45:32.649000 | 2017-10-09T05:42:44 | 2017-10-09T05:42:44 | 77,789,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package jp.hanatoya.ipcam.utils;
import android.os.Environment;
import android.util.Log;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import org.greenrobot.greendao.query.Query;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jp.hanatoya.ipcam.repo.Cam;
import jp.hanatoya.ipcam.repo.CamDao;
import jp.hanatoya.ipcam.repo.Switch;
import jp.hanatoya.ipcam.repo.SwitchDao;
public class MyFileUtils {
private static final String DIRNAME = "ipcam";
private static final String FILENAME = "data.json";
/* Checks if external storage is available for read and write */
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static void saveToSdCard(String json) {
// Get the directory for the user's public pictures directory.
FileWriter writer;
File dir = new File(Environment.getExternalStorageDirectory(), DIRNAME);
if (!dir.mkdirs()) {
Log.e("File System", "Directory not created");
}
try {
if (!dir.isDirectory()) {
throw new IOException("Unable to create directory. Maybe the SD card is mounted?");
}
File outputFile = new File(dir, FILENAME);
writer = new FileWriter(outputFile);
writer.write(json);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isSettingsFileExist(){
File dir = new File(Environment.getExternalStorageDirectory(), DIRNAME);
File file = new File(dir, FILENAME);
return file.exists();
}
public static boolean importDb(CamDao camDao, SwitchDao switchDao){
File dir = new File(Environment.getExternalStorageDirectory(), DIRNAME);
File file = new File(dir, FILENAME);
try {
FileInputStream is = new FileInputStream(file);
int size = 0;
size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String mResponse = new String(buffer);
ArrayList<Cam> cams = GsonUtils.toBean(mResponse, new TypeToken<ArrayList<Cam>>(){}.getType());
if (cams == null){
return false;
}
for (Cam c : cams){
camDao.insertOrReplace(c);
for (Switch s : c.getSwitches()){
switchDao.insertOrReplace(s);
}
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (JsonParseException e){
return false;
}
}
public static void dumpDb(CamDao camDao, SwitchDao switchDao){
List<Cam> cams = camDao.loadAll();
if (cams != null){
for (Cam c : cams){
Query query = switchDao.queryBuilder().where(SwitchDao.Properties.CamId.eq(c.getId())).orderAsc(SwitchDao.Properties.Id).build();
c.setSwitches(query.list());
}
String json = GsonUtils.toJson(cams);
saveToSdCard(json);
}
}
}
|
UTF-8
|
Java
| 3,815 |
java
|
MyFileUtils.java
|
Java
|
[] | null |
[] |
package jp.hanatoya.ipcam.utils;
import android.os.Environment;
import android.util.Log;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import org.greenrobot.greendao.query.Query;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jp.hanatoya.ipcam.repo.Cam;
import jp.hanatoya.ipcam.repo.CamDao;
import jp.hanatoya.ipcam.repo.Switch;
import jp.hanatoya.ipcam.repo.SwitchDao;
public class MyFileUtils {
private static final String DIRNAME = "ipcam";
private static final String FILENAME = "data.json";
/* Checks if external storage is available for read and write */
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static void saveToSdCard(String json) {
// Get the directory for the user's public pictures directory.
FileWriter writer;
File dir = new File(Environment.getExternalStorageDirectory(), DIRNAME);
if (!dir.mkdirs()) {
Log.e("File System", "Directory not created");
}
try {
if (!dir.isDirectory()) {
throw new IOException("Unable to create directory. Maybe the SD card is mounted?");
}
File outputFile = new File(dir, FILENAME);
writer = new FileWriter(outputFile);
writer.write(json);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isSettingsFileExist(){
File dir = new File(Environment.getExternalStorageDirectory(), DIRNAME);
File file = new File(dir, FILENAME);
return file.exists();
}
public static boolean importDb(CamDao camDao, SwitchDao switchDao){
File dir = new File(Environment.getExternalStorageDirectory(), DIRNAME);
File file = new File(dir, FILENAME);
try {
FileInputStream is = new FileInputStream(file);
int size = 0;
size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String mResponse = new String(buffer);
ArrayList<Cam> cams = GsonUtils.toBean(mResponse, new TypeToken<ArrayList<Cam>>(){}.getType());
if (cams == null){
return false;
}
for (Cam c : cams){
camDao.insertOrReplace(c);
for (Switch s : c.getSwitches()){
switchDao.insertOrReplace(s);
}
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (JsonParseException e){
return false;
}
}
public static void dumpDb(CamDao camDao, SwitchDao switchDao){
List<Cam> cams = camDao.loadAll();
if (cams != null){
for (Cam c : cams){
Query query = switchDao.queryBuilder().where(SwitchDao.Properties.CamId.eq(c.getId())).orderAsc(SwitchDao.Properties.Id).build();
c.setSwitches(query.list());
}
String json = GsonUtils.toJson(cams);
saveToSdCard(json);
}
}
}
| 3,815 | 0.609699 | 0.609436 | 123 | 30.01626 | 25.563244 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.577236 | false | false |
9
|
9edea02c090ba3611b101d71e86dfa29960349f2
| 19,997,367,784,227 |
25567d29f18f6fde34c9ed3308e2642eb1083043
|
/src/main/java/Service/UpdateAllCards.java
|
98988ee3686b617ea530efd4eb1cc1959a7de6a5
|
[] |
no_license
|
mihairuncan/Lab5-CinemaJavaFX_OOP
|
https://github.com/mihairuncan/Lab5-CinemaJavaFX_OOP
|
761a38dab5156c95139bb4ef375258dd8f085e6b
|
ffaa78f7a0b3e8e3ce3d6a4940bce0bc4ebd29c5
|
refs/heads/master
| 2020-05-04T01:26:40.260000 | 2019-04-19T18:48:04 | 2019-04-19T18:48:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Service;
import Domain.Entity;
import Repository.IRepository;
import java.util.List;
public class UpdateAllCards<T extends Entity> extends UndoRedoOperation {
private List<T> updatedList;
private List<T> actualList;
UpdateAllCards(IRepository<T> repository, List<T> updatedList, List<T> actualList) {
super(repository);
this.updatedList = updatedList;
this.actualList = actualList;
}
@Override
public void doUndo() {
for (T updatedEntity : actualList) {
repository.update(updatedEntity);
}
}
@Override
public void doRedo() {
for (T updatedEntity : updatedList) {
repository.update(updatedEntity);
}
}
}
|
UTF-8
|
Java
| 739 |
java
|
UpdateAllCards.java
|
Java
|
[] | null |
[] |
package Service;
import Domain.Entity;
import Repository.IRepository;
import java.util.List;
public class UpdateAllCards<T extends Entity> extends UndoRedoOperation {
private List<T> updatedList;
private List<T> actualList;
UpdateAllCards(IRepository<T> repository, List<T> updatedList, List<T> actualList) {
super(repository);
this.updatedList = updatedList;
this.actualList = actualList;
}
@Override
public void doUndo() {
for (T updatedEntity : actualList) {
repository.update(updatedEntity);
}
}
@Override
public void doRedo() {
for (T updatedEntity : updatedList) {
repository.update(updatedEntity);
}
}
}
| 739 | 0.64682 | 0.64682 | 31 | 22.774193 | 21.676075 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false |
9
|
6cfb3986064b373c5498f7a6d4a211ae95b8f97f
| 19,997,367,783,325 |
f7f88f93ff2ac13f9ef6201cf19d9b37bb5292b0
|
/Abstract Factory/src/com/cognizant/abstractfactory/Impl/AudiHeadlight.java
|
bb0160461eaf1dfab556f02564dc64dcaa5c4425
|
[] |
no_license
|
Pushpendu9626/projects
|
https://github.com/Pushpendu9626/projects
|
d669fca0fee618fd9193aa49fb4e0bf19a763ccf
|
79e004d3c4bd16deddc21025c56a1f2b06334359
|
refs/heads/master
| 2021-04-08T04:02:14.107000 | 2020-12-08T05:16:32 | 2020-12-08T05:16:32 | 248,738,325 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cognizant.abstractfactory.Impl;
import com.cognizant.abstractfactory.model.Headlight;
public class AudiHeadlight extends Headlight {
public void classification() {
System.out.println("This is the headlight of Audi");
}
}
|
UTF-8
|
Java
| 240 |
java
|
AudiHeadlight.java
|
Java
|
[] | null |
[] |
package com.cognizant.abstractfactory.Impl;
import com.cognizant.abstractfactory.model.Headlight;
public class AudiHeadlight extends Headlight {
public void classification() {
System.out.println("This is the headlight of Audi");
}
}
| 240 | 0.7875 | 0.7875 | 10 | 23 | 23.164629 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false |
9
|
1c83cb7b771c03f4deac6629f9e0fac4b9f57e47
| 35,562,329,227,519 |
87addaf0013fd965bb9de393fc5309b309219077
|
/playgrounds/ivtExt/src/main/java/playground/ivt/maxess/package-info.java
|
992c0385aa7b110ef23faf85f678c59f7e9d8f6c
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
harisbal/matsim
|
https://github.com/harisbal/matsim
|
8a5f45fee07f7bdff98a9cf89259ba8ed9bb7404
|
39632b3e7f6e06b29c4cf8bf9d780dce36e4f45c
|
refs/heads/master
| 2021-01-25T04:14:25.853000 | 2017-06-04T12:37:35 | 2017-06-04T12:37:35 | 93,409,900 | 1 | 1 | null | true | 2017-06-05T14:00:58 | 2017-06-05T14:00:58 | 2017-05-09T19:17:15 | 2017-06-04T14:04:50 | 866,570 | 0 | 0 | 0 | null | null | null |
/**
* This package contains code related to accessibility computations for the MAXess project.
* <br>
* It contains code for two purposes:
* <ul>
* <li>Convert travel diary data (in the form of MATSim plans) to a dataset for estimating choice models externally
* (BIOGEME or similar) </li>
* <li>Compute accessibility as the expected utility from a nested logit model, for each person in a population
* (synthetic population or similar) </li>
* </ul>
* @author thibautd
*/
package playground.ivt.maxess;
|
UTF-8
|
Java
| 520 |
java
|
package-info.java
|
Java
|
[
{
"context": "c population or similar)\t</li>\n * </ul>\n * @author thibautd\n */\npackage playground.ivt.maxess;",
"end": 485,
"score": 0.999064028263092,
"start": 477,
"tag": "USERNAME",
"value": "thibautd"
}
] | null |
[] |
/**
* This package contains code related to accessibility computations for the MAXess project.
* <br>
* It contains code for two purposes:
* <ul>
* <li>Convert travel diary data (in the form of MATSim plans) to a dataset for estimating choice models externally
* (BIOGEME or similar) </li>
* <li>Compute accessibility as the expected utility from a nested logit model, for each person in a population
* (synthetic population or similar) </li>
* </ul>
* @author thibautd
*/
package playground.ivt.maxess;
| 520 | 0.726923 | 0.726923 | 13 | 39.076923 | 39.357262 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.076923 | false | false |
9
|
2a05344c70deb71d8d3811fbb0905264915d6af8
| 8,598,524,565,203 |
64c9f7d8a5c7769f7be550d0323c706e348323db
|
/spring-aop/src/main/java/com/udemy/spring/aop/springaop/business/Business1.java
|
6581125df7b0774c549f7d16382edf125c98b5f2
|
[] |
no_license
|
leninkumar31/ObjectOrientedDesign
|
https://github.com/leninkumar31/ObjectOrientedDesign
|
50ad0a28e044bbb3f091e9796a4f66beb4a71c7e
|
f571f5df9b307911ccbbe3e1391e4648bfdadd31
|
refs/heads/main
| 2023-07-18T05:44:13.106000 | 2021-08-26T12:45:35 | 2021-08-26T12:45:35 | 346,699,196 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.udemy.spring.aop.springaop.business;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.udemy.spring.aop.springaop.dao.Dao1;
@Service
public class Business1 {
@Autowired
private Dao1 dao1;
public String calcSomething() {
return dao1.getSomething();
}
}
|
UTF-8
|
Java
| 348 |
java
|
Business1.java
|
Java
|
[] | null |
[] |
package com.udemy.spring.aop.springaop.business;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.udemy.spring.aop.springaop.dao.Dao1;
@Service
public class Business1 {
@Autowired
private Dao1 dao1;
public String calcSomething() {
return dao1.getSomething();
}
}
| 348 | 0.787356 | 0.772988 | 17 | 19.470589 | 20.324188 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.823529 | false | false |
9
|
584f3c91cd695a8ece601dcd3d60c463e11821ca
| 27,556,510,203,999 |
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
|
/com.tencent.mm/classes.jar/com/tencent/mm/plugin/finder/webview/b.java
|
50086f06f0104e601c3917f74efcd682ce1b452f
|
[] |
no_license
|
tsuzcx/qq_apk
|
https://github.com/tsuzcx/qq_apk
|
0d5e792c3c7351ab781957bac465c55c505caf61
|
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
|
refs/heads/main
| 2022-07-02T10:32:11.651000 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | false | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | 2022-01-31T06:56:43 | 2022-01-31T09:46:26 | 167,304 | 0 | 1 | 1 |
Java
| false | false |
package com.tencent.mm.plugin.finder.webview;
import kotlin.Metadata;
@Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/finder/webview/BoxDialogBackgroundTouchListener;", "", "onBackgroundTouchEvent", "", "ev", "Landroid/view/MotionEvent;", "dialogOffsetY", "", "plugin-finder_release"}, k=1, mv={1, 5, 1}, xi=48)
public abstract interface b
{
public abstract boolean bSD();
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes10.jar
* Qualified Name: com.tencent.mm.plugin.finder.webview.b
* JD-Core Version: 0.7.0.1
*/
|
UTF-8
|
Java
| 576 |
java
|
b.java
|
Java
|
[] | null |
[] |
package com.tencent.mm.plugin.finder.webview;
import kotlin.Metadata;
@Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/finder/webview/BoxDialogBackgroundTouchListener;", "", "onBackgroundTouchEvent", "", "ev", "Landroid/view/MotionEvent;", "dialogOffsetY", "", "plugin-finder_release"}, k=1, mv={1, 5, 1}, xi=48)
public abstract interface b
{
public abstract boolean bSD();
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes10.jar
* Qualified Name: com.tencent.mm.plugin.finder.webview.b
* JD-Core Version: 0.7.0.1
*/
| 576 | 0.675347 | 0.651042 | 19 | 28.631578 | 55.02364 | 240 | false | false | 0 | 0 | 0 | 0 | 70 | 0.121528 | 1 | false | false |
9
|
952689045df07b3c9c9d4a5685be3ac83f819f4e
| 5,909,875,049,424 |
9ddcab8912917e8bfafad147825d8ea040018dfa
|
/app/src/main/java/com/lianren/android/improve/user/presenter/ContactListContract.java
|
f61e84a1662b72633394f0ba10b5c32a17c8c030
|
[] |
no_license
|
lmDai/lianren
|
https://github.com/lmDai/lianren
|
ac8ed7f1c113ee3130c7c218f0876beed3dfbd2a
|
3b07bf09ed3e64a9de587676b59b68596f41d042
|
refs/heads/master
| 2021-04-19T18:01:27.876000 | 2020-03-30T03:39:20 | 2020-03-30T03:39:20 | 249,623,979 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lianren.android.improve.user.presenter;
import com.lianren.android.improve.base.BasePresenter;
import com.lianren.android.improve.base.BaseView;
import com.lianren.android.improve.bean.ContactUserBean;
import com.lianren.android.improve.bean.PairListBean;
import java.util.List;
/**
* @package: com.lianren.android.improve.user.presenter
* @user:xhkj
* @date:2019/12/20
* @description:联系人
**/
public interface ContactListContract {
interface EmptyView {
void hideEmptyLayout();
void showErrorLayout(int errorType);
}
interface View extends BaseView<Presenter> {
void showContactUser(List<ContactUserBean> mList);
void showDeleteSuccess(ContactUserBean tags, int position);
void showDeleteFailure(int strId);
void showDeleteFailure(String strId);
}
interface Presenter extends BasePresenter {
void getContactUser(int page);
void dealBlackAdd(ContactUserBean tags, int position);
void dealDelete(ContactUserBean tags, int position);
}
}
|
UTF-8
|
Java
| 1,064 |
java
|
ContactListContract.java
|
Java
|
[
{
"context": "m.lianren.android.improve.user.presenter\n * @user:xhkj\n * @date:2019/12/20\n * @description:联系人\n **/\npubl",
"end": 367,
"score": 0.9995644688606262,
"start": 363,
"tag": "USERNAME",
"value": "xhkj"
}
] | null |
[] |
package com.lianren.android.improve.user.presenter;
import com.lianren.android.improve.base.BasePresenter;
import com.lianren.android.improve.base.BaseView;
import com.lianren.android.improve.bean.ContactUserBean;
import com.lianren.android.improve.bean.PairListBean;
import java.util.List;
/**
* @package: com.lianren.android.improve.user.presenter
* @user:xhkj
* @date:2019/12/20
* @description:联系人
**/
public interface ContactListContract {
interface EmptyView {
void hideEmptyLayout();
void showErrorLayout(int errorType);
}
interface View extends BaseView<Presenter> {
void showContactUser(List<ContactUserBean> mList);
void showDeleteSuccess(ContactUserBean tags, int position);
void showDeleteFailure(int strId);
void showDeleteFailure(String strId);
}
interface Presenter extends BasePresenter {
void getContactUser(int page);
void dealBlackAdd(ContactUserBean tags, int position);
void dealDelete(ContactUserBean tags, int position);
}
}
| 1,064 | 0.728733 | 0.721172 | 39 | 26.128204 | 23.614618 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
9
|
7a25cc9b9f90ab47986ced9c657b9f4d5c020329
| 2,482,491,118,093 |
922dc6087755f442e5755ea5173a0baaf02b0f68
|
/src/main/java/pl/time4web/warehousemanager/service/StandService.java
|
a6db50118eba4dbc7b5f3ef3977c7de585788c4d
|
[] |
no_license
|
nemo83/WarehouseManager
|
https://github.com/nemo83/WarehouseManager
|
419dbf2245fafb98e7904de4a6b2035fbb55a511
|
f79cdca7012fb3feef5584d7fbdc5829356351ba
|
refs/heads/master
| 2016-08-08T13:39:22.928000 | 2012-06-14T18:02:04 | 2012-06-14T18:02:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.time4web.warehousemanager.service;
import java.util.List;
import pl.time4web.warehousemanager.domain.Stand;
public interface StandService {
Stand findByPlace(String stand);
List<Stand> findByPage(Integer page);
Integer getNumberOfPages();
Integer nextPage(Integer page);
Integer prevPage(Integer page);
Integer upBy(Integer page, Integer step);
Integer downBy(Integer page, Integer step);
Integer getPageForStand(String place);
}
|
UTF-8
|
Java
| 472 |
java
|
StandService.java
|
Java
|
[] | null |
[] |
package pl.time4web.warehousemanager.service;
import java.util.List;
import pl.time4web.warehousemanager.domain.Stand;
public interface StandService {
Stand findByPlace(String stand);
List<Stand> findByPage(Integer page);
Integer getNumberOfPages();
Integer nextPage(Integer page);
Integer prevPage(Integer page);
Integer upBy(Integer page, Integer step);
Integer downBy(Integer page, Integer step);
Integer getPageForStand(String place);
}
| 472 | 0.764831 | 0.760593 | 18 | 24.222221 | 18.100201 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false |
9
|
1a3babedadb1b613a57a477dbb7ac4670957b743
| 27,075,473,868,238 |
d473d6b951a877c1686101df6d6ab45a105b4423
|
/adapters/gwt/src/main/java/org/jreact/adapt/gwt/value/GetValueFromValueChangeEvent.java
|
1429b80fafde2e98f8ce54700bcc026a484cf6f2
|
[] |
no_license
|
chris-martin/JReact
|
https://github.com/chris-martin/JReact
|
371a0c326c5f05bd2771431d982a8d30d5359511
|
79b931c1e815c9e4cf3bb934ee6bc2f2b60f3a9c
|
refs/heads/master
| 2016-09-06T08:21:04.874000 | 2010-09-15T03:34:09 | 2010-09-15T03:34:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.jreact.adapt.gwt.value;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import fj.F;
class GetValueFromValueChangeEvent<A>
extends F<ValueChangeEvent<A>, A> {
@Override
public A f(
final ValueChangeEvent<A> event) {
return event.getValue();
}
}
|
UTF-8
|
Java
| 316 |
java
|
GetValueFromValueChangeEvent.java
|
Java
|
[] | null |
[] |
package org.jreact.adapt.gwt.value;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import fj.F;
class GetValueFromValueChangeEvent<A>
extends F<ValueChangeEvent<A>, A> {
@Override
public A f(
final ValueChangeEvent<A> event) {
return event.getValue();
}
}
| 316 | 0.670886 | 0.670886 | 17 | 17.588236 | 19.535967 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false |
9
|
e7b290a72d41cf411994d2775ccc3639f8cdb05a
| 17,660,905,586,180 |
d472ecefd53a69bd8158462b2d00a2d9eb9dfc90
|
/src/game/PlayerRecord.java
|
8a1933fa1fef745289e4f9f3cbad134d54d53cfa
|
[] |
no_license
|
mgalea/Games-Server
|
https://github.com/mgalea/Games-Server
|
d00fa752d8f8777da94d62ef2225c16fb5f9a6ba
|
75f53e9bf6a938a69505e1ac8b1f60822ed315e1
|
refs/heads/master
| 2021-01-19T04:05:28.408000 | 2016-06-10T14:45:34 | 2016-06-10T14:45:34 | 60,414,078 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package game;
public class PlayerRecord {
public byte[] getBytes() {
// TODO Auto-generated method stub
return null;
}
}
|
UTF-8
|
Java
| 130 |
java
|
PlayerRecord.java
|
Java
|
[] | null |
[] |
package game;
public class PlayerRecord {
public byte[] getBytes() {
// TODO Auto-generated method stub
return null;
}
}
| 130 | 0.684615 | 0.684615 | 10 | 12 | 12.976903 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false |
9
|
28e49ea471e0ef6f4fa06f80400e343fb6aacfeb
| 8,048,768,734,768 |
23bb8280c83a93663301989dd3f5a558dae5ef06
|
/src/main/java/org/elasticsearch/index/cache/CacheStats.java
|
29a3dded962f536cb44750c227adca38d4dc4bb7
|
[
"Apache-2.0"
] |
permissive
|
drakeg/elasticsearch
|
https://github.com/drakeg/elasticsearch
|
803226bc4f41bbe6cfb750528f492fdef512a323
|
595e0e254e34ac4358bed8eb814fb5240caaf9de
|
refs/heads/master
| 2019-08-22T06:05:26.212000 | 2013-02-23T13:23:36 | 2013-02-23T13:23:36 | 8,387,255 | 1 | 1 |
Apache-2.0
| true | 2019-12-05T01:07:50 | 2013-02-24T06:15:17 | 2019-12-05T01:06:42 | 2019-12-05T01:07:49 | 22,442 | 1 | 1 | 2 |
Java
| false | false |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.cache;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import java.io.IOException;
/**
*
*/
public class CacheStats implements Streamable, ToXContent {
long filterEvictions;
long filterCount;
long filterSize;
long idCacheSize;
public CacheStats() {
}
public CacheStats(long filterEvictions, long filterSize, long filterCount, long idCacheSize) {
this.filterEvictions = filterEvictions;
this.filterSize = filterSize;
this.filterCount = filterCount;
this.idCacheSize = idCacheSize;
}
public void add(CacheStats stats) {
this.filterEvictions += stats.filterEvictions;
this.filterSize += stats.filterSize;
this.filterCount += stats.filterCount;
this.idCacheSize += stats.idCacheSize;
}
public long getFilterEvictions() {
return this.filterEvictions;
}
public long getFilterMemEvictions() {
return this.filterEvictions;
}
public long getFilterCount() {
return this.filterCount;
}
public long getFilterSizeInBytes() {
return this.filterSize;
}
public ByteSizeValue getFilterSize() {
return new ByteSizeValue(filterSize);
}
public long getIdCacheSizeInBytes() {
return idCacheSize;
}
public ByteSizeValue getIdCacheSize() {
return new ByteSizeValue(idCacheSize);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.CACHE);
builder.field(Fields.FILTER_COUNT, filterCount);
builder.field(Fields.FILTER_EVICTIONS, filterEvictions);
builder.field(Fields.FILTER_SIZE, getFilterSize().toString());
builder.field(Fields.FILTER_SIZE_IN_BYTES, filterSize);
builder.field(Fields.ID_CACHE_SIZE, getIdCacheSize().toString());
builder.field(Fields.ID_CACHE_SIZE_IN_BYTES, idCacheSize);
builder.endObject();
return builder;
}
static final class Fields {
static final XContentBuilderString CACHE = new XContentBuilderString("cache");
static final XContentBuilderString FILTER_EVICTIONS = new XContentBuilderString("filter_evictions");
static final XContentBuilderString FILTER_COUNT = new XContentBuilderString("filter_count");
static final XContentBuilderString FILTER_SIZE = new XContentBuilderString("filter_size");
static final XContentBuilderString FILTER_SIZE_IN_BYTES = new XContentBuilderString("filter_size_in_bytes");
static final XContentBuilderString ID_CACHE_SIZE = new XContentBuilderString("id_cache_size");
static final XContentBuilderString ID_CACHE_SIZE_IN_BYTES = new XContentBuilderString("id_cache_size_in_bytes");
}
public static CacheStats readCacheStats(StreamInput in) throws IOException {
CacheStats stats = new CacheStats();
stats.readFrom(in);
return stats;
}
@Override
public void readFrom(StreamInput in) throws IOException {
filterEvictions = in.readVLong();
filterSize = in.readVLong();
filterCount = in.readVLong();
idCacheSize = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(filterEvictions);
out.writeVLong(filterSize);
out.writeVLong(filterCount);
out.writeVLong(idCacheSize);
}
}
|
UTF-8
|
Java
| 4,620 |
java
|
CacheStats.java
|
Java
|
[
{
"context": "/*\n * Licensed to ElasticSearch and Shay Banon under one\n * or more contributor license agreemen",
"end": 46,
"score": 0.9998800158500671,
"start": 36,
"tag": "NAME",
"value": "Shay Banon"
}
] | null |
[] |
/*
* Licensed to ElasticSearch and <NAME> under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.cache;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentBuilderString;
import java.io.IOException;
/**
*
*/
public class CacheStats implements Streamable, ToXContent {
long filterEvictions;
long filterCount;
long filterSize;
long idCacheSize;
public CacheStats() {
}
public CacheStats(long filterEvictions, long filterSize, long filterCount, long idCacheSize) {
this.filterEvictions = filterEvictions;
this.filterSize = filterSize;
this.filterCount = filterCount;
this.idCacheSize = idCacheSize;
}
public void add(CacheStats stats) {
this.filterEvictions += stats.filterEvictions;
this.filterSize += stats.filterSize;
this.filterCount += stats.filterCount;
this.idCacheSize += stats.idCacheSize;
}
public long getFilterEvictions() {
return this.filterEvictions;
}
public long getFilterMemEvictions() {
return this.filterEvictions;
}
public long getFilterCount() {
return this.filterCount;
}
public long getFilterSizeInBytes() {
return this.filterSize;
}
public ByteSizeValue getFilterSize() {
return new ByteSizeValue(filterSize);
}
public long getIdCacheSizeInBytes() {
return idCacheSize;
}
public ByteSizeValue getIdCacheSize() {
return new ByteSizeValue(idCacheSize);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.CACHE);
builder.field(Fields.FILTER_COUNT, filterCount);
builder.field(Fields.FILTER_EVICTIONS, filterEvictions);
builder.field(Fields.FILTER_SIZE, getFilterSize().toString());
builder.field(Fields.FILTER_SIZE_IN_BYTES, filterSize);
builder.field(Fields.ID_CACHE_SIZE, getIdCacheSize().toString());
builder.field(Fields.ID_CACHE_SIZE_IN_BYTES, idCacheSize);
builder.endObject();
return builder;
}
static final class Fields {
static final XContentBuilderString CACHE = new XContentBuilderString("cache");
static final XContentBuilderString FILTER_EVICTIONS = new XContentBuilderString("filter_evictions");
static final XContentBuilderString FILTER_COUNT = new XContentBuilderString("filter_count");
static final XContentBuilderString FILTER_SIZE = new XContentBuilderString("filter_size");
static final XContentBuilderString FILTER_SIZE_IN_BYTES = new XContentBuilderString("filter_size_in_bytes");
static final XContentBuilderString ID_CACHE_SIZE = new XContentBuilderString("id_cache_size");
static final XContentBuilderString ID_CACHE_SIZE_IN_BYTES = new XContentBuilderString("id_cache_size_in_bytes");
}
public static CacheStats readCacheStats(StreamInput in) throws IOException {
CacheStats stats = new CacheStats();
stats.readFrom(in);
return stats;
}
@Override
public void readFrom(StreamInput in) throws IOException {
filterEvictions = in.readVLong();
filterSize = in.readVLong();
filterCount = in.readVLong();
idCacheSize = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(filterEvictions);
out.writeVLong(filterSize);
out.writeVLong(filterCount);
out.writeVLong(idCacheSize);
}
}
| 4,616 | 0.714935 | 0.714069 | 131 | 34.274811 | 29.414919 | 120 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541985 | false | false |
9
|
bbd7c815e43f55ed7a5a9289c18880c89f7b891b
| 22,874,995,865,095 |
c0b08d68bf1d451420283ef051a7434526bffd50
|
/ProjetoLocadoraJava/src/br/com/fean/poo2/locadora/modelo/reserva/Reserva.java
|
9aa1f169b0a0b083e30f35c7069b831a7d393028
|
[] |
no_license
|
ProjetoPoo/ProjetoLocadora
|
https://github.com/ProjetoPoo/ProjetoLocadora
|
a45a6e098d2b25d9f0bc6c35b5b5507d01ce6952
|
ba849bf723a9ab022189c258fbf7e6547a7bf9be
|
refs/heads/master
| 2016-09-15T20:43:24.297000 | 2014-07-07T21:31:41 | 2014-07-07T21:31:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.fean.poo2.locadora.modelo.reserva;
// Generated 19/06/2014 18:08:01 by Hibernate Tools 3.6.0
import br.com.fean.poo2.locadora.modelo.socio.Socio;
import br.com.fean.poo2.locadora.modelo.midia.Midia;
import br.com.fean.poo2.locadora.modelo.dependente.Dependente;
import java.util.Date;
/**
* Reserva generated by hbm2java
*/
public class Reserva implements java.io.Serializable {
private Integer id;
private Dependente dependentes;
private Midia midias;
private Socio socios;
private Date data2;
private Date hora;
public Reserva() {
}
public Reserva(Dependente dependentes, Midia midias, Socio socios) {
this.dependentes = dependentes;
this.midias = midias;
this.socios = socios;
}
public Reserva(Dependente dependentes, Midia midias, Socio socios, Date data2, Date hora) {
this.dependentes = dependentes;
this.midias = midias;
this.socios = socios;
this.data2 = data2;
this.hora = hora;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Dependente getDependentes() {
return this.dependentes;
}
public void setDependentes(Dependente dependentes) {
this.dependentes = dependentes;
}
public Midia getMidias() {
return this.midias;
}
public void setMidias(Midia midias) {
this.midias = midias;
}
public Socio getSocios() {
return this.socios;
}
public void setSocios(Socio socios) {
this.socios = socios;
}
public Date getData2() {
return this.data2;
}
public void setData2(Date data2) {
this.data2 = data2;
}
public Date getHora() {
return this.hora;
}
public void setHora(Date hora) {
this.hora = hora;
}
}
|
UTF-8
|
Java
| 1,930 |
java
|
Reserva.java
|
Java
|
[] | null |
[] |
package br.com.fean.poo2.locadora.modelo.reserva;
// Generated 19/06/2014 18:08:01 by Hibernate Tools 3.6.0
import br.com.fean.poo2.locadora.modelo.socio.Socio;
import br.com.fean.poo2.locadora.modelo.midia.Midia;
import br.com.fean.poo2.locadora.modelo.dependente.Dependente;
import java.util.Date;
/**
* Reserva generated by hbm2java
*/
public class Reserva implements java.io.Serializable {
private Integer id;
private Dependente dependentes;
private Midia midias;
private Socio socios;
private Date data2;
private Date hora;
public Reserva() {
}
public Reserva(Dependente dependentes, Midia midias, Socio socios) {
this.dependentes = dependentes;
this.midias = midias;
this.socios = socios;
}
public Reserva(Dependente dependentes, Midia midias, Socio socios, Date data2, Date hora) {
this.dependentes = dependentes;
this.midias = midias;
this.socios = socios;
this.data2 = data2;
this.hora = hora;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Dependente getDependentes() {
return this.dependentes;
}
public void setDependentes(Dependente dependentes) {
this.dependentes = dependentes;
}
public Midia getMidias() {
return this.midias;
}
public void setMidias(Midia midias) {
this.midias = midias;
}
public Socio getSocios() {
return this.socios;
}
public void setSocios(Socio socios) {
this.socios = socios;
}
public Date getData2() {
return this.data2;
}
public void setData2(Date data2) {
this.data2 = data2;
}
public Date getHora() {
return this.hora;
}
public void setHora(Date hora) {
this.hora = hora;
}
}
| 1,930 | 0.620207 | 0.603627 | 88 | 20.90909 | 19.488129 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.431818 | false | false |
9
|
f327b1826f6f8a4d11ead0877b1a8f43773426fa
| 17,884,243,824,415 |
3771e7bcc7a24d1df9988728f5ca4d9bb53aec9b
|
/src/com/company/TusharBirthdayParty.java
|
84498d062d91df37a0bc2fbdceb1e50ecda1abb4
|
[] |
no_license
|
sidiiitg123/DP
|
https://github.com/sidiiitg123/DP
|
cd3ee3c4c47bca532cd1a0da1f54605c9774dc48
|
4c089b2a5f9abd215e7c2712390e876b3360f36c
|
refs/heads/master
| 2022-09-04T20:28:52.662000 | 2020-05-19T07:19:10 | 2020-05-19T07:19:10 | 263,763,925 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TusharBirthdayParty {
public int solve(final List<Integer> A, final List<Integer> B, final List<Integer> C) {
int totSum = 0;
int a = 0;
for (Integer b : A) {
if (b > a) {
a = b;
}
}
int[] v = new int[a + 1];
for (int i = 1; i <= a; i++) {
int min = Integer.MAX_VALUE;
for (int j = 0; j < B.size(); j++) {
if (B.get(j) > i) {
continue;
}
int value = v[i - B.get(j)] + C.get(j);
if (value < min) {
min = value;
}
}
v[i] = min;
}
for (Integer b : A) {
totSum += v[b];
}
return totSum;
}
}
|
UTF-8
|
Java
| 914 |
java
|
TusharBirthdayParty.java
|
Java
|
[] | null |
[] |
package com.company;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TusharBirthdayParty {
public int solve(final List<Integer> A, final List<Integer> B, final List<Integer> C) {
int totSum = 0;
int a = 0;
for (Integer b : A) {
if (b > a) {
a = b;
}
}
int[] v = new int[a + 1];
for (int i = 1; i <= a; i++) {
int min = Integer.MAX_VALUE;
for (int j = 0; j < B.size(); j++) {
if (B.get(j) > i) {
continue;
}
int value = v[i - B.get(j)] + C.get(j);
if (value < min) {
min = value;
}
}
v[i] = min;
}
for (Integer b : A) {
totSum += v[b];
}
return totSum;
}
}
| 914 | 0.391685 | 0.386214 | 40 | 21.85 | 17.938158 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false |
9
|
831df074e8aa6d12b4a3a12172172a10ee6b77d1
| 14,370,960,604,092 |
32ce9ae76a357dc28ec4c4e36c3bf306dfd21b5d
|
/src/Servicios/SosColision.java
|
aef6780ec6a2e78a806395b17d80bc4f8bf1dfcd
|
[] |
no_license
|
set-toluca/Integral-SET-PROVISION-
|
https://github.com/set-toluca/Integral-SET-PROVISION-
|
1ea2598e1837f70fe72eb24d49ebef170a9d42e5
|
a5d3638b749833956bef801b9bbc1dad59fc8571
|
refs/heads/master
| 2020-04-15T12:43:22.115000 | 2019-12-17T00:05:48 | 2019-12-17T00:05:48 | 64,501,263 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* 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 Servicios;
import Hibernate.Util.HibernateUtil;
import Hibernate.entidades.Acceso;
import Hibernate.entidades.Configuracion;
import Hibernate.entidades.Cuenta;
import Hibernate.entidades.Foto;
import Hibernate.entidades.Notificacion;
import Hibernate.entidades.Orden;
import Hibernate.entidades.Usuario;
import Integral.ExtensionFileFilter;
import Integral.Ftp;
import Integral.Herramientas;
import Integral.PeticionPost;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.poi.util.IOUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* @author Sistemas
*/
public class SosColision extends javax.swing.JPanel {
String estado="";
String sessionPrograma="";
Usuario usr;
String ord="";
Herramientas h;
Orden orden_act;
JFileChooser selector;
JFileChooser selectorFoto;
String ruta;
String n_carpeta="";
DefaultListModel modeloLista= new DefaultListModel();
File foto=null;
Hilo miHilo=null;
/**
* Creates new form SmLogistics
*/
public SosColision(String ord, Usuario usr, String estado, String sessionPrograma, String carpeta) {
initComponents();
this.ord=ord;
this.usr=usr;
this.estado=estado;
this.sessionPrograma=sessionPrograma;
ruta=carpeta;
buscaDatos();
selector=new JFileChooser();
selector.setFileFilter(new ExtensionFileFilter("Documentos(PDF y DOCX)", new String[] { "PDF", "DOCX" }));
selector.setAcceptAllFileFilterUsed(false);
selector.setMultiSelectionEnabled(true);
selectorFoto=new JFileChooser();
selectorFoto.setFileFilter(new ExtensionFileFilter("Documentos(JPG y JPEG)", new String[] { "JPG", "JPEG" }));
selectorFoto.setAcceptAllFileFilterUsed(false);
selectorFoto.setMultiSelectionEnabled(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
ListaSOS = new javax.swing.JDialog();
jPanel7 = new javax.swing.JPanel();
b_autorizar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
c_estatus1 = new javax.swing.JComboBox();
id_unidad = new javax.swing.JLabel();
id_sucursal = new javax.swing.JLabel();
l_carpeta = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
jPanel16 = new javax.swing.JPanel();
jPanel18 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
t_ingreso = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
t_promesa = new javax.swing.JTextField();
t_salida = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
c_estatus = new javax.swing.JComboBox();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel3 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
t_descripcion = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
t_economico = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
t_autorizo = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
t_reporte = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
t_deducible = new javax.swing.JFormattedTextField();
t_demerito = new javax.swing.JFormattedTextField();
b_ac = new javax.swing.JButton();
jPanel8 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
b_inventario_carga = new javax.swing.JButton();
b_inventario = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
b_pago_carga = new javax.swing.JButton();
b_pago = new javax.swing.JButton();
jPanel6 = new javax.swing.JPanel();
b_cotizacion_carga = new javax.swing.JButton();
b_cotizacion = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
b_desgaste_carga = new javax.swing.JButton();
b_desgaste = new javax.swing.JButton();
jPanel9 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
lista_fotos = new javax.swing.JList(modeloLista);
b_menos = new javax.swing.JButton();
b_mas = new javax.swing.JButton();
c_carpetas = new javax.swing.JComboBox();
b_foto = new javax.swing.JButton();
jLabel13 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
t_solicitud = new javax.swing.JTextField();
ListaSOS.setModalExclusionType(null);
ListaSOS.setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "Lista de Reparaciones Asignadas", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
b_autorizar.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
b_autorizar.setText("Enlazar");
b_autorizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_autorizarActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jLabel2.setText("Filtrar por Estatus:");
c_estatus1.setBackground(new java.awt.Color(204, 255, 255));
c_estatus1.setForeground(new java.awt.Color(51, 0, 255));
c_estatus1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PROGRAMADA", "PROCESO", "VALUACION", "EN REPARACION", "TERMINADA", "ENTREGADA", "CANCELADA", "PERDIDA TOTAL" }));
c_estatus1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c_estatus1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(c_estatus1, 0, 181, Short.MAX_VALUE)
.addGap(260, 260, 260)
.addComponent(b_autorizar)))
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(c_estatus1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b_autorizar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(18, Short.MAX_VALUE))
);
javax.swing.GroupLayout ListaSOSLayout = new javax.swing.GroupLayout(ListaSOS.getContentPane());
ListaSOS.getContentPane().setLayout(ListaSOSLayout);
ListaSOSLayout.setHorizontalGroup(
ListaSOSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
ListaSOSLayout.setVerticalGroup(
ListaSOSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
id_unidad.setText("jLabel13");
id_sucursal.setText("jLabel13");
l_carpeta.setText("jLabel13");
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "SOS Collision", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 12))); // NOI18N
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Servicios/icono.png"))); // NOI18N
jPanel16.setBackground(new java.awt.Color(255, 255, 255));
jPanel16.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "GENERAL", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
jPanel16.setLayout(new java.awt.BorderLayout());
jPanel18.setBackground(new java.awt.Color(255, 255, 255));
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel5.setText("Ingreso");
t_ingreso.setEditable(false);
t_ingreso.setBackground(new java.awt.Color(204, 255, 255));
t_ingreso.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_ingreso.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_ingreso.setEnabled(false);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Promesa");
t_promesa.setEditable(false);
t_promesa.setBackground(new java.awt.Color(204, 255, 255));
t_promesa.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_promesa.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_promesa.setEnabled(false);
t_salida.setEditable(false);
t_salida.setBackground(new java.awt.Color(204, 255, 255));
t_salida.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_salida.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_salida.setEnabled(false);
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setText("Salida");
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(t_ingreso, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(t_promesa, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel18Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(t_salida, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(t_ingreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(t_promesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(t_salida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel16.add(jPanel18, java.awt.BorderLayout.CENTER);
c_estatus.setBackground(new java.awt.Color(204, 255, 255));
c_estatus.setForeground(new java.awt.Color(51, 0, 255));
c_estatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PROGRAMADA", "PROCESO", "VALUACION", "EN REPARACION", "TERMINADO", "ENTREGADA", "CANCELADA", "PERDIDA TOTAL" }));
c_estatus.setEnabled(false);
c_estatus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c_estatusActionPerformed(evt);
}
});
jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jTabbedPane1StateChanged(evt);
}
});
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
t_descripcion.setEditable(false);
t_descripcion.setColumns(20);
t_descripcion.setRows(5);
jScrollPane2.setViewportView(t_descripcion);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel3.setText("Descripción:");
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel7.setText("Economico:");
t_economico.setEditable(false);
t_economico.setBackground(new java.awt.Color(204, 255, 255));
t_economico.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_economico.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_economico.setEnabled(false);
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel8.setText("Autorizo:");
t_autorizo.setEditable(false);
t_autorizo.setBackground(new java.awt.Color(204, 255, 255));
t_autorizo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_autorizo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_autorizo.setEnabled(false);
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel9.setText("N° Reporte:");
t_reporte.setEditable(false);
t_reporte.setBackground(new java.awt.Color(204, 255, 255));
t_reporte.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_reporte.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_reporte.setEnabled(false);
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("Deducible:");
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("Demerito:");
t_deducible.setBackground(new java.awt.Color(204, 255, 255));
t_deducible.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_deducible.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
t_deducible.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
t_deducible.setText("0.00");
t_deducible.setDisabledTextColor(new java.awt.Color(2, 38, 253));
t_deducible.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t_deducibleActionPerformed(evt);
}
});
t_demerito.setBackground(new java.awt.Color(204, 255, 255));
t_demerito.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_demerito.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
t_demerito.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
t_demerito.setText("0.00");
t_demerito.setDisabledTextColor(new java.awt.Color(2, 38, 253));
b_ac.setText("Guardar");
b_ac.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_acActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t_autorizo))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel7)
.addComponent(jLabel9)
.addComponent(t_reporte)
.addComponent(t_economico, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel10))
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(t_deducible, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(t_demerito, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
.addComponent(jLabel11)
.addComponent(b_ac, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(90, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jLabel10))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(t_economico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t_deducible, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(t_reporte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(t_demerito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_ac)
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(7, 7, 7)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(t_autorizo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jTabbedPane1.addTab("Reporte", jPanel3);
jPanel8.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "INVENTARIO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_inventario_carga.setBackground(new java.awt.Color(2, 135, 242));
b_inventario_carga.setForeground(new java.awt.Color(255, 255, 255));
b_inventario_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_inventario_carga.setToolTipText("Calendario");
b_inventario_carga.setEnabled(false);
b_inventario_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_inventario_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_inventario_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_inventario_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_inventario_cargaActionPerformed(evt);
}
});
b_inventario.setEnabled(false);
b_inventario.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_inventario.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_inventarioActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_inventario, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_inventario_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_inventario, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_inventario_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "INFO. PAGO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_pago_carga.setBackground(new java.awt.Color(2, 135, 242));
b_pago_carga.setForeground(new java.awt.Color(255, 255, 255));
b_pago_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_pago_carga.setToolTipText("Calendario");
b_pago_carga.setEnabled(false);
b_pago_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_pago_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_pago_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_pago_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_pago_cargaActionPerformed(evt);
}
});
b_pago.setEnabled(false);
b_pago.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_pago.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_pagoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_pago, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_pago_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_pago, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_pago_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "COTIZACIÓN", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_cotizacion_carga.setBackground(new java.awt.Color(2, 135, 242));
b_cotizacion_carga.setForeground(new java.awt.Color(255, 255, 255));
b_cotizacion_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_cotizacion_carga.setToolTipText("Calendario");
b_cotizacion_carga.setEnabled(false);
b_cotizacion_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_cotizacion_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_cotizacion_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_cotizacion_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_cotizacion_cargaActionPerformed(evt);
}
});
b_cotizacion.setEnabled(false);
b_cotizacion.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_cotizacion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_cotizacionActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(b_cotizacion, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(b_cotizacion_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_cotizacion, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_cotizacion_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "DESGASTE", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_desgaste_carga.setBackground(new java.awt.Color(2, 135, 242));
b_desgaste_carga.setForeground(new java.awt.Color(255, 255, 255));
b_desgaste_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_desgaste_carga.setToolTipText("Calendario");
b_desgaste_carga.setEnabled(false);
b_desgaste_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_desgaste_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_desgaste_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_desgaste_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_desgaste_cargaActionPerformed(evt);
}
});
b_desgaste.setEnabled(false);
b_desgaste.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_desgaste.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_desgasteActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(b_desgaste, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(b_desgaste_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_desgaste, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_desgaste_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Informes", jPanel8);
lista_fotos.setEnabled(false);
lista_fotos.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
lista_fotosValueChanged(evt);
}
});
jScrollPane3.setViewportView(lista_fotos);
b_menos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/menos.png"))); // NOI18N
b_menos.setEnabled(false);
b_menos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_menosActionPerformed(evt);
}
});
b_mas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/mas.png"))); // NOI18N
b_mas.setEnabled(false);
b_mas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_masActionPerformed(evt);
}
});
c_carpetas.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "INGRESO", "CAMBIOS", "PROCESO", "SALIDA" }));
c_carpetas.setEnabled(false);
c_carpetas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c_carpetasActionPerformed(evt);
}
});
b_foto.setBackground(new java.awt.Color(255, 255, 255));
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/login.jpg"))); // NOI18N
b_foto.setEnabled(false);
b_foto.setOpaque(false);
b_foto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_fotoActionPerformed(evt);
}
});
jLabel13.setText("Carpeta:");
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel9Layout.createSequentialGroup()
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(c_carpetas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b_menos, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_mas, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_foto, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(124, 124, 124))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(b_foto, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(b_menos, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b_mas, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(c_carpetas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(22, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Galeria", jPanel9);
jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel12.setText("Estatus:");
jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel14.setText("REPARACION:");
t_solicitud.setBackground(new java.awt.Color(204, 255, 255));
t_solicitud.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_solicitud.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_solicitud.setEnabled(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel16, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t_solicitud))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(c_estatus, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTabbedPane1)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(t_solicitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addComponent(jPanel16, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(c_estatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void b_inventario_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_inventario_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_inventario.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/inventario/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setInventario(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Inventario de Ingreso");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "INVENTARIO");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_desgaste);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_inventario_cargaActionPerformed
private void b_desgaste_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_desgaste_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_desgaste.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/desgaste/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setDesgaste(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Desgaste no atribuible al siniestro");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "DESGASTE");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_desgaste);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_desgaste_cargaActionPerformed
private void b_pago_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_pago_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_pago.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/pago/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setPago(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Pago");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "PAGO");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_pago);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_pago_cargaActionPerformed
private void b_cotizacion_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_cotizacion_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_cotizacion.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/cotizacion/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setEntrega(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Cotizacion");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "COTIZACION");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_cotizacion);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_cotizacion_cargaActionPerformed
private void b_inventarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_inventarioActionPerformed
// TODO add your handling code here:
if(b_inventario.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/inventario/"))
{
miFtp.AbrirArchivo(b_inventario.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_inventarioActionPerformed
private void b_desgasteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_desgasteActionPerformed
// TODO add your handling code here:
if(b_desgaste.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/desgaste/"))
{
miFtp.AbrirArchivo(b_desgaste.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_desgasteActionPerformed
private void b_pagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_pagoActionPerformed
// TODO add your handling code here:
if(b_pago.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/pago/"))
{
miFtp.AbrirArchivo(b_pago.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_pagoActionPerformed
private void b_cotizacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_cotizacionActionPerformed
// TODO add your handling code here:
if(b_cotizacion.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/cotizacion/"))
{
miFtp.AbrirArchivo(b_cotizacion.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_cotizacionActionPerformed
private void c_estatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c_estatusActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_c_estatusActionPerformed
private void b_autorizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_autorizarActionPerformed
/*if(t_user.getText().compareTo("")!=0)
{
if(t_contra.getPassword().toString().compareTo("")!=0)
{
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
session.beginTransaction().begin();
Usuario autoriza = (Usuario)session.createCriteria(Usuario.class).add(Restrictions.eq("idUsuario", t_user.getText())).add(Restrictions.eq("clave", t_contra.getText())).setMaxResults(1).uniqueResult();
if(autoriza!=null)
{
if(autoriza.getAutorizarSobrecosto()==true)
{
usrAut=autoriza;
ListaSOS.dispose();
}
else
JOptionPane.showMessageDialog(this, "¡El usuario no tiene permiso de autorizar!");
}
else
{
session.beginTransaction().rollback();
JOptionPane.showMessageDialog(this, "¡Datos Incorrectos!");
t_user.requestFocus();
}
}catch(Exception e)
{
session.beginTransaction().rollback();
JOptionPane.showMessageDialog(this, "¡Error al consultar los datos!");
e.printStackTrace();
}
finally
{
if(session.isOpen()==true)
session.close();
}
}
else
{
JOptionPane.showMessageDialog(this, "¡Ingrese la contraseña!");
t_contra.requestFocus();
}
}
else
{
JOptionPane.showMessageDialog(this, "¡Ingrese el usuario!");
t_user.requestFocus();
}*/
}//GEN-LAST:event_b_autorizarActionPerformed
private void c_estatus1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c_estatus1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_c_estatus1ActionPerformed
private void lista_fotosValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lista_fotosValueChanged
// TODO add your handling code here:
if(!lista_fotos.isSelectionEmpty())
{
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/gearsan.gif")));
miHilo=null;
miHilo = new Hilo("http://tbstoluca.ddns.net/sm-l/recursos/reparacion/"+l_carpeta.getText()+"/"+c_carpetas.getSelectedItem().toString()+"/", lista_fotos.getSelectedValue().toString(), b_foto.getWidth()-40, b_foto.getHeight()-40);
}
else
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/login.jpg")));
}//GEN-LAST:event_lista_fotosValueChanged
private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged
// TODO add your handling code here:
try{
String ventana=jTabbedPane1.getTitleAt(jTabbedPane1.getSelectedIndex());
if(ventana.compareTo("Galeria")==0)
{
leerDirectorio();
}
}catch(Exception e){
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/login.jpg")));
}
}//GEN-LAST:event_jTabbedPane1StateChanged
private void c_carpetasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c_carpetasActionPerformed
// TODO add your handling code here:
if(l_carpeta.getText().compareTo("")!=0)
{
//System.out.println("Evento");
leerDirectorio();
}
}//GEN-LAST:event_c_carpetasActionPerformed
private void b_fotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_fotoActionPerformed
// TODO add your handling code here:
if(foto!=null && foto.exists()){
try{
Desktop.getDesktop().open(foto);
}catch(Exception e){}
}
}//GEN-LAST:event_b_fotoActionPerformed
private void b_masActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_masActionPerformed
// TODO add your handling code here:
try
{
File destino=null;
int estado=selectorFoto.showOpenDialog(null);
File[] archivos = selectorFoto.getSelectedFiles();
if(estado==0)
{
for(int p=0; p<archivos.length; p++)
{
if(archivos[p].exists())
{
if(!modeloLista.contains(archivos[p].getName()))
{
Herramientas h = new Herramientas(this.usr, 0);
Ftp miFtp=new Ftp();
if(miFtp.conectar("tbstoluca.ddns.net", "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()))
{
boolean existe=true;
if(!miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()+"/"+c_carpetas.getSelectedItem().toString()+"/"))
{
if(miFtp.crearDirectorio("/"+c_carpetas.getSelectedItem().toString()))
{
if(!miFtp.cambiarDirectorio("/"+c_carpetas.getSelectedItem().toString()+"/"))
existe=false;
}
else
existe=false;
}
if(existe)
{
if(miFtp.subirArchivo(archivos[p].getPath(), archivos[p].getName()))
modeloLista.addElement(archivos[p].getName());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio RAIZ");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
}//GEN-LAST:event_b_masActionPerformed
private void b_menosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_menosActionPerformed
// TODO add your handling code here:
int[] totalEliminar = lista_fotos.getSelectedIndices();
if(totalEliminar.length>0){
int opt=JOptionPane.showConfirmDialog(this, "¡Las Fotos se eliminarán del Servidor!");
if (JOptionPane.YES_OPTION == opt)
{
Herramientas h = new Herramientas(this.usr, 0);
for(int x=0; x<totalEliminar.length; x++)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar("tbstoluca.ddns.net", "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()+"/"+c_carpetas.getSelectedItem().toString()+"/"))
{
if(miFtp.borrarArchivo(modeloLista.elementAt(totalEliminar[x]-x).toString()))
modeloLista.removeElementAt(totalEliminar[x]-x);
else{
x=totalEliminar.length;
JOptionPane.showMessageDialog(null, "Algunas fotos no fue posible eliminarlas intente mas tarde!");
}
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio RAIZ");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
miFtp.desconectar();
}
}
}
else
JOptionPane.showMessageDialog(null, "Seleccione las fotos a eliminar");
}//GEN-LAST:event_b_menosActionPerformed
private void b_acActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_acActionPerformed
// TODO add your handling code here:
h= new Herramientas(this.usr, 0);
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, Integer.parseInt(ord));
if(t_deducible.getText().compareTo("")!=0)
orden_act.setDeducible(((Number)t_deducible.getValue()).doubleValue());
else
orden_act.setDeducible(null);
if(t_demerito.getText().compareTo("")!=0)
orden_act.setDemerito(((Number)t_demerito.getValue()).doubleValue());
else
orden_act.setDemerito(null);
session.update(orden_act);
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_MONTOS");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("DEDUCIBLE", ""+((Number)t_deducible.getValue()).doubleValue());
service.add("DEMERITO", ""+((Number)t_demerito.getValue()).doubleValue());
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
JOptionPane.showMessageDialog(this, "LOS MONTOS FUERON ACTUALIZADOS Y SE NOTIFICO AL CLIENTE");
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "LOS MONTOS FUERON ACTUALIZADOS");
}
}
catch(Exception e)
{
session.beginTransaction().rollback();
e.printStackTrace();
JOptionPane.showMessageDialog(this, "NO SE PUDO REALIZAR LA ACTUALIZACION");
}
if(session!=null)
if(session.isOpen())
{
session.flush();
session.clear();
session.close();
}
}//GEN-LAST:event_b_acActionPerformed
private void t_deducibleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_t_deducibleActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_t_deducibleActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JDialog ListaSOS;
private javax.swing.JButton b_ac;
private javax.swing.JButton b_autorizar;
private javax.swing.JButton b_cotizacion;
private javax.swing.JButton b_cotizacion_carga;
private javax.swing.JButton b_desgaste;
private javax.swing.JButton b_desgaste_carga;
private javax.swing.JButton b_foto;
private javax.swing.JButton b_inventario;
private javax.swing.JButton b_inventario_carga;
private javax.swing.JButton b_mas;
private javax.swing.JButton b_menos;
private javax.swing.JButton b_pago;
private javax.swing.JButton b_pago_carga;
private javax.swing.JComboBox c_carpetas;
private javax.swing.JComboBox c_estatus;
private javax.swing.JComboBox c_estatus1;
private javax.swing.JLabel id_sucursal;
private javax.swing.JLabel id_unidad;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable jTable1;
private javax.swing.JLabel l_carpeta;
private javax.swing.JList lista_fotos;
private javax.swing.JTextField t_autorizo;
private javax.swing.JFormattedTextField t_deducible;
private javax.swing.JFormattedTextField t_demerito;
private javax.swing.JTextArea t_descripcion;
private javax.swing.JTextField t_economico;
private javax.swing.JTextField t_ingreso;
private javax.swing.JTextField t_promesa;
private javax.swing.JTextField t_reporte;
private javax.swing.JTextField t_salida;
private javax.swing.JTextField t_solicitud;
// End of variables declaration//GEN-END:variables
public void buscaDatos()
{
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File f;
usr = (Usuario)session.get(Usuario.class, usr.getIdUsuario());
if(usr.getConsultaSm() || usr.getEditaSm())
{
orden_act = (Orden)session.get(Orden.class, Integer.parseInt(ord));
if(orden_act.getIdSm()!=null){
t_solicitud.setText(orden_act.getIdSm());
if(usr.getEditaSm())
{
b_inventario_carga.setEnabled(true);
b_desgaste_carga.setEnabled(true);
b_pago_carga.setEnabled(true);
b_cotizacion_carga.setEnabled(true);
b_inventario.setEnabled(true);
b_desgaste.setEnabled(true);
b_pago.setEnabled(true);
b_cotizacion.setEnabled(true);
b_mas.setEnabled(true);
b_menos.setEnabled(true);
c_carpetas.setEnabled(true);
lista_fotos.setEnabled(true);
b_foto.setEnabled(true);
//c_estatus.setEnabled(true);
t_deducible.setEnabled(true);
t_demerito.setEnabled(true);
}
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.CONSULTA_REPARACION");
service.add("ID_REPARACION", t_solicitud.getText());
System.out.println(service.getRespueta());
JSONObject respuesta = new JSONObject(service.getRespueta());
if(respuesta.getInt("ESTADO")==1)
{
JSONArray datos_array=respuesta.getJSONArray("DATOS");
JSONObject datos = datos_array.getJSONObject(0);
if(datos.get("fecha_llegada").toString().compareToIgnoreCase("null")!=0)
t_ingreso.setText(datos.get("fecha_llegada").toString());
else
t_ingreso.setText(datos.get("pendiente").toString());
if(datos.get("fecha_promesa").toString().compareToIgnoreCase("null")!=0)
t_promesa.setText(datos.get("fecha_promesa").toString());
else
t_promesa.setText("pendiente");
if(datos.get("fecha_entrega").toString().compareToIgnoreCase("null")!=0)
t_salida.setText(datos.get("fecha_entrega").toString());
else
t_salida.setText("pendiente");
if(datos.get("deducible").toString().compareToIgnoreCase("null")!=0)
{
t_deducible.setValue(Double.parseDouble(datos.get("deducible").toString()));
t_deducible.commitEdit();
}
else
{
t_deducible.setValue(0.0d);
t_deducible.commitEdit();
}
if(datos.get("demerito").toString().compareToIgnoreCase("null")!=0)
{
t_demerito.setValue(Double.parseDouble(datos.get("demerito").toString()));
t_demerito.commitEdit();
}
else
{
t_demerito.setValue(0.0d);
t_demerito.commitEdit();
}
if(datos.get("descripcion").toString().compareToIgnoreCase("null")!=0)
t_descripcion.setText(datos.get("descripcion").toString());
else
t_descripcion.setText("");
if(datos.get("autorizo").toString().compareToIgnoreCase("null")!=0)
t_autorizo.setText(datos.get("autorizo").toString());
else
t_autorizo.setText("pendiente");
if(datos.get("n_economico").toString().compareToIgnoreCase("null")!=0)
t_economico.setText(datos.get("n_economico").toString());
else
t_economico.setText("-");
if(datos.get("no_reporte_cabina").toString().compareToIgnoreCase("null")!=0)
t_reporte.setText(datos.get("no_reporte_cabina").toString());
else
t_reporte.setText("-");
if(datos.get("inventario").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("inventario").toString(), b_inventario);
else
b_inventario.setText("pendiente");
if(datos.get("pago").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("pago").toString(), b_pago);
else
b_pago.setText("pendiente");
if(datos.get("cotizacion").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("cotizacion").toString(), b_cotizacion);
else
b_cotizacion.setText("pendiente");
if(datos.get("desgaste").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("desgaste").toString(), b_desgaste);
else
b_desgaste.setText("pendiente");
if(datos.get("id_unidad").toString().compareToIgnoreCase("null")!=0)
id_unidad.setText(datos.get("id_unidad").toString());
else
id_unidad.setText("");
if(datos.get("id_sucursal").toString().compareToIgnoreCase("null")!=0)
id_sucursal.setText(datos.get("id_sucursal").toString());
else
id_sucursal.setText("");
if(datos.get("n_carpeta").toString().compareToIgnoreCase("null")!=0)
l_carpeta.setText(datos.get("n_carpeta").toString());
else
l_carpeta.setText("");
}
else
{
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
}
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error Al Conectar con el Servidor");
}
}
else
{
if(usr.getEditaSm())
{
b_inventario_carga.setEnabled(false);
b_desgaste_carga.setEnabled(false);
b_pago_carga.setEnabled(false);
b_cotizacion_carga.setEnabled(false);
b_inventario.setEnabled(false);
b_desgaste.setEnabled(false);
b_pago.setEnabled(false);
b_cotizacion.setEnabled(false);
//c_estatus.setEnabled(false);
t_deducible.setEnabled(true);
t_demerito.setEnabled(true);
}
}
}
else
{
JOptionPane.showMessageDialog(null, "¡Acceso denegado!");
}
}catch(Exception e)
{
System.out.println(e);
this.setVisible(false);
}
if(session!=null)
if(session.isOpen()==true)
session.close();
}
//generate uri according to the filePath
private URI getFileURI(String filePath)
{
URI uri = null;
filePath = filePath.trim();
if(filePath.indexOf("http") == 0 || filePath.indexOf("\\") == 0)
{
if(filePath.indexOf("\\") == 0) filePath = "file:" + filePath;
try
{
filePath = filePath.replaceAll(" ", "%20");
URL url = new URL(filePath);
uri = url.toURI();
} catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (URISyntaxException ex)
{
ex.printStackTrace();
}
}
else
{
File file = new File(filePath);
uri = file.toURI();
}
return uri;
}
void agregaArchivo(String nombre, JButton bt){
if(nombre.contains(".pdf") || nombre.contains(".PDF"))
bt.setIcon(new ImageIcon("imagenes/pdf.png"));
else
{
if(nombre.contains(".docx") || nombre.contains(".DOCX"))
bt.setIcon(new ImageIcon("imagenes/word.png"));
else
bt.setIcon(new ImageIcon("imagenes/desconocido.png"));
}
bt.setText(nombre);
}
private List<Object[]> executeHQLQuery(String hql) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
session.disconnect();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
List lista = null;
return lista;
} finally {
if (session.isOpen()) {
session.close();
}
}
}
/**
*
* @param rutaImagen ej "http://tbstoluca.ddns.net/sm-l/"
* @param w size of image with
* @param h size of imae height
* @return Imae icon of file url
*/
public ImageIcon imagenFTP(String rutaImagen, String nombreImagen, int w, int h){
ImageIcon imageIcon=null;
try {
InputStream in=new URL(rutaImagen+nombreImagen).openStream();
foto = File.createTempFile("tmp", ".jpg");
OutputStream out = new FileOutputStream(foto.getAbsolutePath());
IOUtils.copy(in,out);
in.close();
out.close();
foto.deleteOnExit();
imageIcon = new javax.swing.ImageIcon(new URL(rutaImagen+nombreImagen));
Image img = imageIcon.getImage();
Image dimg = img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
imageIcon.setImage(dimg);
} catch (Exception e) {
e.printStackTrace();
imageIcon = new javax.swing.ImageIcon(getClass().getResource("/recursos/error.jpg"));
}
return imageIcon;
}
void leerDirectorio(){
Ftp miFtp=new Ftp();
foto=null;
if(miFtp.conectar("tbstoluca.ddns.net", "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()+"/"))
{
boolean existe=true;
if(!miFtp.cambiarDirectorio(c_carpetas.getSelectedItem().toString()))
{
if(miFtp.crearDirectorio("/"+c_carpetas.getSelectedItem().toString()))
{
if(!miFtp.cambiarDirectorio(c_carpetas.getSelectedItem().toString()))
existe=false;
}
else
existe=false;
}
modeloLista.clear();
if(existe)
{
FTPFile[] lista = miFtp.listarArchivos();
int cantidad=lista.length;
for(int x=0; x<cantidad; x++){
modeloLista.addElement(lista[x].getName());
}
}try{
miFtp.desconectar();}catch(Exception e){}
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
public class Hilo implements Runnable
{
Thread t;
String rutaImagen;
String nombreImagen;
int w;
int h;
public Hilo(String rutaImagen, String nombreImagen, int w, int h)
{
this.rutaImagen=rutaImagen;
this.nombreImagen=nombreImagen;
this.w=w;
this.h=h;
t=new Thread(this,"Fotos");
t.start();
}
@Override
public void run() {
b_foto.setIcon(imagenFTP(rutaImagen, nombreImagen, w, h));
t.interrupt();
}
}
}
|
UTF-8
|
Java
| 108,332 |
java
|
SosColision.java
|
Java
|
[
{
"context": "ay;\nimport org.json.JSONObject;\n\n/**\n *\n * @author Sistemas\n */\npublic class SosColision extends javax.swing.",
"end": 1486,
"score": 0.983359694480896,
"start": 1478,
"tag": "NAME",
"value": "Sistemas"
}
] | null |
[] |
/*
* 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 Servicios;
import Hibernate.Util.HibernateUtil;
import Hibernate.entidades.Acceso;
import Hibernate.entidades.Configuracion;
import Hibernate.entidades.Cuenta;
import Hibernate.entidades.Foto;
import Hibernate.entidades.Notificacion;
import Hibernate.entidades.Orden;
import Hibernate.entidades.Usuario;
import Integral.ExtensionFileFilter;
import Integral.Ftp;
import Integral.Herramientas;
import Integral.PeticionPost;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.poi.util.IOUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* @author Sistemas
*/
public class SosColision extends javax.swing.JPanel {
String estado="";
String sessionPrograma="";
Usuario usr;
String ord="";
Herramientas h;
Orden orden_act;
JFileChooser selector;
JFileChooser selectorFoto;
String ruta;
String n_carpeta="";
DefaultListModel modeloLista= new DefaultListModel();
File foto=null;
Hilo miHilo=null;
/**
* Creates new form SmLogistics
*/
public SosColision(String ord, Usuario usr, String estado, String sessionPrograma, String carpeta) {
initComponents();
this.ord=ord;
this.usr=usr;
this.estado=estado;
this.sessionPrograma=sessionPrograma;
ruta=carpeta;
buscaDatos();
selector=new JFileChooser();
selector.setFileFilter(new ExtensionFileFilter("Documentos(PDF y DOCX)", new String[] { "PDF", "DOCX" }));
selector.setAcceptAllFileFilterUsed(false);
selector.setMultiSelectionEnabled(true);
selectorFoto=new JFileChooser();
selectorFoto.setFileFilter(new ExtensionFileFilter("Documentos(JPG y JPEG)", new String[] { "JPG", "JPEG" }));
selectorFoto.setAcceptAllFileFilterUsed(false);
selectorFoto.setMultiSelectionEnabled(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
ListaSOS = new javax.swing.JDialog();
jPanel7 = new javax.swing.JPanel();
b_autorizar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
c_estatus1 = new javax.swing.JComboBox();
id_unidad = new javax.swing.JLabel();
id_sucursal = new javax.swing.JLabel();
l_carpeta = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
jPanel16 = new javax.swing.JPanel();
jPanel18 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
t_ingreso = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
t_promesa = new javax.swing.JTextField();
t_salida = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
c_estatus = new javax.swing.JComboBox();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel3 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
t_descripcion = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
t_economico = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
t_autorizo = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
t_reporte = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
t_deducible = new javax.swing.JFormattedTextField();
t_demerito = new javax.swing.JFormattedTextField();
b_ac = new javax.swing.JButton();
jPanel8 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
b_inventario_carga = new javax.swing.JButton();
b_inventario = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
b_pago_carga = new javax.swing.JButton();
b_pago = new javax.swing.JButton();
jPanel6 = new javax.swing.JPanel();
b_cotizacion_carga = new javax.swing.JButton();
b_cotizacion = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
b_desgaste_carga = new javax.swing.JButton();
b_desgaste = new javax.swing.JButton();
jPanel9 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
lista_fotos = new javax.swing.JList(modeloLista);
b_menos = new javax.swing.JButton();
b_mas = new javax.swing.JButton();
c_carpetas = new javax.swing.JComboBox();
b_foto = new javax.swing.JButton();
jLabel13 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
t_solicitud = new javax.swing.JTextField();
ListaSOS.setModalExclusionType(null);
ListaSOS.setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "Lista de Reparaciones Asignadas", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP));
b_autorizar.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
b_autorizar.setText("Enlazar");
b_autorizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_autorizarActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jLabel2.setText("Filtrar por Estatus:");
c_estatus1.setBackground(new java.awt.Color(204, 255, 255));
c_estatus1.setForeground(new java.awt.Color(51, 0, 255));
c_estatus1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PROGRAMADA", "PROCESO", "VALUACION", "EN REPARACION", "TERMINADA", "ENTREGADA", "CANCELADA", "PERDIDA TOTAL" }));
c_estatus1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c_estatus1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(c_estatus1, 0, 181, Short.MAX_VALUE)
.addGap(260, 260, 260)
.addComponent(b_autorizar)))
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(c_estatus1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b_autorizar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(18, Short.MAX_VALUE))
);
javax.swing.GroupLayout ListaSOSLayout = new javax.swing.GroupLayout(ListaSOS.getContentPane());
ListaSOS.getContentPane().setLayout(ListaSOSLayout);
ListaSOSLayout.setHorizontalGroup(
ListaSOSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
ListaSOSLayout.setVerticalGroup(
ListaSOSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
id_unidad.setText("jLabel13");
id_sucursal.setText("jLabel13");
l_carpeta.setText("jLabel13");
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "SOS Collision", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 12))); // NOI18N
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Servicios/icono.png"))); // NOI18N
jPanel16.setBackground(new java.awt.Color(255, 255, 255));
jPanel16.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "GENERAL", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
jPanel16.setLayout(new java.awt.BorderLayout());
jPanel18.setBackground(new java.awt.Color(255, 255, 255));
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel5.setText("Ingreso");
t_ingreso.setEditable(false);
t_ingreso.setBackground(new java.awt.Color(204, 255, 255));
t_ingreso.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_ingreso.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_ingreso.setEnabled(false);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Promesa");
t_promesa.setEditable(false);
t_promesa.setBackground(new java.awt.Color(204, 255, 255));
t_promesa.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_promesa.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_promesa.setEnabled(false);
t_salida.setEditable(false);
t_salida.setBackground(new java.awt.Color(204, 255, 255));
t_salida.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_salida.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_salida.setEnabled(false);
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setText("Salida");
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(t_ingreso, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(t_promesa, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel18Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(t_salida, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(t_ingreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(t_promesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(t_salida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel16.add(jPanel18, java.awt.BorderLayout.CENTER);
c_estatus.setBackground(new java.awt.Color(204, 255, 255));
c_estatus.setForeground(new java.awt.Color(51, 0, 255));
c_estatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PROGRAMADA", "PROCESO", "VALUACION", "EN REPARACION", "TERMINADO", "ENTREGADA", "CANCELADA", "PERDIDA TOTAL" }));
c_estatus.setEnabled(false);
c_estatus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c_estatusActionPerformed(evt);
}
});
jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jTabbedPane1StateChanged(evt);
}
});
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
t_descripcion.setEditable(false);
t_descripcion.setColumns(20);
t_descripcion.setRows(5);
jScrollPane2.setViewportView(t_descripcion);
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel3.setText("Descripción:");
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel7.setText("Economico:");
t_economico.setEditable(false);
t_economico.setBackground(new java.awt.Color(204, 255, 255));
t_economico.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_economico.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_economico.setEnabled(false);
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel8.setText("Autorizo:");
t_autorizo.setEditable(false);
t_autorizo.setBackground(new java.awt.Color(204, 255, 255));
t_autorizo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_autorizo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_autorizo.setEnabled(false);
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel9.setText("N° Reporte:");
t_reporte.setEditable(false);
t_reporte.setBackground(new java.awt.Color(204, 255, 255));
t_reporte.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_reporte.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_reporte.setEnabled(false);
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("Deducible:");
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("Demerito:");
t_deducible.setBackground(new java.awt.Color(204, 255, 255));
t_deducible.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_deducible.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
t_deducible.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
t_deducible.setText("0.00");
t_deducible.setDisabledTextColor(new java.awt.Color(2, 38, 253));
t_deducible.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
t_deducibleActionPerformed(evt);
}
});
t_demerito.setBackground(new java.awt.Color(204, 255, 255));
t_demerito.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_demerito.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
t_demerito.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
t_demerito.setText("0.00");
t_demerito.setDisabledTextColor(new java.awt.Color(2, 38, 253));
b_ac.setText("Guardar");
b_ac.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_acActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t_autorizo))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel7)
.addComponent(jLabel9)
.addComponent(t_reporte)
.addComponent(t_economico, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel10))
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(t_deducible, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(t_demerito, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
.addComponent(jLabel11)
.addComponent(b_ac, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(90, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jLabel10))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(t_economico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t_deducible, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(t_reporte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(t_demerito, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_ac)
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(7, 7, 7)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(t_autorizo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jTabbedPane1.addTab("Reporte", jPanel3);
jPanel8.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "INVENTARIO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_inventario_carga.setBackground(new java.awt.Color(2, 135, 242));
b_inventario_carga.setForeground(new java.awt.Color(255, 255, 255));
b_inventario_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_inventario_carga.setToolTipText("Calendario");
b_inventario_carga.setEnabled(false);
b_inventario_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_inventario_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_inventario_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_inventario_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_inventario_cargaActionPerformed(evt);
}
});
b_inventario.setEnabled(false);
b_inventario.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_inventario.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_inventarioActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_inventario, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_inventario_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_inventario, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_inventario_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "INFO. PAGO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_pago_carga.setBackground(new java.awt.Color(2, 135, 242));
b_pago_carga.setForeground(new java.awt.Color(255, 255, 255));
b_pago_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_pago_carga.setToolTipText("Calendario");
b_pago_carga.setEnabled(false);
b_pago_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_pago_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_pago_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_pago_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_pago_cargaActionPerformed(evt);
}
});
b_pago.setEnabled(false);
b_pago.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_pago.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_pagoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_pago, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_pago_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_pago, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_pago_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "COTIZACIÓN", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_cotizacion_carga.setBackground(new java.awt.Color(2, 135, 242));
b_cotizacion_carga.setForeground(new java.awt.Color(255, 255, 255));
b_cotizacion_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_cotizacion_carga.setToolTipText("Calendario");
b_cotizacion_carga.setEnabled(false);
b_cotizacion_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_cotizacion_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_cotizacion_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_cotizacion_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_cotizacion_cargaActionPerformed(evt);
}
});
b_cotizacion.setEnabled(false);
b_cotizacion.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_cotizacion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_cotizacionActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(b_cotizacion, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(b_cotizacion_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_cotizacion, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_cotizacion_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "DESGASTE", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Arial", 1, 10))); // NOI18N
b_desgaste_carga.setBackground(new java.awt.Color(2, 135, 242));
b_desgaste_carga.setForeground(new java.awt.Color(255, 255, 255));
b_desgaste_carga.setIcon(new ImageIcon("imagenes/subir.png"));
b_desgaste_carga.setToolTipText("Calendario");
b_desgaste_carga.setEnabled(false);
b_desgaste_carga.setMaximumSize(new java.awt.Dimension(32, 8));
b_desgaste_carga.setMinimumSize(new java.awt.Dimension(32, 8));
b_desgaste_carga.setPreferredSize(new java.awt.Dimension(28, 24));
b_desgaste_carga.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_desgaste_cargaActionPerformed(evt);
}
});
b_desgaste.setEnabled(false);
b_desgaste.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
b_desgaste.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_desgasteActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(b_desgaste, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(b_desgaste_carga, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(b_desgaste, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_desgaste_carga, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Informes", jPanel8);
lista_fotos.setEnabled(false);
lista_fotos.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
lista_fotosValueChanged(evt);
}
});
jScrollPane3.setViewportView(lista_fotos);
b_menos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/menos.png"))); // NOI18N
b_menos.setEnabled(false);
b_menos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_menosActionPerformed(evt);
}
});
b_mas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/mas.png"))); // NOI18N
b_mas.setEnabled(false);
b_mas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_masActionPerformed(evt);
}
});
c_carpetas.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "INGRESO", "CAMBIOS", "PROCESO", "SALIDA" }));
c_carpetas.setEnabled(false);
c_carpetas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c_carpetasActionPerformed(evt);
}
});
b_foto.setBackground(new java.awt.Color(255, 255, 255));
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/login.jpg"))); // NOI18N
b_foto.setEnabled(false);
b_foto.setOpaque(false);
b_foto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_fotoActionPerformed(evt);
}
});
jLabel13.setText("Carpeta:");
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel9Layout.createSequentialGroup()
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(c_carpetas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b_menos, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_mas, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(b_foto, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(124, 124, 124))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(b_foto, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(b_menos, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b_mas, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(c_carpetas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(22, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Galeria", jPanel9);
jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel12.setText("Estatus:");
jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel14.setText("REPARACION:");
t_solicitud.setBackground(new java.awt.Color(204, 255, 255));
t_solicitud.setHorizontalAlignment(javax.swing.JTextField.CENTER);
t_solicitud.setBorder(javax.swing.BorderFactory.createEtchedBorder());
t_solicitud.setEnabled(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel16, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t_solicitud))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(c_estatus, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTabbedPane1)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(t_solicitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addComponent(jPanel16, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(42, 42, 42)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(c_estatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void b_inventario_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_inventario_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_inventario.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/inventario/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setInventario(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Inventario de Ingreso");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "INVENTARIO");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_desgaste);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_inventario_cargaActionPerformed
private void b_desgaste_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_desgaste_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_desgaste.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/desgaste/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setDesgaste(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Desgaste no atribuible al siniestro");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "DESGASTE");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_desgaste);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_desgaste_cargaActionPerformed
private void b_pago_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_pago_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_pago.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/pago/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setPago(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Pago");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "PAGO");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_pago);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_pago_cargaActionPerformed
private void b_cotizacion_cargaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_cotizacion_cargaActionPerformed
// TODO add your handling code here:
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File destino=null;
int estado=selector.showOpenDialog(null);
File archivo = selector.getSelectedFile();
if(estado==0)
{
if(archivo.exists())
{
Herramientas h = new Herramientas(this.usr, 0);
String nombre=b_cotizacion.getText();
if(nombre.compareTo("pendiente")==0)
nombre=h.randomString(11)+".pdf";
System.out.println(nombre);
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/cotizacion/"))
{
if(miFtp.subirArchivo(archivo.getPath(), nombre))
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, orden_act.getIdOrden());
orden_act.setEntrega(nombre);
session.saveOrUpdate(orden_act);
//creamos las notificaciones**************
ArrayList<Acceso> accesos=new ArrayList();
Acceso [] aux1 = (Acceso[])orden_act.getClientes().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
if(orden_act.getCompania()!=null)
{
aux1 = (Acceso[])orden_act.getCompania().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
if(orden_act.getAgente()!=null)
{
aux1 = (Acceso[])orden_act.getAgente().getAccesos().toArray(new Acceso[0]);
accesos.addAll(Arrays.asList(aux1));
}
String notificaciones="{\"NOTIFICACIONES\":[";
for(int a=0; a<accesos.size(); a++)
{
Notificacion nueva=new Notificacion();
nueva.setMensaje("OT:"+orden_act.getIdOrden()+" Cotizacion");
nueva.setExtra("");
nueva.setIntentos(0);
nueva.setVisto(false);
nueva.setAcceso(accesos.get(a));
Integer id = (Integer)session.save(nueva);
nueva=(Notificacion)session.get(Notificacion.class, id);
nueva.setExtra("{\"VENTANA\":\"MuestraPDF\",\"ID_ORDEN\":\""+orden_act.getIdOrden()+"\",\"ID_NOTIFICACION\":\""+id+"\",\"ID_USUARIO\":\""+accesos.get(a).getIdAcceso()+"\",\"ARCHIVO\":\""+nombre+"\"}");
session.update(nueva);
notificaciones+="{\"ID\":\""+id+"\"}";
if(a+1 < accesos.size())
notificaciones+=",";
}
notificaciones+="]}";
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_ARCHIVO");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("TIPO", "COTIZACION");
service.add("ARCHIVO_NOMBRE", nombre);
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
{
JOptionPane.showMessageDialog(this, "EL ARCHIVO FUE CARGADO Y SE NOTIFICO AL CLIENTE");
}
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
agregaArchivo(nombre, b_cotizacion);
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "El archivo fue cargado con exito pero no se pudo notificar al cliente.");
}
}
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
if(session!= null)
if(session.isOpen())
session.close();
}//GEN-LAST:event_b_cotizacion_cargaActionPerformed
private void b_inventarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_inventarioActionPerformed
// TODO add your handling code here:
if(b_inventario.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/inventario/"))
{
miFtp.AbrirArchivo(b_inventario.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_inventarioActionPerformed
private void b_desgasteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_desgasteActionPerformed
// TODO add your handling code here:
if(b_desgaste.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/desgaste/"))
{
miFtp.AbrirArchivo(b_desgaste.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_desgasteActionPerformed
private void b_pagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_pagoActionPerformed
// TODO add your handling code here:
if(b_pago.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/pago/"))
{
miFtp.AbrirArchivo(b_pago.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_pagoActionPerformed
private void b_cotizacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_cotizacionActionPerformed
// TODO add your handling code here:
if(b_cotizacion.getText().compareToIgnoreCase("pendiente")!=0)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar(ruta, "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/documentos/cotizacion/"))
{
miFtp.AbrirArchivo(b_cotizacion.getText());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}//GEN-LAST:event_b_cotizacionActionPerformed
private void c_estatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c_estatusActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_c_estatusActionPerformed
private void b_autorizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_autorizarActionPerformed
/*if(t_user.getText().compareTo("")!=0)
{
if(t_contra.getPassword().toString().compareTo("")!=0)
{
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
session.beginTransaction().begin();
Usuario autoriza = (Usuario)session.createCriteria(Usuario.class).add(Restrictions.eq("idUsuario", t_user.getText())).add(Restrictions.eq("clave", t_contra.getText())).setMaxResults(1).uniqueResult();
if(autoriza!=null)
{
if(autoriza.getAutorizarSobrecosto()==true)
{
usrAut=autoriza;
ListaSOS.dispose();
}
else
JOptionPane.showMessageDialog(this, "¡El usuario no tiene permiso de autorizar!");
}
else
{
session.beginTransaction().rollback();
JOptionPane.showMessageDialog(this, "¡Datos Incorrectos!");
t_user.requestFocus();
}
}catch(Exception e)
{
session.beginTransaction().rollback();
JOptionPane.showMessageDialog(this, "¡Error al consultar los datos!");
e.printStackTrace();
}
finally
{
if(session.isOpen()==true)
session.close();
}
}
else
{
JOptionPane.showMessageDialog(this, "¡Ingrese la contraseña!");
t_contra.requestFocus();
}
}
else
{
JOptionPane.showMessageDialog(this, "¡Ingrese el usuario!");
t_user.requestFocus();
}*/
}//GEN-LAST:event_b_autorizarActionPerformed
private void c_estatus1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c_estatus1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_c_estatus1ActionPerformed
private void lista_fotosValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lista_fotosValueChanged
// TODO add your handling code here:
if(!lista_fotos.isSelectionEmpty())
{
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/gearsan.gif")));
miHilo=null;
miHilo = new Hilo("http://tbstoluca.ddns.net/sm-l/recursos/reparacion/"+l_carpeta.getText()+"/"+c_carpetas.getSelectedItem().toString()+"/", lista_fotos.getSelectedValue().toString(), b_foto.getWidth()-40, b_foto.getHeight()-40);
}
else
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/login.jpg")));
}//GEN-LAST:event_lista_fotosValueChanged
private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged
// TODO add your handling code here:
try{
String ventana=jTabbedPane1.getTitleAt(jTabbedPane1.getSelectedIndex());
if(ventana.compareTo("Galeria")==0)
{
leerDirectorio();
}
}catch(Exception e){
b_foto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/login.jpg")));
}
}//GEN-LAST:event_jTabbedPane1StateChanged
private void c_carpetasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c_carpetasActionPerformed
// TODO add your handling code here:
if(l_carpeta.getText().compareTo("")!=0)
{
//System.out.println("Evento");
leerDirectorio();
}
}//GEN-LAST:event_c_carpetasActionPerformed
private void b_fotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_fotoActionPerformed
// TODO add your handling code here:
if(foto!=null && foto.exists()){
try{
Desktop.getDesktop().open(foto);
}catch(Exception e){}
}
}//GEN-LAST:event_b_fotoActionPerformed
private void b_masActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_masActionPerformed
// TODO add your handling code here:
try
{
File destino=null;
int estado=selectorFoto.showOpenDialog(null);
File[] archivos = selectorFoto.getSelectedFiles();
if(estado==0)
{
for(int p=0; p<archivos.length; p++)
{
if(archivos[p].exists())
{
if(!modeloLista.contains(archivos[p].getName()))
{
Herramientas h = new Herramientas(this.usr, 0);
Ftp miFtp=new Ftp();
if(miFtp.conectar("tbstoluca.ddns.net", "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()))
{
boolean existe=true;
if(!miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()+"/"+c_carpetas.getSelectedItem().toString()+"/"))
{
if(miFtp.crearDirectorio("/"+c_carpetas.getSelectedItem().toString()))
{
if(!miFtp.cambiarDirectorio("/"+c_carpetas.getSelectedItem().toString()+"/"))
existe=false;
}
else
existe=false;
}
if(existe)
{
if(miFtp.subirArchivo(archivos[p].getPath(), archivos[p].getName()))
modeloLista.addElement(archivos[p].getName());
miFtp.desconectar();
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio RAIZ");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
}
}
}
}catch (Exception ioe)
{
ioe.printStackTrace();
javax.swing.JOptionPane.showMessageDialog(null, "Error no se pudo cargar el archivo");
}
}//GEN-LAST:event_b_masActionPerformed
private void b_menosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_menosActionPerformed
// TODO add your handling code here:
int[] totalEliminar = lista_fotos.getSelectedIndices();
if(totalEliminar.length>0){
int opt=JOptionPane.showConfirmDialog(this, "¡Las Fotos se eliminarán del Servidor!");
if (JOptionPane.YES_OPTION == opt)
{
Herramientas h = new Herramientas(this.usr, 0);
for(int x=0; x<totalEliminar.length; x++)
{
Ftp miFtp=new Ftp();
if(miFtp.conectar("tbstoluca.ddns.net", "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()+"/"+c_carpetas.getSelectedItem().toString()+"/"))
{
if(miFtp.borrarArchivo(modeloLista.elementAt(totalEliminar[x]-x).toString()))
modeloLista.removeElementAt(totalEliminar[x]-x);
else{
x=totalEliminar.length;
JOptionPane.showMessageDialog(null, "Algunas fotos no fue posible eliminarlas intente mas tarde!");
}
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio RAIZ");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
miFtp.desconectar();
}
}
}
else
JOptionPane.showMessageDialog(null, "Seleccione las fotos a eliminar");
}//GEN-LAST:event_b_menosActionPerformed
private void b_acActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_acActionPerformed
// TODO add your handling code here:
h= new Herramientas(this.usr, 0);
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
session.beginTransaction().begin();
orden_act = (Orden)session.get(Orden.class, Integer.parseInt(ord));
if(t_deducible.getText().compareTo("")!=0)
orden_act.setDeducible(((Number)t_deducible.getValue()).doubleValue());
else
orden_act.setDeducible(null);
if(t_demerito.getText().compareTo("")!=0)
orden_act.setDemerito(((Number)t_demerito.getValue()).doubleValue());
else
orden_act.setDemerito(null);
session.update(orden_act);
session.beginTransaction().commit();
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.GUARDA_MONTOS");
service.add("ID_REPARACION", t_solicitud.getText());
service.add("DEDUCIBLE", ""+((Number)t_deducible.getValue()).doubleValue());
service.add("DEMERITO", ""+((Number)t_demerito.getValue()).doubleValue());
String resp=service.getRespueta();
System.out.println(resp);
JSONObject respuesta = new JSONObject(resp);
if(respuesta.getInt("ESTADO")==1)
JOptionPane.showMessageDialog(this, "LOS MONTOS FUERON ACTUALIZADOS Y SE NOTIFICO AL CLIENTE");
else
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "LOS MONTOS FUERON ACTUALIZADOS");
}
}
catch(Exception e)
{
session.beginTransaction().rollback();
e.printStackTrace();
JOptionPane.showMessageDialog(this, "NO SE PUDO REALIZAR LA ACTUALIZACION");
}
if(session!=null)
if(session.isOpen())
{
session.flush();
session.clear();
session.close();
}
}//GEN-LAST:event_b_acActionPerformed
private void t_deducibleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_t_deducibleActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_t_deducibleActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JDialog ListaSOS;
private javax.swing.JButton b_ac;
private javax.swing.JButton b_autorizar;
private javax.swing.JButton b_cotizacion;
private javax.swing.JButton b_cotizacion_carga;
private javax.swing.JButton b_desgaste;
private javax.swing.JButton b_desgaste_carga;
private javax.swing.JButton b_foto;
private javax.swing.JButton b_inventario;
private javax.swing.JButton b_inventario_carga;
private javax.swing.JButton b_mas;
private javax.swing.JButton b_menos;
private javax.swing.JButton b_pago;
private javax.swing.JButton b_pago_carga;
private javax.swing.JComboBox c_carpetas;
private javax.swing.JComboBox c_estatus;
private javax.swing.JComboBox c_estatus1;
private javax.swing.JLabel id_sucursal;
private javax.swing.JLabel id_unidad;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable jTable1;
private javax.swing.JLabel l_carpeta;
private javax.swing.JList lista_fotos;
private javax.swing.JTextField t_autorizo;
private javax.swing.JFormattedTextField t_deducible;
private javax.swing.JFormattedTextField t_demerito;
private javax.swing.JTextArea t_descripcion;
private javax.swing.JTextField t_economico;
private javax.swing.JTextField t_ingreso;
private javax.swing.JTextField t_promesa;
private javax.swing.JTextField t_reporte;
private javax.swing.JTextField t_salida;
private javax.swing.JTextField t_solicitud;
// End of variables declaration//GEN-END:variables
public void buscaDatos()
{
Session session = HibernateUtil.getSessionFactory().openSession();
try
{
File f;
usr = (Usuario)session.get(Usuario.class, usr.getIdUsuario());
if(usr.getConsultaSm() || usr.getEditaSm())
{
orden_act = (Orden)session.get(Orden.class, Integer.parseInt(ord));
if(orden_act.getIdSm()!=null){
t_solicitud.setText(orden_act.getIdSm());
if(usr.getEditaSm())
{
b_inventario_carga.setEnabled(true);
b_desgaste_carga.setEnabled(true);
b_pago_carga.setEnabled(true);
b_cotizacion_carga.setEnabled(true);
b_inventario.setEnabled(true);
b_desgaste.setEnabled(true);
b_pago.setEnabled(true);
b_cotizacion.setEnabled(true);
b_mas.setEnabled(true);
b_menos.setEnabled(true);
c_carpetas.setEnabled(true);
lista_fotos.setEnabled(true);
b_foto.setEnabled(true);
//c_estatus.setEnabled(true);
t_deducible.setEnabled(true);
t_demerito.setEnabled(true);
}
try{
PeticionPost service=new PeticionPost("http://tbstoluca.ddns.net/sm-l/service/api.php");
service.add("METODO", "REPARACION.CONSULTA_REPARACION");
service.add("ID_REPARACION", t_solicitud.getText());
System.out.println(service.getRespueta());
JSONObject respuesta = new JSONObject(service.getRespueta());
if(respuesta.getInt("ESTADO")==1)
{
JSONArray datos_array=respuesta.getJSONArray("DATOS");
JSONObject datos = datos_array.getJSONObject(0);
if(datos.get("fecha_llegada").toString().compareToIgnoreCase("null")!=0)
t_ingreso.setText(datos.get("fecha_llegada").toString());
else
t_ingreso.setText(datos.get("pendiente").toString());
if(datos.get("fecha_promesa").toString().compareToIgnoreCase("null")!=0)
t_promesa.setText(datos.get("fecha_promesa").toString());
else
t_promesa.setText("pendiente");
if(datos.get("fecha_entrega").toString().compareToIgnoreCase("null")!=0)
t_salida.setText(datos.get("fecha_entrega").toString());
else
t_salida.setText("pendiente");
if(datos.get("deducible").toString().compareToIgnoreCase("null")!=0)
{
t_deducible.setValue(Double.parseDouble(datos.get("deducible").toString()));
t_deducible.commitEdit();
}
else
{
t_deducible.setValue(0.0d);
t_deducible.commitEdit();
}
if(datos.get("demerito").toString().compareToIgnoreCase("null")!=0)
{
t_demerito.setValue(Double.parseDouble(datos.get("demerito").toString()));
t_demerito.commitEdit();
}
else
{
t_demerito.setValue(0.0d);
t_demerito.commitEdit();
}
if(datos.get("descripcion").toString().compareToIgnoreCase("null")!=0)
t_descripcion.setText(datos.get("descripcion").toString());
else
t_descripcion.setText("");
if(datos.get("autorizo").toString().compareToIgnoreCase("null")!=0)
t_autorizo.setText(datos.get("autorizo").toString());
else
t_autorizo.setText("pendiente");
if(datos.get("n_economico").toString().compareToIgnoreCase("null")!=0)
t_economico.setText(datos.get("n_economico").toString());
else
t_economico.setText("-");
if(datos.get("no_reporte_cabina").toString().compareToIgnoreCase("null")!=0)
t_reporte.setText(datos.get("no_reporte_cabina").toString());
else
t_reporte.setText("-");
if(datos.get("inventario").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("inventario").toString(), b_inventario);
else
b_inventario.setText("pendiente");
if(datos.get("pago").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("pago").toString(), b_pago);
else
b_pago.setText("pendiente");
if(datos.get("cotizacion").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("cotizacion").toString(), b_cotizacion);
else
b_cotizacion.setText("pendiente");
if(datos.get("desgaste").toString().compareToIgnoreCase("null")!=0)
agregaArchivo(datos.get("desgaste").toString(), b_desgaste);
else
b_desgaste.setText("pendiente");
if(datos.get("id_unidad").toString().compareToIgnoreCase("null")!=0)
id_unidad.setText(datos.get("id_unidad").toString());
else
id_unidad.setText("");
if(datos.get("id_sucursal").toString().compareToIgnoreCase("null")!=0)
id_sucursal.setText(datos.get("id_sucursal").toString());
else
id_sucursal.setText("");
if(datos.get("n_carpeta").toString().compareToIgnoreCase("null")!=0)
l_carpeta.setText(datos.get("n_carpeta").toString());
else
l_carpeta.setText("");
}
else
{
JOptionPane.showMessageDialog(this, respuesta.getString("MENSAJE"));
}
}catch(Exception e){
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error Al Conectar con el Servidor");
}
}
else
{
if(usr.getEditaSm())
{
b_inventario_carga.setEnabled(false);
b_desgaste_carga.setEnabled(false);
b_pago_carga.setEnabled(false);
b_cotizacion_carga.setEnabled(false);
b_inventario.setEnabled(false);
b_desgaste.setEnabled(false);
b_pago.setEnabled(false);
b_cotizacion.setEnabled(false);
//c_estatus.setEnabled(false);
t_deducible.setEnabled(true);
t_demerito.setEnabled(true);
}
}
}
else
{
JOptionPane.showMessageDialog(null, "¡Acceso denegado!");
}
}catch(Exception e)
{
System.out.println(e);
this.setVisible(false);
}
if(session!=null)
if(session.isOpen()==true)
session.close();
}
//generate uri according to the filePath
private URI getFileURI(String filePath)
{
URI uri = null;
filePath = filePath.trim();
if(filePath.indexOf("http") == 0 || filePath.indexOf("\\") == 0)
{
if(filePath.indexOf("\\") == 0) filePath = "file:" + filePath;
try
{
filePath = filePath.replaceAll(" ", "%20");
URL url = new URL(filePath);
uri = url.toURI();
} catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (URISyntaxException ex)
{
ex.printStackTrace();
}
}
else
{
File file = new File(filePath);
uri = file.toURI();
}
return uri;
}
void agregaArchivo(String nombre, JButton bt){
if(nombre.contains(".pdf") || nombre.contains(".PDF"))
bt.setIcon(new ImageIcon("imagenes/pdf.png"));
else
{
if(nombre.contains(".docx") || nombre.contains(".DOCX"))
bt.setIcon(new ImageIcon("imagenes/word.png"));
else
bt.setIcon(new ImageIcon("imagenes/desconocido.png"));
}
bt.setText(nombre);
}
private List<Object[]> executeHQLQuery(String hql) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
session.disconnect();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
List lista = null;
return lista;
} finally {
if (session.isOpen()) {
session.close();
}
}
}
/**
*
* @param rutaImagen ej "http://tbstoluca.ddns.net/sm-l/"
* @param w size of image with
* @param h size of imae height
* @return Imae icon of file url
*/
public ImageIcon imagenFTP(String rutaImagen, String nombreImagen, int w, int h){
ImageIcon imageIcon=null;
try {
InputStream in=new URL(rutaImagen+nombreImagen).openStream();
foto = File.createTempFile("tmp", ".jpg");
OutputStream out = new FileOutputStream(foto.getAbsolutePath());
IOUtils.copy(in,out);
in.close();
out.close();
foto.deleteOnExit();
imageIcon = new javax.swing.ImageIcon(new URL(rutaImagen+nombreImagen));
Image img = imageIcon.getImage();
Image dimg = img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
imageIcon.setImage(dimg);
} catch (Exception e) {
e.printStackTrace();
imageIcon = new javax.swing.ImageIcon(getClass().getResource("/recursos/error.jpg"));
}
return imageIcon;
}
void leerDirectorio(){
Ftp miFtp=new Ftp();
foto=null;
if(miFtp.conectar("tbstoluca.ddns.net", "sm", "04650077", 3310))
{
if(miFtp.cambiarDirectorio("/recursos/reparacion/"+l_carpeta.getText()+"/"))
{
boolean existe=true;
if(!miFtp.cambiarDirectorio(c_carpetas.getSelectedItem().toString()))
{
if(miFtp.crearDirectorio("/"+c_carpetas.getSelectedItem().toString()))
{
if(!miFtp.cambiarDirectorio(c_carpetas.getSelectedItem().toString()))
existe=false;
}
else
existe=false;
}
modeloLista.clear();
if(existe)
{
FTPFile[] lista = miFtp.listarArchivos();
int cantidad=lista.length;
for(int x=0; x<cantidad; x++){
modeloLista.addElement(lista[x].getName());
}
}try{
miFtp.desconectar();}catch(Exception e){}
}
else
JOptionPane.showMessageDialog(null, "No fue posible encontrar el directorio");
}
else
JOptionPane.showMessageDialog(null, "No fue posible conectar al servidor FTP");
}
public class Hilo implements Runnable
{
Thread t;
String rutaImagen;
String nombreImagen;
int w;
int h;
public Hilo(String rutaImagen, String nombreImagen, int w, int h)
{
this.rutaImagen=rutaImagen;
this.nombreImagen=nombreImagen;
this.w=w;
this.h=h;
t=new Thread(this,"Fotos");
t.start();
}
@Override
public void run() {
b_foto.setIcon(imagenFTP(rutaImagen, nombreImagen, w, h));
t.interrupt();
}
}
}
| 108,332 | 0.559075 | 0.546981 | 2,009 | 52.916874 | 39.361019 | 299 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.795421 | false | false |
9
|
52061f71c0e52de456fdde111ece9d92959c1de1
| 32,349,693,675,235 |
49b5c1714dc8e4cef797c4f53bddfe0f76017654
|
/main/plugins/org.talend.updates.runtime/src/main/java/org/talend/updates/runtime/engine/factory/AbstractExtraUpdatesFactory.java
|
0f291880fec98a73d233a320a5e90667c203c223
|
[
"Apache-2.0"
] |
permissive
|
cyroxx/tcommon-studio-se
|
https://github.com/cyroxx/tcommon-studio-se
|
4cd240a850fed34c1b02ae8b72274ede96d977bc
|
a211a9f5c32844708567c46727ad0900c212a155
|
refs/heads/master
| 2021-01-18T06:18:09.024000 | 2015-07-31T10:15:15 | 2015-07-31T10:20:00 | 40,002,469 | 1 | 0 | null | true | 2015-07-31T11:34:34 | 2015-07-31T11:34:34 | 2015-06-10T09:02:48 | 2015-07-31T10:20:23 | 1,130,660 | 0 | 0 | 0 | null | null | null |
// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.updates.runtime.engine.factory;
import java.util.Set;
import org.eclipse.core.databinding.observable.IObservable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.talend.updates.runtime.model.ExtraFeature;
/**
* created by ggu on Jul 17, 2014 Detailled comment
*
*/
public abstract class AbstractExtraUpdatesFactory {
public abstract void retrieveUninstalledExtraFeatures(IProgressMonitor monitor, Set<ExtraFeature> uninstalledExtraFeatures)
throws Exception;
/**
* This method is used to add an item to the set and use a specific realm if the Set is an IObservable, any
* observant be notified of the set modification.
*
* @param uninstalledExtraFeatures, The set to add the feature extraF, optionnaly an IObservable
* @param extraF, the extra feature to be added to the set
*/
protected void addToSet(final Set<ExtraFeature> uninstalledExtraFeatures, final ExtraFeature extraF) {
Runnable setExtraFeatureRunnable = new Runnable() {
@Override
public void run() {
uninstalledExtraFeatures.add(extraF);
}
};
if (uninstalledExtraFeatures instanceof IObservable) {
((IObservable) uninstalledExtraFeatures).getRealm().exec(setExtraFeatureRunnable);
} else {
setExtraFeatureRunnable.run();
}
}
}
|
UTF-8
|
Java
| 1,930 |
java
|
AbstractExtraUpdatesFactory.java
|
Java
|
[
{
"context": "tes.runtime.model.ExtraFeature;\n\n/**\n * created by ggu on Jul 17, 2014 Detailled comment\n *\n */\npublic a",
"end": 784,
"score": 0.9995841979980469,
"start": 781,
"tag": "USERNAME",
"value": "ggu"
}
] | null |
[] |
// ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.updates.runtime.engine.factory;
import java.util.Set;
import org.eclipse.core.databinding.observable.IObservable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.talend.updates.runtime.model.ExtraFeature;
/**
* created by ggu on Jul 17, 2014 Detailled comment
*
*/
public abstract class AbstractExtraUpdatesFactory {
public abstract void retrieveUninstalledExtraFeatures(IProgressMonitor monitor, Set<ExtraFeature> uninstalledExtraFeatures)
throws Exception;
/**
* This method is used to add an item to the set and use a specific realm if the Set is an IObservable, any
* observant be notified of the set modification.
*
* @param uninstalledExtraFeatures, The set to add the feature extraF, optionnaly an IObservable
* @param extraF, the extra feature to be added to the set
*/
protected void addToSet(final Set<ExtraFeature> uninstalledExtraFeatures, final ExtraFeature extraF) {
Runnable setExtraFeatureRunnable = new Runnable() {
@Override
public void run() {
uninstalledExtraFeatures.add(extraF);
}
};
if (uninstalledExtraFeatures instanceof IObservable) {
((IObservable) uninstalledExtraFeatures).getRealm().exec(setExtraFeatureRunnable);
} else {
setExtraFeatureRunnable.run();
}
}
}
| 1,930 | 0.649223 | 0.63886 | 52 | 36.115383 | 34.758869 | 127 | false | false | 0 | 0 | 0 | 0 | 84 | 0.08601 | 0.384615 | false | false |
9
|
b97bf0f0213d53a351e06a9a5eec5f101a0fa8ec
| 32,349,693,677,199 |
fa6a004491549aeab13b3a0ebb60e670b2076530
|
/src/main/java/com/bbsuper/nev/beans/enums/result/LoginCodeEnum.java
|
b44895a3a29d47b7cce602648b94f744aa080f36
|
[] |
no_license
|
terryhart/springboot-demo
|
https://github.com/terryhart/springboot-demo
|
ae9e58ff974decc38438c639a17d6a6d81612dca
|
5376f72f4fa2a00d1057e15923a525616b378a73
|
refs/heads/master
| 2020-05-17T07:17:20.572000 | 2018-11-28T07:45:25 | 2018-11-28T07:45:25 | 183,576,044 | 2 | 1 | null | true | 2019-04-26T07:03:51 | 2019-04-26T07:03:51 | 2018-11-28T07:45:27 | 2018-11-28T07:45:25 | 157 | 0 | 0 | 0 | null | false | false |
package com.bbsuper.nev.beans.enums.result;
import com.bbsuper.nev.beans.vo.common.RetCode;
/**
* 登录响应枚举
* @author liwei
* @date: 2018年10月25日 上午10:29:34
*
*/
public enum LoginCodeEnum implements RetCode{
PWD_ERR(1001,"账号或密码错误"),
IMG_CODE_ERR(1002,"验证码错误"),
LOCKING(1003,"账号被锁定,10分钟后再试"),
NOT_EXIST(1004,"账号不存在"),
DISABLED(1005,"账号或角色被禁用");
private int code;
private String msg;
@Override
public int getCode() {
return code;
}
@Override
public String getMsg() {
return msg;
}
private LoginCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
|
UTF-8
|
Java
| 700 |
java
|
LoginCodeEnum.java
|
Java
|
[
{
"context": "beans.vo.common.RetCode;\n\n/**\n * 登录响应枚举\n * @author liwei\n * @date: 2018年10月25日 上午10:29:34\n *\n */\npublic en",
"end": 124,
"score": 0.9995183348655701,
"start": 119,
"tag": "USERNAME",
"value": "liwei"
}
] | null |
[] |
package com.bbsuper.nev.beans.enums.result;
import com.bbsuper.nev.beans.vo.common.RetCode;
/**
* 登录响应枚举
* @author liwei
* @date: 2018年10月25日 上午10:29:34
*
*/
public enum LoginCodeEnum implements RetCode{
PWD_ERR(1001,"账号或密码错误"),
IMG_CODE_ERR(1002,"验证码错误"),
LOCKING(1003,"账号被锁定,10分钟后再试"),
NOT_EXIST(1004,"账号不存在"),
DISABLED(1005,"账号或角色被禁用");
private int code;
private String msg;
@Override
public int getCode() {
return code;
}
@Override
public String getMsg() {
return msg;
}
private LoginCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
| 700 | 0.671053 | 0.611842 | 43 | 13.139535 | 14.463396 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.162791 | false | false |
9
|
48fc28e9d8ded22ea7f4940e4d68cdfefc09dbba
| 18,322,330,525,397 |
f39c372dfc195abd83dc89ee9071c24d7b67c0ad
|
/src/main/java/com/arkady/utils/Constants.java
|
e5522af01f250467be898a91d471901d87a9e139
|
[] |
no_license
|
KESHAmambo/IEEE_802_11ad_beamforming_simulation
|
https://github.com/KESHAmambo/IEEE_802_11ad_beamforming_simulation
|
95f3cc3b129fd7826fd5817a4a821a085cc04401
|
4c78c95306c669343f24e62de4dfd03d0e794b2d
|
refs/heads/master
| 2021-07-10T15:13:51.077000 | 2018-06-17T12:34:23 | 2018-06-17T12:34:23 | 136,636,997 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.arkady.utils;
/**
* Created by abara on 16.05.2018.
*/
public class Constants {
/*
All transmission speeds are scaled as 1 : 1000
*/
// control PHY speed in bytes per real milly second (27500000 bytes / second)
public static final Integer CONTROL_PHY_SPEED = 27500;
public static final int SPEED_SCALE = 1000;
}
|
UTF-8
|
Java
| 354 |
java
|
Constants.java
|
Java
|
[
{
"context": "package com.arkady.utils;\n\n/**\n * Created by abara on 16.05.2018.\n */\npublic class Constants {\n /",
"end": 50,
"score": 0.9984445571899414,
"start": 45,
"tag": "USERNAME",
"value": "abara"
}
] | null |
[] |
package com.arkady.utils;
/**
* Created by abara on 16.05.2018.
*/
public class Constants {
/*
All transmission speeds are scaled as 1 : 1000
*/
// control PHY speed in bytes per real milly second (27500000 bytes / second)
public static final Integer CONTROL_PHY_SPEED = 27500;
public static final int SPEED_SCALE = 1000;
}
| 354 | 0.675141 | 0.590395 | 15 | 22.6 | 25.078012 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
9
|
aac08290a0f09bf9ecdbb888fa02c5f967d3910f
| 25,855,703,187,266 |
fde6e01af06c100a4888cde10177a61155f8c07b
|
/PropertyManagementRun/src/main/java/run/superMonkey/pm/controller/EmployeesController.java
|
5ad3883b110e40e6c818d1d0e46640925d7daa62
|
[] |
no_license
|
cjw12138/cjwrepository
|
https://github.com/cjw12138/cjwrepository
|
1b66ef2692e7a12f797e6a5942b9e738f44b1f8a
|
ffdc89a7e8e9147a2de22e6fe96981ae6f939d7b
|
refs/heads/master
| 2022-12-22T06:39:16.880000 | 2019-08-21T03:07:40 | 2019-08-21T03:07:40 | 200,985,717 | 0 | 0 | null | false | 2022-12-16T05:02:49 | 2019-08-07T06:21:15 | 2019-08-21T06:21:21 | 2022-12-16T05:02:47 | 20,899 | 0 | 0 | 5 |
JavaScript
| false | false |
package run.superMonkey.pm.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import run.superMonkey.pm.model.entity.EmployessEntity;
import run.superMonkey.pm.service.EmployeesService;
import run.superMonkey.pm.utils.ResultMessage;
@RestController
@RequestMapping("/employees/emp")
public class EmployeesController {
@Autowired
private EmployeesService es=null;
@RequestMapping("/add")
public ResultMessage<EmployessEntity> add(
@RequestParam(required = false)Integer empid,
@RequestParam(required = false)Integer deptno,
@RequestParam(required = false)String empname,
@RequestParam(required = false)String sex,
@RequestParam(required = false)Integer age,
@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date joindate,
@RequestParam(required = false)String job,
@RequestParam(required = false)String wx)throws Exception{
EmployessEntity em=new EmployessEntity();
em.setEmpid(empid);
em.setDeptno(deptno);
em.setEmpname(empname);
em.setSex(sex);
em.setAge(age);
em.setJoindate(joindate);
em.setJob(job);
em.setWx(wx);
es.insert(em);
return new ResultMessage<EmployessEntity>("OK","增加员工成功");
}
@PostMapping("/get/list")
public ResultMessage<EmployessEntity> getListByAll(
@RequestParam(required = false,defaultValue ="0") int deptno,
@RequestParam(required = false,defaultValue ="") String sex,
@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false)Date joindate,
@RequestParam(required = false,defaultValue = "1") int page,
@RequestParam(required = false,defaultValue ="10") int rows)throws Exception{
ResultMessage<EmployessEntity> result=new ResultMessage<EmployessEntity>("OK","取得员工列表分页成功");
result.setCount(es.getCountByCondition(deptno, sex, joindate));
result.setPageCount(es.getPageCountByCondition(deptno, sex, joindate, rows));
result.setList(es.getListByPage(deptno,sex,joindate,page,rows));
result.setPage(page);
result.setRows(rows);
return result;
}
//验证员工ID是否存在,如果存在则不合法,不存在则合法,用于增加员工时检查ID是否已经存在
@GetMapping(value="/checkidexist")
public boolean checkIdExist(Integer empid) throws Exception{
return !es.checkIdExist(empid);
}
}
|
UTF-8
|
Java
| 2,793 |
java
|
EmployeesController.java
|
Java
|
[] | null |
[] |
package run.superMonkey.pm.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import run.superMonkey.pm.model.entity.EmployessEntity;
import run.superMonkey.pm.service.EmployeesService;
import run.superMonkey.pm.utils.ResultMessage;
@RestController
@RequestMapping("/employees/emp")
public class EmployeesController {
@Autowired
private EmployeesService es=null;
@RequestMapping("/add")
public ResultMessage<EmployessEntity> add(
@RequestParam(required = false)Integer empid,
@RequestParam(required = false)Integer deptno,
@RequestParam(required = false)String empname,
@RequestParam(required = false)String sex,
@RequestParam(required = false)Integer age,
@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date joindate,
@RequestParam(required = false)String job,
@RequestParam(required = false)String wx)throws Exception{
EmployessEntity em=new EmployessEntity();
em.setEmpid(empid);
em.setDeptno(deptno);
em.setEmpname(empname);
em.setSex(sex);
em.setAge(age);
em.setJoindate(joindate);
em.setJob(job);
em.setWx(wx);
es.insert(em);
return new ResultMessage<EmployessEntity>("OK","增加员工成功");
}
@PostMapping("/get/list")
public ResultMessage<EmployessEntity> getListByAll(
@RequestParam(required = false,defaultValue ="0") int deptno,
@RequestParam(required = false,defaultValue ="") String sex,
@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false)Date joindate,
@RequestParam(required = false,defaultValue = "1") int page,
@RequestParam(required = false,defaultValue ="10") int rows)throws Exception{
ResultMessage<EmployessEntity> result=new ResultMessage<EmployessEntity>("OK","取得员工列表分页成功");
result.setCount(es.getCountByCondition(deptno, sex, joindate));
result.setPageCount(es.getPageCountByCondition(deptno, sex, joindate, rows));
result.setList(es.getListByPage(deptno,sex,joindate,page,rows));
result.setPage(page);
result.setRows(rows);
return result;
}
//验证员工ID是否存在,如果存在则不合法,不存在则合法,用于增加员工时检查ID是否已经存在
@GetMapping(value="/checkidexist")
public boolean checkIdExist(Integer empid) throws Exception{
return !es.checkIdExist(empid);
}
}
| 2,793 | 0.753823 | 0.752331 | 70 | 36.299999 | 25.920952 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.2 | false | false |
9
|
1daf95ca04dc243051611d10f62dbfcf39584a7a
| 17,669,495,475,511 |
6c307fc0211f98ee62a2413da50f448f1c7016aa
|
/src/com/heihei/util/AddContact.java
|
c4dced6bff2fb5bea50332664efb2ade5bf01c82
|
[] |
no_license
|
heiheisoftware/ApiDemos
|
https://github.com/heiheisoftware/ApiDemos
|
30a56dafcc47d9e6bccc66af8195b9f2b96d62ab
|
dd083eb013198230c9e47ed5ee2eae62d9d20f75
|
refs/heads/master
| 2021-01-19T03:22:20.835000 | 2017-12-13T06:16:24 | 2017-12-13T06:16:24 | 16,367,594 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//
//package com.heihei.util;
//
//import android.app.Activity;
//import android.content.ContentProviderOperation;
//import android.content.Context;
//import android.os.Bundle;
//import android.provider.ContactsContract;
//import android.util.Log;
//
//import java.io.BufferedInputStream;
//import java.io.IOException;
//import java.util.ArrayList;
//
//public class AddContact extends Activity {
// private static final String TAG = "MainActivity";
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// try {
// BufferedInputStream bis = new BufferedInputStream(getAssets().open("Mobile.txt"));
// byte[] bf = new byte[1024];
//
// StringBuilder sb = new StringBuilder();
// int count = 0;
// while (-1 != (count = bis.read(bf))) {
// sb.append(new String(bf, 0, count));
// }
//
// String[] pArr = sb.toString().split("\n");
//
// Log.d(TAG, "onCreate: " + pArr.length);
//
// for (int i = 0; i < 5; i++) {
// addContact(this, "", "", pArr[i], "", "", "", "");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// private void addContact(Context context, String name,
// String organisation, String phone, String fax, String email, String address, String website) {
//
// ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//
// //在名片表插入一个新名片
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.RawContacts.CONTENT_URI)
// .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
// .withValue(ContactsContract.RawContacts._ID, 0)
// .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
// .withValue(
// ContactsContract.RawContacts.AGGREGATION_MODE,
// ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED).build());
//
// // add name
// //添加一条新名字记录;对应RAW_CONTACT_ID为0的名片
// if (!name.equals("")) {
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(
// ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name).build());
// }
//
// //添加昵称
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
// ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, "").build());
//
// // add company
// if (!organisation.equals("")) {
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
// .withValue(
// ContactsContract.CommonDataKinds.Organization.COMPANY, organisation)
// .withValue(
// ContactsContract.CommonDataKinds.Organization.TYPE,
// ContactsContract.CommonDataKinds.Organization.TYPE_WORK).build());
// }
//
// // add phone
// if (!phone.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
// .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 1).build());
// }
//
// // add Fax
// if (!fax.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(
// ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
// ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.Phone.NUMBER, fax)
// .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
// ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK).build());
// }
//
// // add email
// if (!email.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(
// ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
// ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
// .withValue(ContactsContract.CommonDataKinds.Email.TYPE, 1).build());
// }
//
// // add address
// if (!address.equals("")) {
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(
// ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.StructuredPostal.STREET, address)
// .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
// ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK).build());
// }
//
// // add website
// if (!website.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.Website.URL, website)
// .withValue(
// ContactsContract.CommonDataKinds.Website.TYPE,
// ContactsContract.CommonDataKinds.Website.TYPE_WORK).build());
// }
//
//// // add IM
//// String qq1 = "452824089";
//// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(
//// ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
//// ContactsContract.Data.MIMETYPE,
//// ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE).withValue(
//// ContactsContract.CommonDataKinds.Im.DATA1, qq1)
//// .withValue(
//// ContactsContract.CommonDataKinds.Im.PROTOCOL,
//// ContactsContract.CommonDataKinds.Im.PROTOCOL_QQ).build());
//
// // add logo image
// // Bitmap bm = logo;
// // if (bm != null) {
// // ByteArrayOutputStream baos = new ByteArrayOutputStream();
// // bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
// // byte[] photo = baos.toByteArray();
// // if (photo != null) {
// //
// // ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// // .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// // .withValue(ContactsContract.Data.MIMETYPE,
// // ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
// // .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
// // .build());
// // }
// // }
//
// try {
// context.getContentResolver().applyBatch(
// ContactsContract.AUTHORITY, ops);
// } catch (Exception e) {
// }
//
// }
//
//}
|
UTF-8
|
Java
| 9,161 |
java
|
AddContact.java
|
Java
|
[] | null |
[] |
//
//package com.heihei.util;
//
//import android.app.Activity;
//import android.content.ContentProviderOperation;
//import android.content.Context;
//import android.os.Bundle;
//import android.provider.ContactsContract;
//import android.util.Log;
//
//import java.io.BufferedInputStream;
//import java.io.IOException;
//import java.util.ArrayList;
//
//public class AddContact extends Activity {
// private static final String TAG = "MainActivity";
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//
// try {
// BufferedInputStream bis = new BufferedInputStream(getAssets().open("Mobile.txt"));
// byte[] bf = new byte[1024];
//
// StringBuilder sb = new StringBuilder();
// int count = 0;
// while (-1 != (count = bis.read(bf))) {
// sb.append(new String(bf, 0, count));
// }
//
// String[] pArr = sb.toString().split("\n");
//
// Log.d(TAG, "onCreate: " + pArr.length);
//
// for (int i = 0; i < 5; i++) {
// addContact(this, "", "", pArr[i], "", "", "", "");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// private void addContact(Context context, String name,
// String organisation, String phone, String fax, String email, String address, String website) {
//
// ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//
// //在名片表插入一个新名片
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.RawContacts.CONTENT_URI)
// .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
// .withValue(ContactsContract.RawContacts._ID, 0)
// .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
// .withValue(
// ContactsContract.RawContacts.AGGREGATION_MODE,
// ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED).build());
//
// // add name
// //添加一条新名字记录;对应RAW_CONTACT_ID为0的名片
// if (!name.equals("")) {
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(
// ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name).build());
// }
//
// //添加昵称
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
// ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, "").build());
//
// // add company
// if (!organisation.equals("")) {
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
// .withValue(
// ContactsContract.CommonDataKinds.Organization.COMPANY, organisation)
// .withValue(
// ContactsContract.CommonDataKinds.Organization.TYPE,
// ContactsContract.CommonDataKinds.Organization.TYPE_WORK).build());
// }
//
// // add phone
// if (!phone.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
// .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 1).build());
// }
//
// // add Fax
// if (!fax.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(
// ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
// ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.Phone.NUMBER, fax)
// .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
// ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK).build());
// }
//
// // add email
// if (!email.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(
// ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
// ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
// .withValue(ContactsContract.CommonDataKinds.Email.TYPE, 1).build());
// }
//
// // add address
// if (!address.equals("")) {
// ops.add(ContentProviderOperation
// .newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(
// ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.StructuredPostal.STREET, address)
// .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
// ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK).build());
// }
//
// // add website
// if (!website.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE).withValue(
// ContactsContract.CommonDataKinds.Website.URL, website)
// .withValue(
// ContactsContract.CommonDataKinds.Website.TYPE,
// ContactsContract.CommonDataKinds.Website.TYPE_WORK).build());
// }
//
//// // add IM
//// String qq1 = "452824089";
//// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(
//// ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(
//// ContactsContract.Data.MIMETYPE,
//// ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE).withValue(
//// ContactsContract.CommonDataKinds.Im.DATA1, qq1)
//// .withValue(
//// ContactsContract.CommonDataKinds.Im.PROTOCOL,
//// ContactsContract.CommonDataKinds.Im.PROTOCOL_QQ).build());
//
// // add logo image
// // Bitmap bm = logo;
// // if (bm != null) {
// // ByteArrayOutputStream baos = new ByteArrayOutputStream();
// // bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
// // byte[] photo = baos.toByteArray();
// // if (photo != null) {
// //
// // ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// // .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// // .withValue(ContactsContract.Data.MIMETYPE,
// // ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
// // .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
// // .build());
// // }
// // }
//
// try {
// context.getContentResolver().applyBatch(
// ContactsContract.AUTHORITY, ops);
// } catch (Exception e) {
// }
//
// }
//
//}
| 9,161 | 0.562369 | 0.558193 | 184 | 47.451088 | 33.316792 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.559783 | false | false |
9
|
d79fedb161167afee4e020362a8ce5c2d7ed5506
| 12,996,571,053,104 |
dcc9e2fd943cbed63aa10f59044521a56111c53f
|
/src/main/java/dev/cammiescorner/icarus/common/items/WingItem.java
|
ceb46b4f2e80e752ed5fdd5f29d77604c0224a80
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
CammiePone/Icarus
|
https://github.com/CammiePone/Icarus
|
694851e1469d13b530cf387fbda9086593b160b0
|
a4686a51489c435dc29dbd2188109305f73c2661
|
refs/heads/1.19-dev
| 2023-08-26T13:05:22.164000 | 2023-03-09T01:21:18 | 2023-03-09T01:21:18 | 319,166,649 | 8 | 12 |
NOASSERTION
| false | 2023-08-02T19:00:10 | 2020-12-07T00:59:33 | 2023-04-01T14:08:39 | 2023-08-02T19:00:10 | 266 | 7 | 8 | 28 |
Java
| false | false |
package dev.cammiescorner.icarus.common.items;
import dev.cammiescorner.icarus.Icarus;
import dev.cammiescorner.icarus.core.integration.IcarusConfig;
import dev.cammiescorner.icarus.core.util.IcarusHelper;
import dev.cammiescorner.icarus.core.util.SlowFallEntity;
import dev.emi.trinkets.api.SlotReference;
import dev.emi.trinkets.api.TrinketItem;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.registry.Registries;
import net.minecraft.registry.tag.TagKey;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
import net.minecraft.util.Rarity;
import org.jetbrains.annotations.Nullable;
public class WingItem extends TrinketItem {
private final DyeColor primaryColour;
private final DyeColor secondaryColour;
private final WingType wingType;
private static final TagKey<Item> MELTS = TagKey.of(Registries.ITEM.getKey(), new Identifier(Icarus.MOD_ID, "melts"));
/**
* The default constructor.
*/
public WingItem(DyeColor primaryColour, DyeColor secondaryColour, WingType wingType) {
super(new Item.Settings().maxCount(1).maxDamage(IcarusConfig.wingsDurability).rarity(wingType == WingType.UNIQUE ? Rarity.EPIC : Rarity.RARE));
this.primaryColour = primaryColour;
this.secondaryColour = secondaryColour;
this.wingType = wingType;
}
public boolean isUsable(ItemStack stack) {
return IcarusConfig.wingsDurability <= 0 || stack.getDamage() < stack.getMaxDamage() - 1;
}
@Override
public void tick(ItemStack stack, SlotReference slot, LivingEntity entity) {
if(entity instanceof PlayerEntity player) {
if(Icarus.HAS_WINGS.test(player))
return;
if(player.getHungerManager().getFoodLevel() <= 6 || !isUsable(stack)) {
IcarusHelper.stopFlying(player);
return;
}
if(player.isFallFlying()) {
if(player.forwardSpeed > 0)
IcarusHelper.applySpeed(player, stack);
if((IcarusConfig.canSlowFall && player.isSneaking()) || player.isSubmergedInWater())
IcarusHelper.stopFlying(player);
if(player.getPos().y > player.world.getHeight() + 64 && player.age % 2 == 0 && stack.isIn(MELTS))
stack.damage(1, player, p -> p.sendEquipmentBreakStatus(EquipmentSlot.CHEST));
}
else {
if(player.isOnGround() || player.isTouchingWater())
((SlowFallEntity) player).setSlowFalling(false);
if(((SlowFallEntity) player).isSlowFalling()) {
player.fallDistance = 0F;
player.setVelocity(player.getVelocity().x, -0.4, player.getVelocity().z);
}
}
}
}
@Override
public boolean canRepair(ItemStack stack, ItemStack ingredient) {
return ingredient.isOf(Items.PHANTOM_MEMBRANE);
}
@Nullable
@Override
public SoundEvent getEquipSound() {
return SoundEvents.ITEM_ARMOR_EQUIP_ELYTRA;
}
public DyeColor getPrimaryColour() {
return this.primaryColour;
}
public DyeColor getSecondaryColour() {
return this.secondaryColour;
}
public WingType getWingType() {
return this.wingType;
}
public enum WingType {
FEATHERED, DRAGON, MECHANICAL_FEATHERED, MECHANICAL_LEATHER, LIGHT, UNIQUE
}
}
|
UTF-8
|
Java
| 3,303 |
java
|
WingItem.java
|
Java
|
[] | null |
[] |
package dev.cammiescorner.icarus.common.items;
import dev.cammiescorner.icarus.Icarus;
import dev.cammiescorner.icarus.core.integration.IcarusConfig;
import dev.cammiescorner.icarus.core.util.IcarusHelper;
import dev.cammiescorner.icarus.core.util.SlowFallEntity;
import dev.emi.trinkets.api.SlotReference;
import dev.emi.trinkets.api.TrinketItem;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.registry.Registries;
import net.minecraft.registry.tag.TagKey;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
import net.minecraft.util.Rarity;
import org.jetbrains.annotations.Nullable;
public class WingItem extends TrinketItem {
private final DyeColor primaryColour;
private final DyeColor secondaryColour;
private final WingType wingType;
private static final TagKey<Item> MELTS = TagKey.of(Registries.ITEM.getKey(), new Identifier(Icarus.MOD_ID, "melts"));
/**
* The default constructor.
*/
public WingItem(DyeColor primaryColour, DyeColor secondaryColour, WingType wingType) {
super(new Item.Settings().maxCount(1).maxDamage(IcarusConfig.wingsDurability).rarity(wingType == WingType.UNIQUE ? Rarity.EPIC : Rarity.RARE));
this.primaryColour = primaryColour;
this.secondaryColour = secondaryColour;
this.wingType = wingType;
}
public boolean isUsable(ItemStack stack) {
return IcarusConfig.wingsDurability <= 0 || stack.getDamage() < stack.getMaxDamage() - 1;
}
@Override
public void tick(ItemStack stack, SlotReference slot, LivingEntity entity) {
if(entity instanceof PlayerEntity player) {
if(Icarus.HAS_WINGS.test(player))
return;
if(player.getHungerManager().getFoodLevel() <= 6 || !isUsable(stack)) {
IcarusHelper.stopFlying(player);
return;
}
if(player.isFallFlying()) {
if(player.forwardSpeed > 0)
IcarusHelper.applySpeed(player, stack);
if((IcarusConfig.canSlowFall && player.isSneaking()) || player.isSubmergedInWater())
IcarusHelper.stopFlying(player);
if(player.getPos().y > player.world.getHeight() + 64 && player.age % 2 == 0 && stack.isIn(MELTS))
stack.damage(1, player, p -> p.sendEquipmentBreakStatus(EquipmentSlot.CHEST));
}
else {
if(player.isOnGround() || player.isTouchingWater())
((SlowFallEntity) player).setSlowFalling(false);
if(((SlowFallEntity) player).isSlowFalling()) {
player.fallDistance = 0F;
player.setVelocity(player.getVelocity().x, -0.4, player.getVelocity().z);
}
}
}
}
@Override
public boolean canRepair(ItemStack stack, ItemStack ingredient) {
return ingredient.isOf(Items.PHANTOM_MEMBRANE);
}
@Nullable
@Override
public SoundEvent getEquipSound() {
return SoundEvents.ITEM_ARMOR_EQUIP_ELYTRA;
}
public DyeColor getPrimaryColour() {
return this.primaryColour;
}
public DyeColor getSecondaryColour() {
return this.secondaryColour;
}
public WingType getWingType() {
return this.wingType;
}
public enum WingType {
FEATHERED, DRAGON, MECHANICAL_FEATHERED, MECHANICAL_LEATHER, LIGHT, UNIQUE
}
}
| 3,303 | 0.75719 | 0.753255 | 103 | 31.067961 | 29.023012 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.048544 | false | false |
9
|
ba15a4beb106203506fc1a8ce284b674c7e0e152
| 13,580,686,611,603 |
b3bb9529cda6f89043ba503ed37ad562dc49d720
|
/src/test/java/com/euronextclone/MatchingUnitStepDefinitions.java
|
49f969d5a1aaf1dba42f7708d4dad6a1187b2d88
|
[] |
no_license
|
mattdavey/EuronextClone
|
https://github.com/mattdavey/EuronextClone
|
de09106ca051f5a90d0ad476346842a0a8a08ca9
|
0ae7d79a2c3832b8404d3f09709074c3f0df1657
|
refs/heads/master
| 2022-07-07T15:00:15.371000 | 2020-10-14T01:34:08 | 2020-10-14T01:34:08 | 4,967,750 | 18 | 19 | null | false | 2022-06-29T15:54:44 | 2012-07-10T02:16:01 | 2022-06-24T11:49:17 | 2022-06-29T15:54:44 | 6,320 | 32 | 20 | 20 |
Java
| false | false |
package com.euronextclone;
import com.euronextclone.ordertypes.*;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.table.DataTable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class MatchingUnitStepDefinitions {
private final MatchingUnit matchingUnit;
private final List<Trade> generatedTrades;
public MatchingUnitStepDefinitions(World world) {
matchingUnit = world.getMatchingUnit();
generatedTrades = world.getGeneratedTrades();
}
@Given("^that trading mode for security is \"([^\"]*)\" and phase is \"([^\"]*)\"$")
public void that_trading_mode_for_security_is_and_phase_is(TradingMode tradingMode, TradingPhase phase) throws Throwable {
matchingUnit.setTradingMode(tradingMode);
matchingUnit.setTradingPhase(phase);
}
@Given("^that reference price is ([0-9]*\\.?[0-9]+)$")
public void that_reference_price_is_(double price) throws Throwable {
matchingUnit.setReferencePrice(price);
}
@Given("^the following orders are submitted in this order:$")
public void the_following_orders_are_submitted_in_this_order(DataTable orderTable) throws Throwable {
final List<OrderEntryRow> orderRows = orderTable.asList(OrderEntryRow.class);
for (OrderEntryRow orderRow : orderRows) {
matchingUnit.addOrder(new OrderEntry(orderRow.side, orderRow.broker, orderRow.quantity, orderRow.getOrderType()));
}
}
@When("^class auction completes$")
public void class_auction_completes() throws Throwable {
matchingUnit.auction();
}
@Then("^the calculated IMP is:$")
public void the_calculated_IMP_is(List<Double> imp) {
assertThat(matchingUnit.getIndicativeMatchingPrice(), is(imp.get(0)));
}
@Then("^the following trades are generated:$")
public void the_following_trades_are_generated(DataTable expectedTradesTable) throws Throwable {
final List<TradeRow> expectedTrades = expectedTradesTable.asList(TradeRow.class);
final List<TradeRow> actualTrades = FluentIterable.from(generatedTrades).transform(TradeRow.FROM_TRADE).toImmutableList();
assertEquals(expectedTrades, actualTrades);
generatedTrades.clear();
}
@Then("^no trades are generated$")
public void no_trades_are_generated() throws Throwable {
List<TradeRow> actualTrades = FluentIterable.from(generatedTrades).transform(TradeRow.FROM_TRADE).toImmutableList();
List<TradeRow> empty = new ArrayList<TradeRow>();
assertEquals(empty, actualTrades);
}
@Then("^the book is empty$")
public void the_book_is_empty() throws Throwable {
final List<OrderBookRow> actualBuy = FluentIterable.from(matchingUnit.getOrders(OrderSide.Buy)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
final List<OrderBookRow> actualSell = FluentIterable.from(matchingUnit.getOrders(OrderSide.Sell)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
assertEquals(new ArrayList<OrderBookRow>(), actualBuy);
assertEquals(new ArrayList<OrderBookRow>(), actualSell);
}
@Then("^the book looks like:$")
public void the_book_looks_like(DataTable expectedBooks) throws Throwable {
final List<String> headerColumns = new ArrayList<String>(expectedBooks.raw().get(0));
final int columns = headerColumns.size();
final int sideSize = columns / 2;
for (int i = 0; i < columns; i++) {
headerColumns.set(i, (i < sideSize ? "Buy " : "Sell ") + headerColumns.get(i));
}
final List<List<String>> raw = new ArrayList<List<String>>();
raw.add(headerColumns);
final List<List<String>> body = expectedBooks.raw().subList(1, expectedBooks.raw().size());
raw.addAll(body);
final DataTable montageTable = expectedBooks.toTable(raw);
final List<MontageRow> rows = montageTable.asList(MontageRow.class);
final List<OrderBookRow> expectedBids = FluentIterable.from(rows).filter(MontageRow.NON_EMPTY_BID).transform(MontageRow.TO_TEST_BID).toImmutableList();
final List<OrderBookRow> expectedAsks = FluentIterable.from(rows).filter(MontageRow.NON_EMPTY_ASK).transform(MontageRow.TO_TEST_ASK).toImmutableList();
final List<OrderBookRow> actualBuy = FluentIterable.from(matchingUnit.getOrders(OrderSide.Buy)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
final List<OrderBookRow> actualSell = FluentIterable.from(matchingUnit.getOrders(OrderSide.Sell)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
assertEquals(expectedBids, actualBuy);
assertEquals(expectedAsks, actualSell);
}
private static class MontageRow {
private String buyBroker;
private Integer buyQuantity;
private String buyPrice;
private String sellBroker;
private Integer sellQuantity;
private String sellPrice;
public static final Predicate<? super MontageRow> NON_EMPTY_BID = new Predicate<MontageRow>() {
@Override
public boolean apply(final MontageRow input) {
return input.buyBroker != null && !"".equals(input.buyBroker);
}
};
public static final Function<? super MontageRow, OrderBookRow> TO_TEST_BID = new Function<MontageRow, OrderBookRow>() {
@Override
public OrderBookRow apply(final MontageRow input) {
final OrderBookRow orderRow = new OrderBookRow();
orderRow.side = OrderSide.Buy;
orderRow.broker = input.buyBroker;
orderRow.price = input.buyPrice;
orderRow.quantity = input.buyQuantity;
return orderRow;
}
};
public static final Function<? super MontageRow, OrderBookRow> TO_TEST_ASK = new Function<MontageRow, OrderBookRow>() {
@Override
public OrderBookRow apply(final MontageRow input) {
final OrderBookRow orderRow = new OrderBookRow();
orderRow.side = OrderSide.Sell;
orderRow.broker = input.sellBroker;
orderRow.price = input.sellPrice;
orderRow.quantity = input.sellQuantity;
return orderRow;
}
};
public static final Predicate<? super MontageRow> NON_EMPTY_ASK = new Predicate<MontageRow>() {
@Override
public boolean apply(final MontageRow input) {
return input.sellBroker != null && !"".equals(input.sellBroker);
}
};
}
private static class TradeRow {
private String buyingBroker;
private String sellingBroker;
private int quantity;
private double price;
public static final Function<? super Trade, TradeRow> FROM_TRADE = new Function<Trade, TradeRow>() {
@Override
public TradeRow apply(Trade input) {
TradeRow tradeRow = new TradeRow();
tradeRow.setBuyingBroker(input.getBuyBroker());
tradeRow.setPrice(input.getPrice());
tradeRow.setQuantity(input.getQuantity());
tradeRow.setSellingBroker(input.getSellBroker());
return tradeRow;
}
};
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TradeRow tradeRow = (TradeRow) o;
if (Double.compare(tradeRow.price, price) != 0) return false;
if (quantity != tradeRow.quantity) return false;
if (!buyingBroker.equals(tradeRow.buyingBroker)) return false;
if (!sellingBroker.equals(tradeRow.sellingBroker)) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = buyingBroker.hashCode();
result = 31 * result + sellingBroker.hashCode();
result = 31 * result + quantity;
temp = price != +0.0d ? Double.doubleToLongBits(price) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public String toString() {
return "TradeRow{" +
"buyingBroker='" + buyingBroker + '\'' +
", sellingBroker='" + sellingBroker + '\'' +
", quantity=" + quantity +
", price=" + price +
'}';
}
public void setBuyingBroker(String buyingBroker) {
this.buyingBroker = buyingBroker;
}
public void setSellingBroker(String sellingBroker) {
this.sellingBroker = sellingBroker;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setPrice(double price) {
this.price = price;
}
}
private static class OrderEntryRow {
private static final Pattern PEG = Pattern.compile("Peg(?:\\[(.+)\\])?", Pattern.CASE_INSENSITIVE);
private String broker;
private OrderSide side;
private int quantity;
private String price;
public OrderType getOrderType() {
Matcher peg = PEG.matcher(price);
if (peg.matches()) {
String limit = peg.group(1);
return limit != null ? new PegWithLimit(Double.parseDouble(limit)) : new Peg();
}
if ("MTL".compareToIgnoreCase(price) == 0) {
return new MarketToLimit();
}
if ("MO".compareToIgnoreCase(price) == 0) {
return new Market();
}
return new Limit(Double.parseDouble(price));
}
}
private static class OrderBookRow {
private String broker;
private OrderSide side;
private int quantity;
private String price;
public static Function<? super Order, OrderBookRow> FROM_Order(final MatchingUnit matchingUnit) {
return new Function<Order, OrderBookRow>() {
@Override
public OrderBookRow apply(final Order order) {
final OrderSide side = order.getSide();
final OrderType orderType = order.getOrderType();
final Double bestLimit = matchingUnit.getBestLimit(side);
final OrderBookRow orderRow = new OrderBookRow();
orderRow.broker = order.getBroker();
orderRow.side = order.getSide();
Double price = orderType.price(side, matchingUnit.getBestLimit(side));
orderRow.price = orderType.displayPrice(price);
orderRow.quantity = order.getQuantity();
return orderRow;
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderBookRow orderRow = (OrderBookRow) o;
if (quantity != orderRow.quantity) return false;
if (!broker.equals(orderRow.broker)) return false;
if (price != null ? !price.equals(orderRow.price) : orderRow.price != null) return false;
if (side != orderRow.side) return false;
return true;
}
@Override
public int hashCode() {
int result = broker.hashCode();
result = 31 * result + side.hashCode();
result = 31 * result + quantity;
result = 31 * result + (price != null ? price.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "OrderBookRow{" +
"broker='" + broker + '\'' +
", side=" + side +
", quantity=" + quantity +
", price=" + price +
'}';
}
}
}
|
UTF-8
|
Java
| 12,608 |
java
|
MatchingUnitStepDefinitions.java
|
Java
|
[] | null |
[] |
package com.euronextclone;
import com.euronextclone.ordertypes.*;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.table.DataTable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class MatchingUnitStepDefinitions {
private final MatchingUnit matchingUnit;
private final List<Trade> generatedTrades;
public MatchingUnitStepDefinitions(World world) {
matchingUnit = world.getMatchingUnit();
generatedTrades = world.getGeneratedTrades();
}
@Given("^that trading mode for security is \"([^\"]*)\" and phase is \"([^\"]*)\"$")
public void that_trading_mode_for_security_is_and_phase_is(TradingMode tradingMode, TradingPhase phase) throws Throwable {
matchingUnit.setTradingMode(tradingMode);
matchingUnit.setTradingPhase(phase);
}
@Given("^that reference price is ([0-9]*\\.?[0-9]+)$")
public void that_reference_price_is_(double price) throws Throwable {
matchingUnit.setReferencePrice(price);
}
@Given("^the following orders are submitted in this order:$")
public void the_following_orders_are_submitted_in_this_order(DataTable orderTable) throws Throwable {
final List<OrderEntryRow> orderRows = orderTable.asList(OrderEntryRow.class);
for (OrderEntryRow orderRow : orderRows) {
matchingUnit.addOrder(new OrderEntry(orderRow.side, orderRow.broker, orderRow.quantity, orderRow.getOrderType()));
}
}
@When("^class auction completes$")
public void class_auction_completes() throws Throwable {
matchingUnit.auction();
}
@Then("^the calculated IMP is:$")
public void the_calculated_IMP_is(List<Double> imp) {
assertThat(matchingUnit.getIndicativeMatchingPrice(), is(imp.get(0)));
}
@Then("^the following trades are generated:$")
public void the_following_trades_are_generated(DataTable expectedTradesTable) throws Throwable {
final List<TradeRow> expectedTrades = expectedTradesTable.asList(TradeRow.class);
final List<TradeRow> actualTrades = FluentIterable.from(generatedTrades).transform(TradeRow.FROM_TRADE).toImmutableList();
assertEquals(expectedTrades, actualTrades);
generatedTrades.clear();
}
@Then("^no trades are generated$")
public void no_trades_are_generated() throws Throwable {
List<TradeRow> actualTrades = FluentIterable.from(generatedTrades).transform(TradeRow.FROM_TRADE).toImmutableList();
List<TradeRow> empty = new ArrayList<TradeRow>();
assertEquals(empty, actualTrades);
}
@Then("^the book is empty$")
public void the_book_is_empty() throws Throwable {
final List<OrderBookRow> actualBuy = FluentIterable.from(matchingUnit.getOrders(OrderSide.Buy)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
final List<OrderBookRow> actualSell = FluentIterable.from(matchingUnit.getOrders(OrderSide.Sell)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
assertEquals(new ArrayList<OrderBookRow>(), actualBuy);
assertEquals(new ArrayList<OrderBookRow>(), actualSell);
}
@Then("^the book looks like:$")
public void the_book_looks_like(DataTable expectedBooks) throws Throwable {
final List<String> headerColumns = new ArrayList<String>(expectedBooks.raw().get(0));
final int columns = headerColumns.size();
final int sideSize = columns / 2;
for (int i = 0; i < columns; i++) {
headerColumns.set(i, (i < sideSize ? "Buy " : "Sell ") + headerColumns.get(i));
}
final List<List<String>> raw = new ArrayList<List<String>>();
raw.add(headerColumns);
final List<List<String>> body = expectedBooks.raw().subList(1, expectedBooks.raw().size());
raw.addAll(body);
final DataTable montageTable = expectedBooks.toTable(raw);
final List<MontageRow> rows = montageTable.asList(MontageRow.class);
final List<OrderBookRow> expectedBids = FluentIterable.from(rows).filter(MontageRow.NON_EMPTY_BID).transform(MontageRow.TO_TEST_BID).toImmutableList();
final List<OrderBookRow> expectedAsks = FluentIterable.from(rows).filter(MontageRow.NON_EMPTY_ASK).transform(MontageRow.TO_TEST_ASK).toImmutableList();
final List<OrderBookRow> actualBuy = FluentIterable.from(matchingUnit.getOrders(OrderSide.Buy)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
final List<OrderBookRow> actualSell = FluentIterable.from(matchingUnit.getOrders(OrderSide.Sell)).transform(OrderBookRow.FROM_Order(matchingUnit)).toImmutableList();
assertEquals(expectedBids, actualBuy);
assertEquals(expectedAsks, actualSell);
}
private static class MontageRow {
private String buyBroker;
private Integer buyQuantity;
private String buyPrice;
private String sellBroker;
private Integer sellQuantity;
private String sellPrice;
public static final Predicate<? super MontageRow> NON_EMPTY_BID = new Predicate<MontageRow>() {
@Override
public boolean apply(final MontageRow input) {
return input.buyBroker != null && !"".equals(input.buyBroker);
}
};
public static final Function<? super MontageRow, OrderBookRow> TO_TEST_BID = new Function<MontageRow, OrderBookRow>() {
@Override
public OrderBookRow apply(final MontageRow input) {
final OrderBookRow orderRow = new OrderBookRow();
orderRow.side = OrderSide.Buy;
orderRow.broker = input.buyBroker;
orderRow.price = input.buyPrice;
orderRow.quantity = input.buyQuantity;
return orderRow;
}
};
public static final Function<? super MontageRow, OrderBookRow> TO_TEST_ASK = new Function<MontageRow, OrderBookRow>() {
@Override
public OrderBookRow apply(final MontageRow input) {
final OrderBookRow orderRow = new OrderBookRow();
orderRow.side = OrderSide.Sell;
orderRow.broker = input.sellBroker;
orderRow.price = input.sellPrice;
orderRow.quantity = input.sellQuantity;
return orderRow;
}
};
public static final Predicate<? super MontageRow> NON_EMPTY_ASK = new Predicate<MontageRow>() {
@Override
public boolean apply(final MontageRow input) {
return input.sellBroker != null && !"".equals(input.sellBroker);
}
};
}
private static class TradeRow {
private String buyingBroker;
private String sellingBroker;
private int quantity;
private double price;
public static final Function<? super Trade, TradeRow> FROM_TRADE = new Function<Trade, TradeRow>() {
@Override
public TradeRow apply(Trade input) {
TradeRow tradeRow = new TradeRow();
tradeRow.setBuyingBroker(input.getBuyBroker());
tradeRow.setPrice(input.getPrice());
tradeRow.setQuantity(input.getQuantity());
tradeRow.setSellingBroker(input.getSellBroker());
return tradeRow;
}
};
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TradeRow tradeRow = (TradeRow) o;
if (Double.compare(tradeRow.price, price) != 0) return false;
if (quantity != tradeRow.quantity) return false;
if (!buyingBroker.equals(tradeRow.buyingBroker)) return false;
if (!sellingBroker.equals(tradeRow.sellingBroker)) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = buyingBroker.hashCode();
result = 31 * result + sellingBroker.hashCode();
result = 31 * result + quantity;
temp = price != +0.0d ? Double.doubleToLongBits(price) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public String toString() {
return "TradeRow{" +
"buyingBroker='" + buyingBroker + '\'' +
", sellingBroker='" + sellingBroker + '\'' +
", quantity=" + quantity +
", price=" + price +
'}';
}
public void setBuyingBroker(String buyingBroker) {
this.buyingBroker = buyingBroker;
}
public void setSellingBroker(String sellingBroker) {
this.sellingBroker = sellingBroker;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setPrice(double price) {
this.price = price;
}
}
private static class OrderEntryRow {
private static final Pattern PEG = Pattern.compile("Peg(?:\\[(.+)\\])?", Pattern.CASE_INSENSITIVE);
private String broker;
private OrderSide side;
private int quantity;
private String price;
public OrderType getOrderType() {
Matcher peg = PEG.matcher(price);
if (peg.matches()) {
String limit = peg.group(1);
return limit != null ? new PegWithLimit(Double.parseDouble(limit)) : new Peg();
}
if ("MTL".compareToIgnoreCase(price) == 0) {
return new MarketToLimit();
}
if ("MO".compareToIgnoreCase(price) == 0) {
return new Market();
}
return new Limit(Double.parseDouble(price));
}
}
private static class OrderBookRow {
private String broker;
private OrderSide side;
private int quantity;
private String price;
public static Function<? super Order, OrderBookRow> FROM_Order(final MatchingUnit matchingUnit) {
return new Function<Order, OrderBookRow>() {
@Override
public OrderBookRow apply(final Order order) {
final OrderSide side = order.getSide();
final OrderType orderType = order.getOrderType();
final Double bestLimit = matchingUnit.getBestLimit(side);
final OrderBookRow orderRow = new OrderBookRow();
orderRow.broker = order.getBroker();
orderRow.side = order.getSide();
Double price = orderType.price(side, matchingUnit.getBestLimit(side));
orderRow.price = orderType.displayPrice(price);
orderRow.quantity = order.getQuantity();
return orderRow;
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderBookRow orderRow = (OrderBookRow) o;
if (quantity != orderRow.quantity) return false;
if (!broker.equals(orderRow.broker)) return false;
if (price != null ? !price.equals(orderRow.price) : orderRow.price != null) return false;
if (side != orderRow.side) return false;
return true;
}
@Override
public int hashCode() {
int result = broker.hashCode();
result = 31 * result + side.hashCode();
result = 31 * result + quantity;
result = 31 * result + (price != null ? price.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "OrderBookRow{" +
"broker='" + broker + '\'' +
", side=" + side +
", quantity=" + quantity +
", price=" + price +
'}';
}
}
}
| 12,608 | 0.61112 | 0.608661 | 318 | 38.650944 | 34.48563 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584906 | false | false |
9
|
1cf7e4f56ecac9d47d802a35c195af3e760d742f
| 27,650,999,522,093 |
80f8f8a6f2076befb7a930edbbdff4f19d3af3eb
|
/java开发相关/spring-javaconfig/SpringMVC基本功能/java/exception/VoControllerAdvice.java
|
b0511c800e1d187324cd730abe89b74381eb1a68
|
[] |
no_license
|
blowind/note_of_learn
|
https://github.com/blowind/note_of_learn
|
8d8822fb6e1015430b71bc946b184d40442791a2
|
302e6def5d93604157c86f68ec92e710fcd41bb5
|
refs/heads/master
| 2022-12-22T14:01:59.943000 | 2021-05-18T02:29:41 | 2021-05-18T02:29:41 | 108,507,926 | 1 | 2 | null | false | 2022-12-15T23:27:26 | 2017-10-27T06:27:56 | 2021-05-18T02:29:57 | 2022-12-15T23:27:23 | 3,061 | 1 | 0 | 16 |
Java
| false | false |
package com.zxf.springmvc.exception;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName: VoControllerAdvice
* @Description: 定义控制器通知来处理异常
* @Author: ZhangXuefeng
* @Date: 2018/12/3 23:40
* @Version: 1.0
**/
/*ControllerAdvice表示定义一个控制器通知*/
@ControllerAdvice(
/*指定拦截包*/
basePackages = {"com.zxf.springmvc.controller.*"},
/*限定被标注为@Controller或者@RestController的类才能被拦截*/
annotations = {Controller.class, RestController.class})
public class VoControllerAdvice {
/*@ExceptionHandler注解指定捕获异常后的处理方法*/
/*异常处理,可以定义异常类型进行拦截处理,此处指定拦截NotFoundException异常*/
@ExceptionHandler(value = NotFoundException.class)
/*拦截异常后以JSON的方式作为响应返回给前端*/
@ResponseBody
/*定义服务器错误状态码*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> exception(HttpServletRequest request, NotFoundException ex) {
Map<String, Object> msgMap = new HashMap<>();
msgMap.put("code", ex.getCode());
msgMap.put("message", ex.getCustomMessage());
return msgMap;
}
}
|
UTF-8
|
Java
| 1,471 |
java
|
VoControllerAdvice.java
|
Java
|
[
{
"context": "erAdvice\n * @Description: 定义控制器通知来处理异常\n * @Author: ZhangXuefeng\n * @Date: 2018/12/3 23:40\n * @Version: 1.0\n **/\n/",
"end": 370,
"score": 0.9998098015785217,
"start": 358,
"tag": "NAME",
"value": "ZhangXuefeng"
}
] | null |
[] |
package com.zxf.springmvc.exception;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName: VoControllerAdvice
* @Description: 定义控制器通知来处理异常
* @Author: ZhangXuefeng
* @Date: 2018/12/3 23:40
* @Version: 1.0
**/
/*ControllerAdvice表示定义一个控制器通知*/
@ControllerAdvice(
/*指定拦截包*/
basePackages = {"com.zxf.springmvc.controller.*"},
/*限定被标注为@Controller或者@RestController的类才能被拦截*/
annotations = {Controller.class, RestController.class})
public class VoControllerAdvice {
/*@ExceptionHandler注解指定捕获异常后的处理方法*/
/*异常处理,可以定义异常类型进行拦截处理,此处指定拦截NotFoundException异常*/
@ExceptionHandler(value = NotFoundException.class)
/*拦截异常后以JSON的方式作为响应返回给前端*/
@ResponseBody
/*定义服务器错误状态码*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> exception(HttpServletRequest request, NotFoundException ex) {
Map<String, Object> msgMap = new HashMap<>();
msgMap.put("code", ex.getCode());
msgMap.put("message", ex.getCustomMessage());
return msgMap;
}
}
| 1,471 | 0.721285 | 0.710843 | 39 | 30.923077 | 21.365421 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
9
|
176d233d277459c6d86c0df6c7e8ec96ceab0f7d
| 23,948,737,690,199 |
65feb54ce508dcb456daab274a8dbfce0850ce63
|
/src/org/valachi_maas/finalFight/NodeDef.java
|
97931dd292d4a309ea8781d89f64f1feaf551d50
|
[] |
no_license
|
Chainmanner/Java-Grade12-TheShootout-TopDownShooter
|
https://github.com/Chainmanner/Java-Grade12-TheShootout-TopDownShooter
|
973462567ebfdf224a4b58f7a1279061a2183725
|
e9a27fdf831d572ff4020c1346e6623b4baffeca
|
refs/heads/master
| 2020-03-29T08:23:28.958000 | 2019-12-16T00:31:09 | 2019-12-16T00:31:09 | 149,708,721 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.valachi_maas.finalFight;
import java.util.ArrayList;
enum node_t
{
PATH,
COVER
}
/**
* Node to which an NPC can go to, in order to find its way around.
* @author Gabriel Valachi
* @author Anthony Maas
*/
public class NodeDef implements Comparable<Object>
{
public float m_fXPos, m_fYPos;
public int m_iNodeID;
public node_t m_eType;
public ArrayList<NodeDef> m_hLinkedNodes = new ArrayList<NodeDef>();
/**
* Constructor.
* Preconditions:
* - x and y >= [min 32-bit integer] and <= [max 32-bit integer].
* @param id - Node ID.
* @param x - X coordinate.
* @param y - Y coordinate.
* @param type - Type of node. Can be a path or cover node.
*/
public NodeDef( int id, float x, float y, node_t type )
{
m_iNodeID = id;
m_fXPos = x;
m_fYPos = y;
m_eType = type;
}
/**
* Compares this node's ID to another's.
* Preconditions:
* - obj is a NodeDef instance.
* Postconditions:
* - Returns 0 if this node's ID is equal to the other's,
* -1 if it's smaller, or
* 1 if it's greater.
*/
@Override
public int compareTo( Object obj )
{
Utils.Assert( obj instanceof NodeDef );
NodeDef node = (NodeDef)obj;
if ( node.m_iNodeID == this.m_iNodeID )
return 0;
else if ( node.m_iNodeID < this.m_iNodeID )
return 1;
else
return -1;
}
/**
* Returns this node in the form of a String.
* No preconditions.
* Postconditions:
* - Returns the node type, ID, and coordinates as a String.
*/
@Override
public String toString()
{
return "[" +(m_eType == node_t.PATH ? "PATH" : "COVER")
+ "|ID: " + m_iNodeID
+ "|X: " + m_fXPos + " Y: " + m_fYPos + "]";
}
}
|
UTF-8
|
Java
| 1,740 |
java
|
NodeDef.java
|
Java
|
[
{
"context": "o to, in order to find its way around.\r\n * @author Gabriel Valachi\r\n * @author Anthony Maas\r\n */\r\npublic class NodeD",
"end": 208,
"score": 0.9998831748962402,
"start": 193,
"tag": "NAME",
"value": "Gabriel Valachi"
},
{
"context": "ay around.\r\n * @author Gabriel Valachi\r\n * @author Anthony Maas\r\n */\r\npublic class NodeDef implements Comparable<",
"end": 233,
"score": 0.9998733401298523,
"start": 221,
"tag": "NAME",
"value": "Anthony Maas"
}
] | null |
[] |
package org.valachi_maas.finalFight;
import java.util.ArrayList;
enum node_t
{
PATH,
COVER
}
/**
* Node to which an NPC can go to, in order to find its way around.
* @author <NAME>
* @author <NAME>
*/
public class NodeDef implements Comparable<Object>
{
public float m_fXPos, m_fYPos;
public int m_iNodeID;
public node_t m_eType;
public ArrayList<NodeDef> m_hLinkedNodes = new ArrayList<NodeDef>();
/**
* Constructor.
* Preconditions:
* - x and y >= [min 32-bit integer] and <= [max 32-bit integer].
* @param id - Node ID.
* @param x - X coordinate.
* @param y - Y coordinate.
* @param type - Type of node. Can be a path or cover node.
*/
public NodeDef( int id, float x, float y, node_t type )
{
m_iNodeID = id;
m_fXPos = x;
m_fYPos = y;
m_eType = type;
}
/**
* Compares this node's ID to another's.
* Preconditions:
* - obj is a NodeDef instance.
* Postconditions:
* - Returns 0 if this node's ID is equal to the other's,
* -1 if it's smaller, or
* 1 if it's greater.
*/
@Override
public int compareTo( Object obj )
{
Utils.Assert( obj instanceof NodeDef );
NodeDef node = (NodeDef)obj;
if ( node.m_iNodeID == this.m_iNodeID )
return 0;
else if ( node.m_iNodeID < this.m_iNodeID )
return 1;
else
return -1;
}
/**
* Returns this node in the form of a String.
* No preconditions.
* Postconditions:
* - Returns the node type, ID, and coordinates as a String.
*/
@Override
public String toString()
{
return "[" +(m_eType == node_t.PATH ? "PATH" : "COVER")
+ "|ID: " + m_iNodeID
+ "|X: " + m_fXPos + " Y: " + m_fYPos + "]";
}
}
| 1,725 | 0.593678 | 0.587931 | 75 | 21.200001 | 19.608841 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.586667 | false | false |
9
|
72960afbb3ebed888061811fc99b97eb887db12e
| 25,821,343,399,897 |
b4e6d277f7aafdb1085c288e75512dfb7c2f82a0
|
/mms/src/main/java/global/sesoc/mms/dao/MemberRepository.java
|
6eb5507a2d38480049cef54ef04f2d7c77e7cbfd
|
[] |
no_license
|
10000co/mms
|
https://github.com/10000co/mms
|
6f151b45ef108b4c2136c44a2b1ab8f90b662a3e
|
0d6df1764bb59656680931a1145cfe9015a0c38e
|
refs/heads/master
| 2020-03-24T10:37:36.473000 | 2018-08-09T06:08:51 | 2018-08-09T06:08:51 | 142,662,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package global.sesoc.mms.dao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import global.sesoc.mms.dto.Members;
@Repository
public class MemberRepository {
@Autowired
SqlSession session;
/**
* 회원 가입
* @param member
* @return int 회원가입처리
*/
public int insertMember(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
int result = mapper.insertMember(member);
return result;
}
/**
* 아이디 중복확인, 로그인
* @param member
* @return 조회된 member
*/
public Members selectMember(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
Members result = mapper.selectMember(member);
return result;
}
public int updateMember(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
int result = mapper.updateMember(member);
return result;
}
public Members selectMemberInfo(String userid) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
Members result = mapper.selectMemberInfo(userid);
return result;
}
public Members memberChkPwd(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
Members result = mapper.selectMember(member);
return result;
}
}
|
UTF-8
|
Java
| 1,451 |
java
|
MemberRepository.java
|
Java
|
[] | null |
[] |
package global.sesoc.mms.dao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import global.sesoc.mms.dto.Members;
@Repository
public class MemberRepository {
@Autowired
SqlSession session;
/**
* 회원 가입
* @param member
* @return int 회원가입처리
*/
public int insertMember(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
int result = mapper.insertMember(member);
return result;
}
/**
* 아이디 중복확인, 로그인
* @param member
* @return 조회된 member
*/
public Members selectMember(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
Members result = mapper.selectMember(member);
return result;
}
public int updateMember(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
int result = mapper.updateMember(member);
return result;
}
public Members selectMemberInfo(String userid) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
Members result = mapper.selectMemberInfo(userid);
return result;
}
public Members memberChkPwd(Members member) {
MemberMapper mapper = session.getMapper(MemberMapper.class);
Members result = mapper.selectMember(member);
return result;
}
}
| 1,451 | 0.712456 | 0.712456 | 60 | 21.416666 | 21.623514 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.483333 | false | false |
9
|
7dad79933bc12172055604af003198384e49fd8c
| 29,961,691,903,176 |
70be9a9b22e35ad7a2de0c99758c5202f14e0b1d
|
/main-ms/src/main/java/com/vidnichuk/isogj/impl/client/AuthServiceClient.java
|
65b07e55724559363f91a517d390517b67c0e1bd
|
[] |
no_license
|
DrGrave/SoDDRM
|
https://github.com/DrGrave/SoDDRM
|
90d942ec8161b16b68eafed99be6254ddcbf399f
|
026dd037bf14424e368c5b7416ef3a752e5ce89a
|
refs/heads/master
| 2021-10-22T13:56:44.569000 | 2019-03-11T10:38:06 | 2019-03-11T10:38:06 | 174,976,187 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vidnichuk.isogj.impl.client;
import com.vidnichuk.isogj.api.dto.model.AuthUserDto;
import com.vidnichuk.isogj.api.dto.model.UserDto;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "oauth-ms")
public interface AuthServiceClient {
@RequestMapping(method = RequestMethod.POST, value = "/users/create", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(AuthUserDto user);
}
|
UTF-8
|
Java
| 611 |
java
|
AuthServiceClient.java
|
Java
|
[] | null |
[] |
package com.vidnichuk.isogj.impl.client;
import com.vidnichuk.isogj.api.dto.model.AuthUserDto;
import com.vidnichuk.isogj.api.dto.model.UserDto;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "oauth-ms")
public interface AuthServiceClient {
@RequestMapping(method = RequestMethod.POST, value = "/users/create", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(AuthUserDto user);
}
| 611 | 0.810147 | 0.808511 | 16 | 37.1875 | 31.94178 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
9
|
7b932d91fa9bfa9a825104761d17bc839a585dd1
| 25,108,378,871,701 |
f40824375d99acc1c3d3b55da5c1ef89bfa228d0
|
/tableview/src/main/java/com/evrencoskun/tableview/adapter/recyclerview/CellRecyclerViewAdapter.java
|
a446600687515b0bd2793ef32669d9083136a204
|
[
"MIT"
] |
permissive
|
adithyarao1/TableView
|
https://github.com/adithyarao1/TableView
|
ae76228b6cbea2b56e5f39a17732efafbc73d5f3
|
aeb424c273293b8b2c65c563494537c3c1ca2b08
|
refs/heads/master
| 2021-07-03T12:57:04.897000 | 2017-09-25T20:52:23 | 2017-09-25T20:52:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.evrencoskun.tableview.adapter.recyclerview;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.evrencoskun.tableview.R;
import com.evrencoskun.tableview.adapter.ITableAdapter;
import com.evrencoskun.tableview.layoutmanager.ColumnLayoutManager;
import com.evrencoskun.tableview.listener.HorizontalRecyclerViewListener;
import java.util.ArrayList;
import java.util.List;
/**
* Created by evrencoskun on 10/06/2017.
*/
public class CellRecyclerViewAdapter<C> extends AbstractRecyclerViewAdapter<C> {
private static final String LOG_TAG = CellRecyclerViewAdapter.class.getSimpleName();
private List<RecyclerView.Adapter> m_jAdapterList;
private ITableAdapter m_iTableAdapter;
private final DividerItemDecoration m_jCellItemDecoration;
private HorizontalRecyclerViewListener m_iHorizontalListener;
// This is for testing purpose
private int m_nRecyclerViewId = 0;
public CellRecyclerViewAdapter(Context context, List<C> p_jItemList, ITableAdapter
p_iTableAdapter) {
super(context, p_jItemList);
this.m_iTableAdapter = p_iTableAdapter;
// Initialize the array
m_jAdapterList = new ArrayList<>();
// Create Item decoration
m_jCellItemDecoration = createCellItemDecoration();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a RecyclerView as a Row of the CellRecyclerView
final CellRecyclerView jRecyclerView = new CellRecyclerView(m_jContext);
// Add divider
jRecyclerView.addItemDecoration(m_jCellItemDecoration);
if (m_iTableAdapter.getTableView() != null) {
// set touch m_iHorizontalListener to scroll synchronously
if (m_iHorizontalListener == null) {
m_iHorizontalListener = m_iTableAdapter.getTableView()
.getHorizontalRecyclerViewListener();
}
jRecyclerView.addOnItemTouchListener(m_iHorizontalListener);
// Set the Column layout manager that helps the fit width of the cell and column header
// and it also helps to locate the scroll position of the horizontal recyclerView
// which is row recyclerView
ColumnLayoutManager layoutManager = new ColumnLayoutManager(m_jContext,
m_iTableAdapter.getTableView(), jRecyclerView);
jRecyclerView.setLayoutManager(layoutManager);
// This is for testing purpose to find out which recyclerView is displayed.
jRecyclerView.setId(m_nRecyclerViewId);
m_nRecyclerViewId++;
}
return new CellRowViewHolder(jRecyclerView);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int p_nYPosition) {
if (!(holder instanceof CellRowViewHolder)) {
return;
}
CellRowViewHolder viewHolder = (CellRowViewHolder) holder;
// Set adapter to the RecyclerView
List<C> rowList = (List<C>) m_jItemList.get(p_nYPosition);
CellRowRecyclerViewAdapter viewAdapter = new CellRowRecyclerViewAdapter(m_jContext,
rowList, m_iTableAdapter, viewHolder.m_jRecyclerView, p_nYPosition);
viewHolder.m_jRecyclerView.setAdapter(viewAdapter);
// Add the adapter to the list
m_jAdapterList.add(viewAdapter);
}
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
// The below code helps to display a new attached recyclerView on exact scrolled position.
CellRowViewHolder viewHolder = (CellRowViewHolder) holder;
((ColumnLayoutManager) viewHolder.m_jRecyclerView.getLayoutManager())
.scrollToPositionWithOffset(m_iHorizontalListener.getScrollPosition(),
m_iHorizontalListener.getScrollPositionOffset());
}
@Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
CellRowViewHolder viewHolder = (CellRowViewHolder) holder;
// ScrolledX should be cleared at that time. Because we need to prepare each recyclerView
// at onViewAttachedToWindow process.
viewHolder.m_jRecyclerView.clearScrolledX();
}
public static class CellRowViewHolder extends RecyclerView.ViewHolder {
public final CellRecyclerView m_jRecyclerView;
public CellRowViewHolder(View itemView) {
super(itemView);
m_jRecyclerView = (CellRecyclerView) itemView;
}
}
private DividerItemDecoration createCellItemDecoration() {
Drawable mDivider = ContextCompat.getDrawable(m_jContext, R.drawable.cell_line_divider);
DividerItemDecoration jItemDecoration = new DividerItemDecoration(m_jContext,
DividerItemDecoration.HORIZONTAL);
jItemDecoration.setDrawable(mDivider);
return jItemDecoration;
}
public void notifyCellDataSetChanged() {
if (m_jAdapterList != null && !m_jAdapterList.isEmpty()) {
for (RecyclerView.Adapter adapter : m_jAdapterList) {
adapter.notifyDataSetChanged();
}
}
}
}
|
UTF-8
|
Java
| 5,516 |
java
|
CellRecyclerViewAdapter.java
|
Java
|
[
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by evrencoskun on 10/06/2017.\n */\n\npublic class CellRecyclerView",
"end": 658,
"score": 0.9997255206108093,
"start": 647,
"tag": "USERNAME",
"value": "evrencoskun"
}
] | null |
[] |
package com.evrencoskun.tableview.adapter.recyclerview;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.evrencoskun.tableview.R;
import com.evrencoskun.tableview.adapter.ITableAdapter;
import com.evrencoskun.tableview.layoutmanager.ColumnLayoutManager;
import com.evrencoskun.tableview.listener.HorizontalRecyclerViewListener;
import java.util.ArrayList;
import java.util.List;
/**
* Created by evrencoskun on 10/06/2017.
*/
public class CellRecyclerViewAdapter<C> extends AbstractRecyclerViewAdapter<C> {
private static final String LOG_TAG = CellRecyclerViewAdapter.class.getSimpleName();
private List<RecyclerView.Adapter> m_jAdapterList;
private ITableAdapter m_iTableAdapter;
private final DividerItemDecoration m_jCellItemDecoration;
private HorizontalRecyclerViewListener m_iHorizontalListener;
// This is for testing purpose
private int m_nRecyclerViewId = 0;
public CellRecyclerViewAdapter(Context context, List<C> p_jItemList, ITableAdapter
p_iTableAdapter) {
super(context, p_jItemList);
this.m_iTableAdapter = p_iTableAdapter;
// Initialize the array
m_jAdapterList = new ArrayList<>();
// Create Item decoration
m_jCellItemDecoration = createCellItemDecoration();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a RecyclerView as a Row of the CellRecyclerView
final CellRecyclerView jRecyclerView = new CellRecyclerView(m_jContext);
// Add divider
jRecyclerView.addItemDecoration(m_jCellItemDecoration);
if (m_iTableAdapter.getTableView() != null) {
// set touch m_iHorizontalListener to scroll synchronously
if (m_iHorizontalListener == null) {
m_iHorizontalListener = m_iTableAdapter.getTableView()
.getHorizontalRecyclerViewListener();
}
jRecyclerView.addOnItemTouchListener(m_iHorizontalListener);
// Set the Column layout manager that helps the fit width of the cell and column header
// and it also helps to locate the scroll position of the horizontal recyclerView
// which is row recyclerView
ColumnLayoutManager layoutManager = new ColumnLayoutManager(m_jContext,
m_iTableAdapter.getTableView(), jRecyclerView);
jRecyclerView.setLayoutManager(layoutManager);
// This is for testing purpose to find out which recyclerView is displayed.
jRecyclerView.setId(m_nRecyclerViewId);
m_nRecyclerViewId++;
}
return new CellRowViewHolder(jRecyclerView);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int p_nYPosition) {
if (!(holder instanceof CellRowViewHolder)) {
return;
}
CellRowViewHolder viewHolder = (CellRowViewHolder) holder;
// Set adapter to the RecyclerView
List<C> rowList = (List<C>) m_jItemList.get(p_nYPosition);
CellRowRecyclerViewAdapter viewAdapter = new CellRowRecyclerViewAdapter(m_jContext,
rowList, m_iTableAdapter, viewHolder.m_jRecyclerView, p_nYPosition);
viewHolder.m_jRecyclerView.setAdapter(viewAdapter);
// Add the adapter to the list
m_jAdapterList.add(viewAdapter);
}
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
// The below code helps to display a new attached recyclerView on exact scrolled position.
CellRowViewHolder viewHolder = (CellRowViewHolder) holder;
((ColumnLayoutManager) viewHolder.m_jRecyclerView.getLayoutManager())
.scrollToPositionWithOffset(m_iHorizontalListener.getScrollPosition(),
m_iHorizontalListener.getScrollPositionOffset());
}
@Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
CellRowViewHolder viewHolder = (CellRowViewHolder) holder;
// ScrolledX should be cleared at that time. Because we need to prepare each recyclerView
// at onViewAttachedToWindow process.
viewHolder.m_jRecyclerView.clearScrolledX();
}
public static class CellRowViewHolder extends RecyclerView.ViewHolder {
public final CellRecyclerView m_jRecyclerView;
public CellRowViewHolder(View itemView) {
super(itemView);
m_jRecyclerView = (CellRecyclerView) itemView;
}
}
private DividerItemDecoration createCellItemDecoration() {
Drawable mDivider = ContextCompat.getDrawable(m_jContext, R.drawable.cell_line_divider);
DividerItemDecoration jItemDecoration = new DividerItemDecoration(m_jContext,
DividerItemDecoration.HORIZONTAL);
jItemDecoration.setDrawable(mDivider);
return jItemDecoration;
}
public void notifyCellDataSetChanged() {
if (m_jAdapterList != null && !m_jAdapterList.isEmpty()) {
for (RecyclerView.Adapter adapter : m_jAdapterList) {
adapter.notifyDataSetChanged();
}
}
}
}
| 5,516 | 0.701414 | 0.699239 | 147 | 36.523811 | 30.961317 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.455782 | false | false |
9
|
c844bf67499f454e0afd21b8787f120d572a7aeb
| 25,108,378,873,093 |
8a9fec362586db291e34c4fdec30c319a83fe654
|
/src/oopc15/ue1/businesslogic/Bird.java
|
3dc4f5f80cd7b0ed1e23e49920d77f1888b7c959
|
[] |
no_license
|
fabs04/OOP1
|
https://github.com/fabs04/OOP1
|
1e9291ee5a657b21c84e64b06acee97e232eb970
|
75656bd8bc2d20d8ac293a3fe88df5ce7c7d360e
|
refs/heads/master
| 2020-03-31T16:52:22.229000 | 2018-10-10T11:15:19 | 2018-10-10T11:15:19 | 152,395,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package oopc15.ue1.businesslogic;
import oopc15.ue1.interfaces.IPoint;
import java.util.LinkedList;
public class Bird {
private IPoint position;
private LinkedList<Bird> neighbors;
public Bird(IPoint position){
this.position = position;
}
private void notifyNeighbors(){
for(Bird bird : neighbors){
bird.onNeighborPosChanged();
}
}
private void onNeighborPosChanged(){
}
}
|
UTF-8
|
Java
| 448 |
java
|
Bird.java
|
Java
|
[] | null |
[] |
package oopc15.ue1.businesslogic;
import oopc15.ue1.interfaces.IPoint;
import java.util.LinkedList;
public class Bird {
private IPoint position;
private LinkedList<Bird> neighbors;
public Bird(IPoint position){
this.position = position;
}
private void notifyNeighbors(){
for(Bird bird : neighbors){
bird.onNeighborPosChanged();
}
}
private void onNeighborPosChanged(){
}
}
| 448 | 0.658482 | 0.645089 | 24 | 17.666666 | 16.239527 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291667 | false | false |
9
|
35601fe7598aeb0372aae4d05f66030cf559e43a
| 32,615,981,695,177 |
01927e2f7f50121aeecde7b70343046500024e4d
|
/poc-hdfs-etc/src/main/java/org/galatea/pochdfs/entrypoint/HdfsWriterRestController.java
|
a40d635dd7b3e53b9e625244128e2cbb2f63c158
|
[] |
no_license
|
galatea-associates/poc-hdfs-etc
|
https://github.com/galatea-associates/poc-hdfs-etc
|
9109168e61251a5cebc23987779737db9c2583bb
|
4b6e041d8aa27e76650dff8f2b12e5ffea5936ea
|
refs/heads/master
| 2023-04-27T15:45:09.639000 | 2019-08-07T20:50:11 | 2019-08-07T20:50:11 | 191,573,803 | 0 | 0 | null | false | 2023-04-21T20:43:28 | 2019-06-12T13:13:13 | 2019-08-07T20:50:23 | 2023-04-21T20:43:27 | 1,022 | 0 | 0 | 2 |
Java
| false | false |
package org.galatea.pochdfs.entrypoint;
import org.galatea.pochdfs.service.writer.SwapDataWriterService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
//@RestController
public class HdfsWriterRestController {
private final SwapDataWriterService writer;
@PostMapping(value = "/write", produces = { MediaType.ALL_VALUE })
public ResponseEntity<String> writeEndpoint(
@RequestParam(value = "filePath", required = true) final String filePath) {
try {
writer.writeData(filePath);
return new ResponseEntity<>("Write Swap Data to Local Succeeded", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|
UTF-8
|
Java
| 997 |
java
|
HdfsWriterRestController.java
|
Java
|
[] | null |
[] |
package org.galatea.pochdfs.entrypoint;
import org.galatea.pochdfs.service.writer.SwapDataWriterService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
//@RestController
public class HdfsWriterRestController {
private final SwapDataWriterService writer;
@PostMapping(value = "/write", produces = { MediaType.ALL_VALUE })
public ResponseEntity<String> writeEndpoint(
@RequestParam(value = "filePath", required = true) final String filePath) {
try {
writer.writeData(filePath);
return new ResponseEntity<>("Write Swap Data to Local Succeeded", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| 997 | 0.770311 | 0.770311 | 29 | 32.379311 | 27.345066 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.310345 | false | false |
9
|
553b96c9a65b55b0ac9d5051ea10703a81da91dc
| 26,079,041,427,690 |
e169a7b36da0054663e1e977136af49933e5c396
|
/src/main/java/ru/iopump/jdbi/cucumber/DbHelper.java
|
f92d50417fb5b2b10f5100277e8867171eb46e54
|
[] |
no_license
|
kochetkov-ma/jdbi-crud
|
https://github.com/kochetkov-ma/jdbi-crud
|
0cedbdecb84770f1d0e6403ec108243cdb1932ea
|
11dd0043aca42f5d1c169bbce529851f68611498
|
refs/heads/master
| 2020-05-19T19:26:44.557000 | 2019-05-06T11:15:14 | 2019-05-06T11:15:14 | 185,180,511 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ru.iopump.jdbi.cucumber;
import static java.lang.String.format;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import com.google.common.collect.Maps;
import io.cucumber.datatable.DataTable;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.sqlobject.config.RegisterBeanMapper;
import ru.iopump.jdbi.db.dao.CrudDao;
import ru.iopump.jdbi.db.dao.Dao;
import ru.iopump.jdbi.db.dao.DaoCondition;
import ru.iopump.jdbi.db.dao.DaoConditionChain;
import ru.iopump.jdbi.db.entity.Entity;
import ru.iopump.jdbi.db.exception.DbException;
import ru.iopump.jdbi.util.ReflectionUtils;
@SuppressWarnings("unused")
public class DbHelper {
private final String[] daoPackages;
private final Object DAO_CLASSES_LOCK = new Object();
private Map<String, Class<? extends CrudDao>> DAO_CLASSES_CACHE;
public DbHelper(String... daoPackages) {
this.daoPackages = daoPackages;
}
/**
* Превратить cucumber Пример вида 'имя колонки|значение' в карту вида [имя колонки : значение].
*
* @param dataTable Пример cucumber.
*/
public static Map<String, String> asMap(@Nullable DataTable dataTable) {
if (dataTable == null) {
return Maps.newHashMap();
}
return dataTable.asMap(String.class, String.class);
}
/**
* Загрузить {@link CrudDao} по имени таблицы.
* Имя таблицы проверяется в первую очередь, если имеется аннотация {@link Dao}, если аннотации нет (или значение пустое),
* то вызывается метод {@link CrudDao#getTableName()}.
*/
@NonNull
public <DAO extends CrudDao> DAO loadDaoByTableName(@NonNull Jdbi jdbi,
@Nullable String table) {
synchronized (DAO_CLASSES_LOCK) {
if (DAO_CLASSES_CACHE == null) {
DAO_CLASSES_CACHE = ReflectionUtils.getAllClasses(CrudDao.class, daoPackages)
.stream()
.filter(i -> i != CrudDao.class)
.map(this::getTableClass)
.filter(Objects::nonNull)
.collect(Collectors.toMap(Pair::getKey,
Pair::getValue,
(one, two) -> {
// если есть Dao аннотация, то использовать именно этот класс в первую очередь.
if (two.isAnnotationPresent(Dao.class)) {
return two;
} else {
return one;
}
}));
}
}
final Class<? extends CrudDao> cls = DAO_CLASSES_CACHE.get(StringUtils.upperCase(table));
if (cls == null) {
throw new IllegalArgumentException(format("Не найдено CrudDao для таблицы %s в пакете %s",
table,
Arrays.toString(daoPackages))
);
}
//noinspection unchecked
return (DAO) jdbi.onDemand(cls);
}
/**
* Получить класс сущености, чтобы потом создать его через отражение.
*/
public <ENTITY extends Entity> Class<ENTITY> getEntityClass(@NonNull final CrudDao crudDao) {
Class clz;
if (Proxy.isProxyClass(crudDao.getClass())) {
clz = crudDao.getClass().getInterfaces()[0];
} else {
clz = crudDao.getClass();
}
if (clz.isAnnotationPresent(Dao.class)) {
Class res = ((Dao) clz.getAnnotation(Dao.class)).entityClass();
if (res != Entity.class) {
//noinspection unchecked
return (Class<ENTITY>) res;
}
}
if (clz.isAnnotationPresent(RegisterBeanMapper.class)) {
//noinspection unchecked
return (Class<ENTITY>) ((RegisterBeanMapper) clz.getAnnotation(RegisterBeanMapper.class)).value();
}
throw new DbException(format("Для DAO %s не удается получить класс ENTITY. " +
"Проверьте наличие аннотаций : Dao или RegisterBeanMapper", clz));
}
@NonNull
public DaoConditionChain dataTableToConditionals(@NonNull DataTable dataTable) {
return dataTable.asLists(Object.class)
.stream()
.map(row -> {
if (row.size() == 2) {
return DaoCondition.equal((String) row.get(0), row.get(1));
} else if (row.size() == 3) {
return new DaoCondition((String) row.get(0), (String) row.get(1), row.get(2));
} else {
throw new IllegalArgumentException(format("Ряд %s должн быть рамером 2 или 3",
Objects.toString(row)));
}
})
.reduce(new DaoConditionChain(), DaoConditionChain::and, (one, two) -> two);
}
//region Private
@Nullable
private Pair<String, Class<? extends CrudDao>> getTableClass(@NonNull Class<? extends CrudDao> crudDaoClass) {
String tableName = null;
if (crudDaoClass.isAnnotationPresent(Dao.class)) {
if (!crudDaoClass.getAnnotation(Dao.class).include()) {
return null;
}
if (!StringUtils.isBlank(crudDaoClass.getAnnotation(Dao.class).tableName())) {
tableName = crudDaoClass.getAnnotation(Dao.class).tableName();
}
}
if (tableName == null) {
try {
final CrudDao proxy = (CrudDao) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{crudDaoClass},
(p, m, a) -> {
final Method method = crudDaoClass.getMethod("getTableName");
Constructor<Lookup> constructor = Lookup.class
.getDeclaredConstructor(Class.class);
constructor.setAccessible(true);
return constructor.newInstance(crudDaoClass)
.in(crudDaoClass)
.unreflectSpecial(method, crudDaoClass)
.bindTo(p)
.invokeWithArguments();
}
);
tableName = proxy.getTableName();
} catch (Throwable e) {
throw new DbException(format("В классе %s не найден метод %s", crudDaoClass, "getTableName"), e);
}
}
return Pair.of(StringUtils.upperCase(tableName), crudDaoClass);
}
//endregion
}
|
UTF-8
|
Java
| 7,567 |
java
|
DbHelper.java
|
Java
|
[] | null |
[] |
package ru.iopump.jdbi.cucumber;
import static java.lang.String.format;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import com.google.common.collect.Maps;
import io.cucumber.datatable.DataTable;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.sqlobject.config.RegisterBeanMapper;
import ru.iopump.jdbi.db.dao.CrudDao;
import ru.iopump.jdbi.db.dao.Dao;
import ru.iopump.jdbi.db.dao.DaoCondition;
import ru.iopump.jdbi.db.dao.DaoConditionChain;
import ru.iopump.jdbi.db.entity.Entity;
import ru.iopump.jdbi.db.exception.DbException;
import ru.iopump.jdbi.util.ReflectionUtils;
@SuppressWarnings("unused")
public class DbHelper {
private final String[] daoPackages;
private final Object DAO_CLASSES_LOCK = new Object();
private Map<String, Class<? extends CrudDao>> DAO_CLASSES_CACHE;
public DbHelper(String... daoPackages) {
this.daoPackages = daoPackages;
}
/**
* Превратить cucumber Пример вида 'имя колонки|значение' в карту вида [имя колонки : значение].
*
* @param dataTable Пример cucumber.
*/
public static Map<String, String> asMap(@Nullable DataTable dataTable) {
if (dataTable == null) {
return Maps.newHashMap();
}
return dataTable.asMap(String.class, String.class);
}
/**
* Загрузить {@link CrudDao} по имени таблицы.
* Имя таблицы проверяется в первую очередь, если имеется аннотация {@link Dao}, если аннотации нет (или значение пустое),
* то вызывается метод {@link CrudDao#getTableName()}.
*/
@NonNull
public <DAO extends CrudDao> DAO loadDaoByTableName(@NonNull Jdbi jdbi,
@Nullable String table) {
synchronized (DAO_CLASSES_LOCK) {
if (DAO_CLASSES_CACHE == null) {
DAO_CLASSES_CACHE = ReflectionUtils.getAllClasses(CrudDao.class, daoPackages)
.stream()
.filter(i -> i != CrudDao.class)
.map(this::getTableClass)
.filter(Objects::nonNull)
.collect(Collectors.toMap(Pair::getKey,
Pair::getValue,
(one, two) -> {
// если есть Dao аннотация, то использовать именно этот класс в первую очередь.
if (two.isAnnotationPresent(Dao.class)) {
return two;
} else {
return one;
}
}));
}
}
final Class<? extends CrudDao> cls = DAO_CLASSES_CACHE.get(StringUtils.upperCase(table));
if (cls == null) {
throw new IllegalArgumentException(format("Не найдено CrudDao для таблицы %s в пакете %s",
table,
Arrays.toString(daoPackages))
);
}
//noinspection unchecked
return (DAO) jdbi.onDemand(cls);
}
/**
* Получить класс сущености, чтобы потом создать его через отражение.
*/
public <ENTITY extends Entity> Class<ENTITY> getEntityClass(@NonNull final CrudDao crudDao) {
Class clz;
if (Proxy.isProxyClass(crudDao.getClass())) {
clz = crudDao.getClass().getInterfaces()[0];
} else {
clz = crudDao.getClass();
}
if (clz.isAnnotationPresent(Dao.class)) {
Class res = ((Dao) clz.getAnnotation(Dao.class)).entityClass();
if (res != Entity.class) {
//noinspection unchecked
return (Class<ENTITY>) res;
}
}
if (clz.isAnnotationPresent(RegisterBeanMapper.class)) {
//noinspection unchecked
return (Class<ENTITY>) ((RegisterBeanMapper) clz.getAnnotation(RegisterBeanMapper.class)).value();
}
throw new DbException(format("Для DAO %s не удается получить класс ENTITY. " +
"Проверьте наличие аннотаций : Dao или RegisterBeanMapper", clz));
}
@NonNull
public DaoConditionChain dataTableToConditionals(@NonNull DataTable dataTable) {
return dataTable.asLists(Object.class)
.stream()
.map(row -> {
if (row.size() == 2) {
return DaoCondition.equal((String) row.get(0), row.get(1));
} else if (row.size() == 3) {
return new DaoCondition((String) row.get(0), (String) row.get(1), row.get(2));
} else {
throw new IllegalArgumentException(format("Ряд %s должн быть рамером 2 или 3",
Objects.toString(row)));
}
})
.reduce(new DaoConditionChain(), DaoConditionChain::and, (one, two) -> two);
}
//region Private
@Nullable
private Pair<String, Class<? extends CrudDao>> getTableClass(@NonNull Class<? extends CrudDao> crudDaoClass) {
String tableName = null;
if (crudDaoClass.isAnnotationPresent(Dao.class)) {
if (!crudDaoClass.getAnnotation(Dao.class).include()) {
return null;
}
if (!StringUtils.isBlank(crudDaoClass.getAnnotation(Dao.class).tableName())) {
tableName = crudDaoClass.getAnnotation(Dao.class).tableName();
}
}
if (tableName == null) {
try {
final CrudDao proxy = (CrudDao) Proxy.newProxyInstance(
Thread.currentThread().getContextClassLoader(),
new Class[]{crudDaoClass},
(p, m, a) -> {
final Method method = crudDaoClass.getMethod("getTableName");
Constructor<Lookup> constructor = Lookup.class
.getDeclaredConstructor(Class.class);
constructor.setAccessible(true);
return constructor.newInstance(crudDaoClass)
.in(crudDaoClass)
.unreflectSpecial(method, crudDaoClass)
.bindTo(p)
.invokeWithArguments();
}
);
tableName = proxy.getTableName();
} catch (Throwable e) {
throw new DbException(format("В классе %s не найден метод %s", crudDaoClass, "getTableName"), e);
}
}
return Pair.of(StringUtils.upperCase(tableName), crudDaoClass);
}
//endregion
}
| 7,567 | 0.554698 | 0.552735 | 174 | 39.982758 | 29.849714 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534483 | false | false |
9
|
d3a1569da03f877b835af3886bcaad23c1f45670
| 26,018,911,889,283 |
31d162610f56e7dbb64c4eb461996b65c1c86b14
|
/src/main/java/parsers/GfaParser.java
|
8850d9f376d9455be4c50ddc33dde202615f4079
|
[
"Apache-2.0"
] |
permissive
|
ProgrammingLife2016/PL3-2016
|
https://github.com/ProgrammingLife2016/PL3-2016
|
538d5f0eb887d250c61de915414b94e3844559d4
|
02f299c13843625ccb74516030f5b65921d0e71b
|
refs/heads/master
| 2021-01-17T13:18:37.992000 | 2016-06-23T16:58:49 | 2016-06-23T16:58:49 | 56,146,157 | 3 | 3 | null | false | 2016-07-03T22:32:26 | 2016-04-13T11:29:36 | 2016-05-20T10:50:21 | 2016-07-03T22:28:11 | 65,664 | 3 | 0 | 1 |
Java
| null | null |
package parsers;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import db.DatabaseManager;
import db.tables.BubbleTable;
import db.tables.GenomeSegmentLinkTable;
import db.tables.GenomeTable;
import db.tables.LinkTable;
import db.tables.SegmentTable;
import db.tables.Table;
import db.tuples.GenomeSegmentLinkTuple;
import db.tuples.GenomeTuple;
import db.tuples.LinkTuple;
import db.tuples.SegmentTuple;
public class GfaParser {
/**
* These 5 constants are used to designate specific parts of a line that was
* parsed from the gfa file.
*/
private static final int SEGMENTID_IDX = 1;
private static final int SEGMENTCONTENT_IDX = 2;
private static final int SEGMENTGENOMES_IDX = 4;
private static final int LINKFROM_IDX = 1;
private static final int LINKTO_IDX = 3;
/**
* List of tables contained within the database.
*/
private List<Table> tables = new ArrayList<>();
/**
* Hashmap of genomes for effiently storing specific genomes.
*/
private HashMap<String,Integer> genomes = new HashMap<>();
/**
* Required DatabaseManager for loading parsed lines into the database.
*/
private DatabaseManager dbManager;
public GfaParser(DatabaseManager dbManager) {
this.dbManager = dbManager;
}
/**
* Reads the gfa file with the given path and stores the results in the
* table using it's DatabaseManager.
*
* @param gfaPath
* Path to the gfa file.
* @throws GfaException
* Exception thrown when execution fails.
*/
public void parse(String gfaPath) throws GfaException {
tables.add(new SegmentTable());
tables.add(new GenomeTable());
tables.add(new LinkTable());
tables.add(new GenomeSegmentLinkTable());
tables.add(new BubbleTable());
dbManager.createTables(tables);
String line;
try {
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(gfaPath),
Charset.defaultCharset()));
while ((line = bufferedReader.readLine()) != null) {
char type = line.charAt(0);
switch (type) {
case 'H': parseHeader(line);
break;
case 'S': parseSegment(line);
break;
case 'L': parseLink(line);
break;
default: throw new GfaException();
}
}
bufferedReader.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + gfaPath);
e.printStackTrace();
} catch (IOException e) {
System.err.println("Error reading file: " + gfaPath);
e.printStackTrace();
}
}
/**
* Helper method to parse a Header line
*
* @param line
* Header line to parse.
*/
private void parseHeader(String line) {
String[] split = line.split("\\s")[1].split(":");
if (split[0].equals("ORI")) {
String[] genomeNames = split[2].split(";");
for (int i = 0; i < genomeNames.length; i++) {
String genomeName = genomeNames[i];
genomes.put(genomeName, i + 1);
dbManager.insert(new GenomeTuple(i + 1,
genomeName.substring(0,genomeName.length() - 6)));
}
}
}
/**
* Helper method to parse a Segment line
*
* @param line
* Segment line to parse.
*
*/
private void parseSegment(String line) {
String[] split = line.split("\\s");
dbManager.insert(new SegmentTuple(Integer.parseInt(split[SEGMENTID_IDX]),
split[SEGMENTCONTENT_IDX]));
String[] genomesInSegment = split[SEGMENTGENOMES_IDX].split(":")[2].split(";");
for (String gen : genomesInSegment) {
dbManager.insert(new GenomeSegmentLinkTuple(Integer.parseInt(split[SEGMENTID_IDX]),
genomes.get(gen)));
}
}
/**
* Helper method to parse a Link line
*
* @param line
* Link line to parse.
*/
private void parseLink(String line) {
String[] split = line.split("\\s");
dbManager.insert(new LinkTuple(Integer.parseInt(split[LINKFROM_IDX]),
Integer.parseInt(split[LINKTO_IDX])));
}
public HashMap<String, Integer> getGenomes() {
return this.genomes;
}
}
|
UTF-8
|
Java
| 4,291 |
java
|
GfaParser.java
|
Java
|
[] | null |
[] |
package parsers;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import db.DatabaseManager;
import db.tables.BubbleTable;
import db.tables.GenomeSegmentLinkTable;
import db.tables.GenomeTable;
import db.tables.LinkTable;
import db.tables.SegmentTable;
import db.tables.Table;
import db.tuples.GenomeSegmentLinkTuple;
import db.tuples.GenomeTuple;
import db.tuples.LinkTuple;
import db.tuples.SegmentTuple;
public class GfaParser {
/**
* These 5 constants are used to designate specific parts of a line that was
* parsed from the gfa file.
*/
private static final int SEGMENTID_IDX = 1;
private static final int SEGMENTCONTENT_IDX = 2;
private static final int SEGMENTGENOMES_IDX = 4;
private static final int LINKFROM_IDX = 1;
private static final int LINKTO_IDX = 3;
/**
* List of tables contained within the database.
*/
private List<Table> tables = new ArrayList<>();
/**
* Hashmap of genomes for effiently storing specific genomes.
*/
private HashMap<String,Integer> genomes = new HashMap<>();
/**
* Required DatabaseManager for loading parsed lines into the database.
*/
private DatabaseManager dbManager;
public GfaParser(DatabaseManager dbManager) {
this.dbManager = dbManager;
}
/**
* Reads the gfa file with the given path and stores the results in the
* table using it's DatabaseManager.
*
* @param gfaPath
* Path to the gfa file.
* @throws GfaException
* Exception thrown when execution fails.
*/
public void parse(String gfaPath) throws GfaException {
tables.add(new SegmentTable());
tables.add(new GenomeTable());
tables.add(new LinkTable());
tables.add(new GenomeSegmentLinkTable());
tables.add(new BubbleTable());
dbManager.createTables(tables);
String line;
try {
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(gfaPath),
Charset.defaultCharset()));
while ((line = bufferedReader.readLine()) != null) {
char type = line.charAt(0);
switch (type) {
case 'H': parseHeader(line);
break;
case 'S': parseSegment(line);
break;
case 'L': parseLink(line);
break;
default: throw new GfaException();
}
}
bufferedReader.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + gfaPath);
e.printStackTrace();
} catch (IOException e) {
System.err.println("Error reading file: " + gfaPath);
e.printStackTrace();
}
}
/**
* Helper method to parse a Header line
*
* @param line
* Header line to parse.
*/
private void parseHeader(String line) {
String[] split = line.split("\\s")[1].split(":");
if (split[0].equals("ORI")) {
String[] genomeNames = split[2].split(";");
for (int i = 0; i < genomeNames.length; i++) {
String genomeName = genomeNames[i];
genomes.put(genomeName, i + 1);
dbManager.insert(new GenomeTuple(i + 1,
genomeName.substring(0,genomeName.length() - 6)));
}
}
}
/**
* Helper method to parse a Segment line
*
* @param line
* Segment line to parse.
*
*/
private void parseSegment(String line) {
String[] split = line.split("\\s");
dbManager.insert(new SegmentTuple(Integer.parseInt(split[SEGMENTID_IDX]),
split[SEGMENTCONTENT_IDX]));
String[] genomesInSegment = split[SEGMENTGENOMES_IDX].split(":")[2].split(";");
for (String gen : genomesInSegment) {
dbManager.insert(new GenomeSegmentLinkTuple(Integer.parseInt(split[SEGMENTID_IDX]),
genomes.get(gen)));
}
}
/**
* Helper method to parse a Link line
*
* @param line
* Link line to parse.
*/
private void parseLink(String line) {
String[] split = line.split("\\s");
dbManager.insert(new LinkTuple(Integer.parseInt(split[LINKFROM_IDX]),
Integer.parseInt(split[LINKTO_IDX])));
}
public HashMap<String, Integer> getGenomes() {
return this.genomes;
}
}
| 4,291 | 0.664414 | 0.660685 | 157 | 26.331211 | 20.947733 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.955414 | false | false |
9
|
5a6753823fe4aee2b8f6aadd268e3a77df3c6289
| 25,142,738,575,437 |
5e1907d7a32d1f9020c83b19cddb81f4daf39bf9
|
/src/main/java/com/demo/ewalletshopping/dao/CartDetailDao.java
|
0f9d8e23b21b86c50729562eebb71d24665dc7ed
|
[] |
no_license
|
grandhe10/eWalletShopping
|
https://github.com/grandhe10/eWalletShopping
|
e45375b9fd762e5529c80c14eb6f7f7ecc1d5a88
|
962471e13ec75fa4002f65c96f9115b93ed6adbf
|
refs/heads/master
| 2022-11-17T12:03:59.022000 | 2020-07-09T03:53:20 | 2020-07-09T03:53:20 | 278,024,716 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.demo.ewalletshopping.dao;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.demo.ewalletshopping.model.Cart;
import com.demo.ewalletshopping.model.CartDetail;
/**
* @author Suma
* This interface extends {@link CrudRepository}
*
*/
@Repository
public interface CartDetailDao extends CrudRepository<CartDetail, Long>{
/**
* This method is used to get Cart details by cart
* @param cart
* @return List<CartDetail>
*/
Optional<List<CartDetail>> findByCart(Cart cart);
}
|
UTF-8
|
Java
| 618 |
java
|
CartDetailDao.java
|
Java
|
[
{
"context": "o.ewalletshopping.model.CartDetail;\n/**\n * @author Suma\n * This interface extends {@link CrudRepository}\n",
"end": 313,
"score": 0.9988892078399658,
"start": 309,
"tag": "NAME",
"value": "Suma"
}
] | null |
[] |
package com.demo.ewalletshopping.dao;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.demo.ewalletshopping.model.Cart;
import com.demo.ewalletshopping.model.CartDetail;
/**
* @author Suma
* This interface extends {@link CrudRepository}
*
*/
@Repository
public interface CartDetailDao extends CrudRepository<CartDetail, Long>{
/**
* This method is used to get Cart details by cart
* @param cart
* @return List<CartDetail>
*/
Optional<List<CartDetail>> findByCart(Cart cart);
}
| 618 | 0.770227 | 0.770227 | 26 | 22.76923 | 22.503517 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576923 | false | false |
9
|
07a97e0fb2684128cfbc320ef8a8532ab2f4be70
| 25,142,738,573,928 |
a49363ef9fea4aba1deeecc339c74cecca1e2deb
|
/app/src/main/java/com/example/car2go/ui/services/AddInquiry.java
|
1f15403e4130fc5e5cda4fa6f1932fdaf2ee8d8d
|
[] |
no_license
|
KavinduLakshitha/Car2Go
|
https://github.com/KavinduLakshitha/Car2Go
|
935920e3eac5f51dc921d395b317aea24888a0ab
|
bc5790e4351aa1a51bb728456c14ba9caab09027
|
refs/heads/master
| 2023-08-06T03:41:43.056000 | 2021-10-03T15:07:17 | 2021-10-03T15:07:17 | 407,877,719 | 0 | 1 | null | false | 2021-10-03T15:07:18 | 2021-09-18T14:09:13 | 2021-09-26T11:34:57 | 2021-10-03T15:07:17 | 4,584 | 0 | 0 | 0 |
Java
| false | false |
package com.example.car2go.ui.services;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.car2go.R;
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 org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class AddInquiry extends AppCompatActivity {
EditText name,nic,phone,email,inquiry;
Button buttonSend;
DatabaseReference databaseInquiry;
ListView listViewInquiry;
List<Inquiry> inquiryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_inquiry);
databaseInquiry = FirebaseDatabase.getInstance().getReference("inquiries");
name =(EditText) findViewById(R.id.enter_name);
phone = (EditText) findViewById(R.id.enter_phone);
nic = (EditText) findViewById(R.id.enter_nic);
email = (EditText) findViewById(R.id.enter_email);
inquiry = (EditText) findViewById(R.id.enter_inquiry);
buttonSend = (Button) findViewById(R.id.Send) ;
listViewInquiry=(ListView) findViewById(R.id.listViewInquiry);
inquiryList = new ArrayList<>();
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addInquiry();
}
});
}
@Override
protected void onStart() {
super.onStart();
databaseInquiry.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange( DataSnapshot dataSnapshot) {
inquiryList.clear();
for(DataSnapshot inquirySnapshot : dataSnapshot.getChildren()){
Inquiry inquiry = inquirySnapshot.getValue(Inquiry.class);
inquiryList.add(inquiry);
}
InquiryList adapter = new InquiryList(AddInquiry.this,inquiryList);
listViewInquiry.setAdapter(adapter);
}
@Override
public void onCancelled( DatabaseError error) {
}
});
}
private void showUpdateDialog(String inquiryID, String customerName, String customerNIC, String customerEmail, String customerPhone, String customerInquiry){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_inquiry,null);
dialogBuilder.setView(dialogView);
final EditText editName = (EditText) dialogView.findViewById(R.id.editTextName);
final EditText editNIC = (EditText) dialogView.findViewById(R.id.editTextNIC);
final EditText editPhone = (EditText) dialogView.findViewById(R.id.editTextPhone);
final EditText editEmail = (EditText) dialogView.findViewById(R.id.editTextEmail);
final EditText editInquiry= (EditText) dialogView.findViewById(R.id.editTextInquiry);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdate);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Inquiry" + inquiryID);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String name = editName.getText().toString().trim();
String nic = editNIC.getText().toString().trim();
String phone = editPhone.getText().toString().trim();
String email= editEmail.getText().toString().trim();
String inquiry = editInquiry.getText().toString().trim();
if (TextUtils.isEmpty(inquiry)) {
editInquiry.setError("Inquiry Required");
return;
}
updateArtist(inquiryID, name, nic, phone, email,inquiry);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
deleteInquiry(inquiryID);
}
});
}
private void deleteInquiry(String inquiryID){
DatabaseReference drInquiry = FirebaseDatabase.getInstance().getReference("inquiries").child(inquiryID);
drInquiry.removeValue();
Toast.makeText(this,"Inquiry Delete Succesfull",Toast.LENGTH_LONG).show();
}
private boolean updateArtist(String inquiryId, String customerName, String customerNIC, String customerEmail, String customerPhone, String customerInquiry){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("inquiries").child(inquiryId);
Inquiry inquiry = new Inquiry(inquiryId, customerName , customerNIC,customerEmail,customerPhone,customerInquiry);
databaseReference.setValue(inquiry);
Toast.makeText(this,"Inquiry Updated Succesfull",Toast.LENGTH_LONG).show();
return true;
}
private void addInquiry(){
String Name = name.getText().toString().trim();
String NIC = nic.getText().toString().trim();
String Phone = phone.getText().toString().trim();
String Email = email.getText().toString().trim();
String Inquiry = inquiry.getText().toString().trim();
if(!TextUtils.isEmpty(Inquiry)){
String id = databaseInquiry.push().getKey();
Inquiry inquiry = new Inquiry(id, Name , NIC, Phone, Email, Inquiry );
databaseInquiry.child(id).setValue(inquiry);
Toast.makeText(this,"Inquiry Added Successful!!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"You Should Enter Inquiry ", Toast.LENGTH_LONG).show();
}
}
}
|
UTF-8
|
Java
| 6,680 |
java
|
AddInquiry.java
|
Java
|
[] | null |
[] |
package com.example.car2go.ui.services;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.car2go.R;
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 org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class AddInquiry extends AppCompatActivity {
EditText name,nic,phone,email,inquiry;
Button buttonSend;
DatabaseReference databaseInquiry;
ListView listViewInquiry;
List<Inquiry> inquiryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_inquiry);
databaseInquiry = FirebaseDatabase.getInstance().getReference("inquiries");
name =(EditText) findViewById(R.id.enter_name);
phone = (EditText) findViewById(R.id.enter_phone);
nic = (EditText) findViewById(R.id.enter_nic);
email = (EditText) findViewById(R.id.enter_email);
inquiry = (EditText) findViewById(R.id.enter_inquiry);
buttonSend = (Button) findViewById(R.id.Send) ;
listViewInquiry=(ListView) findViewById(R.id.listViewInquiry);
inquiryList = new ArrayList<>();
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addInquiry();
}
});
}
@Override
protected void onStart() {
super.onStart();
databaseInquiry.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange( DataSnapshot dataSnapshot) {
inquiryList.clear();
for(DataSnapshot inquirySnapshot : dataSnapshot.getChildren()){
Inquiry inquiry = inquirySnapshot.getValue(Inquiry.class);
inquiryList.add(inquiry);
}
InquiryList adapter = new InquiryList(AddInquiry.this,inquiryList);
listViewInquiry.setAdapter(adapter);
}
@Override
public void onCancelled( DatabaseError error) {
}
});
}
private void showUpdateDialog(String inquiryID, String customerName, String customerNIC, String customerEmail, String customerPhone, String customerInquiry){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_inquiry,null);
dialogBuilder.setView(dialogView);
final EditText editName = (EditText) dialogView.findViewById(R.id.editTextName);
final EditText editNIC = (EditText) dialogView.findViewById(R.id.editTextNIC);
final EditText editPhone = (EditText) dialogView.findViewById(R.id.editTextPhone);
final EditText editEmail = (EditText) dialogView.findViewById(R.id.editTextEmail);
final EditText editInquiry= (EditText) dialogView.findViewById(R.id.editTextInquiry);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdate);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Inquiry" + inquiryID);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String name = editName.getText().toString().trim();
String nic = editNIC.getText().toString().trim();
String phone = editPhone.getText().toString().trim();
String email= editEmail.getText().toString().trim();
String inquiry = editInquiry.getText().toString().trim();
if (TextUtils.isEmpty(inquiry)) {
editInquiry.setError("Inquiry Required");
return;
}
updateArtist(inquiryID, name, nic, phone, email,inquiry);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
deleteInquiry(inquiryID);
}
});
}
private void deleteInquiry(String inquiryID){
DatabaseReference drInquiry = FirebaseDatabase.getInstance().getReference("inquiries").child(inquiryID);
drInquiry.removeValue();
Toast.makeText(this,"Inquiry Delete Succesfull",Toast.LENGTH_LONG).show();
}
private boolean updateArtist(String inquiryId, String customerName, String customerNIC, String customerEmail, String customerPhone, String customerInquiry){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("inquiries").child(inquiryId);
Inquiry inquiry = new Inquiry(inquiryId, customerName , customerNIC,customerEmail,customerPhone,customerInquiry);
databaseReference.setValue(inquiry);
Toast.makeText(this,"Inquiry Updated Succesfull",Toast.LENGTH_LONG).show();
return true;
}
private void addInquiry(){
String Name = name.getText().toString().trim();
String NIC = nic.getText().toString().trim();
String Phone = phone.getText().toString().trim();
String Email = email.getText().toString().trim();
String Inquiry = inquiry.getText().toString().trim();
if(!TextUtils.isEmpty(Inquiry)){
String id = databaseInquiry.push().getKey();
Inquiry inquiry = new Inquiry(id, Name , NIC, Phone, Email, Inquiry );
databaseInquiry.child(id).setValue(inquiry);
Toast.makeText(this,"Inquiry Added Successful!!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"You Should Enter Inquiry ", Toast.LENGTH_LONG).show();
}
}
}
| 6,680 | 0.672305 | 0.672006 | 173 | 37.618496 | 32.522541 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.774566 | false | false |
9
|
52525551eabdd7de6d003334ce305514cf21b6e8
| 28,106,266,048,414 |
92bed53a2c31134e252c269bbd35af5e9dd9d4bb
|
/ws_java_12/ChatConnect.java
|
15b4eadf64ee9109c3589f73ba7ac46e1cfc3603
|
[] |
no_license
|
sxngho/ssafy_workshop
|
https://github.com/sxngho/ssafy_workshop
|
438a4e5c0a265a62d81f6f8c8e4bb0f152f4a67a
|
091e5782942a504c2913b02a33b9a8e400482cbd
|
refs/heads/master
| 2020-07-10T23:57:57.611000 | 2019-05-16T08:28:46 | 2019-05-16T08:28:46 | 204,403,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ssafy.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatConnect {
protected String ip;
protected int port;
protected String name;
private Socket s;
private BufferedReader br;
private PrintWriter pw;
private ChatClient cl;
public ChatConnect(ChatClient cl,String ip,int port,String name) {
this.cl=cl;
this.ip=ip;
this.port=port;
this.name=name;
}
public void go() {
try {
s = new Socket(ip,port);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);
ChatClientThread ct = new ChatClientThread(s);
ct.start();
} catch (IOException e) {
e.getMessage();
}
}
public void send(String str){
pw.println(str);
}
class ChatClientThread extends Thread{
Socket s;
BufferedReader br1;
String str;
public ChatClientThread(Socket s) throws IOException {
this.s = s;
br1 = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
public void run(){
try{
while ( ( str = br1.readLine() ) != null){
cl.show(str);
}
}catch (IOException e){
System.out.println(e.getMessage());
}
}
}
}
|
UTF-8
|
Java
| 1,399 |
java
|
ChatConnect.java
|
Java
|
[] | null |
[] |
package com.ssafy.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatConnect {
protected String ip;
protected int port;
protected String name;
private Socket s;
private BufferedReader br;
private PrintWriter pw;
private ChatClient cl;
public ChatConnect(ChatClient cl,String ip,int port,String name) {
this.cl=cl;
this.ip=ip;
this.port=port;
this.name=name;
}
public void go() {
try {
s = new Socket(ip,port);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);
ChatClientThread ct = new ChatClientThread(s);
ct.start();
} catch (IOException e) {
e.getMessage();
}
}
public void send(String str){
pw.println(str);
}
class ChatClientThread extends Thread{
Socket s;
BufferedReader br1;
String str;
public ChatClientThread(Socket s) throws IOException {
this.s = s;
br1 = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
public void run(){
try{
while ( ( str = br1.readLine() ) != null){
cl.show(str);
}
}catch (IOException e){
System.out.println(e.getMessage());
}
}
}
}
| 1,399 | 0.706219 | 0.704074 | 69 | 19.275362 | 18.413042 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.884058 | false | false |
9
|
06057ba0db1cbef0c1f3610afa4018b93c339246
| 22,402,549,421,180 |
bb4570849fa3e34d33a649c3d577b40729ffe110
|
/src/test/java/com/milkit/app/domain/userinfo/UserInfoControllerTest.java
|
4279fba45e84ba046126d6e4d3f24125124508da
|
[] |
no_license
|
milkitmoon/jwt_demo
|
https://github.com/milkitmoon/jwt_demo
|
3fa0c5fb5e3d498884bff23cadc44810bafaa469
|
14afe7fc48d36646ee69c558d491b6fb74a420e9
|
refs/heads/master
| 2023-02-23T18:43:28.953000 | 2021-02-04T04:57:04 | 2021-02-04T04:57:04 | 290,957,565 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.milkit.app.domain.userinfo;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import com.milkit.app.api.userinfo.UserInfoController;
import com.milkit.app.config.WebSecurityConfigure;
import com.milkit.app.domain.userinfo.service.UserInfoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.bind.annotation.RequestParam;
@WebMvcTest(UserInfoController.class)
@Import(WebSecurityConfigure.class)
@Slf4j
public class UserInfoControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private UserInfoServiceImpl userInfoServie;
@Test
@WithMockUser(username = "admin", roles = {"ADMIN"})
public void userinfoAll_테스트() throws Exception {
//given
List<UserInfo> list = Arrays.asList(new UserInfo(1L, "admin", "ROLE_ADMIN"), new UserInfo(2L, "test", "ROLE_MEMBER"));
given(userInfoServie.selectAll()).willReturn(list);
//when
final ResultActions actions = mvc.perform(get("/api/userinfo")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print());
//then
actions
.andExpect(status().isOk())
.andExpect(jsonPath("code").value("0"))
.andExpect(jsonPath("message").value("성공했습니다"))
.andExpect(jsonPath("value[0].id").value(1L))
.andExpect(jsonPath("value[0].userID").value("admin"))
.andExpect(jsonPath("value[0].authRole").value("ROLE_ADMIN"))
.andExpect(jsonPath("value[1].id").value(2L))
.andExpect(jsonPath("value[1].userID").value("test"))
.andExpect(jsonPath("value[1].authRole").value("ROLE_MEMBER"))
;
}
}
|
UTF-8
|
Java
| 3,047 |
java
|
UserInfoControllerTest.java
|
Java
|
[
{
"context": " \n \n @Test\n @WithMockUser(username = \"admin\", roles = {\"ADMIN\"})\n public void userinfoAll_",
"end": 1915,
"score": 0.9991405010223389,
"start": 1910,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "<UserInfo> list = Arrays.asList(new UserInfo(1L, \"admin\", \"ROLE_ADMIN\"), new UserInfo(2L, \"test\", \"ROLE_M",
"end": 2070,
"score": 0.9866162538528442,
"start": 2065,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "nfo(1L, \"admin\", \"ROLE_ADMIN\"), new UserInfo(2L, \"test\", \"ROLE_MEMBER\"));\n given(userInfoServie.s",
"end": 2110,
"score": 0.7398709654808044,
"start": 2106,
"tag": "USERNAME",
"value": "test"
}
] | null |
[] |
package com.milkit.app.domain.userinfo;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import com.milkit.app.api.userinfo.UserInfoController;
import com.milkit.app.config.WebSecurityConfigure;
import com.milkit.app.domain.userinfo.service.UserInfoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.bind.annotation.RequestParam;
@WebMvcTest(UserInfoController.class)
@Import(WebSecurityConfigure.class)
@Slf4j
public class UserInfoControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private UserInfoServiceImpl userInfoServie;
@Test
@WithMockUser(username = "admin", roles = {"ADMIN"})
public void userinfoAll_테스트() throws Exception {
//given
List<UserInfo> list = Arrays.asList(new UserInfo(1L, "admin", "ROLE_ADMIN"), new UserInfo(2L, "test", "ROLE_MEMBER"));
given(userInfoServie.selectAll()).willReturn(list);
//when
final ResultActions actions = mvc.perform(get("/api/userinfo")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print());
//then
actions
.andExpect(status().isOk())
.andExpect(jsonPath("code").value("0"))
.andExpect(jsonPath("message").value("성공했습니다"))
.andExpect(jsonPath("value[0].id").value(1L))
.andExpect(jsonPath("value[0].userID").value("admin"))
.andExpect(jsonPath("value[0].authRole").value("ROLE_ADMIN"))
.andExpect(jsonPath("value[1].id").value(2L))
.andExpect(jsonPath("value[1].userID").value("test"))
.andExpect(jsonPath("value[1].authRole").value("ROLE_MEMBER"))
;
}
}
| 3,047 | 0.724662 | 0.72004 | 80 | 36.862499 | 29.209478 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false |
9
|
e567dc2e4795f078a265611cb0df5de468eca9e4
| 22,557,168,266,703 |
a64b490387b2a20b6d15b050b824ba56aef370e4
|
/src/units/bullets/AbstractBullet.java
|
cf0096b2c5d24c8969f973da0d5908d1570c5008
|
[] |
no_license
|
kgyorev/Team-Errol-game
|
https://github.com/kgyorev/Team-Errol-game
|
d90acf174226d5cae6be3aa6c3b9a43d8833998d
|
78f08d026e7c0086b0b6176a0ba835aa6153a7b0
|
refs/heads/master
| 2021-06-18T05:06:49.620000 | 2017-04-25T12:17:47 | 2017-04-25T12:17:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package units.bullets;
import units.bricks.Brick;
import units.bricks.Stone;
import units.platform.Platform;
import java.awt.*;
public abstract class AbstractBullet implements Ammo {
private int x;
private int y;
private int width;
private int height;
private Image image;
private Platform platform;
private Brick[] bricks;
private Stone[] stones;
private boolean targetHit;
protected AbstractBullet(int x, int y, int width, int height, Platform platform, Brick[] bricks, Stone[] stones, Image image) {
this.setX(x);
this.setY(y);
this.setWidth(width);
this.setHeight(height);
this.platform = platform;
this.bricks = bricks;
this.stones = stones;
this.image = image;
}
public Image getImage() {
return image;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public Brick[] getBricks() {
return this.bricks;
}
public Stone[] getStones() {
return this.stones;
}
@Override
public boolean hasHitTarget() {
return this.targetHit;
}
protected Platform getPlatform() {
return platform;
}
protected void setX(int x) {
this.x = x;
}
protected void setY(int y) {
this.y = y;
}
protected void setWidth(int width) {
this.width = width;
}
protected void setHeight(int height) {
this.height = height;
}
protected void hitTarget() {
this.targetHit = true;
}
}
|
UTF-8
|
Java
| 1,720 |
java
|
AbstractBullet.java
|
Java
|
[] | null |
[] |
package units.bullets;
import units.bricks.Brick;
import units.bricks.Stone;
import units.platform.Platform;
import java.awt.*;
public abstract class AbstractBullet implements Ammo {
private int x;
private int y;
private int width;
private int height;
private Image image;
private Platform platform;
private Brick[] bricks;
private Stone[] stones;
private boolean targetHit;
protected AbstractBullet(int x, int y, int width, int height, Platform platform, Brick[] bricks, Stone[] stones, Image image) {
this.setX(x);
this.setY(y);
this.setWidth(width);
this.setHeight(height);
this.platform = platform;
this.bricks = bricks;
this.stones = stones;
this.image = image;
}
public Image getImage() {
return image;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public Brick[] getBricks() {
return this.bricks;
}
public Stone[] getStones() {
return this.stones;
}
@Override
public boolean hasHitTarget() {
return this.targetHit;
}
protected Platform getPlatform() {
return platform;
}
protected void setX(int x) {
this.x = x;
}
protected void setY(int y) {
this.y = y;
}
protected void setWidth(int width) {
this.width = width;
}
protected void setHeight(int height) {
this.height = height;
}
protected void hitTarget() {
this.targetHit = true;
}
}
| 1,720 | 0.587791 | 0.587791 | 89 | 18.325842 | 18.062796 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483146 | false | false |
9
|
d76751b4b3df2a442aab82da24c07ac5f8f999bf
| 22,986,664,977,074 |
f4b7924a03289706c769aff23abf4cce028de6bc
|
/messageLibrary/src/main/java/ebd/messageLibrary/packet/trainpackets/Packet_44.java
|
5049ef054fccc913b1b9a5bf734b08a079fe2124
|
[] |
no_license
|
jimbok8/ebd
|
https://github.com/jimbok8/ebd
|
aa18a2066b4a873bad1551e1578a7a1215de9b8b
|
9b0d5197bede5def2972cc44e63ac3711010eed4
|
refs/heads/main
| 2023-06-17T21:16:08.003000 | 2021-07-05T14:53:38 | 2021-07-05T14:53:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ebd.messageLibrary.packet.trainpackets;
import ebd.messageLibrary.packet.TrainPacket;
import ebd.messageLibrary.serialization.annotations.BitLength;
import ebd.messageLibrary.serialization.annotations.OrderIndex;
import ebd.messageLibrary.util.ETCSVariables;
import ebd.messageLibrary.util.userData.UserData;
/**
* ID: 44 <br>
* Type: Train To Track <br>
* Description: Data Used By Applications Outside The ERTMS/ETCS System <br>
* Transmitted By: RBC, RIU <br>
* Elements: userData (must be set)
*
* @author Christopher Bernjus
*/
public class Packet_44 extends TrainPacket {
// -------------------------------------------------------
// Data Used By Applications Outside The ERTMS/ETCS System
// -------------------------------------------------------
/** {@link ETCSVariables#NID_XUSER} */
@BitLength(9)
@OrderIndex(2)
public int NID_XUSER = ETCSVariables.NID_XUSER;
/** Other Data Objects depending on {@link ETCSVariables#NID_XUSER} **/
@OrderIndex(3)
public UserData userData;
// Constructors
/**
* Constructs An Empty {@link Packet_44}
*
* @author Christopher Bernjus
*/
public Packet_44() {
super(44);
}
/**
* Constructs A {@link Packet_44}
*
* @param NID_XUSER
* {@link ETCSVariables#NID_XUSER}
* @param userData
* UserData Object depending on {@link ETCSVariables#NID_XUSER}
*
* @author Christopher Bernjus
*/
public Packet_44(int NID_XUSER, UserData userData) {
super(44);
this.NID_XUSER = NID_XUSER;
this.userData = userData;
}
// Other Functions
@Override
public boolean equals(Object object) {
if(this == object) return true;
if(object == null || getClass() != object.getClass()) return false;
if(!super.equals(object)) return false;
Packet_44 packet_44 = (Packet_44) object;
return NID_XUSER == packet_44.NID_XUSER && userData.equals(packet_44.userData);
}
@Override
public String toString() {
return "Packet_44{"
+ "NID_PACKET=" + NID_PACKET
+ ", L_PACKET=" + L_PACKET
+ ", NID_XUSER=" + NID_XUSER
+ ", userData=" + userData.toString()
+ '}';
}
}
|
UTF-8
|
Java
| 2,111 |
java
|
Packet_44.java
|
Java
|
[
{
"context": "\n * Elements: userData (must be set)\n *\n * @author Christopher Bernjus\n */\npublic class Packet_44 extends TrainPacket {\n",
"end": 546,
"score": 0.9999108910560608,
"start": 527,
"tag": "NAME",
"value": "Christopher Bernjus"
},
{
"context": "structs An Empty {@link Packet_44}\n\t *\n\t * @author Christopher Bernjus\n\t */\n\tpublic Packet_44() {\n\t\tsuper(44);\n\t}\n\n\t/**\n",
"end": 1117,
"score": 0.9999069571495056,
"start": 1098,
"tag": "NAME",
"value": "Christopher Bernjus"
},
{
"context": "on {@link ETCSVariables#NID_XUSER}\n\t *\n\t * @author Christopher Bernjus\n\t */\n\tpublic Packet_44(int NID_XUSER, UserData us",
"end": 1399,
"score": 0.999908447265625,
"start": 1380,
"tag": "NAME",
"value": "Christopher Bernjus"
}
] | null |
[] |
package ebd.messageLibrary.packet.trainpackets;
import ebd.messageLibrary.packet.TrainPacket;
import ebd.messageLibrary.serialization.annotations.BitLength;
import ebd.messageLibrary.serialization.annotations.OrderIndex;
import ebd.messageLibrary.util.ETCSVariables;
import ebd.messageLibrary.util.userData.UserData;
/**
* ID: 44 <br>
* Type: Train To Track <br>
* Description: Data Used By Applications Outside The ERTMS/ETCS System <br>
* Transmitted By: RBC, RIU <br>
* Elements: userData (must be set)
*
* @author <NAME>
*/
public class Packet_44 extends TrainPacket {
// -------------------------------------------------------
// Data Used By Applications Outside The ERTMS/ETCS System
// -------------------------------------------------------
/** {@link ETCSVariables#NID_XUSER} */
@BitLength(9)
@OrderIndex(2)
public int NID_XUSER = ETCSVariables.NID_XUSER;
/** Other Data Objects depending on {@link ETCSVariables#NID_XUSER} **/
@OrderIndex(3)
public UserData userData;
// Constructors
/**
* Constructs An Empty {@link Packet_44}
*
* @author <NAME>
*/
public Packet_44() {
super(44);
}
/**
* Constructs A {@link Packet_44}
*
* @param NID_XUSER
* {@link ETCSVariables#NID_XUSER}
* @param userData
* UserData Object depending on {@link ETCSVariables#NID_XUSER}
*
* @author <NAME>
*/
public Packet_44(int NID_XUSER, UserData userData) {
super(44);
this.NID_XUSER = NID_XUSER;
this.userData = userData;
}
// Other Functions
@Override
public boolean equals(Object object) {
if(this == object) return true;
if(object == null || getClass() != object.getClass()) return false;
if(!super.equals(object)) return false;
Packet_44 packet_44 = (Packet_44) object;
return NID_XUSER == packet_44.NID_XUSER && userData.equals(packet_44.userData);
}
@Override
public String toString() {
return "Packet_44{"
+ "NID_PACKET=" + NID_PACKET
+ ", L_PACKET=" + L_PACKET
+ ", NID_XUSER=" + NID_XUSER
+ ", userData=" + userData.toString()
+ '}';
}
}
| 2,072 | 0.644718 | 0.630033 | 84 | 24.130953 | 22.516544 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.190476 | false | false |
9
|
a339247983c58f122c876276c94701080a84f778
| 22,462,678,989,082 |
84dfeb5d6a0816dfc50acb6285d04813cd8efb20
|
/src/main/java/com/notification/errors/EmployeeNotFoundException.java
|
ff6c69f2a5a374d939317024b1f7a772f80db4d6
|
[
"Apache-2.0"
] |
permissive
|
toantonthat/spring-boot-with-fcm
|
https://github.com/toantonthat/spring-boot-with-fcm
|
60050f9ae3a95e36fa6e832958f189605466d499
|
d1d2e15b1278304b135eb29c2b142ebbdc8e24c6
|
refs/heads/main
| 2023-04-23T16:37:08.877000 | 2021-05-10T02:07:26 | 2021-05-10T02:07:26 | 350,757,832 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.notification.errors;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class EmployeeNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EmployeeNotFoundException() {
}
public EmployeeNotFoundException(Integer employeeId) {
super("Employee: " + employeeId + " not found.");
}
}
|
UTF-8
|
Java
| 461 |
java
|
EmployeeNotFoundException.java
|
Java
|
[] | null |
[] |
package com.notification.errors;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class EmployeeNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EmployeeNotFoundException() {
}
public EmployeeNotFoundException(Integer employeeId) {
super("Employee: " + employeeId + " not found.");
}
}
| 461 | 0.796095 | 0.793926 | 16 | 27.8125 | 25.107815 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false |
9
|
23d33751b4d2436ad35079f0cedf3e94a397836f
| 21,079,699,546,382 |
183931eedd8ed7ff685e22cb055f86f12a54d707
|
/javaRush/thread/src/ReadAndPrintFile.java
|
ec79220fb33e1671743d802f594375fa69425b0c
|
[] |
no_license
|
cynepCTAPuk/headFirstJava
|
https://github.com/cynepCTAPuk/headFirstJava
|
94a87be8f6958ab373cd1640a5bdb9c3cc3bf166
|
7cb45f6e2336bbc78852d297ad3474fd491e5870
|
refs/heads/master
| 2023-08-16T06:51:14.206000 | 2023-08-08T16:44:11 | 2023-08-08T16:44:11 | 154,661,091 | 0 | 1 | null | false | 2023-01-06T21:32:31 | 2018-10-25T11:40:54 | 2021-10-08T20:45:04 | 2023-01-06T21:32:27 | 46,377 | 0 | 0 | 75 |
Java
| false | false |
import java.io.BufferedReader;
import java.io.FileReader;
public class ReadAndPrintFile {
public static void main(String[] args) {
read("src/ReadAndPrintFile.java");
}
private static void read(String file) {
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String string;
while ((string = reader.readLine()) != null) stringBuilder.append(string).append("\n");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(stringBuilder);
}
}
|
UTF-8
|
Java
| 623 |
java
|
ReadAndPrintFile.java
|
Java
|
[] | null |
[] |
import java.io.BufferedReader;
import java.io.FileReader;
public class ReadAndPrintFile {
public static void main(String[] args) {
read("src/ReadAndPrintFile.java");
}
private static void read(String file) {
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String string;
while ((string = reader.readLine()) != null) stringBuilder.append(string).append("\n");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(stringBuilder);
}
}
| 623 | 0.634029 | 0.634029 | 19 | 31.789474 | 26.164618 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false |
9
|
ff215c6e9c4ab2a052d1900a4fb5170103b05078
| 2,078,764,215,936 |
a97e71d0928cf470c30f538c930555f95699b8f9
|
/kafka-utils/src/test/java/commons/ConfigTest.java
|
10b9df2fb14b36da310be845f13514b357b1acec
|
[] |
no_license
|
super-sponge/commons-utils
|
https://github.com/super-sponge/commons-utils
|
55fe053538e7872888695dbf27e34f679c24d633
|
3066d82f1540f5e2b3d96e72cf4519a8983de1ad
|
refs/heads/master
| 2021-04-12T09:06:59.528000 | 2017-06-16T08:28:19 | 2017-06-16T08:28:19 | 94,521,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package commons;
import junit.framework.TestCase;
import java.util.Map;
import java.util.Properties;
/**
* Created by sponge on 2017/6/12.
*/
public class ConfigTest extends TestCase {
public void testGetConsumerProperties() throws Exception {
Config.setConfDir("src/main/conf");
Properties props = Config.getConsumerProperties();
for(Map.Entry<Object, Object> entry : props.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("key : " + key + " value : " + value);
}
}
public void testGetProducerProperties() {
Config.setConfDir("src/main/conf");
Properties props = Config.getProducerProperties();
for(Map.Entry<Object, Object> entry : props.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("key : " + key + " value : " + value);
}
}
}
|
UTF-8
|
Java
| 1,025 |
java
|
ConfigTest.java
|
Java
|
[
{
"context": "p;\nimport java.util.Properties;\n\n/**\n * Created by sponge on 2017/6/12.\n */\npublic class ConfigTest extends",
"end": 128,
"score": 0.9995598793029785,
"start": 122,
"tag": "USERNAME",
"value": "sponge"
}
] | null |
[] |
package commons;
import junit.framework.TestCase;
import java.util.Map;
import java.util.Properties;
/**
* Created by sponge on 2017/6/12.
*/
public class ConfigTest extends TestCase {
public void testGetConsumerProperties() throws Exception {
Config.setConfDir("src/main/conf");
Properties props = Config.getConsumerProperties();
for(Map.Entry<Object, Object> entry : props.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("key : " + key + " value : " + value);
}
}
public void testGetProducerProperties() {
Config.setConfDir("src/main/conf");
Properties props = Config.getProducerProperties();
for(Map.Entry<Object, Object> entry : props.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println("key : " + key + " value : " + value);
}
}
}
| 1,025 | 0.608781 | 0.601951 | 33 | 30.09091 | 25.189421 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false |
9
|
7865dce4319b83c43f4ebb5bad7c482b361ea3c6
| 9,646,496,583,073 |
9f720a5c683e42dcedbb46da976247932892cac9
|
/itrip-dao/src/main/java/com/cskt/service/ItripUserService.java
|
3fc4274ede49c322eceedb2b253d38cfc23aa386
|
[] |
no_license
|
jemjojo/itripbaclkend
|
https://github.com/jemjojo/itripbaclkend
|
78af36b97026172e567cc0ac6dae669352c6653b
|
00a371375b99d8a8cd91dea2ba9f4d44d9bbfe5c
|
refs/heads/master
| 2023-03-21T00:06:46.822000 | 2021-03-02T03:28:35 | 2021-03-02T03:28:35 | 343,636,518 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cskt.service;
import com.cskt.entity.ItripUser;
import com.baomidou.mybatisplus.extension.service.IService;
public interface ItripUserService extends IService<ItripUser>{
}
|
UTF-8
|
Java
| 188 |
java
|
ItripUserService.java
|
Java
|
[] | null |
[] |
package com.cskt.service;
import com.cskt.entity.ItripUser;
import com.baomidou.mybatisplus.extension.service.IService;
public interface ItripUserService extends IService<ItripUser>{
}
| 188 | 0.829787 | 0.829787 | 8 | 22.5 | 24.974987 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
9
|
5a71412246ebde74c4e4b625ec8d410f5b3c1557
| 1,623,497,670,369 |
6deea76877f919866b6a5fb4c2b175b9310cb5b2
|
/src/com/matri/dao/impl/UserDAOImpl.java
|
31d00c1733e9a395cca2364694654c621d54d984
|
[] |
no_license
|
mehulpopat/matrimonial
|
https://github.com/mehulpopat/matrimonial
|
0c2782ca84b6fa358a40b4733f84e1c48b5e2884
|
1df8047a59788020c2703eb4aa413bb9f1f89c80
|
refs/heads/master
| 2020-03-31T02:30:17.132000 | 2018-12-02T07:47:14 | 2018-12-02T07:47:14 | 151,826,839 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.matri.dao.impl;
import java.util.HashMap;
import java.util.Map;
import com.matri.dao.UserDAO;
import com.matri.entities.User;
public class UserDAOImpl extends MasterDAOImpl implements UserDAO {
@Override
public User getUserById(Long id) {
String query = "From User where id = :id";
Map params = new HashMap();
params.put("id", id);
return (User) getSingleRow(query, params);
}
}
|
UTF-8
|
Java
| 426 |
java
|
UserDAOImpl.java
|
Java
|
[] | null |
[] |
package com.matri.dao.impl;
import java.util.HashMap;
import java.util.Map;
import com.matri.dao.UserDAO;
import com.matri.entities.User;
public class UserDAOImpl extends MasterDAOImpl implements UserDAO {
@Override
public User getUserById(Long id) {
String query = "From User where id = :id";
Map params = new HashMap();
params.put("id", id);
return (User) getSingleRow(query, params);
}
}
| 426 | 0.697183 | 0.697183 | 19 | 20.421053 | 18.826956 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.157895 | false | false |
9
|
d85b803bba14a210dde642eceaf60ca36a384415
| 17,660,905,562,544 |
5bf7511c9f5ae9e970751523aa447c0d6370544f
|
/src/test/java/com/bitbuy/usermanagement/service/UserServiceTest.java
|
e0bf9cf937d53e4e702cedf699f699f12af17b32
|
[] |
no_license
|
tilakjayswal16/UserManagement
|
https://github.com/tilakjayswal16/UserManagement
|
4aa1a4f07cc3d319ab378bc1ed93ad25dcce87d9
|
58b48efe188e7a1fbf4ca19780be3b9a610f2eb1
|
refs/heads/master
| 2023-07-22T21:39:29.655000 | 2021-09-08T06:11:54 | 2021-09-08T06:11:54 | 404,229,652 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bitbuy.usermanagement.service;
import com.bitbuy.usermanagement.constant.AppConstant;
import com.bitbuy.usermanagement.dao.UserRepository;
import com.bitbuy.usermanagement.exception.ValidationException;
import com.bitbuy.usermanagement.model.User;
import com.bitbuy.usermanagement.model.UserUpdate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.NoSuchElementException;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserRepository userRepository;
@Test
public void shouldGiveValidUserObject_getUser() {
Mockito.when(userRepository.findByUuid(getMockUUID())).thenReturn(getMockUser());
User expectedUser = userService.getUser(getMockUUID());
assertNotNull(expectedUser);
assertEquals(expectedUser.getUsername(), getMockUser().getUsername());
assertEquals(expectedUser.getPassword(), getMockUser().getPassword());
}
@Test
public void shouldThrowExceptionForInvalidUUID_getUser() {
assertThrows(NoSuchElementException.class, () -> {
userService.getUser(null);
});
}
@Test
public void shouldUpdateUserSuccessfully_updateUserByUUID() throws ValidationException {
Mockito.when(userRepository.findByUuid(getMockUUID())).thenReturn(getMockUser());
UserUpdate userToBeUpdated = new UserUpdate("changed@abc.com", "changedName",1234567890);
String expectedServiceResponse = AppConstant.USER_UPDATE_SUCCESS + getMockUUID();
String actualServiceResponse = userService.updateUserByUUID(userToBeUpdated, getMockUUID());
assertNotNull(actualServiceResponse);
assertTrue(!actualServiceResponse.isEmpty());
assertEquals(expectedServiceResponse, actualServiceResponse);
}
@Test
public void shouldThrowAnErrorForInvalidUser_updateUserByUUID() {
assertThrows(NoSuchElementException.class, () -> {
userService.updateUserByUUID(null, getMockUUID());
});
}
private User getMockUser() {
User user = new User("test", "test");
user.setEmail("test@abc.com");
user.setName("xyz");
user.setPhone(1234567890);
return user;
}
private String getMockUUID() {
return new String("ABCD");
}
}
|
UTF-8
|
Java
| 2,603 |
java
|
UserServiceTest.java
|
Java
|
[
{
"context": " UserUpdate userToBeUpdated = new UserUpdate(\"changed@abc.com\", \"changedName\",1234567890);\n\n String expe",
"end": 1688,
"score": 0.9999088048934937,
"start": 1673,
"tag": "EMAIL",
"value": "changed@abc.com"
},
{
"context": "rToBeUpdated = new UserUpdate(\"changed@abc.com\", \"changedName\",1234567890);\n\n String expectedService",
"end": 1699,
"score": 0.4890021085739136,
"start": 1692,
"tag": "USERNAME",
"value": "changed"
},
{
"context": "er getMockUser() {\n\n User user = new User(\"test\", \"test\");\n user.setEmail(\"test@abc.com\");",
"end": 2381,
"score": 0.9878559112548828,
"start": 2377,
"tag": "USERNAME",
"value": "test"
},
{
"context": " new User(\"test\", \"test\");\n user.setEmail(\"test@abc.com\");\n user.setName(\"xyz\");\n user.setP",
"end": 2428,
"score": 0.9999300241470337,
"start": 2416,
"tag": "EMAIL",
"value": "test@abc.com"
},
{
"context": "r.setEmail(\"test@abc.com\");\n user.setName(\"xyz\");\n user.setPhone(1234567890);\n ret",
"end": 2457,
"score": 0.9346434473991394,
"start": 2454,
"tag": "USERNAME",
"value": "xyz"
}
] | null |
[] |
package com.bitbuy.usermanagement.service;
import com.bitbuy.usermanagement.constant.AppConstant;
import com.bitbuy.usermanagement.dao.UserRepository;
import com.bitbuy.usermanagement.exception.ValidationException;
import com.bitbuy.usermanagement.model.User;
import com.bitbuy.usermanagement.model.UserUpdate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.NoSuchElementException;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@InjectMocks
private UserServiceImpl userService;
@Mock
private UserRepository userRepository;
@Test
public void shouldGiveValidUserObject_getUser() {
Mockito.when(userRepository.findByUuid(getMockUUID())).thenReturn(getMockUser());
User expectedUser = userService.getUser(getMockUUID());
assertNotNull(expectedUser);
assertEquals(expectedUser.getUsername(), getMockUser().getUsername());
assertEquals(expectedUser.getPassword(), getMockUser().getPassword());
}
@Test
public void shouldThrowExceptionForInvalidUUID_getUser() {
assertThrows(NoSuchElementException.class, () -> {
userService.getUser(null);
});
}
@Test
public void shouldUpdateUserSuccessfully_updateUserByUUID() throws ValidationException {
Mockito.when(userRepository.findByUuid(getMockUUID())).thenReturn(getMockUser());
UserUpdate userToBeUpdated = new UserUpdate("<EMAIL>", "changedName",1234567890);
String expectedServiceResponse = AppConstant.USER_UPDATE_SUCCESS + getMockUUID();
String actualServiceResponse = userService.updateUserByUUID(userToBeUpdated, getMockUUID());
assertNotNull(actualServiceResponse);
assertTrue(!actualServiceResponse.isEmpty());
assertEquals(expectedServiceResponse, actualServiceResponse);
}
@Test
public void shouldThrowAnErrorForInvalidUser_updateUserByUUID() {
assertThrows(NoSuchElementException.class, () -> {
userService.updateUserByUUID(null, getMockUUID());
});
}
private User getMockUser() {
User user = new User("test", "test");
user.setEmail("<EMAIL>");
user.setName("xyz");
user.setPhone(1234567890);
return user;
}
private String getMockUUID() {
return new String("ABCD");
}
}
| 2,590 | 0.722628 | 0.714944 | 89 | 28.24719 | 29.025475 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.539326 | false | false |
9
|
0c13e1ca1c6b74adf26ea5e4348fb13b8287d7a7
| 28,716,151,349,835 |
ad489a64a0cbcbd2063910e833feaf1cccf4aa21
|
/抖音达人数据分析平台源码/抖音达人数据分析平台源码/dyPlatform/src/main/java/com/lida/dy/dao/TypeRepositioy.java
|
767a3d24c15f49d87cf143251b389581542dcd51
|
[] |
no_license
|
hjhbbd/DY-Data
|
https://github.com/hjhbbd/DY-Data
|
565bb68193eed119c7835d24713243cd39ee295d
|
a38fa0f255bfa714383602559b8b6b4390d01b1d
|
refs/heads/main
| 2023-08-25T00:27:30.901000 | 2021-11-02T03:44:20 | 2021-11-02T03:44:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lida.dy.dao;
import com.lida.dy.model.entity.TalentTypeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @Auther: lida
* @Description:
* @Date 2020/1/5 0005 10:30
* @Version: 1.0
*/
public interface TypeRepositioy extends JpaRepository<TalentTypeEntity, Integer> {
public List<TalentTypeEntity> findByTypeNameEquals(String name);
}
|
UTF-8
|
Java
| 405 |
java
|
TypeRepositioy.java
|
Java
|
[
{
"context": "pository;\n\nimport java.util.List;\n\n/**\n * @Auther: lida\n * @Description:\n * @Date 2020/1/5 0005 10:30\n * ",
"end": 183,
"score": 0.9995347261428833,
"start": 179,
"tag": "USERNAME",
"value": "lida"
}
] | null |
[] |
package com.lida.dy.dao;
import com.lida.dy.model.entity.TalentTypeEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @Auther: lida
* @Description:
* @Date 2020/1/5 0005 10:30
* @Version: 1.0
*/
public interface TypeRepositioy extends JpaRepository<TalentTypeEntity, Integer> {
public List<TalentTypeEntity> findByTypeNameEquals(String name);
}
| 405 | 0.762963 | 0.723457 | 16 | 24.3125 | 25.791759 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
9
|
7cffa2d2beb387bffad3c0472a72a95b44755d3f
| 11,003,706,223,756 |
a2621a811b14785703124bb306ddf859cdff0552
|
/demoCassandra/src/main/java/waterKingCovToNoSql/tools/UtilTools.java
|
9505a53cc1bc74445723cafd592b1edba4f075cf
|
[] |
no_license
|
fhdone/meteorafhd
|
https://github.com/fhdone/meteorafhd
|
3e22266bcfbb0c3721d9c47594fd7783bee621f3
|
1e11270eb8fad403f2a7c6c73556e9ecdcb83c80
|
refs/heads/master
| 2018-09-23T03:43:00.169000 | 2015-03-14T06:28:36 | 2015-03-14T06:28:36 | 32,193,390 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package waterKingCovToNoSql.tools;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.apache.cassandra.service.Cassandra;
import org.apache.cassandra.service.ColumnPath;
import org.apache.cassandra.service.Cassandra.Client;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class UtilTools {
static private Client cassandraClient;
static private final String keyspace = "WATER_KING";
static private Map<String,Map<String,ColumnPath>> columnPathMap = new HashMap<String,Map<String,ColumnPath>>();
synchronized public static Client getCassandraClient() {
if( cassandraClient!=null){
return cassandraClient;
}
String server = "127.0.0.1";
int port = 9160;
/* 首先指定cassandra server的地址 */
TTransport socket = new TSocket(server, port);
System.out.println(" connected to " + server + ":" + port + ".");
/* 指定通信协议为二进制流协议 */
TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, false, false);
cassandraClient = new Cassandra.Client(binaryProtocol);
/* 建立通信连接 */
try{
socket.open();
}catch( TTransportException e ){
System.out.println("connect DB happen error");
throw new RuntimeException(e);
}
return cassandraClient;
}
public static Map<String,ColumnPath> getColumnPath(Object obj , String cfName ){
Map<String,ColumnPath> returnMap = new HashMap<String,ColumnPath>();
Class c = obj.getClass();
if( columnPathMap.get(cfName)!=null ){
return columnPathMap.get(cfName);
}
Field objFields[] = c.getDeclaredFields();
int length = objFields.length;
Field.setAccessible(objFields, true);
for(int i = 0;i < length; i++){
try{
String colPathName = objFields[i].getName() ;
System.out.println("create ColumnPath "+colPathName);
ColumnPath cp = new ColumnPath(cfName, null, colPathName.getBytes());
returnMap.put(objFields[i].getName() , cp );
}catch(Exception e){
e.printStackTrace();
}
}
columnPathMap.put(cfName, returnMap);
return returnMap;
}
public static String getKeyspace() {
return keyspace;
}
}
|
GB18030
|
Java
| 2,509 |
java
|
UtilTools.java
|
Java
|
[
{
"context": "Client;\r\n\tstatic private final String keyspace = \"WATER_KING\";\r\n\tstatic private Map<String,Map<String,ColumnPa",
"end": 602,
"score": 0.9987238049507141,
"start": 592,
"tag": "KEY",
"value": "WATER_KING"
},
{
"context": "aClient;\r\n \t}\r\n \t\r\n String server = \"127.0.0.1\";\r\n int port = 9160;\r\n \r\n /* 首",
"end": 901,
"score": 0.9983050227165222,
"start": 892,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null |
[] |
package waterKingCovToNoSql.tools;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.apache.cassandra.service.Cassandra;
import org.apache.cassandra.service.ColumnPath;
import org.apache.cassandra.service.Cassandra.Client;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class UtilTools {
static private Client cassandraClient;
static private final String keyspace = "WATER_KING";
static private Map<String,Map<String,ColumnPath>> columnPathMap = new HashMap<String,Map<String,ColumnPath>>();
synchronized public static Client getCassandraClient() {
if( cassandraClient!=null){
return cassandraClient;
}
String server = "127.0.0.1";
int port = 9160;
/* 首先指定cassandra server的地址 */
TTransport socket = new TSocket(server, port);
System.out.println(" connected to " + server + ":" + port + ".");
/* 指定通信协议为二进制流协议 */
TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, false, false);
cassandraClient = new Cassandra.Client(binaryProtocol);
/* 建立通信连接 */
try{
socket.open();
}catch( TTransportException e ){
System.out.println("connect DB happen error");
throw new RuntimeException(e);
}
return cassandraClient;
}
public static Map<String,ColumnPath> getColumnPath(Object obj , String cfName ){
Map<String,ColumnPath> returnMap = new HashMap<String,ColumnPath>();
Class c = obj.getClass();
if( columnPathMap.get(cfName)!=null ){
return columnPathMap.get(cfName);
}
Field objFields[] = c.getDeclaredFields();
int length = objFields.length;
Field.setAccessible(objFields, true);
for(int i = 0;i < length; i++){
try{
String colPathName = objFields[i].getName() ;
System.out.println("create ColumnPath "+colPathName);
ColumnPath cp = new ColumnPath(cfName, null, colPathName.getBytes());
returnMap.put(objFields[i].getName() , cp );
}catch(Exception e){
e.printStackTrace();
}
}
columnPathMap.put(cfName, returnMap);
return returnMap;
}
public static String getKeyspace() {
return keyspace;
}
}
| 2,509 | 0.658934 | 0.654457 | 78 | 29.5 | 24.658566 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.576923 | false | false |
9
|
95ee34cab501d73a741cfa01fecfaff215440c8a
| 1,967,095,088,019 |
693995978adb623590dfc215fa166961af70fe8f
|
/core/core-activity/src/main/java/com/shanjin/service/IOrderRewardService.java
|
6277b3eb35299734a3a6ef845068aa31afa4311d
|
[] |
no_license
|
yxxcrtd/omeng.cc
|
https://github.com/yxxcrtd/omeng.cc
|
13ea163bee5cd89bd5a50388e7aae81da3355ca0
|
dffea0dbc666272712e82ef4ce25e427f97d05a1
|
refs/heads/master
| 2022-12-24T07:36:07.662000 | 2019-06-05T07:38:14 | 2019-06-05T07:38:14 | 190,348,103 | 1 | 1 | null | false | 2022-12-16T07:52:01 | 2019-06-05T07:35:46 | 2020-01-20T18:28:03 | 2022-12-16T07:52:01 | 8,807 | 1 | 1 | 57 |
Java
| false | false |
package com.shanjin.service;
import com.alibaba.fastjson.JSONObject;
public interface IOrderRewardService {
public abstract JSONObject getOrderRewardByMerId(String paramString, String activityId);
public abstract JSONObject getOrderRewardList(String paramString, String activityId, int paramInt1, int paramInt2);
}
|
UTF-8
|
Java
| 332 |
java
|
IOrderRewardService.java
|
Java
|
[] | null |
[] |
package com.shanjin.service;
import com.alibaba.fastjson.JSONObject;
public interface IOrderRewardService {
public abstract JSONObject getOrderRewardByMerId(String paramString, String activityId);
public abstract JSONObject getOrderRewardList(String paramString, String activityId, int paramInt1, int paramInt2);
}
| 332 | 0.810241 | 0.804217 | 9 | 34.888889 | 40.577621 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.111111 | false | false |
9
|
eb8da8b9d9132c0e7f4b06f6fe0a37f095d54870
| 36,412,732,759,614 |
9994ad943b02b03211cca9692abd66515968db40
|
/dukandar-app/jan18-3am-back/Dukandar-18-jan/src/main/java/com/example/demo/controller/VendorController.java
|
49f94bc3a58807918669d33dc4851aadddba90f8
|
[] |
no_license
|
pratikgd111/Projects
|
https://github.com/pratikgd111/Projects
|
88ace1d50c5fac50e61a555dcb3f69b0702ef313
|
bf5d66173f76f9fee210a6f4206e420ae01d3d90
|
refs/heads/master
| 2023-08-14T04:53:37.007000 | 2021-09-17T06:10:07 | 2021-09-17T06:10:07 | 297,138,715 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.demo.controller;
import com.example.demo.Dao.IAccountRepository;
import com.example.demo.Dao.IPostRepository;
import com.example.demo.pojo.*;
import com.example.demo.security.JwtTokenProvider;
import com.example.demo.service.*;
import com.example.demo.util.ReviewInfo;
import com.example.demo.util.SessionRelated;
import com.example.demo.util.ShopEnquiryInfo;
import com.example.demo.util.StringObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/vendor")
@CrossOrigin
public class VendorController {
@Autowired
private IAccountRepository accountRepo;
@Autowired
private JwtTokenProvider jwtService;
@Autowired
private IVendorService vendorService;
@Autowired
private IVendorInfoService vendorInfoService;
@Autowired
private IShopAddressService shopAddressService;
@Autowired
private AmazonClient amazonClient;
@Autowired
private IPostRepository postRepository;
@Autowired
private IReviewService reviewService;
@Autowired
private IShopEnquiryService shopEnquiryService;
@GetMapping("/personal-info")
public ResponseEntity<?> getPersonalInfo(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
VendorInfo vendorInfo = v.getVendorInfo();
return new ResponseEntity<>(vendorInfo, HttpStatus.OK);
}
@GetMapping("/get-shop-address")
public ResponseEntity<?> getShopAddress(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
return new ResponseEntity<>(v.getAddress(), HttpStatus.OK);
}
@GetMapping("/shop-info")
public ResponseEntity<?> getShopInfo(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
ShopDetails shopDetails = v.getShopDetails();
return new ResponseEntity<>(shopDetails,HttpStatus.OK);
}
@GetMapping("get-domain-info")
public ResponseEntity<?> getDomainInfo(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
Domain domain = v.getDomain();
return new ResponseEntity<>(new StringObject(domain.getType().toString()), HttpStatus.OK);
}
@PostMapping("/personal-info")
public ResponseEntity<?> saveVendorInfo(@RequestBody VendorInfo vendorInfo,@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
Vendor vendor = vendorService.getVendor(v.getVendorId());
vendorInfo.setVendorInfoId(vendor.getVendorInfo().getVendorInfoId());
vendorInfo.setPhoto(vendor.getVendorInfo().getPhoto());
vendor.addVendorInfo(vendorInfo);
Vendor vendor1 = vendorService.saveVendor(vendor);
return new ResponseEntity<>(vendor1.getVendorInfo(), HttpStatus.OK);
}
@PostMapping("/save-post")
public ResponseEntity<?> saveVendorPost(@RequestBody Post post,@RequestHeader int postId){
Post post1 = postRepository.findById(postId).get();
post1.setOfferName(post.getOfferName());
post1.setOfferDescription(post.getOfferDescription());
post1.setValid_till(post.getValid_till());
Post post2 = postRepository.save(post1);
return new ResponseEntity<>(post2, HttpStatus.OK);
}
@GetMapping("get-all-posts")
public ResponseEntity<?> getAllPosts(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
List<Post> allPosts =v.getPosts();
return new ResponseEntity<>(allPosts, HttpStatus.OK);
}
@PostMapping("/upload-file")
public ResponseEntity<?> uploadVendorPhoto(@RequestPart(value = "file") MultipartFile file, @RequestPart(value="token") String token) {
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
/*
Vendor v =null;
Role role = SessionRelated.getRoleOfAccount(token);
if(role.equals(Role.VENDOR)){
int id = SessionRelated.getUserOrVendorId(token);
v = vendorService.getVendor(id);
}*/
String fileUrl = this.amazonClient.uploadFile(file);
VendorInfo vendorInfo = new VendorInfo();
vendorInfo.setPhoto(fileUrl);
v.addVendorInfo(vendorInfo);
Vendor vendor1 = vendorService.saveVendor(v);
return new ResponseEntity<>(vendor1.getVendorInfo(), HttpStatus.OK);
}
@PostMapping("/upload-shop-photo")
public ResponseEntity<?> uploadShopPhoto(@RequestPart(value = "file") MultipartFile file, @RequestPart(value="token") String token) {
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
String fileUrl = this.amazonClient.uploadFile(file);
ShopPhotos shopPhotos = new ShopPhotos();
shopPhotos.setPhoto(fileUrl);
v.addShopPhoto(shopPhotos);
Vendor vendor1 = vendorService.saveVendor(v);
return new ResponseEntity<>(vendor1.getShopPhotos(), HttpStatus.OK);
}
@PostMapping("/upload-post-image")
public ResponseEntity<?> uploadPostImage(@RequestPart(value = "file") MultipartFile file, @RequestPart String token) {
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
String fileUrl = this.amazonClient.uploadFile(file);
Post post = new Post();
post.setPhoto(fileUrl);
v.addPost(post);
Post post1 = postRepository.save(post);
return new ResponseEntity<>(post1, HttpStatus.OK);
}
@DeleteMapping("/delete-file")
public String deleteFile(@RequestPart(value = "url") String fileUrl) {
String message = this.amazonClient.deleteFileFromS3Bucket(fileUrl);
return message;
}
@GetMapping("/get-shop-photos")
public ResponseEntity<?> getAllShopPhotos(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
return new ResponseEntity<>(v.getShopPhotos(), HttpStatus.OK);
}
@GetMapping("/shop-reviews")
public ResponseEntity<?> getAllShopReviews(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
List<ReviewInfo> allShopReviews = reviewService.getAllShopReviews(v);
return new ResponseEntity<>( allShopReviews, HttpStatus.OK);
}
else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping("/shop-enquiries")
public ResponseEntity<?> getShopEnquries(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
List<ShopEnquiryInfo> allShopEnquries = shopEnquiryService.getEnquiry(v);
return new ResponseEntity<>( allShopEnquries, HttpStatus.OK);
}
else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
|
UTF-8
|
Java
| 10,950 |
java
|
VendorController.java
|
Java
|
[] | null |
[] |
package com.example.demo.controller;
import com.example.demo.Dao.IAccountRepository;
import com.example.demo.Dao.IPostRepository;
import com.example.demo.pojo.*;
import com.example.demo.security.JwtTokenProvider;
import com.example.demo.service.*;
import com.example.demo.util.ReviewInfo;
import com.example.demo.util.SessionRelated;
import com.example.demo.util.ShopEnquiryInfo;
import com.example.demo.util.StringObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/vendor")
@CrossOrigin
public class VendorController {
@Autowired
private IAccountRepository accountRepo;
@Autowired
private JwtTokenProvider jwtService;
@Autowired
private IVendorService vendorService;
@Autowired
private IVendorInfoService vendorInfoService;
@Autowired
private IShopAddressService shopAddressService;
@Autowired
private AmazonClient amazonClient;
@Autowired
private IPostRepository postRepository;
@Autowired
private IReviewService reviewService;
@Autowired
private IShopEnquiryService shopEnquiryService;
@GetMapping("/personal-info")
public ResponseEntity<?> getPersonalInfo(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
VendorInfo vendorInfo = v.getVendorInfo();
return new ResponseEntity<>(vendorInfo, HttpStatus.OK);
}
@GetMapping("/get-shop-address")
public ResponseEntity<?> getShopAddress(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
return new ResponseEntity<>(v.getAddress(), HttpStatus.OK);
}
@GetMapping("/shop-info")
public ResponseEntity<?> getShopInfo(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
ShopDetails shopDetails = v.getShopDetails();
return new ResponseEntity<>(shopDetails,HttpStatus.OK);
}
@GetMapping("get-domain-info")
public ResponseEntity<?> getDomainInfo(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
Domain domain = v.getDomain();
return new ResponseEntity<>(new StringObject(domain.getType().toString()), HttpStatus.OK);
}
@PostMapping("/personal-info")
public ResponseEntity<?> saveVendorInfo(@RequestBody VendorInfo vendorInfo,@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
Vendor vendor = vendorService.getVendor(v.getVendorId());
vendorInfo.setVendorInfoId(vendor.getVendorInfo().getVendorInfoId());
vendorInfo.setPhoto(vendor.getVendorInfo().getPhoto());
vendor.addVendorInfo(vendorInfo);
Vendor vendor1 = vendorService.saveVendor(vendor);
return new ResponseEntity<>(vendor1.getVendorInfo(), HttpStatus.OK);
}
@PostMapping("/save-post")
public ResponseEntity<?> saveVendorPost(@RequestBody Post post,@RequestHeader int postId){
Post post1 = postRepository.findById(postId).get();
post1.setOfferName(post.getOfferName());
post1.setOfferDescription(post.getOfferDescription());
post1.setValid_till(post.getValid_till());
Post post2 = postRepository.save(post1);
return new ResponseEntity<>(post2, HttpStatus.OK);
}
@GetMapping("get-all-posts")
public ResponseEntity<?> getAllPosts(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
List<Post> allPosts =v.getPosts();
return new ResponseEntity<>(allPosts, HttpStatus.OK);
}
@PostMapping("/upload-file")
public ResponseEntity<?> uploadVendorPhoto(@RequestPart(value = "file") MultipartFile file, @RequestPart(value="token") String token) {
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
/*
Vendor v =null;
Role role = SessionRelated.getRoleOfAccount(token);
if(role.equals(Role.VENDOR)){
int id = SessionRelated.getUserOrVendorId(token);
v = vendorService.getVendor(id);
}*/
String fileUrl = this.amazonClient.uploadFile(file);
VendorInfo vendorInfo = new VendorInfo();
vendorInfo.setPhoto(fileUrl);
v.addVendorInfo(vendorInfo);
Vendor vendor1 = vendorService.saveVendor(v);
return new ResponseEntity<>(vendor1.getVendorInfo(), HttpStatus.OK);
}
@PostMapping("/upload-shop-photo")
public ResponseEntity<?> uploadShopPhoto(@RequestPart(value = "file") MultipartFile file, @RequestPart(value="token") String token) {
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
String fileUrl = this.amazonClient.uploadFile(file);
ShopPhotos shopPhotos = new ShopPhotos();
shopPhotos.setPhoto(fileUrl);
v.addShopPhoto(shopPhotos);
Vendor vendor1 = vendorService.saveVendor(v);
return new ResponseEntity<>(vendor1.getShopPhotos(), HttpStatus.OK);
}
@PostMapping("/upload-post-image")
public ResponseEntity<?> uploadPostImage(@RequestPart(value = "file") MultipartFile file, @RequestPart String token) {
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
String fileUrl = this.amazonClient.uploadFile(file);
Post post = new Post();
post.setPhoto(fileUrl);
v.addPost(post);
Post post1 = postRepository.save(post);
return new ResponseEntity<>(post1, HttpStatus.OK);
}
@DeleteMapping("/delete-file")
public String deleteFile(@RequestPart(value = "url") String fileUrl) {
String message = this.amazonClient.deleteFileFromS3Bucket(fileUrl);
return message;
}
@GetMapping("/get-shop-photos")
public ResponseEntity<?> getAllShopPhotos(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
}
return new ResponseEntity<>(v.getShopPhotos(), HttpStatus.OK);
}
@GetMapping("/shop-reviews")
public ResponseEntity<?> getAllShopReviews(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
List<ReviewInfo> allShopReviews = reviewService.getAllShopReviews(v);
return new ResponseEntity<>( allShopReviews, HttpStatus.OK);
}
else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping("/shop-enquiries")
public ResponseEntity<?> getShopEnquries(@RequestHeader String token){
String jwt= token.substring(7);
int accId=jwtService.getValidatedAccountId(jwt);
Integer account_id = Integer.valueOf(accId);
//String role = jwtService.getValidatedAccountRole(token);
Account account=accountRepo.getByAccountId(account_id);
Vendor v=null;
if(account.getRole().equals(Role.VENDOR)) {
v=account.getV();
List<ShopEnquiryInfo> allShopEnquries = shopEnquiryService.getEnquiry(v);
return new ResponseEntity<>( allShopEnquries, HttpStatus.OK);
}
else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
| 10,950 | 0.668402 | 0.665845 | 362 | 29.248619 | 27.937164 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.491713 | false | false |
9
|
f9b85ac9a9217792de5a89c41947bf92f93972e4
| 38,706,245,307,786 |
aca883133b1beb991044057b58a5c89ac862f8ce
|
/app/src/main/java/com/example/cake/sync/service/ProcessRequest.java
|
13ddcdbd9a2bb6c5bd50fda2a5172976cdfe1fb9
|
[] |
no_license
|
Devabrata-Kakati/supercake
|
https://github.com/Devabrata-Kakati/supercake
|
193e63c2a002c72f3eddcb5933de28e0ebb4bb6f
|
be7cc1a6dc37c6eb65579f093297b332d3701b9f
|
refs/heads/master
| 2018-01-08T00:20:41.054000 | 2015-10-23T12:03:10 | 2015-10-23T12:03:10 | 44,810,650 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.cake.sync.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
import com.example.cake.bean.SummitOrderbean;
import com.example.cake.dataobjects.DataSyncResponse;
public class ProcessRequest {
public DataSyncResponse fetchDataFromServer(String url) {
ProcessResponse processResponse = new ProcessResponse();
DataSyncResponse dataResponse = null;
// String url = ApplicationConstants.HTTP_CAKE_PRODUCT_API;
System.out.println("hit url :::::::::::"+url);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
// Execute the request
HttpResponse response;
String result = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
if (response.getStatusLine().getStatusCode() != 401) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
dataResponse = (DataSyncResponse) processResponse.processDataSyncRetailerOwnerResponse(result);
instream.close();
} else {
Log.d("ProcessJsonRequest", "Authenication Failed::");
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataResponse;
}
public SummitOrderbean summitDataFromServer(String url, String dataToBeSend) {
ProcessResponse processResponse = new ProcessResponse();
SummitOrderbean dataResponse = null;
// String url = ApplicationConstants.HTTP_CAKE_PRODUCT_API;
try {
System.out.println("hit url :::::::::::"+url);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
StringEntity se;
se = new StringEntity(dataToBeSend);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// Execute the request
HttpResponse response;
String result = null;
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
if (response.getStatusLine().getStatusCode() != 401) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
dataResponse = (SummitOrderbean) processResponse.summitDataResponse(result);
instream.close();
} else {
Log.d("ProcessJsonRequest", "Authenication Failed::");
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataResponse;
}
public DataSyncResponse fetchLocationDataFromServer(String url) {
ProcessResponse processResponse = new ProcessResponse();
DataSyncResponse dataResponse = null;
System.out.println("hit url :::::::::::"+url);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
// Execute the request
HttpResponse response;
String result = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
if (response.getStatusLine().getStatusCode() != 401) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
dataResponse = (DataSyncResponse) processResponse.processDataSyncLocationResponse(result);
instream.close();
} else {
Log.d("ProcessJsonRequest", "Authenication Failed::");
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataResponse;
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
|
UTF-8
|
Java
| 4,912 |
java
|
ProcessRequest.java
|
Java
|
[] | null |
[] |
package com.example.cake.sync.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
import com.example.cake.bean.SummitOrderbean;
import com.example.cake.dataobjects.DataSyncResponse;
public class ProcessRequest {
public DataSyncResponse fetchDataFromServer(String url) {
ProcessResponse processResponse = new ProcessResponse();
DataSyncResponse dataResponse = null;
// String url = ApplicationConstants.HTTP_CAKE_PRODUCT_API;
System.out.println("hit url :::::::::::"+url);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
// Execute the request
HttpResponse response;
String result = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
if (response.getStatusLine().getStatusCode() != 401) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
dataResponse = (DataSyncResponse) processResponse.processDataSyncRetailerOwnerResponse(result);
instream.close();
} else {
Log.d("ProcessJsonRequest", "Authenication Failed::");
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataResponse;
}
public SummitOrderbean summitDataFromServer(String url, String dataToBeSend) {
ProcessResponse processResponse = new ProcessResponse();
SummitOrderbean dataResponse = null;
// String url = ApplicationConstants.HTTP_CAKE_PRODUCT_API;
try {
System.out.println("hit url :::::::::::"+url);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
StringEntity se;
se = new StringEntity(dataToBeSend);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// Execute the request
HttpResponse response;
String result = null;
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
if (response.getStatusLine().getStatusCode() != 401) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
dataResponse = (SummitOrderbean) processResponse.summitDataResponse(result);
instream.close();
} else {
Log.d("ProcessJsonRequest", "Authenication Failed::");
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataResponse;
}
public DataSyncResponse fetchLocationDataFromServer(String url) {
ProcessResponse processResponse = new ProcessResponse();
DataSyncResponse dataResponse = null;
System.out.println("hit url :::::::::::"+url);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
// Execute the request
HttpResponse response;
String result = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
if (response.getStatusLine().getStatusCode() != 401) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
dataResponse = (DataSyncResponse) processResponse.processDataSyncLocationResponse(result);
instream.close();
} else {
Log.d("ProcessJsonRequest", "Authenication Failed::");
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataResponse;
}
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
| 4,912 | 0.707451 | 0.705619 | 183 | 25.84153 | 22.176687 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.469945 | false | false |
9
|
b5570e1c0b0b61678e5b943ff3042612184abdb3
| 38,671,885,538,990 |
6957f79a6e5209ee30815a09c3e99e833daf3a02
|
/SmallSecuredApp/src/main/java/dev/saranda/springsecurity/smallsecuredapp/repository/ProductRepository.java
|
e3b6f398460c839e262cf9b1116308cd6c8358b2
|
[] |
no_license
|
Bezifabr/SpringSecurityTraining
|
https://github.com/Bezifabr/SpringSecurityTraining
|
1df96a8bafda36e841a40822f552ee70ec7a4241
|
1105076c9c647b6b3ee463bced70fe9394206d34
|
refs/heads/main
| 2023-03-05T07:59:46.982000 | 2021-02-19T23:55:45 | 2021-02-19T23:55:45 | 338,346,354 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dev.saranda.springsecurity.smallsecuredapp.repository;
import dev.saranda.springsecurity.smallsecuredapp.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Integer> {
}
|
UTF-8
|
Java
| 271 |
java
|
ProductRepository.java
|
Java
|
[] | null |
[] |
package dev.saranda.springsecurity.smallsecuredapp.repository;
import dev.saranda.springsecurity.smallsecuredapp.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Integer> {
}
| 271 | 0.859779 | 0.859779 | 7 | 37.714287 | 32.692131 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
9
|
8472a7255bf5fefbdb71393122a56cbaccb8f93f
| 38,843,684,265,464 |
6f565ece8f8b29f429457be7462aa31c5f67aa8e
|
/streamcaster/src/main/java/org/lavajug/streamcaster/plugins/AbstractPlugin.java
|
057e435dd429db0694ec3b62718aa81dfede76fa
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
ndeloof/stream-catcher
|
https://github.com/ndeloof/stream-catcher
|
7b915fddb31d51a3cb58f2d71e416d9053fd08a1
|
55e5f9fb04f5a5091c1ff983cba6d02d882e277c
|
refs/heads/master
| 2019-08-08T22:23:53.694000 | 2016-03-06T18:46:41 | 2016-03-06T18:46:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2014 LavaJUG.
*
* 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.lavajug.streamcaster.plugins;
import java.awt.image.BufferedImage;
import java.util.Map;
/**
*
* @author Sylvain Desgrais <sylvain.desgrais@gmail.com>
*/
public abstract class AbstractPlugin implements Plugin {
private boolean initialized = false;
private Map<String, BufferedImage> reciever;
private String name;
@Override
public final void run() {
if (!initialized) {
this.init();
this.initialized = true;
}
send(this.produce());
}
/**
*
* @param name of the source
* @param reciever is the container where put the image when it is computed
*/
@Override
public final void setReciever(String name, Map<String, BufferedImage> reciever) {
this.reciever = reciever;
this.name = name;
}
/**
* set the image in the container when it is ready to use
*
* @param image computed
*/
protected final void send(BufferedImage image) {
this.reciever.put(name, image);
}
}
|
UTF-8
|
Java
| 1,565 |
java
|
AbstractPlugin.java
|
Java
|
[
{
"context": "edImage;\nimport java.util.Map;\n\n/**\n * \n * @author Sylvain Desgrais <sylvain.desgrais@gmail.com>\n */\npublic abstract ",
"end": 732,
"score": 0.9998900890350342,
"start": 716,
"tag": "NAME",
"value": "Sylvain Desgrais"
},
{
"context": "a.util.Map;\n\n/**\n * \n * @author Sylvain Desgrais <sylvain.desgrais@gmail.com>\n */\npublic abstract class AbstractPlugin impleme",
"end": 760,
"score": 0.9999315738677979,
"start": 734,
"tag": "EMAIL",
"value": "sylvain.desgrais@gmail.com"
}
] | null |
[] |
/*
* Copyright 2014 LavaJUG.
*
* 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.lavajug.streamcaster.plugins;
import java.awt.image.BufferedImage;
import java.util.Map;
/**
*
* @author <NAME> <<EMAIL>>
*/
public abstract class AbstractPlugin implements Plugin {
private boolean initialized = false;
private Map<String, BufferedImage> reciever;
private String name;
@Override
public final void run() {
if (!initialized) {
this.init();
this.initialized = true;
}
send(this.produce());
}
/**
*
* @param name of the source
* @param reciever is the container where put the image when it is computed
*/
@Override
public final void setReciever(String name, Map<String, BufferedImage> reciever) {
this.reciever = reciever;
this.name = name;
}
/**
* set the image in the container when it is ready to use
*
* @param image computed
*/
protected final void send(BufferedImage image) {
this.reciever.put(name, image);
}
}
| 1,536 | 0.695208 | 0.690096 | 62 | 24.241936 | 24.984953 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.33871 | false | false |
1
|
0bb6e1bfbc47322fdea70e2954a4aedefc8e8c68
| 22,643,067,645,681 |
6abd2ee3afacaa2af7237629f22a732696c6826e
|
/Mango API/src/com/serotonin/m2m2/web/mvc/rest/v1/model/pointValue/IdPointValueTimeCsvStreamCallback.java
|
888ddb6dcc728d2f9f004809bf18970313173dfe
|
[] |
no_license
|
PLCMercenary/ma-modules-public
|
https://github.com/PLCMercenary/ma-modules-public
|
32ff2d97bf1b560153390c4b334ec6c4a481f5a3
|
3c3b7d23d927b664c22891df5c6fa65353e4a8af
|
refs/heads/main
| 2020-12-04T13:01:49.968000 | 2020-01-03T20:20:54 | 2020-01-03T20:20:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Copyright (C) 2015 Infinite Automation Software. All rights reserved.
* @author Terry Packer
*/
package com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue;
import java.io.IOException;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.infiniteautomation.mango.util.Functions;
import com.serotonin.db.MappedRowCallback;
import com.serotonin.m2m2.DataTypes;
import com.serotonin.m2m2.rt.dataImage.IdPointValueTime;
import com.serotonin.m2m2.rt.dataImage.types.DataValue;
import com.serotonin.m2m2.rt.dataImage.types.NumericValue;
import com.serotonin.m2m2.vo.DataPointVO;
import au.com.bytecode.opencsv.CSVWriter;
/**
*
* CSV Format is point per column, all points plus time columns per row. Useful in multi point
* queries
*
* @author Terry Packer
*
*/
public class IdPointValueTimeCsvStreamCallback extends PointValueTimeCsvWriter implements MappedRowCallback<IdPointValueTime>{
private final Log LOG = LogFactory.getLog(PointValueTimeJsonStreamCallback.class);
private final String TIMESTAMP = "timestamp";
private final LimitCounter limiter;
private final Map<Integer, DataPointVO> voMap;
private long currentTime;
//Map of data point Id to column ID
private final Map<Integer, Integer> columnMap;
private final String[] headers;
private String[] rowData;
private boolean wroteHeaders;
/**
*
* @param writer
* @param voMap
* @param useRendered
* @param unitConversion
* @param limit
* @param dateTimeFormat - format for date strings, if null then use epoch millis number
* @param timezone
*/
public IdPointValueTimeCsvStreamCallback(CSVWriter writer, Map<Integer, DataPointVO> voMap, boolean useRendered, boolean unitConversion, Integer limit, String dateTimeFormat, String timezone) {
super(writer, useRendered, unitConversion, dateTimeFormat, timezone);
this.limiter = new LimitCounter(limit);
this.voMap = voMap;
this.currentTime = Long.MIN_VALUE;
this.wroteHeaders = false;
this.columnMap = new HashMap<Integer,Integer>(voMap.size());
this.rowData = new String[voMap.size() + 1];
this.headers = new String[voMap.size() + 1];
this.headers[0] = TIMESTAMP;
//Generate the column Ids and Header
int columnId = 1;
DataPointVO vo;
Iterator<Integer> it = this.voMap.keySet().iterator();
while(it.hasNext()){
Integer id = it.next();
vo = voMap.get(id);
this.columnMap.put(id, columnId);
this.headers[columnId] = vo.getXid();
columnId++;
}
}
/* (non-Javadoc)
* @see com.serotonin.db.MappedRowCallback#row(java.lang.Object, int)
*/
@Override
public void row(IdPointValueTime pvt, int index) {
try{
DataPointVO vo = this.voMap.get(pvt.getId());
long time = pvt.getTime();
if(dateFormatter == null)
this.rowData[0] = Long.toString(time);
else
this.rowData[0] = dateFormatter.format(ZonedDateTime
.ofInstant(Instant.ofEpochMilli(time), TimeZone.getDefault().toZoneId()));
//Ensure we are saving into the correct time entry
if(this.currentTime != time){
if(!wroteHeaders){
this.writer.writeNext(headers);
this.wroteHeaders = true;
}else{
//Write the line
if(this.limiter.limited())
return;
this.writer.writeNext(rowData);
for(int i=0; i< this.rowData.length; i++)
this.rowData[i] = new String();
}
this.currentTime = time;
}
if(useRendered){
//Convert to Alphanumeric Value
this.rowData[this.columnMap.get(vo.getId())] = Functions.getRenderedText(vo, pvt);
}else if(unitConversion){
if (pvt.getValue() instanceof NumericValue)
this.rowData[this.columnMap.get(vo.getId())] = Double.toString(vo.getUnit().getConverterTo(vo.getRenderedUnit()).convert(pvt.getValue().getDoubleValue()));
else
this.rowData[this.columnMap.get(vo.getId())] = this.createDataValueString(pvt.getValue());
}else{
if(vo.getPointLocator().getDataTypeId() == DataTypes.IMAGE)
this.rowData[this.columnMap.get(vo.getId())] = imageServletBuilder.buildAndExpand(pvt.getTime(), vo.getId()).toUri().toString();
else
this.rowData[this.columnMap.get(vo.getId())] = this.createDataValueString(pvt.getValue());
}
}catch(Exception e){
LOG.error(e.getMessage(), e);
}
}
private String createDataValueString(DataValue value){
if(value == null){
return "";
}else{
switch(value.getDataType()){
case DataTypes.ALPHANUMERIC:
return value.getStringValue();
case DataTypes.BINARY:
return Boolean.toString(value.getBooleanValue());
case DataTypes.MULTISTATE:
return Integer.toString(value.getIntegerValue());
case DataTypes.NUMERIC:
return Double.toString(value.getDoubleValue());
default:
LOG.error("Unsupported data type for DataValue: " + value.getDataType());
return "unsupported-value-type";
}
}
}
/**
* Finish any open objects
* @throws IOException
*/
public void finish(){
if((this.wroteHeaders)&&(!this.limiter.limited())){
this.writer.writeNext(rowData);
}
}
}
|
UTF-8
|
Java
| 5,228 |
java
|
IdPointValueTimeCsvStreamCallback.java
|
Java
|
[
{
"context": "tomation Software. All rights reserved.\n * @author Terry Packer\n */\npackage com.serotonin.m2m2.web.mvc.rest.v1.mo",
"end": 100,
"score": 0.9998562335968018,
"start": 88,
"tag": "NAME",
"value": "Terry Packer"
},
{
"context": " Useful in multi point \n * queries\n * \n * @author Terry Packer\n *\n */\npublic class IdPointValueTimeCsvStreamCall",
"end": 975,
"score": 0.9998481869697571,
"start": 963,
"tag": "NAME",
"value": "Terry Packer"
}
] | null |
[] |
/**
* Copyright (C) 2015 Infinite Automation Software. All rights reserved.
* @author <NAME>
*/
package com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue;
import java.io.IOException;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.infiniteautomation.mango.util.Functions;
import com.serotonin.db.MappedRowCallback;
import com.serotonin.m2m2.DataTypes;
import com.serotonin.m2m2.rt.dataImage.IdPointValueTime;
import com.serotonin.m2m2.rt.dataImage.types.DataValue;
import com.serotonin.m2m2.rt.dataImage.types.NumericValue;
import com.serotonin.m2m2.vo.DataPointVO;
import au.com.bytecode.opencsv.CSVWriter;
/**
*
* CSV Format is point per column, all points plus time columns per row. Useful in multi point
* queries
*
* @author <NAME>
*
*/
public class IdPointValueTimeCsvStreamCallback extends PointValueTimeCsvWriter implements MappedRowCallback<IdPointValueTime>{
private final Log LOG = LogFactory.getLog(PointValueTimeJsonStreamCallback.class);
private final String TIMESTAMP = "timestamp";
private final LimitCounter limiter;
private final Map<Integer, DataPointVO> voMap;
private long currentTime;
//Map of data point Id to column ID
private final Map<Integer, Integer> columnMap;
private final String[] headers;
private String[] rowData;
private boolean wroteHeaders;
/**
*
* @param writer
* @param voMap
* @param useRendered
* @param unitConversion
* @param limit
* @param dateTimeFormat - format for date strings, if null then use epoch millis number
* @param timezone
*/
public IdPointValueTimeCsvStreamCallback(CSVWriter writer, Map<Integer, DataPointVO> voMap, boolean useRendered, boolean unitConversion, Integer limit, String dateTimeFormat, String timezone) {
super(writer, useRendered, unitConversion, dateTimeFormat, timezone);
this.limiter = new LimitCounter(limit);
this.voMap = voMap;
this.currentTime = Long.MIN_VALUE;
this.wroteHeaders = false;
this.columnMap = new HashMap<Integer,Integer>(voMap.size());
this.rowData = new String[voMap.size() + 1];
this.headers = new String[voMap.size() + 1];
this.headers[0] = TIMESTAMP;
//Generate the column Ids and Header
int columnId = 1;
DataPointVO vo;
Iterator<Integer> it = this.voMap.keySet().iterator();
while(it.hasNext()){
Integer id = it.next();
vo = voMap.get(id);
this.columnMap.put(id, columnId);
this.headers[columnId] = vo.getXid();
columnId++;
}
}
/* (non-Javadoc)
* @see com.serotonin.db.MappedRowCallback#row(java.lang.Object, int)
*/
@Override
public void row(IdPointValueTime pvt, int index) {
try{
DataPointVO vo = this.voMap.get(pvt.getId());
long time = pvt.getTime();
if(dateFormatter == null)
this.rowData[0] = Long.toString(time);
else
this.rowData[0] = dateFormatter.format(ZonedDateTime
.ofInstant(Instant.ofEpochMilli(time), TimeZone.getDefault().toZoneId()));
//Ensure we are saving into the correct time entry
if(this.currentTime != time){
if(!wroteHeaders){
this.writer.writeNext(headers);
this.wroteHeaders = true;
}else{
//Write the line
if(this.limiter.limited())
return;
this.writer.writeNext(rowData);
for(int i=0; i< this.rowData.length; i++)
this.rowData[i] = new String();
}
this.currentTime = time;
}
if(useRendered){
//Convert to Alphanumeric Value
this.rowData[this.columnMap.get(vo.getId())] = Functions.getRenderedText(vo, pvt);
}else if(unitConversion){
if (pvt.getValue() instanceof NumericValue)
this.rowData[this.columnMap.get(vo.getId())] = Double.toString(vo.getUnit().getConverterTo(vo.getRenderedUnit()).convert(pvt.getValue().getDoubleValue()));
else
this.rowData[this.columnMap.get(vo.getId())] = this.createDataValueString(pvt.getValue());
}else{
if(vo.getPointLocator().getDataTypeId() == DataTypes.IMAGE)
this.rowData[this.columnMap.get(vo.getId())] = imageServletBuilder.buildAndExpand(pvt.getTime(), vo.getId()).toUri().toString();
else
this.rowData[this.columnMap.get(vo.getId())] = this.createDataValueString(pvt.getValue());
}
}catch(Exception e){
LOG.error(e.getMessage(), e);
}
}
private String createDataValueString(DataValue value){
if(value == null){
return "";
}else{
switch(value.getDataType()){
case DataTypes.ALPHANUMERIC:
return value.getStringValue();
case DataTypes.BINARY:
return Boolean.toString(value.getBooleanValue());
case DataTypes.MULTISTATE:
return Integer.toString(value.getIntegerValue());
case DataTypes.NUMERIC:
return Double.toString(value.getDoubleValue());
default:
LOG.error("Unsupported data type for DataValue: " + value.getDataType());
return "unsupported-value-type";
}
}
}
/**
* Finish any open objects
* @throws IOException
*/
public void finish(){
if((this.wroteHeaders)&&(!this.limiter.limited())){
this.writer.writeNext(rowData);
}
}
}
| 5,216 | 0.711553 | 0.706963 | 168 | 30.119047 | 30.433928 | 195 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.494048 | false | false |
1
|
d56c3ede82787988f7267dd7a86975ad9157740c
| 37,632,503,462,268 |
7d6992632368990bb46cbd1d6bce17722c677d7d
|
/src/main/java/com/kap/hackerrank/languagespecific/strings/StringCompare.java
|
706de337d788336de841a1d56559363ce7406381
|
[] |
no_license
|
Kost1s/HackerRank
|
https://github.com/Kost1s/HackerRank
|
c985e1c57de03802fa92a6ced99ce5c4da8a5820
|
7f4e8d558fd4af30bb60605b9eb573e87d150673
|
refs/heads/master
| 2021-08-09T18:38:43.649000 | 2021-06-12T03:31:40 | 2021-06-12T03:31:40 | 89,055,923 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kap.hackerrank.languagespecific.strings;
import com.sun.deploy.util.ArrayUtil;
import java.util.Scanner;
/**
* @author Konstantinos Antoniou
*/
public class StringCompare {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String originalString = sc.nextLine();
String reverseString = new StringBuffer(originalString).reverse().toString();
if (originalString.equals(reverseString)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
|
UTF-8
|
Java
| 579 |
java
|
StringCompare.java
|
Java
|
[
{
"context": "ayUtil;\n\nimport java.util.Scanner;\n\n/**\n * @author Konstantinos Antoniou\n */\npublic class StringCompare {\n\n public stat",
"end": 156,
"score": 0.9998617172241211,
"start": 135,
"tag": "NAME",
"value": "Konstantinos Antoniou"
}
] | null |
[] |
package com.kap.hackerrank.languagespecific.strings;
import com.sun.deploy.util.ArrayUtil;
import java.util.Scanner;
/**
* @author <NAME>
*/
public class StringCompare {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String originalString = sc.nextLine();
String reverseString = new StringBuffer(originalString).reverse().toString();
if (originalString.equals(reverseString)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
| 564 | 0.645941 | 0.645941 | 23 | 24.173914 | 22.91127 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false |
1
|
641a31d925815112fd39b7558257ce410d05ebde
| 38,749,194,990,916 |
7c09917a939f596fb87f174747795e6c9a1c8c7b
|
/cloudmall-gatway/cloudmall-gateway-core/src/main/java/top/zy/gateway/config/dynamic/RefreshRouteServiceImpl.java
|
a94406b4e84c0e2906c9ecc12993836e7a001143
|
[] |
no_license
|
houzeyu/cloud-mall
|
https://github.com/houzeyu/cloud-mall
|
d8bfd5bdbf5d56e25e20fb5401efcb2a09a88a73
|
610c28704fa1893fe1a60f9ea45783fff3a74ad7
|
refs/heads/master
| 2022-11-18T07:18:20.084000 | 2019-11-15T06:13:13 | 2019-11-15T06:13:13 | 207,572,023 | 0 | 0 | null | false | 2022-11-16T10:33:45 | 2019-09-10T13:48:18 | 2019-11-15T06:14:01 | 2022-11-16T10:33:45 | 92 | 0 | 0 | 9 |
Java
| false | false |
package top.zy.gateway.config.dynamic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class RefreshRouteServiceImpl implements RefreshRouteService {
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private RouteLocator routeLocator;
@Override
public void refreshRoute() {
RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
publisher.publishEvent(routesRefreshedEvent);
}
}
|
UTF-8
|
Java
| 750 |
java
|
RefreshRouteServiceImpl.java
|
Java
|
[] | null |
[] |
package top.zy.gateway.config.dynamic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.RoutesRefreshedEvent;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class RefreshRouteServiceImpl implements RefreshRouteService {
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private RouteLocator routeLocator;
@Override
public void refreshRoute() {
RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(routeLocator);
publisher.publishEvent(routesRefreshedEvent);
}
}
| 750 | 0.812 | 0.812 | 23 | 31.608696 | 28.282333 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false |
1
|
a784be00e23454043c783ce0bf82cb6e49ca0555
| 30,760,555,838,161 |
3ca73ea4be531a60af5198d4df3fd0e448004e8f
|
/sensei-core/src/main/java/com/senseidb/conf/SenseiSchema.java
|
2e503c0775628f215a19d1d0a0b23ff50e3761a6
|
[
"Apache-2.0"
] |
permissive
|
bcui/sensei
|
https://github.com/bcui/sensei
|
52c21237e8e9aa1f10cc4b7d3dd5d4ce20996ab1
|
8d39ce930ab2f8a64376c5214a51d76f76a53877
|
refs/heads/master
| 2020-12-25T02:49:47.629000 | 2013-05-23T15:01:17 | 2013-05-23T15:01:17 | 1,601,541 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.senseidb.conf;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.Field.TermVector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.senseidb.indexing.DefaultSenseiInterpreter;
import com.senseidb.indexing.DefaultSenseiInterpreter.IndexSpec;
import com.senseidb.indexing.MetaType;
public class SenseiSchema {
public static final String SRC_DATA_FIELD_NAME = "__SRC_DATA__";
public static final String SRC_DATA_COMPRESSED_FIELD_NAME = "stored";
public static final String EVENT_TYPE_FIELD = "type";
public static final String EVENT_FIELD = "data";
public static final String EVENT_TYPE_ADD = "add";
public static final String EVENT_TYPE_UPDATE = "update";
public static final String EVENT_TYPE_DELETE = "delete";
public static final String EVENT_TYPE_SKIP = "skip";
private static Logger logger = Logger.getLogger(SenseiSchema.class);
private String _uidField;
private String _deleteField;
private String _skipField;
private String _srcDataStore;
private String _srcDataField;
private boolean _compressSrcData;
private List<FacetDefinition> facets = new ArrayList<FacetDefinition>();
public static class FieldDefinition {
public Format formatter;
public boolean isMeta;
public IndexSpec textIndexSpec;
public String fromField;
public boolean isMulti;
public boolean isActivity;
public String delim = ",";
public Store store;
public Class type = null;
public String name;
}
public static class FacetDefinition {
public String name;
public String type;
public String column;
public Boolean dynamic;
public Map<String,List<String>> params;
public Set<String> dependSet = new HashSet<String>();
public static FacetDefinition valueOf(JSONObject facet) {
try {
FacetDefinition ret = new FacetDefinition();
ret.name = facet.getString("name");
ret.type = facet.getString("type");
ret.column = facet.optString("column",ret.name);
JSONArray depends= facet.optJSONArray("depends");
if (depends != null) {
for (int i = 0; i < depends.length(); ++i) {
String dep = depends.getString(i).trim();
if (!dep.isEmpty()) {
ret.dependSet.add(dep);
}
}
}
JSONArray paramList = facet.optJSONArray("params");
ret.params = SenseiFacetHandlerBuilder.parseParams(paramList);
return ret;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
private SenseiSchema(){
}
public String getUidField(){
return _uidField;
}
public String getDeleteField(){
return _deleteField;
}
public String getSkipField(){
return _skipField;
}
public String getSrcDataField(){
return _srcDataField;
}
public String getSrcDataStore(){
return _srcDataStore;
}
public boolean isCompressSrcData(){
return _compressSrcData;
}
public void setCompressSrcData(boolean _compressSrcData) {
this._compressSrcData = _compressSrcData;
}
public Map<String,FieldDefinition> getFieldDefMap(){
return _fieldDefMap;
}
private Map<String,FieldDefinition> _fieldDefMap;
private static JSONObject schemaObj;
public static SenseiSchema build(JSONObject schemaObj) throws JSONException,ConfigurationException{
SenseiSchema schema = new SenseiSchema();
schema.setSchemaObj(schemaObj);
schema._fieldDefMap = new HashMap<String,FieldDefinition>();
JSONObject tableElem = schemaObj.optJSONObject("table");
if (tableElem==null){
throw new ConfigurationException("empty schema");
}
schema._uidField = tableElem.getString("uid");
schema._deleteField = tableElem.optString("delete-field","");
schema._skipField = tableElem.optString("skip-field","");
schema._srcDataStore = tableElem.optString("src-data-store","");
schema._srcDataField = tableElem.optString("src-data-field","src_data");
schema._compressSrcData = tableElem.optBoolean("compress-src-data",true);
JSONArray columns = tableElem.optJSONArray("columns");
int count = 0;
if (columns!=null){
count = columns.length();
}
for (int i = 0; i < count; ++i) {
JSONObject column = columns.getJSONObject(i);
try {
String n = column.getString("name");
String t = column.getString("type");
String frm = column.optString("from", "");
String storeString = column.optString("store", "");
FieldDefinition fdef = new FieldDefinition();
fdef.formatter = null;
fdef.fromField = frm.length() > 0 ? frm : n;
fdef.store = storeString.length() > 0 ? DefaultSenseiInterpreter.STORE_VAL_MAP.get(storeString.toUpperCase()) : Store.NO;
if (fdef.store == null) {
throw new ConfigurationException("Invalid indexing parameter specification");
}
fdef.isMeta = true;
fdef.isMulti = column.optBoolean("multi");
fdef.isActivity = column.optBoolean("activity");
fdef.name = n;
String delimString = column.optString("delimiter");
if (delimString!=null && delimString.trim().length()>0){
fdef.delim = delimString;
}
schema._fieldDefMap.put(n, fdef);
if (t.equals("int")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(int.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("short")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(short.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("long")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(long.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = long.class;
} else if (t.equals("float")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(float.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("double")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(double.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("char")) {
fdef.formatter = null;
} else if (t.equals("string")) {
fdef.formatter = null;
} else if (t.equals("boolean")) {
fdef.formatter = null;
} else if (t.equals("date")) {
String f = "";
try {
f = column.optString("format");
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
if (f.isEmpty())
throw new ConfigurationException("Date format cannot be empty.");
fdef.formatter = new SimpleDateFormat(f);
fdef.type = Date.class;
}
else if (t.equals("text")){
fdef.isMeta = false;
String idxString = column.optString("index", "");
String tvString = column.optString("termvector", "");
Index idx = idxString.length() == 0? Index.ANALYZED : DefaultSenseiInterpreter.INDEX_VAL_MAP.get(idxString.toUpperCase());
TermVector tv = tvString.length() == 0? TermVector.NO : DefaultSenseiInterpreter.TV_VAL_MAP.get(tvString.toUpperCase());
if (idx==null || tv==null || fdef.store==null){
throw new ConfigurationException("Invalid indexing parameter specification");
}
IndexSpec indexingSpec = new IndexSpec();
indexingSpec.store = fdef.store;
indexingSpec.index = idx;
indexingSpec.tv = tv;
fdef.textIndexSpec = indexingSpec;
}
} catch (Exception e) {
throw new ConfigurationException("Error parsing schema: "
+ column, e);
}
}
JSONArray facetsList = schemaObj.optJSONArray("facets");
if (facetsList != null) {
for (int i = 0; i < facetsList.length(); i++) {
JSONObject facet = facetsList.optJSONObject(i);
if (facet != null) {
schema.facets.add(FacetDefinition.valueOf(facet));
}
}
}
return schema;
}
@Deprecated
public static SenseiSchema build(Document schemaDoc) throws ConfigurationException{
SenseiSchema schema = new SenseiSchema();
schema._fieldDefMap = new HashMap<String,FieldDefinition>();
NodeList tables = schemaDoc.getElementsByTagName("table");
if (tables==null || tables.getLength()==0){
throw new ConfigurationException("empty schema");
}
if (tables.getLength()>1){
throw new ConfigurationException("multiple schemas not supported");
}
Element tableElem = (Element) tables.item(0);
schema._uidField = tableElem.getAttribute("uid");
schema._deleteField = tableElem.getAttribute("delete-field");
if (schema._deleteField==null) schema._deleteField="";
schema._skipField = tableElem.getAttribute("skip-field");
if (schema._skipField==null) schema._skipField="";
schema._srcDataStore = tableElem.getAttribute("src-data-store");
if (schema._srcDataStore==null) schema._srcDataStore="";
schema._srcDataField = tableElem.getAttribute("src-data-field");
if (schema._srcDataField==null || schema._srcDataField.length() == 0) schema._srcDataField="src_data";
schema._compressSrcData = true;
String compress = tableElem.getAttribute("compress-src-data");
if (compress != null && "false".equals(compress))
schema._compressSrcData = false;
NodeList columns = tableElem.getElementsByTagName("column");
for (int i = 0; i < columns.getLength(); ++i) {
try {
Element column = (Element) columns.item(i);
String n = column.getAttribute("name");
String t = column.getAttribute("type");
String frm = column.getAttribute("from");
FieldDefinition fdef = new FieldDefinition();
fdef.formatter = null;
fdef.fromField = frm.length() > 0 ? frm : n;
fdef.isMeta = true;
fdef.isMulti = false;
String isMultiString = column.getAttribute("multi");
if (isMultiString!=null && isMultiString.trim().length()>0){
fdef.isMulti = Boolean.parseBoolean(isMultiString);
}
String isActivityString = column.getAttribute("activity");
if (isActivityString!=null && isActivityString.trim().length()>0){
fdef.isActivity = Boolean.parseBoolean(isActivityString);
}
String delimString = column.getAttribute("delimiter");
if (delimString!=null && delimString.trim().length()>0){
fdef.delim = delimString;
}
schema._fieldDefMap.put(n, fdef);
if (t.equals("int")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(int.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("short")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(short.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("long")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(long.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = long.class;
} else if (t.equals("float")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(float.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("double")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(double.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("char")) {
fdef.formatter = null;
} else if (t.equals("string")) {
fdef.formatter = null;
} else if (t.equals("boolean")) {
fdef.formatter = null;
} else if (t.equals("date")) {
String f = "";
try {
f = column.getAttribute("format");
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
if (f.isEmpty())
throw new ConfigurationException("Date format cannot be empty.");
fdef.formatter = new SimpleDateFormat(f);
fdef.type = Date.class;
}
else if (t.equals("text")){
fdef.isMeta = false;
String idxString = column.getAttribute("index");
String storeString = column.getAttribute("store");
String tvString = column.getAttribute("termvector");
Index idx = idxString == null ? Index.ANALYZED : DefaultSenseiInterpreter.INDEX_VAL_MAP.get(idxString.toUpperCase());
Store store = storeString == null ? Store.NO : DefaultSenseiInterpreter.STORE_VAL_MAP.get(storeString.toUpperCase());
TermVector tv = tvString == null ? TermVector.NO : DefaultSenseiInterpreter.TV_VAL_MAP.get(tvString.toUpperCase());
if (idx==null || store==null || tv==null){
throw new ConfigurationException("Invalid indexing parameter specification");
}
IndexSpec indexingSpec = new IndexSpec();
indexingSpec.store = store;
indexingSpec.index = idx;
indexingSpec.tv = tv;
fdef.textIndexSpec = indexingSpec;
}
} catch (Exception e) {
throw new ConfigurationException("Error parsing schema: "
+ columns.item(i), e);
}
}
return schema;
}
public List<FacetDefinition> getFacets() {
return facets;
}
public JSONObject getSchemaObj() {
return schemaObj;
}
public void setSchemaObj(JSONObject schemaObj) {
SenseiSchema.schemaObj = schemaObj;
}
}
|
UTF-8
|
Java
| 16,350 |
java
|
SenseiSchema.java
|
Java
|
[] | null |
[] |
package com.senseidb.conf;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.Field.TermVector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.senseidb.indexing.DefaultSenseiInterpreter;
import com.senseidb.indexing.DefaultSenseiInterpreter.IndexSpec;
import com.senseidb.indexing.MetaType;
public class SenseiSchema {
public static final String SRC_DATA_FIELD_NAME = "__SRC_DATA__";
public static final String SRC_DATA_COMPRESSED_FIELD_NAME = "stored";
public static final String EVENT_TYPE_FIELD = "type";
public static final String EVENT_FIELD = "data";
public static final String EVENT_TYPE_ADD = "add";
public static final String EVENT_TYPE_UPDATE = "update";
public static final String EVENT_TYPE_DELETE = "delete";
public static final String EVENT_TYPE_SKIP = "skip";
private static Logger logger = Logger.getLogger(SenseiSchema.class);
private String _uidField;
private String _deleteField;
private String _skipField;
private String _srcDataStore;
private String _srcDataField;
private boolean _compressSrcData;
private List<FacetDefinition> facets = new ArrayList<FacetDefinition>();
public static class FieldDefinition {
public Format formatter;
public boolean isMeta;
public IndexSpec textIndexSpec;
public String fromField;
public boolean isMulti;
public boolean isActivity;
public String delim = ",";
public Store store;
public Class type = null;
public String name;
}
public static class FacetDefinition {
public String name;
public String type;
public String column;
public Boolean dynamic;
public Map<String,List<String>> params;
public Set<String> dependSet = new HashSet<String>();
public static FacetDefinition valueOf(JSONObject facet) {
try {
FacetDefinition ret = new FacetDefinition();
ret.name = facet.getString("name");
ret.type = facet.getString("type");
ret.column = facet.optString("column",ret.name);
JSONArray depends= facet.optJSONArray("depends");
if (depends != null) {
for (int i = 0; i < depends.length(); ++i) {
String dep = depends.getString(i).trim();
if (!dep.isEmpty()) {
ret.dependSet.add(dep);
}
}
}
JSONArray paramList = facet.optJSONArray("params");
ret.params = SenseiFacetHandlerBuilder.parseParams(paramList);
return ret;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
private SenseiSchema(){
}
public String getUidField(){
return _uidField;
}
public String getDeleteField(){
return _deleteField;
}
public String getSkipField(){
return _skipField;
}
public String getSrcDataField(){
return _srcDataField;
}
public String getSrcDataStore(){
return _srcDataStore;
}
public boolean isCompressSrcData(){
return _compressSrcData;
}
public void setCompressSrcData(boolean _compressSrcData) {
this._compressSrcData = _compressSrcData;
}
public Map<String,FieldDefinition> getFieldDefMap(){
return _fieldDefMap;
}
private Map<String,FieldDefinition> _fieldDefMap;
private static JSONObject schemaObj;
public static SenseiSchema build(JSONObject schemaObj) throws JSONException,ConfigurationException{
SenseiSchema schema = new SenseiSchema();
schema.setSchemaObj(schemaObj);
schema._fieldDefMap = new HashMap<String,FieldDefinition>();
JSONObject tableElem = schemaObj.optJSONObject("table");
if (tableElem==null){
throw new ConfigurationException("empty schema");
}
schema._uidField = tableElem.getString("uid");
schema._deleteField = tableElem.optString("delete-field","");
schema._skipField = tableElem.optString("skip-field","");
schema._srcDataStore = tableElem.optString("src-data-store","");
schema._srcDataField = tableElem.optString("src-data-field","src_data");
schema._compressSrcData = tableElem.optBoolean("compress-src-data",true);
JSONArray columns = tableElem.optJSONArray("columns");
int count = 0;
if (columns!=null){
count = columns.length();
}
for (int i = 0; i < count; ++i) {
JSONObject column = columns.getJSONObject(i);
try {
String n = column.getString("name");
String t = column.getString("type");
String frm = column.optString("from", "");
String storeString = column.optString("store", "");
FieldDefinition fdef = new FieldDefinition();
fdef.formatter = null;
fdef.fromField = frm.length() > 0 ? frm : n;
fdef.store = storeString.length() > 0 ? DefaultSenseiInterpreter.STORE_VAL_MAP.get(storeString.toUpperCase()) : Store.NO;
if (fdef.store == null) {
throw new ConfigurationException("Invalid indexing parameter specification");
}
fdef.isMeta = true;
fdef.isMulti = column.optBoolean("multi");
fdef.isActivity = column.optBoolean("activity");
fdef.name = n;
String delimString = column.optString("delimiter");
if (delimString!=null && delimString.trim().length()>0){
fdef.delim = delimString;
}
schema._fieldDefMap.put(n, fdef);
if (t.equals("int")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(int.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("short")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(short.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("long")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(long.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = long.class;
} else if (t.equals("float")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(float.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("double")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(double.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("char")) {
fdef.formatter = null;
} else if (t.equals("string")) {
fdef.formatter = null;
} else if (t.equals("boolean")) {
fdef.formatter = null;
} else if (t.equals("date")) {
String f = "";
try {
f = column.optString("format");
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
if (f.isEmpty())
throw new ConfigurationException("Date format cannot be empty.");
fdef.formatter = new SimpleDateFormat(f);
fdef.type = Date.class;
}
else if (t.equals("text")){
fdef.isMeta = false;
String idxString = column.optString("index", "");
String tvString = column.optString("termvector", "");
Index idx = idxString.length() == 0? Index.ANALYZED : DefaultSenseiInterpreter.INDEX_VAL_MAP.get(idxString.toUpperCase());
TermVector tv = tvString.length() == 0? TermVector.NO : DefaultSenseiInterpreter.TV_VAL_MAP.get(tvString.toUpperCase());
if (idx==null || tv==null || fdef.store==null){
throw new ConfigurationException("Invalid indexing parameter specification");
}
IndexSpec indexingSpec = new IndexSpec();
indexingSpec.store = fdef.store;
indexingSpec.index = idx;
indexingSpec.tv = tv;
fdef.textIndexSpec = indexingSpec;
}
} catch (Exception e) {
throw new ConfigurationException("Error parsing schema: "
+ column, e);
}
}
JSONArray facetsList = schemaObj.optJSONArray("facets");
if (facetsList != null) {
for (int i = 0; i < facetsList.length(); i++) {
JSONObject facet = facetsList.optJSONObject(i);
if (facet != null) {
schema.facets.add(FacetDefinition.valueOf(facet));
}
}
}
return schema;
}
@Deprecated
public static SenseiSchema build(Document schemaDoc) throws ConfigurationException{
SenseiSchema schema = new SenseiSchema();
schema._fieldDefMap = new HashMap<String,FieldDefinition>();
NodeList tables = schemaDoc.getElementsByTagName("table");
if (tables==null || tables.getLength()==0){
throw new ConfigurationException("empty schema");
}
if (tables.getLength()>1){
throw new ConfigurationException("multiple schemas not supported");
}
Element tableElem = (Element) tables.item(0);
schema._uidField = tableElem.getAttribute("uid");
schema._deleteField = tableElem.getAttribute("delete-field");
if (schema._deleteField==null) schema._deleteField="";
schema._skipField = tableElem.getAttribute("skip-field");
if (schema._skipField==null) schema._skipField="";
schema._srcDataStore = tableElem.getAttribute("src-data-store");
if (schema._srcDataStore==null) schema._srcDataStore="";
schema._srcDataField = tableElem.getAttribute("src-data-field");
if (schema._srcDataField==null || schema._srcDataField.length() == 0) schema._srcDataField="src_data";
schema._compressSrcData = true;
String compress = tableElem.getAttribute("compress-src-data");
if (compress != null && "false".equals(compress))
schema._compressSrcData = false;
NodeList columns = tableElem.getElementsByTagName("column");
for (int i = 0; i < columns.getLength(); ++i) {
try {
Element column = (Element) columns.item(i);
String n = column.getAttribute("name");
String t = column.getAttribute("type");
String frm = column.getAttribute("from");
FieldDefinition fdef = new FieldDefinition();
fdef.formatter = null;
fdef.fromField = frm.length() > 0 ? frm : n;
fdef.isMeta = true;
fdef.isMulti = false;
String isMultiString = column.getAttribute("multi");
if (isMultiString!=null && isMultiString.trim().length()>0){
fdef.isMulti = Boolean.parseBoolean(isMultiString);
}
String isActivityString = column.getAttribute("activity");
if (isActivityString!=null && isActivityString.trim().length()>0){
fdef.isActivity = Boolean.parseBoolean(isActivityString);
}
String delimString = column.getAttribute("delimiter");
if (delimString!=null && delimString.trim().length()>0){
fdef.delim = delimString;
}
schema._fieldDefMap.put(n, fdef);
if (t.equals("int")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(int.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("short")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(short.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = int.class;
} else if (t.equals("long")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(long.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = long.class;
} else if (t.equals("float")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(float.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("double")) {
MetaType metaType = DefaultSenseiInterpreter.CLASS_METATYPE_MAP.get(double.class);
String formatString = DefaultSenseiInterpreter.DEFAULT_FORMAT_STRING_MAP.get(metaType);
fdef.formatter = new DecimalFormat(formatString, new DecimalFormatSymbols(Locale.US));
fdef.type = double.class;
} else if (t.equals("char")) {
fdef.formatter = null;
} else if (t.equals("string")) {
fdef.formatter = null;
} else if (t.equals("boolean")) {
fdef.formatter = null;
} else if (t.equals("date")) {
String f = "";
try {
f = column.getAttribute("format");
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
if (f.isEmpty())
throw new ConfigurationException("Date format cannot be empty.");
fdef.formatter = new SimpleDateFormat(f);
fdef.type = Date.class;
}
else if (t.equals("text")){
fdef.isMeta = false;
String idxString = column.getAttribute("index");
String storeString = column.getAttribute("store");
String tvString = column.getAttribute("termvector");
Index idx = idxString == null ? Index.ANALYZED : DefaultSenseiInterpreter.INDEX_VAL_MAP.get(idxString.toUpperCase());
Store store = storeString == null ? Store.NO : DefaultSenseiInterpreter.STORE_VAL_MAP.get(storeString.toUpperCase());
TermVector tv = tvString == null ? TermVector.NO : DefaultSenseiInterpreter.TV_VAL_MAP.get(tvString.toUpperCase());
if (idx==null || store==null || tv==null){
throw new ConfigurationException("Invalid indexing parameter specification");
}
IndexSpec indexingSpec = new IndexSpec();
indexingSpec.store = store;
indexingSpec.index = idx;
indexingSpec.tv = tv;
fdef.textIndexSpec = indexingSpec;
}
} catch (Exception e) {
throw new ConfigurationException("Error parsing schema: "
+ columns.item(i), e);
}
}
return schema;
}
public List<FacetDefinition> getFacets() {
return facets;
}
public JSONObject getSchemaObj() {
return schemaObj;
}
public void setSchemaObj(JSONObject schemaObj) {
SenseiSchema.schemaObj = schemaObj;
}
}
| 16,350 | 0.643486 | 0.642141 | 413 | 38.588379 | 29.607277 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.949153 | false | false |
1
|
0c6443a0c810151103dcc4a0d6d54054390bfdba
| 34,213,709,538,046 |
96f8d42c474f8dd42ecc6811b6e555363f168d3e
|
/zuiyou/sources/com/facebook/stetho/inspector/network/NetworkEventReporter$InspectorRequestCommon.java
|
a89a15ff87421660ff21996603b718c0cdbf6e70
|
[] |
no_license
|
aheadlcx/analyzeApk
|
https://github.com/aheadlcx/analyzeApk
|
050b261595cecc85790558a02d79739a789ae3a3
|
25cecc394dde4ed7d4971baf0e9504dcb7fabaca
|
refs/heads/master
| 2020-03-10T10:24:49.773000 | 2018-04-13T09:44:45 | 2018-04-13T09:44:45 | 129,332,351 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.facebook.stetho.inspector.network;
import com.facebook.stetho.inspector.network.NetworkEventReporter.InspectorHeaders;
public interface NetworkEventReporter$InspectorRequestCommon extends InspectorHeaders {
String friendlyName();
String id();
}
|
UTF-8
|
Java
| 268 |
java
|
NetworkEventReporter$InspectorRequestCommon.java
|
Java
|
[] | null |
[] |
package com.facebook.stetho.inspector.network;
import com.facebook.stetho.inspector.network.NetworkEventReporter.InspectorHeaders;
public interface NetworkEventReporter$InspectorRequestCommon extends InspectorHeaders {
String friendlyName();
String id();
}
| 268 | 0.824627 | 0.824627 | 9 | 28.777779 | 33.422474 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
1
|
f0dd3eb27f015e651a320a4eb743cec7929717d1
| 2,551,210,643,126 |
7f261a1e2bafd1cdd98d58f00a2937303c0dc942
|
/src/ANXCamera/sources/com/android/camera/panorama/PositionDetector.java
|
620d125e0f2404375db46c500ccab77e1df01570
|
[] |
no_license
|
xyzuan/ANXCamera
|
https://github.com/xyzuan/ANXCamera
|
7614ddcb4bcacdf972d67c2ba17702a8e9795c95
|
b9805e5197258e7b980e76a97f7f16de3a4f951a
|
refs/heads/master
| 2022-04-23T16:58:09.592000 | 2019-05-31T17:18:34 | 2019-05-31T17:26:48 | 259,555,505 | 3 | 0 | null | true | 2020-04-28T06:49:57 | 2020-04-28T06:49:57 | 2020-04-25T15:26:00 | 2020-04-25T15:25:57 | 314,105 | 0 | 0 | 0 | null | false | false |
package com.android.camera.panorama;
import android.graphics.Rect;
import android.graphics.RectF;
import android.provider.MiuiSettings.ScreenEffect;
import android.view.ViewGroup;
import com.android.camera.Util;
import com.android.camera.log.Log;
import com.android.camera.panorama.MorphoPanoramaGP3.InitParam;
public class PositionDetector {
public static final int COMPLETED = 1;
public static final int ERROR_IDLE = -1;
public static final int ERROR_REVERSE = -2;
private static final int IDLE_THRES_RATIO = 2;
private static final long IDLE_TIME = 3000000000L;
public static final int OK = 0;
private static final float PREVIEW_LONG_SIDE_CROP_RATIO = 0.8f;
private static final int REVERSE_THRES_RATIO = 7;
private static final int SPEED_CHECK_CONTINUOUSLY_TIMES = 5;
private static final int SPEED_CHECK_IGNORE_TIMES = 15;
private static final int SPEED_CHECK_MODE = 1;
private static final int SPEED_CHECK_MODE_AVERAGE = 1;
private static final String TAG = "PositionDetector";
private static final double TOO_FAST_THRES_RATIO = 0.8d;
private static final double TOO_SLOW_THRES_RATIO = 0.05d;
public static final int WARNING_TOO_FAST = 2;
public static final int WARNING_TOO_SLOW = 3;
private long count;
private volatile double cur_x;
private volatile double cur_y;
private final int direction;
private final RectF frame_rect = new RectF();
private RectF idle_rect = null;
private long idle_start_time;
private double idle_thres;
private int mCameraOrientation;
private final DiffManager mDiffManager = new DiffManager();
private InitParam mInitParam;
private boolean mIsFrontCamera;
private ViewGroup mPreviewFrame;
private int mPreviewHeight;
private int mPreviewWidth;
private final int output_height;
private final int output_width;
private double peak;
private double prev_x;
private double prev_y;
private boolean reset_idle_timer;
private double reverse_thres;
private double reverse_thres2;
private int too_fast_count;
private double too_fast_thres;
private int too_slow_count;
private double too_slow_thres;
private static class DiffManager {
private static final int NUM = 5;
private int add_num;
private double ave;
private int index;
private final double[] pos = new double[5];
public DiffManager() {
clear();
}
private void calc() {
double d = 0.0d;
for (int i = 0; i < this.add_num; i++) {
d += this.pos[i];
}
this.ave = d / ((double) this.add_num);
}
public void add(double d) {
this.pos[this.index] = d;
this.index++;
if (this.index >= 5) {
this.index = 0;
}
if (this.add_num < 5) {
this.add_num++;
}
calc();
}
public void clear() {
for (int i = 0; i < 5; i++) {
this.pos[i] = 0.0d;
}
this.index = 0;
this.add_num = 0;
}
public double getDiff() {
return this.ave;
}
}
public PositionDetector(InitParam initParam, ViewGroup viewGroup, boolean z, int i, int i2, int i3, int i4, int i5, int i6) {
this.mInitParam = initParam;
this.mPreviewFrame = viewGroup;
this.mIsFrontCamera = z;
this.mCameraOrientation = i;
this.mPreviewWidth = i2;
this.mPreviewHeight = i3;
this.count = 0;
this.direction = i4;
this.output_width = i5;
this.output_height = i6;
this.reset_idle_timer = true;
this.too_fast_count = 0;
this.too_slow_count = 0;
this.prev_y = 0.0d;
this.prev_x = 0.0d;
this.cur_y = 0.0d;
this.cur_x = 0.0d;
switch (this.direction) {
case 0:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = (double) i5;
} else {
this.peak = 0.0d;
}
float f = (float) i5;
this.reverse_thres = (double) (0.07f * f);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f);
this.idle_thres = (double) (f * 0.02f);
double d = (double) i5;
this.too_slow_thres = 5.0E-4d * d;
this.too_fast_thres = d * 0.008d;
return;
case 1:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = 0.0d;
} else {
this.peak = (double) i5;
}
float f2 = (float) i5;
this.reverse_thres = (double) (0.07f * f2);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f2);
this.idle_thres = (double) (f2 * 0.02f);
double d2 = (double) i5;
this.too_slow_thres = 5.0E-4d * d2;
this.too_fast_thres = d2 * 0.008d;
return;
case 2:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = (double) i6;
} else {
this.peak = 0.0d;
}
float f3 = (float) i6;
this.reverse_thres = (double) (0.07f * f3);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f3);
this.idle_thres = (double) (f3 * 0.02f);
double d3 = (double) i6;
this.too_slow_thres = 5.0E-4d * d3;
this.too_fast_thres = d3 * 0.008d;
return;
case 3:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = 0.0d;
} else {
this.peak = (double) i6;
}
float f4 = (float) i6;
this.reverse_thres = (double) (0.07f * f4);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f4);
this.idle_thres = (double) (f4 * 0.02f);
double d4 = (double) i6;
this.too_slow_thres = 5.0E-4d * d4;
this.too_fast_thres = d4 * 0.008d;
return;
default:
return;
}
}
/* JADX WARNING: Removed duplicated region for block: B:15:0x0043 */
/* JADX WARNING: Removed duplicated region for block: B:18:0x0049 */
/* Code decompiled incorrectly, please refer to instructions dump. */
private int checkSpeed() {
double d;
double d2;
int i;
switch (this.direction) {
case 2:
case 3:
d2 = this.cur_y;
d = this.prev_y;
break;
default:
d2 = this.cur_x;
d = this.prev_x;
break;
}
this.mDiffManager.add(Math.abs(d2 - d));
if (15 < this.count) {
if (this.mDiffManager.getDiff() < this.too_slow_thres) {
i = 3;
} else if (this.mDiffManager.getDiff() > this.too_fast_thres) {
i = 2;
}
if (this.too_slow_count > 0) {
this.too_slow_count = 0;
}
if (this.too_fast_count > 0) {
this.too_fast_count = 0;
}
return i;
}
i = 0;
if (this.too_slow_count > 0) {
}
if (this.too_fast_count > 0) {
}
return i;
}
private boolean isComplete() {
int i;
int i2;
double d;
boolean z;
boolean z2;
switch (this.direction) {
case 2:
case 3:
d = this.cur_y;
i2 = this.output_height;
i = this.mPreviewHeight / 2;
break;
default:
d = this.cur_x;
i2 = this.output_width;
i = this.mPreviewWidth / 2;
break;
}
int i3 = this.direction;
boolean z3 = false;
if (i3 == 1 || i3 == 3) {
if (this.mInitParam.output_rotation == 90 || this.mInitParam.output_rotation == 0) {
if (d > ((double) (i2 - (i / 2)))) {
z = true;
}
return z;
}
if (d < ((double) (i / 2))) {
z2 = true;
}
return z2;
} else if (this.mInitParam.output_rotation == 90 || this.mInitParam.output_rotation == 0) {
if (d < ((double) (i / 2))) {
z3 = true;
}
return z3;
} else {
if (d > ((double) (i2 - (i / 2)))) {
z3 = true;
}
return z3;
}
}
private boolean isIdle() {
long nanoTime = System.nanoTime();
if (this.reset_idle_timer) {
this.reset_idle_timer = false;
this.idle_start_time = nanoTime;
}
if (this.idle_rect == null) {
double d = this.idle_thres / 2.0d;
this.idle_rect = new RectF((float) (this.cur_x - d), (float) (this.cur_y - d), (float) (this.cur_x + d), (float) (this.cur_y + d));
}
if (IDLE_TIME < nanoTime - this.idle_start_time) {
return true;
}
if (!this.idle_rect.contains((float) this.cur_x, (float) this.cur_y)) {
this.reset_idle_timer = true;
this.idle_rect = null;
}
return false;
}
private boolean isReverse() {
int i;
double d;
double d2;
boolean z;
String str = TAG;
StringBuilder sb = new StringBuilder();
sb.append("cur_x = ");
sb.append(this.cur_x);
sb.append(", cur_y = ");
sb.append(this.cur_y);
Log.v(str, sb.toString());
switch (this.direction) {
case 2:
case 3:
d2 = this.cur_y;
d = this.prev_y;
i = this.output_height;
break;
default:
d2 = this.cur_x;
d = this.prev_x;
i = this.output_width;
break;
}
int i2 = this.direction;
boolean z2 = false;
boolean z3 = i2 == 1 || i2 == 3 ? !((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) : !((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 0 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 270);
if (z3) {
if (d - d2 > this.reverse_thres2) {
return true;
}
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
switch (this.direction) {
case 0:
case 2:
this.peak = Math.min(this.peak, d2);
break;
case 1:
case 3:
this.peak = Math.max(this.peak, d2);
z = true;
break;
}
z = false;
} else {
switch (this.direction) {
case 0:
case 2:
this.peak = Math.max(this.peak, d2);
z = true;
break;
case 1:
case 3:
this.peak = Math.min(this.peak, d2);
break;
}
z = false;
}
if (!z ? !(d2 <= ((double) i) && d2 - this.peak <= this.reverse_thres) : !(d2 <= ((double) i) && this.peak - d2 <= this.reverse_thres)) {
z2 = true;
}
} else if (d2 - d > this.reverse_thres2) {
return true;
} else {
if (d2 > this.peak) {
this.peak = d2;
}
if (d2 < 0.0d || this.peak - d2 > this.reverse_thres) {
return true;
}
}
return z2;
}
private boolean isYOutOfRange() {
boolean z = true;
if (this.cur_x < 0.0d || this.cur_y < 0.0d) {
return true;
}
int min = Math.min(this.output_width, this.output_height);
if (this.mInitParam.output_rotation % 180 == 90) {
if (this.cur_y <= ((double) min)) {
z = false;
}
return z;
}
if (this.cur_x <= ((double) min)) {
z = false;
}
return z;
}
private void updateFrame() {
float f;
float f2;
float f3;
float f4;
Rect rect = new Rect();
this.mPreviewFrame.getGlobalVisibleRect(rect);
if (rect.width() > 0) {
if (this.mInitParam.output_rotation == 90) {
float width = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_width);
f2 = (float) ((this.cur_y / ((double) this.output_height)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) this.cur_x) * width;
} else if (this.mInitParam.output_rotation == 180) {
float width2 = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_height);
f2 = (float) ((this.cur_x / ((double) this.output_width)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width2;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) this.cur_y) * width2;
} else if (this.mInitParam.output_rotation == 270) {
float width3 = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_width);
f2 = (float) ((this.cur_y / ((double) this.output_height)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width3;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) (((double) this.output_width) - this.cur_x)) * width3;
} else {
float width4 = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_height);
f2 = (float) ((this.cur_x / ((double) this.output_width)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width4;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) (((double) this.output_height) - this.cur_y)) * width4;
}
this.frame_rect.set(f3 - f, f2 - f4, f3 + f, f2 + f4);
}
}
public int detect(double d, double d2) {
this.count++;
if (!Util.isEqualsZero(this.cur_x) || !Util.isEqualsZero(this.prev_x)) {
this.prev_x = this.cur_x;
this.cur_x = d;
} else {
this.prev_x = d;
this.cur_x = d;
}
if (!Util.isEqualsZero(this.cur_y) || !Util.isEqualsZero(this.prev_y)) {
this.prev_y = this.cur_y;
this.cur_y = d2;
} else {
this.prev_y = d2;
this.cur_y = d2;
}
if (isYOutOfRange()) {
Log.d(TAG, "isYOutOfRange");
return 1;
} else if (isReverse()) {
Log.d(TAG, "isReverse");
return -2;
} else if (isComplete()) {
Log.d(TAG, "isComplete");
return 1;
} else {
int checkSpeed = checkSpeed();
updateFrame();
return checkSpeed;
}
}
public RectF getFrameRect() {
return this.frame_rect;
}
}
|
UTF-8
|
Java
| 17,340 |
java
|
PositionDetector.java
|
Java
|
[] | null |
[] |
package com.android.camera.panorama;
import android.graphics.Rect;
import android.graphics.RectF;
import android.provider.MiuiSettings.ScreenEffect;
import android.view.ViewGroup;
import com.android.camera.Util;
import com.android.camera.log.Log;
import com.android.camera.panorama.MorphoPanoramaGP3.InitParam;
public class PositionDetector {
public static final int COMPLETED = 1;
public static final int ERROR_IDLE = -1;
public static final int ERROR_REVERSE = -2;
private static final int IDLE_THRES_RATIO = 2;
private static final long IDLE_TIME = 3000000000L;
public static final int OK = 0;
private static final float PREVIEW_LONG_SIDE_CROP_RATIO = 0.8f;
private static final int REVERSE_THRES_RATIO = 7;
private static final int SPEED_CHECK_CONTINUOUSLY_TIMES = 5;
private static final int SPEED_CHECK_IGNORE_TIMES = 15;
private static final int SPEED_CHECK_MODE = 1;
private static final int SPEED_CHECK_MODE_AVERAGE = 1;
private static final String TAG = "PositionDetector";
private static final double TOO_FAST_THRES_RATIO = 0.8d;
private static final double TOO_SLOW_THRES_RATIO = 0.05d;
public static final int WARNING_TOO_FAST = 2;
public static final int WARNING_TOO_SLOW = 3;
private long count;
private volatile double cur_x;
private volatile double cur_y;
private final int direction;
private final RectF frame_rect = new RectF();
private RectF idle_rect = null;
private long idle_start_time;
private double idle_thres;
private int mCameraOrientation;
private final DiffManager mDiffManager = new DiffManager();
private InitParam mInitParam;
private boolean mIsFrontCamera;
private ViewGroup mPreviewFrame;
private int mPreviewHeight;
private int mPreviewWidth;
private final int output_height;
private final int output_width;
private double peak;
private double prev_x;
private double prev_y;
private boolean reset_idle_timer;
private double reverse_thres;
private double reverse_thres2;
private int too_fast_count;
private double too_fast_thres;
private int too_slow_count;
private double too_slow_thres;
private static class DiffManager {
private static final int NUM = 5;
private int add_num;
private double ave;
private int index;
private final double[] pos = new double[5];
public DiffManager() {
clear();
}
private void calc() {
double d = 0.0d;
for (int i = 0; i < this.add_num; i++) {
d += this.pos[i];
}
this.ave = d / ((double) this.add_num);
}
public void add(double d) {
this.pos[this.index] = d;
this.index++;
if (this.index >= 5) {
this.index = 0;
}
if (this.add_num < 5) {
this.add_num++;
}
calc();
}
public void clear() {
for (int i = 0; i < 5; i++) {
this.pos[i] = 0.0d;
}
this.index = 0;
this.add_num = 0;
}
public double getDiff() {
return this.ave;
}
}
public PositionDetector(InitParam initParam, ViewGroup viewGroup, boolean z, int i, int i2, int i3, int i4, int i5, int i6) {
this.mInitParam = initParam;
this.mPreviewFrame = viewGroup;
this.mIsFrontCamera = z;
this.mCameraOrientation = i;
this.mPreviewWidth = i2;
this.mPreviewHeight = i3;
this.count = 0;
this.direction = i4;
this.output_width = i5;
this.output_height = i6;
this.reset_idle_timer = true;
this.too_fast_count = 0;
this.too_slow_count = 0;
this.prev_y = 0.0d;
this.prev_x = 0.0d;
this.cur_y = 0.0d;
this.cur_x = 0.0d;
switch (this.direction) {
case 0:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = (double) i5;
} else {
this.peak = 0.0d;
}
float f = (float) i5;
this.reverse_thres = (double) (0.07f * f);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f);
this.idle_thres = (double) (f * 0.02f);
double d = (double) i5;
this.too_slow_thres = 5.0E-4d * d;
this.too_fast_thres = d * 0.008d;
return;
case 1:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = 0.0d;
} else {
this.peak = (double) i5;
}
float f2 = (float) i5;
this.reverse_thres = (double) (0.07f * f2);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f2);
this.idle_thres = (double) (f2 * 0.02f);
double d2 = (double) i5;
this.too_slow_thres = 5.0E-4d * d2;
this.too_fast_thres = d2 * 0.008d;
return;
case 2:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = (double) i6;
} else {
this.peak = 0.0d;
}
float f3 = (float) i6;
this.reverse_thres = (double) (0.07f * f3);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f3);
this.idle_thres = (double) (f3 * 0.02f);
double d3 = (double) i6;
this.too_slow_thres = 5.0E-4d * d3;
this.too_fast_thres = d3 * 0.008d;
return;
case 3:
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
this.peak = 0.0d;
} else {
this.peak = (double) i6;
}
float f4 = (float) i6;
this.reverse_thres = (double) (0.07f * f4);
this.reverse_thres2 = (double) (PREVIEW_LONG_SIDE_CROP_RATIO * f4);
this.idle_thres = (double) (f4 * 0.02f);
double d4 = (double) i6;
this.too_slow_thres = 5.0E-4d * d4;
this.too_fast_thres = d4 * 0.008d;
return;
default:
return;
}
}
/* JADX WARNING: Removed duplicated region for block: B:15:0x0043 */
/* JADX WARNING: Removed duplicated region for block: B:18:0x0049 */
/* Code decompiled incorrectly, please refer to instructions dump. */
private int checkSpeed() {
double d;
double d2;
int i;
switch (this.direction) {
case 2:
case 3:
d2 = this.cur_y;
d = this.prev_y;
break;
default:
d2 = this.cur_x;
d = this.prev_x;
break;
}
this.mDiffManager.add(Math.abs(d2 - d));
if (15 < this.count) {
if (this.mDiffManager.getDiff() < this.too_slow_thres) {
i = 3;
} else if (this.mDiffManager.getDiff() > this.too_fast_thres) {
i = 2;
}
if (this.too_slow_count > 0) {
this.too_slow_count = 0;
}
if (this.too_fast_count > 0) {
this.too_fast_count = 0;
}
return i;
}
i = 0;
if (this.too_slow_count > 0) {
}
if (this.too_fast_count > 0) {
}
return i;
}
private boolean isComplete() {
int i;
int i2;
double d;
boolean z;
boolean z2;
switch (this.direction) {
case 2:
case 3:
d = this.cur_y;
i2 = this.output_height;
i = this.mPreviewHeight / 2;
break;
default:
d = this.cur_x;
i2 = this.output_width;
i = this.mPreviewWidth / 2;
break;
}
int i3 = this.direction;
boolean z3 = false;
if (i3 == 1 || i3 == 3) {
if (this.mInitParam.output_rotation == 90 || this.mInitParam.output_rotation == 0) {
if (d > ((double) (i2 - (i / 2)))) {
z = true;
}
return z;
}
if (d < ((double) (i / 2))) {
z2 = true;
}
return z2;
} else if (this.mInitParam.output_rotation == 90 || this.mInitParam.output_rotation == 0) {
if (d < ((double) (i / 2))) {
z3 = true;
}
return z3;
} else {
if (d > ((double) (i2 - (i / 2)))) {
z3 = true;
}
return z3;
}
}
private boolean isIdle() {
long nanoTime = System.nanoTime();
if (this.reset_idle_timer) {
this.reset_idle_timer = false;
this.idle_start_time = nanoTime;
}
if (this.idle_rect == null) {
double d = this.idle_thres / 2.0d;
this.idle_rect = new RectF((float) (this.cur_x - d), (float) (this.cur_y - d), (float) (this.cur_x + d), (float) (this.cur_y + d));
}
if (IDLE_TIME < nanoTime - this.idle_start_time) {
return true;
}
if (!this.idle_rect.contains((float) this.cur_x, (float) this.cur_y)) {
this.reset_idle_timer = true;
this.idle_rect = null;
}
return false;
}
private boolean isReverse() {
int i;
double d;
double d2;
boolean z;
String str = TAG;
StringBuilder sb = new StringBuilder();
sb.append("cur_x = ");
sb.append(this.cur_x);
sb.append(", cur_y = ");
sb.append(this.cur_y);
Log.v(str, sb.toString());
switch (this.direction) {
case 2:
case 3:
d2 = this.cur_y;
d = this.prev_y;
i = this.output_height;
break;
default:
d2 = this.cur_x;
d = this.prev_x;
i = this.output_width;
break;
}
int i2 = this.direction;
boolean z2 = false;
boolean z3 = i2 == 1 || i2 == 3 ? !((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) : !((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 0 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 270);
if (z3) {
if (d - d2 > this.reverse_thres2) {
return true;
}
if ((this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 90 || (this.mInitParam.output_rotation + this.mCameraOrientation) % ScreenEffect.SCREEN_PAPER_MODE_TWILIGHT_START_DEAULT == 180) {
switch (this.direction) {
case 0:
case 2:
this.peak = Math.min(this.peak, d2);
break;
case 1:
case 3:
this.peak = Math.max(this.peak, d2);
z = true;
break;
}
z = false;
} else {
switch (this.direction) {
case 0:
case 2:
this.peak = Math.max(this.peak, d2);
z = true;
break;
case 1:
case 3:
this.peak = Math.min(this.peak, d2);
break;
}
z = false;
}
if (!z ? !(d2 <= ((double) i) && d2 - this.peak <= this.reverse_thres) : !(d2 <= ((double) i) && this.peak - d2 <= this.reverse_thres)) {
z2 = true;
}
} else if (d2 - d > this.reverse_thres2) {
return true;
} else {
if (d2 > this.peak) {
this.peak = d2;
}
if (d2 < 0.0d || this.peak - d2 > this.reverse_thres) {
return true;
}
}
return z2;
}
private boolean isYOutOfRange() {
boolean z = true;
if (this.cur_x < 0.0d || this.cur_y < 0.0d) {
return true;
}
int min = Math.min(this.output_width, this.output_height);
if (this.mInitParam.output_rotation % 180 == 90) {
if (this.cur_y <= ((double) min)) {
z = false;
}
return z;
}
if (this.cur_x <= ((double) min)) {
z = false;
}
return z;
}
private void updateFrame() {
float f;
float f2;
float f3;
float f4;
Rect rect = new Rect();
this.mPreviewFrame.getGlobalVisibleRect(rect);
if (rect.width() > 0) {
if (this.mInitParam.output_rotation == 90) {
float width = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_width);
f2 = (float) ((this.cur_y / ((double) this.output_height)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) this.cur_x) * width;
} else if (this.mInitParam.output_rotation == 180) {
float width2 = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_height);
f2 = (float) ((this.cur_x / ((double) this.output_width)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width2;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) this.cur_y) * width2;
} else if (this.mInitParam.output_rotation == 270) {
float width3 = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_width);
f2 = (float) ((this.cur_y / ((double) this.output_height)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width3;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) (((double) this.output_width) - this.cur_x)) * width3;
} else {
float width4 = ((float) this.mPreviewFrame.getWidth()) / ((float) this.output_height);
f2 = (float) ((this.cur_x / ((double) this.output_width)) * ((double) rect.height()));
f = (((float) this.mInitParam.input_height) / 2.0f) * width4;
f4 = ((float) rect.height()) / 2.0f;
f3 = ((float) (((double) this.output_height) - this.cur_y)) * width4;
}
this.frame_rect.set(f3 - f, f2 - f4, f3 + f, f2 + f4);
}
}
public int detect(double d, double d2) {
this.count++;
if (!Util.isEqualsZero(this.cur_x) || !Util.isEqualsZero(this.prev_x)) {
this.prev_x = this.cur_x;
this.cur_x = d;
} else {
this.prev_x = d;
this.cur_x = d;
}
if (!Util.isEqualsZero(this.cur_y) || !Util.isEqualsZero(this.prev_y)) {
this.prev_y = this.cur_y;
this.cur_y = d2;
} else {
this.prev_y = d2;
this.cur_y = d2;
}
if (isYOutOfRange()) {
Log.d(TAG, "isYOutOfRange");
return 1;
} else if (isReverse()) {
Log.d(TAG, "isReverse");
return -2;
} else if (isComplete()) {
Log.d(TAG, "isComplete");
return 1;
} else {
int checkSpeed = checkSpeed();
updateFrame();
return checkSpeed;
}
}
public RectF getFrameRect() {
return this.frame_rect;
}
}
| 17,340 | 0.498097 | 0.47624 | 452 | 37.362831 | 40.595089 | 541 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.732301 | false | false |
1
|
26933ce75e1a2536e6de29bb40752b5a16db0822
| 2,551,210,639,408 |
4d4472294e67e821403f67281ba0aafac9f5759e
|
/src/main/java/com/salesforceiq/augmenteddriver/util/AugmentedProvider.java
|
3567606af5c5d3991161e4c40be353907890796b
|
[
"Apache-2.0"
] |
permissive
|
relateiq/AugmentedDriver
|
https://github.com/relateiq/AugmentedDriver
|
c6bdce2884fed93d4313edc5b0203bd3cc304a90
|
81b616c6559e32c7017a51d3937218bd3e201ed7
|
refs/heads/master
| 2020-01-30T14:52:10.073000 | 2019-08-12T08:39:24 | 2019-08-12T08:39:24 | 46,003,935 | 47 | 17 |
Apache-2.0
| false | 2020-02-03T11:17:38 | 2015-11-11T19:14:53 | 2019-09-22T15:30:24 | 2020-02-03T11:17:38 | 33,208 | 40 | 16 | 2 |
Java
| false | false |
package com.salesforceiq.augmenteddriver.util;
import com.google.inject.Provider;
import org.openqa.selenium.remote.RemoteWebDriver;
/**
* Provider extension that also allows initializing it
*
* (since we cannot initialize it at Guice init time, since the driver needs to be created,
* and that is at setUp time.
*/
public interface AugmentedProvider<T extends RemoteWebDriver> extends Provider<T> {
/**
* Sets the driver that will be used for this test.
*
* <p>
* SHOULD NOT BE CALLED OUTSIDE THE SETUP FOR THE BASE TESTCASES.
* </p>
* @param driver the driver to set.
*/
void initialize(T driver);
/**
* @return Whether the provider has been initialized or not.
*/
boolean isInitialized();
}
|
UTF-8
|
Java
| 767 |
java
|
AugmentedProvider.java
|
Java
|
[] | null |
[] |
package com.salesforceiq.augmenteddriver.util;
import com.google.inject.Provider;
import org.openqa.selenium.remote.RemoteWebDriver;
/**
* Provider extension that also allows initializing it
*
* (since we cannot initialize it at Guice init time, since the driver needs to be created,
* and that is at setUp time.
*/
public interface AugmentedProvider<T extends RemoteWebDriver> extends Provider<T> {
/**
* Sets the driver that will be used for this test.
*
* <p>
* SHOULD NOT BE CALLED OUTSIDE THE SETUP FOR THE BASE TESTCASES.
* </p>
* @param driver the driver to set.
*/
void initialize(T driver);
/**
* @return Whether the provider has been initialized or not.
*/
boolean isInitialized();
}
| 767 | 0.683181 | 0.683181 | 27 | 27.407408 | 27.587248 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.259259 | false | false |
1
|
b3bef912653e179d004614976db7646567379b6a
| 36,129,264,924,306 |
b09f56919e3baac6aff3cc7a590505b21efd72eb
|
/src/main/java/com/zorm/persister/entity/UnionSubclassEntityPersister.java
|
10b3f8fa8b0563933538d88172812d181bca4077
|
[] |
no_license
|
SHENJIAYUN/zorm
|
https://github.com/SHENJIAYUN/zorm
|
51d2d2674dfb98bf77203e3de35f7f5191148180
|
fe849f55d5523bd24d5069e8f54678108a9de162
|
refs/heads/master
| 2021-01-18T21:50:28.686000 | 2016-05-19T14:52:39 | 2016-05-19T14:52:39 | 52,928,318 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zorm.persister.entity;
import java.io.Serializable;
import java.util.*;
import com.zorm.FilterAliasGenerator;
import com.zorm.LockMode;
import com.zorm.LockOptions;
import com.zorm.StaticFilterAliasGenerator;
import com.zorm.config.Settings;
import com.zorm.dialect.Dialect;
import com.zorm.engine.ExecuteUpdateResultCheckStyle;
import com.zorm.engine.Mapping;
import com.zorm.engine.ValueInclusion;
import com.zorm.exception.AssertionFailure;
import com.zorm.exception.MappingException;
import com.zorm.exception.ZormException;
import com.zorm.mapping.Column;
import com.zorm.mapping.PersistentClass;
import com.zorm.mapping.Subclass;
import com.zorm.mapping.Table;
import com.zorm.session.SessionFactoryImplementor;
import com.zorm.session.SessionImplementor;
import com.zorm.sql.SelectFragment;
import com.zorm.type.StandardBasicTypes;
import com.zorm.type.Type;
import com.zorm.type.VersionType;
import com.zorm.util.ArrayHelper;
import com.zorm.util.JoinedIterator;
import com.zorm.util.SingletonIterator;
public class UnionSubclassEntityPersister extends AbstractEntityPersister{
// the class hierarchy structure
private final String subquery;
private final String tableName;
//private final String rootTableName;
private final String[] subclassClosure;
private final String[] spaces;
private final String[] subclassSpaces;
private final Object discriminatorValue;
private final String discriminatorSQLValue;
private final Map subclassByDiscriminatorValue = new HashMap();
private final String[] constraintOrderedTableNames;
private final String[][] constraintOrderedKeyColumnNames;
public UnionSubclassEntityPersister(
final PersistentClass persistentClass,
final SessionFactoryImplementor factory,
final Mapping mapping) throws ZormException {
super( persistentClass, factory );
// TABLE
tableName = persistentClass.getTable().getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
);
//Custom SQL
String sql;
boolean callable = false;
ExecuteUpdateResultCheckStyle checkStyle = null;
sql = persistentClass.getCustomSQLInsert();
callable = sql != null && persistentClass.isCustomInsertCallable();
checkStyle = sql == null
? ExecuteUpdateResultCheckStyle.COUNT
: persistentClass.getCustomSQLInsertCheckStyle() == null
? ExecuteUpdateResultCheckStyle.determineDefault( sql, callable )
: persistentClass.getCustomSQLInsertCheckStyle();
customSQLInsert = new String[] { sql };
insertCallable = new boolean[] { callable };
insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };
sql = persistentClass.getCustomSQLUpdate();
callable = sql != null && persistentClass.isCustomUpdateCallable();
checkStyle = sql == null
? ExecuteUpdateResultCheckStyle.COUNT
: persistentClass.getCustomSQLUpdateCheckStyle() == null
? ExecuteUpdateResultCheckStyle.determineDefault( sql, callable )
: persistentClass.getCustomSQLUpdateCheckStyle();
customSQLUpdate = new String[] { sql };
updateCallable = new boolean[] { callable };
updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };
sql = persistentClass.getCustomSQLDelete();
callable = sql != null && persistentClass.isCustomDeleteCallable();
checkStyle = sql == null
? ExecuteUpdateResultCheckStyle.COUNT
: persistentClass.getCustomSQLDeleteCheckStyle() == null
? ExecuteUpdateResultCheckStyle.determineDefault( sql, callable )
: persistentClass.getCustomSQLDeleteCheckStyle();
customSQLDelete = new String[] { sql };
deleteCallable = new boolean[] { callable };
deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };
discriminatorValue = persistentClass.getSubclassId();
discriminatorSQLValue = String.valueOf( persistentClass.getSubclassId() );
// PROPERTIES
int subclassSpan = persistentClass.getSubclassSpan() + 1;
subclassClosure = new String[subclassSpan];
subclassClosure[0] = getEntityName();
// SUBCLASSES
subclassByDiscriminatorValue.put(
persistentClass.getSubclassId(),
persistentClass.getEntityName()
);
if ( persistentClass.isPolymorphic() ) {
Iterator iter = persistentClass.getSubclassIterator();
int k=1;
while ( iter.hasNext() ) {
Subclass sc = (Subclass) iter.next();
subclassClosure[k++] = sc.getEntityName();
subclassByDiscriminatorValue.put( sc.getSubclassId(), sc.getEntityName() );
}
}
int spacesSize = 1 + persistentClass.getSynchronizedTables().size();
spaces = new String[spacesSize];
spaces[0] = tableName;
Iterator iter = persistentClass.getSynchronizedTables().iterator();
for ( int i=1; i<spacesSize; i++ ) {
spaces[i] = (String) iter.next();
}
HashSet subclassTables = new HashSet();
iter = persistentClass.getSubclassTableClosureIterator();
while ( iter.hasNext() ) {
Table table = (Table) iter.next();
subclassTables.add( table.getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
) );
}
subclassSpaces = ArrayHelper.toStringArray(subclassTables);
//子类数据库表
subquery = generateSubquery(persistentClass, mapping);
if ( isMultiTable() ) {
int idColumnSpan = getIdentifierColumnSpan();
ArrayList tableNames = new ArrayList();
ArrayList keyColumns = new ArrayList();
if ( !isAbstract() ) {
tableNames.add( tableName );
keyColumns.add( getIdentifierColumnNames() );
}
iter = persistentClass.getSubclassTableClosureIterator();
while ( iter.hasNext() ) {
Table tab = ( Table ) iter.next();
if ( !tab.isAbstractUnionTable() ) {
String tableName = tab.getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
);
tableNames.add( tableName );
String[] key = new String[idColumnSpan];
Iterator citer = tab.getPrimaryKey().getColumnIterator();
for ( int k=0; k<idColumnSpan; k++ ) {
key[k] = ( ( Column ) citer.next() ).getQuotedName( factory.getDialect() );
}
keyColumns.add( key );
}
}
constraintOrderedTableNames = ArrayHelper.toStringArray( tableNames );
constraintOrderedKeyColumnNames = ArrayHelper.to2DStringArray( keyColumns );
}
else {
constraintOrderedTableNames = new String[] { tableName };
constraintOrderedKeyColumnNames = new String[][] { getIdentifierColumnNames() };
}
initSubclassPropertyAliasesMap(persistentClass);
postConstruct(mapping);
}
public Serializable[] getQuerySpaces() {
return subclassSpaces;
}
public String getTableName() {
return subquery;
}
public Type getDiscriminatorType() {
return StandardBasicTypes.INTEGER;
}
public Object getDiscriminatorValue() {
return discriminatorValue;
}
public String getDiscriminatorSQLValue() {
return discriminatorSQLValue;
}
public String[] getSubclassClosure() {
return subclassClosure;
}
public String getSubclassForDiscriminatorValue(Object value) {
return (String) subclassByDiscriminatorValue.get(value);
}
public Serializable[] getPropertySpaces() {
return spaces;
}
protected boolean isDiscriminatorFormula() {
return false;
}
protected String getDiscriminatorFormula() {
return null;
}
protected String getTableName(int j) {
return tableName;
}
protected String[] getKeyColumns(int j) {
return getIdentifierColumnNames();
}
protected boolean isTableCascadeDeleteEnabled(int j) {
return false;
}
protected boolean isPropertyOfTable(int property, int j) {
return true;
}
// Execute the SQL:
public String fromTableFragment(String name) {
return getTableName() + ' ' + name;
}
public String filterFragment(String name) {
return hasWhere() ?
" and " + getSQLWhereString(name) :
"";
}
public String getSubclassPropertyTableName(int i) {
return getTableName();
}
protected void addDiscriminatorToSelect(SelectFragment select, String name, String suffix) {
select.addColumn( name, getDiscriminatorColumnName(), getDiscriminatorAlias() );
}
protected int[] getPropertyTableNumbersInSelect() {
return new int[ getPropertySpan() ];
}
protected int getSubclassPropertyTableNumber(int i) {
return 0;
}
public int getSubclassPropertyTableNumber(String propertyName) {
return 0;
}
public boolean isMultiTable() {
return isAbstract() || hasSubclasses();
}
public int getTableSpan() {
return 1;
}
protected int[] getSubclassColumnTableNumberClosure() {
return new int[ getSubclassColumnClosure().length ];
}
protected int[] getSubclassFormulaTableNumberClosure() {
return new int[ getSubclassFormulaClosure().length ];
}
protected boolean[] getTableHasColumns() {
return new boolean[] { true };
}
protected int[] getPropertyTableNumbers() {
return new int[ getPropertySpan() ];
}
protected String generateSubquery(PersistentClass model, Mapping mapping) {
Dialect dialect = getFactory().getDialect();
Settings settings = getFactory().getSettings();
if ( !model.hasSubclasses() ) {
return model.getTable().getQualifiedName(
dialect,
settings.getDefaultCatalogName(),
settings.getDefaultSchemaName()
);
}
HashSet columns = new LinkedHashSet();
Iterator titer = model.getSubclassTableClosureIterator();
while ( titer.hasNext() ) {
Table table = (Table) titer.next();
if ( !table.isAbstractUnionTable() ) {
Iterator citer = table.getColumnIterator();
while ( citer.hasNext() ) columns.add( citer.next() );
}
}
StringBuilder buf = new StringBuilder()
.append("( ");
Iterator siter = new JoinedIterator(
new SingletonIterator(model),
model.getSubclassIterator()
);
while ( siter.hasNext() ) {
PersistentClass clazz = (PersistentClass) siter.next();
Table table = clazz.getTable();
if ( !table.isAbstractUnionTable() ) {
buf.append("select ");
Iterator citer = columns.iterator();
while ( citer.hasNext() ) {
Column col = (Column) citer.next();
if ( !table.containsColumn(col) ) {
int sqlType = col.getSqlTypeCode(mapping);
buf.append( dialect.getSelectClauseNullString(sqlType) )
.append(" as ");
}
buf.append( col.getName() );
buf.append(", ");
}
buf.append( clazz.getSubclassId() )
.append(" as clazz_");
buf.append(" from ")
.append( table.getQualifiedName(
dialect,
settings.getDefaultCatalogName(),
settings.getDefaultSchemaName()
) );
buf.append(" union ");
if ( dialect.supportsUnionAll() ) {
buf.append("all ");
}
}
}
if ( buf.length() > 2 ) {
//chop the last union (all)
buf.setLength( buf.length() - ( dialect.supportsUnionAll() ? 11 : 7 ) );
}
return buf.append(" )").toString();
}
protected String[] getSubclassTableKeyColumns(int j) {
if (j!=0) throw new AssertionFailure("only one table");
return getIdentifierColumnNames();
}
public String getSubclassTableName(int j) {
if (j!=0) throw new AssertionFailure("only one table");
return tableName;
}
public int getSubclassTableSpan() {
return 1;
}
protected boolean isClassOrSuperclassTable(int j) {
if (j!=0) throw new AssertionFailure("only one table");
return true;
}
public String getPropertyTableName(String propertyName) {
//TODO: check this....
return getTableName();
}
public String[] getConstraintOrderedTableNameClosure() {
return constraintOrderedTableNames;
}
public String[][] getContraintOrderedTableKeyColumnClosure() {
return constraintOrderedKeyColumnNames;
}
@Override
public FilterAliasGenerator getFilterAliasGenerator(String rootAlias) {
return new StaticFilterAliasGenerator(rootAlias);
}
}
|
UTF-8
|
Java
| 11,970 |
java
|
UnionSubclassEntityPersister.java
|
Java
|
[] | null |
[] |
package com.zorm.persister.entity;
import java.io.Serializable;
import java.util.*;
import com.zorm.FilterAliasGenerator;
import com.zorm.LockMode;
import com.zorm.LockOptions;
import com.zorm.StaticFilterAliasGenerator;
import com.zorm.config.Settings;
import com.zorm.dialect.Dialect;
import com.zorm.engine.ExecuteUpdateResultCheckStyle;
import com.zorm.engine.Mapping;
import com.zorm.engine.ValueInclusion;
import com.zorm.exception.AssertionFailure;
import com.zorm.exception.MappingException;
import com.zorm.exception.ZormException;
import com.zorm.mapping.Column;
import com.zorm.mapping.PersistentClass;
import com.zorm.mapping.Subclass;
import com.zorm.mapping.Table;
import com.zorm.session.SessionFactoryImplementor;
import com.zorm.session.SessionImplementor;
import com.zorm.sql.SelectFragment;
import com.zorm.type.StandardBasicTypes;
import com.zorm.type.Type;
import com.zorm.type.VersionType;
import com.zorm.util.ArrayHelper;
import com.zorm.util.JoinedIterator;
import com.zorm.util.SingletonIterator;
public class UnionSubclassEntityPersister extends AbstractEntityPersister{
// the class hierarchy structure
private final String subquery;
private final String tableName;
//private final String rootTableName;
private final String[] subclassClosure;
private final String[] spaces;
private final String[] subclassSpaces;
private final Object discriminatorValue;
private final String discriminatorSQLValue;
private final Map subclassByDiscriminatorValue = new HashMap();
private final String[] constraintOrderedTableNames;
private final String[][] constraintOrderedKeyColumnNames;
public UnionSubclassEntityPersister(
final PersistentClass persistentClass,
final SessionFactoryImplementor factory,
final Mapping mapping) throws ZormException {
super( persistentClass, factory );
// TABLE
tableName = persistentClass.getTable().getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
);
//Custom SQL
String sql;
boolean callable = false;
ExecuteUpdateResultCheckStyle checkStyle = null;
sql = persistentClass.getCustomSQLInsert();
callable = sql != null && persistentClass.isCustomInsertCallable();
checkStyle = sql == null
? ExecuteUpdateResultCheckStyle.COUNT
: persistentClass.getCustomSQLInsertCheckStyle() == null
? ExecuteUpdateResultCheckStyle.determineDefault( sql, callable )
: persistentClass.getCustomSQLInsertCheckStyle();
customSQLInsert = new String[] { sql };
insertCallable = new boolean[] { callable };
insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };
sql = persistentClass.getCustomSQLUpdate();
callable = sql != null && persistentClass.isCustomUpdateCallable();
checkStyle = sql == null
? ExecuteUpdateResultCheckStyle.COUNT
: persistentClass.getCustomSQLUpdateCheckStyle() == null
? ExecuteUpdateResultCheckStyle.determineDefault( sql, callable )
: persistentClass.getCustomSQLUpdateCheckStyle();
customSQLUpdate = new String[] { sql };
updateCallable = new boolean[] { callable };
updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };
sql = persistentClass.getCustomSQLDelete();
callable = sql != null && persistentClass.isCustomDeleteCallable();
checkStyle = sql == null
? ExecuteUpdateResultCheckStyle.COUNT
: persistentClass.getCustomSQLDeleteCheckStyle() == null
? ExecuteUpdateResultCheckStyle.determineDefault( sql, callable )
: persistentClass.getCustomSQLDeleteCheckStyle();
customSQLDelete = new String[] { sql };
deleteCallable = new boolean[] { callable };
deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };
discriminatorValue = persistentClass.getSubclassId();
discriminatorSQLValue = String.valueOf( persistentClass.getSubclassId() );
// PROPERTIES
int subclassSpan = persistentClass.getSubclassSpan() + 1;
subclassClosure = new String[subclassSpan];
subclassClosure[0] = getEntityName();
// SUBCLASSES
subclassByDiscriminatorValue.put(
persistentClass.getSubclassId(),
persistentClass.getEntityName()
);
if ( persistentClass.isPolymorphic() ) {
Iterator iter = persistentClass.getSubclassIterator();
int k=1;
while ( iter.hasNext() ) {
Subclass sc = (Subclass) iter.next();
subclassClosure[k++] = sc.getEntityName();
subclassByDiscriminatorValue.put( sc.getSubclassId(), sc.getEntityName() );
}
}
int spacesSize = 1 + persistentClass.getSynchronizedTables().size();
spaces = new String[spacesSize];
spaces[0] = tableName;
Iterator iter = persistentClass.getSynchronizedTables().iterator();
for ( int i=1; i<spacesSize; i++ ) {
spaces[i] = (String) iter.next();
}
HashSet subclassTables = new HashSet();
iter = persistentClass.getSubclassTableClosureIterator();
while ( iter.hasNext() ) {
Table table = (Table) iter.next();
subclassTables.add( table.getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
) );
}
subclassSpaces = ArrayHelper.toStringArray(subclassTables);
//子类数据库表
subquery = generateSubquery(persistentClass, mapping);
if ( isMultiTable() ) {
int idColumnSpan = getIdentifierColumnSpan();
ArrayList tableNames = new ArrayList();
ArrayList keyColumns = new ArrayList();
if ( !isAbstract() ) {
tableNames.add( tableName );
keyColumns.add( getIdentifierColumnNames() );
}
iter = persistentClass.getSubclassTableClosureIterator();
while ( iter.hasNext() ) {
Table tab = ( Table ) iter.next();
if ( !tab.isAbstractUnionTable() ) {
String tableName = tab.getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
);
tableNames.add( tableName );
String[] key = new String[idColumnSpan];
Iterator citer = tab.getPrimaryKey().getColumnIterator();
for ( int k=0; k<idColumnSpan; k++ ) {
key[k] = ( ( Column ) citer.next() ).getQuotedName( factory.getDialect() );
}
keyColumns.add( key );
}
}
constraintOrderedTableNames = ArrayHelper.toStringArray( tableNames );
constraintOrderedKeyColumnNames = ArrayHelper.to2DStringArray( keyColumns );
}
else {
constraintOrderedTableNames = new String[] { tableName };
constraintOrderedKeyColumnNames = new String[][] { getIdentifierColumnNames() };
}
initSubclassPropertyAliasesMap(persistentClass);
postConstruct(mapping);
}
public Serializable[] getQuerySpaces() {
return subclassSpaces;
}
public String getTableName() {
return subquery;
}
public Type getDiscriminatorType() {
return StandardBasicTypes.INTEGER;
}
public Object getDiscriminatorValue() {
return discriminatorValue;
}
public String getDiscriminatorSQLValue() {
return discriminatorSQLValue;
}
public String[] getSubclassClosure() {
return subclassClosure;
}
public String getSubclassForDiscriminatorValue(Object value) {
return (String) subclassByDiscriminatorValue.get(value);
}
public Serializable[] getPropertySpaces() {
return spaces;
}
protected boolean isDiscriminatorFormula() {
return false;
}
protected String getDiscriminatorFormula() {
return null;
}
protected String getTableName(int j) {
return tableName;
}
protected String[] getKeyColumns(int j) {
return getIdentifierColumnNames();
}
protected boolean isTableCascadeDeleteEnabled(int j) {
return false;
}
protected boolean isPropertyOfTable(int property, int j) {
return true;
}
// Execute the SQL:
public String fromTableFragment(String name) {
return getTableName() + ' ' + name;
}
public String filterFragment(String name) {
return hasWhere() ?
" and " + getSQLWhereString(name) :
"";
}
public String getSubclassPropertyTableName(int i) {
return getTableName();
}
protected void addDiscriminatorToSelect(SelectFragment select, String name, String suffix) {
select.addColumn( name, getDiscriminatorColumnName(), getDiscriminatorAlias() );
}
protected int[] getPropertyTableNumbersInSelect() {
return new int[ getPropertySpan() ];
}
protected int getSubclassPropertyTableNumber(int i) {
return 0;
}
public int getSubclassPropertyTableNumber(String propertyName) {
return 0;
}
public boolean isMultiTable() {
return isAbstract() || hasSubclasses();
}
public int getTableSpan() {
return 1;
}
protected int[] getSubclassColumnTableNumberClosure() {
return new int[ getSubclassColumnClosure().length ];
}
protected int[] getSubclassFormulaTableNumberClosure() {
return new int[ getSubclassFormulaClosure().length ];
}
protected boolean[] getTableHasColumns() {
return new boolean[] { true };
}
protected int[] getPropertyTableNumbers() {
return new int[ getPropertySpan() ];
}
protected String generateSubquery(PersistentClass model, Mapping mapping) {
Dialect dialect = getFactory().getDialect();
Settings settings = getFactory().getSettings();
if ( !model.hasSubclasses() ) {
return model.getTable().getQualifiedName(
dialect,
settings.getDefaultCatalogName(),
settings.getDefaultSchemaName()
);
}
HashSet columns = new LinkedHashSet();
Iterator titer = model.getSubclassTableClosureIterator();
while ( titer.hasNext() ) {
Table table = (Table) titer.next();
if ( !table.isAbstractUnionTable() ) {
Iterator citer = table.getColumnIterator();
while ( citer.hasNext() ) columns.add( citer.next() );
}
}
StringBuilder buf = new StringBuilder()
.append("( ");
Iterator siter = new JoinedIterator(
new SingletonIterator(model),
model.getSubclassIterator()
);
while ( siter.hasNext() ) {
PersistentClass clazz = (PersistentClass) siter.next();
Table table = clazz.getTable();
if ( !table.isAbstractUnionTable() ) {
buf.append("select ");
Iterator citer = columns.iterator();
while ( citer.hasNext() ) {
Column col = (Column) citer.next();
if ( !table.containsColumn(col) ) {
int sqlType = col.getSqlTypeCode(mapping);
buf.append( dialect.getSelectClauseNullString(sqlType) )
.append(" as ");
}
buf.append( col.getName() );
buf.append(", ");
}
buf.append( clazz.getSubclassId() )
.append(" as clazz_");
buf.append(" from ")
.append( table.getQualifiedName(
dialect,
settings.getDefaultCatalogName(),
settings.getDefaultSchemaName()
) );
buf.append(" union ");
if ( dialect.supportsUnionAll() ) {
buf.append("all ");
}
}
}
if ( buf.length() > 2 ) {
//chop the last union (all)
buf.setLength( buf.length() - ( dialect.supportsUnionAll() ? 11 : 7 ) );
}
return buf.append(" )").toString();
}
protected String[] getSubclassTableKeyColumns(int j) {
if (j!=0) throw new AssertionFailure("only one table");
return getIdentifierColumnNames();
}
public String getSubclassTableName(int j) {
if (j!=0) throw new AssertionFailure("only one table");
return tableName;
}
public int getSubclassTableSpan() {
return 1;
}
protected boolean isClassOrSuperclassTable(int j) {
if (j!=0) throw new AssertionFailure("only one table");
return true;
}
public String getPropertyTableName(String propertyName) {
//TODO: check this....
return getTableName();
}
public String[] getConstraintOrderedTableNameClosure() {
return constraintOrderedTableNames;
}
public String[][] getContraintOrderedTableKeyColumnClosure() {
return constraintOrderedKeyColumnNames;
}
@Override
public FilterAliasGenerator getFilterAliasGenerator(String rootAlias) {
return new StaticFilterAliasGenerator(rootAlias);
}
}
| 11,970 | 0.720856 | 0.719267 | 407 | 28.383293 | 23.377377 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.36855 | false | false |
1
|
121a0d67d647e876ce6436e72b979580f301cf46
| 36,636,071,073,896 |
225011bbc304c541f0170ef5b7ba09b967885e95
|
/mf/org/w3c/dom/svg/SVGPathSegList.java
|
0e3934937db64c9dff0520a27f67ed95fe0179e0
|
[] |
no_license
|
sebaudracco/bubble
|
https://github.com/sebaudracco/bubble
|
66536da5367f945ca3318fecc4a5f2e68c1df7ee
|
e282cda009dfc9422594b05c63e15f443ef093dc
|
refs/heads/master
| 2023-08-25T09:32:04.599000 | 2018-08-14T15:27:23 | 2018-08-14T15:27:23 | 140,444,001 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mf.org.w3c.dom.svg;
import mf.org.w3c.dom.DOMException;
public interface SVGPathSegList {
SVGPathSeg appendItem(SVGPathSeg sVGPathSeg) throws DOMException, SVGException;
void clear() throws DOMException;
SVGPathSeg getItem(int i) throws DOMException;
int getNumberOfItems();
SVGPathSeg initialize(SVGPathSeg sVGPathSeg) throws DOMException, SVGException;
SVGPathSeg insertItemBefore(SVGPathSeg sVGPathSeg, int i) throws DOMException, SVGException;
SVGPathSeg removeItem(int i) throws DOMException;
SVGPathSeg replaceItem(SVGPathSeg sVGPathSeg, int i) throws DOMException, SVGException;
}
|
UTF-8
|
Java
| 637 |
java
|
SVGPathSegList.java
|
Java
|
[] | null |
[] |
package mf.org.w3c.dom.svg;
import mf.org.w3c.dom.DOMException;
public interface SVGPathSegList {
SVGPathSeg appendItem(SVGPathSeg sVGPathSeg) throws DOMException, SVGException;
void clear() throws DOMException;
SVGPathSeg getItem(int i) throws DOMException;
int getNumberOfItems();
SVGPathSeg initialize(SVGPathSeg sVGPathSeg) throws DOMException, SVGException;
SVGPathSeg insertItemBefore(SVGPathSeg sVGPathSeg, int i) throws DOMException, SVGException;
SVGPathSeg removeItem(int i) throws DOMException;
SVGPathSeg replaceItem(SVGPathSeg sVGPathSeg, int i) throws DOMException, SVGException;
}
| 637 | 0.786499 | 0.783359 | 21 | 29.333334 | 33.563492 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.761905 | false | false |
1
|
3f2530dc10a83d102d7a3aae28a37d4a134ee5a3
| 38,036,230,394,011 |
e806e41e64cbe820411ef1ed5658bc0aa10883e8
|
/backstage/BorrowBook/src/Extenddao/DiscountDao.java
|
62c036e13504a8465306ae938c37296f1754bd96
|
[] |
no_license
|
YihaiDuan/SE_Final_Report
|
https://github.com/YihaiDuan/SE_Final_Report
|
485b582f2701fb0749c7e2aa11deca2176051360
|
10103d89dc4933035bae51040a86e9ba7c582630
|
refs/heads/master
| 2020-09-14T14:38:07.144000 | 2019-11-23T06:06:21 | 2019-11-23T06:06:21 | 223,157,487 | 2 | 0 | null | false | 2019-11-22T03:25:25 | 2019-11-21T11:21:14 | 2019-11-22T02:23:53 | 2019-11-22T03:25:24 | 37,588 | 2 | 0 | 0 |
Java
| false | false |
package Extenddao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import entity.Discount;
import util.HibernateUtil;
//打折卷和优惠劵
public class DiscountDao
{
//添加打折卷和优惠劵
public int SaveDiscount(Discount d)
{
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
session.save(d);
tx.commit();
HibernateUtil.closeSession(session);
return d.getId();
}
//根据id获取打折卷
public Discount getDisCountByid(int id)
{
Session session =HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Discount ds=(Discount) session.get(Discount.class,id);
tx.commit();
HibernateUtil.closeSession(session);
if(ds!=null)
{
return ds;
}
else
{
return null;
}
}
//更新打折的标志位
public void UpdateShowStaus(Discount ds)
{
Session session =HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Discount ds1=(Discount) session.get(Discount.class,ds.getId());
ds1.setShowstatus(ds.getShowstatus());
session.update(ds1);
tx.commit();
HibernateUtil.closeSession(session);
}
public List<Discount> getScoreDiscount()
{
Session session =HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
List<Discount> ds=session.createQuery("from Discount where status=1").list();
tx.commit();
HibernateUtil.closeSession(session);
if(ds!=null&&ds.size()>0)
{
return ds;
}
else
{
return null;
}
}
//删除对象
public void deleteDiscount(Discount discount){
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.delete(discount);
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
session.getTransaction().rollback();
}
finally{
HibernateUtil.closeSession(session);
}
}//删除全部已过期
public void deleteOutTimeDiscount(){
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
String hql = "delete from Discount where showstatus=2";
session.createQuery(hql).executeUpdate();
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
session.getTransaction().rollback();
}
finally{
HibernateUtil.closeSession(session);
}
}
//修改对象
public void updateDiscount(Discount discount){
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.update(discount);
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
session.getTransaction().rollback();
}
finally{
HibernateUtil.closeSession(session);
}
}
}
|
UTF-8
|
Java
| 3,001 |
java
|
DiscountDao.java
|
Java
|
[] | null |
[] |
package Extenddao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import entity.Discount;
import util.HibernateUtil;
//打折卷和优惠劵
public class DiscountDao
{
//添加打折卷和优惠劵
public int SaveDiscount(Discount d)
{
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
session.save(d);
tx.commit();
HibernateUtil.closeSession(session);
return d.getId();
}
//根据id获取打折卷
public Discount getDisCountByid(int id)
{
Session session =HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Discount ds=(Discount) session.get(Discount.class,id);
tx.commit();
HibernateUtil.closeSession(session);
if(ds!=null)
{
return ds;
}
else
{
return null;
}
}
//更新打折的标志位
public void UpdateShowStaus(Discount ds)
{
Session session =HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Discount ds1=(Discount) session.get(Discount.class,ds.getId());
ds1.setShowstatus(ds.getShowstatus());
session.update(ds1);
tx.commit();
HibernateUtil.closeSession(session);
}
public List<Discount> getScoreDiscount()
{
Session session =HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
List<Discount> ds=session.createQuery("from Discount where status=1").list();
tx.commit();
HibernateUtil.closeSession(session);
if(ds!=null&&ds.size()>0)
{
return ds;
}
else
{
return null;
}
}
//删除对象
public void deleteDiscount(Discount discount){
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.delete(discount);
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
session.getTransaction().rollback();
}
finally{
HibernateUtil.closeSession(session);
}
}//删除全部已过期
public void deleteOutTimeDiscount(){
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
String hql = "delete from Discount where showstatus=2";
session.createQuery(hql).executeUpdate();
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
session.getTransaction().rollback();
}
finally{
HibernateUtil.closeSession(session);
}
}
//修改对象
public void updateDiscount(Discount discount){
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.update(discount);
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
session.getTransaction().rollback();
}
finally{
HibernateUtil.closeSession(session);
}
}
}
| 3,001 | 0.663458 | 0.661396 | 166 | 16.518072 | 17.696478 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.39759 | false | false |
1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.