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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7aaf465f4cb82277df14ef07171b697d5162c598 | 22,016,002,365,801 | c7601970613d396b27ca720016a003e43e4c8fe9 | /app/src/main/java/com/craxiom/networksurveyplus/QcdmPcapWriter.java | 9f59886cee9bdb14e28517d98de41dee41132c9b | [
"Apache-2.0"
]
| permissive | bryanburress/android-network-survey-rooted | https://github.com/bryanburress/android-network-survey-rooted | d52b08acb0d29e6f0a50d6eb02d42346d0720add | a75a8fd6bb9a636cd7739d29f0d80404852989aa | refs/heads/master | 2022-12-10T23:52:18.076000 | 2020-08-29T20:31:09 | 2020-08-29T20:31:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.craxiom.networksurveyplus;
import android.os.Environment;
import com.craxiom.networksurveyplus.messages.DiagCommand;
import com.craxiom.networksurveyplus.messages.GsmtapConstants;
import com.craxiom.networksurveyplus.messages.LteRrcSubtypes;
import com.craxiom.networksurveyplus.messages.ParserUtils;
import com.craxiom.networksurveyplus.messages.QcdmMessage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import timber.log.Timber;
import static com.craxiom.networksurveyplus.messages.QcdmConstants.*;
/**
* Writes the QCDM messages to a PCAP file.
* <p>
* The PCAP file format can be found here: https://wiki.wireshark.org/Development/LibpcapFileFormat#File_Format
* <p>
* This class handles writing the pcap file global header, and then it also adds the appropriate layer 3 (IP),
* layer 4 (UDP), and GSM_TAP headers to the front of each QCDM message.
* <p>
* Credit goes to Wireshark, QCSuper (https://github.com/P1sec/QCSuper/blob/master/protocol/gsmtap.py), and
* Mobile Sentinel (https://github.com/RUB-SysSec/mobile_sentinel/blob/master/app/src/main/python/writers/pcapwriter.py)
* for the information on how to construct the appropriate headers to drop the QCDM messages in a pcap file.
*
* @since 0.1.0
*/
public class QcdmPcapWriter implements IQcdmMessageListener
{
private static final String LOG_DIRECTORY_NAME = "NetworkSurveyPlusData";
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault());
private static final byte[] ETHERNET_HEADER = {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x08, (byte) 0x00};
/**
* The 24 byte PCAP global header.
*/
private static final byte[] PCAP_FILE_GLOBAL_HEADER = {(byte) 0xd4, (byte) 0xc3, (byte) 0xb2, (byte) 0xa1, // PCAP magic number in little endian
2, 0, 4, 0, // Major and minor file version (2 bytes each)
0, 0, 0, 0, // GMT Offset (4 bytes)
0, 0, 0, 0, // Timestamp Accuracy: (4 bytes)
(byte) 0xff, (byte) 0xff, 0, 0, // Snapshot (length)
(byte) 0xe4, 0, 0, 0 // Link Layer Type (4 bytes): 228 is LINKTYPE_IPV4
};
private final BufferedOutputStream outputStream;
/**
* Constructs a new QCDM pcap file writer.
* <p>
* This constructor creates the file, and writes out the PCAP global header.
*
* @throws IOException If an error occurs when creating or writing to the file.
*/
QcdmPcapWriter() throws IOException
{
final File pcapFile = new File(createNewFilePath());
pcapFile.getParentFile().mkdirs();
outputStream = new BufferedOutputStream(new FileOutputStream(pcapFile));
outputStream.write(PCAP_FILE_GLOBAL_HEADER);
outputStream.flush();
}
@Override
public void onQcdmMessage(QcdmMessage qcdmMessage)
{
try
{
if (qcdmMessage.getOpCode() == DiagCommand.DIAG_LOG_F)
{
Timber.d("Pcap Writer listener: %s", qcdmMessage);
byte[] pcapRecord = null;
final int logType = qcdmMessage.getLogType();
switch (logType)
{
case LOG_LTE_RRC_OTA_MSG_LOG_C:
pcapRecord = convertLteRrcOtaMessage(qcdmMessage);
break;
}
if (pcapRecord != null)
{
Timber.v("Writing a message to the pcap file"); // TODO Delete me
outputStream.write(pcapRecord);
outputStream.flush();
}
}
} catch (Exception e)
{
Timber.e(e, "Could not handle a QCDM message");
}
}
/**
* Closes the pcap file's output stream.
*/
public void close()
{
try
{
outputStream.close();
} catch (IOException e)
{
Timber.e(e, "Could not close the pcap file output stream");
}
}
// TODO Javadoc
private static byte[] convertLteRrcOtaMessage(QcdmMessage qcdmMessage)
{
Timber.v("Handling an LTE RRC message"); // TODO Delete me
final byte[] logPayload = qcdmMessage.getLogPayload();
// The base header is 6 bytes:
// 1 byte each for Ext Header Version, RRC Rel, RRC Version, and Bearer ID
// 2 bytes for Physical Cell ID
final int extHeaderVersion = logPayload[0] & 0xFF;
final int pci = ParserUtils.getShort(logPayload, 4, ByteOrder.LITTLE_ENDIAN);
// Next is the extended header, which is either 7, 9, 11, or 13 bytes:
// freq is 2 bytes if extHeaderVersion < 8 and 4 bytes otherwise
// 2 bytes for System Frame Number (12 bits) & Subframe Number (4 bits)
// 1 byte for Channel Type
// Optional 4 bytes of padding if the length is != actual length. Something about the SIB mask is present.
// 2 bytes for length
final int frequencyLength = extHeaderVersion < 8 ? 2 : 4;
final int earfcn;
if (frequencyLength == 2)
{
earfcn = ParserUtils.getShort(logPayload, 6, ByteOrder.LITTLE_ENDIAN);
} else
{
earfcn = ParserUtils.getInteger(logPayload, 6, ByteOrder.LITTLE_ENDIAN);
}
// Mobile Sentinel seems to take the system frame number and combine it with the PCI into a 4 byte int value
// The System Frame Number as the last 12 bits, and the PCI as the first 16 bits.
// Shift the SFN right by 4 bytes because I *think* the last 4 bytes represent the subframe number (0 - 9).
final short sfnAndsubfn = ParserUtils.getShort(logPayload, 6 + frequencyLength, ByteOrder.LITTLE_ENDIAN);
final int subframeNumber = sfnAndsubfn & 0xF;
final int sfn = sfnAndsubfn >>> 4;
final int sfnAndPci = sfn | (pci << 16);
// If the length field (last two bytes of the extended header) is != to the actual length then the extended header is 4 bytes longer
int baseAndExtHeaderLength = 6 + frequencyLength + 5;
int length = ParserUtils.getShort(logPayload, baseAndExtHeaderLength - 2, ByteOrder.LITTLE_ENDIAN);
if (length != logPayload.length - baseAndExtHeaderLength)
{
baseAndExtHeaderLength += 4;
length = ParserUtils.getShort(logPayload, baseAndExtHeaderLength - 2, ByteOrder.LITTLE_ENDIAN);
}
// TODO QCSuper seems to ignore if the channel type is != 254, 255, 9, or 10. Not sure why that is.
int channelType = ParserUtils.getShort(logPayload, 6 + frequencyLength + 2, ByteOrder.LITTLE_ENDIAN);
boolean isUplink = channelType == LTE_UL_CCCH || channelType == LTE_UL_DCCH;
// TODO QCSuper subtracts 7 from the channelType if it is greater than LTE_UL_DCCH (8), but I have no idea why
if (channelType > LTE_UL_DCCH) channelType -= 7;
final int gsmtapChannelType = getGsmtapChannelType(channelType);
if (gsmtapChannelType == -1)
{
Timber.w("Unknown channel type received for LOG_LTE_RRC_OTA_MSG_LOG_C: %d", channelType);
return null;
}
Timber.d("baseAndExtHeaderLength=%d, providedLength=%d", baseAndExtHeaderLength, length);
final byte[] message = Arrays.copyOfRange(logPayload, baseAndExtHeaderLength, baseAndExtHeaderLength + length);
final byte[] gsmtapHeader = getGsmtapHeader(GsmtapConstants.GSMTAP_TYPE_LTE_RRC, gsmtapChannelType, earfcn, isUplink, sfnAndPci, subframeNumber);
final byte[] layer4Header = getLayer4Header(gsmtapHeader.length + message.length);
final byte[] layer3Header = getLayer3Header(layer4Header.length + gsmtapHeader.length + message.length);
final long currentTimeMillis = System.currentTimeMillis();
final byte[] pcapRecordHeader = getPcapRecordHeader(currentTimeMillis / 1000, (currentTimeMillis * 1000) % 1_000_000,
layer3Header.length + layer4Header.length + gsmtapHeader.length + message.length);
return concatenateByteArrays(pcapRecordHeader, layer3Header, layer4Header, gsmtapHeader, message);
}
// TODO Javadoc
private static int getGsmtapChannelType(int channelType)
{
switch (channelType)
{
case LTE_BCCH_DL_SCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_BCCH_DL_SCH_Message.ordinal();
case LTE_PCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_PCCH_Message.ordinal();
case LTE_DL_CCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_DL_CCCH_Message.ordinal();
case LTE_DL_DCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_DL_DCCH_Message.ordinal();
case LTE_UL_CCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_UL_CCCH_Message.ordinal();
case LTE_UL_DCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_UL_DCCH_Message.ordinal();
default:
return -1;
}
}
/**
* Concatenates the provided byte arrays to one long byte array.
*
* @param arrays The arrays to combine into one.
* @return the new concatenated byte array.
*/
private static byte[] concatenateByteArrays(byte[]... arrays)
{
try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
for (byte[] byteArray : arrays)
{
outputStream.write(byteArray);
}
return outputStream.toByteArray();
} catch (IOException e)
{
Timber.e(e, "A problem occured when trying to create the pcap record byte array");
}
return null;
}
/**
* Constructs a byte array in the GSMTAP header format. The header is always the same except for the
* payload type and subtype fields.
* <p>
* https://wiki.wireshark.org/GSMTAP
* http://osmocom.org/projects/baseband/wiki/GSMTAP
* <p>
* From the Osmocom website:
* <pre>
* struct gsmtap_hdr {
* uint8_t version; version, set to 0x01 currently
* uint8_t hdr_len; length in number of 32bit words
* uint8_t type; see GSMTAP_TYPE_*
* uint8_t timeslot; timeslot (0..7 on Um)
*
* uint16_t arfcn; ARFCN (frequency)
* int8_t signal_dbm; signal level in dBm
* int8_t snr_db; signal/noise ratio in dB
*
* uint32_t frame_number; GSM Frame Number (FN)
*
* uint8_t sub_type; Type of burst/channel, see above
* uint8_t antenna_nr; Antenna Number
* uint8_t sub_slot; sub-slot within timeslot
* uint8_t res; reserved for future use (RFU)
*
* } +attribute+((packed));
* </pre>
*
* @param payloadType The type of payload that follows this GSMTAP header.
* @param gsmtapChannelType The channel subtype.
* @param arfcn The ARFCN to include in the GSMTAP header (limited to 14 bits).
* @param isUplink True if the cellular payload represents an uplink message, false otherwise.
* @param sfnAndPci The System Frame Number as the last 12 bits, and the PCI as the first 16 bits.
* @return The byte array for the GSMTAP header.
*/
public static byte[] getGsmtapHeader(int payloadType, int gsmtapChannelType, int arfcn, boolean isUplink, int sfnAndPci, int subframeNumber)
{
// GSMTAP assumes the ARFCN fits in 14 bits, but the LTE spec has the EARFCN range go up to 65535
if (arfcn < 0 || arfcn > 16_383) arfcn = 0;
int arfcnAndUplink = isUplink ? arfcn | 0x40 : arfcn;
return new byte[]{
(byte) 0x02, // GSMTAP version (2) (There is a version 3 but Wireshark does not seem to parse it
(byte) 0x04, // Header length (4 aka 16 bytes)
(byte) (payloadType & 0xFF), // Payload type (1 byte)
(byte) 0x00, // Time Slot
(byte) ((arfcnAndUplink & 0xFF00) >>> 8), (byte) (arfcnAndUplink & 0x00FF), // Uplink (bit 15) ARFCN (last 14 bits)
(byte) 0x00, // Signal Level dBm
(byte) 0x00, // Signal/Noise Ratio dB
(byte) (sfnAndPci >>> 24), (byte) ((sfnAndPci & 0xFF0000) >>> 16), (byte) ((sfnAndPci & 0xFF00) >>> 8), (byte) (sfnAndPci & 0xFF), // GSM Frame Number
(byte) (gsmtapChannelType & 0xFF), // Subtype - Type of burst/channel
(byte) 0x00, // Antenna Number
(byte) (subframeNumber & 0xFF), // Sub-Slot
(byte) 0x00 // Reserved for future use
};
}
/**
* Constructs a byte array in the layer 4 header format (UDP header). The header is always the same except for the
* total length field, which it calculates using the provided value (it adds 8 because the UDP header is 8 bytes).
*
* @param packetLength The length of the GSM TAP header, and the payload.
* @return The byte array for the layer 4 header.
*/
public static byte[] getLayer4Header(int packetLength)
{
final int totalLength = 8 + packetLength;
return new byte[]{
(byte) 0x12, (byte) 0x79, // Source Port (GSMTAP Port 4729) // TODO Source port should be a client port
(byte) 0x12, (byte) 0x79, // Destination Port (GSMTAP Port 4729)
(byte) ((totalLength & 0xFF00) >>> 8), (byte) (totalLength & 0x00FF), // Total length (layer 3 header plus all other headers and the payload, aka start of layer 3 header to end of packet)
(byte) 0x00, (byte) 0x00, // checksum
};
}
/**
* Constructs a byte array in the layer 3 header format (IP header). The header is always the same except for the
* total length field, which it calculates using the provided value (it adds 20 because the IP header is 20 bytes).
*
* @param packetLength The length of the layer 4 header, GSM TAP header, and the payload.
* @return The byte array for the layer 3 header.
*/
public static byte[] getLayer3Header(int packetLength)
{
final int totalLength = 20 + packetLength;
return new byte[]{
(byte) 0x45, // IPv4 version (4) and length (5 aka 20 bytes))
(byte) 0x00, // Differentiated Services Codepoint
(byte) ((totalLength & 0xFF00) >>> 8), (byte) (totalLength & 0x00FF), // Total length (layer 3 header plus all other headers and the payload, aka start of layer 3 header to end of packet)
(byte) 0x00, (byte) 0x00, // Identification
(byte) 0x00, (byte) 0x00, // Flags
(byte) 0x40, // Time to live (64)
(byte) 0x11, // Protocol (17 UDP)
(byte) 0x00, (byte) 0x00, // Header checksum
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, // Source IP
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, // Destination IP
};
}
/**
* Returns the header that is placed at the beginning of each PCAP record.
*
* @param timeSec The time that this pcap record was generated in seconds.
* @param timeMicroSec The microseconds use to add more precision to the {@code timeSec} parameter.
* @param length The length of the pcap record (I think including this pcap record header).
* @return The byte[] for the pcap record header.
*/
public static byte[] getPcapRecordHeader(long timeSec, long timeMicroSec, int length)
{
return new byte[]{
(byte) (timeSec & 0x00FF), (byte) ((timeSec & 0xFF00) >>> 8), (byte) ((timeSec & 0xFF0000) >>> 16), (byte) (timeSec >>> 24),
(byte) (timeMicroSec & 0x00FF), (byte) ((timeMicroSec & 0xFF00) >>> 8), (byte) ((timeMicroSec & 0xFF0000) >>> 16), (byte) (timeMicroSec >>> 24),
(byte) (length & 0xFF), (byte) ((length & 0xFF00) >>> 8), (byte) ((length & 0xFF0000) >>> 16), (byte) (length >>> 24), // Frame length
(byte) (length & 0xFF), (byte) ((length & 0xFF00) >>> 8), (byte) ((length & 0xFF0000) >>> 16), (byte) (length >>> 24), // Capture length
};
}
/**
* @return The full path to the public directory where we store the pcap files.
*/
private String createNewFilePath()
{
return Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/" + LOG_DIRECTORY_NAME + "/" +
Constants.PCAP_FILE_NAME_PREFIX + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + ".pcap";
}
}
| UTF-8 | Java | 17,217 | java | QcdmPcapWriter.java | Java | [
{
"context": "it goes to Wireshark, QCSuper (https://github.com/P1sec/QCSuper/blob/master/protocol/gsmtap.py), and\n * M",
"end": 1211,
"score": 0.9987894892692566,
"start": 1206,
"tag": "USERNAME",
"value": "P1sec"
},
{
"context": "p.py), and\n * Mobile Sentinel (https://github.com/RUB-SysSec/mobile_sentinel/blob/master/app/src/main/python/w",
"end": 1306,
"score": 0.9982962608337402,
"start": 1296,
"tag": "USERNAME",
"value": "RUB-SysSec"
}
]
| null | []
| package com.craxiom.networksurveyplus;
import android.os.Environment;
import com.craxiom.networksurveyplus.messages.DiagCommand;
import com.craxiom.networksurveyplus.messages.GsmtapConstants;
import com.craxiom.networksurveyplus.messages.LteRrcSubtypes;
import com.craxiom.networksurveyplus.messages.ParserUtils;
import com.craxiom.networksurveyplus.messages.QcdmMessage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import timber.log.Timber;
import static com.craxiom.networksurveyplus.messages.QcdmConstants.*;
/**
* Writes the QCDM messages to a PCAP file.
* <p>
* The PCAP file format can be found here: https://wiki.wireshark.org/Development/LibpcapFileFormat#File_Format
* <p>
* This class handles writing the pcap file global header, and then it also adds the appropriate layer 3 (IP),
* layer 4 (UDP), and GSM_TAP headers to the front of each QCDM message.
* <p>
* Credit goes to Wireshark, QCSuper (https://github.com/P1sec/QCSuper/blob/master/protocol/gsmtap.py), and
* Mobile Sentinel (https://github.com/RUB-SysSec/mobile_sentinel/blob/master/app/src/main/python/writers/pcapwriter.py)
* for the information on how to construct the appropriate headers to drop the QCDM messages in a pcap file.
*
* @since 0.1.0
*/
public class QcdmPcapWriter implements IQcdmMessageListener
{
private static final String LOG_DIRECTORY_NAME = "NetworkSurveyPlusData";
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss").withZone(ZoneId.systemDefault());
private static final byte[] ETHERNET_HEADER = {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x08, (byte) 0x00};
/**
* The 24 byte PCAP global header.
*/
private static final byte[] PCAP_FILE_GLOBAL_HEADER = {(byte) 0xd4, (byte) 0xc3, (byte) 0xb2, (byte) 0xa1, // PCAP magic number in little endian
2, 0, 4, 0, // Major and minor file version (2 bytes each)
0, 0, 0, 0, // GMT Offset (4 bytes)
0, 0, 0, 0, // Timestamp Accuracy: (4 bytes)
(byte) 0xff, (byte) 0xff, 0, 0, // Snapshot (length)
(byte) 0xe4, 0, 0, 0 // Link Layer Type (4 bytes): 228 is LINKTYPE_IPV4
};
private final BufferedOutputStream outputStream;
/**
* Constructs a new QCDM pcap file writer.
* <p>
* This constructor creates the file, and writes out the PCAP global header.
*
* @throws IOException If an error occurs when creating or writing to the file.
*/
QcdmPcapWriter() throws IOException
{
final File pcapFile = new File(createNewFilePath());
pcapFile.getParentFile().mkdirs();
outputStream = new BufferedOutputStream(new FileOutputStream(pcapFile));
outputStream.write(PCAP_FILE_GLOBAL_HEADER);
outputStream.flush();
}
@Override
public void onQcdmMessage(QcdmMessage qcdmMessage)
{
try
{
if (qcdmMessage.getOpCode() == DiagCommand.DIAG_LOG_F)
{
Timber.d("Pcap Writer listener: %s", qcdmMessage);
byte[] pcapRecord = null;
final int logType = qcdmMessage.getLogType();
switch (logType)
{
case LOG_LTE_RRC_OTA_MSG_LOG_C:
pcapRecord = convertLteRrcOtaMessage(qcdmMessage);
break;
}
if (pcapRecord != null)
{
Timber.v("Writing a message to the pcap file"); // TODO Delete me
outputStream.write(pcapRecord);
outputStream.flush();
}
}
} catch (Exception e)
{
Timber.e(e, "Could not handle a QCDM message");
}
}
/**
* Closes the pcap file's output stream.
*/
public void close()
{
try
{
outputStream.close();
} catch (IOException e)
{
Timber.e(e, "Could not close the pcap file output stream");
}
}
// TODO Javadoc
private static byte[] convertLteRrcOtaMessage(QcdmMessage qcdmMessage)
{
Timber.v("Handling an LTE RRC message"); // TODO Delete me
final byte[] logPayload = qcdmMessage.getLogPayload();
// The base header is 6 bytes:
// 1 byte each for Ext Header Version, RRC Rel, RRC Version, and Bearer ID
// 2 bytes for Physical Cell ID
final int extHeaderVersion = logPayload[0] & 0xFF;
final int pci = ParserUtils.getShort(logPayload, 4, ByteOrder.LITTLE_ENDIAN);
// Next is the extended header, which is either 7, 9, 11, or 13 bytes:
// freq is 2 bytes if extHeaderVersion < 8 and 4 bytes otherwise
// 2 bytes for System Frame Number (12 bits) & Subframe Number (4 bits)
// 1 byte for Channel Type
// Optional 4 bytes of padding if the length is != actual length. Something about the SIB mask is present.
// 2 bytes for length
final int frequencyLength = extHeaderVersion < 8 ? 2 : 4;
final int earfcn;
if (frequencyLength == 2)
{
earfcn = ParserUtils.getShort(logPayload, 6, ByteOrder.LITTLE_ENDIAN);
} else
{
earfcn = ParserUtils.getInteger(logPayload, 6, ByteOrder.LITTLE_ENDIAN);
}
// Mobile Sentinel seems to take the system frame number and combine it with the PCI into a 4 byte int value
// The System Frame Number as the last 12 bits, and the PCI as the first 16 bits.
// Shift the SFN right by 4 bytes because I *think* the last 4 bytes represent the subframe number (0 - 9).
final short sfnAndsubfn = ParserUtils.getShort(logPayload, 6 + frequencyLength, ByteOrder.LITTLE_ENDIAN);
final int subframeNumber = sfnAndsubfn & 0xF;
final int sfn = sfnAndsubfn >>> 4;
final int sfnAndPci = sfn | (pci << 16);
// If the length field (last two bytes of the extended header) is != to the actual length then the extended header is 4 bytes longer
int baseAndExtHeaderLength = 6 + frequencyLength + 5;
int length = ParserUtils.getShort(logPayload, baseAndExtHeaderLength - 2, ByteOrder.LITTLE_ENDIAN);
if (length != logPayload.length - baseAndExtHeaderLength)
{
baseAndExtHeaderLength += 4;
length = ParserUtils.getShort(logPayload, baseAndExtHeaderLength - 2, ByteOrder.LITTLE_ENDIAN);
}
// TODO QCSuper seems to ignore if the channel type is != 254, 255, 9, or 10. Not sure why that is.
int channelType = ParserUtils.getShort(logPayload, 6 + frequencyLength + 2, ByteOrder.LITTLE_ENDIAN);
boolean isUplink = channelType == LTE_UL_CCCH || channelType == LTE_UL_DCCH;
// TODO QCSuper subtracts 7 from the channelType if it is greater than LTE_UL_DCCH (8), but I have no idea why
if (channelType > LTE_UL_DCCH) channelType -= 7;
final int gsmtapChannelType = getGsmtapChannelType(channelType);
if (gsmtapChannelType == -1)
{
Timber.w("Unknown channel type received for LOG_LTE_RRC_OTA_MSG_LOG_C: %d", channelType);
return null;
}
Timber.d("baseAndExtHeaderLength=%d, providedLength=%d", baseAndExtHeaderLength, length);
final byte[] message = Arrays.copyOfRange(logPayload, baseAndExtHeaderLength, baseAndExtHeaderLength + length);
final byte[] gsmtapHeader = getGsmtapHeader(GsmtapConstants.GSMTAP_TYPE_LTE_RRC, gsmtapChannelType, earfcn, isUplink, sfnAndPci, subframeNumber);
final byte[] layer4Header = getLayer4Header(gsmtapHeader.length + message.length);
final byte[] layer3Header = getLayer3Header(layer4Header.length + gsmtapHeader.length + message.length);
final long currentTimeMillis = System.currentTimeMillis();
final byte[] pcapRecordHeader = getPcapRecordHeader(currentTimeMillis / 1000, (currentTimeMillis * 1000) % 1_000_000,
layer3Header.length + layer4Header.length + gsmtapHeader.length + message.length);
return concatenateByteArrays(pcapRecordHeader, layer3Header, layer4Header, gsmtapHeader, message);
}
// TODO Javadoc
private static int getGsmtapChannelType(int channelType)
{
switch (channelType)
{
case LTE_BCCH_DL_SCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_BCCH_DL_SCH_Message.ordinal();
case LTE_PCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_PCCH_Message.ordinal();
case LTE_DL_CCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_DL_CCCH_Message.ordinal();
case LTE_DL_DCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_DL_DCCH_Message.ordinal();
case LTE_UL_CCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_UL_CCCH_Message.ordinal();
case LTE_UL_DCCH:
return LteRrcSubtypes.GSMTAP_LTE_RRC_SUB_UL_DCCH_Message.ordinal();
default:
return -1;
}
}
/**
* Concatenates the provided byte arrays to one long byte array.
*
* @param arrays The arrays to combine into one.
* @return the new concatenated byte array.
*/
private static byte[] concatenateByteArrays(byte[]... arrays)
{
try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
for (byte[] byteArray : arrays)
{
outputStream.write(byteArray);
}
return outputStream.toByteArray();
} catch (IOException e)
{
Timber.e(e, "A problem occured when trying to create the pcap record byte array");
}
return null;
}
/**
* Constructs a byte array in the GSMTAP header format. The header is always the same except for the
* payload type and subtype fields.
* <p>
* https://wiki.wireshark.org/GSMTAP
* http://osmocom.org/projects/baseband/wiki/GSMTAP
* <p>
* From the Osmocom website:
* <pre>
* struct gsmtap_hdr {
* uint8_t version; version, set to 0x01 currently
* uint8_t hdr_len; length in number of 32bit words
* uint8_t type; see GSMTAP_TYPE_*
* uint8_t timeslot; timeslot (0..7 on Um)
*
* uint16_t arfcn; ARFCN (frequency)
* int8_t signal_dbm; signal level in dBm
* int8_t snr_db; signal/noise ratio in dB
*
* uint32_t frame_number; GSM Frame Number (FN)
*
* uint8_t sub_type; Type of burst/channel, see above
* uint8_t antenna_nr; Antenna Number
* uint8_t sub_slot; sub-slot within timeslot
* uint8_t res; reserved for future use (RFU)
*
* } +attribute+((packed));
* </pre>
*
* @param payloadType The type of payload that follows this GSMTAP header.
* @param gsmtapChannelType The channel subtype.
* @param arfcn The ARFCN to include in the GSMTAP header (limited to 14 bits).
* @param isUplink True if the cellular payload represents an uplink message, false otherwise.
* @param sfnAndPci The System Frame Number as the last 12 bits, and the PCI as the first 16 bits.
* @return The byte array for the GSMTAP header.
*/
public static byte[] getGsmtapHeader(int payloadType, int gsmtapChannelType, int arfcn, boolean isUplink, int sfnAndPci, int subframeNumber)
{
// GSMTAP assumes the ARFCN fits in 14 bits, but the LTE spec has the EARFCN range go up to 65535
if (arfcn < 0 || arfcn > 16_383) arfcn = 0;
int arfcnAndUplink = isUplink ? arfcn | 0x40 : arfcn;
return new byte[]{
(byte) 0x02, // GSMTAP version (2) (There is a version 3 but Wireshark does not seem to parse it
(byte) 0x04, // Header length (4 aka 16 bytes)
(byte) (payloadType & 0xFF), // Payload type (1 byte)
(byte) 0x00, // Time Slot
(byte) ((arfcnAndUplink & 0xFF00) >>> 8), (byte) (arfcnAndUplink & 0x00FF), // Uplink (bit 15) ARFCN (last 14 bits)
(byte) 0x00, // Signal Level dBm
(byte) 0x00, // Signal/Noise Ratio dB
(byte) (sfnAndPci >>> 24), (byte) ((sfnAndPci & 0xFF0000) >>> 16), (byte) ((sfnAndPci & 0xFF00) >>> 8), (byte) (sfnAndPci & 0xFF), // GSM Frame Number
(byte) (gsmtapChannelType & 0xFF), // Subtype - Type of burst/channel
(byte) 0x00, // Antenna Number
(byte) (subframeNumber & 0xFF), // Sub-Slot
(byte) 0x00 // Reserved for future use
};
}
/**
* Constructs a byte array in the layer 4 header format (UDP header). The header is always the same except for the
* total length field, which it calculates using the provided value (it adds 8 because the UDP header is 8 bytes).
*
* @param packetLength The length of the GSM TAP header, and the payload.
* @return The byte array for the layer 4 header.
*/
public static byte[] getLayer4Header(int packetLength)
{
final int totalLength = 8 + packetLength;
return new byte[]{
(byte) 0x12, (byte) 0x79, // Source Port (GSMTAP Port 4729) // TODO Source port should be a client port
(byte) 0x12, (byte) 0x79, // Destination Port (GSMTAP Port 4729)
(byte) ((totalLength & 0xFF00) >>> 8), (byte) (totalLength & 0x00FF), // Total length (layer 3 header plus all other headers and the payload, aka start of layer 3 header to end of packet)
(byte) 0x00, (byte) 0x00, // checksum
};
}
/**
* Constructs a byte array in the layer 3 header format (IP header). The header is always the same except for the
* total length field, which it calculates using the provided value (it adds 20 because the IP header is 20 bytes).
*
* @param packetLength The length of the layer 4 header, GSM TAP header, and the payload.
* @return The byte array for the layer 3 header.
*/
public static byte[] getLayer3Header(int packetLength)
{
final int totalLength = 20 + packetLength;
return new byte[]{
(byte) 0x45, // IPv4 version (4) and length (5 aka 20 bytes))
(byte) 0x00, // Differentiated Services Codepoint
(byte) ((totalLength & 0xFF00) >>> 8), (byte) (totalLength & 0x00FF), // Total length (layer 3 header plus all other headers and the payload, aka start of layer 3 header to end of packet)
(byte) 0x00, (byte) 0x00, // Identification
(byte) 0x00, (byte) 0x00, // Flags
(byte) 0x40, // Time to live (64)
(byte) 0x11, // Protocol (17 UDP)
(byte) 0x00, (byte) 0x00, // Header checksum
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, // Source IP
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, // Destination IP
};
}
/**
* Returns the header that is placed at the beginning of each PCAP record.
*
* @param timeSec The time that this pcap record was generated in seconds.
* @param timeMicroSec The microseconds use to add more precision to the {@code timeSec} parameter.
* @param length The length of the pcap record (I think including this pcap record header).
* @return The byte[] for the pcap record header.
*/
public static byte[] getPcapRecordHeader(long timeSec, long timeMicroSec, int length)
{
return new byte[]{
(byte) (timeSec & 0x00FF), (byte) ((timeSec & 0xFF00) >>> 8), (byte) ((timeSec & 0xFF0000) >>> 16), (byte) (timeSec >>> 24),
(byte) (timeMicroSec & 0x00FF), (byte) ((timeMicroSec & 0xFF00) >>> 8), (byte) ((timeMicroSec & 0xFF0000) >>> 16), (byte) (timeMicroSec >>> 24),
(byte) (length & 0xFF), (byte) ((length & 0xFF00) >>> 8), (byte) ((length & 0xFF0000) >>> 16), (byte) (length >>> 24), // Frame length
(byte) (length & 0xFF), (byte) ((length & 0xFF00) >>> 8), (byte) ((length & 0xFF0000) >>> 16), (byte) (length >>> 24), // Capture length
};
}
/**
* @return The full path to the public directory where we store the pcap files.
*/
private String createNewFilePath()
{
return Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/" + LOG_DIRECTORY_NAME + "/" +
Constants.PCAP_FILE_NAME_PREFIX + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + ".pcap";
}
}
| 17,217 | 0.617065 | 0.590521 | 378 | 44.547619 | 42.259956 | 233 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.730159 | false | false | 10 |
1da977ce04fd2e472ec5cfb2f20f5967a5a903ba | 8,847,632,654,101 | 8823c96d433605e7c13679b027a697e6a647cf9c | /src/main/java/com/lzhlyle/contest/weekly/weekly182/UndergroundSystem.java | 6c2991044c3e56a22f608fb3541227a9469959bb | [
"MIT"
]
| permissive | lzhlyle/leetcode | https://github.com/lzhlyle/leetcode | 62278bf6e949f802da335e8de2d420440f578c2f | 8f053128ed7917c231fd24cfe82552d9c599dc16 | refs/heads/master | 2022-07-14T02:28:11.082000 | 2020-11-16T14:28:20 | 2020-11-16T14:28:20 | 215,598,819 | 2 | 0 | MIT | false | 2022-06-17T02:55:41 | 2019-10-16T16:52:05 | 2020-11-16T14:28:38 | 2022-06-17T02:55:41 | 1,835 | 0 | 0 | 2 | Java | false | false | package com.lzhlyle.contest.weekly.weekly182;
import java.util.HashMap;
import java.util.Map;
public class UndergroundSystem {
private Map<String, long[]> map; // int[2]: {total, n}
private Map<Integer, Tour> tourMap;
public UndergroundSystem() {
map = new HashMap<>();
tourMap = new HashMap<>();
}
public void checkIn(int id, String stationName, int t) {
tourMap.put(id, new Tour(stationName, t));
}
public void checkOut(int id, String stationName, int t) {
if (tourMap.containsKey(id)) {
Tour tour = tourMap.get(id);
String key = tour.from.compareTo(stationName) < 0 ? tour.from + "-" + stationName : stationName + "-" + tour.from;
if (!map.containsKey(key)) map.put(key, new long[2]);
long[] arr = map.get(key);
arr[0] += t - tour.t; // total time
arr[1] += 1; // how many
map.put(key, arr);
}
}
public double getAverageTime(String startStation, String endStation) {
String key = startStation.compareTo(endStation) < 0 ? startStation+ "-" + endStation : endStation+ "-" + startStation;
if (!map.containsKey(key)) return 0;
long[] arr = map.get(key);
double res = arr[0] * 1.0 / arr[1];
System.out.println(res);
return res;
}
class Tour {
String from;
int t;
public Tour(String from, int t) {
this.from = from;
this.t = t;
}
}
public static void main(String[] args) {
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15);
undergroundSystem.checkOut(27, "Waterloo", 20);
undergroundSystem.checkOut(32, "Cambridge", 22);
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // 返回 14.0。从 "Paradise"(时刻 8)到 "Cambridge"(时刻 22)的行程只有一趟
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // 返回 11.0。总共有 2 躺从 "Leyton" 到 "Waterloo" 的行程,编号为 id=45 的乘客出发于 time=3 到达于 time=15,编号为 id=27 的乘客于 time=10 出发于 time=20 到达。所以平均时间为 ( (15-3) + (20-10) ) / 2 = 11.0
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // 返回 11.0
undergroundSystem.checkOut(10, "Waterloo", 38);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // 返回 12.0
}
}
| UTF-8 | Java | 2,807 | java | UndergroundSystem.java | Java | []
| null | []
| package com.lzhlyle.contest.weekly.weekly182;
import java.util.HashMap;
import java.util.Map;
public class UndergroundSystem {
private Map<String, long[]> map; // int[2]: {total, n}
private Map<Integer, Tour> tourMap;
public UndergroundSystem() {
map = new HashMap<>();
tourMap = new HashMap<>();
}
public void checkIn(int id, String stationName, int t) {
tourMap.put(id, new Tour(stationName, t));
}
public void checkOut(int id, String stationName, int t) {
if (tourMap.containsKey(id)) {
Tour tour = tourMap.get(id);
String key = tour.from.compareTo(stationName) < 0 ? tour.from + "-" + stationName : stationName + "-" + tour.from;
if (!map.containsKey(key)) map.put(key, new long[2]);
long[] arr = map.get(key);
arr[0] += t - tour.t; // total time
arr[1] += 1; // how many
map.put(key, arr);
}
}
public double getAverageTime(String startStation, String endStation) {
String key = startStation.compareTo(endStation) < 0 ? startStation+ "-" + endStation : endStation+ "-" + startStation;
if (!map.containsKey(key)) return 0;
long[] arr = map.get(key);
double res = arr[0] * 1.0 / arr[1];
System.out.println(res);
return res;
}
class Tour {
String from;
int t;
public Tour(String from, int t) {
this.from = from;
this.t = t;
}
}
public static void main(String[] args) {
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15);
undergroundSystem.checkOut(27, "Waterloo", 20);
undergroundSystem.checkOut(32, "Cambridge", 22);
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // 返回 14.0。从 "Paradise"(时刻 8)到 "Cambridge"(时刻 22)的行程只有一趟
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // 返回 11.0。总共有 2 躺从 "Leyton" 到 "Waterloo" 的行程,编号为 id=45 的乘客出发于 time=3 到达于 time=15,编号为 id=27 的乘客于 time=10 出发于 time=20 到达。所以平均时间为 ( (15-3) + (20-10) ) / 2 = 11.0
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // 返回 11.0
undergroundSystem.checkOut(10, "Waterloo", 38);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // 返回 12.0
}
}
| 2,807 | 0.580681 | 0.549607 | 65 | 39.092308 | 38.742432 | 232 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.092308 | false | false | 10 |
ed8562369a3fa4da40a507cdf19be0cc1af0412a | 29,583,734,738,308 | 9be3171d320b3aadda0021fc28c8ab0f028bd10b | /demos/demo-14-kafka/src/main/java/demo/kafka/simple/MyRestController.java | 3c58b68010e13660f8cff24acb05a4b5fa700e54 | []
| no_license | VestiDev/spring-boot-in-3-weeks | https://github.com/VestiDev/spring-boot-in-3-weeks | c98ab93d22cf8e97a9a845fb12efb2887f56f520 | bd3e0da826558ab9c91a5b5313f62627ea577b5c | refs/heads/master | 2023-08-21T18:57:13.299000 | 2021-10-11T15:27:02 | 2021-10-11T15:27:02 | 419,099,471 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package demo.kafka.simple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/mykafka")
@CrossOrigin
public class MyRestController {
@Autowired
private MyPublisher publisher;
@GetMapping("/publish")
public String publish(@RequestParam("value") String value) {
for (int i = 1; i <= 5; i++) {
this.publisher.sendMessage("key" + i, value);
}
return "Published 5 messages, keys: 1-5, value: " + value;
}
} | UTF-8 | Java | 557 | java | MyRestController.java | Java | []
| null | []
| package demo.kafka.simple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/mykafka")
@CrossOrigin
public class MyRestController {
@Autowired
private MyPublisher publisher;
@GetMapping("/publish")
public String publish(@RequestParam("value") String value) {
for (int i = 1; i <= 5; i++) {
this.publisher.sendMessage("key" + i, value);
}
return "Published 5 messages, keys: 1-5, value: " + value;
}
} | 557 | 0.67325 | 0.664273 | 21 | 25.571428 | 22.446915 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 10 |
859381cbd33da29888757e65dbae022326ed5abc | 21,483,426,468,591 | aa529158261389306364e8c31e91ee3caec2026a | /src/pom/Pomclasslogin.java | dcc4e9aa16ca2f69f5bc7ae732994e50bea3f06b | []
| no_license | NIQITA21/selenium | https://github.com/NIQITA21/selenium | 2a22f8b333ca12a84de47e12ad7b2e7c2094a005 | 628739b477d4fc8492ec16fb6b2ef654776621ed | refs/heads/master | 2023-07-10T15:46:50.163000 | 2021-08-19T11:51:32 | 2021-08-19T11:51:32 | 397,926,564 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Pomclasslogin {
@FindBy(xpath="//input[@name='email']")
private WebElement untbox;
@FindBy(xpath="//input[@name='pass']")
private WebElement pwdtbox;
@FindBy(xpath="//button[@value='1']")
private WebElement loginbtn;
public Pomclasslogin(WebDriver driver)//constructor
{
PageFactory.initElements(driver, this);
}
public void setusername(String un)
{
untbox.sendKeys(un);
}
public void setpwd(String pwd)
{
pwdtbox.sendKeys(pwd);
}
public void clicklogin()
{
loginbtn.click();
}
}
| UTF-8 | Java | 753 | java | Pomclasslogin.java | Java | []
| null | []
| package pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Pomclasslogin {
@FindBy(xpath="//input[@name='email']")
private WebElement untbox;
@FindBy(xpath="//input[@name='pass']")
private WebElement pwdtbox;
@FindBy(xpath="//button[@value='1']")
private WebElement loginbtn;
public Pomclasslogin(WebDriver driver)//constructor
{
PageFactory.initElements(driver, this);
}
public void setusername(String un)
{
untbox.sendKeys(un);
}
public void setpwd(String pwd)
{
pwdtbox.sendKeys(pwd);
}
public void clicklogin()
{
loginbtn.click();
}
}
| 753 | 0.689243 | 0.687915 | 33 | 20.757576 | 16.86853 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.121212 | false | false | 10 |
1316de0cf1f3cd5b8011a456c8ced19fc86185b0 | 31,044,023,648,863 | 9108212b7dcfc6bc203675f946422e1fc33da828 | /Project Megaman/libgdx_megaman'/core/src/Sprites/Physics1.java | ff24ccb3ba2508fb9a97b900d729d5208fe5849a | []
| no_license | mohamedabdallah20/Mega-man-oop-project | https://github.com/mohamedabdallah20/Mega-man-oop-project | f9e7b3f0c6602a48f8ed6ce2a2b6d1fb2e2a7b2c | c19eddbf0246c3ce4179fc605bedab18e23d8abc | refs/heads/master | 2022-04-14T06:31:14.581000 | 2020-04-06T22:36:04 | 2020-04-06T22:36:04 | 243,014,958 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* package Sprites;
*
*
*
* import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx;
* import com.badlogic.gdx.graphics.GL20; import
* com.badlogic.gdx.graphics.Texture; import
* com.badlogic.gdx.graphics.g2d.Sprite; import
* com.badlogic.gdx.graphics.g2d.SpriteBatch; import
* com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*;
*
* public class Physics1 extends ApplicationAdapter { SpriteBatch batch; Sprite
* sprite; Texture img; World world; Body body;
*
* @Override public void create() {
*
* batch = new SpriteBatch();
*
* img = new Texture("fire1.png"); sprite = new Sprite(img);
*
* // Center the sprite in the top/middle of the screen
* sprite.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2,
* Gdx.graphics.getHeight() / 2);
*
*
* world = new World(new Vector2(0, -98f), true);
*
*
* BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.DynamicBody;
*
* // Set our body to the same position as our sprite
* bodyDef.position.set(sprite.getX(), sprite.getY());
*
* // Create a body in the world using our definition body =
* world.createBody(bodyDef);
*
* // Now define the dimensions of the physics shape PolygonShape shape = new
* PolygonShape();
*
* shape.setAsBox(sprite.getWidth()/2, sprite.getHeight()/2);
*
* FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape;
* fixtureDef.density = 1f;
*
* Fixture fixture = body.createFixture(fixtureDef);
*
* // Shape is the only disposable of the lot, so get rid of it shape.dispose();
* }
*
* @Override public void render() {
*
*
* world.step(Gdx.graphics.getDeltaTime(), 6, 2);
*
* // Now update the spritee position accordingly to it's now updated
* sprite.setPosition(body.getPosition().x, body.getPosition().y);
*
* // You know the rest... Gdx.gl.glClearColor(1, 1, 1, 1);
* Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(sprite,
* sprite.getX(), sprite.getY()); batch.end(); }
*
* @Override public void dispose() { // Hey, I actually did some clean up in a
* code sample! img.dispose(); world.dispose(); } }
*/ | UTF-8 | Java | 2,162 | java | Physics1.java | Java | []
| null | []
| /*
* package Sprites;
*
*
*
* import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx;
* import com.badlogic.gdx.graphics.GL20; import
* com.badlogic.gdx.graphics.Texture; import
* com.badlogic.gdx.graphics.g2d.Sprite; import
* com.badlogic.gdx.graphics.g2d.SpriteBatch; import
* com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*;
*
* public class Physics1 extends ApplicationAdapter { SpriteBatch batch; Sprite
* sprite; Texture img; World world; Body body;
*
* @Override public void create() {
*
* batch = new SpriteBatch();
*
* img = new Texture("fire1.png"); sprite = new Sprite(img);
*
* // Center the sprite in the top/middle of the screen
* sprite.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2,
* Gdx.graphics.getHeight() / 2);
*
*
* world = new World(new Vector2(0, -98f), true);
*
*
* BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.DynamicBody;
*
* // Set our body to the same position as our sprite
* bodyDef.position.set(sprite.getX(), sprite.getY());
*
* // Create a body in the world using our definition body =
* world.createBody(bodyDef);
*
* // Now define the dimensions of the physics shape PolygonShape shape = new
* PolygonShape();
*
* shape.setAsBox(sprite.getWidth()/2, sprite.getHeight()/2);
*
* FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape;
* fixtureDef.density = 1f;
*
* Fixture fixture = body.createFixture(fixtureDef);
*
* // Shape is the only disposable of the lot, so get rid of it shape.dispose();
* }
*
* @Override public void render() {
*
*
* world.step(Gdx.graphics.getDeltaTime(), 6, 2);
*
* // Now update the spritee position accordingly to it's now updated
* sprite.setPosition(body.getPosition().x, body.getPosition().y);
*
* // You know the rest... Gdx.gl.glClearColor(1, 1, 1, 1);
* Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); batch.draw(sprite,
* sprite.getX(), sprite.getY()); batch.end(); }
*
* @Override public void dispose() { // Hey, I actually did some clean up in a
* code sample! img.dispose(); world.dispose(); } }
*/ | 2,162 | 0.676226 | 0.6642 | 65 | 32.276924 | 28.777399 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.830769 | false | false | 10 |
b8b85da9748cd4f19ea346e10194525bcff951cc | 13,932,873,972,859 | 2568d72acaa8888fadbc554de68e2835878ab697 | /imports/JOtransform.java | fcdeab5b875a9127a1d3350ec61433c992866ad3 | []
| no_license | monterhumr/Estructura-de-Datos-Geany | https://github.com/monterhumr/Estructura-de-Datos-Geany | 2bc898926d98e07bac4e1b518c566bd205b73d47 | 467a42e7c04bb9d4ae1d08b54f7b50cfab0b4f0d | refs/heads/master | 2021-01-23T13:30:47.767000 | 2017-03-24T18:36:31 | 2017-03-24T18:36:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package imports;
import javax.swing.JOptionPane;
public class JOtransform<E> implements JoptionTrans<E> {
private String read="";
private int disp=0;
public String inputStr_JO(String data){
return JOptionPane.showInputDialog(null , data);
}
public int inputInt_JO(String data){
read=JOptionPane.showInputDialog(null , data);
disp=Integer.parseInt(read);
return disp;
}
public void msg_JO(String message){
JOptionPane.showMessageDialog(null, message);
}
}
| UTF-8 | Java | 485 | java | JOtransform.java | Java | []
| null | []
| package imports;
import javax.swing.JOptionPane;
public class JOtransform<E> implements JoptionTrans<E> {
private String read="";
private int disp=0;
public String inputStr_JO(String data){
return JOptionPane.showInputDialog(null , data);
}
public int inputInt_JO(String data){
read=JOptionPane.showInputDialog(null , data);
disp=Integer.parseInt(read);
return disp;
}
public void msg_JO(String message){
JOptionPane.showMessageDialog(null, message);
}
}
| 485 | 0.738144 | 0.736082 | 24 | 19.208334 | 19.220169 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.458333 | false | false | 4 |
f171198b0a855d7764b93ca04075f35296ce1f58 | 28,819,230,612,471 | d327a8a9ee12e2b26fa727d73905117f04cda864 | /jobhub/src/main/java/com/packt/pfextensions/util/CustomExporterFactory.java | 169fa532e0f39e8ed49e3295aba92176baa4c6ef | []
| no_license | sudheerj/Learning-Primefaces-Extension-Development | https://github.com/sudheerj/Learning-Primefaces-Extension-Development | 6493d90de23ede0710ae7667964fb58513f5a1b1 | c98fd181e634d1664acd7ba99c0a26ec6b7fa7bd | refs/heads/master | 2020-06-09T02:34:35.121000 | 2014-03-18T16:49:06 | 2014-03-18T16:49:06 | 15,344,574 | 7 | 7 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.packt.pfextensions.util;
import javax.el.ELContext;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import org.primefaces.extensions.component.exporter.*;
import com.packt.pfextensions.controller.ExporterController;
public class CustomExporterFactory implements ExporterFactory {
static public enum ExporterType {
PDF,
XLSX
}
public Exporter getExporterForType(String type) {
Exporter exporter = null;
FacesContext context = FacesContext.getCurrentInstance();
ExporterController bean = (ExporterController) context.getApplication().evaluateExpressionGet(context, "#{exporterController}", ExporterController.class);
Boolean customExport=bean.getCustomExporter();
try {
ExporterType exporterType = ExporterType.valueOf(type.toUpperCase());
switch (exporterType) {
case PDF:
if(customExport) {
exporter = new PDFCustomExporter();
}
else {
exporter = new PDFExporter();
}
break;
case XLSX:
if(customExport) {
exporter = new ExcelCustomExporter();
}
else {
exporter = new ExcelExporter();
}
break;
default: {
if(customExport) {
exporter = new PDFCustomExporter();
}
else {
exporter = new PDFExporter();
}
break;
}
}
} catch (IllegalArgumentException e) {
throw new FacesException(e);
}
return exporter;
}
} | UTF-8 | Java | 1,973 | java | CustomExporterFactory.java | Java | []
| null | []
| package com.packt.pfextensions.util;
import javax.el.ELContext;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import org.primefaces.extensions.component.exporter.*;
import com.packt.pfextensions.controller.ExporterController;
public class CustomExporterFactory implements ExporterFactory {
static public enum ExporterType {
PDF,
XLSX
}
public Exporter getExporterForType(String type) {
Exporter exporter = null;
FacesContext context = FacesContext.getCurrentInstance();
ExporterController bean = (ExporterController) context.getApplication().evaluateExpressionGet(context, "#{exporterController}", ExporterController.class);
Boolean customExport=bean.getCustomExporter();
try {
ExporterType exporterType = ExporterType.valueOf(type.toUpperCase());
switch (exporterType) {
case PDF:
if(customExport) {
exporter = new PDFCustomExporter();
}
else {
exporter = new PDFExporter();
}
break;
case XLSX:
if(customExport) {
exporter = new ExcelCustomExporter();
}
else {
exporter = new ExcelExporter();
}
break;
default: {
if(customExport) {
exporter = new PDFCustomExporter();
}
else {
exporter = new PDFExporter();
}
break;
}
}
} catch (IllegalArgumentException e) {
throw new FacesException(e);
}
return exporter;
}
} | 1,973 | 0.497719 | 0.497719 | 69 | 26.623188 | 26.858784 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.362319 | false | false | 4 |
ff0adeaa3c7be3390df73972acf2b41216f851e5 | 30,837,865,251,977 | c4bd8dbc08c505ad2c0925110cba504b44fdbda2 | /src/main/java/com/github/mitrakumarsujan/datastorageservice/service/file/csv/CsvFileSystemFormResponseStorageStrategy.java | 9027c57c7cd8363fb79b25422b48c753c276a632 | []
| no_license | SujanKumarMitra/survey-app-data-storage-service | https://github.com/SujanKumarMitra/survey-app-data-storage-service | 0dc890eb8ffb6e41a00f890c8bba652e823179b6 | fdf93c71e9894aa78f7ce0214f7b33a1cb36a0c1 | refs/heads/master | 2023-02-04T21:21:37.279000 | 2020-12-26T02:41:51 | 2020-12-26T02:41:51 | 314,949,636 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.mitrakumarsujan.datastorageservice.service.file.csv;
import com.github.mitrakumarsujan.datastorageservice.service.FormResponseRowMapper;
import com.github.mitrakumarsujan.datastorageservice.service.FormResponseStorageService;
import com.github.mitrakumarsujan.datastorageservice.service.FormTemplateHeaderMapper;
import com.github.mitrakumarsujan.datastorageservice.service.file.FileWriterService;
import com.github.mitrakumarsujan.datastorageservice.service.file.FormResponseFileManager;
import com.github.mitrakumarsujan.formmodel.exception.FormNotFoundException;
import com.github.mitrakumarsujan.formmodel.model.form.Form;
import com.github.mitrakumarsujan.formmodel.model.form.FormTemplate;
import com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponse;
import com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponseCollection;
import com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponseCollectionImpl;
import com.github.mitrakumarsujan.formmodel.model.formresponse.ResponseConstants;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toCollection;
/**
* @author Sujan Kumar Mitra
* @since 2020-10-29
*/
@Service("csv-response-storage")
@ConditionalOnProperty(prefix = "app", name = "storage-strategy", havingValue = "file")
public class CsvFileSystemFormResponseStorageStrategy implements FormResponseStorageService {
@Autowired
private FormTemplateHeaderMapper headerMapper;
@Autowired
private FormResponseRowMapper rowMapper;
@Autowired
@Qualifier("csv-response-manager")
private FormResponseFileManager fileManager;
@Autowired
private FileWriterService fileWriter;
private static final Logger LOGGER = LoggerFactory.getLogger(CsvFileSystemFormResponseStorageStrategy.class);
private static final String NEW_LINE = System.lineSeparator();
@Override
public FormResponse save(FormResponse response) {
CharSequence data = prepareWritableData(response);
File file = fileManager.getFile(response.getFormId());
fileWriter.appendData(data, file);
LOGGER.info("response written to file '{}'", file.getAbsolutePath());
return response;
}
private CharSequence prepareWritableData(FormResponse response) {
LocalDateTime timestamp = response.getTimestamp();
List<String> responses = rowMapper.apply(response.getResponses());
responses.add(0, timestamp.toString());
return getWritableData(responses);
}
@Override
public void initFormResponseStorage(Form form) {
FormTemplate template = form.getTemplate();
List<String> headers = headerMapper.apply(template);
headers.add(0, "Timestamp");
CharSequence data = getWritableData(headers);
String formId = form.getId();
fileManager.createFile(formId);
File file = fileManager.getFile(formId);
fileWriter.appendData(data, file);
LOGGER.info("response storage initiated for formId '{}'", formId);
}
private CharSequence getWritableData(List<String> data) {
return data .stream()
.collect(joining(","));
}
@Override
public FormResponseCollection getResponses(String formId) throws FormNotFoundException {
File file = fileManager.getFile(formId);
CSVFormat format = CSVFormat.RFC4180
.withFirstRecordAsHeader()
.withNullString(ResponseConstants.DEFAULT_VALUE)
.withTrim();
try (CSVParser parser = format.parse(new FileReader(file))) {
FormResponseCollectionImpl responseCollection = new FormResponseCollectionImpl();
responseCollection.setFormId(formId);
List<String> headers = parser.getHeaderNames();
responseCollection.setQuestions(headers);
List<List<String>> responses = parser .getRecords()
.stream()
.sequential()
.map(record -> parseRecord(record, headers))
.collect(toCollection(LinkedList::new));
responseCollection.setResponses(responses);
return responseCollection;
} catch (IOException e) {
throw new FormNotFoundException(formId);
}
}
private List<String> parseRecord(CSVRecord record, List<String> headers) {
List<String> response = new LinkedList<>();
for (String header : headers) {
String cell = record.get(header);
response.add(cell);
}
return response;
}
}
| UTF-8 | Java | 4,976 | java | CsvFileSystemFormResponseStorageStrategy.java | Java | [
{
"context": "ce.service.file.csv;\r\n\r\nimport com.github.mitrakumarsujan.datastorageservice.service.FormResponseRowMap",
"end": 104,
"score": 0.5221109986305237,
"start": 101,
"tag": "USERNAME",
"value": "ars"
},
{
"context": "e.FormResponseRowMapper;\r\nimport com.github.mitrakumarsujan.datastorageservice.service.FormResponseStorageS",
"end": 191,
"score": 0.5930061936378479,
"start": 184,
"tag": "USERNAME",
"value": "umarsuj"
},
{
"context": "ce.FormResponseStorageService;\r\nimport com.github.mitrakumarsujan.datastorageservice.service.FormTemplateHeaderMapp",
"end": 283,
"score": 0.8695947527885437,
"start": 268,
"tag": "USERNAME",
"value": "mitrakumarsujan"
},
{
"context": "vice.FormTemplateHeaderMapper;\r\nimport com.github.mitrakumarsujan.datastorageservice.service.file.FileWriterService",
"end": 371,
"score": 0.9456265568733215,
"start": 356,
"tag": "USERNAME",
"value": "mitrakumarsujan"
},
{
"context": "ervice.file.FileWriterService;\r\nimport com.github.mitrakumarsujan.datastorageservice.service.file.FormResponseFileM",
"end": 457,
"score": 0.7311589121818542,
"start": 442,
"tag": "USERNAME",
"value": "mitrakumarsujan"
},
{
"context": "rmResponseFileManager;\r\nimport com.github.mitrakumarsujan.formmodel.exception.FormNotFoundException;\r\ni",
"end": 545,
"score": 0.5064190626144409,
"start": 542,
"tag": "USERNAME",
"value": "ars"
},
{
"context": "jan.formmodel.model.form.Form;\r\nimport com.github.mitrakumarsujan.formmodel.model.form.FormTemplate;\r\nimport com.",
"end": 687,
"score": 0.5960779190063477,
"start": 674,
"tag": "USERNAME",
"value": "mitrakumarsuj"
},
{
"context": "model.model.form.FormTemplate;\r\nimport com.github.mitrakumarsujan.formmodel.model.formresponse.FormResp",
"end": 747,
"score": 0.5274141430854797,
"start": 744,
"tag": "USERNAME",
"value": "mit"
},
{
"context": "del.form.FormTemplate;\r\nimport com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponse;\r\nimp",
"end": 757,
"score": 0.6019078493118286,
"start": 752,
"tag": "USERNAME",
"value": "arsuj"
},
{
"context": "response.FormResponse;\r\nimport com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponseCollec",
"end": 835,
"score": 0.567722499370575,
"start": 830,
"tag": "USERNAME",
"value": "arsuj"
},
{
"context": "stream.Collectors.toCollection;\r\n\r\n/**\r\n * @author Sujan Kumar Mitra\r\n * @since 2020-10-29\r\n */\r\n@Service(\"csv-respons",
"end": 1822,
"score": 0.9998448491096497,
"start": 1805,
"tag": "NAME",
"value": "Sujan Kumar Mitra"
}
]
| null | []
| package com.github.mitrakumarsujan.datastorageservice.service.file.csv;
import com.github.mitrakumarsujan.datastorageservice.service.FormResponseRowMapper;
import com.github.mitrakumarsujan.datastorageservice.service.FormResponseStorageService;
import com.github.mitrakumarsujan.datastorageservice.service.FormTemplateHeaderMapper;
import com.github.mitrakumarsujan.datastorageservice.service.file.FileWriterService;
import com.github.mitrakumarsujan.datastorageservice.service.file.FormResponseFileManager;
import com.github.mitrakumarsujan.formmodel.exception.FormNotFoundException;
import com.github.mitrakumarsujan.formmodel.model.form.Form;
import com.github.mitrakumarsujan.formmodel.model.form.FormTemplate;
import com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponse;
import com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponseCollection;
import com.github.mitrakumarsujan.formmodel.model.formresponse.FormResponseCollectionImpl;
import com.github.mitrakumarsujan.formmodel.model.formresponse.ResponseConstants;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toCollection;
/**
* @author <NAME>
* @since 2020-10-29
*/
@Service("csv-response-storage")
@ConditionalOnProperty(prefix = "app", name = "storage-strategy", havingValue = "file")
public class CsvFileSystemFormResponseStorageStrategy implements FormResponseStorageService {
@Autowired
private FormTemplateHeaderMapper headerMapper;
@Autowired
private FormResponseRowMapper rowMapper;
@Autowired
@Qualifier("csv-response-manager")
private FormResponseFileManager fileManager;
@Autowired
private FileWriterService fileWriter;
private static final Logger LOGGER = LoggerFactory.getLogger(CsvFileSystemFormResponseStorageStrategy.class);
private static final String NEW_LINE = System.lineSeparator();
@Override
public FormResponse save(FormResponse response) {
CharSequence data = prepareWritableData(response);
File file = fileManager.getFile(response.getFormId());
fileWriter.appendData(data, file);
LOGGER.info("response written to file '{}'", file.getAbsolutePath());
return response;
}
private CharSequence prepareWritableData(FormResponse response) {
LocalDateTime timestamp = response.getTimestamp();
List<String> responses = rowMapper.apply(response.getResponses());
responses.add(0, timestamp.toString());
return getWritableData(responses);
}
@Override
public void initFormResponseStorage(Form form) {
FormTemplate template = form.getTemplate();
List<String> headers = headerMapper.apply(template);
headers.add(0, "Timestamp");
CharSequence data = getWritableData(headers);
String formId = form.getId();
fileManager.createFile(formId);
File file = fileManager.getFile(formId);
fileWriter.appendData(data, file);
LOGGER.info("response storage initiated for formId '{}'", formId);
}
private CharSequence getWritableData(List<String> data) {
return data .stream()
.collect(joining(","));
}
@Override
public FormResponseCollection getResponses(String formId) throws FormNotFoundException {
File file = fileManager.getFile(formId);
CSVFormat format = CSVFormat.RFC4180
.withFirstRecordAsHeader()
.withNullString(ResponseConstants.DEFAULT_VALUE)
.withTrim();
try (CSVParser parser = format.parse(new FileReader(file))) {
FormResponseCollectionImpl responseCollection = new FormResponseCollectionImpl();
responseCollection.setFormId(formId);
List<String> headers = parser.getHeaderNames();
responseCollection.setQuestions(headers);
List<List<String>> responses = parser .getRecords()
.stream()
.sequential()
.map(record -> parseRecord(record, headers))
.collect(toCollection(LinkedList::new));
responseCollection.setResponses(responses);
return responseCollection;
} catch (IOException e) {
throw new FormNotFoundException(formId);
}
}
private List<String> parseRecord(CSVRecord record, List<String> headers) {
List<String> response = new LinkedList<>();
for (String header : headers) {
String cell = record.get(header);
response.add(cell);
}
return response;
}
}
| 4,965 | 0.767283 | 0.764068 | 139 | 33.798561 | 28.778784 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 4 |
ce3e20f0999de49a139a03b4043c8fbc74636613 | 13,383,118,102,091 | 4dc627bc19ea9574f84425021ddeb0e189a33b7f | /course/src/main/java/com/haobaoshui/course/service/course/impl/CourseStyleServiceImpl.java | b44c5ced7c9124e63d5843b83623fc2de11039ef | [
"MIT"
]
| permissive | Haobaoshui/course | https://github.com/Haobaoshui/course | b34037377d96ade25be34f572ab39ddc760d7c1e | 46b52ad44974a0b9a1e654484ff05450d7fcbf53 | refs/heads/master | 2020-04-16T23:41:12.217000 | 2020-04-12T15:39:01 | 2020-04-12T15:39:01 | 41,492,859 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.haobaoshui.course.service.course.impl;
import com.haobaoshui.course.model.Page;
import com.haobaoshui.course.model.course.CourseStyle;
import com.haobaoshui.course.repository.course.CourseStyleRepository;
import com.haobaoshui.course.service.course.CourseStyleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CourseStyleServiceImpl implements CourseStyleService {
private final CourseStyleRepository courseStyleRepository;
@Autowired
public CourseStyleServiceImpl(CourseStyleRepository courseStyleRepository) {
this.courseStyleRepository = courseStyleRepository;
}
@Override
public String add(CourseStyle courseStyle) {
return courseStyleRepository.add(courseStyle);
}
@Override
public String add(String name, String note) {
return courseStyleRepository.add(name, note);
}
@Override
public int deleteById(String id) {
return courseStyleRepository.deleteById(id);
}
@Override
public int delete(CourseStyle courseStyle) {
if (courseStyle == null) return 0;
return deleteById(courseStyle.getId());
}
@Override
public int deleteAll() {
return courseStyleRepository.deleteAll();
}
@Override
public int update(String id, String name, String note) {
return courseStyleRepository.update(id, name, note);
}
@Override
public int update(CourseStyle courseStyle) {
return courseStyleRepository.update(courseStyle);
}
@Override
public int getCount() {
return courseStyleRepository.getCount();
}
@Override
public List<CourseStyle> getAllByLikeName(String name) {
return courseStyleRepository.getAllByLikeName(name);
}
@Override
public CourseStyle getByName(String name) {
return courseStyleRepository.getByName(name);
}
@Override
public CourseStyle getByID(String id) {
return courseStyleRepository.getByID(id);
}
@Override
public List<CourseStyle> getAll() {
return courseStyleRepository.getAll();
}
@Override
public Page<CourseStyle> getPage(int pageNo, int pageSize) {
return courseStyleRepository.getPage(pageNo, pageSize);
}
@Override
public Page<CourseStyle> getAllPage() {
return courseStyleRepository.getAllPage();
}
@Override
public Page<CourseStyle> getPageByLikeName(String name, int pageNo, int pageSize) {
return courseStyleRepository.getPageByLikeName(name, pageNo, pageSize);
}
}
| UTF-8 | Java | 2,663 | java | CourseStyleServiceImpl.java | Java | []
| null | []
| package com.haobaoshui.course.service.course.impl;
import com.haobaoshui.course.model.Page;
import com.haobaoshui.course.model.course.CourseStyle;
import com.haobaoshui.course.repository.course.CourseStyleRepository;
import com.haobaoshui.course.service.course.CourseStyleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CourseStyleServiceImpl implements CourseStyleService {
private final CourseStyleRepository courseStyleRepository;
@Autowired
public CourseStyleServiceImpl(CourseStyleRepository courseStyleRepository) {
this.courseStyleRepository = courseStyleRepository;
}
@Override
public String add(CourseStyle courseStyle) {
return courseStyleRepository.add(courseStyle);
}
@Override
public String add(String name, String note) {
return courseStyleRepository.add(name, note);
}
@Override
public int deleteById(String id) {
return courseStyleRepository.deleteById(id);
}
@Override
public int delete(CourseStyle courseStyle) {
if (courseStyle == null) return 0;
return deleteById(courseStyle.getId());
}
@Override
public int deleteAll() {
return courseStyleRepository.deleteAll();
}
@Override
public int update(String id, String name, String note) {
return courseStyleRepository.update(id, name, note);
}
@Override
public int update(CourseStyle courseStyle) {
return courseStyleRepository.update(courseStyle);
}
@Override
public int getCount() {
return courseStyleRepository.getCount();
}
@Override
public List<CourseStyle> getAllByLikeName(String name) {
return courseStyleRepository.getAllByLikeName(name);
}
@Override
public CourseStyle getByName(String name) {
return courseStyleRepository.getByName(name);
}
@Override
public CourseStyle getByID(String id) {
return courseStyleRepository.getByID(id);
}
@Override
public List<CourseStyle> getAll() {
return courseStyleRepository.getAll();
}
@Override
public Page<CourseStyle> getPage(int pageNo, int pageSize) {
return courseStyleRepository.getPage(pageNo, pageSize);
}
@Override
public Page<CourseStyle> getAllPage() {
return courseStyleRepository.getAllPage();
}
@Override
public Page<CourseStyle> getPageByLikeName(String name, int pageNo, int pageSize) {
return courseStyleRepository.getPageByLikeName(name, pageNo, pageSize);
}
}
| 2,663 | 0.71273 | 0.712354 | 100 | 25.629999 | 25.311127 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.38 | false | false | 4 |
c6bf9e4c9fc6e185c23a120455b5dbe5d00c4e6e | 26,156,350,856,960 | e55f27c2b9b17d0f739fec4a5aeb307cd663836b | /Application/cheese-coin-system/src/ui/RegisterUser.java | 003aac19adf19f8b0e7f362a2b1dede5cba8d91f | []
| no_license | dhayanth-dharma/cheese-coin | https://github.com/dhayanth-dharma/cheese-coin | 18007ee7c156b5beba90628ace362038314dc01d | 30073e2575f117b1da7405aa7556c70de5e782ec | refs/heads/master | 2022-04-25T04:21:43.818000 | 2020-04-23T08:14:12 | 2020-04-23T08:14:12 | 258,137,097 | 0 | 0 | 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 UI;
import AsymmetricEn.GenerateKeys;
import Model.Account_M;
import Model.User_M;
import dataAccess.Account_DAO;
import dataAccess.User_DAO;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.bind.DatatypeConverter;
/**
*
* @author user
*/
public class RegisterUser extends javax.swing.JFrame {
/**
* Creates new form RegisterUser
*/
public RegisterUser() {
initComponents();
}
/**
* 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() {
btnRegister = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnRegister.setText("Register");
btnRegister.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegisterActionPerformed(evt);
}
});
btnClose.setText("Close");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
jLabel1.setText("User Name");
txtUserName.setText("user name");
jLabel2.setText("Password");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(66, 66, 66)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(141, 141, 141)
.addComponent(btnRegister)
.addGap(18, 18, 18)
.addComponent(btnClose)))
.addContainerGap(90, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRegister)
.addComponent(btnClose))
.addGap(20, 20, 20))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegisterActionPerformed
try {
String username=txtUserName.getText();
String password=txtPassword.getText();
if(!username.equals(null) && !password.equals(null))
{
User_M user=new User_M();
user.setUser_name(username);
user.setPassword(password);
user.setUser_type("user");
User_DAO userDAO=new User_DAO();
user=userDAO.createAndGet(user);
if(user!=null)
{
Account_DAO acntDao=new Account_DAO();
Account_M lastID=acntDao.getLastAcount();
HashMap<String,String> keys=getKeys();
Account_M account=new Account_M();
account.setUser_id(user.getUse_id());
account.setPublic_key(keys.get("public"));
account.setPrivate_key(keys.get("private"));
account.setAccount_number(lastID.getAccount_number()+1);
account.setBalance(0);
acntDao.create(account);
JOptionPane.showMessageDialog(this, "Registration Successfull");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter user name and password");
}
} catch (Exception ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnRegisterActionPerformed
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_btnCloseActionPerformed
public HashMap<String,String> getKeys()
{
try {
GenerateKeys myKeys = new GenerateKeys(1024);
myKeys.createKeys();
PublicKey pubKey=myKeys.getPublicKey();
PrivateKey priKey=myKeys.getPrivateKey();
String publicKeyString = org.apache.commons.codec.binary.Base64.encodeBase64String(pubKey.getEncoded());
String priKeyString = org.apache.commons.codec.binary.Base64.encodeBase64String(priKey.getEncoded());
HashMap<String,String> keys=new HashMap<String,String>();
keys.put("private", priKeyString);
keys.put("public", publicKeyString);
return keys;
} catch (Exception ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RegisterUser().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClose;
private javax.swing.JButton btnRegister;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 9,897 | java | RegisterUser.java | Java | [
{
"context": "vax.xml.bind.DatatypeConverter;\n\n/**\n *\n * @author user\n */\npublic class RegisterUser extends javax.swing",
"end": 784,
"score": 0.9988308548927307,
"start": 780,
"tag": "USERNAME",
"value": "user"
},
{
"context": " }\n });\n\n jLabel1.setText(\"User Name\");\n\n txtUserName.setText(\"user name\");\n\n ",
"end": 2261,
"score": 0.9968724250793457,
"start": 2252,
"tag": "NAME",
"value": "User Name"
},
{
"context": "tText(\"User Name\");\n\n txtUserName.setText(\"user name\");\n\n jLabel2.setText(\"Password\");\n\n ",
"end": 2304,
"score": 0.9984758496284485,
"start": 2295,
"tag": "USERNAME",
"value": "user name"
},
{
"context": "e.setText(\"user name\");\n\n jLabel2.setText(\"Password\");\n\n javax.swing.GroupLayout layout = new ",
"end": 2342,
"score": 0.8740745186805725,
"start": 2334,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": " user=new User_M();\n user.setUser_name(username);\n user.setPassword(password);\n ",
"end": 5483,
"score": 0.9912009835243225,
"start": 5475,
"tag": "USERNAME",
"value": "username"
},
{
"context": "User_name(username);\n user.setPassword(password);\n user.setUser_type(\"user\");\n ",
"end": 5523,
"score": 0.9978197813034058,
"start": 5515,
"tag": "PASSWORD",
"value": "password"
}
]
| 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 UI;
import AsymmetricEn.GenerateKeys;
import Model.Account_M;
import Model.User_M;
import dataAccess.Account_DAO;
import dataAccess.User_DAO;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.bind.DatatypeConverter;
/**
*
* @author user
*/
public class RegisterUser extends javax.swing.JFrame {
/**
* Creates new form RegisterUser
*/
public RegisterUser() {
initComponents();
}
/**
* 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() {
btnRegister = new javax.swing.JButton();
btnClose = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnRegister.setText("Register");
btnRegister.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegisterActionPerformed(evt);
}
});
btnClose.setText("Close");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
jLabel1.setText("<NAME>");
txtUserName.setText("user name");
jLabel2.setText("<PASSWORD>");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(66, 66, 66)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(141, 141, 141)
.addComponent(btnRegister)
.addGap(18, 18, 18)
.addComponent(btnClose)))
.addContainerGap(90, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRegister)
.addComponent(btnClose))
.addGap(20, 20, 20))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegisterActionPerformed
try {
String username=txtUserName.getText();
String password=txtPassword.getText();
if(!username.equals(null) && !password.equals(null))
{
User_M user=new User_M();
user.setUser_name(username);
user.setPassword(<PASSWORD>);
user.setUser_type("user");
User_DAO userDAO=new User_DAO();
user=userDAO.createAndGet(user);
if(user!=null)
{
Account_DAO acntDao=new Account_DAO();
Account_M lastID=acntDao.getLastAcount();
HashMap<String,String> keys=getKeys();
Account_M account=new Account_M();
account.setUser_id(user.getUse_id());
account.setPublic_key(keys.get("public"));
account.setPrivate_key(keys.get("private"));
account.setAccount_number(lastID.getAccount_number()+1);
account.setBalance(0);
acntDao.create(account);
JOptionPane.showMessageDialog(this, "Registration Successfull");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter user name and password");
}
} catch (Exception ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnRegisterActionPerformed
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_btnCloseActionPerformed
public HashMap<String,String> getKeys()
{
try {
GenerateKeys myKeys = new GenerateKeys(1024);
myKeys.createKeys();
PublicKey pubKey=myKeys.getPublicKey();
PrivateKey priKey=myKeys.getPrivateKey();
String publicKeyString = org.apache.commons.codec.binary.Base64.encodeBase64String(pubKey.getEncoded());
String priKeyString = org.apache.commons.codec.binary.Base64.encodeBase64String(priKey.getEncoded());
HashMap<String,String> keys=new HashMap<String,String>();
keys.put("private", priKeyString);
keys.put("public", publicKeyString);
return keys;
} catch (Exception ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegisterUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RegisterUser().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClose;
private javax.swing.JButton btnRegister;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration//GEN-END:variables
}
| 9,898 | 0.62716 | 0.618874 | 225 | 42.986668 | 34.086098 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631111 | false | false | 4 |
02982784dbf05c3d78c73648fdaef3d9a9a475f4 | 13,846,974,596,977 | a306a17af40ac4df16d3e2b257bca36f83448faf | /src/java/Model/Livro.java | c0779d48bbec50cef36f4d953d2628807a5ee76d | []
| no_license | Marlonrsp/TCC-Projeto-Integrador-Biblioteca | https://github.com/Marlonrsp/TCC-Projeto-Integrador-Biblioteca | 531388b2ccf169f8c034f9936961c49d75729c7b | 79e07a40711fac19190f899c6cf1d3ea8802f688 | refs/heads/master | 2022-11-10T05:19:47.882000 | 2020-06-19T13:25:52 | 2020-06-19T13:25:52 | 273,498,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Model;
public class Livro {
private int id_livro;
private String titulo_livro;
private String autor_livro;
private String editora_livro;
private String genero_livro;
private int numPaginas;
private boolean status;
public int getId_livro() {
return id_livro;
}
public void setId_livro(int id_livro) {
this.id_livro = id_livro;
}
public String getTitulo_livro() {
return titulo_livro;
}
public void setTitulo_livro(String titulo_livro) {
this.titulo_livro = titulo_livro;
}
public String getAutor_livro() {
return autor_livro;
}
public void setAutor_livro(String autor_livro) {
this.autor_livro = autor_livro;
}
public String getEditora_livro() {
return editora_livro;
}
public void setEditora_livro(String editora_livro) {
this.editora_livro = editora_livro;
}
public String getGenero_livro() {
return genero_livro;
}
public void setGenero_livro(String categoria_livro) {
this.genero_livro = categoria_livro;
}
public int getNumPaginas() {
return numPaginas;
}
public void setNum_paginas(int num_paginas) {
this.numPaginas = num_paginas;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public void verificarDisponibilidade() {
if (status) {
System.out.println("Livro Disponivel");
} else {
System.out.println("Livro Indisponível!");
}
}
}
| UTF-8 | Java | 1,723 | java | Livro.java | Java | []
| null | []
| package Model;
public class Livro {
private int id_livro;
private String titulo_livro;
private String autor_livro;
private String editora_livro;
private String genero_livro;
private int numPaginas;
private boolean status;
public int getId_livro() {
return id_livro;
}
public void setId_livro(int id_livro) {
this.id_livro = id_livro;
}
public String getTitulo_livro() {
return titulo_livro;
}
public void setTitulo_livro(String titulo_livro) {
this.titulo_livro = titulo_livro;
}
public String getAutor_livro() {
return autor_livro;
}
public void setAutor_livro(String autor_livro) {
this.autor_livro = autor_livro;
}
public String getEditora_livro() {
return editora_livro;
}
public void setEditora_livro(String editora_livro) {
this.editora_livro = editora_livro;
}
public String getGenero_livro() {
return genero_livro;
}
public void setGenero_livro(String categoria_livro) {
this.genero_livro = categoria_livro;
}
public int getNumPaginas() {
return numPaginas;
}
public void setNum_paginas(int num_paginas) {
this.numPaginas = num_paginas;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public void verificarDisponibilidade() {
if (status) {
System.out.println("Livro Disponivel");
} else {
System.out.println("Livro Indisponível!");
}
}
}
| 1,723 | 0.578397 | 0.578397 | 78 | 20.076923 | 18.143848 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 4 |
78e3cbf8d7672eabe90fdf50aa24201791f20233 | 19,550,691,133,671 | f3417ec1dd48ab52aab275ac1f052cd4b316000b | /Testing/OldTests/JetTest.java | 3f155a3998be933174092880cd1cc3018ab9de9b | [
"MIT"
]
| permissive | MathOnco/HAL | https://github.com/MathOnco/HAL | b96fd3a11015851a32379d8092fdd896a1cd139f | 2627926a59f67bbbab30822faaee898dda6660f8 | refs/heads/master | 2023-07-09T14:11:15.622000 | 2023-06-26T19:33:58 | 2023-06-26T19:33:58 | 162,158,973 | 31 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Testing.OldTests;
import HAL.Gui.GridWindow;
import static HAL.Util.HeatMapJet;
import static HAL.Util.HeatMapParula;
public class JetTest {
public static void main(String[] args) {
GridWindow win=new GridWindow(100,20,10);
for (int i = 0; i < win.xDim; i++) {
for (int j = 0; j < win.yDim; j++) {
//win.SetPix(i, j, HeatMapJet(i, 0, win.xDim-1));
win.SetPix(i, j, HeatMapParula(i, 0, win.xDim-1));
}
}
}
}
| UTF-8 | Java | 506 | java | JetTest.java | Java | []
| null | []
| package Testing.OldTests;
import HAL.Gui.GridWindow;
import static HAL.Util.HeatMapJet;
import static HAL.Util.HeatMapParula;
public class JetTest {
public static void main(String[] args) {
GridWindow win=new GridWindow(100,20,10);
for (int i = 0; i < win.xDim; i++) {
for (int j = 0; j < win.yDim; j++) {
//win.SetPix(i, j, HeatMapJet(i, 0, win.xDim-1));
win.SetPix(i, j, HeatMapParula(i, 0, win.xDim-1));
}
}
}
}
| 506 | 0.563241 | 0.537549 | 18 | 27.111111 | 21.74828 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 4 |
1698a55b0dfff69de58bf4325b2cbdb79adcacb7 | 721,554,517,987 | 47d9d2cba6ab46a59f08b9d3089fc1e68cf6d581 | /src/test/java/com/hzh/o2o/dao/ProductDaoTest.java | 706b13b0c7d3ce3fe7ede9e16cd3655f1c7e2eb9 | []
| no_license | Hongzenghong/o2o | https://github.com/Hongzenghong/o2o | e8bcf4f1cc7016132116e799a1c925bdb48fc539 | 4cc0143d8624c2533e51ba08755778e92e7b49e0 | refs/heads/master | 2020-04-19T09:15:28.255000 | 2019-02-18T16:22:02 | 2019-02-18T16:22:02 | 168,104,497 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hzh.o2o.dao;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import com.hzh.o2o.BaseTest;
import com.hzh.o2o.entity.Product;
import com.hzh.o2o.entity.ProductCategory;
import com.hzh.o2o.entity.ProductImg;
import com.hzh.o2o.entity.Shop;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ProductDaoTest extends BaseTest {
@Autowired
ProductDao productDao;
@Autowired
ProductImgDao productImgDao;
@Test
@Ignore
public void testAInsertProdcut() {
// 注意表中的外键关系,确保这些数据在对应的表中的存在
ProductCategory productCategory = new ProductCategory();
productCategory.setProductCategoryId(1L);
// 注意表中的外键关系,确保这些数据在对应的表中的存在
Shop shop = new Shop();
shop.setShopId(1L);
Product product = new Product();
product.setProductName("糖果");
product.setProductDesc("product desc");
product.setImgAddr("/aaa/bbb");
product.setNormalPrice("10");
product.setPromotionPrice("8");
product.setPriority(66);
product.setCreateTime(new Date());
product.setLastEditTime(new Date());
product.setEnableStatus(1);
product.setProductCategory(productCategory);
product.setShop(shop);
int effectNum = productDao.insertProduct(product);
System.out.println(effectNum);
}
@Test
public void testBQueryProductList() throws Exception {
Shop shop = new Shop();
shop.setShopId(1L);
Product productCondition = new Product();
productCondition.setShop(shop);
productCondition.setProductName("糖果");
List<Product> productList = productDao.queryProductList(productCondition, 0, 2);
assertEquals(2, productList.size());
// 查询总数
int count = productDao.queryProductCount(productCondition);
assertEquals(2, count);
}
@Test
@Ignore
public void testCQueryProductById() throws Exception {
long productId = 1;
// 初始化两个商品下详情图实例作为productID为1的商品下的详情图片
// 批量插入到商品详情图中
ProductImg productImg1 = new ProductImg();
productImg1.setImgAddr("图片1");
productImg1.setImgDesc("测试图片1");
productImg1.setPriority(1);
productImg1.setCreateTime(new Date());
productImg1.setProductId(productId);
ProductImg productImg2 = new ProductImg();
productImg2.setImgAddr("图片2");
productImg2.setImgDesc("测试图片2");
productImg2.setPriority(1);
productImg2.setCreateTime(new Date());
productImg2.setProductId(productId);
List<ProductImg> productImgList = new ArrayList<ProductImg>();
productImgList.add(productImg1);
productImgList.add(productImg2);
int effectedNum = productImgDao.batchInsertProductImg(productImgList);
System.out.println("==================");
assertEquals(2, effectedNum);
// 查询product为1的商品信息并校验返回的详情图实例列表是否为2
Product product = productDao.queryProductById(productId);
assertEquals(2, product.getProductImgList().size());
// 删除新增的这两个商品详情图实例
effectedNum = productImgDao.deleteProductImgByProductId(productId);
assertEquals(2, effectedNum);
System.out.println("===================");
}
@Test
@Ignore
public void testDUpdateProduct() throws Exception {
Product product = new Product();
ProductCategory pc = new ProductCategory();
Shop shop = new Shop();
shop.setShopId(1L);
pc.setProductCategoryId(2L);
product.setProductId(4L);
product.setShop(shop);
product.setProductName("第一个产品");
product.setProductCategory(pc);
// 修改productID为1的商品的名称
// 以及商品类别并校验印象行数是否为1
int effctedNum = productDao.updateProduct(product);
assertEquals(1, effctedNum);
}
@Test
public void testUpdateProductCategoryToNull() {
int effectNum = productDao.updateProductCategoryToNull(5);
assertEquals(1, effectNum);
}
}
| UTF-8 | Java | 4,238 | java | ProductDaoTest.java | Java | []
| null | []
| package com.hzh.o2o.dao;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import com.hzh.o2o.BaseTest;
import com.hzh.o2o.entity.Product;
import com.hzh.o2o.entity.ProductCategory;
import com.hzh.o2o.entity.ProductImg;
import com.hzh.o2o.entity.Shop;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ProductDaoTest extends BaseTest {
@Autowired
ProductDao productDao;
@Autowired
ProductImgDao productImgDao;
@Test
@Ignore
public void testAInsertProdcut() {
// 注意表中的外键关系,确保这些数据在对应的表中的存在
ProductCategory productCategory = new ProductCategory();
productCategory.setProductCategoryId(1L);
// 注意表中的外键关系,确保这些数据在对应的表中的存在
Shop shop = new Shop();
shop.setShopId(1L);
Product product = new Product();
product.setProductName("糖果");
product.setProductDesc("product desc");
product.setImgAddr("/aaa/bbb");
product.setNormalPrice("10");
product.setPromotionPrice("8");
product.setPriority(66);
product.setCreateTime(new Date());
product.setLastEditTime(new Date());
product.setEnableStatus(1);
product.setProductCategory(productCategory);
product.setShop(shop);
int effectNum = productDao.insertProduct(product);
System.out.println(effectNum);
}
@Test
public void testBQueryProductList() throws Exception {
Shop shop = new Shop();
shop.setShopId(1L);
Product productCondition = new Product();
productCondition.setShop(shop);
productCondition.setProductName("糖果");
List<Product> productList = productDao.queryProductList(productCondition, 0, 2);
assertEquals(2, productList.size());
// 查询总数
int count = productDao.queryProductCount(productCondition);
assertEquals(2, count);
}
@Test
@Ignore
public void testCQueryProductById() throws Exception {
long productId = 1;
// 初始化两个商品下详情图实例作为productID为1的商品下的详情图片
// 批量插入到商品详情图中
ProductImg productImg1 = new ProductImg();
productImg1.setImgAddr("图片1");
productImg1.setImgDesc("测试图片1");
productImg1.setPriority(1);
productImg1.setCreateTime(new Date());
productImg1.setProductId(productId);
ProductImg productImg2 = new ProductImg();
productImg2.setImgAddr("图片2");
productImg2.setImgDesc("测试图片2");
productImg2.setPriority(1);
productImg2.setCreateTime(new Date());
productImg2.setProductId(productId);
List<ProductImg> productImgList = new ArrayList<ProductImg>();
productImgList.add(productImg1);
productImgList.add(productImg2);
int effectedNum = productImgDao.batchInsertProductImg(productImgList);
System.out.println("==================");
assertEquals(2, effectedNum);
// 查询product为1的商品信息并校验返回的详情图实例列表是否为2
Product product = productDao.queryProductById(productId);
assertEquals(2, product.getProductImgList().size());
// 删除新增的这两个商品详情图实例
effectedNum = productImgDao.deleteProductImgByProductId(productId);
assertEquals(2, effectedNum);
System.out.println("===================");
}
@Test
@Ignore
public void testDUpdateProduct() throws Exception {
Product product = new Product();
ProductCategory pc = new ProductCategory();
Shop shop = new Shop();
shop.setShopId(1L);
pc.setProductCategoryId(2L);
product.setProductId(4L);
product.setShop(shop);
product.setProductName("第一个产品");
product.setProductCategory(pc);
// 修改productID为1的商品的名称
// 以及商品类别并校验印象行数是否为1
int effctedNum = productDao.updateProduct(product);
assertEquals(1, effctedNum);
}
@Test
public void testUpdateProductCategoryToNull() {
int effectNum = productDao.updateProductCategoryToNull(5);
assertEquals(1, effectNum);
}
}
| 4,238 | 0.733282 | 0.719393 | 129 | 28.139534 | 18.546713 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 4 |
dd0f7011eec0d011cd598ae82c4c3b4e48753173 | 10,642,928,972,488 | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/training/com/hazelcast/internal/nearcache/impl/invalidation/RepairingTaskTest.java | b8fe978324809c2e227b2f6e4ede4dcec0e86cae | []
| no_license | STAMP-project/dspot-experiments | https://github.com/STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919000 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | false | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | 2022-02-18T17:43:31 | 2023-01-26T23:57:40 | 651,434 | 12 | 14 | 5 | null | false | false | /**
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.nearcache.impl.invalidation;
import com.hazelcast.config.Config;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.util.RandomPicker;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastParallelClassRunner.class)
@Category({ QuickTest.class, ParallelTest.class })
public class RepairingTaskTest extends HazelcastTestSupport {
@Test
public void whenToleratedMissCountIsConfigured_thenItShouldBeUsed() {
int maxToleratedMissCount = 123;
Config config = RepairingTaskTest.getConfigWithMaxToleratedMissCount(maxToleratedMissCount);
RepairingTask repairingTask = RepairingTaskTest.newRepairingTask(config);
Assert.assertEquals(maxToleratedMissCount, repairingTask.maxToleratedMissCount);
}
@Test(expected = IllegalArgumentException.class)
public void whenToleratedMissCountIsNegative_thenThrowException() {
Config config = RepairingTaskTest.getConfigWithMaxToleratedMissCount((-1));
RepairingTaskTest.newRepairingTask(config);
}
@Test
public void whenReconciliationIntervalSecondsIsConfigured_thenItShouldBeUsed() {
int reconciliationIntervalSeconds = 91;
Config config = RepairingTaskTest.getConfigWithReconciliationInterval(reconciliationIntervalSeconds);
RepairingTask repairingTask = RepairingTaskTest.newRepairingTask(config);
Assert.assertEquals(reconciliationIntervalSeconds, TimeUnit.NANOSECONDS.toSeconds(repairingTask.reconciliationIntervalNanos));
}
@Test(expected = IllegalArgumentException.class)
public void whenReconciliationIntervalSecondsIsNegative_thenThrowException() {
Config config = RepairingTaskTest.getConfigWithReconciliationInterval((-1));
RepairingTaskTest.newRepairingTask(config);
}
@Test(expected = IllegalArgumentException.class)
public void whenReconciliationIntervalSecondsIsNotZeroButSmallerThanThresholdValue_thenThrowException() {
int thresholdValue = Integer.parseInt(RepairingTask.MIN_RECONCILIATION_INTERVAL_SECONDS.getDefaultValue());
Config config = RepairingTaskTest.getConfigWithReconciliationInterval(RandomPicker.getInt(1, thresholdValue));
RepairingTaskTest.newRepairingTask(config);
}
}
| UTF-8 | Java | 3,186 | java | RepairingTaskTest.java | Java | [
{
"context": "/**\n * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed",
"end": 33,
"score": 0.8098412156105042,
"start": 32,
"tag": "NAME",
"value": "H"
}
]
| null | []
| /**
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.nearcache.impl.invalidation;
import com.hazelcast.config.Config;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.util.RandomPicker;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastParallelClassRunner.class)
@Category({ QuickTest.class, ParallelTest.class })
public class RepairingTaskTest extends HazelcastTestSupport {
@Test
public void whenToleratedMissCountIsConfigured_thenItShouldBeUsed() {
int maxToleratedMissCount = 123;
Config config = RepairingTaskTest.getConfigWithMaxToleratedMissCount(maxToleratedMissCount);
RepairingTask repairingTask = RepairingTaskTest.newRepairingTask(config);
Assert.assertEquals(maxToleratedMissCount, repairingTask.maxToleratedMissCount);
}
@Test(expected = IllegalArgumentException.class)
public void whenToleratedMissCountIsNegative_thenThrowException() {
Config config = RepairingTaskTest.getConfigWithMaxToleratedMissCount((-1));
RepairingTaskTest.newRepairingTask(config);
}
@Test
public void whenReconciliationIntervalSecondsIsConfigured_thenItShouldBeUsed() {
int reconciliationIntervalSeconds = 91;
Config config = RepairingTaskTest.getConfigWithReconciliationInterval(reconciliationIntervalSeconds);
RepairingTask repairingTask = RepairingTaskTest.newRepairingTask(config);
Assert.assertEquals(reconciliationIntervalSeconds, TimeUnit.NANOSECONDS.toSeconds(repairingTask.reconciliationIntervalNanos));
}
@Test(expected = IllegalArgumentException.class)
public void whenReconciliationIntervalSecondsIsNegative_thenThrowException() {
Config config = RepairingTaskTest.getConfigWithReconciliationInterval((-1));
RepairingTaskTest.newRepairingTask(config);
}
@Test(expected = IllegalArgumentException.class)
public void whenReconciliationIntervalSecondsIsNotZeroButSmallerThanThresholdValue_thenThrowException() {
int thresholdValue = Integer.parseInt(RepairingTask.MIN_RECONCILIATION_INTERVAL_SECONDS.getDefaultValue());
Config config = RepairingTaskTest.getConfigWithReconciliationInterval(RandomPicker.getInt(1, thresholdValue));
RepairingTaskTest.newRepairingTask(config);
}
}
| 3,186 | 0.790019 | 0.783741 | 69 | 45.15942 | 35.160347 | 134 | false | false | 0 | 0 | 0 | 0 | 70 | 0.021971 | 0.550725 | false | false | 4 |
272c440f551f01b3eef8ff863c49e78627161bf2 | 12,910,671,725,543 | 459d1bd92d9eaded01f0946c89aa7a9f62848d30 | /wms/src/main/java/org/geoserver/kml/RandomRegionatingStrategy.java | 1f7e40dbcb28cac495e92f1cdc4014c4af2afa7e | []
| no_license | groldan/geoserver_trunk | https://github.com/groldan/geoserver_trunk | 7cb1160cefff03444a3fda186c928a8e6779217a | 2dfb179a149069d0e0b251dab49cefb5294b6f90 | refs/heads/master | 2019-06-16T12:02:04.511000 | 2011-12-03T21:51:51 | 2011-12-03T21:51:51 | 527,962 | 2 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.kml;
import java.sql.Connection;
import org.geoserver.config.GeoServer;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.FeatureIterator;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.filter.FilterFactory;
import org.opengis.filter.spatial.BBOX;
/**
* This strategy just return the features as they come from the db
* and leave the pyramid structure do the rest. Of course is the data is
* inserted in the db in a way that makes it return features in some linear
* way the distribution won't look good. But the same might happen to
* attribute sorting as well, for example, when the high values of the
* sorting attribute do concentrate in a specific area instead of being
* evenly spread out.
* @author Andrea Aime
*/
public class RandomRegionatingStrategy extends
CachedHierarchyRegionatingStrategy {
public RandomRegionatingStrategy(GeoServer gs) {
super(gs);
}
@Override
public FeatureIterator getSortedFeatures(GeometryDescriptor geom,
ReferencedEnvelope latLongEnv, ReferencedEnvelope nativeEnv,
Connection cacheConn) throws Exception {
FeatureSource fs = featureType.getFeatureSource(null, null);
// build the bbox filter
FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
BBOX filter = ff.bbox(geom.getLocalName(), nativeEnv.getMinX(),
nativeEnv.getMinY(), nativeEnv.getMaxX(), nativeEnv.getMaxY(), null);
// build an optimized query (only the necessary attributes
Query q = new Query();
q.setFilter(filter);
// TODO: enable this when JTS learns how to compute centroids
// without triggering the
// generation of Coordinate[] out of the sequences...
// q.setHints(new Hints(Hints.JTS_COORDINATE_SEQUENCE_FACTORY,
// PackedCoordinateSequenceFactory.class));
q.setPropertyNames(new String[] { geom.getLocalName() });
// return the reader
return fs.getFeatures(q).features();
}
}
| UTF-8 | Java | 2,412 | java | RandomRegionatingStrategy.java | Java | [
{
"context": " instead of being\n * evenly spread out.\n * @author Andrea Aime\n */\npublic class RandomRegionatingStrategy extend",
"end": 1108,
"score": 0.9998687505722046,
"start": 1097,
"tag": "NAME",
"value": "Andrea Aime"
}
]
| null | []
| /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.kml;
import java.sql.Connection;
import org.geoserver.config.GeoServer;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.FeatureIterator;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.filter.FilterFactory;
import org.opengis.filter.spatial.BBOX;
/**
* This strategy just return the features as they come from the db
* and leave the pyramid structure do the rest. Of course is the data is
* inserted in the db in a way that makes it return features in some linear
* way the distribution won't look good. But the same might happen to
* attribute sorting as well, for example, when the high values of the
* sorting attribute do concentrate in a specific area instead of being
* evenly spread out.
* @author <NAME>
*/
public class RandomRegionatingStrategy extends
CachedHierarchyRegionatingStrategy {
public RandomRegionatingStrategy(GeoServer gs) {
super(gs);
}
@Override
public FeatureIterator getSortedFeatures(GeometryDescriptor geom,
ReferencedEnvelope latLongEnv, ReferencedEnvelope nativeEnv,
Connection cacheConn) throws Exception {
FeatureSource fs = featureType.getFeatureSource(null, null);
// build the bbox filter
FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
BBOX filter = ff.bbox(geom.getLocalName(), nativeEnv.getMinX(),
nativeEnv.getMinY(), nativeEnv.getMaxX(), nativeEnv.getMaxY(), null);
// build an optimized query (only the necessary attributes
Query q = new Query();
q.setFilter(filter);
// TODO: enable this when JTS learns how to compute centroids
// without triggering the
// generation of Coordinate[] out of the sequences...
// q.setHints(new Hints(Hints.JTS_COORDINATE_SEQUENCE_FACTORY,
// PackedCoordinateSequenceFactory.class));
q.setPropertyNames(new String[] { geom.getLocalName() });
// return the reader
return fs.getFeatures(q).features();
}
}
| 2,407 | 0.717247 | 0.713101 | 62 | 37.903225 | 26.847063 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532258 | false | false | 4 |
5d4b09ec3a7c31263de51fe9763c0cd148c62423 | 28,278,064,707,012 | 274f3dd58086ff1494656e634a79290b2b70f793 | /app/src/main/java/in/blogspot/tecnopandit/notesapp/MainActivity.java | 96141a06bdfb155b88284cc22b1fbf8cee9a7387 | []
| no_license | dhruvshridhar/NotesAPP | https://github.com/dhruvshridhar/NotesAPP | bc80a5024c6c1728980b84834d611b99417e3c5f | 7e316db158edeb8b5db96bd15bb0cb0c6df40786 | refs/heads/master | 2020-12-04T20:56:44.897000 | 2020-01-05T10:24:25 | 2020-01-05T10:24:25 | 231,900,378 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package in.blogspot.tecnopandit.notesapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
ListView listView;
ArrayAdapter<String>arrayAdapter;
@Override
protected void onResume() {
super.onResume();
arrayAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,Prefrence.arrayList);
listView.setAdapter(arrayAdapter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton=findViewById(R.id.floatingActionButton);
listView=findViewById(R.id.listnotes);
Prefrence.arrayList.add("Notes");
arrayAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,Prefrence.arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_LONG).show();
Intent intent=new Intent(getApplicationContext(),Editnote.class);
intent.putExtra("key",position);
startActivity(intent);
}
});
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Editnote.class);
startActivity(intent);
}
});
}
}
| UTF-8 | Java | 2,071 | java | MainActivity.java | Java | []
| null | []
| package in.blogspot.tecnopandit.notesapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
ListView listView;
ArrayAdapter<String>arrayAdapter;
@Override
protected void onResume() {
super.onResume();
arrayAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,Prefrence.arrayList);
listView.setAdapter(arrayAdapter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton=findViewById(R.id.floatingActionButton);
listView=findViewById(R.id.listnotes);
Prefrence.arrayList.add("Notes");
arrayAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,Prefrence.arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_LONG).show();
Intent intent=new Intent(getApplicationContext(),Editnote.class);
intent.putExtra("key",position);
startActivity(intent);
}
});
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Editnote.class);
startActivity(intent);
}
});
}
}
| 2,071 | 0.699179 | 0.697731 | 58 | 34.706898 | 27.882147 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.775862 | false | false | 4 |
91d31bd8b54ee2498999ffaec3124c9a87047e26 | 10,075,993,307,124 | 5ed9e9a524bb8902a33f351a3d606cc8e8b1d441 | /ObjectMaster/src/module-info.java | fcd1f64bebf6041486764961d082284046c5c3d1 | []
| no_license | isaacSoto10/Object_Master_JAVA | https://github.com/isaacSoto10/Object_Master_JAVA | c41fa40741339ff54f042d09a40d5ab7a8b21321 | ac7439907a3d6c74db596097cf27511d949edf91 | refs/heads/main | 2023-07-17T05:08:25.002000 | 2021-09-01T15:05:16 | 2021-09-01T15:05:16 | 402,102,854 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | module zookeper {
} | UTF-8 | Java | 20 | java | module-info.java | Java | []
| null | []
| module zookeper {
} | 20 | 0.7 | 0.7 | 2 | 9 | 8 | 17 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 4 |
9171a5b7c619718d1020ec013cc229f1d5467a58 | 9,036,611,221,850 | 31bbc22ef990641a42122a9f2a94bdbe58843e40 | /EatToGo/src/main/java/co/unicauca/eattogo/presentation/intarface/GUIOrderSummary.java | 14784a4ceaaf08724e220928eeb3cfdfb01a1abf | []
| no_license | Carlos-Salamanca/EatToGo-Tercera-Iteracion | https://github.com/Carlos-Salamanca/EatToGo-Tercera-Iteracion | 3ed2da5823faa9c1e98b268b744f6f26e4773d1a | 7a2ffa5fb7bcc2fb4408b114539ab9c75a2989ba | refs/heads/master | 2023-02-01T12:55:16.777000 | 2020-12-16T17:30:54 | 2020-12-16T17:30:54 | 321,848,609 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.unicauca.eattogo.presentation.intarface;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableModel;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import co.unicauca.eattogo.access.OrderConsumer;
import co.unicauca.eattogo.domain.entity.LunchClient;
import co.unicauca.eattogo.domain.entity.LunchPart;
import co.unicauca.eattogo.domain.entity.LunchPartTypeEnum;
import co.unicauca.eattogo.domain.entity.Order;
import co.unicauca.eattogo.domain.service.ConsumerOrderService;
/**
* Interfaz del resumen de los almuerzos deseados
*
* @author Christian Tobar, Juliana Mora, Yeferson Benavides, Alejandro Latorre,
* Carlos Salamanca
*
*/
public class GUIOrderSummary extends JInternalFrame {
private JLabel lblNewLabel;
private JPanel panel;
private JScrollPane scrollPane;
private JTable table;
private JButton btnRegresarResumen;
private JButton btnPedir;
public static String summary;
public static ArrayList<ArrayList<LunchPart>> summaryOrder = new ArrayList<>();
//public static ArrayList<LunchPart> summaryOrder;
private JButton btnBorrarItemCanasta;
public static ArrayList<Order> orders;
private Order order;
private ConsumerOrderService cService;
/**
* Create the frame.
*/
public GUIOrderSummary() {
addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameClosing(InternalFrameEvent e) {
summary = null;
GUICommunerClient.visibleSelection(true);
dispose();
}
});
setIconifiable(true);
setFrameIcon(new ImageIcon("C:\\Users\\Personal\\eclipse-workspace\\Microservicios-Spring-Boot\\Dish-Service\\src\\main\\resources\\templates\\carro-de-la-compra (1).png"));
summary = "summary";
setTitle("Canasta Pedidos");
setBounds(100, 100, 547, 480);
getContentPane().setLayout(null);
lblNewLabel = new JLabel("Resumen Pedido");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
lblNewLabel.setBounds(170, 11, 182, 43);
getContentPane().add(lblNewLabel);
panel = new JPanel();
panel.setBounds(10, 51, 511, 329);
getContentPane().add(panel);
panel.setLayout(new CardLayout(0, 0));
scrollPane = new JScrollPane();
panel.add(scrollPane, "name_800954736428268");
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Entrada", "Principio", "Proteina", "Bebida", "Subtotal"
}
));
scrollPane.setViewportView(table);
btnRegresarResumen = new JButton("Regresar");
btnRegresarResumen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
GUICommunerClient.botonRegresarOrderSummary();
}
});
btnRegresarResumen.setFont(new Font("Tahoma", Font.BOLD, 12));
btnRegresarResumen.setBounds(10, 414, 89, 28);
getContentPane().add(btnRegresarResumen);
btnPedir = new JButton("Pedir $");
btnPedir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("sizeof orders:" + orders.size());
for(Order or : orders) {
System.out.println("tostring: "+ or.toString());
try {
boolean response = cService.create(or);
} catch (HttpClientErrorException k1) {
System.out.println("Http code is not 2XX. The server responded: " + k1.getStatusCode() + " Cause: "
+ k1.getResponseBodyAsString());
} catch (RestClientException k) {
System.out.println("The server didn't respond: " + k.getMessage());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
JOptionPane.showMessageDialog(null, "Pedido realizado");
}
});
btnPedir.setFont(new Font("Tahoma", Font.BOLD, 12));
btnPedir.setBounds(170, 414, 191, 28);
getContentPane().add(btnPedir);
btnBorrarItemCanasta = new JButton("Borrar");
btnBorrarItemCanasta.setFont(new Font("Tahoma", Font.BOLD, 11));
btnBorrarItemCanasta.setIcon(new ImageIcon("C:\\Users\\Personal\\eclipse-workspace\\Microservicios-Spring-Boot\\Product-Service\\src\\main\\resources\\templates\\remove.png"));
btnBorrarItemCanasta.setBounds(430, 415, 91, 28);
getContentPane().add(btnBorrarItemCanasta);
order = new Order();
orders = new ArrayList<>();
OrderConsumer oc = new OrderConsumer();
cService = new ConsumerOrderService(oc);
loadDataTable(table);
btnPedir.setText(btnPedir.getText() + (GUIAddMenu.priceMenu*table.getRowCount()));
}
/**
* Carga las comidas en el jTable
*/
private static void loadDataTable(JTable jtable) {
DefaultTableModel modelTable = (DefaultTableModel) jtable.getModel();
Object[] fila = new Object[5];
// ArrayList<LunchClient> lunchClients = new ArrayList<>();
LunchClient auxLunCli = new LunchClient();
Order or;
for (int i = 0; i < summaryOrder.size(); i++) {
or = new Order();
//or.setId(i+1L);
for (int j = 0; j < summaryOrder.get(0).size(); j++) {
LunchPartTypeEnum type = summaryOrder.get(i).get(j).getType();
Long idPart = summaryOrder.get(i).get(j).getId();
if (type == LunchPartTypeEnum.ENTRADA) {
fila[0] = summaryOrder.get(i).get(j).getName();
auxLunCli.setEntryId(idPart);
}
if (type == LunchPartTypeEnum.PRINCIPIO) {
fila[1] = summaryOrder.get(i).get(j).getName();
auxLunCli.setSideDishId(idPart);
}
if (type == LunchPartTypeEnum.PROTEINA) {
fila[2] = summaryOrder.get(i).get(j).getName();
auxLunCli.setProteinId(idPart);
}
if (type == LunchPartTypeEnum.JUGO) {
fila[3] = summaryOrder.get(i).get(j).getName();
auxLunCli.setDrinkId(idPart);
}
}
fila[4] = GUIAddMenu.priceMenu + "";
auxLunCli.setPrice(GUIAddMenu.priceMenu);
or.setLunchClient(auxLunCli);
orders.add(or);
// lunchClients.add(auxLunCli);
// order.setLunchClients(lunchClients);
modelTable.addRow(fila);
}
}
}
| UTF-8 | Java | 6,409 | java | GUIOrderSummary.java | Java | [
{
"context": "l resumen de los almuerzos deseados\n * \n * @author Christian Tobar, Juliana Mora, Yeferson Benavides, Alejandro Lato",
"end": 1143,
"score": 0.9998574256896973,
"start": 1128,
"tag": "NAME",
"value": "Christian Tobar"
},
{
"context": "almuerzos deseados\n * \n * @author Christian Tobar, Juliana Mora, Yeferson Benavides, Alejandro Latorre,\n * ",
"end": 1157,
"score": 0.9998608827590942,
"start": 1145,
"tag": "NAME",
"value": "Juliana Mora"
},
{
"context": "ados\n * \n * @author Christian Tobar, Juliana Mora, Yeferson Benavides, Alejandro Latorre,\n * Carlos Salamanca\n ",
"end": 1177,
"score": 0.999873161315918,
"start": 1159,
"tag": "NAME",
"value": "Yeferson Benavides"
},
{
"context": "Christian Tobar, Juliana Mora, Yeferson Benavides, Alejandro Latorre,\n * Carlos Salamanca\n *\n */\npublic class ",
"end": 1196,
"score": 0.9998734593391418,
"start": 1179,
"tag": "NAME",
"value": "Alejandro Latorre"
},
{
"context": " Yeferson Benavides, Alejandro Latorre,\n * Carlos Salamanca\n *\n */\npublic class GUIOrderSummary extends JInte",
"end": 1225,
"score": 0.9998722076416016,
"start": 1209,
"tag": "NAME",
"value": "Carlos Salamanca"
}
]
| null | []
| package co.unicauca.eattogo.presentation.intarface;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableModel;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import co.unicauca.eattogo.access.OrderConsumer;
import co.unicauca.eattogo.domain.entity.LunchClient;
import co.unicauca.eattogo.domain.entity.LunchPart;
import co.unicauca.eattogo.domain.entity.LunchPartTypeEnum;
import co.unicauca.eattogo.domain.entity.Order;
import co.unicauca.eattogo.domain.service.ConsumerOrderService;
/**
* Interfaz del resumen de los almuerzos deseados
*
* @author <NAME>, <NAME>, <NAME>, <NAME>,
* <NAME>
*
*/
public class GUIOrderSummary extends JInternalFrame {
private JLabel lblNewLabel;
private JPanel panel;
private JScrollPane scrollPane;
private JTable table;
private JButton btnRegresarResumen;
private JButton btnPedir;
public static String summary;
public static ArrayList<ArrayList<LunchPart>> summaryOrder = new ArrayList<>();
//public static ArrayList<LunchPart> summaryOrder;
private JButton btnBorrarItemCanasta;
public static ArrayList<Order> orders;
private Order order;
private ConsumerOrderService cService;
/**
* Create the frame.
*/
public GUIOrderSummary() {
addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameClosing(InternalFrameEvent e) {
summary = null;
GUICommunerClient.visibleSelection(true);
dispose();
}
});
setIconifiable(true);
setFrameIcon(new ImageIcon("C:\\Users\\Personal\\eclipse-workspace\\Microservicios-Spring-Boot\\Dish-Service\\src\\main\\resources\\templates\\carro-de-la-compra (1).png"));
summary = "summary";
setTitle("Canasta Pedidos");
setBounds(100, 100, 547, 480);
getContentPane().setLayout(null);
lblNewLabel = new JLabel("Resumen Pedido");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
lblNewLabel.setBounds(170, 11, 182, 43);
getContentPane().add(lblNewLabel);
panel = new JPanel();
panel.setBounds(10, 51, 511, 329);
getContentPane().add(panel);
panel.setLayout(new CardLayout(0, 0));
scrollPane = new JScrollPane();
panel.add(scrollPane, "name_800954736428268");
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Entrada", "Principio", "Proteina", "Bebida", "Subtotal"
}
));
scrollPane.setViewportView(table);
btnRegresarResumen = new JButton("Regresar");
btnRegresarResumen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
GUICommunerClient.botonRegresarOrderSummary();
}
});
btnRegresarResumen.setFont(new Font("Tahoma", Font.BOLD, 12));
btnRegresarResumen.setBounds(10, 414, 89, 28);
getContentPane().add(btnRegresarResumen);
btnPedir = new JButton("Pedir $");
btnPedir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("sizeof orders:" + orders.size());
for(Order or : orders) {
System.out.println("tostring: "+ or.toString());
try {
boolean response = cService.create(or);
} catch (HttpClientErrorException k1) {
System.out.println("Http code is not 2XX. The server responded: " + k1.getStatusCode() + " Cause: "
+ k1.getResponseBodyAsString());
} catch (RestClientException k) {
System.out.println("The server didn't respond: " + k.getMessage());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
JOptionPane.showMessageDialog(null, "Pedido realizado");
}
});
btnPedir.setFont(new Font("Tahoma", Font.BOLD, 12));
btnPedir.setBounds(170, 414, 191, 28);
getContentPane().add(btnPedir);
btnBorrarItemCanasta = new JButton("Borrar");
btnBorrarItemCanasta.setFont(new Font("Tahoma", Font.BOLD, 11));
btnBorrarItemCanasta.setIcon(new ImageIcon("C:\\Users\\Personal\\eclipse-workspace\\Microservicios-Spring-Boot\\Product-Service\\src\\main\\resources\\templates\\remove.png"));
btnBorrarItemCanasta.setBounds(430, 415, 91, 28);
getContentPane().add(btnBorrarItemCanasta);
order = new Order();
orders = new ArrayList<>();
OrderConsumer oc = new OrderConsumer();
cService = new ConsumerOrderService(oc);
loadDataTable(table);
btnPedir.setText(btnPedir.getText() + (GUIAddMenu.priceMenu*table.getRowCount()));
}
/**
* Carga las comidas en el jTable
*/
private static void loadDataTable(JTable jtable) {
DefaultTableModel modelTable = (DefaultTableModel) jtable.getModel();
Object[] fila = new Object[5];
// ArrayList<LunchClient> lunchClients = new ArrayList<>();
LunchClient auxLunCli = new LunchClient();
Order or;
for (int i = 0; i < summaryOrder.size(); i++) {
or = new Order();
//or.setId(i+1L);
for (int j = 0; j < summaryOrder.get(0).size(); j++) {
LunchPartTypeEnum type = summaryOrder.get(i).get(j).getType();
Long idPart = summaryOrder.get(i).get(j).getId();
if (type == LunchPartTypeEnum.ENTRADA) {
fila[0] = summaryOrder.get(i).get(j).getName();
auxLunCli.setEntryId(idPart);
}
if (type == LunchPartTypeEnum.PRINCIPIO) {
fila[1] = summaryOrder.get(i).get(j).getName();
auxLunCli.setSideDishId(idPart);
}
if (type == LunchPartTypeEnum.PROTEINA) {
fila[2] = summaryOrder.get(i).get(j).getName();
auxLunCli.setProteinId(idPart);
}
if (type == LunchPartTypeEnum.JUGO) {
fila[3] = summaryOrder.get(i).get(j).getName();
auxLunCli.setDrinkId(idPart);
}
}
fila[4] = GUIAddMenu.priceMenu + "";
auxLunCli.setPrice(GUIAddMenu.priceMenu);
or.setLunchClient(auxLunCli);
orders.add(or);
// lunchClients.add(auxLunCli);
// order.setLunchClients(lunchClients);
modelTable.addRow(fila);
}
}
}
| 6,361 | 0.716024 | 0.699797 | 196 | 31.69898 | 26.113884 | 178 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.877551 | false | false | 4 |
6be744301a0c54fe5d8d6ff16ab06e7a1e458936 | 22,325,240,039,727 | 5645ec3f6f08f55081d0b4eba7702bcca7146a4d | /src/main/java/org/launchcode/models/data/CuisineDao.java | 504dd28b51bbe31089f0fa83e6040f20415814b9 | []
| no_license | devanray23/Java-RandNums | https://github.com/devanray23/Java-RandNums | 9ad65596f966978a03a29d1203e68ce27ac7eeee | a570b9c1c694258ad75c2052fc5990645e65fb04 | refs/heads/master | 2021-01-19T16:37:23.988000 | 2018-04-19T22:37:22 | 2018-04-19T22:37:22 | 101,012,814 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.launchcode.models.data;
import org.launchcode.models.Cuisine;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.sql.*;
import java.util.ArrayList;
@Repository
@Transactional
public interface CuisineDao extends CrudRepository<Cuisine, Integer> {
/* public static ArrayList<Cuisine> getAllCuisines() throws ClassNotFoundException, SQLException {
ArrayList<Cuisine> cuisines = new ArrayList<>();
Connection c = null;
try {
c = DriverManager.getConnection("jdbc:mysql://localhost:8889/randnums-mvc",
"randnums-mvc", "23isBACK!");
Cuisine cuisine = null;
Statement stm = c.createStatement();
ResultSet resultSet = stm.executeQuery("SELECT * FROM cuisine");
while (resultSet.next()) {
cuisine.setId(resultSet.getInt("id"));
cuisine.setName(resultSet.getString("name"));
cuisines.add(cuisine);
}
} catch (Exception e) {
System.out.println(e);
}
return cuisines;
}*/
ArrayList<Cuisine> findAll();
Cuisine findByName(String name);
} | UTF-8 | Java | 1,277 | java | CuisineDao.java | Java | []
| null | []
| package org.launchcode.models.data;
import org.launchcode.models.Cuisine;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.sql.*;
import java.util.ArrayList;
@Repository
@Transactional
public interface CuisineDao extends CrudRepository<Cuisine, Integer> {
/* public static ArrayList<Cuisine> getAllCuisines() throws ClassNotFoundException, SQLException {
ArrayList<Cuisine> cuisines = new ArrayList<>();
Connection c = null;
try {
c = DriverManager.getConnection("jdbc:mysql://localhost:8889/randnums-mvc",
"randnums-mvc", "23isBACK!");
Cuisine cuisine = null;
Statement stm = c.createStatement();
ResultSet resultSet = stm.executeQuery("SELECT * FROM cuisine");
while (resultSet.next()) {
cuisine.setId(resultSet.getInt("id"));
cuisine.setName(resultSet.getString("name"));
cuisines.add(cuisine);
}
} catch (Exception e) {
System.out.println(e);
}
return cuisines;
}*/
ArrayList<Cuisine> findAll();
Cuisine findByName(String name);
} | 1,277 | 0.64213 | 0.637432 | 48 | 25.625 | 26.259621 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
bec5524db55b6f766ce63e096cfd64c3bab70f4a | 34,102,040,345,108 | 6727d18f9ef9a0b753be8a4c55c762cab6c23de2 | /src/test/java/Junit/tbrito/KataDosTest.java | eb38dd6292a3d5fc8d5d8297e2c08596255e0e22 | []
| no_license | fahelodev/bootcamp-2021-4 | https://github.com/fahelodev/bootcamp-2021-4 | daad32a5b1514d3f32020a41fbb35753a0c81100 | 1a108fbecedf8f4687a3689c0690c8ab566ff609 | refs/heads/main | 2023-08-18T07:05:40.809000 | 2021-09-16T20:35:34 | 2021-09-16T20:35:34 | 395,366,146 | 0 | 24 | null | false | 2021-09-20T16:22:02 | 2021-08-12T15:35:08 | 2021-09-16T20:35:44 | 2021-09-20T16:21:11 | 553 | 0 | 11 | 0 | Java | false | false | package junit.tbrito;
import org.junit.Test;
import static org.junit.Assert.*;
public class KataDosTest {
@Test
public void test1() {
assertEquals("HELLO WORLD", KataDos.toAlternativeString("hello world"));
}
@Test
public void test2() {
assertEquals("hello world", KataDos.toAlternativeString("HELLO WORLD"));
}
@Test
public void test3() {
assertEquals("HELLO world", KataDos.toAlternativeString("hello WORLD"));
}
@Test
public void test4() {
assertEquals("hEllO wOrld", KataDos.toAlternativeString("HeLLo WoRLD"));
}
@Test
public void test5() {
assertEquals("Hello World", KataDos.toAlternativeString(KataDos.toAlternativeString("Hello World")));
}
@Test
public void test6() {
assertEquals("12345", KataDos.toAlternativeString("12345"));
}
@Test
public void test7() {
assertEquals("1A2B3C4D5E", KataDos.toAlternativeString("1a2b3c4d5e"));
}
@Test
public void test8() {
assertEquals("sTRINGuTILS.TOaLTERNATINGcASE", KataDos.toAlternativeString("StringUtils.toAlternatingCase"));
}
@Test
public void kataTitleTests() {
assertEquals("ALTerNAtiNG CaSe", KataDos.toAlternativeString("altERnaTIng cAsE"));
assertEquals("altERnaTIng cAsE", KataDos.toAlternativeString("ALTerNAtiNG CaSe"));
assertEquals("ALTerNAtiNG CaSe <=> altERnaTIng cAsE", KataDos.toAlternativeString("altERnaTIng cAsE <=> ALTerNAtiNG CaSe"));
assertEquals("altERnaTIng cAsE <=> ALTerNAtiNG CaSe", KataDos.toAlternativeString("ALTerNAtiNG CaSe <=> altERnaTIng cAsE"));
}
} | UTF-8 | Java | 1,647 | java | KataDosTest.java | Java | []
| null | []
| package junit.tbrito;
import org.junit.Test;
import static org.junit.Assert.*;
public class KataDosTest {
@Test
public void test1() {
assertEquals("HELLO WORLD", KataDos.toAlternativeString("hello world"));
}
@Test
public void test2() {
assertEquals("hello world", KataDos.toAlternativeString("HELLO WORLD"));
}
@Test
public void test3() {
assertEquals("HELLO world", KataDos.toAlternativeString("hello WORLD"));
}
@Test
public void test4() {
assertEquals("hEllO wOrld", KataDos.toAlternativeString("HeLLo WoRLD"));
}
@Test
public void test5() {
assertEquals("Hello World", KataDos.toAlternativeString(KataDos.toAlternativeString("Hello World")));
}
@Test
public void test6() {
assertEquals("12345", KataDos.toAlternativeString("12345"));
}
@Test
public void test7() {
assertEquals("1A2B3C4D5E", KataDos.toAlternativeString("1a2b3c4d5e"));
}
@Test
public void test8() {
assertEquals("sTRINGuTILS.TOaLTERNATINGcASE", KataDos.toAlternativeString("StringUtils.toAlternatingCase"));
}
@Test
public void kataTitleTests() {
assertEquals("ALTerNAtiNG CaSe", KataDos.toAlternativeString("altERnaTIng cAsE"));
assertEquals("altERnaTIng cAsE", KataDos.toAlternativeString("ALTerNAtiNG CaSe"));
assertEquals("ALTerNAtiNG CaSe <=> altERnaTIng cAsE", KataDos.toAlternativeString("altERnaTIng cAsE <=> ALTerNAtiNG CaSe"));
assertEquals("altERnaTIng cAsE <=> ALTerNAtiNG CaSe", KataDos.toAlternativeString("ALTerNAtiNG CaSe <=> altERnaTIng cAsE"));
}
} | 1,647 | 0.675167 | 0.658166 | 50 | 31.959999 | 37.794689 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54 | false | false | 4 |
a550afba7f4433fb5cd6068451fcc073b88046a6 | 34,102,040,344,647 | 6b1a5dd18f1a64f2fba3a8e84ab99ff3f59789db | /src/MyPackage/TestAtomic.java | fc2a49ac5e147f3dfc1946498bc66ab16bbd2eea | []
| no_license | caniggia15/java | https://github.com/caniggia15/java | a3e53d0f0acca633d05751d95b01183556fb7358 | bde1cfb3f045aa2c329fc866d4ddcd41fb0c592c | refs/heads/master | 2016-08-07T08:22:43.888000 | 2013-12-23T07:54:40 | 2013-12-23T07:54:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package MyPackage;
import java.util.concurrent.atomic.*;
public class TestAtomic implements Runnable {
private final AtomicLong al = new AtomicLong(0);
public long nextId() { return al.getAndIncrement(); }
public long getCount() { return al.get(); }
public static void main(String[] argv)
{
TestAtomic ta = new TestAtomic();
Thread t1 = new Thread(ta);
Thread t2 = new Thread(ta);
Thread t3 = new Thread(ta);
t1.start();
t2.start();
t3.start();
while ( (t1.isAlive() || t2.isAlive() || t3.isAlive()) )
{
System.out.println("wait"+ta.getCount());
}
System.out.println("last:"+ta.getCount());
}
@Override
public void run() {
for (int i=0;i<10000;i++) {
al.incrementAndGet();
}
}
}
| UTF-8 | Java | 777 | java | TestAtomic.java | Java | []
| null | []
| package MyPackage;
import java.util.concurrent.atomic.*;
public class TestAtomic implements Runnable {
private final AtomicLong al = new AtomicLong(0);
public long nextId() { return al.getAndIncrement(); }
public long getCount() { return al.get(); }
public static void main(String[] argv)
{
TestAtomic ta = new TestAtomic();
Thread t1 = new Thread(ta);
Thread t2 = new Thread(ta);
Thread t3 = new Thread(ta);
t1.start();
t2.start();
t3.start();
while ( (t1.isAlive() || t2.isAlive() || t3.isAlive()) )
{
System.out.println("wait"+ta.getCount());
}
System.out.println("last:"+ta.getCount());
}
@Override
public void run() {
for (int i=0;i<10000;i++) {
al.incrementAndGet();
}
}
}
| 777 | 0.603604 | 0.583012 | 38 | 18.447369 | 18.514145 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.868421 | false | false | 4 |
a23e1d8ccaabf243fa6c9314d0b0131636e149a0 | 5,755,256,200,105 | 66f9ae873c97576f12175cb4e46cfea2f9c6008d | /src/main/java/com/flower/allFlowers/model/FlowerRequest.java | 44444f44c18e728c6fe14d7efed356e4c9b912cc | []
| no_license | geyu123456/flower-api | https://github.com/geyu123456/flower-api | 2c1d16a06b3a000c3e6dfb33846c9d90619d9b32 | e300876768a394d7e4995db83712cc088fa228a5 | refs/heads/master | 2018-12-19T16:49:39.840000 | 2018-10-28T11:23:59 | 2018-10-28T11:23:59 | 112,680,299 | 5 | 2 | null | false | 2018-03-01T02:59:02 | 2017-12-01T01:30:06 | 2018-02-18T05:52:00 | 2018-02-28T09:14:54 | 2,043 | 1 | 1 | 1 | JavaScript | false | null | package com.flower.allFlowers.model;
import lombok.Data;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
/**
* Created by geyu on 18-1-11.
*/
@Data
public class FlowerRequest {
private String id;
/**
* 图片存放地址
*/
@NotEmpty(message = "必须上传一张图片")
private String picUrl;
/**
* 接收图片文件
*/
private MultipartFile file;
/**
* 文字描述
*/
private String content;
/**
* 单价
*/
@NotEmpty(message = "单价不能为空")
private BigDecimal price;
/**
* 折扣
*/
@NotEmpty(message = "折扣不能为空")
private BigDecimal discount;
/**
* 花名
*/
@NotEmpty(message = "标题不能为空")
private String title;
/**
* 颜色
*/
@NotEmpty(message = "颜色不能为空")
private String color;
/**
* 花名
*/
@NotEmpty(message = "花名不能为空")
private String name;
/**
* 类型
*/
@NotEmpty(message = "类型不能为空")
private String type;
/**
* 节日
*/
@NotEmpty(message = "节日不能为空")
private String festival;
}
| UTF-8 | Java | 1,298 | java | FlowerRequest.java | Java | [
{
"context": ";\n\nimport java.math.BigDecimal;\n\n/**\n * Created by geyu on 18-1-11.\n */\n@Data\npublic class FlowerRequest ",
"end": 220,
"score": 0.9922081232070923,
"start": 216,
"tag": "USERNAME",
"value": "geyu"
}
]
| null | []
| package com.flower.allFlowers.model;
import lombok.Data;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;
import java.math.BigDecimal;
/**
* Created by geyu on 18-1-11.
*/
@Data
public class FlowerRequest {
private String id;
/**
* 图片存放地址
*/
@NotEmpty(message = "必须上传一张图片")
private String picUrl;
/**
* 接收图片文件
*/
private MultipartFile file;
/**
* 文字描述
*/
private String content;
/**
* 单价
*/
@NotEmpty(message = "单价不能为空")
private BigDecimal price;
/**
* 折扣
*/
@NotEmpty(message = "折扣不能为空")
private BigDecimal discount;
/**
* 花名
*/
@NotEmpty(message = "标题不能为空")
private String title;
/**
* 颜色
*/
@NotEmpty(message = "颜色不能为空")
private String color;
/**
* 花名
*/
@NotEmpty(message = "花名不能为空")
private String name;
/**
* 类型
*/
@NotEmpty(message = "类型不能为空")
private String type;
/**
* 节日
*/
@NotEmpty(message = "节日不能为空")
private String festival;
}
| 1,298 | 0.553603 | 0.549209 | 69 | 15.492754 | 13.528953 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.231884 | false | false | 4 |
5f566c100caa7e5d98cb478eff0ad962c8fb6305 | 19,705,310,011,268 | 9406587f049888f34c4b0f595f3beaa2641645b6 | /data-pipeline/telemetry-location-updater/src/test/java/org/ekstep/ep/samza/task/TelemetryLocationUpdaterTaskTest.java | caacbeadd1ebd10860df335ecfb23606642ae5df | [
"MIT"
]
| permissive | anuthaharinimn/sunbird-data-pipeline | https://github.com/anuthaharinimn/sunbird-data-pipeline | 4f95292d488ee35d4c9e86cbf11e3224d949c501 | 4b6760e475b215b76814b35583e5ed8b257ecba8 | refs/heads/master | 2020-09-07T18:14:24.230000 | 2019-10-10T11:17:50 | 2019-10-10T11:17:50 | 199,994,768 | 0 | 0 | MIT | true | 2019-08-01T06:54:15 | 2019-08-01T06:54:14 | 2019-04-08T09:36:57 | 2019-08-01T06:25:20 | 60,656 | 0 | 0 | 0 | null | false | false | package org.ekstep.ep.samza.task;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.samza.Partition;
import org.apache.samza.config.Config;
import org.apache.samza.metrics.Counter;
import org.apache.samza.metrics.MetricsRegistry;
import org.apache.samza.system.IncomingMessageEnvelope;
import org.apache.samza.system.OutgoingMessageEnvelope;
import org.apache.samza.system.SystemStream;
import org.apache.samza.system.SystemStreamPartition;
import org.apache.samza.task.MessageCollector;
import org.apache.samza.task.TaskContext;
import org.apache.samza.task.TaskCoordinator;
import org.ekstep.ep.samza.domain.DeviceProfile;
import org.ekstep.ep.samza.fixtures.EventFixture;
import org.ekstep.ep.samza.util.DeviceProfileCache;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.*;
public class TelemetryLocationUpdaterTaskTest {
private static final String SUCCESS_TOPIC = "telemetry.with_location";
private static final String FAILED_TOPIC = "telemetry.failed";
private static final String MALFORMED_TOPIC = "telemetry.malformed";
private MessageCollector collectorMock;
private TaskCoordinator coordinatorMock;
private IncomingMessageEnvelope envelopeMock;
private DeviceProfileCache deviceProfileCacheMock;
private TelemetryLocationUpdaterTask telemetryLocationUpdaterTask;
@SuppressWarnings("unchecked")
@Before
public void setUp() {
collectorMock = mock(MessageCollector.class);
TaskContext contextMock = mock(TaskContext.class);
MetricsRegistry metricsRegistry = mock(MetricsRegistry.class);
Counter counter = mock(Counter.class);
coordinatorMock = mock(TaskCoordinator.class);
envelopeMock = mock(IncomingMessageEnvelope.class);
Config configMock = mock(Config.class);
deviceProfileCacheMock = mock(DeviceProfileCache.class);
stub(configMock.get("output.success.topic.name", SUCCESS_TOPIC)).toReturn(SUCCESS_TOPIC);
stub(configMock.get("output.failed.topic.name", FAILED_TOPIC)).toReturn(FAILED_TOPIC);
stub(configMock.get("output.malformed.topic.name", MALFORMED_TOPIC)).toReturn(MALFORMED_TOPIC);
stub(metricsRegistry.newCounter(anyString(), anyString())).toReturn(counter);
stub(contextMock.getMetricsRegistry()).toReturn(metricsRegistry);
stub(envelopeMock.getOffset()).toReturn("2");
stub(envelopeMock.getSystemStreamPartition())
.toReturn(new SystemStreamPartition("kafka", "input.topic", new Partition(1)));
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, deviceProfileCacheMock);
}
@Test
public void shouldSendEventsToSuccessTopicIfDidIsNull() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT_WITHOUT_DID);
stub(deviceProfileCacheMock.getDeviceProfileForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(null);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertFalse(outputEvent.containsKey("devicedata"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(false, flags.get("device_profile_retrieved"));
return true;
}
}));
}
/*
@Test
public void shouldSendEventsToSuccessTopicWithLocationFromDB() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
Map<String, String> resultFromCache = new HashMap<>();
stub(configMock.get("cassandra.keyspace")).toReturn("device_db");
stub(configMock.get("cassandra.device_profile_table")).toReturn("device_profile");
stub(configMock.get("redis.database.deviceLocationStore.id")).toReturn("1");
stub(configMock.get("location.db.redis.key.expiry.seconds")).toReturn("86400");
stub(configMock.get("cache.unresolved.location.key.expiry.seconds")).toReturn("3600");
// RedisConnect redisConnectMock = Mockito.mock(RedisConnect.class);
// CassandraConnect cassandraConnectMock = Mockito.mock(CassandraConnect.class);
DeviceLocationCache cache = Mockito.spy(new DeviceLocationCache(configMock, mock(JobMetrics.class)));
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, cache);
stub(deviceLocationCacheMock.getLocationFromCache("68dfc64a7751ad47617ac1a4e0531fb761ebea6f"))
.toReturn(resultFromCache);
DeviceProfile location = new DeviceProfile("IN", "India", "KA", "Karnataka",
"Bangalore","Banglore-Custom","Karnatak-Custom","KA-Custom");
stub(deviceLocationCacheMock.getLocationFromDeviceProfileDB("68dfc64a7751ad47617ac1a4e0531fb761ebea6f"))
.toReturn(location);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> context = new Gson().fromJson(outputEvent.get("devicedata").toString(), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("IN", context.get("countrycode"));
assertEquals("India", context.get("country"));
assertEquals("KA", context.get("statecode"));
assertEquals("Karnataka", context.get("state"));
assertEquals("Bangalore", context.get("city"));
assertEquals("KA-Custom", context.get("statecustomcode"));
assertEquals("Banglore-Custom", context.get("districtcustom"));
assertEquals("Karnatak-Custom", context.get("statecustomname"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(true, flags.get("device_location_retrieved"));
return true;
}
}));
}
*/
/*
@Test
public void shouldSendEventsToSuccessTopicWithStampingLocationFromChannelAPI() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(null);
DeviceProfile loc = new DeviceProfile();
loc.setCity("");
loc.setState("Karnataka");
stub(locationStoreCache.get("0123221617357783046602")).toReturn(null);
stub(searchService.searchChannelLocationId("0123221617357783046602")).toReturn("loc1");
stub(searchService.searchLocation("loc1")).toReturn(loc);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
assertEquals(outputEvent.get("ver"), "3.0");
assertEquals(outputMessage.contains("\"state\":\"Karnataka\""), true);
assertEquals(outputMessage.contains("\"district\":\"\""), true);
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(flags.get("device_location_retrieved"), true);
return true;
}
}));
}
*/
/*
@Test
@Ignore
public void shouldSendEventsToSuccessTopicWithStampingLocationFromLocalStore() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(null);
DeviceProfile loc = new DeviceProfile("IN", "India", "KA", "Karnataka", "Bangalore");
stub(locationStoreCache.get("0123221617357783046602")).toReturn(loc);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> context = new Gson().fromJson(new Gson().toJson(outputEvent.get("devicedata")), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("IN", context.get("countrycode"));
assertEquals("India", context.get("country"));
assertEquals("KA", context.get("statecode"));
assertEquals("Karnataka", context.get("state"));
assertEquals("Bangalore", context.get("city"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(true, flags.get("device_location_retrieved"));
Map<String, Object> edata = new Gson().fromJson(outputEvent.get("edata").toString(), mapType);
assertNull(edata.get("loc"));
return true;
}
}));
}
*/
@Test
public void shouldSendEventsToSuccessTopicIfFoundInCache() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
Map uaspec = new HashMap();
Map device_spec = new HashMap();
Long first_access = 1559484698000L;
device_spec.put("os", "Android 6.0");
device_spec.put("make", "Motorola XT1706");
uaspec.put("agent", "Mozilla");
uaspec.put("ver", "5.0");
uaspec.put("system", "iPad");
uaspec.put("platform", "AppleWebKit/531.21.10");
uaspec.put("raw", "Mozilla/5.0 (X11 Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)");
DeviceProfile deviceProfile = new DeviceProfile
("IN", "India", "KA", "Karnataka",
"Bangalore", "Banglore-Custom", "Karnatak-Custom",
"KA-Custom", uaspec, device_spec, first_access);
stub(deviceProfileCacheMock.getDeviceProfileForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(deviceProfile);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertTrue(outputMessage.contains("\"countrycode\":\"IN\""));
assertTrue(outputMessage.contains("\"country\":\"India\""));
assertTrue(outputMessage.contains("\"statecode\":\"KA\""));
assertTrue(outputMessage.contains("\"state\":\"Karnataka\""));
assertTrue(outputMessage.contains("\"city\":\"Bangalore\""));
assertTrue(outputMessage.contains("\"statecustomcode\":\"KA-Custom\""));
assertTrue(outputMessage.contains("\"districtcustom\":\"Banglore-Custom\""));
assertTrue(outputMessage.contains("\"statecustomname\":\"Karnatak-Custom\""));
assertTrue(outputMessage.contains("\"iso3166statecode\":\"IN-KA\""));
assertTrue(outputMessage.contains("\"agent\":\"Mozilla\""));
assertTrue(outputMessage.contains("\"ver\":\"5.0\""));
assertTrue(outputMessage.contains("\"system\":\"iPad\""));
assertTrue(outputMessage.contains("\"os\":\"Android 6.0\""));
assertTrue(outputMessage.contains("\"make\":\"Motorola XT1706\""));
assertTrue(outputMessage.contains("\"platform\":\"AppleWebKit/531.21.10\""));
assertTrue(outputMessage.contains("\"raw\":\"Mozilla/5.0 (X11 Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)\""));
assertTrue(outputMessage.contains("\"firstaccess\":1559484698000"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(true, flags.get("device_profile_retrieved"));
return true;
}
}));
}
@Test
public void shouldSendEventToFailedTopicIfEventIsNotParseable() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.UNPARSABLE_START_EVENT);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
verify(collectorMock).send(argThat(validateOutputTopic(envelopeMock.getMessage(), MALFORMED_TOPIC)));
}
@Test
public void shouldSendEventToMalformedTopicIfEventIsAnyRandomString() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.ANY_STRING);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
verify(collectorMock).send(argThat(validateOutputTopic(envelopeMock.getMessage(), MALFORMED_TOPIC)));
}
public ArgumentMatcher<OutgoingMessageEnvelope> validateOutputTopic(final Object message, final String stream) {
return new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
SystemStream systemStream = outgoingMessageEnvelope.getSystemStream();
assertEquals("kafka", systemStream.getSystem());
assertEquals(stream, systemStream.getStream());
return true;
}
};
}
/*
@Test
public void shouldSendEventsToSuccessTopicWithUserLocation() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
DeviceProfile loc1 = new DeviceProfile("IN", "India", "KA", "Karnataka", "Bangalore");
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f",
"0123221617357783046602")).toReturn(loc1);
DeviceProfile loc2 = new DeviceProfile(null, null, null, "Tamil Nadu", null, "Chennai");
String userId = "393407b1-66b1-4c86-9080-b2bce9842886";
stub(userLocationCacheMock.getLocationByUser(userId)).toReturn(loc2);
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, locationEngine);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> userloc = new Gson().fromJson(new Gson().toJson(outputEvent.get("userdata")), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("Tamil Nadu", userloc.get("state"));
assertEquals("Chennai", userloc.get("district"));
return true;
}
}));
}
*/
/*
@Test
public void shouldNotAddUserLocationIfActorTypeIsNotUser() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT_WITH_ACTOR_AS_SYSTEM);
DeviceProfile loc1 = new DeviceProfile("IN", "India", "KA", "Karnataka", "Bangalore");
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f",
"0123221617357783046602")).toReturn(loc1);
DeviceProfile loc2 = new DeviceProfile(null, null, null, "Tamil Nadu", null, "Chennai");
String userId = "393407b1-66b1-4c86-9080-b2bce9842886";
stub(userLocationCacheMock.getLocationByUser(userId)).toReturn(loc2);
// stub(locationEngineMock.getLocation("0123221617357783046602")).toReturn(loc2);
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, locationEngineMock);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Object userlocdata = outputEvent.get("userdata");
assertNull(userlocdata);
return true;
}
}));
}
*/
/*
@Test
public void shouldFallbackToIPLocationIfUserLocationIsNotResolved() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
DeviceProfile loc1 = new DeviceProfile("IN", "India", "KA", "Karnataka", null, "Mysore");
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f",
"0123221617357783046602")).toReturn(null);
String userId = "393407b1-66b1-4c86-9080-b2bce9842886";
stub(userLocationCacheMock.getLocationByUser(userId)).toReturn(null);
// stub(locationEngineMock.getLocation("0123221617357783046602")).toReturn(loc1);
stub(locationEngineMock.deviceLocationCache()).toReturn(deviceLocationCacheMock);
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, locationEngineMock);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> userloc = new Gson().fromJson(new Gson().toJson(outputEvent.get("userdata")), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("Karnataka", userloc.get("state"));
assertEquals("Mysore", userloc.get("district"));
return true;
}
}));
}
*/
}
| UTF-8 | Java | 18,864 | java | TelemetryLocationUpdaterTaskTest.java | Java | [
{
"context": "viceProfileCacheMock.getDeviceProfileForDeviceId(\"68dfc64a7751ad47617ac1a4e0531fb761ebea6f\")).toReturn(null);\n\t\ttelemetryLocationUpdaterTask",
"end": 3076,
"score": 0.7353723645210266,
"start": 3036,
"tag": "KEY",
"value": "68dfc64a7751ad47617ac1a4e0531fb761ebea6f"
},
{
"context": "nCacheMock.getLocationFromDeviceProfileDB(\"68dfc64a7751ad47617ac1a4e0531fb761ebea6f\"))\n\t\t\t\t.toReturn(location);\n\t\ttelemetryLocationU",
"end": 5295,
"score": 0.59089195728302,
"start": 5263,
"tag": "KEY",
"value": "a7751ad47617ac1a4e0531fb761ebea6"
},
{
"context": "b(deviceLocationCacheMock.getLocationForDeviceId(\"68dfc64a7751ad47617ac1a4e0531fb761ebea6f\")).toReturn(null);\n\t\tDeviceProfile loc = new Devi",
"end": 6951,
"score": 0.6943244338035583,
"start": 6911,
"tag": "KEY",
"value": "68dfc64a7751ad47617ac1a4e0531fb761ebea6f"
},
{
"context": "b(deviceLocationCacheMock.getLocationForDeviceId(\"68dfc64a7751ad47617ac1a4e0531fb761ebea6f\",\n\t\t\t\t\"0123221617357783046602\")).toReturn(loc1);\n",
"end": 16088,
"score": 0.9605714082717896,
"start": 16048,
"tag": "KEY",
"value": "68dfc64a7751ad47617ac1a4e0531fb761ebea6f"
},
{
"context": "ofile loc2 = new DeviceProfile(null, null, null, \"Tamil Nadu\", null, \"Chennai\");\n\t\tString userId = \"393407b1-6",
"end": 16208,
"score": 0.991790771484375,
"start": 16198,
"tag": "NAME",
"value": "Tamil Nadu"
},
{
"context": "(deviceLocationCacheMock.getLocationForDeviceId(\"68dfc64a7751ad47617ac1a4e0531fb761ebea6f\",\n\t\t\t\t\"01232216173577",
"end": 17537,
"score": 0.8656704425811768,
"start": 17526,
"tag": "KEY",
"value": "8dfc64a7751"
}
]
| null | []
| package org.ekstep.ep.samza.task;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.samza.Partition;
import org.apache.samza.config.Config;
import org.apache.samza.metrics.Counter;
import org.apache.samza.metrics.MetricsRegistry;
import org.apache.samza.system.IncomingMessageEnvelope;
import org.apache.samza.system.OutgoingMessageEnvelope;
import org.apache.samza.system.SystemStream;
import org.apache.samza.system.SystemStreamPartition;
import org.apache.samza.task.MessageCollector;
import org.apache.samza.task.TaskContext;
import org.apache.samza.task.TaskCoordinator;
import org.ekstep.ep.samza.domain.DeviceProfile;
import org.ekstep.ep.samza.fixtures.EventFixture;
import org.ekstep.ep.samza.util.DeviceProfileCache;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.*;
public class TelemetryLocationUpdaterTaskTest {
private static final String SUCCESS_TOPIC = "telemetry.with_location";
private static final String FAILED_TOPIC = "telemetry.failed";
private static final String MALFORMED_TOPIC = "telemetry.malformed";
private MessageCollector collectorMock;
private TaskCoordinator coordinatorMock;
private IncomingMessageEnvelope envelopeMock;
private DeviceProfileCache deviceProfileCacheMock;
private TelemetryLocationUpdaterTask telemetryLocationUpdaterTask;
@SuppressWarnings("unchecked")
@Before
public void setUp() {
collectorMock = mock(MessageCollector.class);
TaskContext contextMock = mock(TaskContext.class);
MetricsRegistry metricsRegistry = mock(MetricsRegistry.class);
Counter counter = mock(Counter.class);
coordinatorMock = mock(TaskCoordinator.class);
envelopeMock = mock(IncomingMessageEnvelope.class);
Config configMock = mock(Config.class);
deviceProfileCacheMock = mock(DeviceProfileCache.class);
stub(configMock.get("output.success.topic.name", SUCCESS_TOPIC)).toReturn(SUCCESS_TOPIC);
stub(configMock.get("output.failed.topic.name", FAILED_TOPIC)).toReturn(FAILED_TOPIC);
stub(configMock.get("output.malformed.topic.name", MALFORMED_TOPIC)).toReturn(MALFORMED_TOPIC);
stub(metricsRegistry.newCounter(anyString(), anyString())).toReturn(counter);
stub(contextMock.getMetricsRegistry()).toReturn(metricsRegistry);
stub(envelopeMock.getOffset()).toReturn("2");
stub(envelopeMock.getSystemStreamPartition())
.toReturn(new SystemStreamPartition("kafka", "input.topic", new Partition(1)));
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, deviceProfileCacheMock);
}
@Test
public void shouldSendEventsToSuccessTopicIfDidIsNull() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT_WITHOUT_DID);
stub(deviceProfileCacheMock.getDeviceProfileForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(null);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertFalse(outputEvent.containsKey("devicedata"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(false, flags.get("device_profile_retrieved"));
return true;
}
}));
}
/*
@Test
public void shouldSendEventsToSuccessTopicWithLocationFromDB() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
Map<String, String> resultFromCache = new HashMap<>();
stub(configMock.get("cassandra.keyspace")).toReturn("device_db");
stub(configMock.get("cassandra.device_profile_table")).toReturn("device_profile");
stub(configMock.get("redis.database.deviceLocationStore.id")).toReturn("1");
stub(configMock.get("location.db.redis.key.expiry.seconds")).toReturn("86400");
stub(configMock.get("cache.unresolved.location.key.expiry.seconds")).toReturn("3600");
// RedisConnect redisConnectMock = Mockito.mock(RedisConnect.class);
// CassandraConnect cassandraConnectMock = Mockito.mock(CassandraConnect.class);
DeviceLocationCache cache = Mockito.spy(new DeviceLocationCache(configMock, mock(JobMetrics.class)));
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, cache);
stub(deviceLocationCacheMock.getLocationFromCache("68dfc64a7751ad47617ac1a4e0531fb761ebea6f"))
.toReturn(resultFromCache);
DeviceProfile location = new DeviceProfile("IN", "India", "KA", "Karnataka",
"Bangalore","Banglore-Custom","Karnatak-Custom","KA-Custom");
stub(deviceLocationCacheMock.getLocationFromDeviceProfileDB("68dfc64a7751ad47617ac1a4e0531fb761ebea6f"))
.toReturn(location);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> context = new Gson().fromJson(outputEvent.get("devicedata").toString(), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("IN", context.get("countrycode"));
assertEquals("India", context.get("country"));
assertEquals("KA", context.get("statecode"));
assertEquals("Karnataka", context.get("state"));
assertEquals("Bangalore", context.get("city"));
assertEquals("KA-Custom", context.get("statecustomcode"));
assertEquals("Banglore-Custom", context.get("districtcustom"));
assertEquals("Karnatak-Custom", context.get("statecustomname"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(true, flags.get("device_location_retrieved"));
return true;
}
}));
}
*/
/*
@Test
public void shouldSendEventsToSuccessTopicWithStampingLocationFromChannelAPI() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(null);
DeviceProfile loc = new DeviceProfile();
loc.setCity("");
loc.setState("Karnataka");
stub(locationStoreCache.get("0123221617357783046602")).toReturn(null);
stub(searchService.searchChannelLocationId("0123221617357783046602")).toReturn("loc1");
stub(searchService.searchLocation("loc1")).toReturn(loc);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
assertEquals(outputEvent.get("ver"), "3.0");
assertEquals(outputMessage.contains("\"state\":\"Karnataka\""), true);
assertEquals(outputMessage.contains("\"district\":\"\""), true);
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(flags.get("device_location_retrieved"), true);
return true;
}
}));
}
*/
/*
@Test
@Ignore
public void shouldSendEventsToSuccessTopicWithStampingLocationFromLocalStore() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(null);
DeviceProfile loc = new DeviceProfile("IN", "India", "KA", "Karnataka", "Bangalore");
stub(locationStoreCache.get("0123221617357783046602")).toReturn(loc);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> context = new Gson().fromJson(new Gson().toJson(outputEvent.get("devicedata")), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("IN", context.get("countrycode"));
assertEquals("India", context.get("country"));
assertEquals("KA", context.get("statecode"));
assertEquals("Karnataka", context.get("state"));
assertEquals("Bangalore", context.get("city"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(true, flags.get("device_location_retrieved"));
Map<String, Object> edata = new Gson().fromJson(outputEvent.get("edata").toString(), mapType);
assertNull(edata.get("loc"));
return true;
}
}));
}
*/
@Test
public void shouldSendEventsToSuccessTopicIfFoundInCache() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
Map uaspec = new HashMap();
Map device_spec = new HashMap();
Long first_access = 1559484698000L;
device_spec.put("os", "Android 6.0");
device_spec.put("make", "Motorola XT1706");
uaspec.put("agent", "Mozilla");
uaspec.put("ver", "5.0");
uaspec.put("system", "iPad");
uaspec.put("platform", "AppleWebKit/531.21.10");
uaspec.put("raw", "Mozilla/5.0 (X11 Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)");
DeviceProfile deviceProfile = new DeviceProfile
("IN", "India", "KA", "Karnataka",
"Bangalore", "Banglore-Custom", "Karnatak-Custom",
"KA-Custom", uaspec, device_spec, first_access);
stub(deviceProfileCacheMock.getDeviceProfileForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f")).toReturn(deviceProfile);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>() {
}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertTrue(outputMessage.contains("\"countrycode\":\"IN\""));
assertTrue(outputMessage.contains("\"country\":\"India\""));
assertTrue(outputMessage.contains("\"statecode\":\"KA\""));
assertTrue(outputMessage.contains("\"state\":\"Karnataka\""));
assertTrue(outputMessage.contains("\"city\":\"Bangalore\""));
assertTrue(outputMessage.contains("\"statecustomcode\":\"KA-Custom\""));
assertTrue(outputMessage.contains("\"districtcustom\":\"Banglore-Custom\""));
assertTrue(outputMessage.contains("\"statecustomname\":\"Karnatak-Custom\""));
assertTrue(outputMessage.contains("\"iso3166statecode\":\"IN-KA\""));
assertTrue(outputMessage.contains("\"agent\":\"Mozilla\""));
assertTrue(outputMessage.contains("\"ver\":\"5.0\""));
assertTrue(outputMessage.contains("\"system\":\"iPad\""));
assertTrue(outputMessage.contains("\"os\":\"Android 6.0\""));
assertTrue(outputMessage.contains("\"make\":\"Motorola XT1706\""));
assertTrue(outputMessage.contains("\"platform\":\"AppleWebKit/531.21.10\""));
assertTrue(outputMessage.contains("\"raw\":\"Mozilla/5.0 (X11 Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)\""));
assertTrue(outputMessage.contains("\"firstaccess\":1559484698000"));
Map<String, Object> flags = new Gson().fromJson(outputEvent.get("flags").toString(), mapType);
assertEquals(true, flags.get("device_profile_retrieved"));
return true;
}
}));
}
@Test
public void shouldSendEventToFailedTopicIfEventIsNotParseable() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.UNPARSABLE_START_EVENT);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
verify(collectorMock).send(argThat(validateOutputTopic(envelopeMock.getMessage(), MALFORMED_TOPIC)));
}
@Test
public void shouldSendEventToMalformedTopicIfEventIsAnyRandomString() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.ANY_STRING);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
verify(collectorMock).send(argThat(validateOutputTopic(envelopeMock.getMessage(), MALFORMED_TOPIC)));
}
public ArgumentMatcher<OutgoingMessageEnvelope> validateOutputTopic(final Object message, final String stream) {
return new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
SystemStream systemStream = outgoingMessageEnvelope.getSystemStream();
assertEquals("kafka", systemStream.getSystem());
assertEquals(stream, systemStream.getStream());
return true;
}
};
}
/*
@Test
public void shouldSendEventsToSuccessTopicWithUserLocation() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
DeviceProfile loc1 = new DeviceProfile("IN", "India", "KA", "Karnataka", "Bangalore");
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f",
"0123221617357783046602")).toReturn(loc1);
DeviceProfile loc2 = new DeviceProfile(null, null, null, "Tamil Nadu", null, "Chennai");
String userId = "393407b1-66b1-4c86-9080-b2bce9842886";
stub(userLocationCacheMock.getLocationByUser(userId)).toReturn(loc2);
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, locationEngine);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> userloc = new Gson().fromJson(new Gson().toJson(outputEvent.get("userdata")), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("Tamil Nadu", userloc.get("state"));
assertEquals("Chennai", userloc.get("district"));
return true;
}
}));
}
*/
/*
@Test
public void shouldNotAddUserLocationIfActorTypeIsNotUser() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT_WITH_ACTOR_AS_SYSTEM);
DeviceProfile loc1 = new DeviceProfile("IN", "India", "KA", "Karnataka", "Bangalore");
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f",
"0123221617357783046602")).toReturn(loc1);
DeviceProfile loc2 = new DeviceProfile(null, null, null, "<NAME>", null, "Chennai");
String userId = "393407b1-66b1-4c86-9080-b2bce9842886";
stub(userLocationCacheMock.getLocationByUser(userId)).toReturn(loc2);
// stub(locationEngineMock.getLocation("0123221617357783046602")).toReturn(loc2);
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, locationEngineMock);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Object userlocdata = outputEvent.get("userdata");
assertNull(userlocdata);
return true;
}
}));
}
*/
/*
@Test
public void shouldFallbackToIPLocationIfUserLocationIsNotResolved() throws Exception {
stub(envelopeMock.getMessage()).toReturn(EventFixture.INTERACT_EVENT);
DeviceProfile loc1 = new DeviceProfile("IN", "India", "KA", "Karnataka", null, "Mysore");
stub(deviceLocationCacheMock.getLocationForDeviceId("68dfc64a7751ad47617ac1a4e0531fb761ebea6f",
"0123221617357783046602")).toReturn(null);
String userId = "393407b1-66b1-4c86-9080-b2bce9842886";
stub(userLocationCacheMock.getLocationByUser(userId)).toReturn(null);
// stub(locationEngineMock.getLocation("0123221617357783046602")).toReturn(loc1);
stub(locationEngineMock.deviceLocationCache()).toReturn(deviceLocationCacheMock);
telemetryLocationUpdaterTask = new TelemetryLocationUpdaterTask(configMock, contextMock, locationEngineMock);
telemetryLocationUpdaterTask.process(envelopeMock, collectorMock, coordinatorMock);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
verify(collectorMock).send(argThat(new ArgumentMatcher<OutgoingMessageEnvelope>() {
@Override
public boolean matches(Object o) {
OutgoingMessageEnvelope outgoingMessageEnvelope = (OutgoingMessageEnvelope) o;
String outputMessage = (String) outgoingMessageEnvelope.getMessage();
Map<String, Object> outputEvent = new Gson().fromJson(outputMessage, mapType);
Map<String, Object> userloc = new Gson().fromJson(new Gson().toJson(outputEvent.get("userdata")), mapType);
assertEquals("3.0", outputEvent.get("ver"));
assertEquals("Karnataka", userloc.get("state"));
assertEquals("Mysore", userloc.get("district"));
return true;
}
}));
}
*/
}
| 18,860 | 0.760973 | 0.730068 | 386 | 47.870468 | 34.631348 | 127 | false | false | 0 | 0 | 0 | 0 | 64 | 0.006785 | 3.217617 | false | false | 4 |
ef4d302702fcdc9b1dc8eb7cd0cff06a10aab5c3 | 34,230,889,368,180 | 33be2e0598eaf0eba733b960b52e1ea94494838d | /day11-code/src/cn/itcast/demo04/MyOuter.java | 04e3f577caf555330b4b219c50c7220b9c28e1d2 | []
| no_license | nsbstu/basic-code | https://github.com/nsbstu/basic-code | bd47fcff055eed13832a03fd7a7acadc36ef272c | e00f533e6d81367c8275377e6cd7f4c9ba8a2003 | refs/heads/master | 2023-04-12T09:38:36.234000 | 2021-04-20T09:53:02 | 2021-04-20T09:53:02 | 359,740,208 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.itcast.demo04;
/*
局部内部类如果希望访问呢所在方法的局部变量,那么这个局部变量必须是final
从java8开始,只要局部变量事实不变,那么final关键字就可以省略
原因:
1.new的对象在堆里
2.局部变量跟着方法进栈
3.方法运行结束之后,局部变量立马消失
4.new出的对象在堆中持续存在,直到垃圾回收
*/
public class MyOuter {
public void methodOuter(){
final int num = 10;
//num = 20;
class Inner{
public void methodInner(){
System.out.println(num);
}
}
}
}
| UTF-8 | Java | 645 | java | MyOuter.java | Java | []
| null | []
| package cn.itcast.demo04;
/*
局部内部类如果希望访问呢所在方法的局部变量,那么这个局部变量必须是final
从java8开始,只要局部变量事实不变,那么final关键字就可以省略
原因:
1.new的对象在堆里
2.局部变量跟着方法进栈
3.方法运行结束之后,局部变量立马消失
4.new出的对象在堆中持续存在,直到垃圾回收
*/
public class MyOuter {
public void methodOuter(){
final int num = 10;
//num = 20;
class Inner{
public void methodInner(){
System.out.println(num);
}
}
}
}
| 645 | 0.615202 | 0.589074 | 21 | 19.047619 | 12.319077 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | false | false | 4 |
83c0f2a5cc1c3bf567e12297837ca346090c7cd5 | 36,017,595,748,787 | a7ad391e33d767a9091a304e4d9abd8b766f993c | /src/test/java/com/ycj/gpxqBySinaJsonTests.java | e27ef94fb3442fb2162bf95144bf66658f71b833 | []
| no_license | jingfujia/ycj | https://github.com/jingfujia/ycj | 1b10cc56491b8c1402a152707a48c290b255fe0e | 3ab7cdae97846549a6e96b2b138655d385ef871a | refs/heads/master | 2018-12-24T16:34:26.209000 | 2018-12-24T11:31:32 | 2018-12-24T11:31:32 | 115,517,633 | 0 | 0 | null | false | 2020-08-06T14:44:51 | 2017-12-27T12:12:51 | 2020-08-06T14:44:45 | 2020-08-06T14:44:50 | 10,341 | 0 | 0 | 3 | Java | false | false | package com.ycj;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.TestApplication;
import com.ycj.mapper.TGpMapper;
import com.ycj.service.GpUpdateService;
import com.ycj.service.GpxqService;
import com.ycj.utils.GupiaoJob;
import com.ycj.utils.IfengUtils;
import com.ycj.utils.SimpleMailUtil;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=TestApplication.class)
public class gpxqBySinaJsonTests {
@Autowired
TGpMapper gpmapper;
@Autowired
GpxqService gpxqService;
@Autowired
SimpleMailUtil simpleMailUtil;
@Autowired
IfengUtils fengUtils;
@Autowired
GupiaoJob gupiaoJob;
@Autowired
GpUpdateService gpupService;
@Test
public void contextLoads() throws Exception {
//gupiaoJob.getgupiaoBysinaJsonData(0, null);
gupiaoJob.getgupiaoBysinaJsonDataHour(0, null);
System.out.println("end");
}
}
| UTF-8 | Java | 1,030 | java | gpxqBySinaJsonTests.java | Java | []
| null | []
| package com.ycj;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.TestApplication;
import com.ycj.mapper.TGpMapper;
import com.ycj.service.GpUpdateService;
import com.ycj.service.GpxqService;
import com.ycj.utils.GupiaoJob;
import com.ycj.utils.IfengUtils;
import com.ycj.utils.SimpleMailUtil;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=TestApplication.class)
public class gpxqBySinaJsonTests {
@Autowired
TGpMapper gpmapper;
@Autowired
GpxqService gpxqService;
@Autowired
SimpleMailUtil simpleMailUtil;
@Autowired
IfengUtils fengUtils;
@Autowired
GupiaoJob gupiaoJob;
@Autowired
GpUpdateService gpupService;
@Test
public void contextLoads() throws Exception {
//gupiaoJob.getgupiaoBysinaJsonData(0, null);
gupiaoJob.getgupiaoBysinaJsonDataHour(0, null);
System.out.println("end");
}
}
| 1,030 | 0.81068 | 0.807767 | 41 | 24.121952 | 17.685871 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.195122 | false | false | 4 |
f187543325d633b14dc77ef42c6a4d1182df4d99 | 23,519,240,971,096 | 1b88e3de96b1c007a4fa4d83bd29bf44c8e28618 | /src/main/java/br/com/stefanini/clients/api/util/ClienteUtil.java | 9459972215d9cab6bf5d009d61081a62c9d33b35 | []
| no_license | danilodacosta/stefanini-clients-api | https://github.com/danilodacosta/stefanini-clients-api | 01d98953d8471de6867fd01d795696f1db07162f | ca92c4ae8bc80814cf0c4f45ca3cfb601a0d7067 | refs/heads/master | 2022-11-30T22:47:54.874000 | 2020-08-17T05:34:42 | 2020-08-17T05:34:42 | 288,016,825 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.stefanini.clients.api.util;
import java.time.LocalDate;
import br.com.stefanini.clients.api.data.exception.NegocioException;
public class ClienteUtil {
public static void isDataNascimentoValid(LocalDate dataNascimento) {
LocalDate dataAtual = LocalDate.now();
int compareValue = dataAtual.compareTo(dataNascimento);
if (compareValue < 0) {
throw new NegocioException("Data de Nascimento é Inválida.");
}
}
} | UTF-8 | Java | 445 | java | ClienteUtil.java | Java | []
| null | []
| package br.com.stefanini.clients.api.util;
import java.time.LocalDate;
import br.com.stefanini.clients.api.data.exception.NegocioException;
public class ClienteUtil {
public static void isDataNascimentoValid(LocalDate dataNascimento) {
LocalDate dataAtual = LocalDate.now();
int compareValue = dataAtual.compareTo(dataNascimento);
if (compareValue < 0) {
throw new NegocioException("Data de Nascimento é Inválida.");
}
}
} | 445 | 0.767494 | 0.765237 | 20 | 21.200001 | 25.640984 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | false | false | 4 |
025fa8274149590c57e43a687e683477ab648f30 | 16,260,746,216,845 | 07feef87de2edbe03fde5fd4591202d519385e1f | /Tool.java | f8e819cf040a3dc11bb7abe158d1e133ab7ada93 | []
| no_license | MartinKw92/Game | https://github.com/MartinKw92/Game | f22485fe3bc62a4e34ce6627faec5e074f01ee34 | eb0b2d0d18545e76352ad20e16cd7b343484b580 | refs/heads/master | 2021-08-22T23:54:19.863000 | 2017-12-01T19:34:33 | 2017-12-01T19:34:33 | 112,655,258 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Tool {
protected int hp;
protected int dp;
protected int ap;
public Tool(int apx, int dpx, int hpx) {
ap = apx;
dp = dpx;
hp = hpx;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getDp() {
return dp;
}
public void setDp(int dp) {
this.dp = dp;
}
public int getAp() {
return ap;
}
public void setAp(int ap) {
this.ap = ap;
}
@Override
public String toString() {
return "Tool{" +
"hp=" + hp +
", dp=" + dp +
", ap=" + ap +
'}';
}
}
| UTF-8 | Java | 722 | java | Tool.java | Java | []
| null | []
| public class Tool {
protected int hp;
protected int dp;
protected int ap;
public Tool(int apx, int dpx, int hpx) {
ap = apx;
dp = dpx;
hp = hpx;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getDp() {
return dp;
}
public void setDp(int dp) {
this.dp = dp;
}
public int getAp() {
return ap;
}
public void setAp(int ap) {
this.ap = ap;
}
@Override
public String toString() {
return "Tool{" +
"hp=" + hp +
", dp=" + dp +
", ap=" + ap +
'}';
}
}
| 722 | 0.415512 | 0.415512 | 47 | 14.361702 | 11.786082 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361702 | false | false | 4 |
de7f898bd3a10df58f048fcbcefe6efbeb737361 | 13,022,340,910,565 | dcafe642e79f55c03a94e414179569cfaaabd00b | /Student_Information_System/src/edu/iiitb/sis/actions/admin/courses/AdminViewSemesterCourse.java | efa947227d52af3cde145e0d984e81651437fab2 | []
| no_license | tanushreevinayak/work | https://github.com/tanushreevinayak/work | c2e5ec446e7cb9bc33a0b910fdef5ee53800fa25 | 576ee5c88bd9fcb6eb88de5ff264949078d92785 | refs/heads/master | 2021-01-19T14:30:18.771000 | 2015-03-30T17:05:05 | 2015-03-30T17:05:05 | 29,516,509 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.iiitb.sis.actions.admin.courses;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import edu.iiitb.sis.actions.authentication.SessionBean;
import edu.iiitb.sis.dao.admin.courses.AddSemesterDao;
import edu.iiitb.sis.dao.student.ViewCoursesDao;
import edu.iiitb.sis.dao.student.ViewSemesterCoursesDao;
import edu.iiitb.sis.model.CourseModel;
import edu.iiitb.sis.model.ViewSemesterCourseModel;
public class AdminViewSemesterCourse extends ActionSupport implements SessionAware,ModelDriven<ViewSemesterCourseModel>
{
private ViewSemesterCourseModel obj=new ViewSemesterCourseModel();
public ViewSemesterCourseModel getObj() {
return obj;
}
public void setObj(ViewSemesterCourseModel obj) {
this.obj = obj;
}
private static final long serialVersionUID = 1L;
private Map<String,Object> sessionMap=null;
private ArrayList<String> announcementList=new ArrayList<String>();
private ArrayList<String> newsList=new ArrayList<String>();
private String loginName;
private String message;
private SessionBean sessionBean;
private List<String> CourseList=new ArrayList<String>();
private List<String> CourseIdList=new ArrayList<String>();
private List<String> CourseCreditsList=new ArrayList<String>();
private AddSemesterDao viewSemesterCourses=new AddSemesterDao ();
public String execute()
{
System.out.println("going to dddddddddaaaaaooooooo classssssssss");
// courseList=viewCourses.getCourses();
// course=viewCourses.getSyllabus(course);
message="success";
viewSemesterCourses.getSemesterCourses(obj);
// setCourseList(obj.getCoursename(),obj.getCourseid(),obj.getCoursecredit());
setCourseIdList(obj.getCourseid());
setCourseList(obj.getCoursename());
setCourseCreditsList(obj.getCoursecredit());
// setCourseCreditsList(viewSemesterCourses.getSemesterCourses(obj));
// CourseList=viewSemesterCourses.getSemesterCourses(obj);
System.out.println("return ffffffffrrrrrrommmmm ddddddaaaoooo class");
System.out.println("action"+getCourseList());
System.out.println("action"+getCourseIdList());
// System.out.println("action"+obj.getCoursename());
// System.out.println("action"+obj.getCourseid());
// System.out.println("action"+obj.getCoursecredit());
return "success";
}
public void setSession(Map<String, Object> map)
{
this.sessionMap=map;
this.sessionBean=(SessionBean) sessionMap.get("Session");
setSessionValues();
}
//The following function sets the values with session values.
private void setSessionValues()
{
this.announcementList=sessionBean.getAnnouncementList();
this.newsList=sessionBean.getNewsList();
this.loginName=sessionBean.getUserName();
this.loggedInUser=sessionBean.getName();
}
private String loggedInUser;
public String getLoggedInUser()
{
return loggedInUser;
}
public void setLoggedInUser(String loggedInUser) {
this.loggedInUser = loggedInUser;
}
public ArrayList<String> getAnnouncementList() {
return announcementList;
}
public void setAnnouncementList(ArrayList<String> announcementList) {
this.announcementList = announcementList;
}
public ArrayList<String> getNewsList() {
return newsList;
}
public void setNewsList(ArrayList<String> newsList) {
this.newsList = newsList;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public ViewSemesterCourseModel getModel() {
return obj;
}
public List<String> getCourseList() {
return CourseList;
}
public void setCourseList(List<String> courseList) {
CourseList = courseList;
}
public List<String> getCourseCreditsList() {
return CourseCreditsList;
}
public void setCourseCreditsList(List<String> courseCreditsList) {
CourseCreditsList = courseCreditsList;
}
public List<String> getCourseIdList() {
return CourseIdList;
}
public void setCourseIdList(List<String> courseIdList) {
CourseIdList = courseIdList;
}
}
| UTF-8 | Java | 4,266 | java | AdminViewSemesterCourse.java | Java | []
| null | []
| package edu.iiitb.sis.actions.admin.courses;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import edu.iiitb.sis.actions.authentication.SessionBean;
import edu.iiitb.sis.dao.admin.courses.AddSemesterDao;
import edu.iiitb.sis.dao.student.ViewCoursesDao;
import edu.iiitb.sis.dao.student.ViewSemesterCoursesDao;
import edu.iiitb.sis.model.CourseModel;
import edu.iiitb.sis.model.ViewSemesterCourseModel;
public class AdminViewSemesterCourse extends ActionSupport implements SessionAware,ModelDriven<ViewSemesterCourseModel>
{
private ViewSemesterCourseModel obj=new ViewSemesterCourseModel();
public ViewSemesterCourseModel getObj() {
return obj;
}
public void setObj(ViewSemesterCourseModel obj) {
this.obj = obj;
}
private static final long serialVersionUID = 1L;
private Map<String,Object> sessionMap=null;
private ArrayList<String> announcementList=new ArrayList<String>();
private ArrayList<String> newsList=new ArrayList<String>();
private String loginName;
private String message;
private SessionBean sessionBean;
private List<String> CourseList=new ArrayList<String>();
private List<String> CourseIdList=new ArrayList<String>();
private List<String> CourseCreditsList=new ArrayList<String>();
private AddSemesterDao viewSemesterCourses=new AddSemesterDao ();
public String execute()
{
System.out.println("going to dddddddddaaaaaooooooo classssssssss");
// courseList=viewCourses.getCourses();
// course=viewCourses.getSyllabus(course);
message="success";
viewSemesterCourses.getSemesterCourses(obj);
// setCourseList(obj.getCoursename(),obj.getCourseid(),obj.getCoursecredit());
setCourseIdList(obj.getCourseid());
setCourseList(obj.getCoursename());
setCourseCreditsList(obj.getCoursecredit());
// setCourseCreditsList(viewSemesterCourses.getSemesterCourses(obj));
// CourseList=viewSemesterCourses.getSemesterCourses(obj);
System.out.println("return ffffffffrrrrrrommmmm ddddddaaaoooo class");
System.out.println("action"+getCourseList());
System.out.println("action"+getCourseIdList());
// System.out.println("action"+obj.getCoursename());
// System.out.println("action"+obj.getCourseid());
// System.out.println("action"+obj.getCoursecredit());
return "success";
}
public void setSession(Map<String, Object> map)
{
this.sessionMap=map;
this.sessionBean=(SessionBean) sessionMap.get("Session");
setSessionValues();
}
//The following function sets the values with session values.
private void setSessionValues()
{
this.announcementList=sessionBean.getAnnouncementList();
this.newsList=sessionBean.getNewsList();
this.loginName=sessionBean.getUserName();
this.loggedInUser=sessionBean.getName();
}
private String loggedInUser;
public String getLoggedInUser()
{
return loggedInUser;
}
public void setLoggedInUser(String loggedInUser) {
this.loggedInUser = loggedInUser;
}
public ArrayList<String> getAnnouncementList() {
return announcementList;
}
public void setAnnouncementList(ArrayList<String> announcementList) {
this.announcementList = announcementList;
}
public ArrayList<String> getNewsList() {
return newsList;
}
public void setNewsList(ArrayList<String> newsList) {
this.newsList = newsList;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public ViewSemesterCourseModel getModel() {
return obj;
}
public List<String> getCourseList() {
return CourseList;
}
public void setCourseList(List<String> courseList) {
CourseList = courseList;
}
public List<String> getCourseCreditsList() {
return CourseCreditsList;
}
public void setCourseCreditsList(List<String> courseCreditsList) {
CourseCreditsList = courseCreditsList;
}
public List<String> getCourseIdList() {
return CourseIdList;
}
public void setCourseIdList(List<String> courseIdList) {
CourseIdList = courseIdList;
}
}
| 4,266 | 0.771449 | 0.770511 | 155 | 26.522581 | 24.55549 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6 | false | false | 4 |
ade0f03936f44862d2b72754186870b40ce316d9 | 18,107,582,146,937 | 504dfb2ca40c2c99b200a4177134c78274235f40 | /app/src/main/java/com/extenddev/railway/pcm/Data/AgentData/Data.java | 1574b0bf1f7f4a8535af5d7790254e16b42de4bf | []
| no_license | NehadSayedEg/rr | https://github.com/NehadSayedEg/rr | 670378f3c93db72fcd2670c6c60abc29e6cc9061 | ddd551d471dc01b34dec65ceb9d931f91713c8cd | refs/heads/master | 2020-09-08T18:41:43.106000 | 2019-11-12T12:29:43 | 2019-11-12T12:29:43 | 221,212,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.extenddev.railway.pcm.Data.AgentData;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Data {
@SerializedName("AgentList")
@Expose
private List< AgentList > agentList ;
@SerializedName("AgentRoleList")
@Expose
private List< AgentRoleList > agentRoleList ;
@SerializedName("EquipmentPermList")
@Expose
private List< EquipmentPermList > equipmentPermList;
@SerializedName("AgenDescList")
@Expose
private List< AgenDescList > agenDescList ;
public Data(){}
public Data(List<AgentList> agentList, List<AgentRoleList> agentRoleList
, List<EquipmentPermList> equipmentPermList, List<AgenDescList> agenDescList) {
this.agentList = agentList;
this.agentRoleList = agentRoleList;
this.equipmentPermList = equipmentPermList;
this.agenDescList = agenDescList;
}
public List<AgentList> getAgentList() {
return agentList;
}
public void setAgentList(List<AgentList> agentList) {
this.agentList = agentList;
}
public List<AgentRoleList> getAgentRoleList() {
return agentRoleList;
}
public void setAgentRoleList(List<AgentRoleList> agentRoleList) {
this.agentRoleList = agentRoleList;
}
public List<EquipmentPermList> getEquipmentPermList() {
return equipmentPermList;
}
public void setEquipmentPermList(List<EquipmentPermList> equipmentPermList) {
this.equipmentPermList = equipmentPermList;
}
public List<AgenDescList> getAgenDescList() {
return agenDescList;
}
public void setAgenDescList(List<AgenDescList> agenDescList) {
this.agenDescList = agenDescList;
}
}
| UTF-8 | Java | 1,808 | java | Data.java | Java | []
| null | []
|
package com.extenddev.railway.pcm.Data.AgentData;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Data {
@SerializedName("AgentList")
@Expose
private List< AgentList > agentList ;
@SerializedName("AgentRoleList")
@Expose
private List< AgentRoleList > agentRoleList ;
@SerializedName("EquipmentPermList")
@Expose
private List< EquipmentPermList > equipmentPermList;
@SerializedName("AgenDescList")
@Expose
private List< AgenDescList > agenDescList ;
public Data(){}
public Data(List<AgentList> agentList, List<AgentRoleList> agentRoleList
, List<EquipmentPermList> equipmentPermList, List<AgenDescList> agenDescList) {
this.agentList = agentList;
this.agentRoleList = agentRoleList;
this.equipmentPermList = equipmentPermList;
this.agenDescList = agenDescList;
}
public List<AgentList> getAgentList() {
return agentList;
}
public void setAgentList(List<AgentList> agentList) {
this.agentList = agentList;
}
public List<AgentRoleList> getAgentRoleList() {
return agentRoleList;
}
public void setAgentRoleList(List<AgentRoleList> agentRoleList) {
this.agentRoleList = agentRoleList;
}
public List<EquipmentPermList> getEquipmentPermList() {
return equipmentPermList;
}
public void setEquipmentPermList(List<EquipmentPermList> equipmentPermList) {
this.equipmentPermList = equipmentPermList;
}
public List<AgenDescList> getAgenDescList() {
return agenDescList;
}
public void setAgenDescList(List<AgenDescList> agenDescList) {
this.agenDescList = agenDescList;
}
}
| 1,808 | 0.69469 | 0.69469 | 72 | 23.944445 | 24.506172 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.319444 | false | false | 4 |
eb77901a05131130ea164aaa15f1b01162146d41 | 34,316,788,720,496 | 7300a5ec82faa11ee897f7b6b8faf81ca8f83954 | /TestSortedQueue.java | 25299560ec50dc51b9f4eb68b6266e2e3f75faed | []
| no_license | Kzaiser/project4_Java | https://github.com/Kzaiser/project4_Java | 09861adc5fd06ca31974e1aeea5b05a57356714a | 0b25b4db0af82d4de1c668fa1343356a499489fd | refs/heads/master | 2021-01-16T03:23:13.047000 | 2020-03-05T04:55:15 | 2020-03-05T04:55:15 | 242,960,515 | 0 | 0 | null | false | 2020-02-27T08:53:39 | 2020-02-25T09:29:20 | 2020-02-27T08:51:34 | 2020-02-27T08:53:39 | 37 | 0 | 0 | 0 | Java | false | false | // import java.lang.reflect.Member;
import java.util.Random;
import java.util.*;
public class TestSortedQueue {
public static void main(String args[]) {
MySortedQueue<Integer> sQueue = new MySortedQueue<Integer>();
// Member m = new Member();
sQueue.enque(3);
sQueue.enque(2);
sQueue.enque(1);
//queue.enQueue("fuck");
sQueue.enque(4);
sQueue.deque(3);
// sQueue.head();
//queue.enQueue("fuck3");
//first one is fuck4
//queue.enQueue("fuck4");
//queue.enQueue("fuck5");
//last one is fuck6
//sQueue.deque("1");
//queue.deQueue();
//sQueue.front();
Iterator<Integer> itr = sQueue.iterator();
// int pos = 0;
while(itr.hasNext()) {
System.out.println(itr.next() + "");
}
}
} | UTF-8 | Java | 881 | java | TestSortedQueue.java | Java | []
| null | []
| // import java.lang.reflect.Member;
import java.util.Random;
import java.util.*;
public class TestSortedQueue {
public static void main(String args[]) {
MySortedQueue<Integer> sQueue = new MySortedQueue<Integer>();
// Member m = new Member();
sQueue.enque(3);
sQueue.enque(2);
sQueue.enque(1);
//queue.enQueue("fuck");
sQueue.enque(4);
sQueue.deque(3);
// sQueue.head();
//queue.enQueue("fuck3");
//first one is fuck4
//queue.enQueue("fuck4");
//queue.enQueue("fuck5");
//last one is fuck6
//sQueue.deque("1");
//queue.deQueue();
//sQueue.front();
Iterator<Integer> itr = sQueue.iterator();
// int pos = 0;
while(itr.hasNext()) {
System.out.println(itr.next() + "");
}
}
} | 881 | 0.522134 | 0.508513 | 34 | 24.941177 | 15.40806 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617647 | false | false | 4 |
63aedb32b1ea3467fc08a01116f9b3cff4ca2a11 | 32,624,571,643,566 | 98e87559138ebe51739e775b17b3a27134242bc0 | /src/Program1/PerformanceTest.java | 921eb98e2ebc31b1bfd9106c3a7540d7e07bc2f4 | []
| no_license | Marcin-Stan/TSP | https://github.com/Marcin-Stan/TSP | a28e5d79a149448151a76d409a60625b97c82a40 | ef3249c785f0848ad345c294ca10a884719a5df8 | refs/heads/master | 2023-03-09T19:01:18.659000 | 2021-02-25T07:57:42 | 2021-02-25T07:57:42 | 342,164,581 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Program1;
import java.util.ArrayList;
import java.util.Random;
public class PerformanceTest {
public static void getTest(int numberofCities){
Random random = new Random();
ArrayList<City> cities = new ArrayList<>();
for(int i=0;i<numberofCities;i++){
double x = random.nextDouble()*(300-1)+1;
double y = random.nextDouble()*(300-1)+1;
Character ch = (char) ('A'+i);
cities.add(new City(x,y,ch.toString()));
}
printResults(cities);
}
private static void printResults( ArrayList<City> cities){
DFS dfs = new DFS();
BFS bfs = new BFS();
KNN knn = new KNN();
AStar aStar = new AStar();
System.out.println("Test wydajnosci dla "+cities.size()+" miast");
System.out.println("DFS");
dfs.printPerformanceTest(cities);
System.out.println("");
System.out.println("BFS");
bfs.printPerformanceTest(cities);
System.out.println("");
System.out.println("KNN");
knn.printPerformanceTest(cities);
System.out.println("");
System.out.println("ASTAR");
aStar.printPerformanceTest(cities);
System.out.println("");
}
}
| UTF-8 | Java | 1,297 | java | PerformanceTest.java | Java | []
| null | []
| package Program1;
import java.util.ArrayList;
import java.util.Random;
public class PerformanceTest {
public static void getTest(int numberofCities){
Random random = new Random();
ArrayList<City> cities = new ArrayList<>();
for(int i=0;i<numberofCities;i++){
double x = random.nextDouble()*(300-1)+1;
double y = random.nextDouble()*(300-1)+1;
Character ch = (char) ('A'+i);
cities.add(new City(x,y,ch.toString()));
}
printResults(cities);
}
private static void printResults( ArrayList<City> cities){
DFS dfs = new DFS();
BFS bfs = new BFS();
KNN knn = new KNN();
AStar aStar = new AStar();
System.out.println("Test wydajnosci dla "+cities.size()+" miast");
System.out.println("DFS");
dfs.printPerformanceTest(cities);
System.out.println("");
System.out.println("BFS");
bfs.printPerformanceTest(cities);
System.out.println("");
System.out.println("KNN");
knn.printPerformanceTest(cities);
System.out.println("");
System.out.println("ASTAR");
aStar.printPerformanceTest(cities);
System.out.println("");
}
}
| 1,297 | 0.562066 | 0.552814 | 47 | 26.595745 | 20.687811 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659574 | false | false | 4 |
c8ab12a2de751398ac3e9ddce9824a55f200b490 | 35,278,861,386,722 | 27882c0eb961f574e2dbab8ac6e57ac5770f1e49 | /src/main/java/com/clanjhoo/vampire/listeners/WerewolvesSilverHook.java | c4fcbe86d9ffa4a1469f2a959ed7f373a2ebfeeb | []
| no_license | Mowstyl/Vampire | https://github.com/Mowstyl/Vampire | bd4f4dfa243cb22de41e70e62a0ffb0ab5856928 | 68f028205a87375e79af2dfa90b96123f6014ea7 | refs/heads/master | 2023-07-16T20:17:22.705000 | 2023-06-27T21:55:03 | 2023-06-27T21:55:03 | 179,697,940 | 4 | 5 | null | true | 2023-06-09T14:36:20 | 2019-04-05T14:31:45 | 2023-02-17T14:15:23 | 2023-04-04T17:47:08 | 3,286 | 4 | 5 | 1 | Java | false | false | package com.clanjhoo.vampire.listeners;
import com.clanjhoo.vampire.VampireRevamp;
import com.clanjhoo.vampire.entity.VPlayer;
import com.clanjhoo.vampire.util.EntityUtil;
import com.clanjhoo.vampire.util.EventUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import java.util.logging.Level;
public class WerewolvesSilverHook implements Listener {
private boolean initialized = false;
private boolean initialize() {
boolean isWerewolfEnabled = Bukkit.getPluginManager().isPluginEnabled("Werewolf");
if (!isWerewolfEnabled)
HandlerList.unregisterAll(this);
initialized = true;
return isWerewolfEnabled;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onSilverSword(EntityDamageByEntityEvent event) {
if (!(event.getEntity() instanceof Player))
return;
if (!initialized) {
if (!initialize())
return;
VampireRevamp.log(Level.INFO, "Enabled Werewolves silver compatibility!");
}
if (!VampireRevamp.getVampireConfig().compatibility.useWerewolfSilverSword)
return;
if (!EntityUtil.isPlayer(event.getEntity()))
return;
if (!EventUtil.isCloseCombatEvent(event))
return;
try {
VPlayer uplayer = VampireRevamp.getVPlayerManager().tryGetDataNow(event.getEntity().getUniqueId());
if (!uplayer.isVampire())
return;
}
catch (AssertionError ex) {
VampireRevamp.log(Level.WARNING, "Couldn't get data of player " + event.getEntity().getName());
return;
}
Entity rawDamager = EventUtil.getLiableDamager(event);
if (!(rawDamager instanceof LivingEntity))
return;
LivingEntity damager = (LivingEntity) rawDamager;
if (damager.getEquipment() == null)
return;
ItemStack weapon = damager.getEquipment().getItemInMainHand();
boolean isSilverSword = VampireRevamp.getWerewolvesCompat().isSilverSword(weapon);
if (!isSilverSword)
return;
VampireRevamp.debugLog(Level.INFO, "Silver sword used! Scaling damage...");
EventUtil.scaleDamage(event, VampireRevamp.getVampireConfig().compatibility.silverDamageFactor);
}
}
| UTF-8 | Java | 2,679 | java | WerewolvesSilverHook.java | Java | []
| null | []
| package com.clanjhoo.vampire.listeners;
import com.clanjhoo.vampire.VampireRevamp;
import com.clanjhoo.vampire.entity.VPlayer;
import com.clanjhoo.vampire.util.EntityUtil;
import com.clanjhoo.vampire.util.EventUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import java.util.logging.Level;
public class WerewolvesSilverHook implements Listener {
private boolean initialized = false;
private boolean initialize() {
boolean isWerewolfEnabled = Bukkit.getPluginManager().isPluginEnabled("Werewolf");
if (!isWerewolfEnabled)
HandlerList.unregisterAll(this);
initialized = true;
return isWerewolfEnabled;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onSilverSword(EntityDamageByEntityEvent event) {
if (!(event.getEntity() instanceof Player))
return;
if (!initialized) {
if (!initialize())
return;
VampireRevamp.log(Level.INFO, "Enabled Werewolves silver compatibility!");
}
if (!VampireRevamp.getVampireConfig().compatibility.useWerewolfSilverSword)
return;
if (!EntityUtil.isPlayer(event.getEntity()))
return;
if (!EventUtil.isCloseCombatEvent(event))
return;
try {
VPlayer uplayer = VampireRevamp.getVPlayerManager().tryGetDataNow(event.getEntity().getUniqueId());
if (!uplayer.isVampire())
return;
}
catch (AssertionError ex) {
VampireRevamp.log(Level.WARNING, "Couldn't get data of player " + event.getEntity().getName());
return;
}
Entity rawDamager = EventUtil.getLiableDamager(event);
if (!(rawDamager instanceof LivingEntity))
return;
LivingEntity damager = (LivingEntity) rawDamager;
if (damager.getEquipment() == null)
return;
ItemStack weapon = damager.getEquipment().getItemInMainHand();
boolean isSilverSword = VampireRevamp.getWerewolvesCompat().isSilverSword(weapon);
if (!isSilverSword)
return;
VampireRevamp.debugLog(Level.INFO, "Silver sword used! Scaling damage...");
EventUtil.scaleDamage(event, VampireRevamp.getVampireConfig().compatibility.silverDamageFactor);
}
}
| 2,679 | 0.681598 | 0.681598 | 76 | 34.25 | 28.137877 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592105 | false | false | 4 |
91ae5fc8cce5d2618681560172fae626a51cbe70 | 35,278,861,385,726 | be164ac6cc3629f43e1c0da92b0c79d8e0799e90 | /java/source/com/vmail/cache/AcArmCacheRegistry.java | ccad0157ea3ca03aa4769164eb7eee4e709443c9 | []
| no_license | pabplanalp/pvmail | https://github.com/pabplanalp/pvmail | da51b664e17f60dfae9f64764d23e2e150adad10 | 06e75afc0181a416146bd351d37a4045e8656fc4 | refs/heads/master | 2019-04-20T14:12:17.573000 | 2013-07-19T19:22:31 | 2013-07-19T19:22:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vmail.cache;
import com.vmail.cache.base.AcArmCacheRegistryBase;
/**
* The concrete subclass for the arm cache registry. This is stubbed automatically
* and provides a place to extend the auto-generated registry.
*/
public class AcArmCacheRegistry
extends AcArmCacheRegistryBase
{
//##################################################
//# constructor
//##################################################//
public AcArmCacheRegistry(String armCode)
{
super(armCode);
}
}
| UTF-8 | Java | 521 | java | AcArmCacheRegistry.java | Java | []
| null | []
| package com.vmail.cache;
import com.vmail.cache.base.AcArmCacheRegistryBase;
/**
* The concrete subclass for the arm cache registry. This is stubbed automatically
* and provides a place to extend the auto-generated registry.
*/
public class AcArmCacheRegistry
extends AcArmCacheRegistryBase
{
//##################################################
//# constructor
//##################################################//
public AcArmCacheRegistry(String armCode)
{
super(armCode);
}
}
| 521 | 0.573896 | 0.573896 | 20 | 25.049999 | 25.330763 | 83 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 4 |
66e01768bfc2139091ea28793c5bdf600f868904 | 6,708,738,950,900 | 83e2566eb9ac46b55be7fa22469ab8cca2c51685 | /src/main/java/com/Imtiyaaz/Question5/AbstractFactory/NewWorld.java | 5c4c01ec9e9aca70573e4621724ccf79f0595765 | []
| no_license | Imtiyaaz1234/TPAssignment5 | https://github.com/Imtiyaaz1234/TPAssignment5 | 5f0bd810baec3b94fabec3f1ff89dfef20aeed1a | b4bdb133cd3ffc406a35f4d671b95f34bf34d717 | refs/heads/master | 2021-01-18T20:29:44.929000 | 2017-04-02T08:10:18 | 2017-04-02T08:10:18 | 86,972,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.Imtiyaaz.Question5.AbstractFactory;
/**
* Created by Imtiyaaz on 2017/04/01.
*/
public class NewWorld implements World {
public People createPeople(){
return new DifferentPeople();
}
public House createHouse(){
return new DifferentHouse();
}
public Boss createBoss(){
return new DifferentBoss();
}
public World createWorld() {
return null;
}
}
| UTF-8 | Java | 428 | java | NewWorld.java | Java | [
{
"context": "yaaz.Question5.AbstractFactory;\n\n/**\n * Created by Imtiyaaz on 2017/04/01.\n */\npublic class NewWorld implemen",
"end": 75,
"score": 0.9816449284553528,
"start": 67,
"tag": "USERNAME",
"value": "Imtiyaaz"
}
]
| null | []
| package com.Imtiyaaz.Question5.AbstractFactory;
/**
* Created by Imtiyaaz on 2017/04/01.
*/
public class NewWorld implements World {
public People createPeople(){
return new DifferentPeople();
}
public House createHouse(){
return new DifferentHouse();
}
public Boss createBoss(){
return new DifferentBoss();
}
public World createWorld() {
return null;
}
}
| 428 | 0.630841 | 0.609813 | 24 | 16.833334 | 16.709944 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.208333 | false | false | 4 |
29f9a8b9a8ec02a015d637c51f814e23249d9c55 | 8,701,603,770,793 | 6c88543975e389c14ef91fad5cf529ff3361df39 | /src/main/java/com/ignacio/vila/linux/shell/presenter/DirectoryPresenter.java | c2d8d981bd944864d3a34d8ab32362a13c3bbd0c | []
| no_license | ignaciovilagraca/linux-shell | https://github.com/ignaciovilagraca/linux-shell | f5b6122ac445352f6b7fe0f1239aeda37dd1fb95 | 26748ccb9f3935439bcafd4c463f39adb53cc76a | refs/heads/master | 2023-02-18T23:03:52.991000 | 2021-01-22T21:07:12 | 2021-01-22T21:07:12 | 296,939,329 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ignacio.vila.linux.shell.presenter;
import com.ignacio.vila.linux.shell.model.directory.Directory;
import java.util.List;
public class DirectoryPresenter {
public void present(Directory directory) {
List<String> outputs = directory.present();
outputs.forEach(System.out::println);
}
public void presentRecursively(Directory directory) {
List<String> outputs = directory.presentRecursively();
outputs.forEach(System.out::println);
}
}
| UTF-8 | Java | 498 | java | DirectoryPresenter.java | Java | []
| null | []
| package com.ignacio.vila.linux.shell.presenter;
import com.ignacio.vila.linux.shell.model.directory.Directory;
import java.util.List;
public class DirectoryPresenter {
public void present(Directory directory) {
List<String> outputs = directory.present();
outputs.forEach(System.out::println);
}
public void presentRecursively(Directory directory) {
List<String> outputs = directory.presentRecursively();
outputs.forEach(System.out::println);
}
}
| 498 | 0.718876 | 0.718876 | 17 | 28.294117 | 24.16552 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 4 |
ad933bb9b2de1b8fea2b1a8c89309429432ff6b1 | 10,376,641,027,972 | c9c11256deb315d5632fcb9cef05f0832ebedd25 | /app/src/main/java/com/example/cool/loginpro/LoginUserDetailsActivity.java | 24b51969e86e52c6fc7aa1a273d83666a2b57161 | []
| no_license | Satyamp32/LoginProject | https://github.com/Satyamp32/LoginProject | 18ec48b80af7dcec70e24cd8ef7a196ab9e1086e | 5ec01b86a90c3f07e1a86c0df9327f95c1e090a4 | refs/heads/master | 2020-03-25T20:48:50.290000 | 2018-08-09T12:07:03 | 2018-08-09T12:07:03 | 144,147,363 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.cool.loginpro;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.util.Patterns;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class LoginUserDetailsActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener {
DatePickerDialog picker;
private static final int PICTURE_SELECTED = 1;
private Button mEdit,mUpdate;
private EditText mFirstName, mLastName, mEmail, mPassword, mMobileNo, mDob, mId;
private DatabaseHelper databaseHelper;
private User user;
private DatePickerDialog datePickerDialog;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private TextView nav_username,nav_email;
private ImageView imageView,nav_image;
String emailFromPref,email,emailFromIntent;
TextView error;
Bitmap bitmap;
String finalDateOfBirth ="";
private Uri filePath;
private static final int PICK_IMAGE_REQUEST = 234;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_user_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
gettingMail();
emailFromIntent = getIntent().getStringExtra("EMAIL");
initViews();
initListeners();
falseEditText();
trueEditText();
initObjects();
mDob.setKeyListener(null);
if(emailFromPref.isEmpty())
{
email=emailFromIntent;
}
else
email=emailFromPref;
getAllCandidate();
//mEdit.setVisibility(View.VISIBLE);
//mUpdate.setVisibility(View.GONE);
}
public void gettingMail()
{
emailFromPref= new UserPerfManager(this).getEmail();
}
private void initViews() {
error=(TextView)findViewById(R.id.error1);
mId = (EditText) findViewById(R.id.editTextId);
imageView = (ImageView) findViewById(R.id.imageview3);
mEdit = (Button) findViewById(R.id.buttonEdit);
mUpdate = (Button) findViewById(R.id.buttonUpdate);
mFirstName = (EditText) findViewById(R.id.editTextFirstname);
mLastName = (EditText) findViewById(R.id.editTextLastname);
mEmail = (EditText) findViewById(R.id.editTextEmail_id);
mPassword = (EditText) findViewById(R.id.editTextPassword);
mMobileNo = (EditText) findViewById(R.id.editTextPhone_number);
mDob = (EditText) findViewById(R.id.editTextDate_of_birth);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
nav_username=(TextView)navigationView.getHeaderView(0).findViewById(R.id.nav_username);
nav_email=(TextView)navigationView.getHeaderView(0).findViewById(R.id.nav_email);
nav_image=(ImageView)navigationView.getHeaderView(0).findViewById(R.id.imageView1);
}
private void initListeners() {
mEdit.setOnClickListener( this);
mUpdate.setOnClickListener( this);
imageView.setOnClickListener( this);
mDob.setOnClickListener( this);
navigationView.setNavigationItemSelectedListener(this);
}
private void initObjects() {
databaseHelper = new DatabaseHelper(this);
user = new User();
}
// public void edit(View view) {
// Intent intent = new Intent(LoginUserDetailsActivity.this, UpdateDetailsActivity.class);
// startActivity(intent);
// }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_user_details, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout1:
alertDialog();
break;
case R.id.home:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonEdit:
trueEditText();
mEdit.setVisibility(View.GONE);
mUpdate.setVisibility(View.VISIBLE);
break;
case R.id.buttonUpdate:
updateButton();
//falseEditText();
break;
case R.id.imageview3:
selectProfileImage();
break;
case R.id.editTextDate_of_birth:
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(LoginUserDetailsActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mDob.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
finalDateOfBirth= mDob.getText().toString();
}
}, year, month, day);
picker.show();
break;
}
}
private void falseEditText() {
imageView.setEnabled(false);
mId.setEnabled(false);
mFirstName.setEnabled(false);
mLastName.setEnabled(false);
mEmail.setEnabled(false);
mPassword.setEnabled(false);
mMobileNo.setEnabled(false);
mDob.setEnabled(false);
}
private void trueEditText() {
imageView.setEnabled(true);
mId.setEnabled(true);
mFirstName.setEnabled(true);
mLastName.setEnabled(true);
mEmail.setEnabled(true);
mPassword.setEnabled(true);
mMobileNo.setEnabled(true);
mDob.setEnabled(true);
}
public void gallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
Log.d("filepath",filePath.getPath());
Log.d("Bitmap", String.valueOf(bitmap));
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader (bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
imageView.setImageBitmap(circleBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void updateButton() {
String fname=mFirstName.getText().toString();
String lname=mLastName.getText().toString();
String password=mPassword.getText().toString();
String dateofbirth=mDob.getText().toString();
String phoneNo =mMobileNo.getText().toString();
String email =mEmail.getText().toString();
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
bitmap=imageView.getDrawingCache();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
byte [] data=outputStream.toByteArray();
error.setVisibility(View.INVISIBLE);
mFirstName.setCursorVisible(true);
mLastName.setCursorVisible(true);
mEmail.setCursorVisible(true);
mDob.setCursorVisible(true);
mMobileNo.setCursorVisible(true);
mPassword.setCursorVisible(true);
/*if(finalDateOfBirth.isEmpty())
{
mDob.setError("date is mandatory");
}*/
if(imageView.getDrawable() ==null )
{
mFirstName.setCursorVisible(false);
mLastName.setCursorVisible(false);
mEmail.setCursorVisible(false);
mDob.setCursorVisible(false);
mMobileNo.setCursorVisible(false);
mPassword.setCursorVisible(false);
//textInputLayout.setError("image is mandatory");
Toast.makeText(getApplicationContext(),"image is mandatory",Toast.LENGTH_LONG).show();
error.setVisibility(View.VISIBLE);
}
else if (fname.equals("")&& imageView.getDrawable()!=null )
{
mFirstName.setError("First Name is Mandatory");
}
else if(lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mLastName.setError("Last Name is Mandatory");
}
else if(email.equals("")|| !Patterns.EMAIL_ADDRESS.matcher(email).matches() && !lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mEmail.setError("Enter Correct Email Format");
}
else if(phoneNo.equals("")||!Patterns.PHONE.matcher(phoneNo).matches() && !email.equals("")|| !Patterns.EMAIL_ADDRESS.matcher(email).matches() && !lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mMobileNo.setError(" Mobile Number is Mandatory");
}
else if (phoneNo.length()!=10 && !phoneNo.equals("")||!Patterns.PHONE.matcher(phoneNo).matches() && !email.equals("")|| !Patterns.EMAIL_ADDRESS.matcher(email).matches() && !lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mMobileNo.setError("Please Enter 10 digit Mobile Number");
}
else if(dateofbirth.equals(""))
{
mDob.setError("Date of birth is mandatory");
}
else if(password.equals(""))
{
mPassword.setError("Password is Mandatory");
}
{
user.setId(mId.getId());
user.setmFirstName(mFirstName.getText().toString().trim());
user.setmLastName(mLastName.getText().toString().trim());
user.setmDob(mDob.getText().toString().trim());
user.setmEmailId(mEmail.getText().toString().trim());
user.setmMobileNo(mMobileNo.getText().toString().trim());
user.setmPassword(mPassword.getText().toString().trim());
user.setImage(getStringImage(bitmap));
if (databaseHelper.updateCandidate(user,data)) {
Toast.makeText(LoginUserDetailsActivity.this, "updated successfully", Toast.LENGTH_LONG).show();
falseEditText();
mEdit.setVisibility(View.VISIBLE);
mUpdate.setVisibility(View.GONE);
}
else
{
Toast.makeText(LoginUserDetailsActivity.this, "Data not Updated", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onBackPressed() {
alertDialogBackPressed();
}
public void getAllCandidate() {
//String s = getIntent().getStringExtra("EMAIL");
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("Select * from durga WHERE candidate_email = '" + email + "'", null);
cursor.moveToFirst();
mId.setText(cursor.getString(0));
mFirstName.setText(cursor.getString(1));
mLastName.setText(cursor.getString(2));
mDob.setText(cursor.getString(3));
mEmail.setText(cursor.getString(4));
mMobileNo.setText(cursor.getString(5));
mPassword.setText(cursor.getString(6));
byte b[] = cursor.getBlob(7);
if (b != null) {
Bitmap bp = BitmapFactory.decodeByteArray(b, 0, b.length);
imageView.setImageBitmap(bp);
} else {
imageView.setImageResource(R.drawable.user_icon);
}
Bitmap bp = BitmapFactory.decodeByteArray(b, 0, b.length);
//setting user name and Email id of the user to navigation drawer header
nav_username.setText(cursor.getString(1));
nav_email.setText(cursor.getString(4));
nav_image.setImageBitmap(bp);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.logout_nav:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this,R.style.AppTheme2);
alertDialog.setTitle("Confirm Logout");
alertDialog.setMessage("Are you sure you want to Logout?");
alertDialog.setIcon(R.drawable.alert);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new UserPerfManager(getApplicationContext()).clear();
Intent intent = new Intent(LoginUserDetailsActivity.this, LoginActivity.class);
startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
break;
case R.id.nav_call:
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+919880447564"));
startActivity(intent);
break;
case R.id.nav_msg:
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addCategory(Intent.CATEGORY_APP_MESSAGING);
startActivity(intent1);
break;
case R.id.nav_email:
Intent intent2 = new Intent(Intent.ACTION_SENDTO);
//intent2.addCategory(Intent.CATEGORY_APP_EMAIL);
intent2.setData(Uri.parse("mailto:vgowthamteddy@gmail.com"));
startActivity(intent2);
break;
case R.id.webview_nav:
Intent intent3 = new Intent(LoginUserDetailsActivity.this,WebViewActivity.class);
startActivity(intent3);
break;
}
return false;
}
public String getStringImage(Bitmap bmp)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 85, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void alertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppTheme2);
builder.setTitle("Alert Dialog");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new UserPerfManager(getApplicationContext()).clear();
Intent intent = new Intent(LoginUserDetailsActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setMessage("Are You want to logout");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public void alertDialogBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppTheme2);
builder.setTitle("Alert Dialog");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setMessage("Are You want to Exit");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void requestCameraPermission() {
// Camera permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(LoginUserDetailsActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
0);
}
public void selectProfileImage()
{
//Toast.makeText(getApplicationContext(),"welcome",Toast.LENGTH_LONG).show();
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
requestCameraPermission();
gallery();
}
else{
//Toast.makeText(getApplicationContext(),"not working",Toast.LENGTH_LONG).show();
gallery();
}
}
} | UTF-8 | Java | 20,346 | java | LoginUserDetailsActivity.java | Java | [
{
"context": " mEdit,mUpdate;\n private EditText mFirstName, mLastName, mEmail, mPassword, mMobileNo, mDob, mId;\n pri",
"end": 1792,
"score": 0.566693902015686,
"start": 1784,
"tag": "NAME",
"value": "LastName"
},
{
"context": "ame.getText().toString();\n String password=mPassword.getText().toString();\n\n String dateofbirth=mDob.getText().toS",
"end": 9878,
"score": 0.9923579692840576,
"start": 9850,
"tag": "PASSWORD",
"value": "mPassword.getText().toString"
},
{
"context": " {\n mPassword.setError(\"Password is Mandatory\");\n }\n\n {\n user.setId(mI",
"end": 12738,
"score": 0.7017229795455933,
"start": 12729,
"tag": "PASSWORD",
"value": "Mandatory"
},
{
"context": " intent2.setData(Uri.parse(\"mailto:vgowthamteddy@gmail.com\"));\n startActivity(intent2);\n ",
"end": 17042,
"score": 0.999923825263977,
"start": 17019,
"tag": "EMAIL",
"value": "vgowthamteddy@gmail.com"
}
]
| null | []
| package com.example.cool.loginpro;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.util.Patterns;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class LoginUserDetailsActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener {
DatePickerDialog picker;
private static final int PICTURE_SELECTED = 1;
private Button mEdit,mUpdate;
private EditText mFirstName, mLastName, mEmail, mPassword, mMobileNo, mDob, mId;
private DatabaseHelper databaseHelper;
private User user;
private DatePickerDialog datePickerDialog;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private TextView nav_username,nav_email;
private ImageView imageView,nav_image;
String emailFromPref,email,emailFromIntent;
TextView error;
Bitmap bitmap;
String finalDateOfBirth ="";
private Uri filePath;
private static final int PICK_IMAGE_REQUEST = 234;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_user_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
gettingMail();
emailFromIntent = getIntent().getStringExtra("EMAIL");
initViews();
initListeners();
falseEditText();
trueEditText();
initObjects();
mDob.setKeyListener(null);
if(emailFromPref.isEmpty())
{
email=emailFromIntent;
}
else
email=emailFromPref;
getAllCandidate();
//mEdit.setVisibility(View.VISIBLE);
//mUpdate.setVisibility(View.GONE);
}
public void gettingMail()
{
emailFromPref= new UserPerfManager(this).getEmail();
}
private void initViews() {
error=(TextView)findViewById(R.id.error1);
mId = (EditText) findViewById(R.id.editTextId);
imageView = (ImageView) findViewById(R.id.imageview3);
mEdit = (Button) findViewById(R.id.buttonEdit);
mUpdate = (Button) findViewById(R.id.buttonUpdate);
mFirstName = (EditText) findViewById(R.id.editTextFirstname);
mLastName = (EditText) findViewById(R.id.editTextLastname);
mEmail = (EditText) findViewById(R.id.editTextEmail_id);
mPassword = (EditText) findViewById(R.id.editTextPassword);
mMobileNo = (EditText) findViewById(R.id.editTextPhone_number);
mDob = (EditText) findViewById(R.id.editTextDate_of_birth);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
nav_username=(TextView)navigationView.getHeaderView(0).findViewById(R.id.nav_username);
nav_email=(TextView)navigationView.getHeaderView(0).findViewById(R.id.nav_email);
nav_image=(ImageView)navigationView.getHeaderView(0).findViewById(R.id.imageView1);
}
private void initListeners() {
mEdit.setOnClickListener( this);
mUpdate.setOnClickListener( this);
imageView.setOnClickListener( this);
mDob.setOnClickListener( this);
navigationView.setNavigationItemSelectedListener(this);
}
private void initObjects() {
databaseHelper = new DatabaseHelper(this);
user = new User();
}
// public void edit(View view) {
// Intent intent = new Intent(LoginUserDetailsActivity.this, UpdateDetailsActivity.class);
// startActivity(intent);
// }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_user_details, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout1:
alertDialog();
break;
case R.id.home:
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonEdit:
trueEditText();
mEdit.setVisibility(View.GONE);
mUpdate.setVisibility(View.VISIBLE);
break;
case R.id.buttonUpdate:
updateButton();
//falseEditText();
break;
case R.id.imageview3:
selectProfileImage();
break;
case R.id.editTextDate_of_birth:
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(LoginUserDetailsActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mDob.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
finalDateOfBirth= mDob.getText().toString();
}
}, year, month, day);
picker.show();
break;
}
}
private void falseEditText() {
imageView.setEnabled(false);
mId.setEnabled(false);
mFirstName.setEnabled(false);
mLastName.setEnabled(false);
mEmail.setEnabled(false);
mPassword.setEnabled(false);
mMobileNo.setEnabled(false);
mDob.setEnabled(false);
}
private void trueEditText() {
imageView.setEnabled(true);
mId.setEnabled(true);
mFirstName.setEnabled(true);
mLastName.setEnabled(true);
mEmail.setEnabled(true);
mPassword.setEnabled(true);
mMobileNo.setEnabled(true);
mDob.setEnabled(true);
}
public void gallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
Log.d("filepath",filePath.getPath());
Log.d("Bitmap", String.valueOf(bitmap));
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader (bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
imageView.setImageBitmap(circleBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void updateButton() {
String fname=mFirstName.getText().toString();
String lname=mLastName.getText().toString();
String password=<PASSWORD>();
String dateofbirth=mDob.getText().toString();
String phoneNo =mMobileNo.getText().toString();
String email =mEmail.getText().toString();
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
bitmap=imageView.getDrawingCache();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
byte [] data=outputStream.toByteArray();
error.setVisibility(View.INVISIBLE);
mFirstName.setCursorVisible(true);
mLastName.setCursorVisible(true);
mEmail.setCursorVisible(true);
mDob.setCursorVisible(true);
mMobileNo.setCursorVisible(true);
mPassword.setCursorVisible(true);
/*if(finalDateOfBirth.isEmpty())
{
mDob.setError("date is mandatory");
}*/
if(imageView.getDrawable() ==null )
{
mFirstName.setCursorVisible(false);
mLastName.setCursorVisible(false);
mEmail.setCursorVisible(false);
mDob.setCursorVisible(false);
mMobileNo.setCursorVisible(false);
mPassword.setCursorVisible(false);
//textInputLayout.setError("image is mandatory");
Toast.makeText(getApplicationContext(),"image is mandatory",Toast.LENGTH_LONG).show();
error.setVisibility(View.VISIBLE);
}
else if (fname.equals("")&& imageView.getDrawable()!=null )
{
mFirstName.setError("First Name is Mandatory");
}
else if(lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mLastName.setError("Last Name is Mandatory");
}
else if(email.equals("")|| !Patterns.EMAIL_ADDRESS.matcher(email).matches() && !lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mEmail.setError("Enter Correct Email Format");
}
else if(phoneNo.equals("")||!Patterns.PHONE.matcher(phoneNo).matches() && !email.equals("")|| !Patterns.EMAIL_ADDRESS.matcher(email).matches() && !lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mMobileNo.setError(" Mobile Number is Mandatory");
}
else if (phoneNo.length()!=10 && !phoneNo.equals("")||!Patterns.PHONE.matcher(phoneNo).matches() && !email.equals("")|| !Patterns.EMAIL_ADDRESS.matcher(email).matches() && !lname.equals("") && !fname.equals("")&& imageView.getDrawable()!=null)
{
mMobileNo.setError("Please Enter 10 digit Mobile Number");
}
else if(dateofbirth.equals(""))
{
mDob.setError("Date of birth is mandatory");
}
else if(password.equals(""))
{
mPassword.setError("Password is <PASSWORD>");
}
{
user.setId(mId.getId());
user.setmFirstName(mFirstName.getText().toString().trim());
user.setmLastName(mLastName.getText().toString().trim());
user.setmDob(mDob.getText().toString().trim());
user.setmEmailId(mEmail.getText().toString().trim());
user.setmMobileNo(mMobileNo.getText().toString().trim());
user.setmPassword(mPassword.getText().toString().trim());
user.setImage(getStringImage(bitmap));
if (databaseHelper.updateCandidate(user,data)) {
Toast.makeText(LoginUserDetailsActivity.this, "updated successfully", Toast.LENGTH_LONG).show();
falseEditText();
mEdit.setVisibility(View.VISIBLE);
mUpdate.setVisibility(View.GONE);
}
else
{
Toast.makeText(LoginUserDetailsActivity.this, "Data not Updated", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onBackPressed() {
alertDialogBackPressed();
}
public void getAllCandidate() {
//String s = getIntent().getStringExtra("EMAIL");
databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("Select * from durga WHERE candidate_email = '" + email + "'", null);
cursor.moveToFirst();
mId.setText(cursor.getString(0));
mFirstName.setText(cursor.getString(1));
mLastName.setText(cursor.getString(2));
mDob.setText(cursor.getString(3));
mEmail.setText(cursor.getString(4));
mMobileNo.setText(cursor.getString(5));
mPassword.setText(cursor.getString(6));
byte b[] = cursor.getBlob(7);
if (b != null) {
Bitmap bp = BitmapFactory.decodeByteArray(b, 0, b.length);
imageView.setImageBitmap(bp);
} else {
imageView.setImageResource(R.drawable.user_icon);
}
Bitmap bp = BitmapFactory.decodeByteArray(b, 0, b.length);
//setting user name and Email id of the user to navigation drawer header
nav_username.setText(cursor.getString(1));
nav_email.setText(cursor.getString(4));
nav_image.setImageBitmap(bp);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.logout_nav:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this,R.style.AppTheme2);
alertDialog.setTitle("Confirm Logout");
alertDialog.setMessage("Are you sure you want to Logout?");
alertDialog.setIcon(R.drawable.alert);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new UserPerfManager(getApplicationContext()).clear();
Intent intent = new Intent(LoginUserDetailsActivity.this, LoginActivity.class);
startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
break;
case R.id.nav_call:
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+919880447564"));
startActivity(intent);
break;
case R.id.nav_msg:
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addCategory(Intent.CATEGORY_APP_MESSAGING);
startActivity(intent1);
break;
case R.id.nav_email:
Intent intent2 = new Intent(Intent.ACTION_SENDTO);
//intent2.addCategory(Intent.CATEGORY_APP_EMAIL);
intent2.setData(Uri.parse("mailto:<EMAIL>"));
startActivity(intent2);
break;
case R.id.webview_nav:
Intent intent3 = new Intent(LoginUserDetailsActivity.this,WebViewActivity.class);
startActivity(intent3);
break;
}
return false;
}
public String getStringImage(Bitmap bmp)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 85, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void alertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppTheme2);
builder.setTitle("Alert Dialog");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new UserPerfManager(getApplicationContext()).clear();
Intent intent = new Intent(LoginUserDetailsActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setMessage("Are You want to logout");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public void alertDialogBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppTheme2);
builder.setTitle("Alert Dialog");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setMessage("Are You want to Exit");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void requestCameraPermission() {
// Camera permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(LoginUserDetailsActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
0);
}
public void selectProfileImage()
{
//Toast.makeText(getApplicationContext(),"welcome",Toast.LENGTH_LONG).show();
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
requestCameraPermission();
gallery();
}
else{
//Toast.makeText(getApplicationContext(),"not working",Toast.LENGTH_LONG).show();
gallery();
}
}
} | 20,313 | 0.624693 | 0.620761 | 552 | 35.860508 | 31.257122 | 251 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.713768 | false | false | 4 |
327c20707181841e6caaf2e1a9b9b9a7d00a4660 | 28,415,503,668,752 | 1db016d7f1da09f4b385a12a2b8abe78a3c19868 | /Chapter-1 Arrays and Strings/stringCompress.java | dca7cf8204602b582257d5018b0088f82510e120 | []
| no_license | XiPu99/CtCI | https://github.com/XiPu99/CtCI | d06f62c0d9763608c4859af87dc12e87eea9e877 | 36e40296bc073afe4f271949e23c28b3f7ea2071 | refs/heads/master | 2020-03-29T03:14:48.817000 | 2019-01-17T03:01:35 | 2019-01-17T03:01:35 | 149,474,597 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Perform basic string compression using the counts of repeated
characters, eg. "aabcccccaaa" -> "a2b1c5a3". If the compressed
string is not smaller than the original string, the method should
return the original string.
*/
/*
Using a string instead of a stringbuilder will result in a time
complexity of O(p+k^2). p is the size of the input string s.
k is the size of character sequence in the compressed string.
It takes O(k^2) to concatenate a string of size k.
Using a stringbuilder can avoid this problem.
*/
public String compress(String s){
// use a string builder instead of a string
StringBuilder compressed = new StringBuilder();
char current = s.charAt(0);
int streak = 1;
for(int i = 1; i < s.length(); i++){
if(s.charAt(i)!=current){
compressed.append(current);
compressed.append(streak);
current = s.charAt(i);
streak = 1;
}
else{
streak++;
}
}
// i forgot to add the following two lines at the end
compressed.append(current);
compressed.append(streak);
return compressed.length()>=s.length() ? s : compressed.toString();
}
/*
A more concise version of the first approach
*/
public String compress(String s) {
StringBuilder compressed = new StringBuilder();
int streak = 0;
for(int i = 0; i < s.length(); i++) {
streak++;
if(((i+1)>=s.length())||(s.charAt(i)!=s.charAt(i+1))) {
compressed.append(s.charAt(i));
compressed.append(streak);
streak = 0;
}
}
return compressed.length()>=s.length() ? s : compressed.toString();
}
| UTF-8 | Java | 1,570 | java | stringCompress.java | Java | []
| null | []
| /*
Perform basic string compression using the counts of repeated
characters, eg. "aabcccccaaa" -> "a2b1c5a3". If the compressed
string is not smaller than the original string, the method should
return the original string.
*/
/*
Using a string instead of a stringbuilder will result in a time
complexity of O(p+k^2). p is the size of the input string s.
k is the size of character sequence in the compressed string.
It takes O(k^2) to concatenate a string of size k.
Using a stringbuilder can avoid this problem.
*/
public String compress(String s){
// use a string builder instead of a string
StringBuilder compressed = new StringBuilder();
char current = s.charAt(0);
int streak = 1;
for(int i = 1; i < s.length(); i++){
if(s.charAt(i)!=current){
compressed.append(current);
compressed.append(streak);
current = s.charAt(i);
streak = 1;
}
else{
streak++;
}
}
// i forgot to add the following two lines at the end
compressed.append(current);
compressed.append(streak);
return compressed.length()>=s.length() ? s : compressed.toString();
}
/*
A more concise version of the first approach
*/
public String compress(String s) {
StringBuilder compressed = new StringBuilder();
int streak = 0;
for(int i = 0; i < s.length(); i++) {
streak++;
if(((i+1)>=s.length())||(s.charAt(i)!=s.charAt(i+1))) {
compressed.append(s.charAt(i));
compressed.append(streak);
streak = 0;
}
}
return compressed.length()>=s.length() ? s : compressed.toString();
}
| 1,570 | 0.657962 | 0.648408 | 57 | 26.543859 | 23.191854 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 4 |
522fda6dfbd3ab1b9663063b044d3146bf480556 | 22,892,175,721,991 | 7344163b049d953f7af58676228fce6d75bd29c5 | /WebView/src/com/example/webview/WebViewActivity.java | 723bf762df015af7e016adf5cdf3de47260ee8b2 | []
| no_license | tallen94/Android-Projects | https://github.com/tallen94/Android-Projects | 010f31c250bc8ab9c0488897a19b0b6dfbab65dc | 387efa858d8d10579bdccfcad0e1f5482c3c223f | refs/heads/master | 2021-01-18T16:08:51.457000 | 2015-10-21T18:19:39 | 2015-10-21T18:19:39 | 44,694,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.webview;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class WebViewActivity extends Activity {
private final int REDIRECT_COUNTDOWN_TIME = 15;
private final int WEBPAGE_MAX_TIME = 200;
private String filename;
private Queue<String> urls;
private ArrayList<Double> loadTimes;
private TextView tv1;
private WebView pageloader;
private long pageLoadStartTime;
private String currentUrl;
private TriggerNextURL triggerNextURLReceiver;
private AlarmManager maxTimeCountDownAlarm;
private PendingIntent pendingPageCancel;
private PendingIntent pendingPageLoad;
private AlarmManager verificationCountDownAlarm;
private static int errorCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
urls = new LinkedList<String>();
loadQueue();
loadTimes = new ArrayList<Double>();
tv1 = (TextView) findViewById(R.id.tvLoadTimes);
pageloader = (WebView) findViewById(R.id.webview);
pageloader.getSettings().setJavaScriptEnabled(true);
pageloader.setWebViewClient(new CustomWebViewClient());
Intent pageCancel = new Intent();
pageCancel.setAction(StopLoadingURL.PROCESS_RESPONSE);
pageCancel.addCategory(Intent.CATEGORY_DEFAULT);
maxTimeCountDownAlarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pendingPageCancel = PendingIntent.getBroadcast(getApplicationContext(), 0, pageCancel, 0);
Intent pageLoad = new Intent();
pageLoad.setAction(TriggerNextURL.PROCESS_RESPONSE);
pageLoad.addCategory(Intent.CATEGORY_DEFAULT);
verificationCountDownAlarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pendingPageLoad = PendingIntent.getBroadcast(getApplicationContext(), 0, pageLoad, 0);
triggerNextURLReceiver = new TriggerNextURL();
IntentFilter filter = new IntentFilter(TriggerNextURL.PROCESS_RESPONSE);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(triggerNextURLReceiver, filter);
loadNextUrl();
}
public void loadQueue() {
Bundle intentBundle = getIntent().getExtras();
InputStream is;
if(intentBundle.getBoolean("fileName")) {
is = getResources().openRawResource(R.raw.top200sites);
filename = "top200data";
} else {
is = getResources().openRawResource(R.raw.other200sites);
filename = "other200data";
}
Scanner input = new Scanner(is).useDelimiter("\\A");
while (input.hasNext()) {
String url = input.nextLine();
urls.add(url);
}
}
public void loadNextUrl() {
if(!urls.isEmpty()){
currentUrl = urls.remove();
errorCode = 0;
pageloader.clearCache(true);
Log.i("loadNextUrl", "Loaded Url " + currentUrl);
pageloader.loadUrl("http://www." + currentUrl);
pageLoadStartTime = System.currentTimeMillis();
maxTimeCountDownAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + WEBPAGE_MAX_TIME * 1000, pendingPageCancel);
Log.i("Count Down: ", "In " + WEBPAGE_MAX_TIME + " seconds this page load will end if it's not done yet.");
} else {
// used for graphing purposes so data is in sorted order
quickSort(loadTimes, 0, loadTimes.size() - 1);
writeData();
}
}
private double getTimeSince(long previousTime) {
long currTime = Calendar.getInstance().getTime().getTime();
double timeSince = ((double)((currTime - previousTime) / 100)) / 10;
return timeSince;
}
public class CustomWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
maxTimeCountDownAlarm.cancel(pendingPageCancel);
Log.i("onPageFinished", "onPageFinished was called for the url: " + url);
Log.i("Count Down", "Waiting " + REDIRECT_COUNTDOWN_TIME + " seconds to load the next URL.");
verificationCountDownAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + REDIRECT_COUNTDOWN_TIME * 1000, pendingPageLoad);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
WebViewActivity.errorCode = errorCode;
}
}
public class TriggerNextURL extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "com.example.webview.pageLoad.action.triggerNextURL";
@Override
public void onReceive(Context context, Intent pageLoadService) {
double pageLoadTime = getTimeSince(pageLoadStartTime) - REDIRECT_COUNTDOWN_TIME;
loadTimes.add(pageLoadTime);
tv1.setText(tv1.getText() + "Page " + currentUrl + " loaded in " + pageLoadTime + " seconds : Error code = " + errorCode + "\n");
loadNextUrl();
}
}
public class StopLoadingURL extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "com.example.webview.pageLoad.action.stopLoadingURL";
@Override
public void onReceive(Context arg0, Intent arg1) {
errorCode = -1;
pageloader.stopLoading();
Log.i("URL Stopped", currentUrl);
}
}
public int partition(ArrayList<Double> arr, int left, int right) {
int i = left, j = right;
double tmp;
double pivot = arr.get((left + right) / 2);
while (i <= j) {
while (arr.get(i) < pivot)
i++;
while (arr.get(j) > pivot)
j--;
if (i <= j) {
tmp = arr.get(i);
arr.set(i, arr.get(j));
arr.set(j, tmp);
i++;
j--;
}
};
return i;
}
public void quickSort(ArrayList<Double> arr, int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}
public void writeData(){
FileOutputStream output;
try {
output = openFileOutput(filename, Context.CONTEXT_IGNORE_SECURITY);
double entry = 1;
for(Double d : loadTimes){
d = Math.round(d * 10.0) / 10.0;
String s = d + "\t" + (entry / loadTimes.size()) + "\n";
output.write(s.getBytes());
entry += 1.0;
}
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this, "File Saved", Toast.LENGTH_SHORT).show();;
}
}
| UTF-8 | Java | 6,920 | java | WebViewActivity.java | Java | []
| null | []
| package com.example.webview;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class WebViewActivity extends Activity {
private final int REDIRECT_COUNTDOWN_TIME = 15;
private final int WEBPAGE_MAX_TIME = 200;
private String filename;
private Queue<String> urls;
private ArrayList<Double> loadTimes;
private TextView tv1;
private WebView pageloader;
private long pageLoadStartTime;
private String currentUrl;
private TriggerNextURL triggerNextURLReceiver;
private AlarmManager maxTimeCountDownAlarm;
private PendingIntent pendingPageCancel;
private PendingIntent pendingPageLoad;
private AlarmManager verificationCountDownAlarm;
private static int errorCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
urls = new LinkedList<String>();
loadQueue();
loadTimes = new ArrayList<Double>();
tv1 = (TextView) findViewById(R.id.tvLoadTimes);
pageloader = (WebView) findViewById(R.id.webview);
pageloader.getSettings().setJavaScriptEnabled(true);
pageloader.setWebViewClient(new CustomWebViewClient());
Intent pageCancel = new Intent();
pageCancel.setAction(StopLoadingURL.PROCESS_RESPONSE);
pageCancel.addCategory(Intent.CATEGORY_DEFAULT);
maxTimeCountDownAlarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pendingPageCancel = PendingIntent.getBroadcast(getApplicationContext(), 0, pageCancel, 0);
Intent pageLoad = new Intent();
pageLoad.setAction(TriggerNextURL.PROCESS_RESPONSE);
pageLoad.addCategory(Intent.CATEGORY_DEFAULT);
verificationCountDownAlarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
pendingPageLoad = PendingIntent.getBroadcast(getApplicationContext(), 0, pageLoad, 0);
triggerNextURLReceiver = new TriggerNextURL();
IntentFilter filter = new IntentFilter(TriggerNextURL.PROCESS_RESPONSE);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(triggerNextURLReceiver, filter);
loadNextUrl();
}
public void loadQueue() {
Bundle intentBundle = getIntent().getExtras();
InputStream is;
if(intentBundle.getBoolean("fileName")) {
is = getResources().openRawResource(R.raw.top200sites);
filename = "top200data";
} else {
is = getResources().openRawResource(R.raw.other200sites);
filename = "other200data";
}
Scanner input = new Scanner(is).useDelimiter("\\A");
while (input.hasNext()) {
String url = input.nextLine();
urls.add(url);
}
}
public void loadNextUrl() {
if(!urls.isEmpty()){
currentUrl = urls.remove();
errorCode = 0;
pageloader.clearCache(true);
Log.i("loadNextUrl", "Loaded Url " + currentUrl);
pageloader.loadUrl("http://www." + currentUrl);
pageLoadStartTime = System.currentTimeMillis();
maxTimeCountDownAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + WEBPAGE_MAX_TIME * 1000, pendingPageCancel);
Log.i("Count Down: ", "In " + WEBPAGE_MAX_TIME + " seconds this page load will end if it's not done yet.");
} else {
// used for graphing purposes so data is in sorted order
quickSort(loadTimes, 0, loadTimes.size() - 1);
writeData();
}
}
private double getTimeSince(long previousTime) {
long currTime = Calendar.getInstance().getTime().getTime();
double timeSince = ((double)((currTime - previousTime) / 100)) / 10;
return timeSince;
}
public class CustomWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
maxTimeCountDownAlarm.cancel(pendingPageCancel);
Log.i("onPageFinished", "onPageFinished was called for the url: " + url);
Log.i("Count Down", "Waiting " + REDIRECT_COUNTDOWN_TIME + " seconds to load the next URL.");
verificationCountDownAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + REDIRECT_COUNTDOWN_TIME * 1000, pendingPageLoad);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
WebViewActivity.errorCode = errorCode;
}
}
public class TriggerNextURL extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "com.example.webview.pageLoad.action.triggerNextURL";
@Override
public void onReceive(Context context, Intent pageLoadService) {
double pageLoadTime = getTimeSince(pageLoadStartTime) - REDIRECT_COUNTDOWN_TIME;
loadTimes.add(pageLoadTime);
tv1.setText(tv1.getText() + "Page " + currentUrl + " loaded in " + pageLoadTime + " seconds : Error code = " + errorCode + "\n");
loadNextUrl();
}
}
public class StopLoadingURL extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "com.example.webview.pageLoad.action.stopLoadingURL";
@Override
public void onReceive(Context arg0, Intent arg1) {
errorCode = -1;
pageloader.stopLoading();
Log.i("URL Stopped", currentUrl);
}
}
public int partition(ArrayList<Double> arr, int left, int right) {
int i = left, j = right;
double tmp;
double pivot = arr.get((left + right) / 2);
while (i <= j) {
while (arr.get(i) < pivot)
i++;
while (arr.get(j) > pivot)
j--;
if (i <= j) {
tmp = arr.get(i);
arr.set(i, arr.get(j));
arr.set(j, tmp);
i++;
j--;
}
};
return i;
}
public void quickSort(ArrayList<Double> arr, int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}
public void writeData(){
FileOutputStream output;
try {
output = openFileOutput(filename, Context.CONTEXT_IGNORE_SECURITY);
double entry = 1;
for(Double d : loadTimes){
d = Math.round(d * 10.0) / 10.0;
String s = d + "\t" + (entry / loadTimes.size()) + "\n";
output.write(s.getBytes());
entry += 1.0;
}
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this, "File Saved", Toast.LENGTH_SHORT).show();;
}
}
| 6,920 | 0.704624 | 0.696532 | 210 | 31.952381 | 26.832596 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.304762 | false | false | 4 |
d3b42602d244f8a22ae551601cb65d454692ecf7 | 29,197,187,715,153 | 06e29f50de3998cd7cb5f36d9355fde60f598b0a | /src/com/method/model/ReferenceToInstanceMethodinLambda.java | e019c2d4b8880b707018e6cd9722077869403a04 | []
| no_license | paruashra/Java8Features | https://github.com/paruashra/Java8Features | cb36737b539d038a30f4500a3a80ab3c85bee95d | 1009af0c2738175ded99b9706b468e6fbf664fbe | refs/heads/master | 2020-04-15T00:08:45.161000 | 2019-01-06T13:17:20 | 2019-01-06T13:17:20 | 164,230,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.method.model;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class ReferenceToInstanceMethodinLambda {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Bean", 27));
persons.add(new Person("Sean", 21));
persons.add(new Person("Martin", 45));
persons.add(new Person("Frank", 27));
List<String> personNames = ReferenceToInstanceMethodinLambda.getPersonsName(persons, Person::getName);
personNames.forEach(System.out::println);
}
private static List<String> getPersonsName(List<Person> persons, Function<Person, String> f) {
List<String> results = new ArrayList<>();
persons.forEach(x-> results.add(f.apply(x)));
return results;
}
}
| UTF-8 | Java | 848 | java | ReferenceToInstanceMethodinLambda.java | Java | [
{
"context": "ew ArrayList<>();\n persons.add(new Person(\"Bean\", 27));\n persons.add(new Person(\"Sean\", 21",
"end": 296,
"score": 0.9991558790206909,
"start": 292,
"tag": "NAME",
"value": "Bean"
},
{
"context": "son(\"Bean\", 27));\n persons.add(new Person(\"Sean\", 21));\n persons.add(new Person(\"Martin\", ",
"end": 341,
"score": 0.9995485544204712,
"start": 337,
"tag": "NAME",
"value": "Sean"
},
{
"context": "son(\"Sean\", 21));\n persons.add(new Person(\"Martin\", 45));\n persons.add(new Person(\"Frank\", 2",
"end": 388,
"score": 0.9996601343154907,
"start": 382,
"tag": "NAME",
"value": "Martin"
},
{
"context": "n(\"Martin\", 45));\n persons.add(new Person(\"Frank\", 27));\n\n List<String> personNames = Refer",
"end": 434,
"score": 0.9995929002761841,
"start": 429,
"tag": "NAME",
"value": "Frank"
}
]
| null | []
| package com.method.model;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class ReferenceToInstanceMethodinLambda {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Bean", 27));
persons.add(new Person("Sean", 21));
persons.add(new Person("Martin", 45));
persons.add(new Person("Frank", 27));
List<String> personNames = ReferenceToInstanceMethodinLambda.getPersonsName(persons, Person::getName);
personNames.forEach(System.out::println);
}
private static List<String> getPersonsName(List<Person> persons, Function<Person, String> f) {
List<String> results = new ArrayList<>();
persons.forEach(x-> results.add(f.apply(x)));
return results;
}
}
| 848 | 0.670991 | 0.661557 | 25 | 32.919998 | 28.717827 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.84 | false | false | 4 |
6594101e48f18ae7c01205bd959b768bbac5696e | 28,724,741,320,170 | dc4b91cb9034a240ccf4920920cb2aebcf02b493 | /src/main/java/br/com/vianuvem/challenge/service/impl/ListsServiceImpl.java | bcb2f35a7a9f430c5a58e25f6f6cd795c97cf20c | []
| no_license | eltonsimor/one-choice | https://github.com/eltonsimor/one-choice | 7e82b14f5573b663e22b7e31422db5ffe54ef3e8 | eb61975185c12d1a2c5e6f7aa9aa33e2a6abc09f | refs/heads/master | 2021-01-01T15:38:59.060000 | 2017-09-14T12:51:14 | 2017-09-14T12:51:14 | 97,668,418 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.vianuvem.challenge.service.impl;
import br.com.vianuvem.challenge.converter.ConverterUtils;
import br.com.vianuvem.challenge.dto.ListsDTO;
import br.com.vianuvem.challenge.entity.ListsEntity;
import br.com.vianuvem.challenge.repository.ListsRepository;
import br.com.vianuvem.challenge.service.ListsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.inject.Singleton;
import java.util.List;
/**
* Created by eltonmoraes on 7/18/17.
*/
@Singleton
@Component
public class ListsServiceImpl implements ListsService {
private static final long serialVersionUID = 7406658242948998892L;
@Autowired
private ListsRepository listsRepository;
@Override
public List<ListsDTO> findAllLists() throws Exception {
List<ListsDTO> lists = ConverterUtils.convertTo(listsRepository.findAll(),List.class);
return lists;
}
@Override
public ListsDTO saveList(ListsDTO dto) throws Exception {
ListsEntity entity = listsRepository.save(ConverterUtils.convertTo(dto, ListsEntity.class));
ListsDTO listsDto = ConverterUtils.convertTo(entity, ListsDTO.class);
return listsDto;
}
@Override
public ListsDTO findListByPk(Integer pk) throws Exception {
ListsDTO listsDto = ConverterUtils.convertTo(listsRepository.findOne(pk), ListsDTO.class);
return listsDto;
}
@Override
public void deleteList(Integer pk) throws Exception {
listsRepository.delete(pk);
}
}
| UTF-8 | Java | 1,614 | java | ListsServiceImpl.java | Java | [
{
"context": "ngleton;\nimport java.util.List;\n\n/**\n * Created by eltonmoraes on 7/18/17.\n */\n@Singleton\n@Component\npublic clas",
"end": 573,
"score": 0.9996396899223328,
"start": 562,
"tag": "USERNAME",
"value": "eltonmoraes"
}
]
| null | []
| package br.com.vianuvem.challenge.service.impl;
import br.com.vianuvem.challenge.converter.ConverterUtils;
import br.com.vianuvem.challenge.dto.ListsDTO;
import br.com.vianuvem.challenge.entity.ListsEntity;
import br.com.vianuvem.challenge.repository.ListsRepository;
import br.com.vianuvem.challenge.service.ListsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.inject.Singleton;
import java.util.List;
/**
* Created by eltonmoraes on 7/18/17.
*/
@Singleton
@Component
public class ListsServiceImpl implements ListsService {
private static final long serialVersionUID = 7406658242948998892L;
@Autowired
private ListsRepository listsRepository;
@Override
public List<ListsDTO> findAllLists() throws Exception {
List<ListsDTO> lists = ConverterUtils.convertTo(listsRepository.findAll(),List.class);
return lists;
}
@Override
public ListsDTO saveList(ListsDTO dto) throws Exception {
ListsEntity entity = listsRepository.save(ConverterUtils.convertTo(dto, ListsEntity.class));
ListsDTO listsDto = ConverterUtils.convertTo(entity, ListsDTO.class);
return listsDto;
}
@Override
public ListsDTO findListByPk(Integer pk) throws Exception {
ListsDTO listsDto = ConverterUtils.convertTo(listsRepository.findOne(pk), ListsDTO.class);
return listsDto;
}
@Override
public void deleteList(Integer pk) throws Exception {
listsRepository.delete(pk);
}
}
| 1,614 | 0.758364 | 0.743494 | 52 | 30.038462 | 29.138239 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false | 4 |
0becef876323d8cdd8361beaf4c1dfaa1d5aee00 | 9,328,669,000,137 | 2c0604e6dcd286b21d0496eeb51a1380d3830715 | /currency-exchange-services/src/main/java/com/duyngoc/currencyexchangeservices/controllers/CurrencyExchangeController.java | 81f4874cde745eee6ada52d2e5fa1cb153b922e3 | []
| no_license | Ngocvovn/netflix-cloud-example | https://github.com/Ngocvovn/netflix-cloud-example | daf94f30bd4009897a51dcada24931a027551a57 | 6f24444cad063d00dbcfd558c19810c9da7d1a63 | refs/heads/master | 2020-04-09T13:43:20.272000 | 2018-12-04T15:36:06 | 2018-12-04T15:36:06 | 160,378,998 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.duyngoc.currencyexchangeservices.controllers;
import com.duyngoc.currencyexchangeservices.dao.ExchangeRepository;
import com.duyngoc.currencyexchangeservices.models.ExchangeValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
@RestController
public class CurrencyExchangeController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private Environment environment;
@Autowired
private ExchangeRepository exchangeRepository;
@GetMapping("/currency-exchange/from/{from}/to/{to}")
public ExchangeValue retrieveExchangeValue(@PathVariable String from, @PathVariable String to) {
ExchangeValue exchangeValue = exchangeRepository.findByFromAndTo(from, to);
exchangeValue.setPort(Integer.parseInt(environment.getProperty("local.server.port")));
logger.info(exchangeValue.toString());
return exchangeValue;
}
}
| UTF-8 | Java | 1,249 | java | CurrencyExchangeController.java | Java | []
| null | []
| package com.duyngoc.currencyexchangeservices.controllers;
import com.duyngoc.currencyexchangeservices.dao.ExchangeRepository;
import com.duyngoc.currencyexchangeservices.models.ExchangeValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
@RestController
public class CurrencyExchangeController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private Environment environment;
@Autowired
private ExchangeRepository exchangeRepository;
@GetMapping("/currency-exchange/from/{from}/to/{to}")
public ExchangeValue retrieveExchangeValue(@PathVariable String from, @PathVariable String to) {
ExchangeValue exchangeValue = exchangeRepository.findByFromAndTo(from, to);
exchangeValue.setPort(Integer.parseInt(environment.getProperty("local.server.port")));
logger.info(exchangeValue.toString());
return exchangeValue;
}
}
| 1,249 | 0.800641 | 0.799039 | 32 | 38 | 29.497881 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 4 |
993e7be892ecc6102ce50437ff1ff980cc369fb9 | 21,517,786,193,593 | 027144ea64c2b6843bd9e684183a19d0271b4ef6 | /src/test/java/pro/belbix/tim/exchanges/bitmax/BitmaxRESTTestApi.java | 36a3d999f34dae6e4e1cc7983eb639b55a48bcd9 | []
| no_license | belbix/tim | https://github.com/belbix/tim | d576c74f12f979a22721b116299d50d4ff137078 | 41536256f20a99799ab4fdbed8bcaea887c31d07 | refs/heads/master | 2022-12-25T23:22:22.843000 | 2020-10-11T09:18:46 | 2020-10-11T09:18:46 | 301,081,418 | 0 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pro.belbix.tim.exchanges.bitmax;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import pro.belbix.tim.SimpleApp;
import pro.belbix.tim.entity.Order;
import pro.belbix.tim.entity.Tick;
import pro.belbix.tim.exceptions.TIMRetryException;
import pro.belbix.tim.exceptions.TIMRuntimeException;
import pro.belbix.tim.exchanges.models.Balance;
import pro.belbix.tim.exchanges.models.Position;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import static pro.belbix.tim.entity.Order.OrderType.LIMIT;
import static pro.belbix.tim.models.OrderSide.SHORT_CLOSE;
import static pro.belbix.tim.models.OrderSide.SHORT_OPEN;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SimpleApp.class)
public class BitmaxRESTTestApi {
@Autowired
private BitmaxREST bitmaxREST;
// @Test
public void addOrder() throws TIMRetryException {
Order shortOpen = new Order();
shortOpen.setId(UUID.randomUUID().toString());
shortOpen.setServer("bitmax");
shortOpen.setSymbol("BTCUSD");
shortOpen.setDateCreate(LocalDateTime.now());
shortOpen.setOrderSide(SHORT_OPEN);
shortOpen.setOrderType(LIMIT.toString());
shortOpen.setAmount(0.00125);
try {
bitmaxREST.addOrder(shortOpen);
} catch (TIMRuntimeException e) {
if (e.getMessage().startsWith("6010")) {
System.out.println("" + e.getMessage());
return;
} else throw e;
}
Order shortClose = new Order();
shortClose.setId(UUID.randomUUID().toString());
shortClose.setServer("bitmax");
shortClose.setSymbol("BTCUSD");
shortClose.setDateCreate(LocalDateTime.now());
shortClose.setOrderSide(SHORT_CLOSE);
shortClose.setOrderType(LIMIT.toString());
shortClose.setAmount(0.00125);
bitmaxREST.addOrder(shortClose);
}
// @Test
public void updateOrder() throws InterruptedException, TIMRetryException {
Order orderSell = new Order();
orderSell.setId(UUID.randomUUID().toString());
orderSell.setServer("bitmax");
orderSell.setSymbol("BTCUSD");
orderSell.setDateCreate(LocalDateTime.now());
orderSell.setOrderSide(SHORT_OPEN);
orderSell.setOrderType(LIMIT.toString());
orderSell.setAmount(0.00125);
try {
Order responseSell = bitmaxREST.addOrder(orderSell);
Thread.sleep(10000);
bitmaxREST.updateOrder(responseSell);
} catch (TIMRuntimeException e) {
if (e.getMessage().startsWith("6010")) System.out.println("" + e.getMessage());
else throw e;
}
}
// @Test
public void getOrders() throws TIMRetryException {
Order orderSell = new Order();
orderSell.setId(UUID.randomUUID().toString().replace("-", ""));
orderSell.setServer("bitmax");
orderSell.setSymbol("BTCUSD");
orderSell.setDateCreate(LocalDateTime.now());
orderSell.setOrderSide(SHORT_OPEN);
orderSell.setOrderType(LIMIT.toString());
orderSell.setAmount(1d);
bitmaxREST.getOrders(orderSell.getSymbol(), 100);
}
// @Test
public void closeOrder() throws TIMRetryException {
Order orderSell = new Order();
orderSell.setId(UUID.randomUUID().toString().replace("-", ""));
orderSell.setServer("bitmax");
orderSell.setSymbol("BTCUSD");
orderSell.setDateCreate(LocalDateTime.now());
orderSell.setOrderSide(SHORT_OPEN);
orderSell.setOrderType(LIMIT.toString());
orderSell.setAmount(1d);
bitmaxREST.closeOrder(orderSell);
}
// @Test
public void closeAllOrders() throws TIMRetryException {
bitmaxREST.closeAllOrders("BTC/USDT");
}
@Test
public void getOrderBook() throws TIMRetryException {
List<Tick> ticks = bitmaxREST.getOrderBook("BTC", 0);
// Assert.assertNotNull(ticks);
// Assert.assertTrue(ticks.size() >= 2);
// for(Tick tick: ticks){
// System.out.println(tick.toString());
// }
}
// @Test
public void getBalance() throws TIMRetryException {
Balance balance = bitmaxREST.getBalance("BTC");
System.out.println(balance.toString());
}
@Test
public void lastPrice() throws TIMRetryException {
Tick tick = bitmaxREST.lastPrice("BTC");
System.out.println(tick);
}
// @Test
public void positions() throws TIMRetryException {
List<Position> positions = bitmaxREST.positions();
for (Position position : positions) {
System.out.println(position.symbol() + ": " + position.currentQty());
}
}
@Test
public void historyOrders() throws TIMRetryException {
bitmaxREST.historyOrders();
}
}
| UTF-8 | Java | 5,089 | java | BitmaxRESTTestApi.java | Java | []
| null | []
| package pro.belbix.tim.exchanges.bitmax;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import pro.belbix.tim.SimpleApp;
import pro.belbix.tim.entity.Order;
import pro.belbix.tim.entity.Tick;
import pro.belbix.tim.exceptions.TIMRetryException;
import pro.belbix.tim.exceptions.TIMRuntimeException;
import pro.belbix.tim.exchanges.models.Balance;
import pro.belbix.tim.exchanges.models.Position;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import static pro.belbix.tim.entity.Order.OrderType.LIMIT;
import static pro.belbix.tim.models.OrderSide.SHORT_CLOSE;
import static pro.belbix.tim.models.OrderSide.SHORT_OPEN;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SimpleApp.class)
public class BitmaxRESTTestApi {
@Autowired
private BitmaxREST bitmaxREST;
// @Test
public void addOrder() throws TIMRetryException {
Order shortOpen = new Order();
shortOpen.setId(UUID.randomUUID().toString());
shortOpen.setServer("bitmax");
shortOpen.setSymbol("BTCUSD");
shortOpen.setDateCreate(LocalDateTime.now());
shortOpen.setOrderSide(SHORT_OPEN);
shortOpen.setOrderType(LIMIT.toString());
shortOpen.setAmount(0.00125);
try {
bitmaxREST.addOrder(shortOpen);
} catch (TIMRuntimeException e) {
if (e.getMessage().startsWith("6010")) {
System.out.println("" + e.getMessage());
return;
} else throw e;
}
Order shortClose = new Order();
shortClose.setId(UUID.randomUUID().toString());
shortClose.setServer("bitmax");
shortClose.setSymbol("BTCUSD");
shortClose.setDateCreate(LocalDateTime.now());
shortClose.setOrderSide(SHORT_CLOSE);
shortClose.setOrderType(LIMIT.toString());
shortClose.setAmount(0.00125);
bitmaxREST.addOrder(shortClose);
}
// @Test
public void updateOrder() throws InterruptedException, TIMRetryException {
Order orderSell = new Order();
orderSell.setId(UUID.randomUUID().toString());
orderSell.setServer("bitmax");
orderSell.setSymbol("BTCUSD");
orderSell.setDateCreate(LocalDateTime.now());
orderSell.setOrderSide(SHORT_OPEN);
orderSell.setOrderType(LIMIT.toString());
orderSell.setAmount(0.00125);
try {
Order responseSell = bitmaxREST.addOrder(orderSell);
Thread.sleep(10000);
bitmaxREST.updateOrder(responseSell);
} catch (TIMRuntimeException e) {
if (e.getMessage().startsWith("6010")) System.out.println("" + e.getMessage());
else throw e;
}
}
// @Test
public void getOrders() throws TIMRetryException {
Order orderSell = new Order();
orderSell.setId(UUID.randomUUID().toString().replace("-", ""));
orderSell.setServer("bitmax");
orderSell.setSymbol("BTCUSD");
orderSell.setDateCreate(LocalDateTime.now());
orderSell.setOrderSide(SHORT_OPEN);
orderSell.setOrderType(LIMIT.toString());
orderSell.setAmount(1d);
bitmaxREST.getOrders(orderSell.getSymbol(), 100);
}
// @Test
public void closeOrder() throws TIMRetryException {
Order orderSell = new Order();
orderSell.setId(UUID.randomUUID().toString().replace("-", ""));
orderSell.setServer("bitmax");
orderSell.setSymbol("BTCUSD");
orderSell.setDateCreate(LocalDateTime.now());
orderSell.setOrderSide(SHORT_OPEN);
orderSell.setOrderType(LIMIT.toString());
orderSell.setAmount(1d);
bitmaxREST.closeOrder(orderSell);
}
// @Test
public void closeAllOrders() throws TIMRetryException {
bitmaxREST.closeAllOrders("BTC/USDT");
}
@Test
public void getOrderBook() throws TIMRetryException {
List<Tick> ticks = bitmaxREST.getOrderBook("BTC", 0);
// Assert.assertNotNull(ticks);
// Assert.assertTrue(ticks.size() >= 2);
// for(Tick tick: ticks){
// System.out.println(tick.toString());
// }
}
// @Test
public void getBalance() throws TIMRetryException {
Balance balance = bitmaxREST.getBalance("BTC");
System.out.println(balance.toString());
}
@Test
public void lastPrice() throws TIMRetryException {
Tick tick = bitmaxREST.lastPrice("BTC");
System.out.println(tick);
}
// @Test
public void positions() throws TIMRetryException {
List<Position> positions = bitmaxREST.positions();
for (Position position : positions) {
System.out.println(position.symbol() + ": " + position.currentQty());
}
}
@Test
public void historyOrders() throws TIMRetryException {
bitmaxREST.historyOrders();
}
}
| 5,089 | 0.653763 | 0.646099 | 150 | 32.926666 | 21.765446 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.593333 | false | false | 4 |
fe47e7993119639c8ae485caa417e046991eaffe | 26,139,171,006,122 | ee60152a30159e34877c58e8be8d2114b10aa213 | /core/src/gdx/objects/Score.java | 968e1585de1c4783ff6d334f0f5f1fbd8bc19c39 | []
| no_license | DaphneLai/PolyGone-Final | https://github.com/DaphneLai/PolyGone-Final | 9b9c8d925777d5d5e7c0cb1fbf9c79b19d37bc85 | db4187376e46a8b9c117c515b7a07d6671a9092f | refs/heads/master | 2021-09-05T08:43:10.082000 | 2018-01-25T18:26:04 | 2018-01-25T18:26:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gdx.objects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.audio.Sound;
public class Score {
Sound sdCorrect, sdWrong;
boolean oneWasPressed = false;
public static int nNum, Points; //https://www.youtube.com/watch?v=cGqq59-Kd7Y creating score countdown
public Score() {
sdCorrect = Gdx.audio.newSound(Gdx.files.internal("Right.mp3")); //http://soundbible.com/free-sound-effects-1.html >finding sounds
sdCorrect.setVolume(0, 0.5f);
sdWrong = Gdx.audio.newSound(Gdx.files.internal("Wrong.mp3"));
sdWrong.setVolume(0, 0.5f);
}
public static boolean isCorrect(int _nShp, int _nNum) {
int nNum = _nNum;
int nShp = _nShp;
if (nNum == 3 && nShp == 0) {
return true;
} else if (nNum == 4 && nShp == 1) {
return true;
} else if (nNum == 5 && nShp == 2) {
return true;
} else if (nNum == 6 && nShp == 3) {
return true;
} else if (nNum == 7 && nShp == 4) {
return true;
} else if (nNum == 8 && nShp == 5) {
return true;
} else if (nNum == 9 && nShp == 6) {
return true;
} else if (nNum == 10 && nShp == 7) {
return true;
} else if (nNum == 11 && nShp == 8) {
return true;
} else if (nNum == 12 && nShp == 9) {
return true;
} else if (nNum == 13 && nShp == 10) {
return true;
}
return false;
}
public void checkInputs() {
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_0)) {
if (oneWasPressed) {
nNum = 10;
oneWasPressed = false;
} else {
nNum = 0;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_1)) {
if (!oneWasPressed) {
nNum = 1;
oneWasPressed = true;
} else {
nNum = 11;
oneWasPressed = false;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_2)) {
if (oneWasPressed) {
nNum = 12;
oneWasPressed = false;
} else {
nNum = 2;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_3)) {
if (oneWasPressed) {
nNum = 13;
oneWasPressed = false;
} else {
nNum = 3;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_4)) {
nNum = 4;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_5)) {
nNum = 5;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_6)) {
nNum = 6;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_7)) {
nNum = 7;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_8)) {
nNum = 8;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_9)) {
nNum = 9;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.ENTER)) {
oneWasPressed = false;
System.out.println(nNum);
if (isCorrect(gdx.screens.ScrGame.nShp, nNum) == true) {
Points += 10;
nNum = 0;
sdCorrect.play();
//Score.addScore(10);
System.out.println("CORRECT");
} else {
//Score.subScore(5);
Points -= 5;
nNum = 0;
sdWrong.play();
System.out.println("INCORRECT");
}
}
}
}
| UTF-8 | Java | 3,843 | java | Score.java | Java | []
| null | []
| package gdx.objects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.audio.Sound;
public class Score {
Sound sdCorrect, sdWrong;
boolean oneWasPressed = false;
public static int nNum, Points; //https://www.youtube.com/watch?v=cGqq59-Kd7Y creating score countdown
public Score() {
sdCorrect = Gdx.audio.newSound(Gdx.files.internal("Right.mp3")); //http://soundbible.com/free-sound-effects-1.html >finding sounds
sdCorrect.setVolume(0, 0.5f);
sdWrong = Gdx.audio.newSound(Gdx.files.internal("Wrong.mp3"));
sdWrong.setVolume(0, 0.5f);
}
public static boolean isCorrect(int _nShp, int _nNum) {
int nNum = _nNum;
int nShp = _nShp;
if (nNum == 3 && nShp == 0) {
return true;
} else if (nNum == 4 && nShp == 1) {
return true;
} else if (nNum == 5 && nShp == 2) {
return true;
} else if (nNum == 6 && nShp == 3) {
return true;
} else if (nNum == 7 && nShp == 4) {
return true;
} else if (nNum == 8 && nShp == 5) {
return true;
} else if (nNum == 9 && nShp == 6) {
return true;
} else if (nNum == 10 && nShp == 7) {
return true;
} else if (nNum == 11 && nShp == 8) {
return true;
} else if (nNum == 12 && nShp == 9) {
return true;
} else if (nNum == 13 && nShp == 10) {
return true;
}
return false;
}
public void checkInputs() {
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_0)) {
if (oneWasPressed) {
nNum = 10;
oneWasPressed = false;
} else {
nNum = 0;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_1)) {
if (!oneWasPressed) {
nNum = 1;
oneWasPressed = true;
} else {
nNum = 11;
oneWasPressed = false;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_2)) {
if (oneWasPressed) {
nNum = 12;
oneWasPressed = false;
} else {
nNum = 2;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_3)) {
if (oneWasPressed) {
nNum = 13;
oneWasPressed = false;
} else {
nNum = 3;
}
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_4)) {
nNum = 4;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_5)) {
nNum = 5;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_6)) {
nNum = 6;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_7)) {
nNum = 7;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_8)) {
nNum = 8;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.NUMPAD_9)) {
nNum = 9;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.ENTER)) {
oneWasPressed = false;
System.out.println(nNum);
if (isCorrect(gdx.screens.ScrGame.nShp, nNum) == true) {
Points += 10;
nNum = 0;
sdCorrect.play();
//Score.addScore(10);
System.out.println("CORRECT");
} else {
//Score.subScore(5);
Points -= 5;
nNum = 0;
sdWrong.play();
System.out.println("INCORRECT");
}
}
}
}
| 3,843 | 0.449649 | 0.430133 | 120 | 30.025 | 21.123629 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516667 | false | false | 4 |
759865686a85b65877260e800c8b843b1407b05a | 23,167,053,639,360 | 620e73faa70ebce2c45dcab0d65290b49d9690df | /app/src/main/java/com/mihailenko/ilya/weatherforecastapp/ui/adapter/ForecastAdapter.java | 9354424909f1116683e71bb724f09bc6d8d5f3f4 | []
| no_license | ArshaWIN/WeatherForecastApp | https://github.com/ArshaWIN/WeatherForecastApp | 11c67b615b26cb479817cd4aa9c4db3d7bb0e79c | 8abeabc1ef5c9f572f499fb1a47ce80cb18ef419 | refs/heads/master | 2021-01-25T11:55:07.320000 | 2018-08-13T11:30:39 | 2018-08-13T11:30:39 | 93,951,458 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mihailenko.ilya.weatherforecastapp.ui.adapter;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mihailenko.ilya.weatherforecastapp.BR;
import com.mihailenko.ilya.weatherforecastapp.R;
import com.mihailenko.ilya.weatherforecastapp.models.weather.ForecastDayItem;
import com.mihailenko.ilya.weatherforecastapp.databinding.ItemCurrentWeatherBinding;
import com.mihailenko.ilya.weatherforecastapp.databinding.ItemDayForecastBinding;
import java.util.List;
/**
* Created by Ilya on 12.06.2017.
*/
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.ForecastViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_NORMAL = 1;
private List<ForecastDayItem> items;
private LayoutInflater layoutInflater;
public ForecastAdapter(List<ForecastDayItem> items) {
this.items = items;
}
@Override
public ForecastViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
if (viewType == TYPE_HEADER) {
ItemCurrentWeatherBinding binding =
DataBindingUtil.inflate(layoutInflater, R.layout.item_current_weather, parent, false);
return new ForecastCurrentWeather(binding.getRoot());
}
ItemDayForecastBinding binding =
DataBindingUtil.inflate(layoutInflater, R.layout.item_day_forecast, parent, false);
return new ForecastDay(binding.getRoot());
}
@Override
public int getItemViewType(int position) {
return position == 0 ? TYPE_HEADER : TYPE_NORMAL;
}
@Override
public void onBindViewHolder(ForecastViewHolder holder, int position) {
if (items == null) {
return;
}
holder.setItem(items.get(position));
}
@Override
public int getItemCount() {
return items == null ? 0 : items.size();
}
public void setForecast(List<ForecastDayItem> items) {
this.items = items;
notifyDataSetChanged();
}
abstract static class ForecastViewHolder<TBinding extends ViewDataBinding> extends RecyclerView.ViewHolder {
private final TBinding binding;
ForecastViewHolder(View view) {
super(view);
binding = DataBindingUtil.bind(view);
}
void setItem(ForecastDayItem item) {
binding.setVariable(BR.forecast, item);
}
}
private static class ForecastCurrentWeather extends ForecastViewHolder<ItemCurrentWeatherBinding> {
ForecastCurrentWeather(View view) {
super(view);
}
}
private static class ForecastDay extends ForecastViewHolder<ItemDayForecastBinding> {
ForecastDay(View view) {
super(view);
}
}
}
| UTF-8 | Java | 3,062 | java | ForecastAdapter.java | Java | [
{
"context": "inding;\n\nimport java.util.List;\n\n/**\n * Created by Ilya on 12.06.2017.\n */\n\npublic class ForecastAdapter ",
"end": 680,
"score": 0.9488644003868103,
"start": 676,
"tag": "NAME",
"value": "Ilya"
}
]
| null | []
| package com.mihailenko.ilya.weatherforecastapp.ui.adapter;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mihailenko.ilya.weatherforecastapp.BR;
import com.mihailenko.ilya.weatherforecastapp.R;
import com.mihailenko.ilya.weatherforecastapp.models.weather.ForecastDayItem;
import com.mihailenko.ilya.weatherforecastapp.databinding.ItemCurrentWeatherBinding;
import com.mihailenko.ilya.weatherforecastapp.databinding.ItemDayForecastBinding;
import java.util.List;
/**
* Created by Ilya on 12.06.2017.
*/
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.ForecastViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_NORMAL = 1;
private List<ForecastDayItem> items;
private LayoutInflater layoutInflater;
public ForecastAdapter(List<ForecastDayItem> items) {
this.items = items;
}
@Override
public ForecastViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
if (viewType == TYPE_HEADER) {
ItemCurrentWeatherBinding binding =
DataBindingUtil.inflate(layoutInflater, R.layout.item_current_weather, parent, false);
return new ForecastCurrentWeather(binding.getRoot());
}
ItemDayForecastBinding binding =
DataBindingUtil.inflate(layoutInflater, R.layout.item_day_forecast, parent, false);
return new ForecastDay(binding.getRoot());
}
@Override
public int getItemViewType(int position) {
return position == 0 ? TYPE_HEADER : TYPE_NORMAL;
}
@Override
public void onBindViewHolder(ForecastViewHolder holder, int position) {
if (items == null) {
return;
}
holder.setItem(items.get(position));
}
@Override
public int getItemCount() {
return items == null ? 0 : items.size();
}
public void setForecast(List<ForecastDayItem> items) {
this.items = items;
notifyDataSetChanged();
}
abstract static class ForecastViewHolder<TBinding extends ViewDataBinding> extends RecyclerView.ViewHolder {
private final TBinding binding;
ForecastViewHolder(View view) {
super(view);
binding = DataBindingUtil.bind(view);
}
void setItem(ForecastDayItem item) {
binding.setVariable(BR.forecast, item);
}
}
private static class ForecastCurrentWeather extends ForecastViewHolder<ItemCurrentWeatherBinding> {
ForecastCurrentWeather(View view) {
super(view);
}
}
private static class ForecastDay extends ForecastViewHolder<ItemDayForecastBinding> {
ForecastDay(View view) {
super(view);
}
}
}
| 3,062 | 0.692685 | 0.688439 | 99 | 29.929293 | 29.306549 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 4 |
a17cf219396fed76b8920864af9c76572bec09d9 | 18,519,898,990,225 | fb6ec9a303407de9f9f3933b3821ab748f081875 | /src/main/java/com/awin/resources/ProductResource.java | ac2d8d1d9cffab500e3ff143787939af281f0313 | []
| no_license | alokmaurya05/fileUpload | https://github.com/alokmaurya05/fileUpload | 3497f9b1b83dc412b8fdb63a9a835bae66e4f8ae | c5bff0af7542e8dcfb58f1879cd8a480ac8a11c3 | refs/heads/master | 2023-05-23T16:14:15.129000 | 2021-06-03T11:30:37 | 2021-06-03T11:30:37 | 365,223,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.awin.resources;
import java.util.List;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.awin.buildResponse.Response;
import com.awin.entity.Product;
import com.awin.error.ProductException;
import com.awin.services.ProductService;
import com.github.fge.jsonpatch.JsonPatch;
@RestController
@RequestMapping(value = "/api/product")
public class ProductResource {
private static final Logger logger = LogManager.getLogger(ProductResource.class);
@Autowired
private ProductService productService;
@GetMapping(value = "/all")
public ResponseEntity<?> getAllProduct() {
logger.info("Fetching all product details ");
List<Product> products = null;
try {
products = productService.getAllProduct();
if (products.isEmpty()) {
logger.info("No product details found ");
return Response.fail("No Data Available", HttpStatus.NOT_FOUND);
}
} catch (Exception e) {
logger.error("error in getting all product ", e.getMessage());
throw new ProductException(e.getMessage());
}
logger.info("Fetching All product done no of product {}", products.size());
return Response.success(products, HttpStatus.OK);
}
@GetMapping(value = "/{productName}")
public ResponseEntity<?> getAllProductByCustomer(@PathVariable("productName") String product_Name) {
logger.info("Getting product with name {} ",product_Name);
List<Product> products = productService.getProductByName(product_Name);
return Response.success(products, HttpStatus.OK);
}
@PatchMapping (value = "/{id}", consumes = "application/json-patch+json")
public ResponseEntity<Product> update(@PathVariable(name = "id") int id, @RequestBody JsonPatch updateProductPatch) throws Exception {
logger.info("Update for product with id {} ",id);
Product product = productService.updateProduct(updateProductPatch, id);
if(Objects.isNull(product)) {
logger.error("Error in product update request {} ",id);
return Response.fail(product, HttpStatus.NOT_MODIFIED);
}
return Response.success(product, HttpStatus.OK);
}
}
| UTF-8 | Java | 2,635 | java | ProductResource.java | Java | []
| null | []
| package com.awin.resources;
import java.util.List;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.awin.buildResponse.Response;
import com.awin.entity.Product;
import com.awin.error.ProductException;
import com.awin.services.ProductService;
import com.github.fge.jsonpatch.JsonPatch;
@RestController
@RequestMapping(value = "/api/product")
public class ProductResource {
private static final Logger logger = LogManager.getLogger(ProductResource.class);
@Autowired
private ProductService productService;
@GetMapping(value = "/all")
public ResponseEntity<?> getAllProduct() {
logger.info("Fetching all product details ");
List<Product> products = null;
try {
products = productService.getAllProduct();
if (products.isEmpty()) {
logger.info("No product details found ");
return Response.fail("No Data Available", HttpStatus.NOT_FOUND);
}
} catch (Exception e) {
logger.error("error in getting all product ", e.getMessage());
throw new ProductException(e.getMessage());
}
logger.info("Fetching All product done no of product {}", products.size());
return Response.success(products, HttpStatus.OK);
}
@GetMapping(value = "/{productName}")
public ResponseEntity<?> getAllProductByCustomer(@PathVariable("productName") String product_Name) {
logger.info("Getting product with name {} ",product_Name);
List<Product> products = productService.getProductByName(product_Name);
return Response.success(products, HttpStatus.OK);
}
@PatchMapping (value = "/{id}", consumes = "application/json-patch+json")
public ResponseEntity<Product> update(@PathVariable(name = "id") int id, @RequestBody JsonPatch updateProductPatch) throws Exception {
logger.info("Update for product with id {} ",id);
Product product = productService.updateProduct(updateProductPatch, id);
if(Objects.isNull(product)) {
logger.error("Error in product update request {} ",id);
return Response.fail(product, HttpStatus.NOT_MODIFIED);
}
return Response.success(product, HttpStatus.OK);
}
}
| 2,635 | 0.76926 | 0.768501 | 75 | 34.133335 | 28.697193 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.706667 | false | false | 4 |
5e82fdd55d3fb35c42ea460f7a4449f7097e1966 | 24,584,392,807,518 | 207269745c95ab1c13e5584fc58cf978cbfa776f | /day07-code(Interface)/src/com/xuesong/demo07InnerClass/Outer02.java | 1d4c9041306460d6dc4898d044a72ee55cca3e28 | []
| no_license | forsnow/Java-Note | https://github.com/forsnow/Java-Note | 79bbc670a38da04072cc5ec625884f32959b3169 | 465c02479d364518363310bcd9888b558877f31f | refs/heads/master | 2020-09-02T16:15:55.562000 | 2020-02-24T03:27:40 | 2020-02-24T03:27:40 | 219,257,132 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xuesong.demo07InnerClass;
public class Outer02 {
public void outerMethod(){
class Inner{
int num = 100;
public void innerMethod(){
System.out.println(num);
}
}
Inner inner = new Inner();
inner.innerMethod();
}
}
| UTF-8 | Java | 319 | java | Outer02.java | Java | []
| null | []
| package com.xuesong.demo07InnerClass;
public class Outer02 {
public void outerMethod(){
class Inner{
int num = 100;
public void innerMethod(){
System.out.println(num);
}
}
Inner inner = new Inner();
inner.innerMethod();
}
}
| 319 | 0.517241 | 0.495298 | 16 | 18.9375 | 14.471821 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 4 |
a878a2e56c3fd5ebc3d98e2e71fa8a24966c8a14 | 2,130,303,806,927 | 72760f02926f2d1cabd987a47087a368c08ec8dd | /app/src/main/java/com/monad/searcher/Util/NotificationService.java | ab3985cfd27bc57206e72ece4a70d7614f296057 | []
| no_license | kangseyun/Searcher | https://github.com/kangseyun/Searcher | 7a960fafd6b75351bd747d3b232731407f8d04a5 | 57f6dd3ec9a3f7ba4b4c028553c517c264742ffe | refs/heads/master | 2020-12-03T01:40:08.174000 | 2017-09-18T13:26:47 | 2017-09-18T13:26:47 | 95,851,202 | 0 | 0 | null | false | 2017-08-02T08:37:28 | 2017-06-30T05:16:20 | 2017-06-30T05:20:13 | 2017-08-02T08:37:28 | 704 | 0 | 0 | 0 | Java | null | null | package com.monad.searcher.Util;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.On;
import com.github.nkzawa.socketio.client.Socket;
import com.monad.searcher.Activity.MainActivity;
import com.monad.searcher.Model.LoginSingleton;
import com.monad.searcher.Model.NotificationModel;
import com.monad.searcher.Model.PushModel;
import com.monad.searcher.Model.TokenCheckModel;
import com.monad.searcher.Model.TokenModel;
import com.monad.searcher.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
/**
* Created by seyun on 2017. 9. 4..
*/
public class NotificationService extends IntentService {
private String[] txtArr = {"", };
private NotificationModel notificationModel;
private Realm realm;
public NotificationService() {
super("NotificationService");
}
@Override
public void onCreate(){
super.onCreate();
Log.i("Service", "onCreate Call");
mSocket.on("message", onNewMessage);
mSocket.connect();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("socket", "open");
onHandleIntent(intent);
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i("socket", "open");
return null;
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i("call", "handle");
try {
realm = Realm.getDefaultInstance();
// go do some network calls/etc and get some data
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmQuery<PushModel> query = realm.where(PushModel.class);
PushModel result = query.findAll().first();
Log.i("result", result.getPush());
txtArr = result.getPush().split(",");
}
});
} finally {
if(realm != null) {
realm.close();
}
}
}
private Socket mSocket;
{
try {
mSocket = IO.socket("http://115.68.122.248:3000");
Log.i("SocketOpen", "Open");
} catch (URISyntaxException e) {}
}
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
Log.i("response", "response");
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
int push;
String message;
try {
push = data.getInt("push");
message = data.getString("message");
} catch (JSONException e) {
return;
}
for(int i=0;i<txtArr.length;i++) {
try {
if(Integer.parseInt(txtArr[i]) == push) {
if(LoginSingleton.getInstance().getFlag())
sendNotification(message);
}
} catch (NumberFormatException ex) {}
}
}
}, 0);
}
};
private void sendNotification(String messageBody) {
realm.beginTransaction();
notificationModel = realm.createObject(NotificationModel.class); // 새 객체 만들기
notificationModel.setContent(messageBody);
Log.i("save", messageBody);
realm.commitTransaction();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.searcher_icon)
.setContentTitle("써처 알림")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
@Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off("message", onNewMessage);
}
}
| UTF-8 | Java | 5,534 | java | NotificationService.java | Java | [
{
"context": "at;\nimport android.util.Log;\n\nimport com.github.nkzawa.emitter.Emitter;\nimport com.github.nkzawa.socketi",
"end": 519,
"score": 0.7441749572753906,
"start": 515,
"tag": "USERNAME",
"value": "zawa"
},
{
"context": "ithub.nkzawa.emitter.Emitter;\nimport com.github.nkzawa.socketio.client.IO;\nimport com.github.nkzawa.sock",
"end": 561,
"score": 0.6309174299240112,
"start": 557,
"tag": "USERNAME",
"value": "zawa"
},
{
"context": "b.nkzawa.socketio.client.IO;\nimport com.github.nkzawa.socketio.client.On;\nimport com.github.nkzawa.sock",
"end": 606,
"score": 0.5149738192558289,
"start": 603,
"tag": "USERNAME",
"value": "awa"
},
{
"context": ";\nimport io.realm.RealmResults;\n\n/**\n * Created by seyun on 2017. 9. 4..\n */\n\npublic class NotificationSer",
"end": 1192,
"score": 0.7919754981994629,
"start": 1187,
"tag": "USERNAME",
"value": "seyun"
},
{
"context": " try {\n mSocket = IO.socket(\"http://115.68.122.248:3000\");\n Log.i(\"SocketOpen\", \"Open\");\n",
"end": 2855,
"score": 0.9996541738510132,
"start": 2841,
"tag": "IP_ADDRESS",
"value": "115.68.122.248"
}
]
| null | []
| package com.monad.searcher.Util;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.On;
import com.github.nkzawa.socketio.client.Socket;
import com.monad.searcher.Activity.MainActivity;
import com.monad.searcher.Model.LoginSingleton;
import com.monad.searcher.Model.NotificationModel;
import com.monad.searcher.Model.PushModel;
import com.monad.searcher.Model.TokenCheckModel;
import com.monad.searcher.Model.TokenModel;
import com.monad.searcher.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
/**
* Created by seyun on 2017. 9. 4..
*/
public class NotificationService extends IntentService {
private String[] txtArr = {"", };
private NotificationModel notificationModel;
private Realm realm;
public NotificationService() {
super("NotificationService");
}
@Override
public void onCreate(){
super.onCreate();
Log.i("Service", "onCreate Call");
mSocket.on("message", onNewMessage);
mSocket.connect();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("socket", "open");
onHandleIntent(intent);
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i("socket", "open");
return null;
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i("call", "handle");
try {
realm = Realm.getDefaultInstance();
// go do some network calls/etc and get some data
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmQuery<PushModel> query = realm.where(PushModel.class);
PushModel result = query.findAll().first();
Log.i("result", result.getPush());
txtArr = result.getPush().split(",");
}
});
} finally {
if(realm != null) {
realm.close();
}
}
}
private Socket mSocket;
{
try {
mSocket = IO.socket("http://172.16.31.10:3000");
Log.i("SocketOpen", "Open");
} catch (URISyntaxException e) {}
}
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
Log.i("response", "response");
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
int push;
String message;
try {
push = data.getInt("push");
message = data.getString("message");
} catch (JSONException e) {
return;
}
for(int i=0;i<txtArr.length;i++) {
try {
if(Integer.parseInt(txtArr[i]) == push) {
if(LoginSingleton.getInstance().getFlag())
sendNotification(message);
}
} catch (NumberFormatException ex) {}
}
}
}, 0);
}
};
private void sendNotification(String messageBody) {
realm.beginTransaction();
notificationModel = realm.createObject(NotificationModel.class); // 새 객체 만들기
notificationModel.setContent(messageBody);
Log.i("save", messageBody);
realm.commitTransaction();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.searcher_icon)
.setContentTitle("써처 알림")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
@Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off("message", onNewMessage);
}
}
| 5,532 | 0.597933 | 0.593036 | 172 | 31.05814 | 22.475492 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604651 | false | false | 4 |
d3020ccd1b090b02bf02c2f5b365c8a5fe6ccc33 | 28,965,259,502,780 | b9c479cce89fcf32e5c6f0d373df2b2654d69569 | /src/jUnit/FrameTests.java | e9ab25c94168e75f26af43227986bce35cd01de1 | []
| no_license | ES1-2017-LEI-PL-101/ES1-2017-LEI-PL-101 | https://github.com/ES1-2017-LEI-PL-101/ES1-2017-LEI-PL-101 | 0e16735b3fb11cd7d67307edff11db8d32e4f125 | db6a4877e349698e425ed53fce36939ab7e53006 | refs/heads/dev | 2021-08-31T21:24:03.625000 | 2017-12-23T00:24:01 | 2017-12-23T00:24:01 | 107,707,781 | 1 | 0 | null | true | 2017-12-20T23:41:04 | 2017-10-20T17:36:23 | 2017-10-20T17:39:42 | 2017-12-20T23:41:04 | 12,251 | 0 | 0 | 0 | Java | false | null | package jUnit;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.*;
import java.awt.Component;
import java.awt.List;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextField;
import org.junit.jupiter.api.Test;
import antiSpamUI.AntiSpamGUI;
import antiSpamUI.Frame;
class FrameTests {
AntiSpamGUI gui = new AntiSpamGUI();
Frame f = gui.getFrame();
@Test
void testFrame() {
assertTrue(f instanceof Frame);
}
@Test
void testGetFrame() {
assertTrue(f.getFrame() instanceof JFrame);
}
@Test
void testGetChosenPathRules() {
JTextField path = f.getChosenPathRules();
f.setChosenPathRules( new JTextField("test"));
assertEquals(f.getChosenPathRules().getText(), "test");
f.setChosenPathRules(path);
}
@Test
void testGetChosenPathHam() {
JTextField path = f.getChosenPathHam();
f.setChosenPathHam( new JTextField("test"));
assertEquals(f.getChosenPathHam().getText(), "test");
f.setChosenPathHam(path);
}
@Test
void testGetChosenPathSpam() {
JTextField path = f.getChosenPathSpam();
f.setChosenPathSpam( new JTextField("test"));
assertEquals(f.getChosenPathSpam().getText(), "test");
f.setChosenPathSpam(path);
}
@Test
void testGetTableManual() {
assertTrue(f.getTableManual() instanceof JTable);
}
@Test
void testGetTableAuto() {
assertTrue(f.getTableAuto() instanceof JTable);
}
@Test
void testGetGui() {
assertTrue(f.getGui() instanceof AntiSpamGUI);
}
@Test
void testIsPathValid() {
gui.getAntiSpamFilterProblem().readHam("./files/ham.log");
gui.getAntiSpamFilterProblem().readSpam("./files/spam.log");
gui.getAntiSpamFilterProblem().readRules("./files/rules.cf");
assertEquals(f.isPathValid(), true);
gui.getAntiSpamFilterProblem().setRules(new LinkedHashMap<String, Double>());
assertEquals(f.isPathValid(), false);
}
@Test
void testChangeButtons() {
gui.getAntiSpamFilterProblem().readHam("./files/ham.log");
gui.getAntiSpamFilterProblem().readSpam("./files/spam.log");
gui.getAntiSpamFilterProblem().readRules("./files/rules.cf");
assertEquals(f.isPathValid(), true);
f.testButton = new JButton("");
f.testButton.setEnabled(false);
f.generateButton = new JButton("");
f.generateButton .setEnabled(false);
f.saveButtonAuto = new JButton("");
f.saveButtonAuto.setEnabled(false);
f.saveButtonTest = new JButton("");
f.saveButtonTest.setEnabled(false);
assertEquals(f.getTestButton().isEnabled(), false);
assertEquals(f.getSaveButtonAuto().isEnabled(), false);
f.changeButtons();
assertEquals(f.getTestButton().isEnabled(), true);
assertEquals(f.getSaveButtonAuto().isEnabled(), true);
}
@Test
void testSetSpinnerFN() {
f.spinnerFN = new JTextField("");
f.setSpinnerFN("test");
assertEquals(f.spinnerFN.getText(), "test");
}
@Test
void testSetSpinnerFP() {
f.spinnerFP = new JTextField("");
f.setSpinnerFP("test");
assertEquals(f.getSpinnerFP().getText(), "test");
}
@Test
void testSetFieldAutoFP() {
f.fieldAutoFP= new JTextField("");
f.setFieldAutoFP("test");
assertEquals(f.getFieldAutoFP().getText(), "test");
}
@Test
void testSetFieldAutoFN() {
f.fieldAutoFN= new JTextField("");
f.setFieldAutoFN("test");
assertEquals(f.getFieldAutoFN().getText(), "test");
}
@Test
void testGetSpinnerFN() {
f.spinnerFN = new JTextField("");
assertTrue(f.getSpinnerFN() instanceof JTextField);
}
@Test
void testGetSpinnerFP() {
f.spinnerFP = new JTextField("");
assertTrue(f.getSpinnerFP() instanceof JTextField);
}
@Test
void testGetFieldAutoFP() {
f.fieldAutoFP= new JTextField("");
assertTrue(f.getFieldAutoFP() instanceof JTextField);
}
@Test
void testGetFieldAutoFN() {
f.fieldAutoFN= new JTextField("");
assertTrue(f.getFieldAutoFN() instanceof JTextField);
}
}
| UTF-8 | Java | 3,915 | java | FrameTests.java | Java | []
| null | []
| package jUnit;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.*;
import java.awt.Component;
import java.awt.List;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextField;
import org.junit.jupiter.api.Test;
import antiSpamUI.AntiSpamGUI;
import antiSpamUI.Frame;
class FrameTests {
AntiSpamGUI gui = new AntiSpamGUI();
Frame f = gui.getFrame();
@Test
void testFrame() {
assertTrue(f instanceof Frame);
}
@Test
void testGetFrame() {
assertTrue(f.getFrame() instanceof JFrame);
}
@Test
void testGetChosenPathRules() {
JTextField path = f.getChosenPathRules();
f.setChosenPathRules( new JTextField("test"));
assertEquals(f.getChosenPathRules().getText(), "test");
f.setChosenPathRules(path);
}
@Test
void testGetChosenPathHam() {
JTextField path = f.getChosenPathHam();
f.setChosenPathHam( new JTextField("test"));
assertEquals(f.getChosenPathHam().getText(), "test");
f.setChosenPathHam(path);
}
@Test
void testGetChosenPathSpam() {
JTextField path = f.getChosenPathSpam();
f.setChosenPathSpam( new JTextField("test"));
assertEquals(f.getChosenPathSpam().getText(), "test");
f.setChosenPathSpam(path);
}
@Test
void testGetTableManual() {
assertTrue(f.getTableManual() instanceof JTable);
}
@Test
void testGetTableAuto() {
assertTrue(f.getTableAuto() instanceof JTable);
}
@Test
void testGetGui() {
assertTrue(f.getGui() instanceof AntiSpamGUI);
}
@Test
void testIsPathValid() {
gui.getAntiSpamFilterProblem().readHam("./files/ham.log");
gui.getAntiSpamFilterProblem().readSpam("./files/spam.log");
gui.getAntiSpamFilterProblem().readRules("./files/rules.cf");
assertEquals(f.isPathValid(), true);
gui.getAntiSpamFilterProblem().setRules(new LinkedHashMap<String, Double>());
assertEquals(f.isPathValid(), false);
}
@Test
void testChangeButtons() {
gui.getAntiSpamFilterProblem().readHam("./files/ham.log");
gui.getAntiSpamFilterProblem().readSpam("./files/spam.log");
gui.getAntiSpamFilterProblem().readRules("./files/rules.cf");
assertEquals(f.isPathValid(), true);
f.testButton = new JButton("");
f.testButton.setEnabled(false);
f.generateButton = new JButton("");
f.generateButton .setEnabled(false);
f.saveButtonAuto = new JButton("");
f.saveButtonAuto.setEnabled(false);
f.saveButtonTest = new JButton("");
f.saveButtonTest.setEnabled(false);
assertEquals(f.getTestButton().isEnabled(), false);
assertEquals(f.getSaveButtonAuto().isEnabled(), false);
f.changeButtons();
assertEquals(f.getTestButton().isEnabled(), true);
assertEquals(f.getSaveButtonAuto().isEnabled(), true);
}
@Test
void testSetSpinnerFN() {
f.spinnerFN = new JTextField("");
f.setSpinnerFN("test");
assertEquals(f.spinnerFN.getText(), "test");
}
@Test
void testSetSpinnerFP() {
f.spinnerFP = new JTextField("");
f.setSpinnerFP("test");
assertEquals(f.getSpinnerFP().getText(), "test");
}
@Test
void testSetFieldAutoFP() {
f.fieldAutoFP= new JTextField("");
f.setFieldAutoFP("test");
assertEquals(f.getFieldAutoFP().getText(), "test");
}
@Test
void testSetFieldAutoFN() {
f.fieldAutoFN= new JTextField("");
f.setFieldAutoFN("test");
assertEquals(f.getFieldAutoFN().getText(), "test");
}
@Test
void testGetSpinnerFN() {
f.spinnerFN = new JTextField("");
assertTrue(f.getSpinnerFN() instanceof JTextField);
}
@Test
void testGetSpinnerFP() {
f.spinnerFP = new JTextField("");
assertTrue(f.getSpinnerFP() instanceof JTextField);
}
@Test
void testGetFieldAutoFP() {
f.fieldAutoFP= new JTextField("");
assertTrue(f.getFieldAutoFP() instanceof JTextField);
}
@Test
void testGetFieldAutoFN() {
f.fieldAutoFN= new JTextField("");
assertTrue(f.getFieldAutoFN() instanceof JTextField);
}
}
| 3,915 | 0.718774 | 0.718774 | 161 | 23.316771 | 20.251961 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.708075 | false | false | 4 |
8cc534477d21085c950da86c251d6edbb949e164 | 9,904,194,586,268 | af8c827c1e382db4865cf8028fcb428f5586333a | /HackBulgariaCourse/src/week08/ToSmash.java | 02e2adb3a5d07ac41fcaa7fe2460c5204619c45a | []
| no_license | GeorgiStankov/JavaRep | https://github.com/GeorgiStankov/JavaRep | 4b1be22b9cb03138a94e4eb349c5fb117340696e | 3df7f73cf9a086f3e281875fcf8229e81cd78577 | refs/heads/master | 2021-01-17T12:39:43.641000 | 2017-03-31T12:09:44 | 2017-03-31T12:09:44 | 58,406,977 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package week08;
public class ToSmash extends Weapon{
int maxDurability;
public ToSmash(int damage, int durability) {
super(damage,durability);
maxDurability=durability;
}
public int hit() {
if (durability > 0 && durability >= maxDurability / 2) {
durability--;
return damage;
}
if (damage > 1) {
damage--;
}
return damage;
}
}
| UTF-8 | Java | 360 | java | ToSmash.java | Java | []
| null | []
| package week08;
public class ToSmash extends Weapon{
int maxDurability;
public ToSmash(int damage, int durability) {
super(damage,durability);
maxDurability=durability;
}
public int hit() {
if (durability > 0 && durability >= maxDurability / 2) {
durability--;
return damage;
}
if (damage > 1) {
damage--;
}
return damage;
}
}
| 360 | 0.658333 | 0.644444 | 22 | 15.363636 | 15.420015 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.772727 | false | false | 4 |
1bfb965f1470b451cd5a5beed73b3367468ecd41 | 5,884,105,251,327 | 0a9a2da70b5297d6f4f232211c86f00945ebb2be | /src/sample/MinusProfWindow.java | c6ded8b40e66a437f2b3b05ed9c18df18921ebf1 | []
| no_license | yardengum/ex6New | https://github.com/yardengum/ex6New | c53af6155ba2fb640173539dc936545e70c152ba | 508bf3e7b31da200a27a1509fd17d678d18532d7 | refs/heads/master | 2016-09-11T19:54:29.812000 | 2016-01-18T19:16:24 | 2016-01-18T19:16:24 | 49,679,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sample;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* Created by yardengum on 1/17/16.
*/
public class MinusProfWindow {
public void show(String id) {
try {
String fromUser = "11 " + id;
PrintWriter out = new PrintWriter((Connect.getSock()).getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader((Connect.getSock()).getInputStream()));
out.println(fromUser);
in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 812 | java | MinusProfWindow.java | Java | [
{
"context": "er;\nimport java.io.PrintWriter;\n\n/**\n * Created by yardengum on 1/17/16.\n */\npublic class MinusProfWindow {\n ",
"end": 280,
"score": 0.999697208404541,
"start": 271,
"tag": "USERNAME",
"value": "yardengum"
}
]
| null | []
| package sample;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* Created by yardengum on 1/17/16.
*/
public class MinusProfWindow {
public void show(String id) {
try {
String fromUser = "11 " + id;
PrintWriter out = new PrintWriter((Connect.getSock()).getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader((Connect.getSock()).getInputStream()));
out.println(fromUser);
in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 812 | 0.62069 | 0.612069 | 29 | 27 | 25.662262 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.551724 | false | false | 4 |
11706f738a5bb5d0ddad765471077ae74b7a4920 | 27,204,322,854,954 | 35b2a2677ce73ca970a10e7fb389c6f18625e778 | /back13411/src/back13411/Main.java | 3689c6676b97e5bf08b927e9f1027c60e501b04c | []
| no_license | JUNGJAEGOO/SSDpurchaseCELEBRATION | https://github.com/JUNGJAEGOO/SSDpurchaseCELEBRATION | fffb73982f35b4877cb4ee9ef22fc087b81d81fd | 00a625e790a4beb085bbb9a4d92e16f560096d6c | refs/heads/master | 2021-09-29T03:43:48.720000 | 2018-11-23T12:52:42 | 2018-11-23T12:52:42 | 110,844,757 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package back13411;
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
ArrayList<node> list = new ArrayList<>();
for (int i = 0 ; i < N ; i++) {
double x = in.nextDouble();
double y = in.nextDouble();
double v = in.nextDouble();
list.add(new node(i,x,y,v));
}
Collections.sort(list);
for (int i = 0 ; i < N ; i++) {
System.out.println(list.get(i).idx+1);
}
}
public static class node implements Comparable<node>{
int idx;
double x;
double y;
double v;
double stan;
@Override
public int compareTo(node o) {
if ( this.stan > o.stan) {
return 1;
}else if ( this.stan == o.stan) {
if ( this.idx > o.idx) {
return 1;
}else {
return -1;
}
}
return -1;
}
node (int idx,double x,double y,double v){
this.idx = idx;
this.x = x;
this.y =y;
this.v = v;
stan = Math.sqrt(( x*x + y*y ))/ v;
}
}
}
| UTF-8 | Java | 1,008 | java | Main.java | Java | []
| null | []
| package back13411;
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
ArrayList<node> list = new ArrayList<>();
for (int i = 0 ; i < N ; i++) {
double x = in.nextDouble();
double y = in.nextDouble();
double v = in.nextDouble();
list.add(new node(i,x,y,v));
}
Collections.sort(list);
for (int i = 0 ; i < N ; i++) {
System.out.println(list.get(i).idx+1);
}
}
public static class node implements Comparable<node>{
int idx;
double x;
double y;
double v;
double stan;
@Override
public int compareTo(node o) {
if ( this.stan > o.stan) {
return 1;
}else if ( this.stan == o.stan) {
if ( this.idx > o.idx) {
return 1;
}else {
return -1;
}
}
return -1;
}
node (int idx,double x,double y,double v){
this.idx = idx;
this.x = x;
this.y =y;
this.v = v;
stan = Math.sqrt(( x*x + y*y ))/ v;
}
}
}
| 1,008 | 0.551587 | 0.539683 | 56 | 17 | 14.284107 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.875 | false | false | 4 |
47d2b256d383be58cc15191ebdf2de801ed34a6b | 21,878,563,457,773 | 658426eb4a98b30c6e269076a4055868ab3c690b | /src/servlet/SaveServlet.java | a55a38415669ce1b66ec68e5c3079bdcb36f98d8 | []
| no_license | mkm303/matrixGameIntegral | https://github.com/mkm303/matrixGameIntegral | a095969b56648f29f1509d4302b36ef542b0cf4b | 856b6457a603907edf104ba397c0f27279d1dc57 | refs/heads/master | 2022-10-19T06:18:23.566000 | 2020-06-14T02:59:49 | 2020-06-14T02:59:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DAO.SaveDAO;
import model.SaveDateTime;
import model.User;
@WebServlet("/SaveServlet")
public class SaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String controle = request.getParameter("controle");
String message = "";
switch(controle) {
case "Save":
message = "セーブしますか?";
break;
case "Logout":
message = "ログアウトしますか?";
break;
case "Reset":
message = "このゲームをやり直しますか?";
break;
}//switch
request.setAttribute("message", message);
HttpSession session = request.getSession();
session.setAttribute("controle", controle);
String path ="/matrix.jsp";
RequestDispatcher dis = request.getRequestDispatcher(path);
dis.forward(request, response);
}//doGet()
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ---- get Parameters ----
request.setCharacterEncoding("UTF-8");
String comfirm = (String) request.getParameter("comfirm");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
ServletContext application = request.getServletContext();
List<Integer> colorDB = application.setAttribute(name, object);
String controle = (String) session.getAttribute("controle");
String saveDateTime = "";
// ---- switch (controle) ----
switch (controle) {
case "Save":
if (comfirm.equals("YES")) {
SaveDateTime sdt = new SaveDateTime();
saveDateTime = sdt.saveDateTime();
} else if (comfirm.equals("NO")) {
;
}
break;
case "Logout":
break;
case "Reset":
break;
}//switch
//---- call method ----
int puzzleId = user.getPuzzleId();
int point = user.getPoint();
boolean isSave = SaveDAO.saveGame(puzzleId, point, colorDB, saveDateTime);
if (isSave) {
}
}//doPost()
}//class
| UTF-8 | Java | 2,743 | java | SaveServlet.java | Java | []
| null | []
| package servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DAO.SaveDAO;
import model.SaveDateTime;
import model.User;
@WebServlet("/SaveServlet")
public class SaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String controle = request.getParameter("controle");
String message = "";
switch(controle) {
case "Save":
message = "セーブしますか?";
break;
case "Logout":
message = "ログアウトしますか?";
break;
case "Reset":
message = "このゲームをやり直しますか?";
break;
}//switch
request.setAttribute("message", message);
HttpSession session = request.getSession();
session.setAttribute("controle", controle);
String path ="/matrix.jsp";
RequestDispatcher dis = request.getRequestDispatcher(path);
dis.forward(request, response);
}//doGet()
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ---- get Parameters ----
request.setCharacterEncoding("UTF-8");
String comfirm = (String) request.getParameter("comfirm");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
ServletContext application = request.getServletContext();
List<Integer> colorDB = application.setAttribute(name, object);
String controle = (String) session.getAttribute("controle");
String saveDateTime = "";
// ---- switch (controle) ----
switch (controle) {
case "Save":
if (comfirm.equals("YES")) {
SaveDateTime sdt = new SaveDateTime();
saveDateTime = sdt.saveDateTime();
} else if (comfirm.equals("NO")) {
;
}
break;
case "Logout":
break;
case "Reset":
break;
}//switch
//---- call method ----
int puzzleId = user.getPuzzleId();
int point = user.getPoint();
boolean isSave = SaveDAO.saveGame(puzzleId, point, colorDB, saveDateTime);
if (isSave) {
}
}//doPost()
}//class
| 2,743 | 0.647256 | 0.646137 | 104 | 24.759615 | 24.351393 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576923 | false | false | 4 |
79aa48ca96fb7dc10f24d557fb93443408fa9f86 | 28,647,431,875,116 | 5c039038f96a1f35bb2cdc64093ec45aed0b347b | /src/test/java/com/ge/digital/utils/ParserUtilityTest.java | 68b05154b83dfbd4f82354e3038c8b968891a045 | []
| no_license | bismayamohapatra/WebCrawlerApplication | https://github.com/bismayamohapatra/WebCrawlerApplication | 807b5a13fc0cbfa6a162451c87adf273d9200fcf | bdf8ce02d7c15399e8cf29ebb662920616222750 | refs/heads/master | 2020-05-20T23:57:36.574000 | 2019-05-19T12:54:53 | 2019-05-19T12:54:53 | 185,815,887 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ge.digital.utils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ParserUtilityTest {
@Test
public void testIsNullOrEmpty_Empty() {
boolean isEmpty = ParserUtility.isNullOrEmpty("");
assertEquals(true,isEmpty);
}
@Test
public void testIsNullOrEmpty_NonEmpty() {
boolean isEmpty = ParserUtility.isNullOrEmpty("Test");
assertEquals(false,isEmpty);
}
@Test
public void testIsNullOrEmpty_Null() {
String str = null;
boolean isEmpty = ParserUtility.isNullOrEmpty(str);
assertEquals(true,isEmpty);
}
@Test
public void testIsNullOrEmpty_NotNull() {
String str = "Test1";
boolean isEmpty = ParserUtility.isNullOrEmpty(str);
assertEquals(false,isEmpty);
}
}
| UTF-8 | Java | 863 | java | ParserUtilityTest.java | Java | []
| null | []
| package com.ge.digital.utils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ParserUtilityTest {
@Test
public void testIsNullOrEmpty_Empty() {
boolean isEmpty = ParserUtility.isNullOrEmpty("");
assertEquals(true,isEmpty);
}
@Test
public void testIsNullOrEmpty_NonEmpty() {
boolean isEmpty = ParserUtility.isNullOrEmpty("Test");
assertEquals(false,isEmpty);
}
@Test
public void testIsNullOrEmpty_Null() {
String str = null;
boolean isEmpty = ParserUtility.isNullOrEmpty(str);
assertEquals(true,isEmpty);
}
@Test
public void testIsNullOrEmpty_NotNull() {
String str = "Test1";
boolean isEmpty = ParserUtility.isNullOrEmpty(str);
assertEquals(false,isEmpty);
}
}
| 863 | 0.633835 | 0.632677 | 34 | 23.382353 | 20.725113 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
e9f54e991442dfd2c12eb251bb0217accfb83423 | 18,665,927,897,626 | f7b9ab00c4eeb1db2170bbd1f28055391a523375 | /src/main/java/de/emp2020/alertEditor/Alert.java | ce62067fdade66d0dffc3d8b27544e5d811cf4ff | []
| no_license | JonasTimmermann/HerokuSpringTest | https://github.com/JonasTimmermann/HerokuSpringTest | 8745333e9a0dad6bd17ef373b5d029f40da945bc | 618076ff4679348fb2da2476ad7eee32f7c05b9a | refs/heads/master | 2021-03-13T12:22:02.235000 | 2020-03-11T22:34:44 | 2020-03-11T22:34:44 | 246,680,878 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.emp2020.alertEditor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.emp2020.Location.Place;
import de.emp2020.alertManager.Distance;
import de.emp2020.users.IUser;
import de.emp2020.users.User;
@Entity
@Transactional
/**
* Domain for a single Alert
*/
public class Alert implements IAlert {
@GeneratedValue
@Id
private Integer alertId; // unique autogenerated identifier, used cross service to identify alerts
private boolean isTriggered = false; // true if alert is currently active, no further notifications will be sent for repeat triggers
private String title = ""; // Human readable name of the alert
private String promQuery = ""; // PromQL expression that, when returning ANY VALUE is considered true and thus trigger the alert
private String description = ""; // Human readable description of what the alert will be monitoring
@ManyToOne
private Place place = null;
// a list of recent triggers, mostly for logging purposes.
// The list is expected to be ordered with the first element being the earliest trigger and the last element being the latest trigger.
@OneToMany(cascade = CascadeType.ALL)
private List<AlertTimestamp> pastTriggers = new ArrayList<AlertTimestamp>();
// The collection of users that is affiliated with the respective alert
@ManyToOne
private User owner; // The sole person with editing rights to the alert
@ManyToOne(cascade = CascadeType.ALL)
private User acceptedUser;
// The user who offered to deal with the alert
@ManyToMany(cascade = CascadeType.ALL)
private List<User> assignedUsers = new ArrayList<User>(); // All users who have been assigned to the alert by an administrator
@ManyToMany(cascade = CascadeType.ALL)
private List<User> transferredUsers = new ArrayList<User>(); // Any users the alert has been messaged to from the Android application
// Distances of tracked user devices
@OneToMany(cascade = CascadeType.ALL)
private List<Distance> distances = new ArrayList<Distance>();
@JsonIgnore
//@JsonProperty("owner")
public String getJsonOwner ()
{
return owner.getUserName();
}
@JsonIgnore
//@JsonProperty("assignedUsers")
public List<String> getAssignedJsonUsers ()
{
return this.getAssignedUsers().stream().map(user -> user.getUserName()).collect(Collectors.toList());
}
/**
* Unites all messageable users into one single collection for retrieval
* @return
* a collection of the interface {@code IUser} containing the owner and all assigned or transfered users
*/
@JsonIgnore
public Collection<IUser> getAllUsers ()
{
List<IUser> users = new ArrayList<IUser>();
if (assignedUsers != null)
{
users.addAll(assignedUsers);
}
if (transferredUsers != null)
{
users.addAll(transferredUsers);
}
return users;
}
/**
* Adds another user to be assigned to the Alert
*/
@JsonIgnore
public void addAssignedUser (User user)
{
assignedUsers.add(user);
}
/**
* Adds another user who has been transfered to the alert, they are expected to be removed once alert has been resolved
* @param user
* a user who will be tracked as transfered
*/
@JsonIgnore
public void addTransferredUser (User user)
{
transferredUsers.add(user);
}
/**
* Triggers the alert, setting it's status to being triggered and logging a unix timestamp of the current system time
*/
@JsonIgnore
public void trigger ()
{
isTriggered = true;
AlertTimestamp timeStamp = new AlertTimestamp();
timeStamp.setStamp(System.currentTimeMillis());
pastTriggers.add(timeStamp);
}
/**
* reads the unix timestamp of the current latest trigger
*/
@JsonIgnore
public Long getTime ()
{
if (pastTriggers == null || pastTriggers.isEmpty())
{
return null;
}
return pastTriggers.get(pastTriggers.size()-1).getStamp();
}
// Autogenerated Getters and Setters
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonProperty("title")
public void setTitle(String alertName) {
this.title = alertName;
}
@JsonProperty("alertId")
public Integer getId() {
return this.alertId;
}
@JsonProperty("alertId")
public void setId(Integer id) {
this.alertId = id;
}
@JsonIgnore
public User getOwner() {
return owner;
}
@JsonIgnore
public void setOwner(User owner) {
this.owner = owner;
}
@JsonIgnore
public User getAcceptedUser() {
return acceptedUser;
}
@JsonIgnore
public void setAcceptedUser(User acceptedUser) {
this.acceptedUser = acceptedUser;
}
@JsonIgnore
public List<User> getAssignedUsers() {
return assignedUsers;
}
@JsonIgnore
public void setAssignedUsers(List<User> assignedUsers) {
this.assignedUsers = assignedUsers;
}
@JsonIgnore
public List<User> getTransferredUsers() {
return transferredUsers;
}
@JsonIgnore
public void setTransferredUsers(List<User> transferredUsers) {
this.transferredUsers = transferredUsers;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("promQuery")
public String getQuery() {
return promQuery;
}
@JsonProperty("promQuery")
public void setQuery(String query) {
this.promQuery = query;
}
@JsonProperty("isTriggered")
public boolean isTriggered() {
return isTriggered;
}
@JsonIgnore
public void setTriggered(boolean isTriggered) {
this.isTriggered = isTriggered;
}
@JsonProperty("pastTriggers")
public List<AlertTimestamp> getPastTriggers() {
return pastTriggers;
}
@JsonIgnore
public void setPastTriggers(List<AlertTimestamp> pastTriggers) {
this.pastTriggers = pastTriggers;
}
@JsonIgnore
public String toString ()
{
return "{" + alertId + ", " + title + ", " + promQuery + "}";
}
@JsonIgnore
public List<Distance> getDistances() {
return distances;
}
@JsonIgnore
public void setDistances(List<Distance> distances) {
this.distances = distances;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
@Override
public Double getLongitude() {
if (place == null)
{
return null;
}
return place.getHorizontalPosition();
}
@Override
public Double getLatitude() {
if (place == null)
{
return null;
}
return place.getVerticalPosition();
}
}
| UTF-8 | Java | 6,875 | java | Alert.java | Java | []
| null | []
| package de.emp2020.alertEditor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.emp2020.Location.Place;
import de.emp2020.alertManager.Distance;
import de.emp2020.users.IUser;
import de.emp2020.users.User;
@Entity
@Transactional
/**
* Domain for a single Alert
*/
public class Alert implements IAlert {
@GeneratedValue
@Id
private Integer alertId; // unique autogenerated identifier, used cross service to identify alerts
private boolean isTriggered = false; // true if alert is currently active, no further notifications will be sent for repeat triggers
private String title = ""; // Human readable name of the alert
private String promQuery = ""; // PromQL expression that, when returning ANY VALUE is considered true and thus trigger the alert
private String description = ""; // Human readable description of what the alert will be monitoring
@ManyToOne
private Place place = null;
// a list of recent triggers, mostly for logging purposes.
// The list is expected to be ordered with the first element being the earliest trigger and the last element being the latest trigger.
@OneToMany(cascade = CascadeType.ALL)
private List<AlertTimestamp> pastTriggers = new ArrayList<AlertTimestamp>();
// The collection of users that is affiliated with the respective alert
@ManyToOne
private User owner; // The sole person with editing rights to the alert
@ManyToOne(cascade = CascadeType.ALL)
private User acceptedUser;
// The user who offered to deal with the alert
@ManyToMany(cascade = CascadeType.ALL)
private List<User> assignedUsers = new ArrayList<User>(); // All users who have been assigned to the alert by an administrator
@ManyToMany(cascade = CascadeType.ALL)
private List<User> transferredUsers = new ArrayList<User>(); // Any users the alert has been messaged to from the Android application
// Distances of tracked user devices
@OneToMany(cascade = CascadeType.ALL)
private List<Distance> distances = new ArrayList<Distance>();
@JsonIgnore
//@JsonProperty("owner")
public String getJsonOwner ()
{
return owner.getUserName();
}
@JsonIgnore
//@JsonProperty("assignedUsers")
public List<String> getAssignedJsonUsers ()
{
return this.getAssignedUsers().stream().map(user -> user.getUserName()).collect(Collectors.toList());
}
/**
* Unites all messageable users into one single collection for retrieval
* @return
* a collection of the interface {@code IUser} containing the owner and all assigned or transfered users
*/
@JsonIgnore
public Collection<IUser> getAllUsers ()
{
List<IUser> users = new ArrayList<IUser>();
if (assignedUsers != null)
{
users.addAll(assignedUsers);
}
if (transferredUsers != null)
{
users.addAll(transferredUsers);
}
return users;
}
/**
* Adds another user to be assigned to the Alert
*/
@JsonIgnore
public void addAssignedUser (User user)
{
assignedUsers.add(user);
}
/**
* Adds another user who has been transfered to the alert, they are expected to be removed once alert has been resolved
* @param user
* a user who will be tracked as transfered
*/
@JsonIgnore
public void addTransferredUser (User user)
{
transferredUsers.add(user);
}
/**
* Triggers the alert, setting it's status to being triggered and logging a unix timestamp of the current system time
*/
@JsonIgnore
public void trigger ()
{
isTriggered = true;
AlertTimestamp timeStamp = new AlertTimestamp();
timeStamp.setStamp(System.currentTimeMillis());
pastTriggers.add(timeStamp);
}
/**
* reads the unix timestamp of the current latest trigger
*/
@JsonIgnore
public Long getTime ()
{
if (pastTriggers == null || pastTriggers.isEmpty())
{
return null;
}
return pastTriggers.get(pastTriggers.size()-1).getStamp();
}
// Autogenerated Getters and Setters
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonProperty("title")
public void setTitle(String alertName) {
this.title = alertName;
}
@JsonProperty("alertId")
public Integer getId() {
return this.alertId;
}
@JsonProperty("alertId")
public void setId(Integer id) {
this.alertId = id;
}
@JsonIgnore
public User getOwner() {
return owner;
}
@JsonIgnore
public void setOwner(User owner) {
this.owner = owner;
}
@JsonIgnore
public User getAcceptedUser() {
return acceptedUser;
}
@JsonIgnore
public void setAcceptedUser(User acceptedUser) {
this.acceptedUser = acceptedUser;
}
@JsonIgnore
public List<User> getAssignedUsers() {
return assignedUsers;
}
@JsonIgnore
public void setAssignedUsers(List<User> assignedUsers) {
this.assignedUsers = assignedUsers;
}
@JsonIgnore
public List<User> getTransferredUsers() {
return transferredUsers;
}
@JsonIgnore
public void setTransferredUsers(List<User> transferredUsers) {
this.transferredUsers = transferredUsers;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("promQuery")
public String getQuery() {
return promQuery;
}
@JsonProperty("promQuery")
public void setQuery(String query) {
this.promQuery = query;
}
@JsonProperty("isTriggered")
public boolean isTriggered() {
return isTriggered;
}
@JsonIgnore
public void setTriggered(boolean isTriggered) {
this.isTriggered = isTriggered;
}
@JsonProperty("pastTriggers")
public List<AlertTimestamp> getPastTriggers() {
return pastTriggers;
}
@JsonIgnore
public void setPastTriggers(List<AlertTimestamp> pastTriggers) {
this.pastTriggers = pastTriggers;
}
@JsonIgnore
public String toString ()
{
return "{" + alertId + ", " + title + ", " + promQuery + "}";
}
@JsonIgnore
public List<Distance> getDistances() {
return distances;
}
@JsonIgnore
public void setDistances(List<Distance> distances) {
this.distances = distances;
}
public Place getPlace() {
return place;
}
public void setPlace(Place place) {
this.place = place;
}
@Override
public Double getLongitude() {
if (place == null)
{
return null;
}
return place.getHorizontalPosition();
}
@Override
public Double getLatitude() {
if (place == null)
{
return null;
}
return place.getVerticalPosition();
}
}
| 6,875 | 0.730909 | 0.727855 | 274 | 24.09124 | 27.190643 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.605839 | false | false | 4 |
bffac69cf801c7014b9cdacc3a6a366a5a02abc8 | 27,822,798,208,459 | 71bf695232cc12c0b20414b1650cd118b8011af3 | /src/main/java/com/hotels/domain/exceptions/ReservationNotAvailableAdvice.java | d6fbdd2abab3cb73508bb8ae2d74afdc779f9f55 | []
| no_license | tableonthewall/hotel-reservation-rest-api | https://github.com/tableonthewall/hotel-reservation-rest-api | ef7317183c985d07be7cdc95391b8eae49378b59 | 4ae1f03c7cefecf790b12b7ad9f62ada935ad21d | refs/heads/master | 2023-08-22T06:47:15.125000 | 2021-10-03T06:43:24 | 2021-10-03T06:43:24 | 412,998,496 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hotels.domain.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ReservationNotAvailableAdvice {
@ResponseBody
@ExceptionHandler(ReservationNotAvailableException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String reservationNotAvailableException(ReservationNotAvailableException ex){
return ex.getMessage();
}
}
| UTF-8 | Java | 645 | java | ReservationNotAvailableAdvice.java | Java | []
| null | []
| package com.hotels.domain.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ReservationNotAvailableAdvice {
@ResponseBody
@ExceptionHandler(ReservationNotAvailableException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String reservationNotAvailableException(ReservationNotAvailableException ex){
return ex.getMessage();
}
}
| 645 | 0.829457 | 0.829457 | 17 | 36.941177 | 25.574507 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 4 |
5add9126ed0e439cc771fd4032a5005456869c98 | 27,822,798,206,637 | 657e8fa46358e67a1bb5500cb7b9f545a83994c2 | /src/main/java/com/standardstate/crypto/util/Divisibility.java | 922fa77916a4e426b789c708af68c87a038862d4 | [
"MIT"
]
| permissive | spacemojo/crypto | https://github.com/spacemojo/crypto | a28ac0e161ab17261240c4e371acba61e681905e | 3c2c14f81b8f07975228e0f9c8e950bf9921f6fe | refs/heads/master | 2017-09-07T21:49:44.331000 | 2016-03-28T14:47:54 | 2016-03-28T14:47:54 | 18,767,755 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.standardstate.crypto.util;
public class Divisibility {
public static boolean by2(final int n) {
if(n == 0) {
return true;
}
return ((n & 1) == 0);
}
}
| UTF-8 | Java | 214 | java | Divisibility.java | Java | []
| null | []
| package com.standardstate.crypto.util;
public class Divisibility {
public static boolean by2(final int n) {
if(n == 0) {
return true;
}
return ((n & 1) == 0);
}
}
| 214 | 0.514019 | 0.495327 | 12 | 16.833334 | 15.021281 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
fc70be778a6fe359e0208da569aca7fa3a3d57b6 | 1,511,828,517,964 | fe13ccb94a2a9638e93f19aa249679f74550f6ca | /ProjetoSpring/src/main/java/br/com/projetospring/dao/UsuarioDAO.java | ff6140869faf3d8680e958fdd3239d841d204deb | []
| no_license | god666/RepositorioEstudo | https://github.com/god666/RepositorioEstudo | 70deaaac78c2a115219667f75fa79c6a58b3024a | 987f35e1abc3366ba36a546a013e7ae4f471bc80 | refs/heads/master | 2020-06-20T04:39:34.674000 | 2016-12-06T18:16:11 | 2016-12-06T18:16:11 | 74,881,246 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.projetospring.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import br.com.projetospring.entidade.Usuario;
/*A annotation @Repository indica que será criado um bean no
* arquivo applicationContext.xml*/
@Repository
public class UsuarioDAO implements InterfaceGenericoDAO<Usuario> {
/*A annotation @PersistenceContext indica que o SPRING irá fazer a injeção
* (da Injeção de Dependência) do EntityManager para o DAO*/
@PersistenceContext
private EntityManager em;
public UsuarioDAO(EntityManager em){
this.em = em;
}
//Este contrutor é necessário para estrutura a classe UsuarioDAO como uma classe bean
public UsuarioDAO() {}
@Transactional
@Override
public Usuario salvar(Usuario usuario) {
return em.merge(usuario);
}
@Transactional
@Override
public void excluir(Usuario usuario) {
em.remove(usuario);
}
@Override
public Usuario buscarPorId(int id) {
Usuario retorno = em.find(Usuario.class, id);
return retorno;
}
@Override
public List<Usuario> buscarTodos() {
Query q = em.createQuery("select u from Usuario u");
return q.getResultList();
}
}
| ISO-8859-1 | Java | 1,340 | java | UsuarioDAO.java | Java | []
| null | []
| package br.com.projetospring.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import br.com.projetospring.entidade.Usuario;
/*A annotation @Repository indica que será criado um bean no
* arquivo applicationContext.xml*/
@Repository
public class UsuarioDAO implements InterfaceGenericoDAO<Usuario> {
/*A annotation @PersistenceContext indica que o SPRING irá fazer a injeção
* (da Injeção de Dependência) do EntityManager para o DAO*/
@PersistenceContext
private EntityManager em;
public UsuarioDAO(EntityManager em){
this.em = em;
}
//Este contrutor é necessário para estrutura a classe UsuarioDAO como uma classe bean
public UsuarioDAO() {}
@Transactional
@Override
public Usuario salvar(Usuario usuario) {
return em.merge(usuario);
}
@Transactional
@Override
public void excluir(Usuario usuario) {
em.remove(usuario);
}
@Override
public Usuario buscarPorId(int id) {
Usuario retorno = em.find(Usuario.class, id);
return retorno;
}
@Override
public List<Usuario> buscarTodos() {
Query q = em.createQuery("select u from Usuario u");
return q.getResultList();
}
}
| 1,340 | 0.769346 | 0.769346 | 55 | 23.200001 | 22.759134 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.054545 | false | false | 4 |
f8642016addf648b01771eecfdee1fec8e2c67f2 | 24,799,141,237,617 | ea6660fd3505ea3c1d3d848c5dba47713dd580d8 | /eladmin-system/src/main/java/com/study/web/dao/DistributionDao.java | bc2a03cbc4a20c9e3a1dbd8676fb11d0ed7fa691 | [
"Apache-2.0"
]
| permissive | zengshunchao/eladmin | https://github.com/zengshunchao/eladmin | 0b2fb70f2d7bb748a49c48984c5a78d804c7319e | 3cb81c9a1a887e80b981e7a8a42a95ac78273dbb | refs/heads/master | 2023-02-02T14:59:38.970000 | 2020-12-24T01:07:41 | 2020-12-24T01:07:41 | 302,866,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.study.web.dao;
import com.study.web.dto.BackGroundDistributionInfoDto;
import com.study.web.dto.DistributionDto;
import com.study.web.dto.WxUserDto;
import com.study.web.entity.Distribution;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 分销员表(Distribution)表数据库访问层
*
* @author zengsc
* @since 2020-10-09 16:10:38
*/
@Repository
public interface DistributionDao {
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
Distribution queryById(Long id);
/**
* 查询指定行数据
*
* @param offset 查询起始位置
* @param limit 查询条数
* @return 对象列表
*/
List<Distribution> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);
/**
* 通过实体作为筛选条件查询
*
* @param distribution 实例对象
* @return 对象列表
*/
List<Distribution> queryAll(Distribution distribution);
/**
* 新增数据
*
* @param distribution 实例对象
* @return 影响行数
*/
int insert(Distribution distribution);
/**
* 修改数据
*
* @param distribution 实例对象
* @return 影响行数
*/
int update(Distribution distribution);
/**
* 通过主键删除数据
*
* @param id 主键
* @return 影响行数
*/
int deleteById(Long id);
Distribution queryByWxUserId(Long wxUserid);
/**
* 下级分销员
*
* @param distributionDto
* @return
*/
List<DistributionDto> getDistributionList(DistributionDto distributionDto);
/**
* 总记录数
*
* @param distributionDto
* @return
*/
int totalList(DistributionDto distributionDto);
/**
* 分销管理-分销列表
*
* @param startNum
* @param pageSize
* @return
*/
List<BackGroundDistributionInfoDto> queryAllDistribution(BackGroundDistributionInfoDto backGroundDistributionInfoDto, @Param("startNum") int startNum, @Param("pageSize") int pageSize);
/**
* 后台-分销管理统计
*
* @return
*/
int backGroundQueryDistributionTotal(BackGroundDistributionInfoDto backGroundDistributionInfoDto);
} | UTF-8 | Java | 2,368 | java | DistributionDao.java | Java | [
{
"context": "t;\n\n/**\n * 分销员表(Distribution)表数据库访问层\n *\n * @author zengsc\n * @since 2020-10-09 16:10:38\n */\n@Repository\npub",
"end": 376,
"score": 0.9996492266654968,
"start": 370,
"tag": "USERNAME",
"value": "zengsc"
}
]
| null | []
| package com.study.web.dao;
import com.study.web.dto.BackGroundDistributionInfoDto;
import com.study.web.dto.DistributionDto;
import com.study.web.dto.WxUserDto;
import com.study.web.entity.Distribution;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 分销员表(Distribution)表数据库访问层
*
* @author zengsc
* @since 2020-10-09 16:10:38
*/
@Repository
public interface DistributionDao {
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
Distribution queryById(Long id);
/**
* 查询指定行数据
*
* @param offset 查询起始位置
* @param limit 查询条数
* @return 对象列表
*/
List<Distribution> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);
/**
* 通过实体作为筛选条件查询
*
* @param distribution 实例对象
* @return 对象列表
*/
List<Distribution> queryAll(Distribution distribution);
/**
* 新增数据
*
* @param distribution 实例对象
* @return 影响行数
*/
int insert(Distribution distribution);
/**
* 修改数据
*
* @param distribution 实例对象
* @return 影响行数
*/
int update(Distribution distribution);
/**
* 通过主键删除数据
*
* @param id 主键
* @return 影响行数
*/
int deleteById(Long id);
Distribution queryByWxUserId(Long wxUserid);
/**
* 下级分销员
*
* @param distributionDto
* @return
*/
List<DistributionDto> getDistributionList(DistributionDto distributionDto);
/**
* 总记录数
*
* @param distributionDto
* @return
*/
int totalList(DistributionDto distributionDto);
/**
* 分销管理-分销列表
*
* @param startNum
* @param pageSize
* @return
*/
List<BackGroundDistributionInfoDto> queryAllDistribution(BackGroundDistributionInfoDto backGroundDistributionInfoDto, @Param("startNum") int startNum, @Param("pageSize") int pageSize);
/**
* 后台-分销管理统计
*
* @return
*/
int backGroundQueryDistributionTotal(BackGroundDistributionInfoDto backGroundDistributionInfoDto);
} | 2,368 | 0.627488 | 0.620853 | 104 | 19.298077 | 25.287151 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.211538 | false | false | 4 |
c06b4c1500307781f72c5e98761d06f8fa0fa1e5 | 10,479,720,272,265 | 8d8fb4dfd7be299076651e02d26eba6cd879428c | /newrelic-agent/src/test/java/com/newrelic/agent/browser/BrowserTransactionStateTest.java | e45477085695a1d0a77d4e8f63b1c95bb420b0cd | [
"Apache-2.0"
]
| permissive | newrelic/newrelic-java-agent | https://github.com/newrelic/newrelic-java-agent | db6dd20f6ba3f43909b004ce4a058f589dd4b017 | eb298ecd8d31f93622388aa12d3ba1e68a58f912 | refs/heads/main | 2023-08-31T05:14:44.428000 | 2023-08-29T10:37:35 | 2023-08-30T18:08:38 | 275,016,355 | 177 | 150 | Apache-2.0 | false | 2023-09-11T14:50:06 | 2020-06-25T21:13:42 | 2023-08-15T16:48:00 | 2023-09-11T12:49:12 | 39,408 | 165 | 129 | 105 | Java | false | false | /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.browser;
import com.google.common.collect.ImmutableMap;
import com.newrelic.agent.MockConfigService;
import com.newrelic.agent.MockCoreService;
import com.newrelic.agent.MockRPMService;
import com.newrelic.agent.MockRPMServiceManager;
import com.newrelic.agent.MockServiceManager;
import com.newrelic.agent.ThreadService;
import com.newrelic.agent.Transaction;
import com.newrelic.agent.TransactionService;
import com.newrelic.agent.attributes.AttributesService;
import com.newrelic.agent.bridge.TransactionNamePriority;
import com.newrelic.agent.config.AgentConfig;
import com.newrelic.agent.config.AgentConfigFactory;
import com.newrelic.agent.config.AgentConfigImpl;
import com.newrelic.agent.config.AttributesConfigImpl;
import com.newrelic.agent.config.BrowserMonitoringConfig;
import com.newrelic.agent.config.ConfigService;
import com.newrelic.agent.config.ConfigServiceFactory;
import com.newrelic.agent.config.TransactionTracerConfigImpl;
import com.newrelic.agent.dispatchers.Dispatcher;
import com.newrelic.agent.errors.ErrorServiceImpl;
import com.newrelic.agent.service.ServiceFactory;
import com.newrelic.agent.stats.StatsService;
import com.newrelic.agent.trace.TransactionTraceService;
import com.newrelic.agent.transaction.PriorityTransactionName;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
public class BrowserTransactionStateTest {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
MockServiceManager serviceManager = new MockServiceManager();
serviceManager.setConfigService(new MockConfigService(AgentConfigFactory.createAgentConfig(
Collections.<String, Object>emptyMap(), Collections.<String, Object>emptyMap(), null)));
serviceManager.setBrowserService(mockBrowserService);
ServiceFactory.setServiceManager(serviceManager);
}
@Test
public void getBrowserTimingHeaderForJsp_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_nullContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
// For content-type "text/html"
@Test
public void getBrowserTimingHeaderForJsp_canRenderHeaderReturnsTrue1_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader()).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeaderForJsp());
}
// For content-type "text/xhtml"
@Test
public void getBrowserTimingHeaderForJsp_canRenderHeaderReturnsTrue2_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/xhtml");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader()).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(anyString())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeader_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_canRenderHeaderReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader()).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeaderWithNonce_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_canRenderHeaderReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader(anyString())).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingFooter_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_canRenderFooterReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingFooter(any())).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_withoutHeaderBeingRendered_returnsEmptyString() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_canRenderFooterReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooterWithNonce_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_canRenderHeaderReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingFooter(any(), any())).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void create_returnsInstance() {
Assert.assertNotNull(BrowserTransactionStateImpl.create(tx));
Assert.assertNull(BrowserTransactionStateImpl.create(null));
}
@Test
public void testUserAttributes() throws Exception {
createServiceManager();
Transaction tx = Transaction.getTransaction();
Transaction.clearTransaction();
BrowserTransactionState bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getUserAttributes().size());
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getUserAttributes().put("one", 1L);
Map<String, Object> user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(1, user.size());
Assert.assertEquals(1L, user.get("one"));
tx.getUserAttributes().put("two", 5.44);
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(2, user.size());
Assert.assertEquals(5.44, user.get("two"));
Assert.assertEquals(0, bts.getAgentAttributes().size());
Transaction.clearTransaction();
tx = Transaction.getTransaction();
bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getUserAttributes().size());
tx.getUserAttributes().put("one", "abc123");
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(1, user.size());
Assert.assertEquals("abc123", user.get("one"));
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getUserAttributes().put("two", 989);
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(2, user.size());
Assert.assertEquals(989, user.get("two"));
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getUserAttributes().put("three", "hello");
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(3, user.size());
Assert.assertEquals("hello", user.get("three"));
Transaction.clearTransaction();
}
@Test
public void testAgentAttributes() throws Exception {
createServiceManager();
Transaction tx = Transaction.getTransaction();
Transaction.clearTransaction();
BrowserTransactionState bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getAgentAttributes().put("one", 1L);
Map<String, Object> agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(1, agentAtts.size());
Assert.assertEquals(1L, agentAtts.get("one"));
tx.getAgentAttributes().put("two", 5.44);
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(2, agentAtts.size());
Assert.assertEquals(5.44, agentAtts.get("two"));
Transaction.clearTransaction();
tx = Transaction.getTransaction();
bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getAgentAttributes().put("one", "abc123");
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(1, agentAtts.size());
Assert.assertEquals("abc123", agentAtts.get("one"));
tx.getAgentAttributes().put("two", 989);
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(2, agentAtts.size());
Assert.assertEquals(989, agentAtts.get("two"));
tx.getAgentAttributes().put("three", "hello");
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(3, agentAtts.size());
Assert.assertEquals("hello", agentAtts.get("three"));
Transaction.clearTransaction();
tx = Transaction.getTransaction();
bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getAgentAttributes().size());
Map<String, String> requests = new HashMap<>();
requests.put("one", "abc123");
requests.put("two", "333");
tx.getPrefixedAgentAttributes().put("request.parameters.", requests);
tx.getAgentAttributes().put("three", 44);
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(3, agentAtts.size());
Assert.assertEquals("abc123", agentAtts.get("request.parameters.one"));
Assert.assertEquals("333", agentAtts.get("request.parameters.two"));
Assert.assertEquals(44, agentAtts.get("three"));
Assert.assertEquals(0, bts.getUserAttributes().size());
Transaction.clearTransaction();
}
@Test
public void testGetAttributes() throws Exception {
createServiceManager();
Transaction tx = Transaction.getTransaction();
Transaction.clearTransaction();
BrowserTransactionState bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getUserAttributes().size());
Assert.assertEquals(0, bts.getAgentAttributes().size());
// user
tx.getUserAttributes().put("one", 1L);
tx.getUserAttributes().put("two", 2.22);
// agent
Map<String, String> requests = new HashMap<>();
requests.put("one", "abc123");
requests.put("two", "ringing");
tx.getPrefixedAgentAttributes().put("request.parameters.", requests);
tx.getAgentAttributes().put("one", 44);
tx.getAgentAttributes().put("two", 44.44);
Map<String, Object> userAtts = bts.getUserAttributes();
Map<String, Object> agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(userAtts);
Assert.assertEquals(2, userAtts.size());
Assert.assertEquals(1L, userAtts.get("one"));
Assert.assertEquals(2.22, (Double) userAtts.get("two"), .001);
Assert.assertNotNull(agentAtts);
Assert.assertEquals(4, agentAtts.size());
Assert.assertEquals("abc123", agentAtts.get("request.parameters.one"));
Assert.assertEquals("ringing", agentAtts.get("request.parameters.two"));
Assert.assertEquals(44, agentAtts.get("one"));
Assert.assertEquals(44.44, (Double) agentAtts.get("two"), .001);
Transaction.clearTransaction();
}
public static void createServiceManager() throws Exception {
createServiceManager(Collections.<String>emptySet(), Collections.<String>emptySet());
}
public static void createServiceManager(Set<String> include, Set<String> exclude) throws Exception {
MockServiceManager serviceManager = new MockServiceManager();
ServiceFactory.setServiceManager(serviceManager);
// Needed by TransactionService
ThreadService threadService = new ThreadService();
serviceManager.setThreadService(threadService);
// Needed by TransactionTraceService
Map<String, Object> map = createConfigMap(include, exclude);
ConfigService configService = ConfigServiceFactory.createConfigService(AgentConfigImpl.createAgentConfig(map),
map);
serviceManager.setConfigService(configService);
// Needed by Transaction
TransactionService transactionService = new TransactionService();
serviceManager.setTransactionService(transactionService);
MockCoreService agent = new MockCoreService();
serviceManager.setCoreService(agent);
// Null pointers if not set
serviceManager.setStatsService(Mockito.mock(StatsService.class));
// Needed by Transaction
TransactionTraceService transactionTraceService = new TransactionTraceService();
serviceManager.setTransactionTraceService(transactionTraceService);
// Needed by Transaction
MockRPMServiceManager rpmServiceManager = new MockRPMServiceManager();
serviceManager.setRPMServiceManager(rpmServiceManager);
MockRPMService rpmService = new MockRPMService();
rpmService.setApplicationName("name");
rpmService.setErrorService(new ErrorServiceImpl("name"));
rpmServiceManager.setRPMService(rpmService);
AttributesService attService = new AttributesService();
serviceManager.setAttributesService(attService);
ServiceFactory.setServiceManager(serviceManager);
}
private static Map<String, Object> createConfigMap(Set<String> include, Set<String> exclude) {
return ImmutableMap.<String, Object>of(
AgentConfigImpl.APP_NAME, "name",
AgentConfigImpl.APDEX_T, 0.5f,
AgentConfigImpl.THREAD_CPU_TIME_ENABLED, Boolean.TRUE,
AgentConfigImpl.TRANSACTION_TRACER, ImmutableMap.<String, Object>of(
TransactionTracerConfigImpl.TRANSACTION_THRESHOLD, 0.0f),
AgentConfigImpl.BROWSER_MONITORING, ImmutableMap.<String, Object>of(
AgentConfigImpl.ATTRIBUTES, ImmutableMap.of(
AttributesConfigImpl.ENABLED, Boolean.TRUE,
AttributesConfigImpl.INCLUDE, include,
AttributesConfigImpl.EXCLUDE, exclude)));
}
@Test
public void allowMultipleFootersDisabled() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(false);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Assert.assertEquals("", bts.getBrowserTimingFooter());
Mockito.verify(tx, times(1)).freezeTransactionName();
}
@Test
public void allowMultipleFootersWithNonceDisabled() {
BrowserTransactionState bts = mockMultipleFootersTest(false);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Assert.assertEquals("", bts.getBrowserTimingFooter("ABC123"));
Mockito.verify(tx, times(1)).freezeTransactionName();
}
@Test
public void allowMultipleFootersEnabled() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(true);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Mockito.verify(tx, times(2)).freezeTransactionName();
}
@Test
public void allowMultipleFootersWithNonceEnabled() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(true);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Mockito.verify(tx, times(2)).freezeTransactionName();
}
@Test
public void allowMultipleFootersMixed() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(true);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Mockito.verify(tx, times(2)).freezeTransactionName();
}
private BrowserTransactionState mockMultipleFootersTest(boolean allowMultipleFooters) {
PriorityTransactionName ptn = PriorityTransactionName.create("/en/betting/Football", null,
TransactionNamePriority.CUSTOM_HIGH);
AgentConfig agentConfig = Mockito.mock(AgentConfig.class);
BrowserMonitoringConfig bmConfig = Mockito.mock(BrowserMonitoringConfig.class);
Mockito.when(bmConfig.isAllowMultipleFooters()).thenReturn(allowMultipleFooters);
Mockito.when(agentConfig.getBrowserMonitoringConfig()).thenReturn(bmConfig);
Mockito.when(tx.isInProgress()).thenReturn(true);
Mockito.when(tx.isIgnore()).thenReturn(false);
Mockito.when(tx.getApplicationName()).thenReturn("Test");
Mockito.when(tx.getPriorityTransactionName()).thenReturn(ptn);
Mockito.when(tx.getAgentConfig()).thenReturn(agentConfig);
Mockito.doNothing().when(tx).freezeTransactionName();
long durationInNanos = TimeUnit.NANOSECONDS.convert(200L, TimeUnit.MILLISECONDS);
Mockito.when(tx.getRunningDurationInNanos()).thenReturn(durationInNanos);
final BrowserConfig bConfig = Mockito.mock(BrowserConfig.class);
BrowserTransactionState bts = new BrowserTransactionStateImpl(tx) {
@Override
protected BrowserConfig getBeaconConfig() {
return bConfig;
}
};
Mockito.when(bConfig.getBrowserTimingHeader()).thenReturn("header");
Mockito.when(bConfig.getBrowserTimingFooter(bts)).thenReturn("footer");
Mockito.when(bConfig.getBrowserTimingFooter(eq(bts), anyString())).thenReturn("footerWithNonce");
return bts;
}
private void simulateBrowserHeaderInjected(BrowserTransactionState instance) {
try {
Field field = instance.getClass().getDeclaredField("browserHeaderRendered");
field.setAccessible(true);
field.setBoolean(instance, true);
} catch (Exception ignored) {
//noop
}
}
@Mock
Transaction tx;
@Mock
BrowserService mockBrowserService;
}
| UTF-8 | Java | 38,823 | java | BrowserTransactionStateTest.java | Java | [
{
"context": "s = new HashMap<>();\n requests.put(\"one\", \"abc123\");\n requests.put(\"two\", \"ringing\");\n ",
"end": 30610,
"score": 0.4358108639717102,
"start": 30607,
"tag": "NAME",
"value": "abc"
}
]
| null | []
| /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.browser;
import com.google.common.collect.ImmutableMap;
import com.newrelic.agent.MockConfigService;
import com.newrelic.agent.MockCoreService;
import com.newrelic.agent.MockRPMService;
import com.newrelic.agent.MockRPMServiceManager;
import com.newrelic.agent.MockServiceManager;
import com.newrelic.agent.ThreadService;
import com.newrelic.agent.Transaction;
import com.newrelic.agent.TransactionService;
import com.newrelic.agent.attributes.AttributesService;
import com.newrelic.agent.bridge.TransactionNamePriority;
import com.newrelic.agent.config.AgentConfig;
import com.newrelic.agent.config.AgentConfigFactory;
import com.newrelic.agent.config.AgentConfigImpl;
import com.newrelic.agent.config.AttributesConfigImpl;
import com.newrelic.agent.config.BrowserMonitoringConfig;
import com.newrelic.agent.config.ConfigService;
import com.newrelic.agent.config.ConfigServiceFactory;
import com.newrelic.agent.config.TransactionTracerConfigImpl;
import com.newrelic.agent.dispatchers.Dispatcher;
import com.newrelic.agent.errors.ErrorServiceImpl;
import com.newrelic.agent.service.ServiceFactory;
import com.newrelic.agent.stats.StatsService;
import com.newrelic.agent.trace.TransactionTraceService;
import com.newrelic.agent.transaction.PriorityTransactionName;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
public class BrowserTransactionStateTest {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
MockServiceManager serviceManager = new MockServiceManager();
serviceManager.setConfigService(new MockConfigService(AgentConfigFactory.createAgentConfig(
Collections.<String, Object>emptyMap(), Collections.<String, Object>emptyMap(), null)));
serviceManager.setBrowserService(mockBrowserService);
ServiceFactory.setServiceManager(serviceManager);
}
@Test
public void getBrowserTimingHeaderForJsp_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_nullContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
// For content-type "text/html"
@Test
public void getBrowserTimingHeaderForJsp_canRenderHeaderReturnsTrue1_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader()).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeaderForJsp());
}
// For content-type "text/xhtml"
@Test
public void getBrowserTimingHeaderForJsp_canRenderHeaderReturnsTrue2_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/xhtml");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader()).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeaderForJsp_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(anyString())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeaderForJsp());
}
@Test
public void getBrowserTimingHeader_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_canRenderHeaderReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader()).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeader_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader());
}
@Test
public void getBrowserTimingHeaderWithNonce_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_canRenderHeaderReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingHeader(anyString())).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingHeaderWithNonce_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingHeader("foo"));
}
@Test
public void getBrowserTimingFooter_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_canRenderFooterReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingFooter(any())).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_withoutHeaderBeingRendered_returnsEmptyString() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooter_canRenderFooterReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
}
@Test
public void getBrowserTimingFooterWithNonce_noTxnInProgress_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_txnIsIgnored_returnsEmptyString() {
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(true);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_txnIsNotWebTxn_returnsEmptyString() {
//Not a web txn
Dispatcher mockDispatcher = mock(Dispatcher.class);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(false);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter());
//Dispatcher is null
when(tx.getDispatcher()).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_incorrectContentType_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("foo");
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_canRenderHeaderReturnsTrue_returnsHeader() {
BrowserConfig mockBrowserConfig = mock(BrowserConfig.class);
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(mockBrowserConfig);
when(mockBrowserConfig.getBrowserTimingFooter(any(), any())).thenReturn("response");
Assert.assertEquals("response", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void getBrowserTimingFooterWithNonce_canRenderHeaderReturnsTrue_andBrowserConfigIsNull_returnsEmptyString() {
Dispatcher mockDispatcher = mock(Dispatcher.class, RETURNS_DEEP_STUBS);
BrowserTransactionState browserTransactionState = new BrowserTransactionStateImpl(tx);
simulateBrowserHeaderInjected(browserTransactionState);
when(tx.isInProgress()).thenReturn(true);
when(tx.isIgnore()).thenReturn(false);
when(tx.getDispatcher()).thenReturn(mockDispatcher);
when(mockDispatcher.isWebTransaction()).thenReturn(true);
when(mockDispatcher.getResponse().getContentType()).thenReturn("text/html");
when(mockBrowserService.getBrowserConfig(any())).thenReturn(null);
Assert.assertEquals("", browserTransactionState.getBrowserTimingFooter("foo"));
}
@Test
public void create_returnsInstance() {
Assert.assertNotNull(BrowserTransactionStateImpl.create(tx));
Assert.assertNull(BrowserTransactionStateImpl.create(null));
}
@Test
public void testUserAttributes() throws Exception {
createServiceManager();
Transaction tx = Transaction.getTransaction();
Transaction.clearTransaction();
BrowserTransactionState bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getUserAttributes().size());
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getUserAttributes().put("one", 1L);
Map<String, Object> user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(1, user.size());
Assert.assertEquals(1L, user.get("one"));
tx.getUserAttributes().put("two", 5.44);
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(2, user.size());
Assert.assertEquals(5.44, user.get("two"));
Assert.assertEquals(0, bts.getAgentAttributes().size());
Transaction.clearTransaction();
tx = Transaction.getTransaction();
bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getUserAttributes().size());
tx.getUserAttributes().put("one", "abc123");
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(1, user.size());
Assert.assertEquals("abc123", user.get("one"));
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getUserAttributes().put("two", 989);
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(2, user.size());
Assert.assertEquals(989, user.get("two"));
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getUserAttributes().put("three", "hello");
user = bts.getUserAttributes();
Assert.assertNotNull(user);
Assert.assertEquals(3, user.size());
Assert.assertEquals("hello", user.get("three"));
Transaction.clearTransaction();
}
@Test
public void testAgentAttributes() throws Exception {
createServiceManager();
Transaction tx = Transaction.getTransaction();
Transaction.clearTransaction();
BrowserTransactionState bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getAgentAttributes().put("one", 1L);
Map<String, Object> agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(1, agentAtts.size());
Assert.assertEquals(1L, agentAtts.get("one"));
tx.getAgentAttributes().put("two", 5.44);
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(2, agentAtts.size());
Assert.assertEquals(5.44, agentAtts.get("two"));
Transaction.clearTransaction();
tx = Transaction.getTransaction();
bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getAgentAttributes().size());
tx.getAgentAttributes().put("one", "abc123");
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(1, agentAtts.size());
Assert.assertEquals("abc123", agentAtts.get("one"));
tx.getAgentAttributes().put("two", 989);
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(2, agentAtts.size());
Assert.assertEquals(989, agentAtts.get("two"));
tx.getAgentAttributes().put("three", "hello");
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(3, agentAtts.size());
Assert.assertEquals("hello", agentAtts.get("three"));
Transaction.clearTransaction();
tx = Transaction.getTransaction();
bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getAgentAttributes().size());
Map<String, String> requests = new HashMap<>();
requests.put("one", "abc123");
requests.put("two", "333");
tx.getPrefixedAgentAttributes().put("request.parameters.", requests);
tx.getAgentAttributes().put("three", 44);
agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(agentAtts);
Assert.assertEquals(3, agentAtts.size());
Assert.assertEquals("abc123", agentAtts.get("request.parameters.one"));
Assert.assertEquals("333", agentAtts.get("request.parameters.two"));
Assert.assertEquals(44, agentAtts.get("three"));
Assert.assertEquals(0, bts.getUserAttributes().size());
Transaction.clearTransaction();
}
@Test
public void testGetAttributes() throws Exception {
createServiceManager();
Transaction tx = Transaction.getTransaction();
Transaction.clearTransaction();
BrowserTransactionState bts = BrowserTransactionStateImpl.create(tx);
Assert.assertEquals(0, bts.getUserAttributes().size());
Assert.assertEquals(0, bts.getAgentAttributes().size());
// user
tx.getUserAttributes().put("one", 1L);
tx.getUserAttributes().put("two", 2.22);
// agent
Map<String, String> requests = new HashMap<>();
requests.put("one", "abc123");
requests.put("two", "ringing");
tx.getPrefixedAgentAttributes().put("request.parameters.", requests);
tx.getAgentAttributes().put("one", 44);
tx.getAgentAttributes().put("two", 44.44);
Map<String, Object> userAtts = bts.getUserAttributes();
Map<String, Object> agentAtts = bts.getAgentAttributes();
Assert.assertNotNull(userAtts);
Assert.assertEquals(2, userAtts.size());
Assert.assertEquals(1L, userAtts.get("one"));
Assert.assertEquals(2.22, (Double) userAtts.get("two"), .001);
Assert.assertNotNull(agentAtts);
Assert.assertEquals(4, agentAtts.size());
Assert.assertEquals("abc123", agentAtts.get("request.parameters.one"));
Assert.assertEquals("ringing", agentAtts.get("request.parameters.two"));
Assert.assertEquals(44, agentAtts.get("one"));
Assert.assertEquals(44.44, (Double) agentAtts.get("two"), .001);
Transaction.clearTransaction();
}
public static void createServiceManager() throws Exception {
createServiceManager(Collections.<String>emptySet(), Collections.<String>emptySet());
}
public static void createServiceManager(Set<String> include, Set<String> exclude) throws Exception {
MockServiceManager serviceManager = new MockServiceManager();
ServiceFactory.setServiceManager(serviceManager);
// Needed by TransactionService
ThreadService threadService = new ThreadService();
serviceManager.setThreadService(threadService);
// Needed by TransactionTraceService
Map<String, Object> map = createConfigMap(include, exclude);
ConfigService configService = ConfigServiceFactory.createConfigService(AgentConfigImpl.createAgentConfig(map),
map);
serviceManager.setConfigService(configService);
// Needed by Transaction
TransactionService transactionService = new TransactionService();
serviceManager.setTransactionService(transactionService);
MockCoreService agent = new MockCoreService();
serviceManager.setCoreService(agent);
// Null pointers if not set
serviceManager.setStatsService(Mockito.mock(StatsService.class));
// Needed by Transaction
TransactionTraceService transactionTraceService = new TransactionTraceService();
serviceManager.setTransactionTraceService(transactionTraceService);
// Needed by Transaction
MockRPMServiceManager rpmServiceManager = new MockRPMServiceManager();
serviceManager.setRPMServiceManager(rpmServiceManager);
MockRPMService rpmService = new MockRPMService();
rpmService.setApplicationName("name");
rpmService.setErrorService(new ErrorServiceImpl("name"));
rpmServiceManager.setRPMService(rpmService);
AttributesService attService = new AttributesService();
serviceManager.setAttributesService(attService);
ServiceFactory.setServiceManager(serviceManager);
}
private static Map<String, Object> createConfigMap(Set<String> include, Set<String> exclude) {
return ImmutableMap.<String, Object>of(
AgentConfigImpl.APP_NAME, "name",
AgentConfigImpl.APDEX_T, 0.5f,
AgentConfigImpl.THREAD_CPU_TIME_ENABLED, Boolean.TRUE,
AgentConfigImpl.TRANSACTION_TRACER, ImmutableMap.<String, Object>of(
TransactionTracerConfigImpl.TRANSACTION_THRESHOLD, 0.0f),
AgentConfigImpl.BROWSER_MONITORING, ImmutableMap.<String, Object>of(
AgentConfigImpl.ATTRIBUTES, ImmutableMap.of(
AttributesConfigImpl.ENABLED, Boolean.TRUE,
AttributesConfigImpl.INCLUDE, include,
AttributesConfigImpl.EXCLUDE, exclude)));
}
@Test
public void allowMultipleFootersDisabled() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(false);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Assert.assertEquals("", bts.getBrowserTimingFooter());
Mockito.verify(tx, times(1)).freezeTransactionName();
}
@Test
public void allowMultipleFootersWithNonceDisabled() {
BrowserTransactionState bts = mockMultipleFootersTest(false);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Assert.assertEquals("", bts.getBrowserTimingFooter("ABC123"));
Mockito.verify(tx, times(1)).freezeTransactionName();
}
@Test
public void allowMultipleFootersEnabled() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(true);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Mockito.verify(tx, times(2)).freezeTransactionName();
}
@Test
public void allowMultipleFootersWithNonceEnabled() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(true);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Mockito.verify(tx, times(2)).freezeTransactionName();
}
@Test
public void allowMultipleFootersMixed() throws Exception {
BrowserTransactionState bts = mockMultipleFootersTest(true);
Assert.assertEquals("header", bts.getBrowserTimingHeader());
Assert.assertEquals("footer", bts.getBrowserTimingFooter());
Assert.assertEquals("footerWithNonce", bts.getBrowserTimingFooter("ABC123"));
Mockito.verify(tx, times(2)).freezeTransactionName();
}
private BrowserTransactionState mockMultipleFootersTest(boolean allowMultipleFooters) {
PriorityTransactionName ptn = PriorityTransactionName.create("/en/betting/Football", null,
TransactionNamePriority.CUSTOM_HIGH);
AgentConfig agentConfig = Mockito.mock(AgentConfig.class);
BrowserMonitoringConfig bmConfig = Mockito.mock(BrowserMonitoringConfig.class);
Mockito.when(bmConfig.isAllowMultipleFooters()).thenReturn(allowMultipleFooters);
Mockito.when(agentConfig.getBrowserMonitoringConfig()).thenReturn(bmConfig);
Mockito.when(tx.isInProgress()).thenReturn(true);
Mockito.when(tx.isIgnore()).thenReturn(false);
Mockito.when(tx.getApplicationName()).thenReturn("Test");
Mockito.when(tx.getPriorityTransactionName()).thenReturn(ptn);
Mockito.when(tx.getAgentConfig()).thenReturn(agentConfig);
Mockito.doNothing().when(tx).freezeTransactionName();
long durationInNanos = TimeUnit.NANOSECONDS.convert(200L, TimeUnit.MILLISECONDS);
Mockito.when(tx.getRunningDurationInNanos()).thenReturn(durationInNanos);
final BrowserConfig bConfig = Mockito.mock(BrowserConfig.class);
BrowserTransactionState bts = new BrowserTransactionStateImpl(tx) {
@Override
protected BrowserConfig getBeaconConfig() {
return bConfig;
}
};
Mockito.when(bConfig.getBrowserTimingHeader()).thenReturn("header");
Mockito.when(bConfig.getBrowserTimingFooter(bts)).thenReturn("footer");
Mockito.when(bConfig.getBrowserTimingFooter(eq(bts), anyString())).thenReturn("footerWithNonce");
return bts;
}
private void simulateBrowserHeaderInjected(BrowserTransactionState instance) {
try {
Field field = instance.getClass().getDeclaredField("browserHeaderRendered");
field.setAccessible(true);
field.setBoolean(instance, true);
} catch (Exception ignored) {
//noop
}
}
@Mock
Transaction tx;
@Mock
BrowserService mockBrowserService;
}
| 38,823 | 0.719393 | 0.715581 | 817 | 46.51897 | 31.778339 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.844553 | false | false | 4 |
45f26912fa4ad2122423c1cd619fcf343260a2d1 | 16,879,221,480,033 | eefe6c2049b7c7413596f6d6b0954902596debdb | /src/main/java/com/cooksys/entity/User.java | b66db65dc8e23f6e89dcb5c9db586bdad4a7f72e | []
| no_license | GiovannyRoman/flight | https://github.com/GiovannyRoman/flight | cc7fdcddebeed3f9eb881cea4347c09964649891 | 04e0498b68b2f17debae5cac98a2bc19fad24e4a | refs/heads/master | 2021-01-12T12:50:58.590000 | 2017-02-28T20:03:09 | 2017-02-28T20:03:09 | 69,025,532 | 0 | 1 | null | true | 2016-09-23T13:06:04 | 2016-09-23T13:06:04 | 2016-09-22T18:30:57 | 2016-09-22T22:47:07 | 94 | 0 | 0 | 0 | null | null | null | package com.cooksys.entity;
import java.util.List;
import javax.persistence.*;
@Entity
@Table(name = "User",uniqueConstraints = @UniqueConstraint(columnNames = { "username" }))
public class User {
@Id
@GeneratedValue
private long id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@OneToMany(mappedBy = "owner" ,fetch=FetchType.EAGER,cascade = CascadeType.ALL)
private List<Route> routes;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Route> getRoutes() {
return routes;
}
public void setRoutes(List<Route> routes) {
this.routes = routes;
}
}
| UTF-8 | Java | 955 | java | User.java | Java | [
{
"context": "neratedValue\n\tprivate long id;\n\t\n\t@Column(name = \"username\")\n\tprivate String username;\n\t\n\t@Column(name = \"pa",
"end": 268,
"score": 0.9949491620063782,
"start": 260,
"tag": "USERNAME",
"value": "username"
},
{
"context": "me\")\n\tprivate String username;\n\t\n\t@Column(name = \"password\")\n\tprivate String password;\n\t\n\t@OneToMany(mappedB",
"end": 324,
"score": 0.8595762252807617,
"start": 316,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "= id;\n\t}\n\t\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\t\n\tpublic void setUsername(String username) {",
"end": 607,
"score": 0.8946178555488586,
"start": 599,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\t\n\tpublic String getPassword() {\n\t\treturn pas",
"end": 684,
"score": 0.9736477136611938,
"start": 676,
"tag": "USERNAME",
"value": "username"
},
{
"context": "name;\n\t}\n\t\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\t\n\tpublic void setPassword(String password) {",
"end": 739,
"score": 0.6541292071342468,
"start": 731,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\t\n\tpublic List<Route> getRoutes() {\n\t\treturn ",
"end": 816,
"score": 0.7782310247421265,
"start": 808,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.cooksys.entity;
import java.util.List;
import javax.persistence.*;
@Entity
@Table(name = "User",uniqueConstraints = @UniqueConstraint(columnNames = { "username" }))
public class User {
@Id
@GeneratedValue
private long id;
@Column(name = "username")
private String username;
@Column(name = "<PASSWORD>")
private String password;
@OneToMany(mappedBy = "owner" ,fetch=FetchType.EAGER,cascade = CascadeType.ALL)
private List<Route> routes;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return <PASSWORD>;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public List<Route> getRoutes() {
return routes;
}
public void setRoutes(List<Route> routes) {
this.routes = routes;
}
}
| 961 | 0.693194 | 0.693194 | 55 | 16.363636 | 18.660959 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.309091 | false | false | 4 |
4a7c3391ad536bdc0c41293eb8068856ecde361a | 24,412,594,118,201 | c38b296ff626bd63995ac880104165119e10df5c | /src/main/java/com/exa/utils/values/ObjectValue.java | c1a84ba1181a515fb217caed1afa231f9bd3f582 | [
"MIT"
]
| permissive | ryvale/xautils | https://github.com/ryvale/xautils | face8cf919de8ef816047351b48c904bded137a0 | 81df362221085ac45a5540a5802568b86ffe6865 | refs/heads/master | 2023-01-13T08:22:01.268000 | 2022-12-31T22:03:06 | 2022-12-31T22:03:06 | 122,200,665 | 0 | 0 | MIT | false | 2022-12-05T23:54:23 | 2018-02-20T13:19:09 | 2022-11-21T20:49:14 | 2022-12-05T23:54:22 | 62 | 0 | 0 | 2 | Java | false | false | package com.exa.utils.values;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.exa.utils.ManagedException;
public class ObjectValue<_C> extends MemoryValue<Map<String, Value<?, _C>>, _C> {
/**
*
*/
private static final long serialVersionUID = 1L;
public ObjectValue() {
super(new LinkedHashMap<>());
}
// use LinkedHashMap instead of Map while creating an instance
public ObjectValue(Map<String, Value<?, _C>> v) {
super(v);
}
@Override
public ObjectValue<_C> asObjectValue() {
return this;
}
public boolean containsAttribut(String name) {
return value.containsKey(name);
}
public String getAttributAsString(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
return v.asString();
}
public String getAttributAsString(String name, String defaultValue) throws ManagedException {
String res = getAttributAsString(name);
if(res == null) return defaultValue;
return res;
}
public String getRequiredAttributAsString(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) throw new ManagedException(String.format("The property %s is required.", name));
/*StringValue<_C> ov = v.asStringValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an string.", name));*/
return v.asRequiredString();
}
public ObjectValue<_C> getRequiredAttributAsObjectValue(String name) throws ManagedException {
ObjectValue<_C> ov = getAttributAsObjectValue(name);
if(ov == null) throw new ManagedException(String.format("The property %s is required.", name));
return ov;
}
public ObjectValue<_C> getAttributAsObjectValue(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ObjectValue<_C> ov = v.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object value.", name));
return ov;
}
public Map<String, Value<?, _C>> getAttributAsMap(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ObjectValue<_C> ov = v.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object value.", name));
return ov.getValue();
}
public Integer getRequiredAttributAsInteger(String name) throws ManagedException {
Integer res = getAttributAsInteger(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public Integer getAttributAsInteger(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
return v.asInteger();
}
public Value<?, _C> getAttribut(String name) {
return value.get(name);
}
public Value<?, _C> getAttribut(String name, int i) throws ManagedException {
Value<?, _C> rpv = value.get(name);
if(rpv == null) return null;
ArrayValue<_C> av = rpv.asArrayValue();
if(av == null) throw new ManagedException(String.format("The attribut %s is not an array", name));
return av.get(i);
}
public Value<?, _C> getRequiredAttribut(String name) throws ManagedException {
Value<?, _C> res = value.get(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public List<Value<?, _C>> getRequiredAttributAsArray(String name) throws ManagedException {
List<Value<?, _C>> res = getAttributAsArray(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public ArrayValue<_C> getAttributAsArrayValue(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ArrayValue<_C> av = v.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property %s is not an array value", name));
return av;
}
public List<Value<?, _C>> getAttributAsArray(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ArrayValue<_C> av = v.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property %s is not an array value", name));
return av.getValue();
}
public ArrayValue<_C> getRequiredAttributAsArrayValue(String name) throws ManagedException {
ArrayValue<_C> av = getAttributAsArrayValue(name);
if(av == null) throw new ManagedException(String.format("The property %s is not a non null array value", name));
return av;
}
public String getPathAttributAsString(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv.asString();
}
public Boolean getPathAttributAsBoolean(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv.asBoolean();
}
public Value<?, _C> getPathAttribut(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv;
}
public Integer getPathAttributAsInteger(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv.asInteger();
}
public Value<?, _C> getAttributEx(String query) throws ManagedException {
Value<?, _C> res;
if(query.endsWith("]")) {
int p = query.indexOf('[');
if(p < 0) throw new ManagedException(String.format("The property path %s not well formed.", query));
int i = Integer.parseInt(query.substring(p+1, query.length()-1));
String att = query.substring(0, p);
res = getAttribut(att, i);
}
else {
res = getAttribut(query);
}
return res;
}
public ArrayValue<_C> getPathAttributAsArrayValue(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttribut(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttribut(parts[i]);
}
ArrayValue<_C> av = rpv.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property %s is not an array.", parts[parts.length - 1]));
return av;
}
public List<Value<?, _C>> getPathAttributAsArray(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttribut(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s is not defined.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s is not defined.", pathAttribut));
rpv = rpo.getAttribut(parts[i]);
}
ArrayValue<_C> av = rpv.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property path %s is not defined.", parts[parts.length - 1]));
return av.getValue();
}
/*public String getPathAttributAsString(String pathAttribut) {
try {
return getPathAttributAsStringEx(pathAttribut);
} catch (ManagedException e) {
e.printStackTrace();
}
return null;
}*/
public ObjectValue<_C> getPathAttributAsObjecValue(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
//if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
ObjectValue<_C> ov = rpv.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object.", parts[parts.length - 1]));
return ov; //.getAttributAsObjectValue(parts[parts.length - 1]);
}
public ObjectValue<_C> getAttributByPathAsObjectValue(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) return null;
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
if(rpv == null) return null;
}
//if(rpv == null) return null;
ObjectValue<_C> ov = rpv.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object.", parts[parts.length - 1]));
return ov; //.getAttributAsObjectValue(parts[parts.length - 1]);
}
/*public ObjectValue getPathAttributAsObjecValue(String pathAttribut) {
try {
return getPathAttributAsObjecValueEx(pathAttribut);
} catch (ManagedException e) {
e.printStackTrace();
}
return null;
}*/
public void setAttribut(String name, String avalue) {
value.put(name, new StringValue<_C>(avalue));
}
public void setAttribut(String name, Value<?, _C> avalue) {
value.put(name, avalue);
}
public ObjectValue<_C> addObjectValueAttribut(String name) {
ObjectValue<_C> res = new ObjectValue<>();
value.put(name, res);
return res;
}
public ArrayValue<_C> addArrayValueAttribut(String name) {
ArrayValue<_C> res = new ArrayValue<>();
value.put(name, res);
return res;
}
public Integer getIntOrStringIntAttribut(String name) throws ManagedException {
IntegerValue<_C> iv = asIntegerValue();
if(iv == null) {
StringValue<_C> sv = asStringValue();
if(sv == null) throw new ManagedException(String.format("This is not an integer or could not be convertes."));
String s = sv.getValue();
if(s == null) return null;
try {
Integer res = Integer.valueOf(s);
return res;
}catch(NumberFormatException e) {
throw new ManagedException(e);
}
}
return iv.getValue();
}
public Integer getRequiredIntOrStringIntAttribut(String name) throws ManagedException {
Integer res = getIntOrStringIntAttribut(name);
if(res == null) throw new ManagedException(String.format("The property %s should not be null", name));
return res;
}
public Boolean getRequiredAttributAsBoolean(String name) throws ManagedException {
Boolean res = getAttributAsBoolean(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public Boolean getAttributAsBoolean(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
return v.asBoolean();
}
@Override
public ObjectValue<_C> clone() /*throws CloneNotSupportedException*/ {
ObjectValue<_C> res = new ObjectValue<>();
for(String k : value.keySet()) {
Value<?, _C> v = value.get(k);
res.setAttribut(k, v == null ? null : v.clone());
}
return res;
}
@Override
public String typeName() {
return "object";
}
}
| UTF-8 | Java | 13,191 | java | ObjectValue.java | Java | []
| null | []
| package com.exa.utils.values;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.exa.utils.ManagedException;
public class ObjectValue<_C> extends MemoryValue<Map<String, Value<?, _C>>, _C> {
/**
*
*/
private static final long serialVersionUID = 1L;
public ObjectValue() {
super(new LinkedHashMap<>());
}
// use LinkedHashMap instead of Map while creating an instance
public ObjectValue(Map<String, Value<?, _C>> v) {
super(v);
}
@Override
public ObjectValue<_C> asObjectValue() {
return this;
}
public boolean containsAttribut(String name) {
return value.containsKey(name);
}
public String getAttributAsString(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
return v.asString();
}
public String getAttributAsString(String name, String defaultValue) throws ManagedException {
String res = getAttributAsString(name);
if(res == null) return defaultValue;
return res;
}
public String getRequiredAttributAsString(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) throw new ManagedException(String.format("The property %s is required.", name));
/*StringValue<_C> ov = v.asStringValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an string.", name));*/
return v.asRequiredString();
}
public ObjectValue<_C> getRequiredAttributAsObjectValue(String name) throws ManagedException {
ObjectValue<_C> ov = getAttributAsObjectValue(name);
if(ov == null) throw new ManagedException(String.format("The property %s is required.", name));
return ov;
}
public ObjectValue<_C> getAttributAsObjectValue(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ObjectValue<_C> ov = v.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object value.", name));
return ov;
}
public Map<String, Value<?, _C>> getAttributAsMap(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ObjectValue<_C> ov = v.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object value.", name));
return ov.getValue();
}
public Integer getRequiredAttributAsInteger(String name) throws ManagedException {
Integer res = getAttributAsInteger(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public Integer getAttributAsInteger(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
return v.asInteger();
}
public Value<?, _C> getAttribut(String name) {
return value.get(name);
}
public Value<?, _C> getAttribut(String name, int i) throws ManagedException {
Value<?, _C> rpv = value.get(name);
if(rpv == null) return null;
ArrayValue<_C> av = rpv.asArrayValue();
if(av == null) throw new ManagedException(String.format("The attribut %s is not an array", name));
return av.get(i);
}
public Value<?, _C> getRequiredAttribut(String name) throws ManagedException {
Value<?, _C> res = value.get(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public List<Value<?, _C>> getRequiredAttributAsArray(String name) throws ManagedException {
List<Value<?, _C>> res = getAttributAsArray(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public ArrayValue<_C> getAttributAsArrayValue(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ArrayValue<_C> av = v.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property %s is not an array value", name));
return av;
}
public List<Value<?, _C>> getAttributAsArray(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
ArrayValue<_C> av = v.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property %s is not an array value", name));
return av.getValue();
}
public ArrayValue<_C> getRequiredAttributAsArrayValue(String name) throws ManagedException {
ArrayValue<_C> av = getAttributAsArrayValue(name);
if(av == null) throw new ManagedException(String.format("The property %s is not a non null array value", name));
return av;
}
public String getPathAttributAsString(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv.asString();
}
public Boolean getPathAttributAsBoolean(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv.asBoolean();
}
public Value<?, _C> getPathAttribut(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv;
}
public Integer getPathAttributAsInteger(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
return rpv.asInteger();
}
public Value<?, _C> getAttributEx(String query) throws ManagedException {
Value<?, _C> res;
if(query.endsWith("]")) {
int p = query.indexOf('[');
if(p < 0) throw new ManagedException(String.format("The property path %s not well formed.", query));
int i = Integer.parseInt(query.substring(p+1, query.length()-1));
String att = query.substring(0, p);
res = getAttribut(att, i);
}
else {
res = getAttribut(query);
}
return res;
}
public ArrayValue<_C> getPathAttributAsArrayValue(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttribut(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttribut(parts[i]);
}
ArrayValue<_C> av = rpv.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property %s is not an array.", parts[parts.length - 1]));
return av;
}
public List<Value<?, _C>> getPathAttributAsArray(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttribut(parts[0]);
if(rpv == null) throw new ManagedException(String.format("The property path %s is not defined.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s is not defined.", pathAttribut));
rpv = rpo.getAttribut(parts[i]);
}
ArrayValue<_C> av = rpv.asArrayValue();
if(av == null) throw new ManagedException(String.format("The property path %s is not defined.", parts[parts.length - 1]));
return av.getValue();
}
/*public String getPathAttributAsString(String pathAttribut) {
try {
return getPathAttributAsStringEx(pathAttribut);
} catch (ManagedException e) {
e.printStackTrace();
}
return null;
}*/
public ObjectValue<_C> getPathAttributAsObjecValue(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
//if(rpv == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
}
if(rpv == null) return null;
ObjectValue<_C> ov = rpv.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object.", parts[parts.length - 1]));
return ov; //.getAttributAsObjectValue(parts[parts.length - 1]);
}
public ObjectValue<_C> getAttributByPathAsObjectValue(String pathAttribut) throws ManagedException {
String parts[] = pathAttribut.split("[.]");
Value<?, _C> rpv = getAttributEx(parts[0]);
if(rpv == null) return null;
for(int i=1;i<parts.length;i++) {
ObjectValue<_C> rpo = rpv.asObjectValue();
if(rpo == null) throw new ManagedException(String.format("The property path %s canot be reach.", pathAttribut));
rpv = rpo.getAttributEx(parts[i]);
if(rpv == null) return null;
}
//if(rpv == null) return null;
ObjectValue<_C> ov = rpv.asObjectValue();
if(ov == null) throw new ManagedException(String.format("The property %s is not an object.", parts[parts.length - 1]));
return ov; //.getAttributAsObjectValue(parts[parts.length - 1]);
}
/*public ObjectValue getPathAttributAsObjecValue(String pathAttribut) {
try {
return getPathAttributAsObjecValueEx(pathAttribut);
} catch (ManagedException e) {
e.printStackTrace();
}
return null;
}*/
public void setAttribut(String name, String avalue) {
value.put(name, new StringValue<_C>(avalue));
}
public void setAttribut(String name, Value<?, _C> avalue) {
value.put(name, avalue);
}
public ObjectValue<_C> addObjectValueAttribut(String name) {
ObjectValue<_C> res = new ObjectValue<>();
value.put(name, res);
return res;
}
public ArrayValue<_C> addArrayValueAttribut(String name) {
ArrayValue<_C> res = new ArrayValue<>();
value.put(name, res);
return res;
}
public Integer getIntOrStringIntAttribut(String name) throws ManagedException {
IntegerValue<_C> iv = asIntegerValue();
if(iv == null) {
StringValue<_C> sv = asStringValue();
if(sv == null) throw new ManagedException(String.format("This is not an integer or could not be convertes."));
String s = sv.getValue();
if(s == null) return null;
try {
Integer res = Integer.valueOf(s);
return res;
}catch(NumberFormatException e) {
throw new ManagedException(e);
}
}
return iv.getValue();
}
public Integer getRequiredIntOrStringIntAttribut(String name) throws ManagedException {
Integer res = getIntOrStringIntAttribut(name);
if(res == null) throw new ManagedException(String.format("The property %s should not be null", name));
return res;
}
public Boolean getRequiredAttributAsBoolean(String name) throws ManagedException {
Boolean res = getAttributAsBoolean(name);
if(res == null) throw new ManagedException(String.format("The property %s is required.", name));
return res;
}
public Boolean getAttributAsBoolean(String name) throws ManagedException {
Value<?, _C> v = value.get(name);
if(v == null) return null;
return v.asBoolean();
}
@Override
public ObjectValue<_C> clone() /*throws CloneNotSupportedException*/ {
ObjectValue<_C> res = new ObjectValue<>();
for(String k : value.keySet()) {
Value<?, _C> v = value.get(k);
res.setAttribut(k, v == null ? null : v.clone());
}
return res;
}
@Override
public String typeName() {
return "object";
}
}
| 13,191 | 0.682056 | 0.680009 | 439 | 29.047836 | 34.002075 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.425968 | false | false | 4 |
47b9947fe8dc134a4cf543b918a3e08bafc01050 | 24,412,594,118,144 | 66146ae814b0830ee390833cdc6f18d4e662e126 | /Java/Homework2/src/CheckID.java | 19c73479b12db30c6a279f046cc824cb259ddaf2 | []
| no_license | larrysoup/CECJ-Homework | https://github.com/larrysoup/CECJ-Homework | bed53d07b28e2cbc6b3abd75f5daaf9d997b708b | ae0e65533dc799b1da977d5f60afc840991d9b8d | refs/heads/master | 2021-01-21T05:00:31.342000 | 2014-08-14T16:08:29 | 2014-08-14T16:08:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 方法的練習-CheckID
* 執行時經由參數輸入一身份証字號,寫一方法(函數)傳回身份証字號是否正確。
* @author Mark
*/
import java.util.Scanner;
public class CheckID {
public static boolean checkID(String[] id) {
/* 身分證字號驗證 */
int checkH, checkF, trans, sum; // checkH 碼1檢查; checkF 身分證檢查碼(碼10); trans 檢查碼計算;
int[] checkB = new int[8]; // 用以存放碼1~碼9之陣列
for (int i = 0; i < 8; i++) {
checkB[i] = Integer.parseInt(id[i+1]); // 將碼1~碼9字串轉為整數放進陣列中
}
checkF = Integer.parseInt(id[9]); // 放入檢查碼
checkH = changeHead(id[0].toUpperCase()); // 將碼1的英文字母轉成整數放入.
trans = (checkH % 10) * 9 + (checkH / 10); // Step1. (個位數 * 9) + (十位數)
sum = trans;
for (int i = 1; i < (id.length-1); i++ ) {
checkB[i-1] *= (9 - i); // Step2. 各數字從右至左依次乘上1~8
}
for (int values: checkB) {
sum += values; // Step3. Step1 與 Step2 的總和
}
trans = 10 - (sum % 10); // Step4. 10 - ( Step3總和除以10的餘數 )
if (checkF == trans) return true;
else return false;
} // end of method checkID
static int changeHead(String head) {
/* 傳回首碼(英文字母)對應之數字 */
int checkH = 0;
switch (head) {
case "A": checkH = 10; break;
case "B": checkH = 11; break;
case "C": checkH = 12; break;
case "D": checkH = 13; break;
case "E": checkH = 14; break;
case "F": checkH = 15; break;
case "G": checkH = 16; break;
case "H": checkH = 17; break;
case "I": checkH = 34; break;
case "J": checkH = 18; break;
case "K": checkH = 19; break;
case "L": checkH = 20; break;
case "M": checkH = 21; break;
case "N": checkH = 22; break;
case "O": checkH = 35; break;
case "P": checkH = 23; break;
case "Q": checkH = 24; break;
case "R": checkH = 25; break;
case "S": checkH = 26; break;
case "T": checkH = 27; break;
case "U": checkH = 28; break;
case "V": checkH = 29; break;
case "W": checkH = 32; break;
case "X": checkH = 30; break;
case "Y": checkH = 31; break;
case "Z": checkH = 33; break;
}
return checkH;
} // end of method changeHead
public static void main(String[] args) {
String[] id = new String[10];
int checkHead;
String str;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("身分證字號驗證器, 欲離開請輸入\"exit\"\n請輸入您的身分證字號: ");
str = scanner.nextLine();
if (str.toLowerCase().equals("exit")) {
scanner.close();
System.exit(0);
}
String[] tokens = str.split("");
tokens[0].toUpperCase();
if (tokens.length == 10) { // 檢查ID格式長度
char[] cArray = str.toCharArray(); // 將字串轉字元
checkHead = (int) cArray[0]; // 放入頭碼(英文字母)
if ( (checkHead >= 65 && checkHead <= 90) || (checkHead >= 97 && checkHead <= 122) ) { //檢查ID碼1格式
if (tokens[1].equals("1") || tokens[1].equals("2")) { // 檢查ID碼2格式
for (int i = 0; i < tokens.length; i++) {
id[i] = tokens[i]; // ID格式正確.
}
System.out.println(checkID(id) ? "正確!" : "錯誤!"); // 驗證ID正確性
}
else {
System.out.println("您輸入的格式有誤!(碼2)");
}
}
else {
System.out.println("您輸入的格式有誤!(碼1)");
}
}
else {
System.out.println("您輸入的格式長度有誤.");
} // end of outer if..else
} // end of infinite while loop
} // end of main()
} // end of checkID | UTF-8 | Java | 3,846 | java | CheckID.java | Java | [
{
"context": " * 執行時經由參數輸入一身份証字號,寫一方法(函數)傳回身份証字號是否正確。\n * @author Mark\n */\nimport java.util.Scanner;\n\npublic class Check",
"end": 75,
"score": 0.9997497200965881,
"start": 71,
"tag": "NAME",
"value": "Mark"
}
]
| null | []
| /*
* 方法的練習-CheckID
* 執行時經由參數輸入一身份証字號,寫一方法(函數)傳回身份証字號是否正確。
* @author Mark
*/
import java.util.Scanner;
public class CheckID {
public static boolean checkID(String[] id) {
/* 身分證字號驗證 */
int checkH, checkF, trans, sum; // checkH 碼1檢查; checkF 身分證檢查碼(碼10); trans 檢查碼計算;
int[] checkB = new int[8]; // 用以存放碼1~碼9之陣列
for (int i = 0; i < 8; i++) {
checkB[i] = Integer.parseInt(id[i+1]); // 將碼1~碼9字串轉為整數放進陣列中
}
checkF = Integer.parseInt(id[9]); // 放入檢查碼
checkH = changeHead(id[0].toUpperCase()); // 將碼1的英文字母轉成整數放入.
trans = (checkH % 10) * 9 + (checkH / 10); // Step1. (個位數 * 9) + (十位數)
sum = trans;
for (int i = 1; i < (id.length-1); i++ ) {
checkB[i-1] *= (9 - i); // Step2. 各數字從右至左依次乘上1~8
}
for (int values: checkB) {
sum += values; // Step3. Step1 與 Step2 的總和
}
trans = 10 - (sum % 10); // Step4. 10 - ( Step3總和除以10的餘數 )
if (checkF == trans) return true;
else return false;
} // end of method checkID
static int changeHead(String head) {
/* 傳回首碼(英文字母)對應之數字 */
int checkH = 0;
switch (head) {
case "A": checkH = 10; break;
case "B": checkH = 11; break;
case "C": checkH = 12; break;
case "D": checkH = 13; break;
case "E": checkH = 14; break;
case "F": checkH = 15; break;
case "G": checkH = 16; break;
case "H": checkH = 17; break;
case "I": checkH = 34; break;
case "J": checkH = 18; break;
case "K": checkH = 19; break;
case "L": checkH = 20; break;
case "M": checkH = 21; break;
case "N": checkH = 22; break;
case "O": checkH = 35; break;
case "P": checkH = 23; break;
case "Q": checkH = 24; break;
case "R": checkH = 25; break;
case "S": checkH = 26; break;
case "T": checkH = 27; break;
case "U": checkH = 28; break;
case "V": checkH = 29; break;
case "W": checkH = 32; break;
case "X": checkH = 30; break;
case "Y": checkH = 31; break;
case "Z": checkH = 33; break;
}
return checkH;
} // end of method changeHead
public static void main(String[] args) {
String[] id = new String[10];
int checkHead;
String str;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("身分證字號驗證器, 欲離開請輸入\"exit\"\n請輸入您的身分證字號: ");
str = scanner.nextLine();
if (str.toLowerCase().equals("exit")) {
scanner.close();
System.exit(0);
}
String[] tokens = str.split("");
tokens[0].toUpperCase();
if (tokens.length == 10) { // 檢查ID格式長度
char[] cArray = str.toCharArray(); // 將字串轉字元
checkHead = (int) cArray[0]; // 放入頭碼(英文字母)
if ( (checkHead >= 65 && checkHead <= 90) || (checkHead >= 97 && checkHead <= 122) ) { //檢查ID碼1格式
if (tokens[1].equals("1") || tokens[1].equals("2")) { // 檢查ID碼2格式
for (int i = 0; i < tokens.length; i++) {
id[i] = tokens[i]; // ID格式正確.
}
System.out.println(checkID(id) ? "正確!" : "錯誤!"); // 驗證ID正確性
}
else {
System.out.println("您輸入的格式有誤!(碼2)");
}
}
else {
System.out.println("您輸入的格式有誤!(碼1)");
}
}
else {
System.out.println("您輸入的格式長度有誤.");
} // end of outer if..else
} // end of infinite while loop
} // end of main()
} // end of checkID | 3,846 | 0.530564 | 0.495252 | 105 | 31.104761 | 21.39823 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.285714 | false | false | 4 |
b81deeeb2ce1c05a5562f680213d2907167b0555 | 21,380,347,207,834 | 3ff62bbb950a86a45910aa02fa435d34bc93dc40 | /Client-Server/src/com/cdk/CricketResult.java | 6cce4574ecf864a4a468b0467a4b74f6a47d4d1a | []
| no_license | adiraag/adikaal | https://github.com/adiraag/adikaal | 1d175423afb0a158447665a72cce56946f51f781 | c0a22151a46fc8b908497dd708950ea19fdc63ef | refs/heads/master | 2020-11-30T04:17:32.572000 | 2017-08-03T12:07:54 | 2017-08-03T12:07:54 | 96,882,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cdk;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class CricketResult extends HttpServlet {
List<CricketMatch> matchInfo = new ArrayList<>();
public void init() throws ServletException {
matchInfo.add(new CricketMatch("INDIA", "ENGLAND", "TEST", 90, "London", "INDIA"));
matchInfo.add(new CricketMatch("INDIA", "ENGLAND", "T-20", 20, "PUNE", "ENGLAND"));
matchInfo.add(new CricketMatch("ENGLAND", "INDIA", "ODI", 50, "DELHI", "INDIA"));
}
public void destroy() {
matchInfo.clear();
matchInfo = null;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String matchType = request.getParameter("matchType");
String country1 = request.getParameter("country1");
String country2 = request.getParameter("country2");
PrintWriter pw = response.getWriter();
pw.write("Details of the match is : ");
Iterator<CricketMatch> itr = matchInfo.iterator();
while (itr.hasNext()) {
CricketMatch match = itr.next();
if (match.getCountry1().equals(country1) && match.getCountry2().equals(country2) && match.getMatchType().equals(matchType)) {
pw.write(match.toString());
break;
}
}
}
} | UTF-8 | Java | 1,566 | java | CricketResult.java | Java | []
| null | []
| package com.cdk;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class CricketResult extends HttpServlet {
List<CricketMatch> matchInfo = new ArrayList<>();
public void init() throws ServletException {
matchInfo.add(new CricketMatch("INDIA", "ENGLAND", "TEST", 90, "London", "INDIA"));
matchInfo.add(new CricketMatch("INDIA", "ENGLAND", "T-20", 20, "PUNE", "ENGLAND"));
matchInfo.add(new CricketMatch("ENGLAND", "INDIA", "ODI", 50, "DELHI", "INDIA"));
}
public void destroy() {
matchInfo.clear();
matchInfo = null;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String matchType = request.getParameter("matchType");
String country1 = request.getParameter("country1");
String country2 = request.getParameter("country2");
PrintWriter pw = response.getWriter();
pw.write("Details of the match is : ");
Iterator<CricketMatch> itr = matchInfo.iterator();
while (itr.hasNext()) {
CricketMatch match = itr.next();
if (match.getCountry1().equals(country1) && match.getCountry2().equals(country2) && match.getMatchType().equals(matchType)) {
pw.write(match.toString());
break;
}
}
}
} | 1,566 | 0.653895 | 0.643678 | 50 | 30.34 | 32.750336 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 4 |
3d9c15046b76b005a135c1ca2b83ca1e422a3d94 | 13,056,700,647,226 | 60afad93634803dba3b914733cd827bb0ba47dcb | /cz.fhsoft.poker.league/src/cz/fhsoft/poker/league/server/services/GameServiceImpl.java | 5b975d521423781ef379e4dbd769da0f876edc69 | []
| no_license | fhrbek/poker-league | https://github.com/fhrbek/poker-league | e2063a8c70f91fbdae110e85230e177f6bba724c | 9a38aca5444f3a63a0cc2f7686bb1ad751b85b4a | refs/heads/master | 2021-01-13T02:24:01.892000 | 2018-12-31T09:44:20 | 2018-12-31T09:44:20 | 7,480,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.fhsoft.poker.league.server.services;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;
import javax.persistence.Query;
import cz.fhsoft.poker.league.client.services.GameService;
import cz.fhsoft.poker.league.server.AbstractServiceImpl;
import cz.fhsoft.poker.league.server.ServletInitializer;
import cz.fhsoft.poker.league.server.persistence.EntityServiceImpl;
import cz.fhsoft.poker.league.server.persistence.EntityServiceImpl.DataAction;
import cz.fhsoft.poker.league.shared.model.v1.Game;
import cz.fhsoft.poker.league.shared.model.v1.Player;
import cz.fhsoft.poker.league.shared.model.v1.PlayerInGame;
import cz.fhsoft.poker.league.shared.model.v1.Tournament;
import cz.fhsoft.poker.league.shared.util.TransferrableException;
@SuppressWarnings("serial")
public class GameServiceImpl extends AbstractServiceImpl implements GameService {
private static final Query currentTournaments = ServletInitializer.getEntityManager().createQuery(
"SELECT t FROM cz.fhsoft.poker.league.shared.model.v1.Tournament t WHERE t.tournamentStart <= :startLimit AND t.tournamentEnd >= :endLimit");
@Override
public List<Tournament> getCurrentTournaments() throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<List<Tournament>>() {
@Override
public List<Tournament> run() throws TransferrableException {
Date currentTime = new Date();
Date startLimit = new Date(currentTime.getTime() + 3600000);
Date endLimit = new Date(currentTime.getTime() - 3600000);
List<Tournament> resultList = new ArrayList<Tournament>();
currentTournaments.setParameter("startLimit", startLimit);
currentTournaments.setParameter("endLimit", endLimit);
for(Object obj : currentTournaments.getResultList()) {
Tournament tournament = (Tournament) obj;
resultList.add(EntityServiceImpl.makeTransferable(tournament));
}
return resultList;
}
});
}
@Override
public WhiteList whiteListDummy(WhiteList whiteList) {
return null;
}
@Override
public long startNewGame(final Integer tournamentId, final List<Integer> playerIds) throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<Long>() {
@Override
public Long run() throws TransferrableException {
Tournament tournament = ServletInitializer.getEntityManager().find(Tournament.class, tournamentId);
if(tournament == null)
throw new IllegalArgumentException("Nebyl nalezen turnaj s ID=" + tournamentId);
int maxGameOrdinal = 0;
for(Game game : tournament.getGames())
if(game.getOrdinal() > maxGameOrdinal)
maxGameOrdinal = game.getOrdinal();
Game game = new Game();
game.setTournament(tournament);
game.setOrdinal(maxGameOrdinal+1);
game.setBuyIn(tournament.getDefaultBuyIn());
game.setPrizeMoneyRuleSet(tournament.getDefaultPrizeMoneyRuleSet());
for(Integer id : playerIds) {
Player player = ServletInitializer.getEntityManager().find(Player.class, id);
if(player == null)
throw new IllegalArgumentException("Nebyl nalezen hráč s ID=" + id);
PlayerInGame playerInGame = new PlayerInGame();
playerInGame.setGame(game);
playerInGame.setPlayer(player);
playerInGame.setRank(0);
game.addToPlayersInGame(playerInGame);
}
ServletInitializer.getEntityManager().merge(game);
long dataVersion = EntityServiceImpl.updateDataVersion();
return dataVersion;
}
});
}
@Override
public long seatOpen(final List<Integer> playerInGameIds) throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<Long>() {
@Override
public Long run() throws TransferrableException {
Game game = null;
List<PlayerInGame> playersInGameForSeatOpen = new ArrayList<PlayerInGame>();
for(Integer playerInGameId : playerInGameIds) {
PlayerInGame playerInGame = ServletInitializer.getEntityManager().find(PlayerInGame.class, playerInGameId);
if(playerInGame == null)
throw new IllegalArgumentException("Hráči k vyřazení s ID=" + playerInGameId + " nebyl nalezen");
if(game == null)
game = playerInGame.getGame();
else if(game != playerInGame.getGame())
throw new IllegalArgumentException("Hráči k vyřazení nehrají stejnou hru");
if(playerInGame.getRank() == 0)
playersInGameForSeatOpen.add(playerInGame);
}
if(game == null)
return EntityServiceImpl.getDataVersionStatic();
int minRank = game.getPlayersInGame().size() + 1;
for(PlayerInGame rankedPlayerInGame : game.getPlayersInGame())
if(rankedPlayerInGame.getRank() > 0 && rankedPlayerInGame.getRank() < minRank)
minRank = rankedPlayerInGame.getRank();
if(minRank <= 1)
throw new IllegalArgumentException("Alespoň jeden hráč byl již označen jako vítěz, nelze vyřadit další hráče");
int finalRank = minRank - playersInGameForSeatOpen.size();
if(finalRank == 2) // there's just one player left - let's mark him as a winner right now
for(PlayerInGame playerInGame : game.getPlayersInGame())
if(!playersInGameForSeatOpen.contains(playerInGame) && playerInGame.getRank() == 0) {
playerInGame.setRank(1);
break;
}
for(PlayerInGame playerInGameForSeatOpen : playersInGameForSeatOpen)
playerInGameForSeatOpen.setRank(finalRank);
ServletInitializer.getEntityManager().merge(game);
long dataVersion = EntityServiceImpl.updateDataVersion();
return dataVersion;
}
});
}
@Override
public long undoSeatOpen(final List<Integer> playerInGameIds) throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<Long>() {
@Override
public Long run() throws TransferrableException {
Game game = null;
List<PlayerInGame> playersInGameForUndoSeatOpen = new ArrayList<PlayerInGame>();
for(Integer playerInGameId : playerInGameIds) {
PlayerInGame playerInGame = ServletInitializer.getEntityManager().find(PlayerInGame.class, playerInGameId);
if(playerInGame == null)
throw new IllegalArgumentException("Hráči k zařazení zpět do hry s ID=" + playerInGameId + " nebyl nalezen");
if(game == null)
game = playerInGame.getGame();
else if(game != playerInGame.getGame())
throw new IllegalArgumentException("Hráči k zařazení zpět do hry nehrají stejnou hru");
if(playerInGame.getRank() > 0)
playersInGameForUndoSeatOpen.add(playerInGame);
}
if(game == null)
return EntityServiceImpl.getDataVersionStatic();
int reRank = 1;
TreeMap<Integer, PlayerInGame> ranks = new TreeMap<Integer, PlayerInGame>();
for(PlayerInGame rankedPlayerInGame : game.getPlayersInGame())
if(rankedPlayerInGame.getRank() > 0 && !playersInGameForUndoSeatOpen.contains(rankedPlayerInGame))
ranks.put(rankedPlayerInGame.getRank(), rankedPlayerInGame);
else
reRank++;
for(PlayerInGame playerInGameForUndoSeatOpen : playersInGameForUndoSeatOpen)
playerInGameForUndoSeatOpen.setRank(0);
for(PlayerInGame rerankedPlayerInGame : ranks.values())
rerankedPlayerInGame.setRank(reRank++);
ServletInitializer.getEntityManager().merge(game);
long dataVersion = EntityServiceImpl.updateDataVersion();
return dataVersion;
}
});
}
}
| UTF-8 | Java | 7,415 | java | GameServiceImpl.java | Java | []
| null | []
| package cz.fhsoft.poker.league.server.services;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;
import javax.persistence.Query;
import cz.fhsoft.poker.league.client.services.GameService;
import cz.fhsoft.poker.league.server.AbstractServiceImpl;
import cz.fhsoft.poker.league.server.ServletInitializer;
import cz.fhsoft.poker.league.server.persistence.EntityServiceImpl;
import cz.fhsoft.poker.league.server.persistence.EntityServiceImpl.DataAction;
import cz.fhsoft.poker.league.shared.model.v1.Game;
import cz.fhsoft.poker.league.shared.model.v1.Player;
import cz.fhsoft.poker.league.shared.model.v1.PlayerInGame;
import cz.fhsoft.poker.league.shared.model.v1.Tournament;
import cz.fhsoft.poker.league.shared.util.TransferrableException;
@SuppressWarnings("serial")
public class GameServiceImpl extends AbstractServiceImpl implements GameService {
private static final Query currentTournaments = ServletInitializer.getEntityManager().createQuery(
"SELECT t FROM cz.fhsoft.poker.league.shared.model.v1.Tournament t WHERE t.tournamentStart <= :startLimit AND t.tournamentEnd >= :endLimit");
@Override
public List<Tournament> getCurrentTournaments() throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<List<Tournament>>() {
@Override
public List<Tournament> run() throws TransferrableException {
Date currentTime = new Date();
Date startLimit = new Date(currentTime.getTime() + 3600000);
Date endLimit = new Date(currentTime.getTime() - 3600000);
List<Tournament> resultList = new ArrayList<Tournament>();
currentTournaments.setParameter("startLimit", startLimit);
currentTournaments.setParameter("endLimit", endLimit);
for(Object obj : currentTournaments.getResultList()) {
Tournament tournament = (Tournament) obj;
resultList.add(EntityServiceImpl.makeTransferable(tournament));
}
return resultList;
}
});
}
@Override
public WhiteList whiteListDummy(WhiteList whiteList) {
return null;
}
@Override
public long startNewGame(final Integer tournamentId, final List<Integer> playerIds) throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<Long>() {
@Override
public Long run() throws TransferrableException {
Tournament tournament = ServletInitializer.getEntityManager().find(Tournament.class, tournamentId);
if(tournament == null)
throw new IllegalArgumentException("Nebyl nalezen turnaj s ID=" + tournamentId);
int maxGameOrdinal = 0;
for(Game game : tournament.getGames())
if(game.getOrdinal() > maxGameOrdinal)
maxGameOrdinal = game.getOrdinal();
Game game = new Game();
game.setTournament(tournament);
game.setOrdinal(maxGameOrdinal+1);
game.setBuyIn(tournament.getDefaultBuyIn());
game.setPrizeMoneyRuleSet(tournament.getDefaultPrizeMoneyRuleSet());
for(Integer id : playerIds) {
Player player = ServletInitializer.getEntityManager().find(Player.class, id);
if(player == null)
throw new IllegalArgumentException("Nebyl nalezen hráč s ID=" + id);
PlayerInGame playerInGame = new PlayerInGame();
playerInGame.setGame(game);
playerInGame.setPlayer(player);
playerInGame.setRank(0);
game.addToPlayersInGame(playerInGame);
}
ServletInitializer.getEntityManager().merge(game);
long dataVersion = EntityServiceImpl.updateDataVersion();
return dataVersion;
}
});
}
@Override
public long seatOpen(final List<Integer> playerInGameIds) throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<Long>() {
@Override
public Long run() throws TransferrableException {
Game game = null;
List<PlayerInGame> playersInGameForSeatOpen = new ArrayList<PlayerInGame>();
for(Integer playerInGameId : playerInGameIds) {
PlayerInGame playerInGame = ServletInitializer.getEntityManager().find(PlayerInGame.class, playerInGameId);
if(playerInGame == null)
throw new IllegalArgumentException("Hráči k vyřazení s ID=" + playerInGameId + " nebyl nalezen");
if(game == null)
game = playerInGame.getGame();
else if(game != playerInGame.getGame())
throw new IllegalArgumentException("Hráči k vyřazení nehrají stejnou hru");
if(playerInGame.getRank() == 0)
playersInGameForSeatOpen.add(playerInGame);
}
if(game == null)
return EntityServiceImpl.getDataVersionStatic();
int minRank = game.getPlayersInGame().size() + 1;
for(PlayerInGame rankedPlayerInGame : game.getPlayersInGame())
if(rankedPlayerInGame.getRank() > 0 && rankedPlayerInGame.getRank() < minRank)
minRank = rankedPlayerInGame.getRank();
if(minRank <= 1)
throw new IllegalArgumentException("Alespoň jeden hráč byl již označen jako vítěz, nelze vyřadit další hráče");
int finalRank = minRank - playersInGameForSeatOpen.size();
if(finalRank == 2) // there's just one player left - let's mark him as a winner right now
for(PlayerInGame playerInGame : game.getPlayersInGame())
if(!playersInGameForSeatOpen.contains(playerInGame) && playerInGame.getRank() == 0) {
playerInGame.setRank(1);
break;
}
for(PlayerInGame playerInGameForSeatOpen : playersInGameForSeatOpen)
playerInGameForSeatOpen.setRank(finalRank);
ServletInitializer.getEntityManager().merge(game);
long dataVersion = EntityServiceImpl.updateDataVersion();
return dataVersion;
}
});
}
@Override
public long undoSeatOpen(final List<Integer> playerInGameIds) throws TransferrableException {
return EntityServiceImpl.doWithLock(new DataAction<Long>() {
@Override
public Long run() throws TransferrableException {
Game game = null;
List<PlayerInGame> playersInGameForUndoSeatOpen = new ArrayList<PlayerInGame>();
for(Integer playerInGameId : playerInGameIds) {
PlayerInGame playerInGame = ServletInitializer.getEntityManager().find(PlayerInGame.class, playerInGameId);
if(playerInGame == null)
throw new IllegalArgumentException("Hráči k zařazení zpět do hry s ID=" + playerInGameId + " nebyl nalezen");
if(game == null)
game = playerInGame.getGame();
else if(game != playerInGame.getGame())
throw new IllegalArgumentException("Hráči k zařazení zpět do hry nehrají stejnou hru");
if(playerInGame.getRank() > 0)
playersInGameForUndoSeatOpen.add(playerInGame);
}
if(game == null)
return EntityServiceImpl.getDataVersionStatic();
int reRank = 1;
TreeMap<Integer, PlayerInGame> ranks = new TreeMap<Integer, PlayerInGame>();
for(PlayerInGame rankedPlayerInGame : game.getPlayersInGame())
if(rankedPlayerInGame.getRank() > 0 && !playersInGameForUndoSeatOpen.contains(rankedPlayerInGame))
ranks.put(rankedPlayerInGame.getRank(), rankedPlayerInGame);
else
reRank++;
for(PlayerInGame playerInGameForUndoSeatOpen : playersInGameForUndoSeatOpen)
playerInGameForUndoSeatOpen.setRank(0);
for(PlayerInGame rerankedPlayerInGame : ranks.values())
rerankedPlayerInGame.setRank(reRank++);
ServletInitializer.getEntityManager().merge(game);
long dataVersion = EntityServiceImpl.updateDataVersion();
return dataVersion;
}
});
}
}
| 7,415 | 0.737434 | 0.732963 | 206 | 34.830097 | 32.695198 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.364078 | false | false | 4 |
6b15c86677963016c555e6776fae35858eeb83c6 | 22,900,765,626,229 | 57eb91f2ddb78604d1a2e2d370d929d31365e2b9 | /app/src/main/java/com/red_folder/beyondpodlistener/ListenerService.java | 628e601228574736e44ff12c9170c587923867ff | [
"Apache-2.0"
]
| permissive | Red-Folder/BeyondPodListener | https://github.com/Red-Folder/BeyondPodListener | 90b7f4c4bbfc0c57ae7c37cbf80cf6bb3f61cc56 | 58a1f922e99503a4897aabb46c64e2cdc28c6e5a | refs/heads/master | 2021-06-11T12:24:54.511000 | 2020-09-24T15:33:01 | 2020-09-24T15:33:01 | 145,292,424 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.red_folder.beyondpodlistener;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.analytics.Analytics;
import com.microsoft.appcenter.crashes.Crashes;
public class ListenerService extends Service implements INotificationListener {
private static String TAG = "ListenerService";
private static final int ONGOING_NOTIFICATION_ID = 5567;
private static final String NOTIFICATION_CHANNEL_ID = "com.red_folder.beyondpodlistener_001";
private static final String NOTIFICATION_CHANNEL_NAME = "com.red_folder.beyondpodlistener";
public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";
public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";
private BroadcastReceiver mReceiver = new BeyondPodReceiver(this);
private Notification.Builder mBuilder = null;
@Override
public void onCreate() {
super.onCreate();
if (!AppCenter.isConfigured()) {
AppCenter.start(getApplication(), BuildConfig.AppCenterSecretKey, Analytics.class, Crashes.class);
}
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
notificationManager.createNotificationChannel(notificationChannel);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
mBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not implemented");
}
private void startForegroundService() {
IntentFilter filter = new IntentFilter();
filter.addAction("mobi.beyondpod.action.PLAYBACK_STATUS");
registerReceiver(mReceiver, filter);
mBuilder.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setColor(Color.GREEN)
.setProgress(0, 0, false)
.setVisibility(Notification.VISIBILITY_PUBLIC);
startForeground(ONGOING_NOTIFICATION_ID, mBuilder.build());
}
private void stopForegroundService() {
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
private Notification buildNotification(PodModel model) {
String title = model.getPlaying() ? "Listening" : "Was listening to";
String text = model.getEpisodeName();
int color = model.getPlaying() ? Color.RED : Color.GREEN;
mBuilder.setContentTitle(title)
.setContentText(text)
.setColor(color);
if (model.getPlaying() && model.getEpisodeDuration() > 0) {
mBuilder.setProgress((int)model.getEpisodeDuration(), (int)model.getEpisodePosition(), false);
} else {
mBuilder.setProgress(0, 0, false);
}
return mBuilder.build();
}
@Override
public void updateNotification(PodModel model) {
if (model != null) {
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ONGOING_NOTIFICATION_ID, buildNotification(model));
}
}
}
| UTF-8 | Java | 5,351 | java | ListenerService.java | Java | []
| null | []
| package com.red_folder.beyondpodlistener;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.analytics.Analytics;
import com.microsoft.appcenter.crashes.Crashes;
public class ListenerService extends Service implements INotificationListener {
private static String TAG = "ListenerService";
private static final int ONGOING_NOTIFICATION_ID = 5567;
private static final String NOTIFICATION_CHANNEL_ID = "com.red_folder.beyondpodlistener_001";
private static final String NOTIFICATION_CHANNEL_NAME = "com.red_folder.beyondpodlistener";
public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";
public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";
private BroadcastReceiver mReceiver = new BeyondPodReceiver(this);
private Notification.Builder mBuilder = null;
@Override
public void onCreate() {
super.onCreate();
if (!AppCenter.isConfigured()) {
AppCenter.start(getApplication(), BuildConfig.AppCenterSecretKey, Analytics.class, Crashes.class);
}
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
notificationManager.createNotificationChannel(notificationChannel);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
mBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case ACTION_START_FOREGROUND_SERVICE:
startForegroundService();
break;
case ACTION_STOP_FOREGROUND_SERVICE:
stopForegroundService();
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not implemented");
}
private void startForegroundService() {
IntentFilter filter = new IntentFilter();
filter.addAction("mobi.beyondpod.action.PLAYBACK_STATUS");
registerReceiver(mReceiver, filter);
mBuilder.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setColor(Color.GREEN)
.setProgress(0, 0, false)
.setVisibility(Notification.VISIBILITY_PUBLIC);
startForeground(ONGOING_NOTIFICATION_ID, mBuilder.build());
}
private void stopForegroundService() {
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
private Notification buildNotification(PodModel model) {
String title = model.getPlaying() ? "Listening" : "Was listening to";
String text = model.getEpisodeName();
int color = model.getPlaying() ? Color.RED : Color.GREEN;
mBuilder.setContentTitle(title)
.setContentText(text)
.setColor(color);
if (model.getPlaying() && model.getEpisodeDuration() > 0) {
mBuilder.setProgress((int)model.getEpisodeDuration(), (int)model.getEpisodePosition(), false);
} else {
mBuilder.setProgress(0, 0, false);
}
return mBuilder.build();
}
@Override
public void updateNotification(PodModel model) {
if (model != null) {
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ONGOING_NOTIFICATION_ID, buildNotification(model));
}
}
}
| 5,351 | 0.679499 | 0.676696 | 137 | 37.058395 | 32.238113 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.664234 | false | false | 4 |
088a702676c80b14390c7a0b879e2086b46b99b0 | 7,241,314,875,497 | 5c1a983c7991ec2a3deecd96cceb319cff0d27a9 | /movieApp/app/src/main/java/com/creapple/movieapp/MainActivity.java | 49ed8d7c39289cefa9ff39cd8565029bef57cf24 | []
| no_license | SpaciousKitchen/android | https://github.com/SpaciousKitchen/android | 873e98dea815d776532bc15712a888a1f96dafb5 | c029e73e4eb4fc93001b443f2252def37bdfd600 | refs/heads/master | 2023-04-24T10:24:34.792000 | 2021-05-12T09:10:37 | 2021-05-12T09:10:37 | 274,675,754 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.creapple.movieapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Dictionary;
public class MainActivity extends AppCompatActivity {
RecyclerView mrecyclerView;
Button btn_good, btn_bad, writecomment, show_btn;
int counter1, counter2, index;
boolean likestate = false, badstate = false;
TextView num_good, num_bad, movie_content;
ArrayList<CommentInfo> commentInfoArrayList;
AdapterComment adapterComment;
RatingBar starbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mrecyclerView = findViewById(R.id.recyclerView);
mrecyclerView.setHasFixedSize(true);
mrecyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
LinearLayoutManager mLayoutManger = new LinearLayoutManager(this);
mrecyclerView.setLayoutManager(mLayoutManger);
starbar = (RatingBar) findViewById(R.id.star_bar);
btn_good = (Button) findViewById(R.id.btn_good);
btn_bad = (Button) findViewById(R.id.btn_bad);
writecomment = (Button) findViewById(R.id.writecomment);
show_btn = (Button) findViewById(R.id.show_btn);
num_good = (TextView) findViewById(R.id.num_good);
num_bad = (TextView) findViewById(R.id.num_bad);
//movie_content = (TextView) findViewById(R.id.searchResult);
counter1 = 2;
counter2 = 3;
index = 0;
num_good.setText(String.valueOf(counter1));
num_bad.setText(String.valueOf(counter2));
commentInfoArrayList = new ArrayList<>();
adapterComment = new AdapterComment(commentInfoArrayList);
mrecyclerView.setAdapter(adapterComment);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mrecyclerView.getContext(), mLayoutManger.getOrientation());
mrecyclerView.addItemDecoration(dividerItemDecoration);
commentInfoArrayList.add(new CommentInfo("thd8686", 1, "10분전", "구리다 구려"));
commentInfoArrayList.add(new CommentInfo("seungjne", 2, "20분전", "이딴걸 영화라고"));
commentInfoArrayList.add(new CommentInfo("youlime_m3", 4, "10분전", "생각보다 나쁘지 않은 듯?"));
commentInfoArrayList.add(new CommentInfo("soso_", 3, "20분전", "호불호가 갈릴듯 .."));
btn_good.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (badstate == false & likestate == false) {
counter1 += 1;
num_good.setText(String.valueOf(counter1));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up_selected);
likestate = !likestate;
} else if (badstate == false & likestate == true) {
counter1 -= 1;
num_good.setText(String.valueOf(counter1));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up);
likestate = !likestate;
} else if (badstate == true & likestate == false) {
counter1 += 1;
counter2 -= 1;
num_good.setText(String.valueOf(counter1));
num_bad.setText(String.valueOf(counter2));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up_selected);
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down);
badstate = !badstate;
likestate = !likestate;
}
}
});
btn_bad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (badstate == false & likestate == false) {
counter2 += 1;
num_bad.setText(String.valueOf(counter2));
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down_selected);
badstate = !badstate;
} else if (badstate == true & likestate == false) {
counter2 -= 1;
num_bad.setText(String.valueOf(counter2));
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down);
badstate = !badstate;
} else if (likestate == true & badstate == false) {
counter1 -= 1;
counter2 += 1;
num_good.setText(String.valueOf(counter1));
num_bad.setText(String.valueOf(counter2));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up);
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down_selected);
badstate = !badstate;
likestate = !likestate;
}
}
});
show_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSendCommentdate();
}
});
writecomment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), WriteComment.class);
startActivityForResult(intent, 101);
}
});
starbar.setEnabled(true);
starbar.setClickable(true);
starbar.setRating(0);
starbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
starbar.setRating(rating);
}
});
}
public void startSendCommentdate(){
Intent intent =new Intent(getApplicationContext(),showAllData.class);
ArrayList <CommentInfo> Comment =new ArrayList<>();
// Comment.add();
// intent.putParcelableArrayListExtra("list", Comment);
startActivity(intent);
}
//응답을 받아주는 메소드
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String writedata = data.getStringExtra("comment");
float writerating1 = data.getExtras().getFloat("inputrating",0F); //rating 받을시에 getExtras().getFloat ??이거 왜일까 /.
Log.e("testval11", writedata);
float writerating = data.getFloatExtra("inputrating",11.1F); //rating 받을시에 getExtras().getFloat ??이거 왜일까 /.
Log.e("testval22", String.valueOf(writerating));
if (requestCode == 101) {
if(data !=null) {
CommentInfo newInfo = new CommentInfo("", writerating, "1분전", writedata); //정보 연결
commentInfoArrayList.add(newInfo);
adapterComment.notifyDataSetChanged();
}else{
}
}
}
}
| UTF-8 | Java | 7,972 | java | MainActivity.java | Java | []
| null | []
| package com.creapple.movieapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Dictionary;
public class MainActivity extends AppCompatActivity {
RecyclerView mrecyclerView;
Button btn_good, btn_bad, writecomment, show_btn;
int counter1, counter2, index;
boolean likestate = false, badstate = false;
TextView num_good, num_bad, movie_content;
ArrayList<CommentInfo> commentInfoArrayList;
AdapterComment adapterComment;
RatingBar starbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mrecyclerView = findViewById(R.id.recyclerView);
mrecyclerView.setHasFixedSize(true);
mrecyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
LinearLayoutManager mLayoutManger = new LinearLayoutManager(this);
mrecyclerView.setLayoutManager(mLayoutManger);
starbar = (RatingBar) findViewById(R.id.star_bar);
btn_good = (Button) findViewById(R.id.btn_good);
btn_bad = (Button) findViewById(R.id.btn_bad);
writecomment = (Button) findViewById(R.id.writecomment);
show_btn = (Button) findViewById(R.id.show_btn);
num_good = (TextView) findViewById(R.id.num_good);
num_bad = (TextView) findViewById(R.id.num_bad);
//movie_content = (TextView) findViewById(R.id.searchResult);
counter1 = 2;
counter2 = 3;
index = 0;
num_good.setText(String.valueOf(counter1));
num_bad.setText(String.valueOf(counter2));
commentInfoArrayList = new ArrayList<>();
adapterComment = new AdapterComment(commentInfoArrayList);
mrecyclerView.setAdapter(adapterComment);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mrecyclerView.getContext(), mLayoutManger.getOrientation());
mrecyclerView.addItemDecoration(dividerItemDecoration);
commentInfoArrayList.add(new CommentInfo("thd8686", 1, "10분전", "구리다 구려"));
commentInfoArrayList.add(new CommentInfo("seungjne", 2, "20분전", "이딴걸 영화라고"));
commentInfoArrayList.add(new CommentInfo("youlime_m3", 4, "10분전", "생각보다 나쁘지 않은 듯?"));
commentInfoArrayList.add(new CommentInfo("soso_", 3, "20분전", "호불호가 갈릴듯 .."));
btn_good.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (badstate == false & likestate == false) {
counter1 += 1;
num_good.setText(String.valueOf(counter1));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up_selected);
likestate = !likestate;
} else if (badstate == false & likestate == true) {
counter1 -= 1;
num_good.setText(String.valueOf(counter1));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up);
likestate = !likestate;
} else if (badstate == true & likestate == false) {
counter1 += 1;
counter2 -= 1;
num_good.setText(String.valueOf(counter1));
num_bad.setText(String.valueOf(counter2));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up_selected);
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down);
badstate = !badstate;
likestate = !likestate;
}
}
});
btn_bad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (badstate == false & likestate == false) {
counter2 += 1;
num_bad.setText(String.valueOf(counter2));
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down_selected);
badstate = !badstate;
} else if (badstate == true & likestate == false) {
counter2 -= 1;
num_bad.setText(String.valueOf(counter2));
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down);
badstate = !badstate;
} else if (likestate == true & badstate == false) {
counter1 -= 1;
counter2 += 1;
num_good.setText(String.valueOf(counter1));
num_bad.setText(String.valueOf(counter2));
btn_good.setBackgroundResource(R.drawable.ic_thumb_up);
btn_bad.setBackgroundResource(R.drawable.ic_thumb_down_selected);
badstate = !badstate;
likestate = !likestate;
}
}
});
show_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSendCommentdate();
}
});
writecomment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), WriteComment.class);
startActivityForResult(intent, 101);
}
});
starbar.setEnabled(true);
starbar.setClickable(true);
starbar.setRating(0);
starbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
starbar.setRating(rating);
}
});
}
public void startSendCommentdate(){
Intent intent =new Intent(getApplicationContext(),showAllData.class);
ArrayList <CommentInfo> Comment =new ArrayList<>();
// Comment.add();
// intent.putParcelableArrayListExtra("list", Comment);
startActivity(intent);
}
//응답을 받아주는 메소드
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String writedata = data.getStringExtra("comment");
float writerating1 = data.getExtras().getFloat("inputrating",0F); //rating 받을시에 getExtras().getFloat ??이거 왜일까 /.
Log.e("testval11", writedata);
float writerating = data.getFloatExtra("inputrating",11.1F); //rating 받을시에 getExtras().getFloat ??이거 왜일까 /.
Log.e("testval22", String.valueOf(writerating));
if (requestCode == 101) {
if(data !=null) {
CommentInfo newInfo = new CommentInfo("", writerating, "1분전", writedata); //정보 연결
commentInfoArrayList.add(newInfo);
adapterComment.notifyDataSetChanged();
}else{
}
}
}
}
| 7,972 | 0.585568 | 0.577011 | 237 | 30.852322 | 30.506266 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.637131 | false | false | 4 |
80b933343dc98f45e17e33870262371049c709d2 | 22,170,621,190,194 | 471178f45ce21b1da8155b07675304edcc565bda | /Stint/android/app/src/main/java/com/oosd/project/taskmanagementapp/adapters/BoardsAdapter.java | 5447e33eeb7eb92b6f801f4333024ffbe0daa2c9 | []
| no_license | DakshaNagre/Stint | https://github.com/DakshaNagre/Stint | db00f76cf765e877fed9a1bd9a00b47677fe1393 | 395a0eacace2974e3946352c7bea6c6721627e68 | refs/heads/master | 2020-12-03T09:42:30.832000 | 2020-12-01T22:53:17 | 2020-12-01T22:53:17 | 231,269,522 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.oosd.project.taskmanagementapp.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.oosd.project.taskmanagementapp.R;
import com.oosd.project.taskmanagementapp.Activities.TasksBenchActivity;
import com.oosd.project.taskmanagementapp.models.Board;
import com.oosd.project.taskmanagementapp.util.Constants;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// Adapter to create cards to render in boards screen
public class BoardsAdapter extends BaseAdapter{
private Context context;
private JSONArray boards;
private static LayoutInflater inflater=null;
public BoardsAdapter(Context dashboard, JSONArray boards) {
this.context = dashboard;
this.boards = boards;
this.inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return boards.length();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
Board boardObject = new Board();
final View rowView = this.inflater.inflate(R.layout.board_card, null);
try {
JSONObject board = this.boards.getJSONObject(position);
// Setting the name on the board card
boardObject.setName((TextView) rowView.findViewById(R.id.boardName));
boardObject.getName().setText(board.getString("name"));
boardObject.getName().setBackgroundColor(Color.parseColor("#fefefe"));
// Setting the background color of the card
String color = board.getString("color");
if(color.equals("null")){
rowView.setBackgroundColor(Color.parseColor("#f2f2f2"));
}else{
rowView.setBackgroundColor(Color.parseColor(color));
}
if(board.getBoolean("image")){
boardObject.setImage((ImageView) rowView.findViewById(R.id.boardBackgroundImage));
Picasso.get()
.load(Constants.S3_IMAGE_BUCKET + "/" + board.getString("board_id"))
.fit().centerCrop()
.into(boardObject.getImage());
}
}catch (JSONException e){
Log.d("JSON Exception", "Exception occured while reading boards array");
}
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent intent = new Intent(context, TasksBenchActivity.class);
intent.putExtra("boardObject", boards.getJSONObject(position).toString());
context.startActivity(intent);
}catch (JSONException exception){
Log.d("JSONException", "Exception has occurred while tapping on board");
}
}
});
return rowView;
}
}
| UTF-8 | Java | 3,447 | java | BoardsAdapter.java | Java | []
| null | []
| package com.oosd.project.taskmanagementapp.adapters;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.oosd.project.taskmanagementapp.R;
import com.oosd.project.taskmanagementapp.Activities.TasksBenchActivity;
import com.oosd.project.taskmanagementapp.models.Board;
import com.oosd.project.taskmanagementapp.util.Constants;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// Adapter to create cards to render in boards screen
public class BoardsAdapter extends BaseAdapter{
private Context context;
private JSONArray boards;
private static LayoutInflater inflater=null;
public BoardsAdapter(Context dashboard, JSONArray boards) {
this.context = dashboard;
this.boards = boards;
this.inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return boards.length();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
Board boardObject = new Board();
final View rowView = this.inflater.inflate(R.layout.board_card, null);
try {
JSONObject board = this.boards.getJSONObject(position);
// Setting the name on the board card
boardObject.setName((TextView) rowView.findViewById(R.id.boardName));
boardObject.getName().setText(board.getString("name"));
boardObject.getName().setBackgroundColor(Color.parseColor("#fefefe"));
// Setting the background color of the card
String color = board.getString("color");
if(color.equals("null")){
rowView.setBackgroundColor(Color.parseColor("#f2f2f2"));
}else{
rowView.setBackgroundColor(Color.parseColor(color));
}
if(board.getBoolean("image")){
boardObject.setImage((ImageView) rowView.findViewById(R.id.boardBackgroundImage));
Picasso.get()
.load(Constants.S3_IMAGE_BUCKET + "/" + board.getString("board_id"))
.fit().centerCrop()
.into(boardObject.getImage());
}
}catch (JSONException e){
Log.d("JSON Exception", "Exception occured while reading boards array");
}
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent intent = new Intent(context, TasksBenchActivity.class);
intent.putExtra("boardObject", boards.getJSONObject(position).toString());
context.startActivity(intent);
}catch (JSONException exception){
Log.d("JSONException", "Exception has occurred while tapping on board");
}
}
});
return rowView;
}
}
| 3,447 | 0.644038 | 0.642878 | 102 | 32.784313 | 27.657438 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 4 |
a30596b2c7d0c6c16934f1c1e06d4ba9f81b9b56 | 27,625,229,686,972 | 77c1deb1edc53a4932880daed29e4a59eb47a591 | /wadi/wadi-core/src/main/java/org/codehaus/wadi/core/contextualiser/Relocater.java | c3ddbbff279071c9eb5d1e84a974357dab45146f | []
| no_license | codehaus/wadi | https://github.com/codehaus/wadi | c3cd36d75ddbd684383412c611591c8b2d1e2f3a | 05479be4cfde94cbecab59f58ca8235bdd97a75c | refs/heads/master | 2023-07-20T00:34:33.892000 | 2009-11-01T07:46:21 | 2009-11-01T07:46:21 | 36,338,824 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
* Copyright 2003-2005 Core Developers Network Ltd.
*
* 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.codehaus.wadi.core.contextualiser;
import org.codehaus.wadi.core.motable.Immoter;
/**
* Abstracts out a strategy for either request or state relocation. This is necessary to
* ensure that a request is processed in the same node as its state.
*
* @author <a href="mailto:jules@coredevelopers.net">Jules Gosnell</a>
* @version $Revision$
*/
public interface Relocater {
/**
* Either relocate the request to the session by proxying/redirection, or the session to the request, by migration...
* @param invocation
* @param id
* @param immoter
* @param b
* @return - whether, or not, the request was contextualised
*/
boolean relocate(Invocation invocation, Object id, Immoter immoter, boolean shuttingDown) throws InvocationException;
}
| UTF-8 | Java | 1,408 | java | Relocater.java | Java | [
{
"context": " node as its state.\n *\n * @author <a href=\"mailto:jules@coredevelopers.net\">Jules Gosnell</a>\n * @version $Revision$\n */\npub",
"end": 942,
"score": 0.9999270439147949,
"start": 918,
"tag": "EMAIL",
"value": "jules@coredevelopers.net"
},
{
"context": "@author <a href=\"mailto:jules@coredevelopers.net\">Jules Gosnell</a>\n * @version $Revision$\n */\npublic interface R",
"end": 957,
"score": 0.999861478805542,
"start": 944,
"tag": "NAME",
"value": "Jules Gosnell"
}
]
| null | []
| /**
*
* Copyright 2003-2005 Core Developers Network Ltd.
*
* 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.codehaus.wadi.core.contextualiser;
import org.codehaus.wadi.core.motable.Immoter;
/**
* Abstracts out a strategy for either request or state relocation. This is necessary to
* ensure that a request is processed in the same node as its state.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Revision$
*/
public interface Relocater {
/**
* Either relocate the request to the session by proxying/redirection, or the session to the request, by migration...
* @param invocation
* @param id
* @param immoter
* @param b
* @return - whether, or not, the request was contextualised
*/
boolean relocate(Invocation invocation, Object id, Immoter immoter, boolean shuttingDown) throws InvocationException;
}
| 1,384 | 0.730114 | 0.721591 | 39 | 35.102566 | 34.380074 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 4 |
a34e61493070588752fb7a802f63ffa032d96ef8 | 27,754,078,674,268 | a968f1fed111ef1f244c7835e177c978808f9b56 | /src/com/spillhuset/Commands/Homes/HomesCommand.java | 23d0b9e097dfe368c2b4ab2cc09c84402e3fc222 | []
| no_license | HeLP-Online/OddJob | https://github.com/HeLP-Online/OddJob | 5c765dc2e3ab0c441cbf6e003bcdb53e8429445e | b4fa406913a0197ace68bf46815bb0fa57515371 | refs/heads/master | 2023-09-05T08:27:56.454000 | 2021-11-12T20:55:39 | 2021-11-12T20:55:39 | 194,704,729 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.spillhuset.Commands.Homes;
import com.spillhuset.OddJob;
import com.spillhuset.Utils.Enum.Plugin;
import com.spillhuset.Utils.SubCommand;
import com.spillhuset.Utils.SubCommandInterface;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class HomesCommand extends SubCommandInterface implements CommandExecutor, TabCompleter {
private final ArrayList<SubCommand> subCommands = new ArrayList<>();
public HomesCommand() {
subCommands.add(new HomeSetCommand());
subCommands.add(new HomeDelCommand());
subCommands.add(new HomeListCommand());
}
@Override
public boolean denyConsole() {
return true;
}
@Override
public boolean onlyConsole() {
return false;
}
@Override
public boolean denyOp() {
return false;
}
@Override
public boolean onlyOp() {
return false;
}
@Override
public Plugin getPlugin() {
return Plugin.home;
}
@Override
public String getPermission() {
return "homes";
}
@Override
public boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) {
StringBuilder nameBuilder = new StringBuilder();
for (SubCommand subCommand : subCommands) {
String name = subCommand.getName();
if (args.length >= 1 && name.equalsIgnoreCase(args[0]) && can(sender, false)) {
subCommand.perform(sender, args);
return true;
}
if (can(sender, false)) {
nameBuilder.append(name).append(",");
}
}
nameBuilder.deleteCharAt(nameBuilder.lastIndexOf(","));
if (!(sender instanceof Player)) {
OddJob.getInstance().getMessageManager().sendSyntax(getPlugin(), nameBuilder.toString(), sender);
return true;
}
if (args.length == 0) {
UUID target = ((Player) sender).getUniqueId();
List<String> test = OddJob.getInstance().getHomesManager().getList(target);
if (test == null || test.isEmpty()) {
OddJob.getInstance().getMessageManager().homesNotSet(sender);
return true;
}
OddJob.getInstance().getMessageManager().homesCount(test, sender.getName(), OddJob.getInstance().getHomesManager().getMax(target), sender, true);
return true;
}
String name = "home";
UUID target;
// homes <home>
// homes <player> <home>
// Searching for a named home
if (args.length == 1) {
name = args[0];
Player player = (Player) sender;
target = player.getUniqueId();
Location location = OddJob.getInstance().getHomesManager().get(target, name);
if (location == null) {
OddJob.getInstance().getMessageManager().errorHome(name, player);
return true;
}
OddJob.getInstance().getHomesManager().teleport(player, target, name);
return true;
}
// Searching for other players homes
if (args.length == 2 && sender.hasPermission("homes.others")) {
name = args[1];
// Check Target Player
target = OddJob.getInstance().getPlayerManager().getUUID(args[0]);
if (target == null) {
OddJob.getInstance().getMessageManager().errorPlayer(getPlugin(), args[0], sender);
return true;
}
// Check Home Location
Location location = OddJob.getInstance().getHomesManager().get(target, name);
if (location == null) {
OddJob.getInstance().getMessageManager().errorHome(name, sender);
return true;
}
OddJob.getInstance().getHomesManager().teleport((Player) sender, target, name);
return true;
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
List<String> list = new ArrayList<>();
// Listing SubCommands
if (args.length >= 1) {
for (SubCommand subCommand : subCommands) {
if (subCommand.getName().equalsIgnoreCase(args[0]) && args.length > 1) {
return subCommand.getTab(sender, args);
} else if (args[0].isEmpty() || subCommand.getName().toLowerCase().startsWith(args[0].toLowerCase())) {
list.add(subCommand.getName());
}
}
}
// homes <home>
// homes <player> <home>
if (sender instanceof Player player) {
if (args.length == 1) {
// Listing own homes
if (OddJob.getInstance().getHomesManager().getList(player.getUniqueId()) != null) {
for (String name : OddJob.getInstance().getHomesManager().getList(player.getUniqueId())) {
if (args[0].isEmpty() || name.toLowerCase().startsWith(args[0].toLowerCase())) {
list.add(name);
}
}
}
// Listing other players
if (can(sender, true)) {
for (String name : OddJob.getInstance().getPlayerManager().getNames()) {
if (args[0].isEmpty() || name.toLowerCase().startsWith(args[0].toLowerCase())) {
list.add(name);
}
}
}
} else if (args.length == 2 && can(sender, true)) {
UUID target = OddJob.getInstance().getPlayerManager().getUUID(args[0]);
if (target != null) {
if (OddJob.getInstance().getHomesManager().getList(target) != null) {
for (String name : OddJob.getInstance().getHomesManager().getList(target)) {
if (args[1].isEmpty() || name.toLowerCase().startsWith(args[1].toLowerCase())) {
list.add(name);
}
}
}
}
}
}
return list;
}
}
| UTF-8 | Java | 6,625 | java | HomesCommand.java | Java | []
| null | []
| package com.spillhuset.Commands.Homes;
import com.spillhuset.OddJob;
import com.spillhuset.Utils.Enum.Plugin;
import com.spillhuset.Utils.SubCommand;
import com.spillhuset.Utils.SubCommandInterface;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class HomesCommand extends SubCommandInterface implements CommandExecutor, TabCompleter {
private final ArrayList<SubCommand> subCommands = new ArrayList<>();
public HomesCommand() {
subCommands.add(new HomeSetCommand());
subCommands.add(new HomeDelCommand());
subCommands.add(new HomeListCommand());
}
@Override
public boolean denyConsole() {
return true;
}
@Override
public boolean onlyConsole() {
return false;
}
@Override
public boolean denyOp() {
return false;
}
@Override
public boolean onlyOp() {
return false;
}
@Override
public Plugin getPlugin() {
return Plugin.home;
}
@Override
public String getPermission() {
return "homes";
}
@Override
public boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) {
StringBuilder nameBuilder = new StringBuilder();
for (SubCommand subCommand : subCommands) {
String name = subCommand.getName();
if (args.length >= 1 && name.equalsIgnoreCase(args[0]) && can(sender, false)) {
subCommand.perform(sender, args);
return true;
}
if (can(sender, false)) {
nameBuilder.append(name).append(",");
}
}
nameBuilder.deleteCharAt(nameBuilder.lastIndexOf(","));
if (!(sender instanceof Player)) {
OddJob.getInstance().getMessageManager().sendSyntax(getPlugin(), nameBuilder.toString(), sender);
return true;
}
if (args.length == 0) {
UUID target = ((Player) sender).getUniqueId();
List<String> test = OddJob.getInstance().getHomesManager().getList(target);
if (test == null || test.isEmpty()) {
OddJob.getInstance().getMessageManager().homesNotSet(sender);
return true;
}
OddJob.getInstance().getMessageManager().homesCount(test, sender.getName(), OddJob.getInstance().getHomesManager().getMax(target), sender, true);
return true;
}
String name = "home";
UUID target;
// homes <home>
// homes <player> <home>
// Searching for a named home
if (args.length == 1) {
name = args[0];
Player player = (Player) sender;
target = player.getUniqueId();
Location location = OddJob.getInstance().getHomesManager().get(target, name);
if (location == null) {
OddJob.getInstance().getMessageManager().errorHome(name, player);
return true;
}
OddJob.getInstance().getHomesManager().teleport(player, target, name);
return true;
}
// Searching for other players homes
if (args.length == 2 && sender.hasPermission("homes.others")) {
name = args[1];
// Check Target Player
target = OddJob.getInstance().getPlayerManager().getUUID(args[0]);
if (target == null) {
OddJob.getInstance().getMessageManager().errorPlayer(getPlugin(), args[0], sender);
return true;
}
// Check Home Location
Location location = OddJob.getInstance().getHomesManager().get(target, name);
if (location == null) {
OddJob.getInstance().getMessageManager().errorHome(name, sender);
return true;
}
OddJob.getInstance().getHomesManager().teleport((Player) sender, target, name);
return true;
}
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
List<String> list = new ArrayList<>();
// Listing SubCommands
if (args.length >= 1) {
for (SubCommand subCommand : subCommands) {
if (subCommand.getName().equalsIgnoreCase(args[0]) && args.length > 1) {
return subCommand.getTab(sender, args);
} else if (args[0].isEmpty() || subCommand.getName().toLowerCase().startsWith(args[0].toLowerCase())) {
list.add(subCommand.getName());
}
}
}
// homes <home>
// homes <player> <home>
if (sender instanceof Player player) {
if (args.length == 1) {
// Listing own homes
if (OddJob.getInstance().getHomesManager().getList(player.getUniqueId()) != null) {
for (String name : OddJob.getInstance().getHomesManager().getList(player.getUniqueId())) {
if (args[0].isEmpty() || name.toLowerCase().startsWith(args[0].toLowerCase())) {
list.add(name);
}
}
}
// Listing other players
if (can(sender, true)) {
for (String name : OddJob.getInstance().getPlayerManager().getNames()) {
if (args[0].isEmpty() || name.toLowerCase().startsWith(args[0].toLowerCase())) {
list.add(name);
}
}
}
} else if (args.length == 2 && can(sender, true)) {
UUID target = OddJob.getInstance().getPlayerManager().getUUID(args[0]);
if (target != null) {
if (OddJob.getInstance().getHomesManager().getList(target) != null) {
for (String name : OddJob.getInstance().getHomesManager().getList(target)) {
if (args[1].isEmpty() || name.toLowerCase().startsWith(args[1].toLowerCase())) {
list.add(name);
}
}
}
}
}
}
return list;
}
}
| 6,625 | 0.550792 | 0.547321 | 184 | 35.005436 | 31.419237 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586957 | false | false | 4 |
c21d39143b00411e3e7e5fc4c5875b9639a609ae | 16,956,530,931,614 | 63d7fa65f1c3835cacc35020a259cfd7565da16e | /src/main/java/com/Hopper/RedeHopper/domain/service/UsuarioService.java | 40c0b8fb9b53268682cb20b02e72d92a26839699 | []
| no_license | JeanCarlos2017/RedeSocialGraceHopper | https://github.com/JeanCarlos2017/RedeSocialGraceHopper | 0fa5a2d33fe6eb084a3691dbd0d10d9d5c4fa925 | 460b724ea17fa5c0d5a68d971fc1fb463f887bc2 | refs/heads/master | 2023-04-16T23:00:48.841000 | 2021-04-10T23:01:13 | 2021-04-10T23:01:13 | 340,437,613 | 2 | 19 | null | false | 2021-04-10T23:01:14 | 2021-02-19T17:11:33 | 2021-04-10T23:00:37 | 2021-04-10T23:01:13 | 40,891 | 1 | 5 | 0 | Java | false | false | package com.Hopper.RedeHopper.domain.service;
import java.nio.charset.Charset;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.Hopper.RedeHopper.domain.model.UsuarioEntidade;
import com.Hopper.RedeHopper.domain.model.UsuarioLogin;
import com.Hopper.RedeHopper.domain.repository.UsuarioRepository;
@Service
public class UsuarioService {
//validação de email
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN, Pattern.CASE_INSENSITIVE);
@Autowired
private UsuarioRepository usuarioRepository;
private boolean validaEmail(String email) {
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
private boolean validaNome(String nome) {
//verifica se já existe um usuário com esse nome
Optional<UsuarioEntidade> encontrou= usuarioRepository.findByNome(nome);
if(encontrou.isEmpty()) return true;
else return false;
}
public UsuarioEntidade cadastraUsuario(UsuarioEntidade usuario) {
//verifica se o email e nome sao válidos
if(this.validaEmail(usuario.getEmail()) && this.validaNome(usuario.getNome())) {
//criptografa a senha do usuário
BCryptPasswordEncoder encoder= new BCryptPasswordEncoder();
String senhaEncoder= encoder.encode(usuario.getSenha());
usuario.setSenha(senhaEncoder);
//gera um código para o usuário de acordo com o nome escolhido
usuario.setCodigo_usuario();
//por fim salva o usuário
return usuarioRepository.save(usuario);
}else return null;
}
public Optional<UsuarioLogin> login(Optional<UsuarioLogin> userParametro) {
BCryptPasswordEncoder encoder= new BCryptPasswordEncoder();
//busca o usuário no banco de dados pelo nome, como o nome é unico não há conflitos
Optional<UsuarioEntidade> usuario= usuarioRepository.findByNome(userParametro.get().getNome());
if(usuario.isPresent()) {
//verifica se a senha do usuário é igual a senha do banco, faz essa verificação considerando a criptografia
if(encoder.matches(userParametro.get().getSenha(), usuario.get().getSenha())) {
//gero o token do usuário
String auth= userParametro.get().getNome() + ":"+ userParametro.get().getSenha();
byte[] encondeAuth= Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader= "Basic "+new String(encondeAuth);
//colocando as informações de usuário no userParametro - que é o usuário para login
userParametro.get().setToken(authHeader);
userParametro.get().setCodigo_usuario(usuario.get().getCodigo_usuario());
userParametro.get().setUrl_foto(usuario.get().getUrl_foto());
userParametro.get().setEmail(usuario.get().getEmail());
userParametro.get().setId(usuario.get().getId_usuario());
return userParametro;
}else {
return null;
}
}else {
return null;
}
}
public void logout(UsuarioEntidade usuario) {
}
public UsuarioRepository getUsuarioRepository() {
return usuarioRepository;
}
public Optional<UsuarioEntidade> buscaUsuarioPorId(long id){
return this.usuarioRepository.findById(id);
}
}
| UTF-8 | Java | 3,490 | java | UsuarioService.java | Java | []
| null | []
| package com.Hopper.RedeHopper.domain.service;
import java.nio.charset.Charset;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.Hopper.RedeHopper.domain.model.UsuarioEntidade;
import com.Hopper.RedeHopper.domain.model.UsuarioLogin;
import com.Hopper.RedeHopper.domain.repository.UsuarioRepository;
@Service
public class UsuarioService {
//validação de email
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN, Pattern.CASE_INSENSITIVE);
@Autowired
private UsuarioRepository usuarioRepository;
private boolean validaEmail(String email) {
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
private boolean validaNome(String nome) {
//verifica se já existe um usuário com esse nome
Optional<UsuarioEntidade> encontrou= usuarioRepository.findByNome(nome);
if(encontrou.isEmpty()) return true;
else return false;
}
public UsuarioEntidade cadastraUsuario(UsuarioEntidade usuario) {
//verifica se o email e nome sao válidos
if(this.validaEmail(usuario.getEmail()) && this.validaNome(usuario.getNome())) {
//criptografa a senha do usuário
BCryptPasswordEncoder encoder= new BCryptPasswordEncoder();
String senhaEncoder= encoder.encode(usuario.getSenha());
usuario.setSenha(senhaEncoder);
//gera um código para o usuário de acordo com o nome escolhido
usuario.setCodigo_usuario();
//por fim salva o usuário
return usuarioRepository.save(usuario);
}else return null;
}
public Optional<UsuarioLogin> login(Optional<UsuarioLogin> userParametro) {
BCryptPasswordEncoder encoder= new BCryptPasswordEncoder();
//busca o usuário no banco de dados pelo nome, como o nome é unico não há conflitos
Optional<UsuarioEntidade> usuario= usuarioRepository.findByNome(userParametro.get().getNome());
if(usuario.isPresent()) {
//verifica se a senha do usuário é igual a senha do banco, faz essa verificação considerando a criptografia
if(encoder.matches(userParametro.get().getSenha(), usuario.get().getSenha())) {
//gero o token do usuário
String auth= userParametro.get().getNome() + ":"+ userParametro.get().getSenha();
byte[] encondeAuth= Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader= "Basic "+new String(encondeAuth);
//colocando as informações de usuário no userParametro - que é o usuário para login
userParametro.get().setToken(authHeader);
userParametro.get().setCodigo_usuario(usuario.get().getCodigo_usuario());
userParametro.get().setUrl_foto(usuario.get().getUrl_foto());
userParametro.get().setEmail(usuario.get().getEmail());
userParametro.get().setId(usuario.get().getId_usuario());
return userParametro;
}else {
return null;
}
}else {
return null;
}
}
public void logout(UsuarioEntidade usuario) {
}
public UsuarioRepository getUsuarioRepository() {
return usuarioRepository;
}
public Optional<UsuarioEntidade> buscaUsuarioPorId(long id){
return this.usuarioRepository.findById(id);
}
}
| 3,490 | 0.744736 | 0.74041 | 92 | 36.684784 | 29.265623 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.130435 | false | false | 4 |
e464a8622bba4b56ce7080a8b1fab6799a71776d | 16,956,530,932,238 | f4bc1b9dd8729724c4a318cb1ae4dbe2244951b9 | /8th_Trimester/1_Java/awt_1/textValid.java | a583ec11e9a4b9a908e71557d2db09b4641131d1 | []
| no_license | iYashBorse/TYBSc-CS | https://github.com/iYashBorse/TYBSc-CS | ba6e90548e7d84668de3b7817c5cfe04d134d2e4 | 0cc77ee5f64b4b27b7b5cda0b228ca8d315af6ac | refs/heads/master | 2023-04-30T10:39:48.698000 | 2021-05-18T05:20:21 | 2021-05-18T05:20:21 | 283,162,705 | 13 | 9 | null | false | 2020-09-10T09:15:52 | 2020-07-28T09:20:01 | 2020-09-09T10:59:31 | 2020-09-09T10:59:28 | 179 | 3 | 4 | 0 | CSS | false | false | /* Write a program with 2 labels, 2 textfields and a button.
Check whether username is MIT and password is WPU, display
appropriate message.*/
import java.awt.*;
import java.awt.event.*;
class textValid extends Frame implements ActionListener{
Label l1,l2,l3;
Button b1;
TextField tf1, tf2;
public textValid(){
setLayout(new FlowLayout());
l1 = new Label("Username: ");
tf1 = new TextField(20);
l2 = new Label("Password: ");
tf2 = new TextField(20);
b1= new Button("Submit!");
l3 = new Label(" ");
b1.addActionListener(this);
add(l1); add(tf1);
add(l2); add(tf2);
add(b1); add(l3);
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==b1){
if(tf1.getText().equals("MIT") && tf2.getText().equals("WPU")){
l3.setText("Valid credentials.");
}
else{
l3.setText("\nInvalid credentials!");
}
}
}
public static void main(String ar[]){
new textValid();
}
}
| UTF-8 | Java | 1,033 | java | textValid.java | Java | [
{
"context": "textfields and a button.\nCheck whether username is MIT and password is WPU, display\nappropriate message.",
"end": 90,
"score": 0.9949076771736145,
"start": 87,
"tag": "USERNAME",
"value": "MIT"
},
{
"context": "ton.\nCheck whether username is MIT and password is WPU, display\nappropriate message.*/\n\nimport java.awt.",
"end": 110,
"score": 0.9989051818847656,
"start": 107,
"tag": "PASSWORD",
"value": "WPU"
}
]
| null | []
| /* Write a program with 2 labels, 2 textfields and a button.
Check whether username is MIT and password is WPU, display
appropriate message.*/
import java.awt.*;
import java.awt.event.*;
class textValid extends Frame implements ActionListener{
Label l1,l2,l3;
Button b1;
TextField tf1, tf2;
public textValid(){
setLayout(new FlowLayout());
l1 = new Label("Username: ");
tf1 = new TextField(20);
l2 = new Label("Password: ");
tf2 = new TextField(20);
b1= new Button("Submit!");
l3 = new Label(" ");
b1.addActionListener(this);
add(l1); add(tf1);
add(l2); add(tf2);
add(b1); add(l3);
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==b1){
if(tf1.getText().equals("MIT") && tf2.getText().equals("WPU")){
l3.setText("Valid credentials.");
}
else{
l3.setText("\nInvalid credentials!");
}
}
}
public static void main(String ar[]){
new textValid();
}
}
| 1,033 | 0.61181 | 0.57696 | 41 | 24.195122 | 17.377052 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.731707 | false | false | 4 |
0b4e5506b4ec5a3412d739ab2953f2692f99c612 | 26,860,725,477,032 | ebe9ab04d6fe6312b002c6899c5312ccbfc5dd34 | /HCF.java | 2bea2869473a7e8ae81a0a359fe681821696be0e | []
| no_license | jenithavalarmathi/jenith | https://github.com/jenithavalarmathi/jenith | 9d32a0ccdf94c5a60d7c768ab8f134cc0ffb2af2 | 4c6e10c8b256e1f8189c38f850c6afd9379c2799 | refs/heads/master | 2021-01-01T17:46:15.698000 | 2017-07-24T07:02:23 | 2017-07-24T07:02:23 | 98,154,625 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class HCF
{
static int gcd(int m, int n)
{
int k=0, i, j;
i = (m > n) ? m : n;
j = (m < n) ? m : n;
k = j;
while(i % j != 0)
{
k = i % j;
i = j;
j = k;
}
return k;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the two numbers: ");
int m = sc.nextInt();
int n = sc.nextInt();
System.out.println("The GCD of two numbers is: " + gcd(m, n));
sc.close();
}
}
| UTF-8 | Java | 625 | java | HCF.java | Java | []
| null | []
| import java.util.*;
public class HCF
{
static int gcd(int m, int n)
{
int k=0, i, j;
i = (m > n) ? m : n;
j = (m < n) ? m : n;
k = j;
while(i % j != 0)
{
k = i % j;
i = j;
j = k;
}
return k;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the two numbers: ");
int m = sc.nextInt();
int n = sc.nextInt();
System.out.println("The GCD of two numbers is: " + gcd(m, n));
sc.close();
}
}
| 625 | 0.4064 | 0.4032 | 29 | 20.551723 | 16.464354 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 4 |
4d3d7b899fabc6386fd409e34926a13a3d98fe1a | 8,117,488,202,395 | 8f1352b12c689ccb709301fbf15637c2244a5eaf | /src/application/system/Invoice_Generator.java | 99cd0551f4b6159fbe2f1dfaf32165e12bb2a4dc | [
"MIT"
]
| permissive | Terkea/booking-system | https://github.com/Terkea/booking-system | 38bf3722ac1fa5877bbcc0fdf7f42812f2b7b99d | 4a8f362a1fe1476cec967db801eaf9244060081e | refs/heads/master | 2020-04-28T18:05:32.792000 | 2019-05-24T16:43:10 | 2019-05-24T16:43:10 | 175,467,421 | 8 | 2 | MIT | false | 2019-05-24T16:43:12 | 2019-03-13T17:23:15 | 2019-05-24T13:37:25 | 2019-05-24T16:43:11 | 76,230 | 5 | 0 | 1 | Java | false | false | package application.system;
import application.model.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.SQLException;
public class Invoice_Generator {
public static String generateInvoiceByBookingId(int bookingID){
Booking currentBooking = null;
User currentUser = null;
Payment currentPayment = null;
Event currentEvent = null;
try {
currentBooking = BookingDAO.getBookingBYID(bookingID);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
currentUser = UserDAO.searchUsersByID(currentBooking.getUser_id());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
currentPayment = PaymentDAO.getPaymentByID(currentBooking.getPayment_id());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
currentEvent = EventDAO.getEventByID(currentBooking.getEvent_id());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String fileName = currentBooking.getId() + "" + currentBooking.getEvent_id() + "" + currentBooking.getPayment_id();
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(new File(fileName + ".pdf")));
document.open();
Font title = new Font();
title.setSize(25);
Paragraph p = new Paragraph("" , title);
if (currentPayment.isStatus() == false){
if (UserDAO.checkCorporateOrganization(currentUser.getId())){
p.add("Invoice no. " + fileName);
}else{
p.add("Receipt no. " + fileName);
}
}else{
p.add("Receipt no. " + fileName);
}
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
document.add(new Paragraph("\n"));
Font info = new Font();
info.setSize(10);
Paragraph p2 = new Paragraph("Vikings" +
"\n" +
"111 Hight Street, \n" +
"London, SW7 2NX, \n" +
"England \n \n" +
"0800 845 4647 \n" +
"www.vikings.com, \n" +
"info@vikings.com \n", info);
p2.setAlignment(Element.ALIGN_LEFT);
document.add(p2);
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Paragraph issued = new Paragraph("Issued: " + (dateFormat.format(date)) + " \n \n", info);
issued.setAlignment(Element.ALIGN_LEFT);
document.add(issued);
Font bold = new Font();
bold.setStyle(Font.BOLD);
Paragraph p3 = new Paragraph("To: " , bold);
document.add(p3);
p3.setAlignment(Element.ALIGN_BOTTOM);
Paragraph p4 = new Paragraph(currentUser.getTitle() + " " + currentUser.getFirst_name() + " " + currentUser.getLast_name() + "\n" +
currentUser.getAddress_line() +", \n" +
currentUser.getAddress_line2() + " \n" +
currentUser.getTown() + " " + currentUser.getCounty() + " \n" +
currentUser.getPostcode().toUpperCase(), info);
document.add(p4);
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
PdfPTable table = new PdfPTable(new float[]{3,3,3,3});
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setFixedHeight(50);
table.setTotalWidth(PageSize.A4.getWidth());
table.setWidthPercentage(100);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell("Event name");
table.addCell("Tickets bought");
table.addCell("Ticket price");
table.addCell("Transaction date and time");
table.setHeaderRows(1);
PdfPCell[] cells = table.getRow(0).getCells();
for (int i = 0; i<cells.length;i++){
cells[i].setBackgroundColor(BaseColor.GRAY);
}
table.addCell(currentEvent.getEvent_type() + " " + currentEvent.getName());
table.addCell(currentBooking.getNumber_of_tickets() + "");
table.addCell(currentEvent.getTicket_price() + " GBP");
table.addCell(currentPayment.getDate_created());
document.add(table);
document.add(new Paragraph("\n"));
double ammount = currentBooking.getNumber_of_tickets() * currentEvent.getTicket_price();
double discount = 20.0/100.0;
double totalAmmount = ammount-(ammount*discount);
Paragraph p5 = new Paragraph("Sub total: " + ammount + " GBP \n");
if (currentPayment.isDiscounted() == true){
p5.add("Discounted: 20%");
}else{
p5.add("Discounted: 0%");
}
p5.setAlignment(Element.ALIGN_RIGHT);
document.add(p5);
document.add(new Paragraph("\n"));
Font total = new Font();
total.setStyle(Font.BOLD);
Paragraph p6 = new Paragraph();
if (currentPayment.isDiscounted() == true){
p6.add("TOTAL AMOUNT: " + totalAmmount + " GBP \n");
}else{
p6.add("TOTAL AMOUNT: " + ammount + " GBP \n");
}
p6.setAlignment(Element.ALIGN_RIGHT);
document.add(p6);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
}
| UTF-8 | Java | 6,488 | java | Invoice_Generator.java | Java | [
{
"context": "ze(10);\n Paragraph p2 = new Paragraph(\"Vikings\" +\n \"\\n\" +\n ",
"end": 2570,
"score": 0.9223044514656067,
"start": 2563,
"tag": "NAME",
"value": "Vikings"
},
{
"context": " \"www.vikings.com, \\n\" +\n \"info@vikings.com \\n\", info);\n p2.setAlignment(Element.A",
"end": 2850,
"score": 0.9999094605445862,
"start": 2834,
"tag": "EMAIL",
"value": "info@vikings.com"
}
]
| null | []
| package application.system;
import application.model.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.SQLException;
public class Invoice_Generator {
public static String generateInvoiceByBookingId(int bookingID){
Booking currentBooking = null;
User currentUser = null;
Payment currentPayment = null;
Event currentEvent = null;
try {
currentBooking = BookingDAO.getBookingBYID(bookingID);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
currentUser = UserDAO.searchUsersByID(currentBooking.getUser_id());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
currentPayment = PaymentDAO.getPaymentByID(currentBooking.getPayment_id());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
currentEvent = EventDAO.getEventByID(currentBooking.getEvent_id());
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String fileName = currentBooking.getId() + "" + currentBooking.getEvent_id() + "" + currentBooking.getPayment_id();
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(new File(fileName + ".pdf")));
document.open();
Font title = new Font();
title.setSize(25);
Paragraph p = new Paragraph("" , title);
if (currentPayment.isStatus() == false){
if (UserDAO.checkCorporateOrganization(currentUser.getId())){
p.add("Invoice no. " + fileName);
}else{
p.add("Receipt no. " + fileName);
}
}else{
p.add("Receipt no. " + fileName);
}
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
document.add(new Paragraph("\n"));
Font info = new Font();
info.setSize(10);
Paragraph p2 = new Paragraph("Vikings" +
"\n" +
"111 Hight Street, \n" +
"London, SW7 2NX, \n" +
"England \n \n" +
"0800 845 4647 \n" +
"www.vikings.com, \n" +
"<EMAIL> \n", info);
p2.setAlignment(Element.ALIGN_LEFT);
document.add(p2);
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Paragraph issued = new Paragraph("Issued: " + (dateFormat.format(date)) + " \n \n", info);
issued.setAlignment(Element.ALIGN_LEFT);
document.add(issued);
Font bold = new Font();
bold.setStyle(Font.BOLD);
Paragraph p3 = new Paragraph("To: " , bold);
document.add(p3);
p3.setAlignment(Element.ALIGN_BOTTOM);
Paragraph p4 = new Paragraph(currentUser.getTitle() + " " + currentUser.getFirst_name() + " " + currentUser.getLast_name() + "\n" +
currentUser.getAddress_line() +", \n" +
currentUser.getAddress_line2() + " \n" +
currentUser.getTown() + " " + currentUser.getCounty() + " \n" +
currentUser.getPostcode().toUpperCase(), info);
document.add(p4);
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
PdfPTable table = new PdfPTable(new float[]{3,3,3,3});
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setFixedHeight(50);
table.setTotalWidth(PageSize.A4.getWidth());
table.setWidthPercentage(100);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell("Event name");
table.addCell("Tickets bought");
table.addCell("Ticket price");
table.addCell("Transaction date and time");
table.setHeaderRows(1);
PdfPCell[] cells = table.getRow(0).getCells();
for (int i = 0; i<cells.length;i++){
cells[i].setBackgroundColor(BaseColor.GRAY);
}
table.addCell(currentEvent.getEvent_type() + " " + currentEvent.getName());
table.addCell(currentBooking.getNumber_of_tickets() + "");
table.addCell(currentEvent.getTicket_price() + " GBP");
table.addCell(currentPayment.getDate_created());
document.add(table);
document.add(new Paragraph("\n"));
double ammount = currentBooking.getNumber_of_tickets() * currentEvent.getTicket_price();
double discount = 20.0/100.0;
double totalAmmount = ammount-(ammount*discount);
Paragraph p5 = new Paragraph("Sub total: " + ammount + " GBP \n");
if (currentPayment.isDiscounted() == true){
p5.add("Discounted: 20%");
}else{
p5.add("Discounted: 0%");
}
p5.setAlignment(Element.ALIGN_RIGHT);
document.add(p5);
document.add(new Paragraph("\n"));
Font total = new Font();
total.setStyle(Font.BOLD);
Paragraph p6 = new Paragraph();
if (currentPayment.isDiscounted() == true){
p6.add("TOTAL AMOUNT: " + totalAmmount + " GBP \n");
}else{
p6.add("TOTAL AMOUNT: " + ammount + " GBP \n");
}
p6.setAlignment(Element.ALIGN_RIGHT);
document.add(p6);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
}
| 6,479 | 0.537916 | 0.52836 | 170 | 37.164707 | 25.967104 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.676471 | false | false | 4 |
21d5117965808cf689cc96a553871d7a6689b752 | 6,210,522,743,408 | 8fd929827a949f6ea5a7db2d3886d593e17d653c | /Feet_to_Meter.java | bf9f75615cdc9563bdf749ddd419b79ab7643362 | []
| no_license | aminspicse/ImportentInterviewProgramm | https://github.com/aminspicse/ImportentInterviewProgramm | e71e6997781a3f5cd667aefde33d092ae572d0d8 | b04902115cbc8ca1a391f622a57c43ccb32e00c4 | refs/heads/master | 2022-12-30T16:28:42.899000 | 2020-10-21T16:33:14 | 2020-10-21T16:33:14 | 299,820,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package programm;
import java.util.Scanner;
/**
* @author MD. AL AMIN
*
*/
public class Feet_to_Meter {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Feet: ");
double feet = sc.nextDouble();
double meter = feet / 3.28;
System.out.println("Meter = "+meter);
}
}
| UTF-8 | Java | 375 | java | Feet_to_Meter.java | Java | [
{
"context": "ogramm;\n\nimport java.util.Scanner;\n\n/**\n * @author MD. AL AMIN\n *\n */\npublic class Feet_to_Meter {\n\n\t/**\n\t * @pa",
"end": 84,
"score": 0.999613881111145,
"start": 73,
"tag": "NAME",
"value": "MD. AL AMIN"
}
]
| null | []
| /**
*
*/
package programm;
import java.util.Scanner;
/**
* @author <NAME>
*
*/
public class Feet_to_Meter {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Feet: ");
double feet = sc.nextDouble();
double meter = feet / 3.28;
System.out.println("Meter = "+meter);
}
}
| 370 | 0.605333 | 0.597333 | 26 | 13.423077 | 14.60288 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 4 |
f292f57d415e90d6d723d8bef773324f5a9e35ad | 11,905,649,387,289 | a850e54f5d2d7cade1d9a7529a79ab6729514804 | /src/main/java/com/smanzana/nostrummagica/blocks/tiles/NostrumObeliskEntity.java | 164952f13b9b2d6a7ac04c9a9fa404a2f4c37f31 | []
| no_license | Dove-Bren/NostrumMagica | https://github.com/Dove-Bren/NostrumMagica | ae9cbe0b43335027419bfc46d1d8569fcced5a4b | a44ac16145c876bde1fa4f3d7a6da3088b909dce | refs/heads/master | 2023-01-21T12:39:10.394000 | 2023-01-14T18:40:40 | 2023-01-14T18:40:40 | 150,891,432 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smanzana.nostrummagica.blocks.tiles;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Nullable;
import com.smanzana.nostrumaetheria.api.blocks.AetherTickingTileEntity;
import com.smanzana.nostrummagica.NostrumMagica;
import com.smanzana.nostrummagica.blocks.NostrumObelisk;
import com.smanzana.nostrummagica.blocks.ObeliskPortal;
import com.smanzana.nostrummagica.world.NostrumChunkLoader;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.common.ForgeChunkManager.Type;
import net.minecraftforge.common.util.Constants.NBT;
public class NostrumObeliskEntity extends AetherTickingTileEntity {
public static class NostrumObeliskTarget {
private BlockPos pos;
private String title;
public NostrumObeliskTarget(BlockPos pos) {
this(pos, toTitle(pos));
}
public NostrumObeliskTarget(BlockPos pos, String title) {
this.pos = pos;
this.title = title;
}
private static String toTitle(BlockPos pos) {
return "(" + pos.getX() + ", " + pos.getY() + ", " + pos.getZ() + ")";
}
public BlockPos getPos() {
return pos;
}
public String getTitle() {
return title;
}
}
private static final String NBT_TICKET_POS = "obelisk_pos";
private static final String NBT_MASTER = "master";
private static final String NBT_TARGETS = "targets";
private static final String NBT_TARGET_X = "x";
private static final String NBT_TARGET_Y = "y";
private static final String NBT_TARGET_Z = "z";
private static final String NBT_TARGET_TITLE = "title";
//private static final String NBT_TARGET_DIMENSION = "dimension";
private static final String NBT_CORNER = "corner";
/**
* If master, destroy in all 4 corners
* If not master, search for master by offset in all corners.
* Destroy ALL masters found, not just the first one.
*/
public static enum Corner {
NE(0),
NW(1),
SW(2),
SE(3);
private int offset;
private Corner(int offset) {
this.offset = offset;
}
public int getOffset() {
return offset;
}
}
private static final float AetherPerBlock = 1f / 2f;
private boolean master;
private List<NostrumObeliskTarget> targets;
private int targetIndex;
private Corner corner;
private int aliveCount;
// Not persisted. Temporary overrides on target. targetOverrideEnds is based off aliveCount.
private BlockPos targetOverride;
private int targetOverrideEnd;
private boolean isDestructing;
public NostrumObeliskEntity() {
super(0, 2000);
master = false;
isDestructing = false;
targets = new LinkedList<>();
targetIndex = 0;
this.compWrapper.configureInOut(true, false);
}
public NostrumObeliskEntity(boolean master) {
this();
this.master = master;
}
public NostrumObeliskEntity(Corner corner) {
this(false);
this.corner = corner;
}
@Override
public void setWorld(World world) {
super.setWorld(world);
this.compWrapper.setAutoFill(!world.isRemote && this.isMaster());
//aetherHandler.setAutoFill(!world.isRemote);
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
nbt = super.writeToNBT(nbt);
NBTTagList list = new NBTTagList();
if (master && targets.size() > 0)
for (NostrumObeliskTarget target : targets) {
if (target == null)
continue;
NBTTagCompound tag = new NBTTagCompound();
tag.setInteger(NBT_TARGET_X, target.pos.getX());
tag.setInteger(NBT_TARGET_Y, target.pos.getY());
tag.setInteger(NBT_TARGET_Z, target.pos.getZ());
tag.setString(NBT_TARGET_TITLE, target.title);
//tag.setInteger(NBT_TARGET_DIMENSION, target.dimension);
list.appendTag(tag);
}
nbt.setTag(NBT_TARGETS, list);
nbt.setBoolean(NBT_MASTER, master);
if (!master && corner != null) {
nbt.setByte(NBT_CORNER, (byte) corner.ordinal());
}
return nbt;
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
if (nbt == null || !nbt.hasKey(NBT_MASTER, NBT.TAG_BYTE))
return;
this.master = nbt.getBoolean(NBT_MASTER);
NBTTagList list = nbt.getTagList(NBT_TARGETS, NBT.TAG_COMPOUND);
if (list != null && list.tagCount() > 0) {
this.targets = new ArrayList<>(list.tagCount());
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound tag = list.getCompoundTagAt(i);
targets.add(new NostrumObeliskTarget(
//tag.getInteger(NBT_TARGET_DIMENSION),
new BlockPos(
tag.getInteger(NBT_TARGET_X),
tag.getInteger(NBT_TARGET_Y),
tag.getInteger(NBT_TARGET_Z)
),
tag.getString(NBT_TARGET_TITLE)));
}
}
if (!master) {
int ord = nbt.getByte(NBT_CORNER);
for (Corner c : Corner.values()) {
if (c.ordinal() == ord)
this.corner = c;
}
}
}
public void destroy() {
if (isDestructing)
return;
isDestructing = true;
if (master) {
// go to all four corners and break all blocks up
int xs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
int zs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
for (int i = 0; i < xs.length; i++)
for (int j = 1; j <= NostrumObelisk.TILE_HEIGHT; j++) { // j starts at one cause the first block is above the base block
BlockPos bp = pos.add(xs[i], j, zs[i]);
IBlockState state = world.getBlockState(bp);
if (state.getBlock() instanceof NostrumObelisk) {
world.destroyBlock(bp, false);
}
}
if (!world.isRemote) {
Ticket ticket = NostrumChunkLoader.instance().pullTicket(genTicketKey());
if (ticket != null) {
ForgeChunkManager.releaseTicket(ticket);
}
}
this.deactivatePortal();
world.destroyBlock(pos, false);
} else {
int xs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
int zs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
for (int i = 0; i < xs.length; i++) {
BlockPos base = pos.add(xs[i], -NostrumObelisk.TILE_OFFSETY, zs[i]);
TileEntity te = world.getTileEntity(base);
if (te != null && te instanceof NostrumObeliskEntity) {
NostrumObeliskEntity entity = (NostrumObeliskEntity) te;
if (entity.master)
entity.destroy();
}
}
}
}
public boolean isMaster() {
return this.master;
}
public void addTarget(BlockPos pos) {
targets.add(new NostrumObeliskTarget(pos));
forceUpdate();
}
public void addTarget(BlockPos pos, String title) {
targets.add(new NostrumObeliskTarget(pos, title));
forceUpdate();
}
public List<NostrumObeliskTarget> getTargets() {
return targets;
}
public boolean canAcceptTarget(BlockPos pos) {
if (pos.equals(this.pos))
return false;
if (!targets.isEmpty())
for (NostrumObeliskTarget targPos : targets) {
if (pos.equals(targPos.pos))
return false;
}
if (!this.world.isRemote) {
IBlockState state = world.getBlockState(pos);
if (state == null || !(state.getBlock() instanceof NostrumObelisk)
|| !NostrumObelisk.blockIsMaster(state))
return false;
}
return true;
}
public void setTargetIndex(int index) {
if (this.targets.size() == 0 || index < 0) {
return;
}
this.targetIndex = Math.min(targets.size() - 1, index);
refreshPortal();
}
public @Nullable BlockPos getCurrentTarget() {
if (targetOverride != null) {
return targetOverride;
}
if (this.targets.size() == 0) {
return null;
}
return targets.get(Math.min(targets.size() - 1, targetIndex)).getPos();
}
public boolean hasOverride() {
return this.targetOverride != null;
}
protected void deactivatePortal() {
// Remove portal above us
world.setBlockToAir(pos.up());
}
protected void activatePortal() {
world.setBlockState(pos.up(), ObeliskPortal.instance().getStateForPlacement(world, pos, EnumFacing.UP, 0f, 0f, 0f, 0, null));
ObeliskPortal.instance().createPaired(world, pos.up());
}
protected void refreshPortal() {
@Nullable BlockPos target;
boolean valid;
if (this.targetOverride != null) {
valid = true;
target = this.targetOverride;
} else {
target = this.getCurrentTarget();
valid = (target != null && IsValidObelisk(world, target));
}
if (valid) {
// Make sure there's a portal
activatePortal();
} else {
deactivatePortal();
}
}
public static boolean IsValidObelisk(World world, BlockPos pos) {
IBlockState state = world.getBlockState(pos);
return !(state == null || !(state.getBlock() instanceof NostrumObelisk)
|| !NostrumObelisk.blockIsMaster(state));
}
public void setOverride(BlockPos override, int durationTicks) {
this.targetOverride = override;
this.targetOverrideEnd = this.aliveCount + durationTicks;
this.refreshPortal();
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
return new SPacketUpdateTileEntity(this.pos, 3, this.getUpdateTag());
}
@Override
public NBTTagCompound getUpdateTag() {
return this.writeToNBT(new NBTTagCompound());
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
super.onDataPacket(net, pkt);
handleUpdateTag(pkt.getNbtCompound());
}
// Registers this TE as a chunk loader. Gets a ticket and forces the chunk.
// Relies on already being placed in the world
public void init() {
if (world.isRemote)
return;
Ticket chunkTicket = ForgeChunkManager.requestTicket(NostrumMagica.instance, world, Type.NORMAL);
chunkTicket.getModData().setTag(NBT_TICKET_POS, NBTUtil.createPosTag(pos));
ForgeChunkManager.forceChunk(chunkTicket, new ChunkPos(pos));
NostrumChunkLoader.instance().addTicket(genTicketKey(), chunkTicket);
}
private String genTicketKey() {
return "nostrum_obelisk_" + pos.getX() + "_" + pos.getY() + "_" + pos.getZ();
}
private void forceUpdate() {
world.notifyBlockUpdate(pos, this.world.getBlockState(pos), this.world.getBlockState(pos), 3);
markDirty();
}
@Override
public void update() {
super.update();
aliveCount++;
if (!world.isRemote && targetOverride != null && aliveCount >= targetOverrideEnd) {
targetOverride = null;
refreshPortal();
}
if (!world.isRemote)
return;
if (corner == null || master)
return;
final long stepInverval = 2;
if (aliveCount % stepInverval != 0)
return;
int step = (int) (aliveCount / stepInverval);
int maxStep = (int) ((20 / stepInverval) * 4); // 4 second period
step = step % maxStep;
float ratio = (float) step / (float) maxStep;
float angle = (float) (ratio * 2f * Math.PI); // radians
angle += ((double) corner.getOffset() + 1.0) * .25 * (2.0 * Math.PI);
float radius = (float) ((1f - ratio) * (NostrumObelisk.TILE_OFFSETH * 1.25));
double x, z, y;
x = Math.cos(angle) * radius;
z = Math.sin(angle) * radius;
y = ratio * (-NostrumObelisk.TILE_OFFSETY);
BlockPos master = getMasterPos();
x += master.getX() + .5;
z += master.getZ() + .5;
y += pos.getY() + .5;
world.spawnParticle(EnumParticleTypes.DRAGON_BREATH, x, y, z, .01, 0, .01, new int[0]);
}
private BlockPos getMasterPos() {
if (this.corner != null)
switch (this.corner) {
case NE:
return pos.add(-NostrumObelisk.TILE_OFFSETH, 1, -NostrumObelisk.TILE_OFFSETH);
case NW:
return pos.add(NostrumObelisk.TILE_OFFSETH, 1, -NostrumObelisk.TILE_OFFSETH);
case SE:
return pos.add(-NostrumObelisk.TILE_OFFSETH, 1, NostrumObelisk.TILE_OFFSETH);
case SW:
return pos.add(NostrumObelisk.TILE_OFFSETH, 1, NostrumObelisk.TILE_OFFSETH);
}
return pos;
};
protected int getAetherCost(BlockPos destination) {
if (this.targetOverride != null && destination == this.targetOverride) {
// No cost for overrides
return 0;
}
double dist = (Math.abs(this.pos.getX() - destination.getX())
+ Math.abs(this.pos.getY() - destination.getY())
+ Math.abs(this.pos.getZ() - destination.getZ()));
//double dist = Math.sqrt(this.pos.distanceSq(destination));
return (int) Math.round(AetherPerBlock * dist);
}
public boolean canAffordTeleport(BlockPos destination) {
return this.compWrapper.check(getAetherCost(destination));
}
/**
* Attempt to pay any secondary fee for teleportation to the provided location.
* This assumes the destination has been checked, etc.
* @param destination
* @return
*/
public boolean deductForTeleport(BlockPos destination) {
return this.compWrapper.checkAndWithdraw(getAetherCost(destination));
}
} | UTF-8 | Java | 13,222 | java | NostrumObeliskEntity.java | Java | [
{
"context": ";\n\t}\n\t\n\tprivate String genTicketKey() {\n\t\treturn \"nostrum_obelisk_\" + pos.getX() + \"_\" + pos.getY() + \"_\" + pos.getZ();\n\t}\n",
"end": 10497,
"score": 0.9457887411117554,
"start": 10474,
"tag": "KEY",
"value": "nostrum_obelisk_\" + pos"
},
{
"context": "enTicketKey() {\n\t\treturn \"nostrum_obelisk_\" + pos.getX() + \"_\" + pos.getY() + \"_\" + pos.getZ();\n\t}\n\t\n\tprivate void",
"end": 10512,
"score": 0.877124011516571,
"start": 10498,
"tag": "KEY",
"value": "getX() + \"_\" +"
},
{
"context": "eturn \"nostrum_obelisk_\" + pos.getX() + \"_\" + pos.getY() + \"_\" + pos.getZ();\n\t}\n\t\n\tprivate void forceUpdate() {\n\t\tworl",
"end": 10535,
"score": 0.7927343845367432,
"start": 10517,
"tag": "KEY",
"value": "getY() + \"_\" + pos"
},
{
"context": "isk_\" + pos.getX() + \"_\" + pos.getY() + \"_\" + pos.getZ();\n\t}\n\t\n\tprivate void forceUpdate() {\n\t\tworld.notify",
"end": 10543,
"score": 0.8101987242698669,
"start": 10536,
"tag": "KEY",
"value": "getZ();"
}
]
| null | []
| package com.smanzana.nostrummagica.blocks.tiles;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Nullable;
import com.smanzana.nostrumaetheria.api.blocks.AetherTickingTileEntity;
import com.smanzana.nostrummagica.NostrumMagica;
import com.smanzana.nostrummagica.blocks.NostrumObelisk;
import com.smanzana.nostrummagica.blocks.ObeliskPortal;
import com.smanzana.nostrummagica.world.NostrumChunkLoader;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.common.ForgeChunkManager.Type;
import net.minecraftforge.common.util.Constants.NBT;
public class NostrumObeliskEntity extends AetherTickingTileEntity {
public static class NostrumObeliskTarget {
private BlockPos pos;
private String title;
public NostrumObeliskTarget(BlockPos pos) {
this(pos, toTitle(pos));
}
public NostrumObeliskTarget(BlockPos pos, String title) {
this.pos = pos;
this.title = title;
}
private static String toTitle(BlockPos pos) {
return "(" + pos.getX() + ", " + pos.getY() + ", " + pos.getZ() + ")";
}
public BlockPos getPos() {
return pos;
}
public String getTitle() {
return title;
}
}
private static final String NBT_TICKET_POS = "obelisk_pos";
private static final String NBT_MASTER = "master";
private static final String NBT_TARGETS = "targets";
private static final String NBT_TARGET_X = "x";
private static final String NBT_TARGET_Y = "y";
private static final String NBT_TARGET_Z = "z";
private static final String NBT_TARGET_TITLE = "title";
//private static final String NBT_TARGET_DIMENSION = "dimension";
private static final String NBT_CORNER = "corner";
/**
* If master, destroy in all 4 corners
* If not master, search for master by offset in all corners.
* Destroy ALL masters found, not just the first one.
*/
public static enum Corner {
NE(0),
NW(1),
SW(2),
SE(3);
private int offset;
private Corner(int offset) {
this.offset = offset;
}
public int getOffset() {
return offset;
}
}
private static final float AetherPerBlock = 1f / 2f;
private boolean master;
private List<NostrumObeliskTarget> targets;
private int targetIndex;
private Corner corner;
private int aliveCount;
// Not persisted. Temporary overrides on target. targetOverrideEnds is based off aliveCount.
private BlockPos targetOverride;
private int targetOverrideEnd;
private boolean isDestructing;
public NostrumObeliskEntity() {
super(0, 2000);
master = false;
isDestructing = false;
targets = new LinkedList<>();
targetIndex = 0;
this.compWrapper.configureInOut(true, false);
}
public NostrumObeliskEntity(boolean master) {
this();
this.master = master;
}
public NostrumObeliskEntity(Corner corner) {
this(false);
this.corner = corner;
}
@Override
public void setWorld(World world) {
super.setWorld(world);
this.compWrapper.setAutoFill(!world.isRemote && this.isMaster());
//aetherHandler.setAutoFill(!world.isRemote);
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
nbt = super.writeToNBT(nbt);
NBTTagList list = new NBTTagList();
if (master && targets.size() > 0)
for (NostrumObeliskTarget target : targets) {
if (target == null)
continue;
NBTTagCompound tag = new NBTTagCompound();
tag.setInteger(NBT_TARGET_X, target.pos.getX());
tag.setInteger(NBT_TARGET_Y, target.pos.getY());
tag.setInteger(NBT_TARGET_Z, target.pos.getZ());
tag.setString(NBT_TARGET_TITLE, target.title);
//tag.setInteger(NBT_TARGET_DIMENSION, target.dimension);
list.appendTag(tag);
}
nbt.setTag(NBT_TARGETS, list);
nbt.setBoolean(NBT_MASTER, master);
if (!master && corner != null) {
nbt.setByte(NBT_CORNER, (byte) corner.ordinal());
}
return nbt;
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
if (nbt == null || !nbt.hasKey(NBT_MASTER, NBT.TAG_BYTE))
return;
this.master = nbt.getBoolean(NBT_MASTER);
NBTTagList list = nbt.getTagList(NBT_TARGETS, NBT.TAG_COMPOUND);
if (list != null && list.tagCount() > 0) {
this.targets = new ArrayList<>(list.tagCount());
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound tag = list.getCompoundTagAt(i);
targets.add(new NostrumObeliskTarget(
//tag.getInteger(NBT_TARGET_DIMENSION),
new BlockPos(
tag.getInteger(NBT_TARGET_X),
tag.getInteger(NBT_TARGET_Y),
tag.getInteger(NBT_TARGET_Z)
),
tag.getString(NBT_TARGET_TITLE)));
}
}
if (!master) {
int ord = nbt.getByte(NBT_CORNER);
for (Corner c : Corner.values()) {
if (c.ordinal() == ord)
this.corner = c;
}
}
}
public void destroy() {
if (isDestructing)
return;
isDestructing = true;
if (master) {
// go to all four corners and break all blocks up
int xs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
int zs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
for (int i = 0; i < xs.length; i++)
for (int j = 1; j <= NostrumObelisk.TILE_HEIGHT; j++) { // j starts at one cause the first block is above the base block
BlockPos bp = pos.add(xs[i], j, zs[i]);
IBlockState state = world.getBlockState(bp);
if (state.getBlock() instanceof NostrumObelisk) {
world.destroyBlock(bp, false);
}
}
if (!world.isRemote) {
Ticket ticket = NostrumChunkLoader.instance().pullTicket(genTicketKey());
if (ticket != null) {
ForgeChunkManager.releaseTicket(ticket);
}
}
this.deactivatePortal();
world.destroyBlock(pos, false);
} else {
int xs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
int zs[] = new int[] {-NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH, -NostrumObelisk.TILE_OFFSETH, NostrumObelisk.TILE_OFFSETH};
for (int i = 0; i < xs.length; i++) {
BlockPos base = pos.add(xs[i], -NostrumObelisk.TILE_OFFSETY, zs[i]);
TileEntity te = world.getTileEntity(base);
if (te != null && te instanceof NostrumObeliskEntity) {
NostrumObeliskEntity entity = (NostrumObeliskEntity) te;
if (entity.master)
entity.destroy();
}
}
}
}
public boolean isMaster() {
return this.master;
}
public void addTarget(BlockPos pos) {
targets.add(new NostrumObeliskTarget(pos));
forceUpdate();
}
public void addTarget(BlockPos pos, String title) {
targets.add(new NostrumObeliskTarget(pos, title));
forceUpdate();
}
public List<NostrumObeliskTarget> getTargets() {
return targets;
}
public boolean canAcceptTarget(BlockPos pos) {
if (pos.equals(this.pos))
return false;
if (!targets.isEmpty())
for (NostrumObeliskTarget targPos : targets) {
if (pos.equals(targPos.pos))
return false;
}
if (!this.world.isRemote) {
IBlockState state = world.getBlockState(pos);
if (state == null || !(state.getBlock() instanceof NostrumObelisk)
|| !NostrumObelisk.blockIsMaster(state))
return false;
}
return true;
}
public void setTargetIndex(int index) {
if (this.targets.size() == 0 || index < 0) {
return;
}
this.targetIndex = Math.min(targets.size() - 1, index);
refreshPortal();
}
public @Nullable BlockPos getCurrentTarget() {
if (targetOverride != null) {
return targetOverride;
}
if (this.targets.size() == 0) {
return null;
}
return targets.get(Math.min(targets.size() - 1, targetIndex)).getPos();
}
public boolean hasOverride() {
return this.targetOverride != null;
}
protected void deactivatePortal() {
// Remove portal above us
world.setBlockToAir(pos.up());
}
protected void activatePortal() {
world.setBlockState(pos.up(), ObeliskPortal.instance().getStateForPlacement(world, pos, EnumFacing.UP, 0f, 0f, 0f, 0, null));
ObeliskPortal.instance().createPaired(world, pos.up());
}
protected void refreshPortal() {
@Nullable BlockPos target;
boolean valid;
if (this.targetOverride != null) {
valid = true;
target = this.targetOverride;
} else {
target = this.getCurrentTarget();
valid = (target != null && IsValidObelisk(world, target));
}
if (valid) {
// Make sure there's a portal
activatePortal();
} else {
deactivatePortal();
}
}
public static boolean IsValidObelisk(World world, BlockPos pos) {
IBlockState state = world.getBlockState(pos);
return !(state == null || !(state.getBlock() instanceof NostrumObelisk)
|| !NostrumObelisk.blockIsMaster(state));
}
public void setOverride(BlockPos override, int durationTicks) {
this.targetOverride = override;
this.targetOverrideEnd = this.aliveCount + durationTicks;
this.refreshPortal();
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
return new SPacketUpdateTileEntity(this.pos, 3, this.getUpdateTag());
}
@Override
public NBTTagCompound getUpdateTag() {
return this.writeToNBT(new NBTTagCompound());
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
super.onDataPacket(net, pkt);
handleUpdateTag(pkt.getNbtCompound());
}
// Registers this TE as a chunk loader. Gets a ticket and forces the chunk.
// Relies on already being placed in the world
public void init() {
if (world.isRemote)
return;
Ticket chunkTicket = ForgeChunkManager.requestTicket(NostrumMagica.instance, world, Type.NORMAL);
chunkTicket.getModData().setTag(NBT_TICKET_POS, NBTUtil.createPosTag(pos));
ForgeChunkManager.forceChunk(chunkTicket, new ChunkPos(pos));
NostrumChunkLoader.instance().addTicket(genTicketKey(), chunkTicket);
}
private String genTicketKey() {
return "nostrum_obelisk_" + pos.<KEY> pos.getY() + "_" + pos.getZ();
}
private void forceUpdate() {
world.notifyBlockUpdate(pos, this.world.getBlockState(pos), this.world.getBlockState(pos), 3);
markDirty();
}
@Override
public void update() {
super.update();
aliveCount++;
if (!world.isRemote && targetOverride != null && aliveCount >= targetOverrideEnd) {
targetOverride = null;
refreshPortal();
}
if (!world.isRemote)
return;
if (corner == null || master)
return;
final long stepInverval = 2;
if (aliveCount % stepInverval != 0)
return;
int step = (int) (aliveCount / stepInverval);
int maxStep = (int) ((20 / stepInverval) * 4); // 4 second period
step = step % maxStep;
float ratio = (float) step / (float) maxStep;
float angle = (float) (ratio * 2f * Math.PI); // radians
angle += ((double) corner.getOffset() + 1.0) * .25 * (2.0 * Math.PI);
float radius = (float) ((1f - ratio) * (NostrumObelisk.TILE_OFFSETH * 1.25));
double x, z, y;
x = Math.cos(angle) * radius;
z = Math.sin(angle) * radius;
y = ratio * (-NostrumObelisk.TILE_OFFSETY);
BlockPos master = getMasterPos();
x += master.getX() + .5;
z += master.getZ() + .5;
y += pos.getY() + .5;
world.spawnParticle(EnumParticleTypes.DRAGON_BREATH, x, y, z, .01, 0, .01, new int[0]);
}
private BlockPos getMasterPos() {
if (this.corner != null)
switch (this.corner) {
case NE:
return pos.add(-NostrumObelisk.TILE_OFFSETH, 1, -NostrumObelisk.TILE_OFFSETH);
case NW:
return pos.add(NostrumObelisk.TILE_OFFSETH, 1, -NostrumObelisk.TILE_OFFSETH);
case SE:
return pos.add(-NostrumObelisk.TILE_OFFSETH, 1, NostrumObelisk.TILE_OFFSETH);
case SW:
return pos.add(NostrumObelisk.TILE_OFFSETH, 1, NostrumObelisk.TILE_OFFSETH);
}
return pos;
};
protected int getAetherCost(BlockPos destination) {
if (this.targetOverride != null && destination == this.targetOverride) {
// No cost for overrides
return 0;
}
double dist = (Math.abs(this.pos.getX() - destination.getX())
+ Math.abs(this.pos.getY() - destination.getY())
+ Math.abs(this.pos.getZ() - destination.getZ()));
//double dist = Math.sqrt(this.pos.distanceSq(destination));
return (int) Math.round(AetherPerBlock * dist);
}
public boolean canAffordTeleport(BlockPos destination) {
return this.compWrapper.check(getAetherCost(destination));
}
/**
* Attempt to pay any secondary fee for teleportation to the provided location.
* This assumes the destination has been checked, etc.
* @param destination
* @return
*/
public boolean deductForTeleport(BlockPos destination) {
return this.compWrapper.checkAndWithdraw(getAetherCost(destination));
}
} | 13,213 | 0.696037 | 0.691423 | 464 | 27.497845 | 26.551592 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.538793 | false | false | 4 |
9be7f4a8b20a32a246a09511ab845fd2468a1719 | 12,953,621,414,449 | 2bfe79e61e0a87ac8950abea3770fbb39fb1ffaa | /shuDeZiJieGou017.java | ee7f2b462500d102f72efa5908c76f1936e3acdf | []
| no_license | liuxinyu199795/JianZhiOffer | https://github.com/liuxinyu199795/JianZhiOffer | aa1fc38d73ce524ebdcb0f2ce5cc200d41f93f2a | 970816aae8007d4a1b357f57d56c45a1707ca427 | refs/heads/master | 2020-06-04T09:23:31.398000 | 2019-07-21T07:00:11 | 2019-07-21T07:00:11 | 191,964,397 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @ProjectName: JianZhiOffer
* @Package: PACKAGE_NAME
* @ClassName: shuDeZiJieGou017
* @Author: XinyuLiu
* @Date: 2019/6/19 23:46
*/
public class shuDeZiJieGou017 {
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
boolean result=false;
if(root1!=null&&root2!=null){
if(root1.val==root2.val){
result=isSubtree(root1,root2);
}
if(!result){
result=HasSubtree(root1.left,root2);
}
if(!result){
result=HasSubtree(root1.right,root2);
}
}
return result;
}
public boolean isSubtree(TreeNode node1,TreeNode node2){
if(node2==null){
return true;
}
if(node1==null){
return false;
}
if(node1.val!=node2.val){
return false;
}
return isSubtree(node1.left,node2.left)&&isSubtree(node1.right,node2.right);
}
}
| UTF-8 | Java | 1,165 | java | shuDeZiJieGou017.java | Java | [
{
"context": "E_NAME\n * @ClassName: shuDeZiJieGou017\n * @Author: XinyuLiu\n * @Date: 2019/6/19 23:46\n */\npublic class shuDeZ",
"end": 112,
"score": 0.9996601343154907,
"start": 104,
"tag": "NAME",
"value": "XinyuLiu"
}
]
| null | []
| /**
* @ProjectName: JianZhiOffer
* @Package: PACKAGE_NAME
* @ClassName: shuDeZiJieGou017
* @Author: XinyuLiu
* @Date: 2019/6/19 23:46
*/
public class shuDeZiJieGou017 {
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
boolean result=false;
if(root1!=null&&root2!=null){
if(root1.val==root2.val){
result=isSubtree(root1,root2);
}
if(!result){
result=HasSubtree(root1.left,root2);
}
if(!result){
result=HasSubtree(root1.right,root2);
}
}
return result;
}
public boolean isSubtree(TreeNode node1,TreeNode node2){
if(node2==null){
return true;
}
if(node1==null){
return false;
}
if(node1.val!=node2.val){
return false;
}
return isSubtree(node1.left,node2.left)&&isSubtree(node1.right,node2.right);
}
}
| 1,165 | 0.525322 | 0.490987 | 46 | 24.326086 | 17.670971 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 4 |
004d9f0218797c6a60f7c3fb11f9f4f8d6951634 | 33,603,824,190,565 | aca55af30c2f49a1e02fd1ebe840e3c05ecbc081 | /Nouveau dossier/com/google/android/gms/drive/internal/q$b.java | a59e2f355ee7944056457e4b8085d14e1ee6370e | []
| no_license | bendito/Dump | https://github.com/bendito/Dump | 88065d20497ed436d540543b84ed47e13ab38c87 | dc3077cc1e5102a740065b99b91badc32cafd195 | refs/heads/master | 2020-02-06T11:31:31.024000 | 2017-07-28T13:16:30 | 2017-07-28T13:16:30 | 98,650,904 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.drive.internal;
class q$b extends com.google.android.gms.drive.internal.c {
private final com.google.android.gms.common.api.a$c vj;
public q$b(com.google.android.gms.common.api.a$c p1)
{
this.vj = p1;
return;
}
public void a(com.google.android.gms.drive.internal.OnDriveIdResponse p6)
{
com.google.android.gms.common.api.a$c v0 = this.vj;
com.google.android.gms.drive.internal.q$e v1 = new com.google.android.gms.drive.internal.q$e;
com.google.android.gms.common.api.Status v2 = com.google.android.gms.common.api.Status.zQ;
com.google.android.gms.drive.internal.q v3 = new com.google.android.gms.drive.internal.q;
com.google.android.gms.drive.DriveId vtmp1 = p6.getDriveId();
com.google.android.gms.drive.DriveId v4 = vtmp1;
v3 = v3(v4);
v1 = v1(v2, v3);
v0.b(v1);
return;
}
public void l(com.google.android.gms.common.api.Status p4)
{
com.google.android.gms.common.api.a$c v0 = this.vj;
com.google.android.gms.drive.internal.q$e v1 = new com.google.android.gms.drive.internal.q$e;
int v2 = 0;
v1 = v1(p4, v2);
v0.b(v1);
return;
}
}
| UTF-8 | Java | 1,252 | java | q$b.java | Java | []
| null | []
| package com.google.android.gms.drive.internal;
class q$b extends com.google.android.gms.drive.internal.c {
private final com.google.android.gms.common.api.a$c vj;
public q$b(com.google.android.gms.common.api.a$c p1)
{
this.vj = p1;
return;
}
public void a(com.google.android.gms.drive.internal.OnDriveIdResponse p6)
{
com.google.android.gms.common.api.a$c v0 = this.vj;
com.google.android.gms.drive.internal.q$e v1 = new com.google.android.gms.drive.internal.q$e;
com.google.android.gms.common.api.Status v2 = com.google.android.gms.common.api.Status.zQ;
com.google.android.gms.drive.internal.q v3 = new com.google.android.gms.drive.internal.q;
com.google.android.gms.drive.DriveId vtmp1 = p6.getDriveId();
com.google.android.gms.drive.DriveId v4 = vtmp1;
v3 = v3(v4);
v1 = v1(v2, v3);
v0.b(v1);
return;
}
public void l(com.google.android.gms.common.api.Status p4)
{
com.google.android.gms.common.api.a$c v0 = this.vj;
com.google.android.gms.drive.internal.q$e v1 = new com.google.android.gms.drive.internal.q$e;
int v2 = 0;
v1 = v1(p4, v2);
v0.b(v1);
return;
}
}
| 1,252 | 0.634185 | 0.609425 | 34 | 35.823528 | 32.766975 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 4 |
2fe921eeb3c09ac13b748a746b5a15c8fad32fa3 | 26,388,279,119,665 | 72324217d3541f7cb850b855954d138c44e8357b | /bookingApi/src/main/java/Util/JSONUtil.java | e11071f32479bbd4b23a20f52448b8635ae37ad8 | []
| no_license | rw1202/QA--Project | https://github.com/rw1202/QA--Project | 9700b026011895849ca741ce75651ef29d48ef9f | b6abe8bf0cfe1fdf4f15a7fa82126d349e39c1f9 | refs/heads/master | 2020-04-06T09:56:01.909000 | 2018-12-02T23:18:15 | 2018-12-02T23:18:15 | 157,362,436 | 0 | 0 | null | false | 2018-11-15T14:52:37 | 2018-11-13T10:30:08 | 2018-11-13T17:10:47 | 2018-11-15T14:52:37 | 30 | 0 | 0 | 0 | Java | false | null | package Util;
import com.google.gson.Gson;
import domain.Booking;
import domain.User;
public class JSONUtil {
private Gson gson;
public JSONUtil() {
this.gson = new Gson();
}
public String getJSONForObject(Object obj) {
return gson.toJson(obj);
}
public <T> T getObjectForJSONBooking(String jsonString, Long userId, Class<T> class1) {
return gson.fromJson(jsonString, class1);
}
public <T> T getObjectForJSONUser(String jsonString, Class<T> class2) {
return gson.fromJson(jsonString, class2);
}
}
| UTF-8 | Java | 564 | java | JSONUtil.java | Java | []
| null | []
| package Util;
import com.google.gson.Gson;
import domain.Booking;
import domain.User;
public class JSONUtil {
private Gson gson;
public JSONUtil() {
this.gson = new Gson();
}
public String getJSONForObject(Object obj) {
return gson.toJson(obj);
}
public <T> T getObjectForJSONBooking(String jsonString, Long userId, Class<T> class1) {
return gson.fromJson(jsonString, class1);
}
public <T> T getObjectForJSONUser(String jsonString, Class<T> class2) {
return gson.fromJson(jsonString, class2);
}
}
| 564 | 0.675532 | 0.66844 | 32 | 15.5 | 21.916033 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
9718b9dad5da62befdd80a2cd2fd0d97dea8acb6 | 29,377,576,308,370 | 1df84731e6d5821698da0eabb99687e27d7abb43 | /src/main/java/edu/harvard/i2b2/fhir/intake/modules/Converter.java | 5df2c328e96e0d337dec51e93821113f2ce96ccc | []
| no_license | waghsk/ifhir | https://github.com/waghsk/ifhir | b1749a5fd0ef95d987325e104324295a9e69976e | 9b6b450d0dfa343d4ba89625fc144eff47f16b06 | refs/heads/master | 2020-02-28T19:50:39.752000 | 2017-04-11T22:39:03 | 2017-04-11T22:39:03 | 87,957,956 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.harvard.i2b2.fhir.intake.modules;
import java.util.List;
import edu.harvard.i2b2.fhir.intake.converter.ConverterException;
import edu.harvard.i2b2.fhir.intake.fetcher.FetchRequest;
import org.hl7.fhir.dstu3.model.Bundle;
public interface Converter {
public List<String> fetchWebServiceData(FetchRequest req) throws ConverterException;
public List<Bundle> fetchWebServiceBundle(FetchRequest req) throws ConverterException;
// String composeRequestXml(Conversion conversion,String resourceName, String patientId, Date startDT, Date endDT);
}
| UTF-8 | Java | 562 | java | Converter.java | Java | []
| null | []
| package edu.harvard.i2b2.fhir.intake.modules;
import java.util.List;
import edu.harvard.i2b2.fhir.intake.converter.ConverterException;
import edu.harvard.i2b2.fhir.intake.fetcher.FetchRequest;
import org.hl7.fhir.dstu3.model.Bundle;
public interface Converter {
public List<String> fetchWebServiceData(FetchRequest req) throws ConverterException;
public List<Bundle> fetchWebServiceBundle(FetchRequest req) throws ConverterException;
// String composeRequestXml(Conversion conversion,String resourceName, String patientId, Date startDT, Date endDT);
}
| 562 | 0.825623 | 0.811388 | 15 | 36.466667 | 37.319996 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.933333 | false | false | 4 |
854dca45e3b6d54750ce60cc61c45aa7e4bfa5dd | 23,510,650,981,341 | a67975b01b6476af2394011aa8fb8a6543fe7796 | /AccountOpening.java | 0ae5f28bb5212283c2b6e69da8d374dfa8eb5fb7 | []
| no_license | PrajwalThorat/IC-Gramin-Bank | https://github.com/PrajwalThorat/IC-Gramin-Bank | 17e3c5453d1ffd60eeafe593a85109b3312b684b | 1cf1bfcc67e8384e37fa5ea1cab090039ee13df3 | refs/heads/main | 2023-07-01T14:52:29.596000 | 2021-08-14T12:54:56 | 2021-08-14T12:54:56 | 396,008,783 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class AccountOpening {
private Customer[] customer;
private int count = 0;
public void numberOfCustomer(){
customer = new Customer[20];
// count = 0 ;
}
public void acceptDetail(){
Scanner scan = new Scanner(System.in);
if(count>=20){
System.out.println("Update Data");
}else{
System.out.print("Enter First Name : ");
String first = scan.nextLine();
System.out.print("Enter Last Name : ");
String last = scan.nextLine();
System.out.print("Enter Mobile No. : ");
String mobileNumber = scan.nextLine();
System.out.print("Enter Email : ");
String emails = scan.nextLine();
// System.out.println("Enter The Address Details");
// System.out.print("House Number : ");
// int houseNumber = scan.nextInt();
// scan.nextLine();
// System.out.print("Enter Streat : ");
// String streat = scan.nextLine();
// System.out.print("Enter Landmark : ");
// String landMarks = scan.nextLine();
// System.out.print("Enter Villege : ");
// String villege = scan.nextLine();
// System.out.print("Enter City : ");
// String city = scan.nextLine();
// System.out.print("Enter PinCode : ");
// int pinCode = scan.nextInt();
// CustomerAddress address = new CustomerAddress(houseNumber, streat, landMarks, villege, city, pinCode);
Customer customers = new Customer(first, last, mobileNumber, emails);
customer[count] = customers;
count++;
}
}
public void showData(){
for(int i=0 ; i<customer.length ; i++){
Customer cust = customer[i];
cust.display();
}
}
}
| UTF-8 | Java | 1,991 | java | AccountOpening.java | Java | []
| null | []
|
import java.util.Scanner;
public class AccountOpening {
private Customer[] customer;
private int count = 0;
public void numberOfCustomer(){
customer = new Customer[20];
// count = 0 ;
}
public void acceptDetail(){
Scanner scan = new Scanner(System.in);
if(count>=20){
System.out.println("Update Data");
}else{
System.out.print("Enter First Name : ");
String first = scan.nextLine();
System.out.print("Enter Last Name : ");
String last = scan.nextLine();
System.out.print("Enter Mobile No. : ");
String mobileNumber = scan.nextLine();
System.out.print("Enter Email : ");
String emails = scan.nextLine();
// System.out.println("Enter The Address Details");
// System.out.print("House Number : ");
// int houseNumber = scan.nextInt();
// scan.nextLine();
// System.out.print("Enter Streat : ");
// String streat = scan.nextLine();
// System.out.print("Enter Landmark : ");
// String landMarks = scan.nextLine();
// System.out.print("Enter Villege : ");
// String villege = scan.nextLine();
// System.out.print("Enter City : ");
// String city = scan.nextLine();
// System.out.print("Enter PinCode : ");
// int pinCode = scan.nextInt();
// CustomerAddress address = new CustomerAddress(houseNumber, streat, landMarks, villege, city, pinCode);
Customer customers = new Customer(first, last, mobileNumber, emails);
customer[count] = customers;
count++;
}
}
public void showData(){
for(int i=0 ; i<customer.length ; i++){
Customer cust = customer[i];
cust.display();
}
}
}
| 1,991 | 0.511803 | 0.508287 | 57 | 32.894737 | 23.444361 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false | 4 |
4c62f362485935417861fe043e16ec3a6285e34f | 9,113,920,634,931 | 4c5494040814f3134e53a0bb894623d0698e0277 | /Algorithm/src/ALG_20171014/Offer16.java | 2a6531c2a5aa3d3629144f4011628f2a352c9c0f | []
| no_license | hongzhi-wang/java_project | https://github.com/hongzhi-wang/java_project | b90ad4b6926f593fb61f2dcb1ead518d5bac5c33 | df3842eece3b5604e044e6b7dcadba9e079f7402 | refs/heads/master | 2021-07-11T12:06:49.657000 | 2017-10-15T03:07:15 | 2017-10-15T03:07:15 | 67,915,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ALG_20171014;
/**
* 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
*
* 1-3-5-7
* 2-4-6-8
* 时间:2017年10月14日
* 作者: 汪宏志
* 描述:
*
*/
public class Offer16 {
public static void main(String[] args) {
ListNode head=new ListNode();
ListNode second=new ListNode();
ListNode third=new ListNode();
ListNode forth=new ListNode();
head.nextNode=second;
second.nextNode=third;
third.nextNode=forth;
head.data=1;
second.data=3;
third.data=5;
forth.data=7;
ListNode head2=new ListNode();
ListNode second2=new ListNode();
ListNode third2=new ListNode();
ListNode forth2=new ListNode();
head2.nextNode=second2;
second2.nextNode=third2;
third2.nextNode=forth2;
head2.data=2;
second2.data=4;
third2.data=6;
forth2.data=8;
ListNode tempNode = inputListNode(head,head2);
ListNode temp = tempNode;
while(temp != null)
{
System.out.println(temp.data);
temp = tempNode.nextNode;
}
}
public static ListNode test()
{
return null;
}
public static ListNode inputListNode(ListNode node1,ListNode node2)
{
if(node1 == null && node2 == null)
{
return null;
}
ListNode temp = null;
if(node1 == null)
{
temp = new ListNode();
temp.data = node2.data;
return temp;
}
if(node2 == null)
{
temp = new ListNode();
temp.data = node1.data;
return temp;
}
if(node1.data < node2.data)
{
temp = new ListNode();
temp.data = node1.data;
node1 = node1.nextNode;
temp.nextNode = inputListNode(node1,node2);
}
else
{
temp = new ListNode();
temp.data = node2.data;
node2 = node2.nextNode;
temp.nextNode = inputListNode(node1,node2);
}
return temp;
}
}
| UTF-8 | Java | 1,934 | java | Offer16.java | Java | [
{
"context": "\n * 1-3-5-7\r\n * 2-4-6-8\r\n * 时间:2017年10月14日\r\n * 作者: 汪宏志\r\n * 描述:\r\n *\r\n */\r\npublic class Offer16 {\r\n\t\r\n\tpub",
"end": 141,
"score": 0.9998616576194763,
"start": 138,
"tag": "NAME",
"value": "汪宏志"
}
]
| null | []
| package ALG_20171014;
/**
* 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
*
* 1-3-5-7
* 2-4-6-8
* 时间:2017年10月14日
* 作者: 汪宏志
* 描述:
*
*/
public class Offer16 {
public static void main(String[] args) {
ListNode head=new ListNode();
ListNode second=new ListNode();
ListNode third=new ListNode();
ListNode forth=new ListNode();
head.nextNode=second;
second.nextNode=third;
third.nextNode=forth;
head.data=1;
second.data=3;
third.data=5;
forth.data=7;
ListNode head2=new ListNode();
ListNode second2=new ListNode();
ListNode third2=new ListNode();
ListNode forth2=new ListNode();
head2.nextNode=second2;
second2.nextNode=third2;
third2.nextNode=forth2;
head2.data=2;
second2.data=4;
third2.data=6;
forth2.data=8;
ListNode tempNode = inputListNode(head,head2);
ListNode temp = tempNode;
while(temp != null)
{
System.out.println(temp.data);
temp = tempNode.nextNode;
}
}
public static ListNode test()
{
return null;
}
public static ListNode inputListNode(ListNode node1,ListNode node2)
{
if(node1 == null && node2 == null)
{
return null;
}
ListNode temp = null;
if(node1 == null)
{
temp = new ListNode();
temp.data = node2.data;
return temp;
}
if(node2 == null)
{
temp = new ListNode();
temp.data = node1.data;
return temp;
}
if(node1.data < node2.data)
{
temp = new ListNode();
temp.data = node1.data;
node1 = node1.nextNode;
temp.nextNode = inputListNode(node1,node2);
}
else
{
temp = new ListNode();
temp.data = node2.data;
node2 = node2.nextNode;
temp.nextNode = inputListNode(node1,node2);
}
return temp;
}
}
| 1,934 | 0.605408 | 0.567329 | 98 | 16.489796 | 14.269451 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.163265 | false | false | 4 |
0ba2afbb825e4171fdb5749088c8a4eed2e21232 | 20,641,612,858,627 | ed7c3dbdd9837cb0607f50016284dbc11ccaedbb | /paycard-parser/src/main/java/com/jaccal/command/gsm/GSMVerifyChv.java | 9f20cb032808d6815524a5c39901913e58509384 | []
| no_license | jmorille/android-nfc-paycardreader | https://github.com/jmorille/android-nfc-paycardreader | 1346c142ec58372cff06814d3cb1de91c3bf80f0 | eee3cfb9bd7365fa45059ede453ba8b68cdf2098 | refs/heads/master | 2020-12-07T15:15:59.131000 | 2014-05-16T21:11:54 | 2014-05-16T21:11:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2005 Chang Sau Sheong, Thomas Tarpin-Lyonnet.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaccal.command.gsm;
import com.jaccal.CardException;
import com.jaccal.command.iso.ISOVerifyChv;
import com.jaccal.util.NumUtil;
/**
*
* @author Thomas Tarpin-Lyonnet
*
*/
public class GSMVerifyChv extends ISOVerifyChv{
public final static String CHV1 = "01";
public final static String CHV2 = "02";
public GSMVerifyChv(String chvRefId, String chv) throws CardException{
super(chvRefId,chv);
super.setCla(GSM11_11.CLA_GSM11_11);
// Check chv length. must be >= 4
if((chv.length() < 4) || (chv.length() > 8))
throw new CardException("CHV value should be at least 4 byte long and less than 8 byte long");
// Check the CHV reference ID value
if((chvRefId.compareTo(CHV1) != 0) && (chvRefId.compareTo(CHV2) != 0))
throw new CardException("Bad CHV reference ID");
// Check if the CHV is decimal digits only (0-9)
try {
Integer.parseInt(chv,10);
} catch (NumberFormatException e) {
throw new CardException("CHV value has to be decimal digits only (0-9)");
}
// Convert the chv in string
String paddedChv = new String();
for(int i=0; i < chv.length(); i++){
paddedChv += "3" + chv.substring(i,i+1);
}
// Add the padding to FF until 16 digits
while(paddedChv.length() < 16){
paddedChv += "FF";
}
byte[] b = NumUtil.toStringHex(paddedChv);
setData(b);
setLc((byte)b.length);
}
/* (non-Javadoc)
* @see com.jaccal.command.Command#setCla(byte)
*/
public void setCla(byte cla){
}
}
| UTF-8 | Java | 2,230 | java | GSMVerifyChv.java | Java | [
{
"context": "/*\n * Copyright (c) 2005 Chang Sau Sheong, Thomas Tarpin-Lyonnet.\n *\n * Licensed under the ",
"end": 41,
"score": 0.9998624920845032,
"start": 25,
"tag": "NAME",
"value": "Chang Sau Sheong"
},
{
"context": "/*\n * Copyright (c) 2005 Chang Sau Sheong, Thomas Tarpin-Lyonnet.\n *\n * Licensed under the Apache License, Version",
"end": 64,
"score": 0.9998091459274292,
"start": 43,
"tag": "NAME",
"value": "Thomas Tarpin-Lyonnet"
},
{
"context": "port com.jaccal.util.NumUtil;\n \n/**\n * \n * @author Thomas Tarpin-Lyonnet\n *\n */\npublic class GSMVerifyChv extends ISOVerif",
"end": 813,
"score": 0.9998868703842163,
"start": 792,
"tag": "NAME",
"value": "Thomas Tarpin-Lyonnet"
}
]
| null | []
| /*
* Copyright (c) 2005 <NAME>, <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 com.jaccal.command.gsm;
import com.jaccal.CardException;
import com.jaccal.command.iso.ISOVerifyChv;
import com.jaccal.util.NumUtil;
/**
*
* @author <NAME>
*
*/
public class GSMVerifyChv extends ISOVerifyChv{
public final static String CHV1 = "01";
public final static String CHV2 = "02";
public GSMVerifyChv(String chvRefId, String chv) throws CardException{
super(chvRefId,chv);
super.setCla(GSM11_11.CLA_GSM11_11);
// Check chv length. must be >= 4
if((chv.length() < 4) || (chv.length() > 8))
throw new CardException("CHV value should be at least 4 byte long and less than 8 byte long");
// Check the CHV reference ID value
if((chvRefId.compareTo(CHV1) != 0) && (chvRefId.compareTo(CHV2) != 0))
throw new CardException("Bad CHV reference ID");
// Check if the CHV is decimal digits only (0-9)
try {
Integer.parseInt(chv,10);
} catch (NumberFormatException e) {
throw new CardException("CHV value has to be decimal digits only (0-9)");
}
// Convert the chv in string
String paddedChv = new String();
for(int i=0; i < chv.length(); i++){
paddedChv += "3" + chv.substring(i,i+1);
}
// Add the padding to FF until 16 digits
while(paddedChv.length() < 16){
paddedChv += "FF";
}
byte[] b = NumUtil.toStringHex(paddedChv);
setData(b);
setLc((byte)b.length);
}
/* (non-Javadoc)
* @see com.jaccal.command.Command#setCla(byte)
*/
public void setCla(byte cla){
}
}
| 2,190 | 0.651121 | 0.63139 | 71 | 30.408451 | 25.499836 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.070423 | false | false | 4 |
670d367f11e5456029da982c7af06e87089138a4 | 20,229,296,027,440 | ea1be0ffdd7f5a1fd26c1a912acab6b70411c0b1 | /app/src/main/java/com/ziyata/absen/model/login/LoginData.java | b1da64adf2d7aa9b5a3d0a0555ff1b53bb2a9128 | []
| no_license | habib1388i/Absen_siswa_baru | https://github.com/habib1388i/Absen_siswa_baru | fae6d396671db0c2dd0b33ec796d9563b8a702d0 | 84a07b2e202b8ea03f08f8efa6bd541179161a97 | refs/heads/master | 2020-05-27T10:24:24.348000 | 2019-05-17T07:05:45 | 2019-05-17T07:05:45 | 188,582,658 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ziyata.absen.model.login;
import com.google.gson.annotations.SerializedName;
public class LoginData {
@SerializedName("id_user")
private String id_user;
@SerializedName("id_kelas")
private String idKelas;
@SerializedName("nama_siswa")
private String namaSiswa;
@SerializedName("alamat")
private String alamat;
@SerializedName("jenkel")
private String jenkel;
@SerializedName("no_telp")
private String noTelp;
@SerializedName("username")
private String username;
@SerializedName("password")
private String password;
public String getId_user() {
return id_user;
}
public void setId_user(String id_user) {
this.id_user = id_user;
}
public String getIdKelas() {
return idKelas;
}
public void setIdKelas(String idKelas) {
this.idKelas = idKelas;
}
public String getNamaSiswa() {
return namaSiswa;
}
public void setNamaSiswa(String namaSiswa) {
this.namaSiswa = namaSiswa;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getJenkel() {
return jenkel;
}
public void setJenkel(String jenkel) {
this.jenkel = jenkel;
}
public String getNoTelp() {
return noTelp;
}
public void setNoTelp(String noTelp) {
this.noTelp = noTelp;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| UTF-8 | Java | 1,793 | java | LoginData.java | Java | [
{
"context": "\n private String noTelp;\n\n @SerializedName(\"username\")\n private String username;\n\n @SerializedNa",
"end": 507,
"score": 0.7701263427734375,
"start": 499,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna",
"end": 1541,
"score": 0.7963868975639343,
"start": 1533,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n ",
"end": 1629,
"score": 0.9526077508926392,
"start": 1621,
"tag": "USERNAME",
"value": "username"
},
{
"context": "assword(String password) {\n this.password = password;\n }\n}\n",
"end": 1783,
"score": 0.9831966757774353,
"start": 1775,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.ziyata.absen.model.login;
import com.google.gson.annotations.SerializedName;
public class LoginData {
@SerializedName("id_user")
private String id_user;
@SerializedName("id_kelas")
private String idKelas;
@SerializedName("nama_siswa")
private String namaSiswa;
@SerializedName("alamat")
private String alamat;
@SerializedName("jenkel")
private String jenkel;
@SerializedName("no_telp")
private String noTelp;
@SerializedName("username")
private String username;
@SerializedName("password")
private String password;
public String getId_user() {
return id_user;
}
public void setId_user(String id_user) {
this.id_user = id_user;
}
public String getIdKelas() {
return idKelas;
}
public void setIdKelas(String idKelas) {
this.idKelas = idKelas;
}
public String getNamaSiswa() {
return namaSiswa;
}
public void setNamaSiswa(String namaSiswa) {
this.namaSiswa = namaSiswa;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getJenkel() {
return jenkel;
}
public void setJenkel(String jenkel) {
this.jenkel = jenkel;
}
public String getNoTelp() {
return noTelp;
}
public void setNoTelp(String noTelp) {
this.noTelp = noTelp;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
}
| 1,795 | 0.619632 | 0.619632 | 94 | 18.074469 | 15.840454 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276596 | false | false | 4 |
fae91e689f00030a8e1a551ddd76f2068ca98fe4 | 21,388,937,158,868 | 019365bfc978c43c3fb13876d4f4b82725b8962c | /Servlets Java ex/lab_10_01/src/java/com/lab1001/services/impl/ImageServiceMem.java | 4ca09cf2df7f3f0484a6be21869ad7f77e2bf7f5 | []
| no_license | KhalidAlghamdi8/Servlets-Java | https://github.com/KhalidAlghamdi8/Servlets-Java | 88ca174a6a8f42043b1a88bfb13221be81acfe86 | 88e4bfea4586f5e45703f765ccfd7fb430f48aba | refs/heads/main | 2023-02-25T06:05:33.823000 | 2021-02-12T12:03:39 | 2021-02-12T12:03:39 | 338,306,836 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lab1001.services.impl;
import com.lab1001.model.Image;
import com.lab1001.services.ImageService;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class ImageServiceMem implements ImageService {
private int currentImageId;
private Map<Integer, Image> images;
public ImageServiceMem() {
}
@PostConstruct
public void setup() {
images = new ConcurrentHashMap<Integer, Image>();
currentImageId = 2000;
addImage(getPhoto("images/AntiquePhoneStand.jpg"), "image/jpeg");
addImage(getPhoto("images/Doll.jpg"), "image/jpeg");
addImage(getPhoto("images/AntiqueCoffeeGrinder.jpg"), "image/jpeg");
addImage(getPhoto("images/SaltPepperShakers.jpg"), "image/jpeg");
addImage(getPhoto("images/PolarBear.jpg"), "image/jpeg");
addImage(getPhoto("images/Backpack.jpg"), "image/jpeg");
addImage(getPhoto("images/HorseSculpture.jpg"), "image/jpeg");
}
@Override
public Image findImageById(int imageId) {
return images.get(imageId);
}
@Override
public Image addImage(Image image) {
int id = currentImageId;
currentImageId++;
image.setImageId(id);
images.put(id, image);
return image;
}
private byte[] getPhoto(String filePath) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
inputStream = getClass().getResourceAsStream(filePath);
outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, read);
}
outputStream.flush();
return outputStream.toByteArray();
} catch (Exception i) {
System.err.println("Exception loading photo:" + filePath + " : " + i.getClass().getName() + " Message: " + i.getMessage());
} finally {
try {
inputStream.close();
} catch (Exception e) {
System.err.println("Error closing stream" + e);
}
try {
outputStream.close();
} catch (Exception e) {
System.err.println("Error closing stream" + e);
}
}
return null;
}
public Map<?, ? extends Object> getImages() {
return images;
}
private void addImage(byte[] data, String contentType) {
addImage(new Image(0, data, contentType));
}
}
| UTF-8 | Java | 2,528 | java | ImageServiceMem.java | Java | []
| null | []
| package com.lab1001.services.impl;
import com.lab1001.model.Image;
import com.lab1001.services.ImageService;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class ImageServiceMem implements ImageService {
private int currentImageId;
private Map<Integer, Image> images;
public ImageServiceMem() {
}
@PostConstruct
public void setup() {
images = new ConcurrentHashMap<Integer, Image>();
currentImageId = 2000;
addImage(getPhoto("images/AntiquePhoneStand.jpg"), "image/jpeg");
addImage(getPhoto("images/Doll.jpg"), "image/jpeg");
addImage(getPhoto("images/AntiqueCoffeeGrinder.jpg"), "image/jpeg");
addImage(getPhoto("images/SaltPepperShakers.jpg"), "image/jpeg");
addImage(getPhoto("images/PolarBear.jpg"), "image/jpeg");
addImage(getPhoto("images/Backpack.jpg"), "image/jpeg");
addImage(getPhoto("images/HorseSculpture.jpg"), "image/jpeg");
}
@Override
public Image findImageById(int imageId) {
return images.get(imageId);
}
@Override
public Image addImage(Image image) {
int id = currentImageId;
currentImageId++;
image.setImageId(id);
images.put(id, image);
return image;
}
private byte[] getPhoto(String filePath) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
inputStream = getClass().getResourceAsStream(filePath);
outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, read);
}
outputStream.flush();
return outputStream.toByteArray();
} catch (Exception i) {
System.err.println("Exception loading photo:" + filePath + " : " + i.getClass().getName() + " Message: " + i.getMessage());
} finally {
try {
inputStream.close();
} catch (Exception e) {
System.err.println("Error closing stream" + e);
}
try {
outputStream.close();
} catch (Exception e) {
System.err.println("Error closing stream" + e);
}
}
return null;
}
public Map<?, ? extends Object> getImages() {
return images;
}
private void addImage(byte[] data, String contentType) {
addImage(new Image(0, data, contentType));
}
}
| 2,528 | 0.675237 | 0.665744 | 85 | 28.741177 | 23.698673 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717647 | false | false | 4 |
6acf4ab63602e07b8144ab56387fbdbb4faa586a | 6,081,673,717,224 | 23c1d4db9a99c95a62183f5c7a4567ec718a6b5b | /src/main/java/com/chihyao/relaxed/module/messagelist/repository/MessageRepository.java | f9872a443bc13a5b650abb4322bb768c01060539 | []
| no_license | chihyaoOwO/relaxed | https://github.com/chihyaoOwO/relaxed | 33cb46f670de92c84b9bf771e81b5e9111c4e657 | 14617366b9627045a3a7d22e59798e2fddcbf864 | refs/heads/master | 2023-06-29T18:47:36.943000 | 2021-08-02T05:57:09 | 2021-08-02T05:57:09 | 371,305,961 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chihyao.relaxed.module.messagelist.repository;
import com.chihyao.relaxed.module.messagelist.entity.Message;
import org.springframework.data.jpa.datatables.repository.DataTablesRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;
public interface MessageRepository extends JpaRepository<Message, UUID>, DataTablesRepository<Message, UUID> {
}
| UTF-8 | Java | 403 | java | MessageRepository.java | Java | []
| null | []
| package com.chihyao.relaxed.module.messagelist.repository;
import com.chihyao.relaxed.module.messagelist.entity.Message;
import org.springframework.data.jpa.datatables.repository.DataTablesRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;
public interface MessageRepository extends JpaRepository<Message, UUID>, DataTablesRepository<Message, UUID> {
}
| 403 | 0.846154 | 0.846154 | 11 | 35.636364 | 37.734173 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 4 |
9496b404559bda2840c72e45de18338e72b7a1fd | 28,398,323,820,774 | 63b47a489021ea01be96defbdab55487d23da25e | /src/main/java/com/chm/kd/kq/service/QuestionAnswerService.java | 44b24d395543c389b32078912f2f4afd7f780ae4 | []
| no_license | cxy654849388/kq | https://github.com/cxy654849388/kq | f2ecfd458cd942b28938d5aaa38b923f305503a8 | 2d28248627edfc6bde4449c73799fa233917e841 | refs/heads/master | 2020-06-29T19:26:46.449000 | 2019-08-30T01:37:28 | 2019-08-30T01:37:28 | 200,603,381 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chm.kd.kq.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chm.kd.kq.entity.QuestionAnswer;
import java.util.List;
/**
* @author caihongming
* @version v1.0
* @title QuestionAnswerService
* @package com.chm.kd.kq.service
* @since 2019-07-12
* description Q群问答表 服务类
**/
public interface QuestionAnswerService extends IService<QuestionAnswer> {
/**
* 获取精确问答信息
*
* @param groupId QQ群号
* @param question 问题
* @return
*/
QuestionAnswer getByGroupIdAndQuestion(Long groupId, String question);
/**
* 查问
*
* @param groupId QQ群号
* @param question 问题
* @return
*/
List<QuestionAnswer> findQuestion(Long groupId, String question);
/**
* 保存问题
*
* @param groupId QQ群号
* @param question 问题
* @param answer 回答
* @param type 消息类型
* @return
*/
Long saveQuestion(Long groupId, List<String> question, String answer, String type);
/**
* 删除问答
*
* @param groupId
* @param questionsIdList
* @return
*/
Long deleteQuestion(Long groupId, List<Integer> questionsIdList);
/**
* 获取所有questionsId为空的问答对象
*
* @return
*/
List<QuestionAnswer> getEmptyQuestionsIdList();
/**
* 回答问题
*
* @param groupId
* @param question
* @return
*/
List<QuestionAnswer> answers(Long groupId, String question);
/**
* 设置问题id
*
* @param questionAnswer
* @return
*/
boolean setQuestionId(QuestionAnswer questionAnswer);
/**
* 复制问答
* @param srcGroupId
* @param destGroupId
* @return
*/
Long copyQuestion(Long srcGroupId, Long destGroupId);
}
| UTF-8 | Java | 1,758 | java | QuestionAnswerService.java | Java | [
{
"context": "ionAnswer;\n\nimport java.util.List;\n\n/**\n * @author caihongming\n * @version v1.0\n * @title QuestionAnswerService\n",
"end": 187,
"score": 0.9996660351753235,
"start": 176,
"tag": "USERNAME",
"value": "caihongming"
}
]
| null | []
| package com.chm.kd.kq.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chm.kd.kq.entity.QuestionAnswer;
import java.util.List;
/**
* @author caihongming
* @version v1.0
* @title QuestionAnswerService
* @package com.chm.kd.kq.service
* @since 2019-07-12
* description Q群问答表 服务类
**/
public interface QuestionAnswerService extends IService<QuestionAnswer> {
/**
* 获取精确问答信息
*
* @param groupId QQ群号
* @param question 问题
* @return
*/
QuestionAnswer getByGroupIdAndQuestion(Long groupId, String question);
/**
* 查问
*
* @param groupId QQ群号
* @param question 问题
* @return
*/
List<QuestionAnswer> findQuestion(Long groupId, String question);
/**
* 保存问题
*
* @param groupId QQ群号
* @param question 问题
* @param answer 回答
* @param type 消息类型
* @return
*/
Long saveQuestion(Long groupId, List<String> question, String answer, String type);
/**
* 删除问答
*
* @param groupId
* @param questionsIdList
* @return
*/
Long deleteQuestion(Long groupId, List<Integer> questionsIdList);
/**
* 获取所有questionsId为空的问答对象
*
* @return
*/
List<QuestionAnswer> getEmptyQuestionsIdList();
/**
* 回答问题
*
* @param groupId
* @param question
* @return
*/
List<QuestionAnswer> answers(Long groupId, String question);
/**
* 设置问题id
*
* @param questionAnswer
* @return
*/
boolean setQuestionId(QuestionAnswer questionAnswer);
/**
* 复制问答
* @param srcGroupId
* @param destGroupId
* @return
*/
Long copyQuestion(Long srcGroupId, Long destGroupId);
}
| 1,758 | 0.648831 | 0.642681 | 87 | 17.689655 | 19.624235 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.229885 | false | false | 4 |
ccecb8f04be1d4c7fa6dc941e840d6a6f72aae47 | 28,862,180,253,521 | 19238af79743400d9b7cb4c29234294750fb0c32 | /ofg6.2_oracle/src/main/java/com/ambition/supplier/entity/ExceptionContact.java | 4c30b5fdd7c9044020be4ac0ca65f03ec826b64f | []
| no_license | laonanhai481580/ofg6.2_oracle | https://github.com/laonanhai481580/ofg6.2_oracle | 7d8ed374c51e298c92713dbea266cfa8ef55ff85 | 286c242bbf44b6addc4622374e95af27e6979242 | refs/heads/master | 2020-04-19T04:03:13.924000 | 2019-01-28T11:27:42 | 2019-01-28T11:27:42 | 167,951,726 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ambition.supplier.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.ambition.product.base.WorkflowIdEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* 物料异常联络单
* @authorBy LPF
*
*/
@Entity
@Table(name = "SUPPLIER_EXCEPTION_CONTACT")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class ExceptionContact extends WorkflowIdEntity{
private static final long serialVersionUID = 1L;
private String formNo;
private String inspectionFormNo;
private String inspectionId;
private String happenSpace;//发生地点
private String productStage;//产品阶段
private String billingArea;//开单区域
private String supplierName;//供应商
private String supplierCode;//
private String exceptionStage;//异常阶段
private String exceptionType;//异常类型
private String exceptionDegree;//异常程度
private String bomName;//品名
private String bomCode;//料号
private String materialType;//物料类别
private Date inspectionDate;//检验日期
private Double incomingAmount;//进料数
@Column(length=40)
private String units;//单位
private Double checkAmount;//抽检数
private String surfaceBad;//外观不良
private Double surfaceBadRate;//外观不良率
private String surfaceBadState;//外观状态
private String functionBad;//功能不良
private Double functionBadRate;//功能不良率
private String functionBadState;//功能状态
private String sizeBad;//尺寸不良
private Double sizeBadRate;//尺寸不良率
private String sizeBadState;//
private String featuresBad;//特性不良
private Double featuresBadRate;//特性不良率
private String featuresBadState;//特性状态
private String badDesc;//异常描述
private String descFile;//附件
private String inspector;//检验员,发起人
private String inspectorLog;
private Date sponsorDate;//发起日期
//主管审核问题描述
@Column(length=1000)
private String reportCheckOpinion;//意见
private String reportChecker;//审核人
private String reportCheckerLog;
private Date reportCheckDate;//
//MQE确认异常
@Column(length=1000)
private String mqeCheckOpinion;//意见
private String mqeChecker;//审核人
private String mqeCheckerLog;
private Date mqeCheckDate;//
private String isImprove;//是否需要发起sqe改进
//PMC意见
@Column(length=1000)
private String pmcOpinion;//pmc意见
private Date demandDeliveryPeriod;//需求交期
private String mrbApply;//mrb申请
private String mrbReportNo;//mrb单号
private String pmcChecker;//pmc审核人
private String pmcCheckerLog;
//MQE提供处理意见
@Column(length=1000)
private String qualityOpinion;//品质中心意见
private String sqeProcessOpinion;//处理意见
private String returnReportNo;//退货通知单单号
private String sqeMrbReportNo;//mrb单号
//MQE主管审核处理意见
@Column(length=1000)
private String mqeSupervisorOpinion;//MQE主管意见
private String mqeSupervisor;//审核人
private String mqeSupervisorLog;
private Date mqeSupervisorDate;//
//供应商回复内容
@Column(length=2000)
private String tempCountermeasures;//暂定对策实施
@Column(length=2000)
private String trueReasonCheck;//真因定义及验证
@Column(length=2000)
private String countermeasures;//永久对策实施
@Column(length=2000)
private String preventHappen;//预防再发生
@Column(length=2000)
private String supplierFile;//
private Date requestDate;//8d回复日期
//MQE确认改善报告
private String mqeComfirm;
private String mqeComfirmLog;
@Column(length=1000)
private String mqeComfirmOpinion;//MQE审核意见
private Date mqeComfirmDate;//
//MQE主管审核
@Column(length=1000)
private String mqeApprovalerOpinion;//MQE主管意见
private Date mqeApprovalerDate;//
private String mqeApprovaler;
private String mqeApprovalerLog;
//MQE追踪改善效果
private String checkResult;//效果确认
private Date sqeFinishDate;//sqe追踪完成时间
private Date checkResultDate;//确认日期
private String supplierEmail;//供应商邮箱地址
private String isClosed="否";//是否结案
private String isClosedAlaysis="否";//是否结案(用于统计)
private String isSupplier="否";//是否供应商回复
private String currentMan;//当前办理人
private String currentManLog;//当前办理人登录名
private String exceptionImproveId;//对应的异常矫正单id
private String exceptionImprovetNo;//对应的异常矫正单编号
//用于集成判断
private Long sourceId;//集成过来原ID
private String sourceUnit;//集成的事业部
public String getFormNo() {
return formNo;
}
public void setFormNo(String formNo) {
this.formNo = formNo;
}
public String getHappenSpace() {
return happenSpace;
}
public void setHappenSpace(String happenSpace) {
this.happenSpace = happenSpace;
}
public String getProductStage() {
return productStage;
}
public void setProductStage(String productStage) {
this.productStage = productStage;
}
public String getBillingArea() {
return billingArea;
}
public void setBillingArea(String billingArea) {
this.billingArea = billingArea;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public String getBomName() {
return bomName;
}
public void setBomName(String bomName) {
this.bomName = bomName;
}
public String getBomCode() {
return bomCode;
}
public void setBomCode(String bomCode) {
this.bomCode = bomCode;
}
public Date getInspectionDate() {
return inspectionDate;
}
public void setInspectionDate(Date inspectionDate) {
this.inspectionDate = inspectionDate;
}
public Double getIncomingAmount() {
return incomingAmount;
}
public void setIncomingAmount(Double incomingAmount) {
this.incomingAmount = incomingAmount;
}
public Double getCheckAmount() {
return checkAmount;
}
public void setCheckAmount(Double checkAmount) {
this.checkAmount = checkAmount;
}
public String getSurfaceBad() {
return surfaceBad;
}
public void setSurfaceBad(String surfaceBad) {
this.surfaceBad = surfaceBad;
}
public Double getSurfaceBadRate() {
return surfaceBadRate;
}
public void setSurfaceBadRate(Double surfaceBadRate) {
this.surfaceBadRate = surfaceBadRate;
}
public String getFunctionBad() {
return functionBad;
}
public void setFunctionBad(String functionBad) {
this.functionBad = functionBad;
}
public Double getFunctionBadRate() {
return functionBadRate;
}
public void setFunctionBadRate(Double functionBadRate) {
this.functionBadRate = functionBadRate;
}
public String getSizeBad() {
return sizeBad;
}
public void setSizeBad(String sizeBad) {
this.sizeBad = sizeBad;
}
public Double getSizeBadRate() {
return sizeBadRate;
}
public void setSizeBadRate(Double sizeBadRate) {
this.sizeBadRate = sizeBadRate;
}
public String getFeaturesBad() {
return featuresBad;
}
public void setFeaturesBad(String featuresBad) {
this.featuresBad = featuresBad;
}
public Double getFeaturesBadRate() {
return featuresBadRate;
}
public void setFeaturesBadRate(Double featuresBadRate) {
this.featuresBadRate = featuresBadRate;
}
public String getBadDesc() {
return badDesc;
}
public void setBadDesc(String badDesc) {
this.badDesc = badDesc;
}
public String getDescFile() {
return descFile;
}
public void setDescFile(String descFile) {
this.descFile = descFile;
}
public String getInspector() {
return inspector;
}
public void setInspector(String inspector) {
this.inspector = inspector;
}
public String getInspectorLog() {
return inspectorLog;
}
public void setInspectorLog(String inspectorLog) {
this.inspectorLog = inspectorLog;
}
public String getReportChecker() {
return reportChecker;
}
public void setReportChecker(String reportChecker) {
this.reportChecker = reportChecker;
}
public String getReportCheckerLog() {
return reportCheckerLog;
}
public void setReportCheckerLog(String reportCheckerLog) {
this.reportCheckerLog = reportCheckerLog;
}
public String getPmcOpinion() {
return pmcOpinion;
}
public void setPmcOpinion(String pmcOpinion) {
this.pmcOpinion = pmcOpinion;
}
public Date getDemandDeliveryPeriod() {
return demandDeliveryPeriod;
}
public void setDemandDeliveryPeriod(Date demandDeliveryPeriod) {
this.demandDeliveryPeriod = demandDeliveryPeriod;
}
public String getMrbApply() {
return mrbApply;
}
public void setMrbApply(String mrbApply) {
this.mrbApply = mrbApply;
}
public String getMrbReportNo() {
return mrbReportNo;
}
public void setMrbReportNo(String mrbReportNo) {
this.mrbReportNo = mrbReportNo;
}
public String getPmcChecker() {
return pmcChecker;
}
public void setPmcChecker(String pmcChecker) {
this.pmcChecker = pmcChecker;
}
public String getPmcCheckerLog() {
return pmcCheckerLog;
}
public void setPmcCheckerLog(String pmcCheckerLog) {
this.pmcCheckerLog = pmcCheckerLog;
}
public String getQualityOpinion() {
return qualityOpinion;
}
public void setQualityOpinion(String qualityOpinion) {
this.qualityOpinion = qualityOpinion;
}
public String getSqeProcessOpinion() {
return sqeProcessOpinion;
}
public void setSqeProcessOpinion(String sqeProcessOpinion) {
this.sqeProcessOpinion = sqeProcessOpinion;
}
public String getReturnReportNo() {
return returnReportNo;
}
public void setReturnReportNo(String returnReportNo) {
this.returnReportNo = returnReportNo;
}
public String getSqeMrbReportNo() {
return sqeMrbReportNo;
}
public void setSqeMrbReportNo(String sqeMrbReportNo) {
this.sqeMrbReportNo = sqeMrbReportNo;
}
public String getTempCountermeasures() {
return tempCountermeasures;
}
public void setTempCountermeasures(String tempCountermeasures) {
this.tempCountermeasures = tempCountermeasures;
}
public String getTrueReasonCheck() {
return trueReasonCheck;
}
public void setTrueReasonCheck(String trueReasonCheck) {
this.trueReasonCheck = trueReasonCheck;
}
public String getCountermeasures() {
return countermeasures;
}
public void setCountermeasures(String countermeasures) {
this.countermeasures = countermeasures;
}
public String getPreventHappen() {
return preventHappen;
}
public void setPreventHappen(String preventHappen) {
this.preventHappen = preventHappen;
}
public String getSupplierFile() {
return supplierFile;
}
public void setSupplierFile(String supplierFile) {
this.supplierFile = supplierFile;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public String getCheckResult() {
return checkResult;
}
public void setCheckResult(String checkResult) {
this.checkResult = checkResult;
}
public Date getSqeFinishDate() {
return sqeFinishDate;
}
public void setSqeFinishDate(Date sqeFinishDate) {
this.sqeFinishDate = sqeFinishDate;
}
public String getMaterialType() {
return materialType;
}
public void setMaterialType(String materialType) {
this.materialType = materialType;
}
public String getSupplierCode() {
return supplierCode;
}
public void setSupplierCode(String supplierCode) {
this.supplierCode = supplierCode;
}
public String getSupplierEmail() {
return supplierEmail;
}
public void setSupplierEmail(String supplierEmail) {
this.supplierEmail = supplierEmail;
}
public String getSurfaceBadState() {
return surfaceBadState;
}
public void setSurfaceBadState(String surfaceBadState) {
this.surfaceBadState = surfaceBadState;
}
public String getFunctionBadState() {
return functionBadState;
}
public void setFunctionBadState(String functionBadState) {
this.functionBadState = functionBadState;
}
public String getSizeBadState() {
return sizeBadState;
}
public void setSizeBadState(String sizeBadState) {
this.sizeBadState = sizeBadState;
}
public String getFeaturesBadState() {
return featuresBadState;
}
public void setFeaturesBadState(String featuresBadState) {
this.featuresBadState = featuresBadState;
}
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public String getInspectionFormNo() {
return inspectionFormNo;
}
public void setInspectionFormNo(String inspectionFormNo) {
this.inspectionFormNo = inspectionFormNo;
}
public String getInspectionId() {
return inspectionId;
}
public void setInspectionId(String inspectionId) {
this.inspectionId = inspectionId;
}
public String getIsClosed() {
return isClosed;
}
public void setIsClosed(String isClosed) {
this.isClosed = isClosed;
}
public String getIsClosedAlaysis() {
return isClosedAlaysis;
}
public void setIsClosedAlaysis(String isClosedAlaysis) {
this.isClosedAlaysis = isClosedAlaysis;
}
public String getIsSupplier() {
return isSupplier;
}
public void setIsSupplier(String isSupplier) {
this.isSupplier = isSupplier;
}
public String getCurrentMan() {
return currentMan;
}
public void setCurrentMan(String currentMan) {
this.currentMan = currentMan;
}
public String getCurrentManLog() {
return currentManLog;
}
public void setCurrentManLog(String currentManLog) {
this.currentManLog = currentManLog;
}
public String getExceptionType() {
return exceptionType;
}
public void setExceptionType(String exceptionType) {
this.exceptionType = exceptionType;
}
public Date getSponsorDate() {
return sponsorDate;
}
public void setSponsorDate(Date sponsorDate) {
this.sponsorDate = sponsorDate;
}
public String getReportCheckOpinion() {
return reportCheckOpinion;
}
public void setReportCheckOpinion(String reportCheckOpinion) {
this.reportCheckOpinion = reportCheckOpinion;
}
public Date getReportCheckDate() {
return reportCheckDate;
}
public void setReportCheckDate(Date reportCheckDate) {
this.reportCheckDate = reportCheckDate;
}
public String getMqeCheckOpinion() {
return mqeCheckOpinion;
}
public void setMqeCheckOpinion(String mqeCheckOpinion) {
this.mqeCheckOpinion = mqeCheckOpinion;
}
public String getMqeChecker() {
return mqeChecker;
}
public void setMqeChecker(String mqeChecker) {
this.mqeChecker = mqeChecker;
}
public String getMqeCheckerLog() {
return mqeCheckerLog;
}
public void setMqeCheckerLog(String mqeCheckerLog) {
this.mqeCheckerLog = mqeCheckerLog;
}
public Date getMqeCheckDate() {
return mqeCheckDate;
}
public void setMqeCheckDate(Date mqeCheckDate) {
this.mqeCheckDate = mqeCheckDate;
}
public String getMqeSupervisorOpinion() {
return mqeSupervisorOpinion;
}
public void setMqeSupervisorOpinion(String mqeSupervisorOpinion) {
this.mqeSupervisorOpinion = mqeSupervisorOpinion;
}
public String getMqeSupervisor() {
return mqeSupervisor;
}
public void setMqeSupervisor(String mqeSupervisor) {
this.mqeSupervisor = mqeSupervisor;
}
public String getMqeSupervisorLog() {
return mqeSupervisorLog;
}
public void setMqeSupervisorLog(String mqeSupervisorLog) {
this.mqeSupervisorLog = mqeSupervisorLog;
}
public Date getMqeSupervisorDate() {
return mqeSupervisorDate;
}
public void setMqeSupervisorDate(Date mqeSupervisorDate) {
this.mqeSupervisorDate = mqeSupervisorDate;
}
public Date getCheckResultDate() {
return checkResultDate;
}
public void setCheckResultDate(Date checkResultDate) {
this.checkResultDate = checkResultDate;
}
public String getExceptionImproveId() {
return exceptionImproveId;
}
public void setExceptionImproveId(String exceptionImproveId) {
this.exceptionImproveId = exceptionImproveId;
}
public String getExceptionImprovetNo() {
return exceptionImprovetNo;
}
public void setExceptionImprovetNo(String exceptionImprovetNo) {
this.exceptionImprovetNo = exceptionImprovetNo;
}
public String getExceptionStage() {
return exceptionStage;
}
public void setExceptionStage(String exceptionStage) {
this.exceptionStage = exceptionStage;
}
public String getExceptionDegree() {
return exceptionDegree;
}
public void setExceptionDegree(String exceptionDegree) {
this.exceptionDegree = exceptionDegree;
}
public String getIsImprove() {
return isImprove;
}
public void setIsImprove(String isImprove) {
this.isImprove = isImprove;
}
public String getMqeComfirmOpinion() {
return mqeComfirmOpinion;
}
public void setMqeComfirmOpinion(String mqeComfirmOpinion) {
this.mqeComfirmOpinion = mqeComfirmOpinion;
}
public Date getMqeComfirmDate() {
return mqeComfirmDate;
}
public void setMqeComfirmDate(Date mqeComfirmDate) {
this.mqeComfirmDate = mqeComfirmDate;
}
public String getMqeApprovalerOpinion() {
return mqeApprovalerOpinion;
}
public void setMqeApprovalerOpinion(String mqeApprovalerOpinion) {
this.mqeApprovalerOpinion = mqeApprovalerOpinion;
}
public Date getMqeApprovalerDate() {
return mqeApprovalerDate;
}
public void setMqeApprovalerDate(Date mqeApprovalerDate) {
this.mqeApprovalerDate = mqeApprovalerDate;
}
public Long getSourceId() {
return sourceId;
}
public void setSourceId(Long sourceId) {
this.sourceId = sourceId;
}
public String getSourceUnit() {
return sourceUnit;
}
public void setSourceUnit(String sourceUnit) {
this.sourceUnit = sourceUnit;
}
public String getMqeComfirm() {
return mqeComfirm;
}
public void setMqeComfirm(String mqeComfirm) {
this.mqeComfirm = mqeComfirm;
}
public String getMqeComfirmLog() {
return mqeComfirmLog;
}
public void setMqeComfirmLog(String mqeComfirmLog) {
this.mqeComfirmLog = mqeComfirmLog;
}
public String getMqeApprovaler() {
return mqeApprovaler;
}
public void setMqeApprovaler(String mqeApprovaler) {
this.mqeApprovaler = mqeApprovaler;
}
public String getMqeApprovalerLog() {
return mqeApprovalerLog;
}
public void setMqeApprovalerLog(String mqeApprovalerLog) {
this.mqeApprovalerLog = mqeApprovalerLog;
}
}
| UTF-8 | Java | 18,078 | java | ExceptionContact.java | Java | [
{
"context": "IgnoreProperties;\n\n/** \n * 物料异常联络单\n * @authorBy LPF\n *\n */\n@Entity\n@Table(name = \"SUPPLIER_EXCEPTION_",
"end": 311,
"score": 0.9988207817077637,
"start": 308,
"tag": "USERNAME",
"value": "LPF"
}
]
| null | []
| package com.ambition.supplier.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.ambition.product.base.WorkflowIdEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* 物料异常联络单
* @authorBy LPF
*
*/
@Entity
@Table(name = "SUPPLIER_EXCEPTION_CONTACT")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class ExceptionContact extends WorkflowIdEntity{
private static final long serialVersionUID = 1L;
private String formNo;
private String inspectionFormNo;
private String inspectionId;
private String happenSpace;//发生地点
private String productStage;//产品阶段
private String billingArea;//开单区域
private String supplierName;//供应商
private String supplierCode;//
private String exceptionStage;//异常阶段
private String exceptionType;//异常类型
private String exceptionDegree;//异常程度
private String bomName;//品名
private String bomCode;//料号
private String materialType;//物料类别
private Date inspectionDate;//检验日期
private Double incomingAmount;//进料数
@Column(length=40)
private String units;//单位
private Double checkAmount;//抽检数
private String surfaceBad;//外观不良
private Double surfaceBadRate;//外观不良率
private String surfaceBadState;//外观状态
private String functionBad;//功能不良
private Double functionBadRate;//功能不良率
private String functionBadState;//功能状态
private String sizeBad;//尺寸不良
private Double sizeBadRate;//尺寸不良率
private String sizeBadState;//
private String featuresBad;//特性不良
private Double featuresBadRate;//特性不良率
private String featuresBadState;//特性状态
private String badDesc;//异常描述
private String descFile;//附件
private String inspector;//检验员,发起人
private String inspectorLog;
private Date sponsorDate;//发起日期
//主管审核问题描述
@Column(length=1000)
private String reportCheckOpinion;//意见
private String reportChecker;//审核人
private String reportCheckerLog;
private Date reportCheckDate;//
//MQE确认异常
@Column(length=1000)
private String mqeCheckOpinion;//意见
private String mqeChecker;//审核人
private String mqeCheckerLog;
private Date mqeCheckDate;//
private String isImprove;//是否需要发起sqe改进
//PMC意见
@Column(length=1000)
private String pmcOpinion;//pmc意见
private Date demandDeliveryPeriod;//需求交期
private String mrbApply;//mrb申请
private String mrbReportNo;//mrb单号
private String pmcChecker;//pmc审核人
private String pmcCheckerLog;
//MQE提供处理意见
@Column(length=1000)
private String qualityOpinion;//品质中心意见
private String sqeProcessOpinion;//处理意见
private String returnReportNo;//退货通知单单号
private String sqeMrbReportNo;//mrb单号
//MQE主管审核处理意见
@Column(length=1000)
private String mqeSupervisorOpinion;//MQE主管意见
private String mqeSupervisor;//审核人
private String mqeSupervisorLog;
private Date mqeSupervisorDate;//
//供应商回复内容
@Column(length=2000)
private String tempCountermeasures;//暂定对策实施
@Column(length=2000)
private String trueReasonCheck;//真因定义及验证
@Column(length=2000)
private String countermeasures;//永久对策实施
@Column(length=2000)
private String preventHappen;//预防再发生
@Column(length=2000)
private String supplierFile;//
private Date requestDate;//8d回复日期
//MQE确认改善报告
private String mqeComfirm;
private String mqeComfirmLog;
@Column(length=1000)
private String mqeComfirmOpinion;//MQE审核意见
private Date mqeComfirmDate;//
//MQE主管审核
@Column(length=1000)
private String mqeApprovalerOpinion;//MQE主管意见
private Date mqeApprovalerDate;//
private String mqeApprovaler;
private String mqeApprovalerLog;
//MQE追踪改善效果
private String checkResult;//效果确认
private Date sqeFinishDate;//sqe追踪完成时间
private Date checkResultDate;//确认日期
private String supplierEmail;//供应商邮箱地址
private String isClosed="否";//是否结案
private String isClosedAlaysis="否";//是否结案(用于统计)
private String isSupplier="否";//是否供应商回复
private String currentMan;//当前办理人
private String currentManLog;//当前办理人登录名
private String exceptionImproveId;//对应的异常矫正单id
private String exceptionImprovetNo;//对应的异常矫正单编号
//用于集成判断
private Long sourceId;//集成过来原ID
private String sourceUnit;//集成的事业部
public String getFormNo() {
return formNo;
}
public void setFormNo(String formNo) {
this.formNo = formNo;
}
public String getHappenSpace() {
return happenSpace;
}
public void setHappenSpace(String happenSpace) {
this.happenSpace = happenSpace;
}
public String getProductStage() {
return productStage;
}
public void setProductStage(String productStage) {
this.productStage = productStage;
}
public String getBillingArea() {
return billingArea;
}
public void setBillingArea(String billingArea) {
this.billingArea = billingArea;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public String getBomName() {
return bomName;
}
public void setBomName(String bomName) {
this.bomName = bomName;
}
public String getBomCode() {
return bomCode;
}
public void setBomCode(String bomCode) {
this.bomCode = bomCode;
}
public Date getInspectionDate() {
return inspectionDate;
}
public void setInspectionDate(Date inspectionDate) {
this.inspectionDate = inspectionDate;
}
public Double getIncomingAmount() {
return incomingAmount;
}
public void setIncomingAmount(Double incomingAmount) {
this.incomingAmount = incomingAmount;
}
public Double getCheckAmount() {
return checkAmount;
}
public void setCheckAmount(Double checkAmount) {
this.checkAmount = checkAmount;
}
public String getSurfaceBad() {
return surfaceBad;
}
public void setSurfaceBad(String surfaceBad) {
this.surfaceBad = surfaceBad;
}
public Double getSurfaceBadRate() {
return surfaceBadRate;
}
public void setSurfaceBadRate(Double surfaceBadRate) {
this.surfaceBadRate = surfaceBadRate;
}
public String getFunctionBad() {
return functionBad;
}
public void setFunctionBad(String functionBad) {
this.functionBad = functionBad;
}
public Double getFunctionBadRate() {
return functionBadRate;
}
public void setFunctionBadRate(Double functionBadRate) {
this.functionBadRate = functionBadRate;
}
public String getSizeBad() {
return sizeBad;
}
public void setSizeBad(String sizeBad) {
this.sizeBad = sizeBad;
}
public Double getSizeBadRate() {
return sizeBadRate;
}
public void setSizeBadRate(Double sizeBadRate) {
this.sizeBadRate = sizeBadRate;
}
public String getFeaturesBad() {
return featuresBad;
}
public void setFeaturesBad(String featuresBad) {
this.featuresBad = featuresBad;
}
public Double getFeaturesBadRate() {
return featuresBadRate;
}
public void setFeaturesBadRate(Double featuresBadRate) {
this.featuresBadRate = featuresBadRate;
}
public String getBadDesc() {
return badDesc;
}
public void setBadDesc(String badDesc) {
this.badDesc = badDesc;
}
public String getDescFile() {
return descFile;
}
public void setDescFile(String descFile) {
this.descFile = descFile;
}
public String getInspector() {
return inspector;
}
public void setInspector(String inspector) {
this.inspector = inspector;
}
public String getInspectorLog() {
return inspectorLog;
}
public void setInspectorLog(String inspectorLog) {
this.inspectorLog = inspectorLog;
}
public String getReportChecker() {
return reportChecker;
}
public void setReportChecker(String reportChecker) {
this.reportChecker = reportChecker;
}
public String getReportCheckerLog() {
return reportCheckerLog;
}
public void setReportCheckerLog(String reportCheckerLog) {
this.reportCheckerLog = reportCheckerLog;
}
public String getPmcOpinion() {
return pmcOpinion;
}
public void setPmcOpinion(String pmcOpinion) {
this.pmcOpinion = pmcOpinion;
}
public Date getDemandDeliveryPeriod() {
return demandDeliveryPeriod;
}
public void setDemandDeliveryPeriod(Date demandDeliveryPeriod) {
this.demandDeliveryPeriod = demandDeliveryPeriod;
}
public String getMrbApply() {
return mrbApply;
}
public void setMrbApply(String mrbApply) {
this.mrbApply = mrbApply;
}
public String getMrbReportNo() {
return mrbReportNo;
}
public void setMrbReportNo(String mrbReportNo) {
this.mrbReportNo = mrbReportNo;
}
public String getPmcChecker() {
return pmcChecker;
}
public void setPmcChecker(String pmcChecker) {
this.pmcChecker = pmcChecker;
}
public String getPmcCheckerLog() {
return pmcCheckerLog;
}
public void setPmcCheckerLog(String pmcCheckerLog) {
this.pmcCheckerLog = pmcCheckerLog;
}
public String getQualityOpinion() {
return qualityOpinion;
}
public void setQualityOpinion(String qualityOpinion) {
this.qualityOpinion = qualityOpinion;
}
public String getSqeProcessOpinion() {
return sqeProcessOpinion;
}
public void setSqeProcessOpinion(String sqeProcessOpinion) {
this.sqeProcessOpinion = sqeProcessOpinion;
}
public String getReturnReportNo() {
return returnReportNo;
}
public void setReturnReportNo(String returnReportNo) {
this.returnReportNo = returnReportNo;
}
public String getSqeMrbReportNo() {
return sqeMrbReportNo;
}
public void setSqeMrbReportNo(String sqeMrbReportNo) {
this.sqeMrbReportNo = sqeMrbReportNo;
}
public String getTempCountermeasures() {
return tempCountermeasures;
}
public void setTempCountermeasures(String tempCountermeasures) {
this.tempCountermeasures = tempCountermeasures;
}
public String getTrueReasonCheck() {
return trueReasonCheck;
}
public void setTrueReasonCheck(String trueReasonCheck) {
this.trueReasonCheck = trueReasonCheck;
}
public String getCountermeasures() {
return countermeasures;
}
public void setCountermeasures(String countermeasures) {
this.countermeasures = countermeasures;
}
public String getPreventHappen() {
return preventHappen;
}
public void setPreventHappen(String preventHappen) {
this.preventHappen = preventHappen;
}
public String getSupplierFile() {
return supplierFile;
}
public void setSupplierFile(String supplierFile) {
this.supplierFile = supplierFile;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public String getCheckResult() {
return checkResult;
}
public void setCheckResult(String checkResult) {
this.checkResult = checkResult;
}
public Date getSqeFinishDate() {
return sqeFinishDate;
}
public void setSqeFinishDate(Date sqeFinishDate) {
this.sqeFinishDate = sqeFinishDate;
}
public String getMaterialType() {
return materialType;
}
public void setMaterialType(String materialType) {
this.materialType = materialType;
}
public String getSupplierCode() {
return supplierCode;
}
public void setSupplierCode(String supplierCode) {
this.supplierCode = supplierCode;
}
public String getSupplierEmail() {
return supplierEmail;
}
public void setSupplierEmail(String supplierEmail) {
this.supplierEmail = supplierEmail;
}
public String getSurfaceBadState() {
return surfaceBadState;
}
public void setSurfaceBadState(String surfaceBadState) {
this.surfaceBadState = surfaceBadState;
}
public String getFunctionBadState() {
return functionBadState;
}
public void setFunctionBadState(String functionBadState) {
this.functionBadState = functionBadState;
}
public String getSizeBadState() {
return sizeBadState;
}
public void setSizeBadState(String sizeBadState) {
this.sizeBadState = sizeBadState;
}
public String getFeaturesBadState() {
return featuresBadState;
}
public void setFeaturesBadState(String featuresBadState) {
this.featuresBadState = featuresBadState;
}
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public String getInspectionFormNo() {
return inspectionFormNo;
}
public void setInspectionFormNo(String inspectionFormNo) {
this.inspectionFormNo = inspectionFormNo;
}
public String getInspectionId() {
return inspectionId;
}
public void setInspectionId(String inspectionId) {
this.inspectionId = inspectionId;
}
public String getIsClosed() {
return isClosed;
}
public void setIsClosed(String isClosed) {
this.isClosed = isClosed;
}
public String getIsClosedAlaysis() {
return isClosedAlaysis;
}
public void setIsClosedAlaysis(String isClosedAlaysis) {
this.isClosedAlaysis = isClosedAlaysis;
}
public String getIsSupplier() {
return isSupplier;
}
public void setIsSupplier(String isSupplier) {
this.isSupplier = isSupplier;
}
public String getCurrentMan() {
return currentMan;
}
public void setCurrentMan(String currentMan) {
this.currentMan = currentMan;
}
public String getCurrentManLog() {
return currentManLog;
}
public void setCurrentManLog(String currentManLog) {
this.currentManLog = currentManLog;
}
public String getExceptionType() {
return exceptionType;
}
public void setExceptionType(String exceptionType) {
this.exceptionType = exceptionType;
}
public Date getSponsorDate() {
return sponsorDate;
}
public void setSponsorDate(Date sponsorDate) {
this.sponsorDate = sponsorDate;
}
public String getReportCheckOpinion() {
return reportCheckOpinion;
}
public void setReportCheckOpinion(String reportCheckOpinion) {
this.reportCheckOpinion = reportCheckOpinion;
}
public Date getReportCheckDate() {
return reportCheckDate;
}
public void setReportCheckDate(Date reportCheckDate) {
this.reportCheckDate = reportCheckDate;
}
public String getMqeCheckOpinion() {
return mqeCheckOpinion;
}
public void setMqeCheckOpinion(String mqeCheckOpinion) {
this.mqeCheckOpinion = mqeCheckOpinion;
}
public String getMqeChecker() {
return mqeChecker;
}
public void setMqeChecker(String mqeChecker) {
this.mqeChecker = mqeChecker;
}
public String getMqeCheckerLog() {
return mqeCheckerLog;
}
public void setMqeCheckerLog(String mqeCheckerLog) {
this.mqeCheckerLog = mqeCheckerLog;
}
public Date getMqeCheckDate() {
return mqeCheckDate;
}
public void setMqeCheckDate(Date mqeCheckDate) {
this.mqeCheckDate = mqeCheckDate;
}
public String getMqeSupervisorOpinion() {
return mqeSupervisorOpinion;
}
public void setMqeSupervisorOpinion(String mqeSupervisorOpinion) {
this.mqeSupervisorOpinion = mqeSupervisorOpinion;
}
public String getMqeSupervisor() {
return mqeSupervisor;
}
public void setMqeSupervisor(String mqeSupervisor) {
this.mqeSupervisor = mqeSupervisor;
}
public String getMqeSupervisorLog() {
return mqeSupervisorLog;
}
public void setMqeSupervisorLog(String mqeSupervisorLog) {
this.mqeSupervisorLog = mqeSupervisorLog;
}
public Date getMqeSupervisorDate() {
return mqeSupervisorDate;
}
public void setMqeSupervisorDate(Date mqeSupervisorDate) {
this.mqeSupervisorDate = mqeSupervisorDate;
}
public Date getCheckResultDate() {
return checkResultDate;
}
public void setCheckResultDate(Date checkResultDate) {
this.checkResultDate = checkResultDate;
}
public String getExceptionImproveId() {
return exceptionImproveId;
}
public void setExceptionImproveId(String exceptionImproveId) {
this.exceptionImproveId = exceptionImproveId;
}
public String getExceptionImprovetNo() {
return exceptionImprovetNo;
}
public void setExceptionImprovetNo(String exceptionImprovetNo) {
this.exceptionImprovetNo = exceptionImprovetNo;
}
public String getExceptionStage() {
return exceptionStage;
}
public void setExceptionStage(String exceptionStage) {
this.exceptionStage = exceptionStage;
}
public String getExceptionDegree() {
return exceptionDegree;
}
public void setExceptionDegree(String exceptionDegree) {
this.exceptionDegree = exceptionDegree;
}
public String getIsImprove() {
return isImprove;
}
public void setIsImprove(String isImprove) {
this.isImprove = isImprove;
}
public String getMqeComfirmOpinion() {
return mqeComfirmOpinion;
}
public void setMqeComfirmOpinion(String mqeComfirmOpinion) {
this.mqeComfirmOpinion = mqeComfirmOpinion;
}
public Date getMqeComfirmDate() {
return mqeComfirmDate;
}
public void setMqeComfirmDate(Date mqeComfirmDate) {
this.mqeComfirmDate = mqeComfirmDate;
}
public String getMqeApprovalerOpinion() {
return mqeApprovalerOpinion;
}
public void setMqeApprovalerOpinion(String mqeApprovalerOpinion) {
this.mqeApprovalerOpinion = mqeApprovalerOpinion;
}
public Date getMqeApprovalerDate() {
return mqeApprovalerDate;
}
public void setMqeApprovalerDate(Date mqeApprovalerDate) {
this.mqeApprovalerDate = mqeApprovalerDate;
}
public Long getSourceId() {
return sourceId;
}
public void setSourceId(Long sourceId) {
this.sourceId = sourceId;
}
public String getSourceUnit() {
return sourceUnit;
}
public void setSourceUnit(String sourceUnit) {
this.sourceUnit = sourceUnit;
}
public String getMqeComfirm() {
return mqeComfirm;
}
public void setMqeComfirm(String mqeComfirm) {
this.mqeComfirm = mqeComfirm;
}
public String getMqeComfirmLog() {
return mqeComfirmLog;
}
public void setMqeComfirmLog(String mqeComfirmLog) {
this.mqeComfirmLog = mqeComfirmLog;
}
public String getMqeApprovaler() {
return mqeApprovaler;
}
public void setMqeApprovaler(String mqeApprovaler) {
this.mqeApprovaler = mqeApprovaler;
}
public String getMqeApprovalerLog() {
return mqeApprovalerLog;
}
public void setMqeApprovalerLog(String mqeApprovalerLog) {
this.mqeApprovalerLog = mqeApprovalerLog;
}
}
| 18,078 | 0.774842 | 0.771848 | 655 | 25.519083 | 18.197454 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.636641 | false | false | 4 |
8f4945473475b8290532598a101a197ad2ffe1c5 | 26,585,847,595,456 | 76386f86e49d67802ac4dc2634803ef295d90915 | /src/java/com/netflix/ice/tag/ResourceGroup.java | 179aced4dae91b2649c6e780d5af047fb1c07517 | [
"Apache-2.0"
]
| permissive | bulbulas/ice | https://github.com/bulbulas/ice | 7a57e06e7ff44cf0403f1fd83e8b2dcfe1927b1a | de83238f093c679d2472c0ac398d6c411a0fcd4a | refs/heads/master | 2021-01-15T08:37:28.866000 | 2015-08-02T23:15:09 | 2015-08-02T23:15:09 | 39,225,981 | 0 | 0 | null | true | 2015-08-02T23:15:09 | 2015-07-16T23:53:28 | 2015-07-16T23:53:31 | 2015-08-02T23:15:09 | 2,620 | 0 | 0 | 0 | Java | null | null | /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.ice.tag;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class ResourceGroup extends Tag {
private ResourceGroup (String name) {
super(name);
}
private static ConcurrentMap<String, ResourceGroup> resourceGroups = Maps.newConcurrentMap();
private final static Logger logger = LoggerFactory.getLogger(ResourceGroup.class);
public static ResourceGroup getResourceGroup(String name) {
ResourceGroup resourceGroup = resourceGroups.get(name);
if (resourceGroup == null) {
resourceGroups.putIfAbsent(name, new ResourceGroup(name));
resourceGroup = resourceGroups.get(name);
}
return resourceGroup;
}
public static List<ResourceGroup> getResourceGroups(List<String> names) {
List<ResourceGroup> result = Lists.newArrayList();
if (names != null) {
for (String name: names) {
ResourceGroup resourceGroup = resourceGroups.get(name);
if (resourceGroup != null)
result.add(resourceGroup);
}
}
return result;
}
public static List<ResourceGroup> searchResourceGroups(List<String> names) {
List<ResourceGroup> result = Lists.newArrayList();
if (names != null) {
for (String name: names) {
Pattern p = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
for(String key: resourceGroups.keySet()) {
// logger.info("Matching |" + key + "|.|" + name + "|");
if (p.matcher(key).find()) {
result.add(resourceGroups.get(key));
}
}
}
}
return result;
}
}
| UTF-8 | Java | 2,591 | java | ResourceGroup.java | Java | [
{
"context": "/*\n *\n * Copyright 2013 Netflix, Inc.\n *\n * Licensed under the Apache Lic",
"end": 28,
"score": 0.951641321182251,
"start": 25,
"tag": "NAME",
"value": "Net"
}
]
| null | []
| /*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.ice.tag;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class ResourceGroup extends Tag {
private ResourceGroup (String name) {
super(name);
}
private static ConcurrentMap<String, ResourceGroup> resourceGroups = Maps.newConcurrentMap();
private final static Logger logger = LoggerFactory.getLogger(ResourceGroup.class);
public static ResourceGroup getResourceGroup(String name) {
ResourceGroup resourceGroup = resourceGroups.get(name);
if (resourceGroup == null) {
resourceGroups.putIfAbsent(name, new ResourceGroup(name));
resourceGroup = resourceGroups.get(name);
}
return resourceGroup;
}
public static List<ResourceGroup> getResourceGroups(List<String> names) {
List<ResourceGroup> result = Lists.newArrayList();
if (names != null) {
for (String name: names) {
ResourceGroup resourceGroup = resourceGroups.get(name);
if (resourceGroup != null)
result.add(resourceGroup);
}
}
return result;
}
public static List<ResourceGroup> searchResourceGroups(List<String> names) {
List<ResourceGroup> result = Lists.newArrayList();
if (names != null) {
for (String name: names) {
Pattern p = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
for(String key: resourceGroups.keySet()) {
// logger.info("Matching |" + key + "|.|" + name + "|");
if (p.matcher(key).find()) {
result.add(resourceGroups.get(key));
}
}
}
}
return result;
}
}
| 2,591 | 0.626013 | 0.622154 | 74 | 34.013512 | 27.621717 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
bf15a4df9c5f9b0577019a9093193b2f45a65b19 | 4,372,276,767,364 | 4e6f144c27892ff81d37ac57f651fd7d7b430497 | /src/module-info.java | bc7f1960f4bdfc6ac623022ee093836a86c79b6b | []
| no_license | Mhasan88/Java_Code | https://github.com/Mhasan88/Java_Code | 7734470c3dc32b6f12107c2f7529711b45cf1be4 | ae0bec22463ad47b8844a84d7998dbe70cc58cb7 | refs/heads/master | 2023-04-23T08:51:02.628000 | 2021-05-18T14:57:48 | 2021-05-18T14:57:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | module All_Java_Code {
} | UTF-8 | Java | 24 | java | module-info.java | Java | []
| null | []
| module All_Java_Code {
} | 24 | 0.708333 | 0.708333 | 2 | 11.5 | 10.5 | 22 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 4 |
29382d7c285c92c11308e96ec721c8df2681fbb3 | 6,622,839,625,319 | f69c50ad4eaf5315c7e19eaa1299537dadd69425 | /src/Node.java | b34f32e917983f5d0f238cd8c524fee9861a1fe5 | []
| no_license | Harikabukkap/PriorityBasedRetrievalSystem | https://github.com/Harikabukkap/PriorityBasedRetrievalSystem | 3b916c2c00cb2a4898a1f4ea8498cebb6a0182eb | 957823e56be4a7b3b84a3b7c044c49fb549897be | refs/heads/master | 2021-01-21T06:21:03.432000 | 2017-02-23T00:00:19 | 2017-02-23T00:00:19 | 82,864,179 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Node Class
*/
public class Node {
/**********VARIABLES**********/
// Frequency of hashtag
int key;
// Degree of node
int degree;
// Hashtag
String tag;
// Parent of node
Node parent;
// Child of node
Node child;
// Previous node
Node prev;
// Next node
Node next;
// childCut value of node
boolean childCut;
/**********METHODS**********/
/*
Method: Node(constructor)
Parm: int key & String tag
Description: Node class constructor which initializes the class variables with the passed parameters if any
Return value: None
*/
public Node(int key, String tag) {
this.key = key;
this.tag = tag;
next = this;
prev = this;
child = null;
parent = null;
this.degree = 0;
}
/*
Method: compare
Parm: Node other
Description: Compares the key values of this and other node.
Return value: -1 if this.key < other.key, 0 if this.key = other.key and 1 if this.key > other.key
*/
public int compare(Node other) {
if (this.key == other.key)
return 0;
else if (this.key > other.key)
return 1;
else return -1;
}
}
| UTF-8 | Java | 1,355 | java | Node.java | Java | []
| null | []
| /*
* Node Class
*/
public class Node {
/**********VARIABLES**********/
// Frequency of hashtag
int key;
// Degree of node
int degree;
// Hashtag
String tag;
// Parent of node
Node parent;
// Child of node
Node child;
// Previous node
Node prev;
// Next node
Node next;
// childCut value of node
boolean childCut;
/**********METHODS**********/
/*
Method: Node(constructor)
Parm: int key & String tag
Description: Node class constructor which initializes the class variables with the passed parameters if any
Return value: None
*/
public Node(int key, String tag) {
this.key = key;
this.tag = tag;
next = this;
prev = this;
child = null;
parent = null;
this.degree = 0;
}
/*
Method: compare
Parm: Node other
Description: Compares the key values of this and other node.
Return value: -1 if this.key < other.key, 0 if this.key = other.key and 1 if this.key > other.key
*/
public int compare(Node other) {
if (this.key == other.key)
return 0;
else if (this.key > other.key)
return 1;
else return -1;
}
}
| 1,355 | 0.503321 | 0.498155 | 59 | 21.966103 | 19.81522 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.338983 | false | false | 4 |
1b1595916bd91d07bed66b06a9606d9704f769ae | 8,753,143,387,216 | b1a414e38a03e5051b92edfb406b8e870e361e2b | /src/main/java/ec/edu/ups/modelo/CuentaDeAhorro.java | 71f187e7ead8b1413d5cd1d942ba5c32f6a5ea78 | []
| no_license | jessicanauta/ProyectoFinalPoliza | https://github.com/jessicanauta/ProyectoFinalPoliza | f3f27265a740fa0af89201d105a2edd4949ffca5 | b93664020c7e981d25f8e0d0367ae70d90ba8c95 | refs/heads/master | 2023-03-09T09:56:06.964000 | 2021-02-18T03:11:37 | 2021-02-18T03:11:37 | 334,754,092 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ec.edu.ups.modelo;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/**
* Esta clase representa una entidad o tabla llamada CuentaDeAhorro de la base de datos y sus columnas
*
*/
@Entity
public class CuentaDeAhorro implements Serializable {
//Atributos de la clase
@Id
@Column(name="numero_cuenta")
private String numeroCuentaDeAhorro;
private Date fechaDeRegistro;
private Double saldoCuentaDeAhorro;
private String tipo;
@OneToOne(fetch = FetchType.EAGER,cascade = {CascadeType.ALL })
@JoinColumn(name="cedula_cliente")
private Cliente cliente;
/**
* Constructor de la clase
*/
public CuentaDeAhorro() {
}
/**
* Metodo que permite obtener el atributo numeroCuentaDeAhorro
* @return El atributo numeroCuentaDeAhorro de esta clase
*/
public String getNumeroCuentaDeAhorro() {
return numeroCuentaDeAhorro;
}
/**
* Metodo que permite asignarle un valor al atributo numeroCuentaDeAhorro
* @param numeroCuentaDeAhorro Variable que se asigna al atributo
*/
public void setNumeroCuentaDeAhorro(String numeroCuentaDeAhorro) {
this.numeroCuentaDeAhorro = numeroCuentaDeAhorro;
}
/**
* Metodo que permite obtener el atributo fechaDeRegistro
* @return El atributo fechaDeRegistro de esta clase
*/
public Date getFechaDeRegistro() {
return fechaDeRegistro;
}
/**
* Metodo que permite asignarle un valor al atributo fechaRegistro
* @param fechaDeRegistro Variable que se asigna al atributo
*/
public void setFechaDeRegistro(Date fechaDeRegistro) {
this.fechaDeRegistro = fechaDeRegistro;
}
/**
* Metodo que permite obtener el atributo saldoCuentaDeAhorro
* @return El atributo saldoCuentaDeAhorro de esta clase
*/
public Double getSaldoCuentaDeAhorro() {
return saldoCuentaDeAhorro;
}
/**
* Metodo que permite asignarle un valor al atributo saldoCuentaDeAhorro
* @param saldoCuentaDeAhorro Variable que se asigna al atributo
*/
public void setSaldoCuentaDeAhorro(Double saldoCuentaDeAhorro) {
this.saldoCuentaDeAhorro = saldoCuentaDeAhorro;
}
/**
* Metodo que permite obtener el atributo cliente
* @return El atributo cliente de esta clase
*/
public Cliente getCliente() {
return cliente;
}
/**
* Metodo que permite asignarle un valor al atributo cliente
* @param cliente Variable que se asigna al atributo
*/
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
| UTF-8 | Java | 2,789 | java | CuentaDeAhorro.java | Java | [
{
"context": ",cascade = {CascadeType.ALL })\n\t@JoinColumn(name=\"cedula_cliente\")\n\tprivate Cliente cliente;\n\t\n\t/** \n\t * Construct",
"end": 792,
"score": 0.9776312112808228,
"start": 778,
"tag": "USERNAME",
"value": "cedula_cliente"
}
]
| null | []
| package ec.edu.ups.modelo;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/**
* Esta clase representa una entidad o tabla llamada CuentaDeAhorro de la base de datos y sus columnas
*
*/
@Entity
public class CuentaDeAhorro implements Serializable {
//Atributos de la clase
@Id
@Column(name="numero_cuenta")
private String numeroCuentaDeAhorro;
private Date fechaDeRegistro;
private Double saldoCuentaDeAhorro;
private String tipo;
@OneToOne(fetch = FetchType.EAGER,cascade = {CascadeType.ALL })
@JoinColumn(name="cedula_cliente")
private Cliente cliente;
/**
* Constructor de la clase
*/
public CuentaDeAhorro() {
}
/**
* Metodo que permite obtener el atributo numeroCuentaDeAhorro
* @return El atributo numeroCuentaDeAhorro de esta clase
*/
public String getNumeroCuentaDeAhorro() {
return numeroCuentaDeAhorro;
}
/**
* Metodo que permite asignarle un valor al atributo numeroCuentaDeAhorro
* @param numeroCuentaDeAhorro Variable que se asigna al atributo
*/
public void setNumeroCuentaDeAhorro(String numeroCuentaDeAhorro) {
this.numeroCuentaDeAhorro = numeroCuentaDeAhorro;
}
/**
* Metodo que permite obtener el atributo fechaDeRegistro
* @return El atributo fechaDeRegistro de esta clase
*/
public Date getFechaDeRegistro() {
return fechaDeRegistro;
}
/**
* Metodo que permite asignarle un valor al atributo fechaRegistro
* @param fechaDeRegistro Variable que se asigna al atributo
*/
public void setFechaDeRegistro(Date fechaDeRegistro) {
this.fechaDeRegistro = fechaDeRegistro;
}
/**
* Metodo que permite obtener el atributo saldoCuentaDeAhorro
* @return El atributo saldoCuentaDeAhorro de esta clase
*/
public Double getSaldoCuentaDeAhorro() {
return saldoCuentaDeAhorro;
}
/**
* Metodo que permite asignarle un valor al atributo saldoCuentaDeAhorro
* @param saldoCuentaDeAhorro Variable que se asigna al atributo
*/
public void setSaldoCuentaDeAhorro(Double saldoCuentaDeAhorro) {
this.saldoCuentaDeAhorro = saldoCuentaDeAhorro;
}
/**
* Metodo que permite obtener el atributo cliente
* @return El atributo cliente de esta clase
*/
public Cliente getCliente() {
return cliente;
}
/**
* Metodo que permite asignarle un valor al atributo cliente
* @param cliente Variable que se asigna al atributo
*/
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
| 2,789 | 0.74758 | 0.74758 | 112 | 23.892857 | 23.826889 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 4 |
b4861f225562c350d234e088a0c17bde401e1d2f | 11,622,181,543,894 | c15a06577678223d68b7b4eeb8f27fb99b7aeb9e | /springboot-start/src/main/java/org/ilmostro/start/controller/RequestContextHolderController.java | 16a7d66e084c5b59329e1b8d90a709c97c094cd9 | [
"ICU",
"MIT"
]
| permissive | MacleZhou/java-tutorial | https://github.com/MacleZhou/java-tutorial | 6fa33b9e7ac5b4f81e5330c9f1e114350b71853b | 245f47dcedc16f65f12f2c132af22da21d5bf7f8 | refs/heads/master | 2023-02-03T12:20:37.887000 | 2020-12-24T07:55:44 | 2020-12-24T07:55:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ilmostro.start.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author li.bowei
* @date 2020/8/14 10:45
*/
@RestController
@RequestMapping("")
@Slf4j
public class RequestContextHolderController {
private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
10, 10000, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
@GetMapping("/thread")
public void simple(String name) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.setAttribute("name", name);
RequestContextHolder.setRequestAttributes(requestAttributes, true);
log.info("main thread sessionId:{}", request.getRequestedSessionId());
List<CompletableFuture> futures = new LinkedList<>();
for (int i = 0; i < 10; i++) {
futures.add(CompletableFuture.runAsync(RequestContextHolderController::test, executor));
}
CompletableFuture[] wait = new CompletableFuture[futures.size()];
for (int i = 0; i < futures.size(); i++) {
wait[i] = futures.get(i);
}
CompletableFuture.allOf(wait).join();
}
public static void test() {
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
log.info("current thread name:{}, sessionId:{}, attr:{}", Thread.currentThread().getName(), request.getRequestedSessionId(), request.getAttribute("name"));
}
}
| UTF-8 | Java | 2,349 | java | RequestContextHolderController.java | Java | [
{
"context": "ort java.util.concurrent.TimeUnit;\n\n/**\n * @author li.bowei\n * @date 2020/8/14 10:45\n */\n@RestController\n@Req",
"end": 771,
"score": 0.9973981380462646,
"start": 763,
"tag": "NAME",
"value": "li.bowei"
}
]
| null | []
| package org.ilmostro.start.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author li.bowei
* @date 2020/8/14 10:45
*/
@RestController
@RequestMapping("")
@Slf4j
public class RequestContextHolderController {
private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
10, 10000, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
@GetMapping("/thread")
public void simple(String name) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.setAttribute("name", name);
RequestContextHolder.setRequestAttributes(requestAttributes, true);
log.info("main thread sessionId:{}", request.getRequestedSessionId());
List<CompletableFuture> futures = new LinkedList<>();
for (int i = 0; i < 10; i++) {
futures.add(CompletableFuture.runAsync(RequestContextHolderController::test, executor));
}
CompletableFuture[] wait = new CompletableFuture[futures.size()];
for (int i = 0; i < futures.size(); i++) {
wait[i] = futures.get(i);
}
CompletableFuture.allOf(wait).join();
}
public static void test() {
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
log.info("current thread name:{}, sessionId:{}, attr:{}", Thread.currentThread().getName(), request.getRequestedSessionId(), request.getAttribute("name"));
}
}
| 2,349 | 0.742869 | 0.731801 | 56 | 40.94643 | 37.70488 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.821429 | false | false | 4 |
025602dafdb5cedbd9eeb1c1f80e7498076380cd | 30,786,325,616,682 | c8f96e8c960a39a055e3ba64ae5c07b615e8ac13 | /gym-vip/src/main/java/com/jm/vip/entity/BaseEntity.java | fde6a9e2c8fcdc0e8767a343234908052df0f757 | []
| no_license | fengzhentian/GymVipManages | https://github.com/fengzhentian/GymVipManages | beb82b9d70baaed56cdad38a1a377880ffc7c3c8 | 5efb3432d81e3c5c0160e43ccc2415a21f459aa5 | refs/heads/master | 2021-01-19T22:49:05.979000 | 2017-10-27T02:35:06 | 2017-10-27T02:35:06 | 88,861,989 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jm.vip.entity;
import java.util.Date;
public class BaseEntity {
private String creator;
private String creationId;
private Date creationTime;
private String modifier;
private String modificationId;
private Date modificationTime;
private String logicDelete;
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator == null ? null : creator.trim();
}
public String getCreationId() {
return creationId;
}
public void setCreationId(String creationId) {
this.creationId = creationId == null ? null : creationId.trim();
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public String getModifier() {
return modifier;
}
public void setModifier(String modifier) {
this.modifier = modifier == null ? null : modifier.trim();
}
public String getModificationId() {
return modificationId;
}
public void setModificationId(String modificationId) {
this.modificationId = modificationId == null ? null : modificationId
.trim();
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
public String getLogicDelete() {
return logicDelete;
}
public void setLogicDelete(String logicDelete) {
this.logicDelete = logicDelete == null ? null : logicDelete.trim();
}
}
| UTF-8 | Java | 1,779 | java | BaseEntity.java | Java | []
| null | []
| package com.jm.vip.entity;
import java.util.Date;
public class BaseEntity {
private String creator;
private String creationId;
private Date creationTime;
private String modifier;
private String modificationId;
private Date modificationTime;
private String logicDelete;
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator == null ? null : creator.trim();
}
public String getCreationId() {
return creationId;
}
public void setCreationId(String creationId) {
this.creationId = creationId == null ? null : creationId.trim();
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public String getModifier() {
return modifier;
}
public void setModifier(String modifier) {
this.modifier = modifier == null ? null : modifier.trim();
}
public String getModificationId() {
return modificationId;
}
public void setModificationId(String modificationId) {
this.modificationId = modificationId == null ? null : modificationId
.trim();
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
public String getLogicDelete() {
return logicDelete;
}
public void setLogicDelete(String logicDelete) {
this.logicDelete = logicDelete == null ? null : logicDelete.trim();
}
}
| 1,779 | 0.620011 | 0.620011 | 77 | 21.103895 | 21.932354 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.298701 | false | false | 4 |
9b38dfded5218d893492caaf64d8097e3f542795 | 4,784,593,618,049 | 81cad335bb6877bbd5ed7d9376ab686bce96866f | /src/main/java/com/freight/ms/dao/CouponRelationMapper.java | cbfdecd2048b1f65fea913b19cddd5382a63d024 | []
| no_license | sophiacode/FreightMS | https://github.com/sophiacode/FreightMS | 8760053a612be43ca15f3b523a7aa36e7374db63 | 9c40860f849e41c9464fbb249003703c1b059502 | refs/heads/master | 2020-03-09T05:00:14.580000 | 2018-05-30T16:10:43 | 2018-05-30T16:10:43 | 124,624,200 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.freight.ms.dao;
import com.freight.ms.model.CouponRelation;
public interface CouponRelationMapper {
/**
* 根据主键删除数据库的记录
*
* @param id
*/
int deleteByPrimaryKey(Integer id);
/**
* 插入数据库记录
*
* @param record
*/
int insert(CouponRelation record);
/**
* 插入数据库记录
*
* @param record
*/
int insertSelective(CouponRelation record);
/**
* 根据主键获取一条数据库记录
*
* @param id
*/
CouponRelation selectByPrimaryKey(Integer id);
/**
* 根据主键来更新部分数据库记录
*
* @param record
*/
int updateByPrimaryKeySelective(CouponRelation record);
/**
* 根据主键来更新数据库记录
*
* @param record
*/
int updateByPrimaryKey(CouponRelation record);
} | UTF-8 | Java | 908 | java | CouponRelationMapper.java | Java | []
| null | []
| package com.freight.ms.dao;
import com.freight.ms.model.CouponRelation;
public interface CouponRelationMapper {
/**
* 根据主键删除数据库的记录
*
* @param id
*/
int deleteByPrimaryKey(Integer id);
/**
* 插入数据库记录
*
* @param record
*/
int insert(CouponRelation record);
/**
* 插入数据库记录
*
* @param record
*/
int insertSelective(CouponRelation record);
/**
* 根据主键获取一条数据库记录
*
* @param id
*/
CouponRelation selectByPrimaryKey(Integer id);
/**
* 根据主键来更新部分数据库记录
*
* @param record
*/
int updateByPrimaryKeySelective(CouponRelation record);
/**
* 根据主键来更新数据库记录
*
* @param record
*/
int updateByPrimaryKey(CouponRelation record);
} | 908 | 0.573265 | 0.573265 | 47 | 15.574468 | 15.454455 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.170213 | false | false | 4 |
6fcac20f889aae47b181d3cab750c37a56ea1a61 | 12,111,807,823,472 | 73b8bac2775aff45ec0414616414919a97c92dd1 | /01_daili/src/com/cpp/jdk/IosmServiceImpo.java | 8fb2a33f16c36429ee7941c665fb91dd3d1c94ac | []
| no_license | cp199326/mybatis | https://github.com/cp199326/mybatis | 7d3b02c2b114695bfb7a0ffd3b198730d010e6e6 | 696eb548f155a0afa28e02bfdf9be3b3fda07356 | refs/heads/master | 2019-06-16T06:53:20.781000 | 2017-07-29T13:14:29 | 2017-07-29T13:14:29 | 98,732,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cpp.jdk;
public interface IosmServiceImpo {
public String doForter();
public void doSecen();
}
| UTF-8 | Java | 112 | java | IosmServiceImpo.java | Java | []
| null | []
| package com.cpp.jdk;
public interface IosmServiceImpo {
public String doForter();
public void doSecen();
}
| 112 | 0.741071 | 0.741071 | 6 | 17.666666 | 12.840907 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
1afcd80156e372079ec0cb0d3b4bc36b12f2cf44 | 18,691,697,720,568 | 3b12549e4397258ba290c43901a6a384db613e5a | /siyueli-platform-member-server-client/src/main/java/com/siyueli/platform/service/member/client/callback/permission/UserRoleFallBack.java | e86f30b31648e5bbbba92d7c46c783abce5ce0d7 | []
| no_license | zhouxhhn/li-member | https://github.com/zhouxhhn/li-member | 56fc91fa5e089fe3aee9e7519a1b4f4a98c539bd | 54155482e60a364fd04d07fb39b17a39b4f95a6d | refs/heads/master | 2020-04-05T10:25:31.586000 | 2018-11-09T02:25:07 | 2018-11-09T02:25:07 | 156,798,261 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.siyueli.platform.service.member.client.callback.permission;
import cn.siyue.platform.base.ResponseData;
import com.siyueli.platform.member.common.PageResponse;
import com.siyueli.platform.member.request.*;
import com.siyueli.platform.member.response.UserRoleVo;
import com.siyueli.platform.service.member.client.callback.BaseServiceFallBack;
import com.siyueli.platform.service.member.client.service.permission.UserRoleClient;
import org.springframework.stereotype.Component;
@Component
public class UserRoleFallBack extends BaseServiceFallBack implements UserRoleClient {
@Override
public ResponseData add(UserRoleAddRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData update(UserRoleUpdateRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData<UserRoleVo> get(UserRoleGetRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData<PageResponse<UserRoleVo>> search(UserRoleSearchRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData delete(UserRoleDeleteRequest requestParam) {
return getDownGradeResponse();
}
}
| UTF-8 | Java | 1,259 | java | UserRoleFallBack.java | Java | []
| null | []
| package com.siyueli.platform.service.member.client.callback.permission;
import cn.siyue.platform.base.ResponseData;
import com.siyueli.platform.member.common.PageResponse;
import com.siyueli.platform.member.request.*;
import com.siyueli.platform.member.response.UserRoleVo;
import com.siyueli.platform.service.member.client.callback.BaseServiceFallBack;
import com.siyueli.platform.service.member.client.service.permission.UserRoleClient;
import org.springframework.stereotype.Component;
@Component
public class UserRoleFallBack extends BaseServiceFallBack implements UserRoleClient {
@Override
public ResponseData add(UserRoleAddRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData update(UserRoleUpdateRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData<UserRoleVo> get(UserRoleGetRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData<PageResponse<UserRoleVo>> search(UserRoleSearchRequest requestParam) {
return getDownGradeResponse();
}
@Override
public ResponseData delete(UserRoleDeleteRequest requestParam) {
return getDownGradeResponse();
}
}
| 1,259 | 0.778396 | 0.778396 | 37 | 33.027027 | 29.921959 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.351351 | false | false | 4 |
83b2489f50be93ae3be7ca4ad318b1b2ca2e25be | 31,645,319,099,507 | 65cdb95907d17de5dcf7e4a3f64886b94f70da20 | /src/main/java/com/meihua/web/LoginController.java | 7634429526467c777fb22550670cf48ab9e0b266 | []
| no_license | hgdhzy/meihua-votee | https://github.com/hgdhzy/meihua-votee | 57063b853e476d843944759da8a22c2361f9d6e0 | 50158cd11f6fa0e28e9d91d9a3e830334f63bbbf | refs/heads/master | 2021-07-18T09:48:15.709000 | 2017-10-25T18:29:18 | 2017-10-25T18:29:18 | 108,308,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.meihua.web;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.meihua.constants.Constant;
import com.meihua.constants.MessageConstant;
import com.meihua.domain.BaseResult;
import com.meihua.domain.LoginResult;
import com.meihua.domain.ResultSuccess;
import com.meihua.service.LoginService;
/**
*
*
* @author HanZhiyuan
*/
@RestController
public class LoginController {
@Autowired
LoginService loginService;
/**
* 登录
*
* @param username
* 用户名(即登录编号)
* @param password
* 密码
* @return 登陆结果
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public BaseResult login(@RequestParam Map<String, String> requestMap) {
String tenantId = requestMap.get("tenantid");
String code = requestMap.get("username");
LoginResult userInfo = loginService.getUserInfo(tenantId, code);
ResultSuccess<LoginResult> resultSuccess = new ResultSuccess<LoginResult>();
resultSuccess.setResult_code(Constant.RESULT_CODE_SUCCESS);
resultSuccess.setMessage(MessageConstant.INFO_0003);
resultSuccess.setResult(userInfo);
return resultSuccess;
}
}
| UTF-8 | Java | 1,444 | java | LoginController.java | Java | [
{
"context": "eihua.service.LoginService;\n\n/**\n *\n * \n * @author HanZhiyuan\n */\n@RestController\npublic class LoginCont",
"end": 625,
"score": 0.5373643636703491,
"start": 622,
"tag": "USERNAME",
"value": "Han"
},
{
"context": "a.service.LoginService;\n\n/**\n *\n * \n * @author HanZhiyuan\n */\n@RestController\npublic class LoginController ",
"end": 632,
"score": 0.7580858469009399,
"start": 625,
"tag": "NAME",
"value": "Zhiyuan"
},
{
"context": " 用户名(即登录编号)\n\t * @param password\n\t * 密码\n\t * @return 登陆结果\n\t */\n\t@RequestMapping(value = \"/",
"end": 826,
"score": 0.9136325716972351,
"start": 824,
"tag": "PASSWORD",
"value": "密码"
}
]
| null | []
| package com.meihua.web;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.meihua.constants.Constant;
import com.meihua.constants.MessageConstant;
import com.meihua.domain.BaseResult;
import com.meihua.domain.LoginResult;
import com.meihua.domain.ResultSuccess;
import com.meihua.service.LoginService;
/**
*
*
* @author HanZhiyuan
*/
@RestController
public class LoginController {
@Autowired
LoginService loginService;
/**
* 登录
*
* @param username
* 用户名(即登录编号)
* @param password
* 密码
* @return 登陆结果
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public BaseResult login(@RequestParam Map<String, String> requestMap) {
String tenantId = requestMap.get("tenantid");
String code = requestMap.get("username");
LoginResult userInfo = loginService.getUserInfo(tenantId, code);
ResultSuccess<LoginResult> resultSuccess = new ResultSuccess<LoginResult>();
resultSuccess.setResult_code(Constant.RESULT_CODE_SUCCESS);
resultSuccess.setMessage(MessageConstant.INFO_0003);
resultSuccess.setResult(userInfo);
return resultSuccess;
}
}
| 1,444 | 0.768466 | 0.765625 | 50 | 27.16 | 23.871624 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.1 | false | false | 4 |
9eb4172a7873d7c258c3549e0d04603837e56d54 | 29,566,554,901,839 | 1f52e9c0247e47aecae0564c435d7d693a6c747d | /src/main/java/bridge/WeatFood.java | adae9fba71e44a37266fe248656ee4f9ad712541 | []
| no_license | o-semenkova/design_paterns_gof | https://github.com/o-semenkova/design_paterns_gof | bf33664b570ae2449a34497d4f8c43d59324daa2 | 62680c02e843a604ef4fb4f2b02c483dd019e330 | refs/heads/master | 2020-09-20T22:18:43.371000 | 2016-10-28T14:37:39 | 2016-10-28T14:37:39 | 67,944,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bridge;
/**
* Created by osemenkova on 10/24/2016.
*/
public class WeatFood extends Food {
public WeatFood(String type) {
super(type);
}
}
| UTF-8 | Java | 166 | java | WeatFood.java | Java | [
{
"context": "package bridge;\n\n/**\n * Created by osemenkova on 10/24/2016.\n */\npublic class WeatFood extends ",
"end": 45,
"score": 0.9996064305305481,
"start": 35,
"tag": "USERNAME",
"value": "osemenkova"
}
]
| null | []
| package bridge;
/**
* Created by osemenkova on 10/24/2016.
*/
public class WeatFood extends Food {
public WeatFood(String type) {
super(type);
}
}
| 166 | 0.63253 | 0.584337 | 10 | 15.6 | 14.860686 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 4 |
c8c0b2cc07798f16c3d8790122830791d350d419 | 6,030,134,106,148 | 44dd3c3a6409ae1fc8fd4a73bbb5e8fdb9382c3c | /kodilla-patterns2/src/main/java/com/kodilla/patterns2/decorator/pizza/KebabPizzaOrderDecorator.java | 57bcd3c4f1eaed94b2e9bc0753669dd83e9e20aa | []
| no_license | mrasinski/maciej-rasinski-kodilla-java | https://github.com/mrasinski/maciej-rasinski-kodilla-java | 0ed06cbb14d9cd556cabeb031cf5cc7cbc0021a2 | 95b93d358b5b7df51614d980df5361914754caa7 | refs/heads/master | 2020-04-18T00:13:07.985000 | 2019-09-08T09:31:41 | 2019-09-08T09:31:41 | 167,067,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kodilla.patterns2.decorator.pizza;
import java.math.BigDecimal;
public class KebabPizzaOrderDecorator extends AbstractPizzaOrderDecorator {
public KebabPizzaOrderDecorator(PizzaOrder pizzaOrder) {
super(pizzaOrder);
}
@Override
public BigDecimal getCost() {
return super.getCost().add(new BigDecimal(13));
}
@Override
public String getPie() {
return super.getPie();
}
@Override
public String getSauce() {
return "Cream sauce";
}
@Override
public String getIngredient() {
return super.getIngredient() + " + chicken + onion";
}
}
| UTF-8 | Java | 642 | java | KebabPizzaOrderDecorator.java | Java | []
| null | []
| package com.kodilla.patterns2.decorator.pizza;
import java.math.BigDecimal;
public class KebabPizzaOrderDecorator extends AbstractPizzaOrderDecorator {
public KebabPizzaOrderDecorator(PizzaOrder pizzaOrder) {
super(pizzaOrder);
}
@Override
public BigDecimal getCost() {
return super.getCost().add(new BigDecimal(13));
}
@Override
public String getPie() {
return super.getPie();
}
@Override
public String getSauce() {
return "Cream sauce";
}
@Override
public String getIngredient() {
return super.getIngredient() + " + chicken + onion";
}
}
| 642 | 0.655763 | 0.65109 | 29 | 21.137932 | 21.18022 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.241379 | false | false | 4 |
33d764cb4a122f41d2d81aa8c43e006cf8f30717 | 13,503,377,193,472 | f6acdfb7a29dab62cc5b5e18c64e1c6bf394384d | /SpringDataMongoDB/src/main/java/com/smpuos/ftn/services/UserService.java | 02be42744eded463ec48e6493d3533663ee66128 | []
| no_license | brankoterzic/SMPOUS | https://github.com/brankoterzic/SMPOUS | f237a780d8ba0a2b9b87ab7247aab074b3df765e | 7b7e93bfbf21cbf5871ca7fdb9098f48552578c2 | refs/heads/master | 2021-01-12T12:34:04.345000 | 2018-12-11T09:34:36 | 2018-12-11T09:34:36 | 72,570,702 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smpuos.ftn.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.smpuos.ftn.models.User;
import com.smpuos.ftn.repositories.UserRepository;
@Service
public class UserService extends AbstractCRUDService<User, String>{
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository){
super(userRepository);
this.userRepository = userRepository;
}
public List<User> findByFirstName(String firstName){
return userRepository.findByFirstName(firstName);
}
public Page<User> findByFirstName(String firstName, Pageable pageable){
return userRepository.findByFirstName(firstName, pageable);
}
}
| UTF-8 | Java | 857 | java | UserService.java | Java | []
| null | []
| package com.smpuos.ftn.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.smpuos.ftn.models.User;
import com.smpuos.ftn.repositories.UserRepository;
@Service
public class UserService extends AbstractCRUDService<User, String>{
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository){
super(userRepository);
this.userRepository = userRepository;
}
public List<User> findByFirstName(String firstName){
return userRepository.findByFirstName(firstName);
}
public Page<User> findByFirstName(String firstName, Pageable pageable){
return userRepository.findByFirstName(firstName, pageable);
}
}
| 857 | 0.814469 | 0.814469 | 32 | 25.78125 | 24.570988 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.