blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
65478df0e0e383332984d93d289cf24c763803be
571ad152fd39096bc49ffb0dd570f9de84f20632
/QPM_SDK/src/main/java/com/zk/qpm/floatview/renderer/QPMTemplateBigTextRenderer.java
b38d8145416378fdfd58685c4517480b6b68c692
[ "Apache-2.0" ]
permissive
sigaritus/QPM
c93ba4766a4654231e386caf67221e1bc5ec896f
3448d29510ec1b8b615feaa795acdb3accf6936b
refs/heads/master
2020-04-14T04:28:17.755012
2018-12-29T08:22:10
2018-12-29T08:22:10
163,636,759
1
0
Apache-2.0
2018-12-31T03:46:27
2018-12-31T03:46:27
null
UTF-8
Java
false
false
1,634
java
package com.zk.qpm.floatview.renderer; import android.os.Build; import android.text.Html; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.zk.qpm.R; import com.zk.qpm.floatview.QPMFloatViewType; import java.util.Map; public class QPMTemplateBigTextRenderer extends BaseTemplateRenderer { public static final String PARAM_BIG_TEXT = "param_big_text"; public QPMTemplateBigTextRenderer(Map<String, Object> mParam) { super(mParam); } @Override public String type() { return QPMFloatViewType.TYPE_FLOAT_VIEW_TEMPLATE_BIG_TEXT; } @Override protected int getLayoutId() { return R.layout.jm_gt_item_floatview_template_bigtext; } @Override protected void renderer(View mView, Map<String, Object> mParam) { TextView valueView = mView.findViewById(R.id.tv_value); Object o = mParam.get(PARAM_BIG_TEXT); if (o == null) { return; } String content = o.toString(); if (!TextUtils.isEmpty(content)) { valueView.setText(formatContent(content)); } } private Spanned formatContent(String content) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Html.fromHtml(content, Html.FROM_HTML_MODE_COMPACT); } else { return Html.fromHtml(content); } } catch (Exception e) { e.printStackTrace(); return new SpannableString(content); } } }
[ "qingw@jumei.com" ]
qingw@jumei.com
1918c66e49e4f56bc0015f9bcc486cf1d601f4cb
103e5ba739622fef101c21484d0e3bcb9c1c40ae
/app/src/main/java/com/builderstrom/user/data/retrofit/modals/SignConformModel.java
e31e704a8e9e5a7260c0bf0349005e64cc9d02d4
[]
no_license
Sahilkumar002/BuilderstormUpdate
26e9f62eaf4230a578b543c925356ac1cddbd07e
dfcc5c774633a016ddabf453ad390e1afbbd863e
refs/heads/master
2023-04-01T21:35:51.022448
2021-04-13T08:04:01
2021-04-13T08:04:01
357,436,410
0
1
null
null
null
null
UTF-8
Java
false
false
20,179
java
//package com.builderstrom.user.repository.retrofit.modals; // //import com.google.gson.annotations.Expose; //import com.google.gson.annotations.SerializedName; // //import java.util.List; // //public class SignConformModel { // // @SerializedName("ResponseCode") // @Expose // private Boolean responseCode; // @SerializedName("Message") // @Expose // private String message; // @SerializedName("signinid") // @Expose // private String signinid; // @SerializedName("latest_mobile_apk_version") // @Expose // private String apkVersion; // @SerializedName("mobile_apk_description") // @Expose // private String apkDescription; // @SerializedName("mobile_apk_filepath") // @Expose // private String apkPath; // @SerializedName("details") // @Expose // private Details details; // @SerializedName("all_assigned_projects") // @Expose // private List<ProjectDetails> allProjects = null; // // public Boolean getResponseCode() { // return responseCode; // } // // public void setResponseCode(Boolean responseCode) { // this.responseCode = responseCode; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getSigninid() { // return signinid; // } // // public void setSigninid(String signinid) { // this.signinid = signinid; // } // // public String getApkVersion() { // return apkVersion; // } // // public void setApkVersion(String apkVersion) { // this.apkVersion = apkVersion; // } // // public String getApkPath() { // return apkPath; // } // // public void setApkPath(String apkPath) { // this.apkPath = apkPath; // } // // public Details getDetails() { // return details; // } // // public void setDetails(Details details) { // this.details = details; // } // // public String getApkDescription() { // return apkDescription; // } // // public void setApkDescription(String apkDescription) { // this.apkDescription = apkDescription; // } // // public List<ProjectDetails> getAllProjects() { // return allProjects; // } // // public void setAllProjects(List<ProjectDetails> allProjects) { // this.allProjects = allProjects; // } // //// public class Projectdetails { //// //// @SerializedName("uid") //// @Expose //// private String uid; //// @SerializedName("collection_uid") //// @Expose //// private String collectionUid; //// @SerializedName("title") //// @Expose //// private String title; //// @SerializedName("added_on") //// @Expose //// private String addedOn; //// @SerializedName("project_primaryEmail") //// @Expose //// private String projectPrimaryEmail; //// @SerializedName("username") //// @Expose //// private String username; //// @SerializedName("password") //// @Expose //// private String password; //// @SerializedName("server_address") //// @Expose //// private String serverAddress; //// @SerializedName("type") //// @Expose //// private String type; //// @SerializedName("contact") //// @Expose //// private String contact; //// @SerializedName("address") //// @Expose //// private String address; //// @SerializedName("zip") //// @Expose //// private String zip; //// @SerializedName("lat") //// @Expose //// private String lat; //// @SerializedName("lang") //// @Expose //// private String lang; //// @SerializedName("end_date") //// @Expose //// private String endDate; //// @SerializedName("note") //// @Expose //// private String note; //// @SerializedName("image") //// @Expose //// private String image; //// @SerializedName("project_id") //// @Expose //// private String projectId; //// @SerializedName("group_id_system") //// @Expose //// private String groupIdSystem; //// @SerializedName("archive") //// @Expose //// private String archive; //// @SerializedName("delete_status") //// @Expose //// private String deleteStatus; //// @SerializedName("project_order") //// @Expose //// private String projectOrder; //// @SerializedName("super_admin_project") //// @Expose //// private String superAdminProject; //// @SerializedName("status") //// @Expose //// private String status; //// @SerializedName("stage") //// @Expose //// private String stage; //// @SerializedName("c_manager") //// @Expose //// private String cManager; //// @SerializedName("color_code") //// @Expose //// private String colorCode; //// @SerializedName("client") //// @Expose //// private String client; //// @SerializedName("description") //// @Expose //// private String description; //// @SerializedName("project_cost") //// @Expose //// private String projectCost; //// @SerializedName("region") //// @Expose //// private String region; //// @SerializedName("db_importor_status") //// @Expose //// private String dbImportorStatus; //// @SerializedName("project_order_no") //// @Expose //// private String projectOrderNo; //// @SerializedName("hidden_status") //// @Expose //// private String hiddenStatus; //// @SerializedName("submittal_revision_sequence_button") //// @Expose //// private String submittalRevisionSequenceButton; //// @SerializedName("submittal_revision_sequence") //// @Expose //// private String submittalRevisionSequence; //// @SerializedName("submittal_days_warning_button") //// @Expose //// private String submittalDaysWarningButton; //// @SerializedName("submittal_days_warning") //// @Expose //// private String submittalDaysWarning; //// @SerializedName("submittal_on_off") //// @Expose //// private String submittalOnOff; //// @SerializedName("submittal_status_graph") //// @Expose //// private String submittalStatusGraph; //// @SerializedName("drawing_revision_sequence_button") //// @Expose //// private String drawingRevisionSequenceButton; //// @SerializedName("drawing_revision_sequence") //// @Expose //// private String drawingRevisionSequence; //// @SerializedName("document_controllers") //// @Expose //// private String documentControllers; //// @SerializedName("plant_manager") //// @Expose //// private String plantManager; //// @SerializedName("proj_doc_flow_manager") //// @Expose //// private String projDocFlowManager; //// @SerializedName("submittals_upload_project_drawing") //// @Expose //// private String submittalsUploadProjectDrawing; //// @SerializedName("submittals_upload_project_document") //// @Expose //// private String submittalsUploadProjectDocument; //// @SerializedName("showfor_mobile_siteaccess") //// @Expose //// private String showforMobileSiteaccess; //// //// public String getUid() { //// return uid; //// } //// //// public void setUid(String uid) { //// this.uid = uid; //// } //// //// public String getCollectionUid() { //// return collectionUid; //// } //// //// public void setCollectionUid(String collectionUid) { //// this.collectionUid = collectionUid; //// } //// //// public String getTitle() { //// return title; //// } //// //// public void setTitle(String title) { //// this.title = title; //// } //// //// public String getAddedOn() { //// return addedOn; //// } //// //// public void setAddedOn(String addedOn) { //// this.addedOn = addedOn; //// } //// //// public String getProjectPrimaryEmail() { //// return projectPrimaryEmail; //// } //// //// public void setProjectPrimaryEmail(String projectPrimaryEmail) { //// this.projectPrimaryEmail = projectPrimaryEmail; //// } //// //// 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 String getServerAddress() { //// return serverAddress; //// } //// //// public void setServerAddress(String serverAddress) { //// this.serverAddress = serverAddress; //// } //// //// public String getType() { //// return type; //// } //// //// public void setType(String type) { //// this.type = type; //// } //// //// public String getContact() { //// return contact; //// } //// //// public void setContact(String contact) { //// this.contact = contact; //// } //// //// public String getAddress() { //// return address; //// } //// //// public void setAddress(String address) { //// this.address = address; //// } //// //// public String getZip() { //// return zip; //// } //// //// public void setZip(String zip) { //// this.zip = zip; //// } //// //// public String getLat() { //// return lat; //// } //// //// public void setLat(String lat) { //// this.lat = lat; //// } //// //// public String getLang() { //// return lang; //// } //// //// public void setLang(String lang) { //// this.lang = lang; //// } //// //// public String getEndDate() { //// return endDate; //// } //// //// public void setEndDate(String endDate) { //// this.endDate = endDate; //// } //// //// public String getNote() { //// return note; //// } //// //// public void setNote(String note) { //// this.note = note; //// } //// //// public String getImage() { //// return image; //// } //// //// public void setImage(String image) { //// this.image = image; //// } //// //// public String getProjectId() { //// return projectId; //// } //// //// public void setProjectId(String projectId) { //// this.projectId = projectId; //// } //// //// public String getGroupIdSystem() { //// return groupIdSystem; //// } //// //// public void setGroupIdSystem(String groupIdSystem) { //// this.groupIdSystem = groupIdSystem; //// } //// //// public String getArchive() { //// return archive; //// } //// //// public void setArchive(String archive) { //// this.archive = archive; //// } //// //// public String getDeleteStatus() { //// return deleteStatus; //// } //// //// public void setDeleteStatus(String deleteStatus) { //// this.deleteStatus = deleteStatus; //// } //// //// public String getProjectOrder() { //// return projectOrder; //// } //// //// public void setProjectOrder(String projectOrder) { //// this.projectOrder = projectOrder; //// } //// //// public String getSuperAdminProject() { //// return superAdminProject; //// } //// //// public void setSuperAdminProject(String superAdminProject) { //// this.superAdminProject = superAdminProject; //// } //// //// public String getStatus() { //// return status; //// } //// //// public void setStatus(String status) { //// this.status = status; //// } //// //// public String getStage() { //// return stage; //// } //// //// public void setStage(String stage) { //// this.stage = stage; //// } //// //// public String getCManager() { //// return cManager; //// } //// //// public void setCManager(String cManager) { //// this.cManager = cManager; //// } //// //// public String getColorCode() { //// return colorCode; //// } //// //// public void setColorCode(String colorCode) { //// this.colorCode = colorCode; //// } //// //// public String getClient() { //// return client; //// } //// //// public void setClient(String client) { //// this.client = client; //// } //// //// public String getDescription() { //// return description; //// } //// //// public void setDescription(String description) { //// this.description = description; //// } //// //// public String getProjectCost() { //// return projectCost; //// } //// //// public void setProjectCost(String projectCost) { //// this.projectCost = projectCost; //// } //// //// public String getRegion() { //// return region; //// } //// //// public void setRegion(String region) { //// this.region = region; //// } //// //// public String getDbImportorStatus() { //// return dbImportorStatus; //// } //// //// public void setDbImportorStatus(String dbImportorStatus) { //// this.dbImportorStatus = dbImportorStatus; //// } //// //// public String getProjectOrderNo() { //// return projectOrderNo; //// } //// //// public void setProjectOrderNo(String projectOrderNo) { //// this.projectOrderNo = projectOrderNo; //// } //// //// public String getHiddenStatus() { //// return hiddenStatus; //// } //// //// public void setHiddenStatus(String hiddenStatus) { //// this.hiddenStatus = hiddenStatus; //// } //// //// public String getSubmittalRevisionSequenceButton() { //// return submittalRevisionSequenceButton; //// } //// //// public void setSubmittalRevisionSequenceButton(String submittalRevisionSequenceButton) { //// this.submittalRevisionSequenceButton = submittalRevisionSequenceButton; //// } //// //// public String getSubmittalRevisionSequence() { //// return submittalRevisionSequence; //// } //// //// public void setSubmittalRevisionSequence(String submittalRevisionSequence) { //// this.submittalRevisionSequence = submittalRevisionSequence; //// } //// //// public String getSubmittalDaysWarningButton() { //// return submittalDaysWarningButton; //// } //// //// public void setSubmittalDaysWarningButton(String submittalDaysWarningButton) { //// this.submittalDaysWarningButton = submittalDaysWarningButton; //// } //// //// public String getSubmittalDaysWarning() { //// return submittalDaysWarning; //// } //// //// public void setSubmittalDaysWarning(String submittalDaysWarning) { //// this.submittalDaysWarning = submittalDaysWarning; //// } //// //// public String getSubmittalOnOff() { //// return submittalOnOff; //// } //// //// public void setSubmittalOnOff(String submittalOnOff) { //// this.submittalOnOff = submittalOnOff; //// } //// //// public String getSubmittalStatusGraph() { //// return submittalStatusGraph; //// } //// //// public void setSubmittalStatusGraph(String submittalStatusGraph) { //// this.submittalStatusGraph = submittalStatusGraph; //// } //// //// public String getDrawingRevisionSequenceButton() { //// return drawingRevisionSequenceButton; //// } //// //// public void setDrawingRevisionSequenceButton(String drawingRevisionSequenceButton) { //// this.drawingRevisionSequenceButton = drawingRevisionSequenceButton; //// } //// //// public String getDrawingRevisionSequence() { //// return drawingRevisionSequence; //// } //// //// public void setDrawingRevisionSequence(String drawingRevisionSequence) { //// this.drawingRevisionSequence = drawingRevisionSequence; //// } //// //// public String getDocumentControllers() { //// return documentControllers; //// } //// //// public void setDocumentControllers(String documentControllers) { //// this.documentControllers = documentControllers; //// } //// //// public String getPlantManager() { //// return plantManager; //// } //// //// public void setPlantManager(String plantManager) { //// this.plantManager = plantManager; //// } //// //// public String getProjDocFlowManager() { //// return projDocFlowManager; //// } //// //// public void setProjDocFlowManager(String projDocFlowManager) { //// this.projDocFlowManager = projDocFlowManager; //// } //// //// public String getSubmittalsUploadProjectDrawing() { //// return submittalsUploadProjectDrawing; //// } //// //// public void setSubmittalsUploadProjectDrawing(String submittalsUploadProjectDrawing) { //// this.submittalsUploadProjectDrawing = submittalsUploadProjectDrawing; //// } //// //// public String getSubmittalsUploadProjectDocument() { //// return submittalsUploadProjectDocument; //// } //// //// public void setSubmittalsUploadProjectDocument(String submittalsUploadProjectDocument) { //// this.submittalsUploadProjectDocument = submittalsUploadProjectDocument; //// } //// //// public String getShowforMobileSiteaccess() { //// return showforMobileSiteaccess; //// } //// //// public void setShowforMobileSiteaccess(String showforMobileSiteaccess) { //// this.showforMobileSiteaccess = showforMobileSiteaccess; //// } //// //// } // // // // public class Details { // // @SerializedName("projectHours") // @Expose // private ProjectHours projectHours; // @SerializedName("projectdetails") // @Expose // private ProjectDetails projectdetails; // @SerializedName("project_title") // @Expose // private String projectTitle; // // public ProjectHours getProjectHours() { // return projectHours; // } // // public void setProjectHours(ProjectHours projectHours) { // this.projectHours = projectHours; // } // // public ProjectDetails getProjectdetails() { // return projectdetails; // } // // public void setProjectdetails(ProjectDetails projectdetails) { // this.projectdetails = projectdetails; // } // // public String getProjectTitle() { // return projectTitle; // } // // public void setProjectTitle(String projectTitle) { // this.projectTitle = projectTitle; // } // // } //}
[ "kumarrohit.sharmasahil002@gmail.com" ]
kumarrohit.sharmasahil002@gmail.com
05ce240d2010e6088b9d6fa210a8bf7584f8a0a6
7f81d67d1b768206d7f92137a0235ce55008e672
/truck/zhgy/src/com/tornado/entity/base/BaseCategory.java
16087fbaa6bb1c956b57d7490163f40b332f2390
[]
no_license
awesometeam/zhgy
446b42352dbc1ea152390cff4d78a4827b456aa4
ed6973adb61f076e706bbea9a80235329b1107f1
refs/heads/master
2021-01-23T11:55:39.194890
2013-01-14T12:15:03
2013-01-14T12:15:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,566
java
package com.tornado.entity.base; import java.io.Serializable; /** * This is an object that contains data related to the category table. * Do not modify this class because it will be overwritten if the configuration file * related to this class is modified. * * @hibernate.class * table="category" */ public abstract class BaseCategory implements Serializable { public static String REF = "Category"; public static String PROP_NAME = "Name"; public static String PROP_INTRODUCTION = "Introduction"; public static String PROP_HIGHERID = "Higherid"; public static String PROP_HAVEHIGHER = "Havehigher"; public static String PROP_NUMBER = "Number"; public static String PROP_ID = "Id"; public static String PROP_LANGUAGE = "Language"; // constructors public BaseCategory () { initialize(); } /** * Constructor for primary key */ public BaseCategory (java.lang.Long id) { this.setId(id); initialize(); } /** * Constructor for required fields */ public BaseCategory ( java.lang.Long id, java.lang.Integer havehigher, java.lang.String language) { this.setId(id); this.setHavehigher(havehigher); this.setLanguage(language); initialize(); } protected void initialize () {} private int hashCode = Integer.MIN_VALUE; // primary key private java.lang.Long id; // fields private java.lang.Integer havehigher; private java.lang.Long higherid; private java.lang.String introduction; private java.lang.String language; private java.lang.String name; private java.lang.String number; /** * Return the unique identifier of this class * @hibernate.id * generator-class="increment" * column="CATEGORY_ID" */ public java.lang.Long getId () { return id; } /** * Set the unique identifier of this class * @param id the new ID */ public void setId (java.lang.Long id) { this.id = id; this.hashCode = Integer.MIN_VALUE; } /** * Return the value associated with the column: HAVEHIGHER */ public java.lang.Integer getHavehigher () { return havehigher; } /** * Set the value related to the column: HAVEHIGHER * @param havehigher the HAVEHIGHER value */ public void setHavehigher (java.lang.Integer havehigher) { this.havehigher = havehigher; } /** * Return the value associated with the column: HIGHERID */ public java.lang.Long getHigherid () { return higherid; } /** * Set the value related to the column: HIGHERID * @param higherid the HIGHERID value */ public void setHigherid (java.lang.Long higherid) { this.higherid = higherid; } /** * Return the value associated with the column: INTRODUCTION */ public java.lang.String getIntroduction () { return introduction; } /** * Set the value related to the column: INTRODUCTION * @param introduction the INTRODUCTION value */ public void setIntroduction (java.lang.String introduction) { this.introduction = introduction; } /** * Return the value associated with the column: LANGUAGE */ public java.lang.String getLanguage () { return language; } /** * Set the value related to the column: LANGUAGE * @param language the LANGUAGE value */ public void setLanguage (java.lang.String language) { this.language = language; } /** * Return the value associated with the column: NAME */ public java.lang.String getName () { return name; } /** * Set the value related to the column: NAME * @param name the NAME value */ public void setName (java.lang.String name) { this.name = name; } /** * Return the value associated with the column: NUMBER */ public java.lang.String getNumber () { return number; } /** * Set the value related to the column: NUMBER * @param number the NUMBER value */ public void setNumber (java.lang.String number) { this.number = number; } public boolean equals (Object obj) { if (null == obj) return false; if (!(obj instanceof com.tornado.entity.Category)) return false; else { com.tornado.entity.Category category = (com.tornado.entity.Category) obj; if (null == this.getId() || null == category.getId()) return false; else return (this.getId().equals(category.getId())); } } public int hashCode () { if (Integer.MIN_VALUE == this.hashCode) { if (null == this.getId()) return super.hashCode(); else { String hashStr = this.getClass().getName() + ":" + this.getId().hashCode(); this.hashCode = hashStr.hashCode(); } } return this.hashCode; } public String toString () { return super.toString(); } }
[ "vince.lr.s@gmail.com" ]
vince.lr.s@gmail.com
b95a36a3312c822ab3475efd67e47b7d63332e08
6574375ead3b0086fd3a8e12acee620d72f0cd2f
/app/src/main/java/com/example/santiagolara/poly12/activity_lesson5_part6.java
01ac7ed640cc6d8bee7d3279cd2fc2281887047c
[]
no_license
adiall1996/Poly-Learning-App
3afac853a40341ad46db7e7b76c3cb71d0c617ee
236ede4b42afabc741519d103194d1a421c48226
refs/heads/master
2022-11-23T09:59:54.613057
2020-07-30T15:41:21
2020-07-30T15:41:21
283,814,286
0
0
null
null
null
null
UTF-8
Java
false
false
853
java
package com.example.santiagolara.poly12; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class activity_lesson5_part6 extends AppCompatActivity { private Button tolesson5_part7; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lesson5_part6); tolesson5_part7 = findViewById(R.id.tolesson5_part7); tolesson5_part7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity_lesson5_part6.this,activity_lesson5_part7.class); startActivity(intent); } }); } }
[ "adiall02@nyit.edu" ]
adiall02@nyit.edu
352fdee083ba49cea695c0ce23d6e0843ef21393
d7bcf0feab308c20efffe2dfac2e0a2103daf0f2
/src/test/java/com/usa/testNG/TestNG_Annotations.java
0f8d7d47ba8313014c864ba4edcf1667c3f8c02e
[]
no_license
QA-Alam/JenkinsProject
24a1fb06de806945b045bd8952fec175d5af3a6f
fac043db571e954468c5e9156cc5db32d8b6c41d
refs/heads/master
2023-07-18T23:22:51.220999
2021-09-30T23:22:44
2021-09-30T23:22:44
410,894,326
0
0
null
null
null
null
UTF-8
Java
false
false
3,226
java
package com.usa.testNG; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class TestNG_Annotations { @Test // Marks a class or a method as a part of the test. public void testCase() { System.out.println(" Only One Test case "); } @BeforeMethod //The annotated method will be run before each test method. public void beforeMethod() { System.out.println("I Am running beforeMethod"); } @AfterMethod //The annotated method will be run after each test method. public void afterMethod() { System.out.println("I Am running afterMethod"); } @BeforeClass //The annotated method will be run only once before the first test method in the current class is invoked. public void beforeClass() { System.out.println("I Am running beforeClass"); } @AfterClass //The annotated method will be run only once after all the test methods in the current class have run. public void afterClass() { System.out.println("I Am running afterClass"); } @BeforeTest //The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. public void beforeTest() { System.out.println("I Am running beforeTest"); } @AfterTest //The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run. public void afterTest() { System.out.println("I Am running afterTest"); } @BeforeSuite //The annotated method will be run only once before all tests in this suite have run. public void beforeSuite() { System.out.println("I Am running beforeSuite"); } @AfterSuite //The annotated method will be run only once after all tests in this suite have run. public void afterSuite() { System.out.println("I Am running afterSuite"); } /* * * @BeforeGroups The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked. @AfterGroups The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked. @DataProvider Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ], where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation. @Listeners Defines listeners on a test class. @Parameters Describes how to pass parameters to a @Test method. */ }
[ "“alam.itprofessional@gmail.com”" ]
“alam.itprofessional@gmail.com”
b57d515f192cdf1f87c2e21b8ae0ba398d4cdb45
93a3eb9e1a660feb6e43e6c90193d7b08112965c
/validation/src/main/java/fi/jawsy/jawwa/validation/DoubleValidators.java
4a282fb0d3bd60161b06f05f14b265dc05bacbad
[ "Apache-2.0" ]
permissive
Gekkio/jawwa
a4766847256bf50f781ef45568a6a894725bb8bc
f679801155772fee8e8d2300683b8f872a3de2e5
HEAD
2016-09-03T07:00:38.105567
2013-12-31T06:31:27
2013-12-31T06:31:27
3,266,917
0
0
null
null
null
null
UTF-8
Java
false
false
683
java
package fi.jawsy.jawwa.validation; import java.io.Serializable; import com.google.common.collect.ImmutableList.Builder; public final class DoubleValidators { private DoubleValidators() { } public static <E> Validator<E, Double> isPositive(final E error) { class PositiveValidator extends ValidatorBase<E, Double> implements Serializable { private static final long serialVersionUID = -2699511581231169209L; @Override public void validate(Double object, Builder<E> errors) { if (object < 0.0) errors.add(error); } } return new PositiveValidator(); } }
[ "joonas.javanainen@gmail.com" ]
joonas.javanainen@gmail.com
967468691cc11c20ac2e7c758f5c2a097962d5ec
cc5ed8da10aa3c2537bc1bc118a06747545b1108
/Tutorial14/src/Main.java
9df1748edaf83c40b10dd7c1e05bdbdde1921870
[]
no_license
Arinjbj/startjava
1bc6a326c8dcc67647a5d1339b8093645ee17d3f
dcf7ffc9fd2bd0744fdc0345f40553ae036b6549
refs/heads/master
2022-11-30T21:33:04.931141
2020-08-13T13:52:52
2020-08-13T13:52:52
279,297,329
0
0
null
null
null
null
UTF-8
Java
false
false
428
java
public class Main { public static void main(String[] args) { int n = 50; int[][] arr = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { arr[i][j] = (int)(Math.random() * 10); } } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(arr[i][j]); System.out.print(" "); System.out.print(" "); } System.out.println(); } } }
[ "qwert1424@naver.com" ]
qwert1424@naver.com
7f5391fc813d39f541e6ebce4dbeff85aae0e3aa
140b6dcf2ca3aa2b54edd07c6cbd8b675af946c5
/src/test/java/com/meiyingying/springboot/SpringbootApplicationTests.java
f85752a7e1ce478d1373873796608b9cdd723dc2
[]
no_license
Somiacao/backend_springboot
5fc881e8aebaf81a980453fdc5a4b04e213db0ae
15035320d3541dd6623bb59f993670a262e52c2f
refs/heads/master
2020-07-09T23:43:22.739858
2019-10-23T01:22:01
2019-10-23T01:22:01
204,111,217
3
0
null
null
null
null
UTF-8
Java
false
false
356
java
package com.meiyingying.springboot; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootApplicationTests { @Test public void contextLoads() { } }
[ "18210240048@fudan.edu.cn" ]
18210240048@fudan.edu.cn
3dc1e4f30779fdb7ba58c54cd2cb365edc93ca0b
4cf28de03d844aa2d84a8e8cec103ba2312ea353
/src/com/xjt/crazypic/edit/crop/BoundedRect.java
d1d8d9f76f40a3354ca803bedc052ecd019bc6ed
[ "Apache-2.0" ]
permissive
jituo666/CrazyPic
873b7b3f67b678cee69d19f096030eb61572df72
706e9f92430af1e72a7fca3bf39bd8dbcf0c30a5
refs/heads/master
2021-01-06T20:38:01.951788
2014-10-14T01:51:59
2014-10-14T01:51:59
24,831,462
0
2
null
null
null
null
UTF-8
Java
false
false
12,844
java
package com.xjt.crazypic.edit.crop; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import com.xjt.crazypic.edit.imageshow.GeometryMathUtils; import java.util.Arrays; /** * Maintains invariant that inner rectangle is constrained to be within the * outer, rotated rectangle. */ public class BoundedRect { private float rot; private RectF outer; private RectF inner; private float[] innerRotated; public BoundedRect(float rotation, Rect outerRect, Rect innerRect) { rot = rotation; outer = new RectF(outerRect); inner = new RectF(innerRect); innerRotated = CropMath.getCornersFromRect(inner); rotateInner(); if (!isConstrained()) reconstrain(); } public BoundedRect(float rotation, RectF outerRect, RectF innerRect) { rot = rotation; outer = new RectF(outerRect); inner = new RectF(innerRect); innerRotated = CropMath.getCornersFromRect(inner); rotateInner(); if (!isConstrained()) reconstrain(); } public void resetTo(float rotation, RectF outerRect, RectF innerRect) { rot = rotation; outer.set(outerRect); inner.set(innerRect); innerRotated = CropMath.getCornersFromRect(inner); rotateInner(); if (!isConstrained()) reconstrain(); } /** * Sets inner, and re-constrains it to fit within the rotated bounding rect. */ public void setInner(RectF newInner) { if (inner.equals(newInner)) return; inner = newInner; innerRotated = CropMath.getCornersFromRect(inner); rotateInner(); if (!isConstrained()) reconstrain(); } /** * Sets rotation, and re-constrains inner to fit within the rotated bounding rect. */ public void setRotation(float rotation) { if (rotation == rot) return; rot = rotation; innerRotated = CropMath.getCornersFromRect(inner); rotateInner(); if (!isConstrained()) reconstrain(); } public void setToInner(RectF r) { r.set(inner); } public void setToOuter(RectF r) { r.set(outer); } public RectF getInner() { return new RectF(inner); } public RectF getOuter() { return new RectF(outer); } /** * Tries to move the inner rectangle by (dx, dy). If this would cause it to leave * the bounding rectangle, snaps the inner rectangle to the edge of the bounding * rectangle. */ public void moveInner(float dx, float dy) { Matrix m0 = getInverseRotMatrix(); RectF translatedInner = new RectF(inner); translatedInner.offset(dx, dy); float[] translatedInnerCorners = CropMath.getCornersFromRect(translatedInner); float[] outerCorners = CropMath.getCornersFromRect(outer); m0.mapPoints(translatedInnerCorners); float[] correction = { 0, 0 }; // find correction vectors for corners that have moved out of bounds for (int i = 0; i < translatedInnerCorners.length; i += 2) { float correctedInnerX = translatedInnerCorners[i] + correction[0]; float correctedInnerY = translatedInnerCorners[i + 1] + correction[1]; if (!CropMath.inclusiveContains(outer, correctedInnerX, correctedInnerY)) { float[] badCorner = { correctedInnerX, correctedInnerY }; float[] nearestSide = CropMath.closestSide(badCorner, outerCorners); float[] correctionVec = GeometryMathUtils.shortestVectorFromPointToLine(badCorner, nearestSide); correction[0] += correctionVec[0]; correction[1] += correctionVec[1]; } } for (int i = 0; i < translatedInnerCorners.length; i += 2) { float correctedInnerX = translatedInnerCorners[i] + correction[0]; float correctedInnerY = translatedInnerCorners[i + 1] + correction[1]; if (!CropMath.inclusiveContains(outer, correctedInnerX, correctedInnerY)) { float[] correctionVec = { correctedInnerX, correctedInnerY }; CropMath.getEdgePoints(outer, correctionVec); correctionVec[0] -= correctedInnerX; correctionVec[1] -= correctedInnerY; correction[0] += correctionVec[0]; correction[1] += correctionVec[1]; } } // Set correction for (int i = 0; i < translatedInnerCorners.length; i += 2) { float correctedInnerX = translatedInnerCorners[i] + correction[0]; float correctedInnerY = translatedInnerCorners[i + 1] + correction[1]; // update translated corners with correction vectors translatedInnerCorners[i] = correctedInnerX; translatedInnerCorners[i + 1] = correctedInnerY; } innerRotated = translatedInnerCorners; // reconstrain to update inner reconstrain(); } /** * Attempts to resize the inner rectangle. If this would cause it to leave * the bounding rect, clips the inner rectangle to fit. */ public void resizeInner(RectF newInner) { Matrix m = getRotMatrix(); Matrix m0 = getInverseRotMatrix(); float[] outerCorners = CropMath.getCornersFromRect(outer); m.mapPoints(outerCorners); float[] oldInnerCorners = CropMath.getCornersFromRect(inner); float[] newInnerCorners = CropMath.getCornersFromRect(newInner); RectF ret = new RectF(newInner); for (int i = 0; i < newInnerCorners.length; i += 2) { float[] c = { newInnerCorners[i], newInnerCorners[i + 1] }; float[] c0 = Arrays.copyOf(c, 2); m0.mapPoints(c0); if (!CropMath.inclusiveContains(outer, c0[0], c0[1])) { float[] outerSide = CropMath.closestSide(c, outerCorners); float[] pathOfCorner = { newInnerCorners[i], newInnerCorners[i + 1], oldInnerCorners[i], oldInnerCorners[i + 1] }; float[] p = GeometryMathUtils.lineIntersect(pathOfCorner, outerSide); if (p == null) { // lines are parallel or not well defined, so don't resize p = new float[2]; p[0] = oldInnerCorners[i]; p[1] = oldInnerCorners[i + 1]; } // relies on corners being in same order as method // getCornersFromRect switch (i) { case 0: case 1: ret.left = (p[0] > ret.left) ? p[0] : ret.left; ret.top = (p[1] > ret.top) ? p[1] : ret.top; break; case 2: case 3: ret.right = (p[0] < ret.right) ? p[0] : ret.right; ret.top = (p[1] > ret.top) ? p[1] : ret.top; break; case 4: case 5: ret.right = (p[0] < ret.right) ? p[0] : ret.right; ret.bottom = (p[1] < ret.bottom) ? p[1] : ret.bottom; break; case 6: case 7: ret.left = (p[0] > ret.left) ? p[0] : ret.left; ret.bottom = (p[1] < ret.bottom) ? p[1] : ret.bottom; break; default: break; } } } float[] retCorners = CropMath.getCornersFromRect(ret); m0.mapPoints(retCorners); innerRotated = retCorners; // reconstrain to update inner reconstrain(); } /** * Attempts to resize the inner rectangle. If this would cause it to leave * the bounding rect, clips the inner rectangle to fit while maintaining * aspect ratio. */ public void fixedAspectResizeInner(RectF newInner) { Matrix m = getRotMatrix(); Matrix m0 = getInverseRotMatrix(); float aspectW = inner.width(); float aspectH = inner.height(); float aspRatio = aspectW / aspectH; float[] corners = CropMath.getCornersFromRect(outer); m.mapPoints(corners); float[] oldInnerCorners = CropMath.getCornersFromRect(inner); float[] newInnerCorners = CropMath.getCornersFromRect(newInner); // find fixed corner int fixed = -1; if (inner.top == newInner.top) { if (inner.left == newInner.left) fixed = 0; // top left else if (inner.right == newInner.right) fixed = 2; // top right } else if (inner.bottom == newInner.bottom) { if (inner.right == newInner.right) fixed = 4; // bottom right else if (inner.left == newInner.left) fixed = 6; // bottom left } // no fixed corner, return without update if (fixed == -1) return; float widthSoFar = newInner.width(); int moved = -1; for (int i = 0; i < newInnerCorners.length; i += 2) { float[] c = { newInnerCorners[i], newInnerCorners[i + 1] }; float[] c0 = Arrays.copyOf(c, 2); m0.mapPoints(c0); if (!CropMath.inclusiveContains(outer, c0[0], c0[1])) { moved = i; if (moved == fixed) continue; float[] l2 = CropMath.closestSide(c, corners); float[] l1 = { newInnerCorners[i], newInnerCorners[i + 1], oldInnerCorners[i], oldInnerCorners[i + 1] }; float[] p = GeometryMathUtils.lineIntersect(l1, l2); if (p == null) { // lines are parallel or not well defined, so set to old // corner p = new float[2]; p[0] = oldInnerCorners[i]; p[1] = oldInnerCorners[i + 1]; } // relies on corners being in same order as method // getCornersFromRect float fixed_x = oldInnerCorners[fixed]; float fixed_y = oldInnerCorners[fixed + 1]; float newWidth = Math.abs(fixed_x - p[0]); float newHeight = Math.abs(fixed_y - p[1]); newWidth = Math.max(newWidth, aspRatio * newHeight); if (newWidth < widthSoFar) widthSoFar = newWidth; } } float heightSoFar = widthSoFar / aspRatio; RectF ret = new RectF(inner); if (fixed == 0) { ret.right = ret.left + widthSoFar; ret.bottom = ret.top + heightSoFar; } else if (fixed == 2) { ret.left = ret.right - widthSoFar; ret.bottom = ret.top + heightSoFar; } else if (fixed == 4) { ret.left = ret.right - widthSoFar; ret.top = ret.bottom - heightSoFar; } else if (fixed == 6) { ret.right = ret.left + widthSoFar; ret.top = ret.bottom - heightSoFar; } float[] retCorners = CropMath.getCornersFromRect(ret); m0.mapPoints(retCorners); innerRotated = retCorners; // reconstrain to update inner reconstrain(); } // internal methods private boolean isConstrained() { for (int i = 0; i < 8; i += 2) { if (!CropMath.inclusiveContains(outer, innerRotated[i], innerRotated[i + 1])) return false; } return true; } private void reconstrain() { // innerRotated has been changed to have incorrect values CropMath.getEdgePoints(outer, innerRotated); Matrix m = getRotMatrix(); float[] unrotated = Arrays.copyOf(innerRotated, 8); m.mapPoints(unrotated); inner = CropMath.trapToRect(unrotated); } private void rotateInner() { Matrix m = getInverseRotMatrix(); m.mapPoints(innerRotated); } private Matrix getRotMatrix() { Matrix m = new Matrix(); m.setRotate(rot, outer.centerX(), outer.centerY()); return m; } private Matrix getInverseRotMatrix() { Matrix m = new Matrix(); m.setRotate(-rot, outer.centerX(), outer.centerY()); return m; } }
[ "jituo666@gmail.com" ]
jituo666@gmail.com
b2bca7d1dc226e157b18d5a5463e6527345f2daa
11430bd7f840f37d24ca6534ebc2289d960510cb
/src/com/mainacad/trapezoid/Trapezoid.java
238244bf84c318ee38291986babd46edd77b1e9c
[]
no_license
HannaLata/WorkWithOOPJuly
31b726f17d2bfe62008fc4fc2764fb34e3796066
0592a794b1f4ce9120c5cba25aef63ed1a0e99b6
refs/heads/master
2022-11-12T01:38:04.451483
2020-07-06T16:03:33
2020-07-06T16:03:33
277,587,917
1
0
null
null
null
null
UTF-8
Java
false
false
897
java
package com.mainacad.trapezoid; import com.mainacad.abs.AbstractShape; public class Trapezoid extends AbstractShape { private double base1; private double base2; private double height; public double getBase1() { return base1; } public void setBase1(double base1) { this.base1 = base1; } public double getBase2() { return base2; } public void setBase2(double base2) { this.base2 = base2; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public Trapezoid(double base1, double base2, double height) { this.base1 = base1; this.base2 = base2; this.height = height; } public Trapezoid() { } @Override public double getArea() { return (base1+base2)/2*height; } }
[ "annalats32@gmail.com" ]
annalats32@gmail.com
e4754a67374ddec973c31b927c7a074cda9996f1
2f2c5ff7456eb38d697d139f46d9efca72d96896
/src/br/edu/unoesc/projetofinal/desktop/Causa_Inclusao.java
06d05428e032400a7e40c7e8bbcecc7249d5ae73
[]
no_license
costaDiones/Controle_Granja_Suinos
b06e60c18b1384172fb14d92f29d8181e26335ef
6b476ecffb1a6242be67a2f7c7e1a171cef70bf0
refs/heads/master
2021-01-10T13:18:26.723876
2016-02-23T19:36:39
2016-02-23T19:36:39
52,386,003
0
0
null
null
null
null
MacCentralEurope
Java
false
false
3,000
java
package br.edu.unoesc.projetofinal.desktop; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import br.edu.unoesc.projetofinal.dao.CausaDAO; import br.edu.unoesc.projetofinal.dao.factory.DaoFactory; import br.edu.unoesc.projetofinal.model.Causa; public class Causa_Inclusao extends JFrame { private JLabel jlbCausa = new JLabel("Causa Morte/Descarte"); private JLabel jlbNome = new JLabel("Nome"); private JTextField jtfNomeCausa = new JTextField(); private JButton jbtCadastrarFornCli = new JButton("Cadastrar"), jbtSair = new JButton("Sair"); private CausaDAO causaDao=DaoFactory.get().causaDao(); private void posicionaObjeto(JComponent obj, int x, int y, int w, int h) { obj.setBounds(x, y, w, h); getContentPane().add(obj); } public Causa_Inclusao(final DefaultTableModel dtmDados) { setLayout(null); jlbCausa.setFont(new Font("Arial", Font.BOLD, 24)); jlbCausa.setForeground(Color.DARK_GRAY); posicionaObjeto(jlbCausa, 85, 45, 500, 25); posicionaObjeto(jlbNome, 100, 105, 100, 25); posicionaObjeto(jtfNomeCausa, 140, 105, 150, 25); posicionaObjeto(jbtCadastrarFornCli, 90, 195, 100, 30); posicionaObjeto(jbtSair, 230, 195, 80, 20); jbtCadastrarFornCli.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(jtfNomeCausa.getText().isEmpty()){ JOptionPane.showMessageDialog(null, "Digite o nome da Causa! "); } else{ int aux=0; for(Causa causa:causaDao.listarTodos()){ if(causa.getNome().equalsIgnoreCase((jtfNomeCausa.getText()))){ aux=1; break; } } if(aux==0){ Causa causa=new Causa(); causa.setNome(jtfNomeCausa.getText()); causaDao.store(causa); dtmDados.setRowCount(1); int linha=1; for(Causa causa1:causaDao.listarTodos()){ dtmDados.setRowCount(dtmDados.getRowCount()+1); dtmDados.setValueAt(causa1.getCodigo(), linha, 0); dtmDados.setValueAt(causa1.getNome(), linha, 1); linha++; } JOptionPane.showMessageDialog(null, "Causa Cadastrada com Sucesso!"); dispose(); } if(aux==1){ JOptionPane.showMessageDialog(null, "JŠ Existe uma Causa Cadastrada com esse Nome!"); } } } }); jbtSair.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); setTitle("Causa Morte"); setSize(400, 285); setVisible(true); this.setResizable(false); setLocationRelativeTo(null); this.getContentPane().setBackground(Color.lightGray); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } }
[ "costadiones@gmail.com" ]
costadiones@gmail.com
1bbdd8d7ef085a482b24d36d897005d09f3745ff
485fe3112f550d9f4d6abfc19aa6eafd01ba30e1
/src/main/java/burrito/client/crud/input/CrudInputFieldWrapper.java
a7a12ae7e7ed96ebcb97c0a6c3310b1977b1ac79
[]
no_license
trotzig/Burrito
b9d82768193f2b72abe4f9531388d15733fa732c
011e4efc48b83376fd2c07a19a9b5ab52e452a57
refs/heads/master
2018-12-28T00:06:25.831272
2013-09-04T13:52:40
2013-09-04T13:52:40
1,337,162
1
0
null
null
null
null
UTF-8
Java
false
false
3,182
java
package burrito.client.crud.input; import burrito.client.crud.generic.CrudField; import burrito.client.widgets.inputfield.InputField; import burrito.client.widgets.validation.HasValidators; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.HasChangeHandlers; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; /** * Widget that can lazily load {@link InputField} widgets * * @author henper * */ public class CrudInputFieldWrapper extends SimplePanel implements HasChangeHandlers { private String fieldName; private Widget widget; private CrudInputField<?> inputField; public CrudInputFieldWrapper() { setWidget(new Label("Missing registration call. If you see this message, you are missing a call to CrudEditFormHelper.register().")); } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public void flagAsMissingField() { setWidget(new Label("No such field: \"" + fieldName + "\". Please check the field name reference (fieldName=\"...\"). Did you misspell?")); } public void init(CrudInputField<?> input) { this.inputField = input; widget = input.getDisplayWidget(); setWidget(widget); } public Widget getWidget() { return widget; } public boolean validate() { if (widget instanceof HasValidators) { return ((HasValidators) widget).validate(); } return true; } public Object getValue() { if (widget instanceof InputField) { return ((InputField<?>) widget).getValue(); } return inputField.getValue(); } public CrudField getCrudField() { return inputField.getCrudField(); } /** * Adds a change handler to this wrapper. Will proxy to underlying widget if the widget iimplements {@link HasChangeHandlers}. * Otherwise a {@link UnsupportedOperationException} is thrown. */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public HandlerRegistration addChangeHandler(final ChangeHandler handler) { if (widget instanceof HasChangeHandlers) { return ((HasChangeHandlers) widget).addChangeHandler(handler); } if (widget instanceof HasValueChangeHandlers) { return ((HasValueChangeHandlers)widget).addValueChangeHandler(new ValueChangeHandler<Object>() { @Override public void onValueChange(ValueChangeEvent<Object> event) { handler.onChange(null); } }); } throw new UnsupportedOperationException("Field of type " + widget.getClass().getName() + " does not implement " + HasChangeHandlers.class.getName()); } /** * Focuses the underlying widget */ public void highlight() { if (widget instanceof HasValidators) { ((HasValidators) widget).highlight(); } } }
[ "henric.persson@gmail.com" ]
henric.persson@gmail.com
9ddd6537faf5acbda6f6db11b13d1348647ab3d4
ee13cdd99bfd4facb1b53d873f8f60f20e9f6282
/src/main/java/com/ideas/controller/COSServiceLayer.java
d840907e79f380fc05eea56fd9d36beb0300a5df
[]
no_license
singh-abhishek/COS
64f6a8d1456a5a345f93c08efdf5d6760febd84c
13d3928743cf4a2ad65727b3bf1011f2be95d8ef
refs/heads/master
2021-01-21T21:43:09.816701
2019-01-22T14:55:12
2019-01-22T14:55:12
26,447,761
0
3
null
null
null
null
UTF-8
Java
false
false
4,464
java
package com.ideas.controller; import java.sql.Date; import java.sql.Time; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.eclipse.jetty.util.ajax.JSON; import org.json.JSONObject; import com.ideas.domain.EmployeeSchedule; public class COSServiceLayer { public ArrayList<JSONObject> convertEmpScheduleToJson( EmployeeSchedule schedule) { ArrayList<JSONObject> jsonObjArray = new ArrayList<JSONObject>(); HashMap<String, Object> map = new HashMap<String, Object>(); for (Date dateKey : schedule.getEventsDateMap().keySet()) { for (String eventKey : schedule.getEventsDateMap().get(dateKey) .keySet()) { map.put("backgroundColor", "#3a87ad"); map.put("allDay", false); map.put("title", eventKey); map.put("start", dateKey + " " + schedule.getEventsDateMap().get(dateKey) .get(eventKey)); if(eventKey.contains("IDeaS Holiday")){ map.put("start", dateKey); map.put("backgroundColor", "#330033"); map.remove("allDay"); } jsonObjArray.add(new JSONObject(map)); } } return jsonObjArray; } public EmployeeSchedule jsonToEmployeeSchedule(String events, String username) { events = events + ","; String[] jsonArrayList = events.split("},"); TreeMap<Date, HashMap<String, Time>> eventDateMap = new TreeMap<Date, HashMap<String, Time>>(); for (int i = 0; i < jsonArrayList.length; i++) { HashMap<String, Time> eventTimeMap = new HashMap<String, Time>(); String parsableString = jsonArrayList[i] + "}"; HashMap<String, String> event = (HashMap<String, String>) JSON.parse(parsableString); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); java.util.Date utilDate = null; try { utilDate = format.parse(event.get("start")); } catch (ParseException e) {} Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(utilDate.getTime()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); java.sql.Date sqlDate = new java.sql.Date(cal.getTimeInMillis()); java.sql.Time sqlTime = new java.sql.Time(utilDate.getTime()); if (!eventDateMap.containsKey(sqlDate)) { eventTimeMap.put(event.get("title"), sqlTime); eventDateMap.put(sqlDate, eventTimeMap); } else { eventTimeMap = eventDateMap.get(sqlDate); eventTimeMap.put(event.get("title"), sqlTime); eventDateMap.put(sqlDate, eventTimeMap); } } return new EmployeeSchedule(username, eventDateMap); } public TreeMap<Time,ArrayList<ArrayList<Object>>> jsonToMap(String timesMap) { TreeMap<Time, ArrayList<ArrayList<Object>>> timeMap = new TreeMap<Time, ArrayList<ArrayList<Object>>>(); ArrayList<ArrayList<Object>> clusters = new ArrayList<ArrayList<Object>>(); ArrayList<Object> cluster = new ArrayList<Object>(); String [] tokens = timesMap.split("\""); for(int i=1;i<tokens.length;i=i+2){ String clusterArray= tokens[i+1].substring(1,tokens[i+1].length()-2); String [] clusterTokens = clusterArray.split("],"); for(int j=0;j<clusterTokens.length;j++){ clusterTokens[j]=clusterTokens[j].replace("[", ""); clusterTokens[j]=clusterTokens[j].replace("]", ""); if (clusterTokens[j].contains(",")){ String[] datapointTokens = clusterTokens[j].split(","); double[] cordinates = new double[2]; for(int k=0;k<datapointTokens.length;k++){ cordinates[k] = Double.parseDouble(datapointTokens[k]); } cluster.add(cordinates); } else { cluster.add(Double.parseDouble(clusterTokens[j])); clusters.add(cluster); cluster = new ArrayList<Object>(); } } timeMap.put(Time.valueOf(tokens[i]), clusters); clusters = new ArrayList<ArrayList<Object>>(); } return timeMap; } public ArrayList<JSONObject> convertToJSONArray( TreeMap<Date, String> companyHolidays) { ArrayList<JSONObject> holidayList = new ArrayList<JSONObject>(); for (Map.Entry<Date, String> entry : companyHolidays.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("title", entry.getValue()); jsonObject.put("start", entry.getKey()); jsonObject.put("textColor", "black"); jsonObject.put("backgroundColor", "#80ACED"); holidayList.add(jsonObject); } return holidayList; } }
[ "singhkmabhishek@gmail.com" ]
singhkmabhishek@gmail.com
3014b0d974c5a9f362cbbbbed367324f08cbb88f
fe67264856483507b221aa39ef39ad54914fff37
/VillagerBank/src/me/zeus/VillagerBank/Resources/IconMenu.java
7cb8ab813284a28a62816df83f1ba122348a7ffd
[]
no_license
YourAverageCamper/VillagerBank
6bf2c2e3f60486e0d53a0f3c67e9c44e3d324752
5b7036ccf4e981f9a01e38faf9671c7cfe2114b4
refs/heads/master
2020-05-18T19:07:30.016884
2013-08-10T15:06:10
2013-08-10T15:06:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,066
java
package me.zeus.VillagerBank.Resources; import java.util.Arrays; import org.bukkit.Bukkit; 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.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; public class IconMenu implements Listener { private String name; private int size; private OptionClickEventHandler handler; private Plugin plugin; private String[] optionNames; private ItemStack[] optionIcons; public IconMenu(String name, int size, OptionClickEventHandler handler, Plugin plugin) { this.name = name; this.size = size; this.handler = handler; this.plugin = plugin; this.optionNames = new String[size]; this.optionIcons = new ItemStack[size]; plugin.getServer().getPluginManager().registerEvents(this, plugin); } public IconMenu setOption(int position, ItemStack icon, String name, String... info) { optionNames[position] = name; optionIcons[position] = setItemNameAndLore(icon, name, info); return this; } public void open(Player player) { Inventory inventory = Bukkit.createInventory(player, size, name); for (int i = 0; i < optionIcons.length; i++) { if (optionIcons[i] != null) { inventory.setItem(i, optionIcons[i]); } } player.openInventory(inventory); } public void destroy() { HandlerList.unregisterAll(this); handler = null; plugin = null; optionNames = null; optionIcons = null; } @EventHandler(priority = EventPriority.MONITOR) void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().getTitle().equals(name)) { event.setCancelled(true); int slot = event.getRawSlot(); if (slot >= 0 && slot < size && optionNames[slot] != null) { Plugin plugin = this.plugin; OptionClickEvent e = new OptionClickEvent((Player) event.getWhoClicked(), slot, optionNames[slot]); handler.onOptionClick(e); if (e.willClose()) { final Player p = (Player) event.getWhoClicked(); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { p.closeInventory(); } }, 1); } if (e.willDestroy()) { destroy(); } } } } public interface OptionClickEventHandler { public void onOptionClick(OptionClickEvent event); } public class OptionClickEvent { private Player player; private int position; private String name; private boolean close; private boolean destroy; public OptionClickEvent(Player player, int position, String name) { this.player = player; this.position = position; this.name = name; this.close = true; this.destroy = false; } public Player getPlayer() { return player; } public int getPosition() { return position; } public String getName() { return name; } public boolean willClose() { return close; } public boolean willDestroy() { return destroy; } public void setWillClose(boolean close) { this.close = close; } public void setWillDestroy(boolean destroy) { this.destroy = destroy; } } private ItemStack setItemNameAndLore(ItemStack item, String name, String[] lore) { ItemMeta im = item.getItemMeta(); im.setDisplayName(name); im.setLore(Arrays.asList(lore)); item.setItemMeta(im); return item; } }
[ "thegreengamerhd@gmail.com" ]
thegreengamerhd@gmail.com
f19c4289ebf351a257ac843646fd9026da81ccc6
8a871a70cfcf7faff78e2d1443694ad86fbd8d66
/app/src/androidTest/java/com/computomovilyubicuo/audiosender/ExampleInstrumentedTest.java
80d56e665925912587302bc33343dec688119e44
[]
no_license
oalberto96/GreenHouseApplication
95fc881cf9b0c12e9415df4efe4333ba4a857a1d
36c7aed0b0fb6bcd63f3bbefa45c246d3ec0ff0e
refs/heads/master
2021-09-23T00:03:58.088444
2018-09-18T20:45:16
2018-09-18T20:45:16
110,402,943
0
0
null
null
null
null
UTF-8
Java
false
false
774
java
package com.computomovilyubicuo.audiosender; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.computomovilyubicuo.audiosender", appContext.getPackageName()); } }
[ "oalberto96c@gmail.com" ]
oalberto96c@gmail.com
5f416afeb02ac9166fc8f4327d8488aef20a36c1
cabb1be82ece5b6bfe1df3b368182d2aad61360e
/okhttp3/internal/Util.java
2d46cd01e853e623d2fd8a1f4a14c45c3bb881d1
[]
no_license
sooraj2102/nagarro_hack_app
4f1d7c488c1acf7439081b1c379db044d4f9966b
3c7de860e75018fea2572ae06b3bdd2f7bf8b907
refs/heads/master
2021-07-01T12:56:33.829341
2020-10-01T09:56:23
2020-10-01T09:56:23
148,969,210
0
3
null
2020-10-01T09:56:24
2018-09-16T06:18:35
Java
UTF-8
Java
false
false
12,894
java
package okhttp3.internal; import java.io.Closeable; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.reflect.Array; import java.net.IDN; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import okhttp3.HttpUrl; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ByteString; import okio.Source; import okio.Timeout; public final class Util { public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; public static final RequestBody EMPTY_REQUEST; public static final ResponseBody EMPTY_RESPONSE; public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final TimeZone UTC; private static final Charset UTF_16_BE; private static final ByteString UTF_16_BE_BOM; private static final Charset UTF_16_LE; private static final ByteString UTF_16_LE_BOM; private static final Charset UTF_32_BE; private static final ByteString UTF_32_BE_BOM; private static final Charset UTF_32_LE; private static final ByteString UTF_32_LE_BOM; public static final Charset UTF_8; private static final ByteString UTF_8_BOM; private static final Pattern VERIFY_AS_IP_ADDRESS; static { EMPTY_RESPONSE = ResponseBody.create(null, EMPTY_BYTE_ARRAY); EMPTY_REQUEST = RequestBody.create(null, EMPTY_BYTE_ARRAY); UTF_8_BOM = ByteString.decodeHex("efbbbf"); UTF_16_BE_BOM = ByteString.decodeHex("feff"); UTF_16_LE_BOM = ByteString.decodeHex("fffe"); UTF_32_BE_BOM = ByteString.decodeHex("0000ffff"); UTF_32_LE_BOM = ByteString.decodeHex("ffff0000"); UTF_8 = Charset.forName("UTF-8"); UTF_16_BE = Charset.forName("UTF-16BE"); UTF_16_LE = Charset.forName("UTF-16LE"); UTF_32_BE = Charset.forName("UTF-32BE"); UTF_32_LE = Charset.forName("UTF-32LE"); UTC = TimeZone.getTimeZone("GMT"); VERIFY_AS_IP_ADDRESS = Pattern.compile("([0-9a-fA-F]*:[0-9a-fA-F:.]*)|([\\d.]+)"); } public static Charset bomAwareCharset(BufferedSource paramBufferedSource, Charset paramCharset) throws IOException { if (paramBufferedSource.rangeEquals(0L, UTF_8_BOM)) { paramBufferedSource.skip(UTF_8_BOM.size()); paramCharset = UTF_8; } do { return paramCharset; if (paramBufferedSource.rangeEquals(0L, UTF_16_BE_BOM)) { paramBufferedSource.skip(UTF_16_BE_BOM.size()); return UTF_16_BE; } if (paramBufferedSource.rangeEquals(0L, UTF_16_LE_BOM)) { paramBufferedSource.skip(UTF_16_LE_BOM.size()); return UTF_16_LE; } if (!paramBufferedSource.rangeEquals(0L, UTF_32_BE_BOM)) continue; paramBufferedSource.skip(UTF_32_BE_BOM.size()); return UTF_32_BE; } while (!paramBufferedSource.rangeEquals(0L, UTF_32_LE_BOM)); paramBufferedSource.skip(UTF_32_LE_BOM.size()); return UTF_32_LE; } public static void checkOffsetAndCount(long paramLong1, long paramLong2, long paramLong3) { if (((paramLong2 | paramLong3) < 0L) || (paramLong2 > paramLong1) || (paramLong1 - paramLong2 < paramLong3)) throw new ArrayIndexOutOfBoundsException(); } public static void closeQuietly(Closeable paramCloseable) { if (paramCloseable != null); try { paramCloseable.close(); return; } catch (RuntimeException localRuntimeException) { throw localRuntimeException; } catch (Exception localException) { } } public static void closeQuietly(ServerSocket paramServerSocket) { if (paramServerSocket != null); try { paramServerSocket.close(); return; } catch (RuntimeException localRuntimeException) { throw localRuntimeException; } catch (Exception localException) { } } public static void closeQuietly(Socket paramSocket) { if (paramSocket != null); try { paramSocket.close(); return; } catch (AssertionError localAssertionError) { while (isAndroidGetsocknameError(localAssertionError)); throw localAssertionError; } catch (RuntimeException localRuntimeException) { throw localRuntimeException; } catch (Exception localException) { } } public static String[] concat(String[] paramArrayOfString, String paramString) { String[] arrayOfString = new String[1 + paramArrayOfString.length]; System.arraycopy(paramArrayOfString, 0, arrayOfString, 0, paramArrayOfString.length); arrayOfString[(-1 + arrayOfString.length)] = paramString; return arrayOfString; } private static boolean containsInvalidHostnameAsciiCodes(String paramString) { for (int i = 0; i < paramString.length(); i++) { int j = paramString.charAt(i); if ((j <= 31) || (j >= 127)); do return true; while (" #%/:?@[\\]".indexOf(j) != -1); } return false; } public static int delimiterOffset(String paramString, int paramInt1, int paramInt2, char paramChar) { for (int i = paramInt1; i < paramInt2; i++) if (paramString.charAt(i) == paramChar) return i; return paramInt2; } public static int delimiterOffset(String paramString1, int paramInt1, int paramInt2, String paramString2) { for (int i = paramInt1; i < paramInt2; i++) if (paramString2.indexOf(paramString1.charAt(i)) != -1) return i; return paramInt2; } public static boolean discard(Source paramSource, int paramInt, TimeUnit paramTimeUnit) { try { boolean bool = skipAll(paramSource, paramInt, paramTimeUnit); return bool; } catch (IOException localIOException) { } return false; } public static String domainToAscii(String paramString) { String str; try { str = IDN.toASCII(paramString).toLowerCase(Locale.US); if (str.isEmpty()) return null; boolean bool = containsInvalidHostnameAsciiCodes(str); if (bool) return null; } catch (IllegalArgumentException localIllegalArgumentException) { str = null; } return str; } public static boolean equal(Object paramObject1, Object paramObject2) { return (paramObject1 == paramObject2) || ((paramObject1 != null) && (paramObject1.equals(paramObject2))); } public static String format(String paramString, Object[] paramArrayOfObject) { return String.format(Locale.US, paramString, paramArrayOfObject); } public static String hostHeader(HttpUrl paramHttpUrl, boolean paramBoolean) { if (paramHttpUrl.host().contains(":")); for (String str = "[" + paramHttpUrl.host() + "]"; ; str = paramHttpUrl.host()) { if ((paramBoolean) || (paramHttpUrl.port() != HttpUrl.defaultPort(paramHttpUrl.scheme()))) str = str + ":" + paramHttpUrl.port(); return str; } } public static <T> List<T> immutableList(List<T> paramList) { return Collections.unmodifiableList(new ArrayList(paramList)); } public static <T> List<T> immutableList(T[] paramArrayOfT) { return Collections.unmodifiableList(Arrays.asList((Object[])paramArrayOfT.clone())); } public static <T> int indexOf(T[] paramArrayOfT, T paramT) { int i = 0; int j = paramArrayOfT.length; while (i < j) { if (equal(paramArrayOfT[i], paramT)) return i; i++; } return -1; } public static int indexOfControlOrNonAscii(String paramString) { int i = 0; int j = paramString.length(); while (i < j) { int k = paramString.charAt(i); if ((k <= 31) || (k >= 127)) return i; i++; } return -1; } private static <T> List<T> intersect(T[] paramArrayOfT1, T[] paramArrayOfT2) { ArrayList localArrayList = new ArrayList(); int i = paramArrayOfT1.length; int j = 0; if (j < i) { T ? = paramArrayOfT1[j]; int k = paramArrayOfT2.length; for (int m = 0; ; m++) { if (m < k) { T ? = paramArrayOfT2[m]; if (!?.equals(?)) continue; localArrayList.add(?); } j++; break; } } return localArrayList; } public static <T> T[] intersect(Class<T> paramClass, T[] paramArrayOfT1, T[] paramArrayOfT2) { List localList = intersect(paramArrayOfT1, paramArrayOfT2); return localList.toArray((Object[])(Object[])Array.newInstance(paramClass, localList.size())); } public static boolean isAndroidGetsocknameError(AssertionError paramAssertionError) { return (paramAssertionError.getCause() != null) && (paramAssertionError.getMessage() != null) && (paramAssertionError.getMessage().contains("getsockname failed")); } public static boolean skipAll(Source paramSource, int paramInt, TimeUnit paramTimeUnit) throws IOException { long l1 = System.nanoTime(); long l2; if (paramSource.timeout().hasDeadline()) l2 = paramSource.timeout().deadlineNanoTime() - l1; while (true) { paramSource.timeout().deadlineNanoTime(l1 + Math.min(l2, paramTimeUnit.toNanos(paramInt))); try { Buffer localBuffer = new Buffer(); while (paramSource.read(localBuffer, 8192L) != -1L) localBuffer.clear(); } catch (InterruptedIOException localInterruptedIOException) { if (l2 == 9223372036854775807L) paramSource.timeout().clearDeadline(); while (true) { return false; l2 = 9223372036854775807L; break; if (l2 == 9223372036854775807L) paramSource.timeout().clearDeadline(); while (true) { return true; paramSource.timeout().deadlineNanoTime(l1 + l2); } paramSource.timeout().deadlineNanoTime(l1 + l2); } } finally { if (l2 != 9223372036854775807L) break label197; } } paramSource.timeout().clearDeadline(); while (true) { throw localObject; label197: paramSource.timeout().deadlineNanoTime(l1 + l2); } } public static int skipLeadingAsciiWhitespace(String paramString, int paramInt1, int paramInt2) { for (int i = paramInt1; i < paramInt2; i++) switch (paramString.charAt(i)) { default: return i; case '\t': case '\n': case '\f': case '\r': case ' ': } return paramInt2; } public static int skipTrailingAsciiWhitespace(String paramString, int paramInt1, int paramInt2) { for (int i = paramInt2 - 1; ; i--) { if (i >= paramInt1); switch (paramString.charAt(i)) { default: paramInt1 = i + 1; return paramInt1; case '\t': case '\n': case '\f': case '\r': case ' ': } } } public static ThreadFactory threadFactory(String paramString, boolean paramBoolean) { return new ThreadFactory(paramString, paramBoolean) { public Thread newThread(Runnable paramRunnable) { Thread localThread = new Thread(paramRunnable, this.val$name); localThread.setDaemon(this.val$daemon); return localThread; } }; } public static String toHumanReadableAscii(String paramString) { int i = 0; int j = paramString.length(); while (i < j) { int k = paramString.codePointAt(i); if ((k > 31) && (k < 127)) { i += Character.charCount(k); continue; } Buffer localBuffer = new Buffer(); localBuffer.writeUtf8(paramString, 0, i); int m = i; if (m < j) { int n = paramString.codePointAt(m); if ((n > 31) && (n < 127)); for (int i1 = n; ; i1 = 63) { localBuffer.writeUtf8CodePoint(i1); m += Character.charCount(n); break; } } paramString = localBuffer.readUtf8(); } return paramString; } public static String trimSubstring(String paramString, int paramInt1, int paramInt2) { int i = skipLeadingAsciiWhitespace(paramString, paramInt1, paramInt2); return paramString.substring(i, skipTrailingAsciiWhitespace(paramString, i, paramInt2)); } public static boolean verifyAsIpAddress(String paramString) { return VERIFY_AS_IP_ADDRESS.matcher(paramString).matches(); } } /* Location: /home/satyam/AndroidStudioProjects/app/dex2jar-0.0.9.15/classes-dex2jar.jar * Qualified Name: okhttp3.internal.Util * JD-Core Version: 0.6.0 */
[ "srjshingari@gmail.com" ]
srjshingari@gmail.com
cc927a22538fe3a1466cc83192d147dc0c1a543b
2627945793f55500887f7ffb90ad5e7f0333aa5b
/net/minecraft/item/EnumDyeColor.java
dd579ea937ff528a3665bcc4ea799fdbd70df5b0
[]
no_license
ClientPlayground/Lightning-Client
392aec9a84b791de63932473a333ab1585415807
b247c43a69d343abfa13a2a9940598fd07de4e4b
refs/heads/main
2022-07-30T05:05:54.106328
2021-04-18T18:15:43
2021-04-18T18:15:43
359,218,103
4
1
null
null
null
null
UTF-8
Java
false
false
3,903
java
package net.minecraft.item; import net.minecraft.block.material.*; import net.minecraft.util.*; public enum EnumDyeColor implements IStringSerializable { WHITE("WHITE", 0, 0, 15, "white", "white", MapColor.snowColor, EnumChatFormatting.WHITE), ORANGE("ORANGE", 1, 1, 14, "orange", "orange", MapColor.adobeColor, EnumChatFormatting.GOLD), MAGENTA("MAGENTA", 2, 2, 13, "magenta", "magenta", MapColor.magentaColor, EnumChatFormatting.AQUA), LIGHT_BLUE("LIGHT_BLUE", 3, 3, 12, "light_blue", "lightBlue", MapColor.lightBlueColor, EnumChatFormatting.BLUE), YELLOW("YELLOW", 4, 4, 11, "yellow", "yellow", MapColor.yellowColor, EnumChatFormatting.YELLOW), LIME("LIME", 5, 5, 10, "lime", "lime", MapColor.limeColor, EnumChatFormatting.GREEN), PINK("PINK", 6, 6, 9, "pink", "pink", MapColor.pinkColor, EnumChatFormatting.LIGHT_PURPLE), GRAY("GRAY", 7, 7, 8, "gray", "gray", MapColor.grayColor, EnumChatFormatting.DARK_GRAY), SILVER("SILVER", 8, 8, 7, "silver", "silver", MapColor.silverColor, EnumChatFormatting.GRAY), CYAN("CYAN", 9, 9, 6, "cyan", "cyan", MapColor.cyanColor, EnumChatFormatting.DARK_AQUA), PURPLE("PURPLE", 10, 10, 5, "purple", "purple", MapColor.purpleColor, EnumChatFormatting.DARK_PURPLE), BLUE("BLUE", 11, 11, 4, "blue", "blue", MapColor.blueColor, EnumChatFormatting.DARK_BLUE), BROWN("BROWN", 12, 12, 3, "brown", "brown", MapColor.brownColor, EnumChatFormatting.GOLD), GREEN("GREEN", 13, 13, 2, "green", "green", MapColor.greenColor, EnumChatFormatting.DARK_GREEN), RED("RED", 14, 14, 1, "red", "red", MapColor.redColor, EnumChatFormatting.DARK_RED), BLACK("BLACK", 15, 15, 0, "black", "black", MapColor.blackColor, EnumChatFormatting.BLACK); private static final EnumDyeColor[] META_LOOKUP; private static final EnumDyeColor[] DYE_DMG_LOOKUP; private final int meta; private final int dyeDamage; private final String name; private final String unlocalizedName; private final MapColor mapColor; private final EnumChatFormatting chatColor; static { META_LOOKUP = new EnumDyeColor[values().length]; DYE_DMG_LOOKUP = new EnumDyeColor[values().length]; EnumDyeColor[] values; for (int length = (values = values()).length, i = 0; i < length; ++i) { final EnumDyeColor enumdyecolor = values[i]; EnumDyeColor.META_LOOKUP[enumdyecolor.getMetadata()] = enumdyecolor; EnumDyeColor.DYE_DMG_LOOKUP[enumdyecolor.getDyeDamage()] = enumdyecolor; } } private EnumDyeColor(final String s, final int n, final int meta, final int dyeDamage, final String name, final String unlocalizedName, final MapColor mapColorIn, final EnumChatFormatting chatColor) { this.meta = meta; this.dyeDamage = dyeDamage; this.name = name; this.unlocalizedName = unlocalizedName; this.mapColor = mapColorIn; this.chatColor = chatColor; } public int getMetadata() { return this.meta; } public int getDyeDamage() { return this.dyeDamage; } public String getUnlocalizedName() { return this.unlocalizedName; } public MapColor getMapColor() { return this.mapColor; } public static EnumDyeColor byDyeDamage(int damage) { if (damage < 0 || damage >= EnumDyeColor.DYE_DMG_LOOKUP.length) { damage = 0; } return EnumDyeColor.DYE_DMG_LOOKUP[damage]; } public static EnumDyeColor byMetadata(int meta) { if (meta < 0 || meta >= EnumDyeColor.META_LOOKUP.length) { meta = 0; } return EnumDyeColor.META_LOOKUP[meta]; } @Override public String toString() { return this.unlocalizedName; } @Override public String getName() { return this.name; } }
[ "nebulalol@icloud.com" ]
nebulalol@icloud.com
acef678f8ad72b65b54a84cc167a315ac46c8192
ea3b00c129d5ea3d70a2b36b724c8cd92913ecfb
/app/src/main/java/enjoyor/enjoyorzemobilehealth/views/AutoTemperatureChart.java
3f4c905eb82b9f63f6a1cb9ffa9fb0e2394ec8f3
[]
no_license
15617817921/ydlc
3f615fd4e941b711c79be94b8101214dd98cffbe
bc7390dbcf70a962e25243d7760fa7ab60b64751
refs/heads/master
2020-04-23T00:38:42.584777
2019-06-05T06:04:17
2019-06-05T06:04:17
170,786,941
0
0
null
null
null
null
UTF-8
Java
false
false
7,567
java
package enjoyor.enjoyorzemobilehealth.views; import android.content.Context; import android.graphics.Canvas; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import java.util.ArrayList; import java.util.List; import enjoyor.enjoyorzemobilehealth.entities.TiWen; import enjoyor.enjoyorzemobilehealth.utlis.ScreenUtils; /** * Created by Administrator on 2017/5/3. */ public class AutoTemperatureChart extends View { //private String[] xLineData = new String[]{"01/01", "01/01", "01/01", "01/01", "01/01", "01/01"}; private String[] yLineData = new String[]{"35", "36", "37", "38", "39", "40", "41", "42"}; //private String[] value = new String[]{"36.1", "36.6", "38.2", "36.5", "39.3", "37.5"}; private List<TiWen> valueList = new ArrayList<>(); private static final int PER_PAGE_COUNT = 4; private Context context; public AutoTemperatureChart(Context context) { super(context); } public AutoTemperatureChart(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AutoTemperatureChart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } // public AutoTemperatureChart(Context context, String[] xLineData, String[] value) { // super(context); // this.context=context; // this.xLineData = xLineData; // this.value = value; // } public AutoTemperatureChart(Context context, List<TiWen> temperatureList) { super(context); this.context = context; choose(temperatureList); } private void choose(List<TiWen> list) { TiWen tiWen = null; for (int i = 0; i < list.size(); i++) { tiWen = list.get(i); if (tiWen.getLeiXing().equals("1")) { valueList.add(tiWen); } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //图标宽度 int chartWidth = this.getWidth(); Log.i("data", chartWidth + "chartWidth------------"); //图标高度 int chartHeight = this.getHeight(); Log.i("data", chartHeight + "chartHeight------------"); //上边距 int padding_top = chartHeight / 8; //右边距 int padding_right = ScreenUtils.getScreenWidth(context) / 8; //左边距 int padding_left = ScreenUtils.getScreenWidth(context) / 8; //下边距 int padding_bottom = chartHeight / 6; //原点坐标 int xPoint = padding_left; int yPoint = chartHeight - padding_bottom; //画X轴 Paint paintXY = new Paint(); //虚线效果,第一个参数:先画长度3的实线,间隔长度为8的空白,数组中可以有很多数,需要成对出现 // 第二个参数为第一种参数这种效果执行时后面复制这种效果间隔的空白的长度 DashPathEffect pathEffect = new DashPathEffect(new float[]{3, 8}, 0); paintXY.setStyle(Paint.Style.STROKE); paintXY.setStrokeWidth(3); paintXY.setColor(0xFF91908E); paintXY.setAntiAlias(true); Path path = new Path(); path.moveTo(xPoint, yPoint); path.lineTo(chartWidth - padding_right, yPoint); paintXY.setPathEffect(pathEffect); //画X轴虚线 //canvas.drawLine(xPoint,yPoint,chartWidth-padding_right,yPoint,paintXY); canvas.drawPath(path, paintXY); //画X轴,Y轴文字的画笔 Paint paintXYText = new Paint(); paintXYText.setStyle(Paint.Style.FILL); paintXYText.setStrokeWidth(1); paintXYText.setColor(0xFF91908E); paintXYText.setAntiAlias(true); paintXYText.setTextSize(20); //画X轴文字 //int perWidth=(chartWidth-padding_left-padding_right)/(xLineData.length-1); //int perWidth=(chartWidth-padding_left-padding_right)/PER_PAGE_COUNT; int perWidth = (ScreenUtils.getScreenWidth(context) - padding_left - padding_right) / (PER_PAGE_COUNT - 1); for (int i = 0; i < valueList.size(); i++) { String xRQData = valueList.get(i).getCaiJiRQ(); String xSJdata = valueList.get(i).getCaiJiSJ(); float textWidthRQ = paintXYText.measureText(xRQData); float textWidthSJ = paintXYText.measureText(xSJdata); canvas.drawText(xRQData, padding_left + i * perWidth - textWidthRQ / 2, yPoint + 30, paintXYText); canvas.drawText(xSJdata, padding_left + i * perWidth - textWidthSJ / 2, yPoint + 50, paintXYText); } //画X轴单位 canvas.drawText("(t)", chartWidth - padding_right + 20, yPoint + 10, paintXYText); //画Y轴相关的文字,单位及横向虚线 int perHeight = (chartHeight - padding_top - padding_bottom) / (yLineData.length - 1); for (int i = 0; i < yLineData.length; i++) { if (i > 0) { Path pathY = new Path(); pathY.moveTo(xPoint, yPoint - perHeight * i); pathY.lineTo(chartWidth - padding_right, yPoint - perHeight * i); //画折线区域内横向虚线 canvas.drawPath(pathY, paintXY); } //画Y轴文字 canvas.drawText(yLineData[i], xPoint - 30, yPoint - i * perHeight, paintXYText); } //画Y轴单位 canvas.drawText("(℃)", xPoint - 30, yPoint - (yLineData.length - 1) * perHeight - 20, paintXYText); //画折线区域内点及折线的画笔 Paint paintContent = new Paint(); paintContent.setStyle(Paint.Style.FILL); paintContent.setStrokeWidth(4); paintContent.setColor(0xFFFF4900); paintContent.setAntiAlias(true); //画折线区域内数字的画笔 Paint paintContentText = new Paint(); paintContentText.setStyle(Paint.Style.FILL); paintContentText.setStrokeWidth(1); paintContentText.setColor(0xFFFF4900); paintContentText.setAntiAlias(true); paintContentText.setTextSize(20); //画温度值及连接线 for (int i = 0; i < valueList.size(); i++) { String temperatureData = valueList.get(i).getTiWen(); int xPos = xPoint + perWidth * i; float yPos = yPoint - yPosition(temperatureData) * perHeight; //画温度圆圈 canvas.drawCircle(xPos, yPos, 9, paintContent); //画圆圈上数字 canvas.drawText(temperatureData, xPos, yPos - 15, paintContentText); //有效值判断 if (i > 0 && yPosition(valueList.get(i - 1).getTiWen()) != -999f && yPosition(temperatureData) != -999f) { int xPrePos = xPoint + perWidth * (i - 1); float yPrePos = yPoint - yPosition(valueList.get(i - 1).getTiWen()) * perHeight; //画相邻圆圈间的连接线 canvas.drawLine(xPrePos, yPrePos, xPos, yPos, paintContent); } } } /** * 计算相对于y轴原点偏移量 * * @param yValue * @return */ private float yPosition(String yValue) { try { return Float.parseFloat(yValue) - 35; } catch (Exception e) { e.printStackTrace(); return -999f; } } }
[ "1454846769@qq.com" ]
1454846769@qq.com
7d8c09f76bad4703fdd8145d16c38cc86c15c032
a0b5419b03e33cae266342847e902c152668b0d6
/Define.java
e3126e3931d5ca812d04275ee575dccb327f6ef6
[]
no_license
bhavanaswarna/Epam
e269b184d0ace1502d942aac73eabc392007263f
67ec86343c193260f78b4dd9d3e3f2f652d99938
refs/heads/master
2020-12-21T20:57:38.387061
2020-02-20T17:48:02
2020-02-20T17:48:02
236,557,407
0
0
null
null
null
null
UTF-8
Java
false
false
329
java
package CleanCode.CleanCode; import java.io.*; public class Define { public double simple(double prin,double in,double per ) { double y=(prin*in*per)/100; return y; } public double compound(double p,double in,double per ) { double y=p*(Math.pow((1+(in/100)),per)); y=y-p; return y; } }
[ "noreply@github.com" ]
bhavanaswarna.noreply@github.com
49d2b979166af868f878974bc88ef5b7cfd7dc9c
a662c68cb436e3c3e99247130fd28837c9843b51
/src/main/java/com/qf/controller/OrderInfoController.java
fceeb3804a3acd2c3ec238466482abb0d56a1b14
[]
no_license
woshiguochao/-5041
004cf28c1142bada4ea5063f15ac2ca1d5f8cec4
3d9c4d5ca44c2660df9e9d4cbff59c633726cfcb
refs/heads/master
2022-12-04T00:51:45.557826
2020-08-11T14:59:54
2020-08-11T14:59:54
286,719,440
0
0
null
null
null
null
UTF-8
Java
false
false
1,578
java
package com.qf.controller; import com.qf.pojo.OrderInfo; import com.qf.pojo.UserInfo; import com.qf.service.OrderInfoService; import com.qf.vo.OrderInfoVO; import com.qf.vo.ShipaddressVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.util.List; @RestController public class OrderInfoController { @Autowired OrderInfoService orderInfoService; //接受购物车发来的订单信息 @RequestMapping("addOrderFromCart") public Object addOrderFromCart(@RequestBody OrderInfo orderInfo){ Object o = this.orderInfoService.addOrderFromCart(orderInfo); System.out.println("addOrderFromCart:加入orderinfo"); return o; } @RequestMapping("selectOrderInfo") public List<OrderInfoVO> selectOrderInfo(@RequestParam int orderid){ List<OrderInfoVO> orderInfoVOS = orderInfoService.selectOrderInfo(orderid); System.out.println("selectOrderInfo"); return orderInfoVOS; } @RequestMapping("selectshipaddress") public List<ShipaddressVO> selectshipaddress(HttpSession session){ List<ShipaddressVO> shipaddress = orderInfoService.selectshipaddress((Integer)session.getAttribute("userId")); System.out.println("selectshipaddress"); return shipaddress; } }
[ "2720225813@qq.com" ]
2720225813@qq.com
5e192a7f365de31ff565867ddbfcd41e76d99d14
9efdb7d314e5dc90a2568ce1d613c0ff02ccfc4b
/app/src/main/java/com/yusong/community/ui/school/mvp/presenter/IDutyTeacherActivityPresenter.java
54adeaba5eef65c3390ad9127060145616aa70be
[]
no_license
feisher/community_huangshan2
1cdcb55e2b9c6394e7f0ac043b2d3c02fed04408
aa3fc8103a0e6be8de89d0c7d81d2869724c4443
refs/heads/master
2021-07-14T18:15:52.164494
2017-10-19T03:25:01
2017-10-19T03:25:01
106,365,007
0
0
null
null
null
null
UTF-8
Java
false
false
318
java
package com.yusong.community.ui.school.mvp.presenter; import com.yusong.community.mvp.BasePresenter; /** * Created by ruanjian on 2017/3/8. */ public interface IDutyTeacherActivityPresenter extends BasePresenter{ void searchTeacherList(String token); void setOndutyTeacher(String token,int teacherId); }
[ "458079442@qq.com" ]
458079442@qq.com
b8dc05e2ec9036fa8d61134c5857fe9ac1f83f70
5da3652b7145992568c0bae29b6e9c45513a0fff
/src/test/java/com/averros/data/codemapper/utils/SpringUtilsTest.java
dc76dbc43869ad3a8627550b69c7ad689d4771c1
[]
no_license
swajahataziz/PentaCoder
63633399a09b498d4291f44f38d86b2fcc02f4cc
30eb722488347d5741e84e76173e617e878bc4a7
refs/heads/master
2020-05-04T23:58:28.651259
2019-05-24T21:47:18
2019-05-24T21:47:18
179,562,014
0
0
null
null
null
null
UTF-8
Java
false
false
1,709
java
package com.averros.data.codemapper.utils; import org.junit.Assert; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; @SpringBootTest public class SpringUtilsTest { @Test public void testSplitWithCommaSeparator() { String testString = "This is a test,it has three columns,this is the third column"; List<String> result = StringUtils.split(testString, ','); List<String> expected = Arrays.asList("This is a test","it has three columns","this is the third column"); Assert.assertThat(result, is(expected)); Assert.assertThat(result, hasItems("This is a test")); } @Test public void testSplitWithPipeSeparator() { String testString = "This is a test|it has three columns|this is the third column"; List<String> result = StringUtils.split(testString, '|'); List<String> expected = Arrays.asList("This is a test","it has three columns","this is the third column"); Assert.assertThat(result, is(expected)); Assert.assertThat(result, hasItems("This is a test")); } @Test public void testSplitWithEscapeCharacters() { String testString = "This is a test|it has \"three\" columns|this is the third column"; List<String> result = StringUtils.split(testString, '|'); List<String> expected = Arrays.asList("This is a test","it has three columns","this is the third column"); Assert.assertThat(result, is(expected)); Assert.assertThat(result, hasItems("This is a test")); } }
[ "swajahataziz@hotmail.com" ]
swajahataziz@hotmail.com
8d737d59818449c0b3d2584b653ba7a0e9bae02b
10e2179dd0907a619696721c6b94beb6e5875812
/ThinkingInJava/src/MyLexer/Lexer.java
4779fce484d1989a137b6f2c51440b3bb2d7a144
[]
no_license
Charles2Alvin/Java-Practice
0610ebf86d16eaf8383b2866e9b790b5374fb3c2
519237a791c57a56553502350f322e936eace1a2
refs/heads/master
2020-05-18T01:37:00.916107
2019-04-29T15:15:57
2019-04-29T15:15:57
184,093,837
0
0
null
null
null
null
UTF-8
Java
false
false
1,006
java
package MyLexer; import java.io.*; public class Lexer { private static String readFile(String filePath) { String outputPath = "/Users/mohaitao/Desktop/lexerOutput.txt"; try { DataInputStream in = new DataInputStream(new FileInputStream(filePath)); BufferedReader d = new BufferedReader(new InputStreamReader(in)); StringBuffer buffer = new StringBuffer(); String count; while((count = d.readLine()) != null){ buffer.append(count+"\n"); } d.close(); return buffer.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String filePath = "/Users/mohaitao/Desktop/exampleProgram.txt"; String result = Lexer.readFile(filePath); System.out.println(result); } }
[ "yggg100@126.com" ]
yggg100@126.com
c093f26ed1b42773678bc678f0fcf9508b93cf7f
9d09f0a59fe5087000ce4010737441357de9ae65
/app/src/main/java/com/xsvideoLive/www/mvp/ui/fragment/square/RecommendFragment.java
eff2866f60db9e9f0a72947182c0466f72d7b049
[]
no_license
lgh990/XiuSe
694e6fd078fec2c4ca537654f8d4aeef5037272d
b3d659c47fae10cf59b2a8fe1eeb65e68f82836f
refs/heads/master
2023-03-01T13:14:19.763557
2021-02-02T04:53:38
2021-02-02T04:53:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,053
java
package com.xsvideoLive.www.mvp.ui.fragment.square; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.listener.OnItemClickListener; import com.xsvideoLive.www.R; import com.xsvideoLive.www.base.BaseMvpFragment; import com.xsvideoLive.www.callback.FriendFabulousCallback; import com.xsvideoLive.www.constant.Constant; import com.xsvideoLive.www.mvp.contract.RecommendContract; import com.xsvideoLive.www.mvp.presenter.RecommendPresenter; import com.xsvideoLive.www.mvp.ui.activity.mine.HomePageAct; import com.xsvideoLive.www.mvp.ui.activity.mine.MyBuddyAct; import com.xsvideoLive.www.mvp.ui.activity.msg.ReportAct; import com.xsvideoLive.www.mvp.ui.activity.square.MessageDetailsAct; import com.xsvideoLive.www.mvp.ui.adapter.FriendsCircleAdapter; import com.xsvideoLive.www.net.bean.FriendsCircleResult; import com.xsvideoLive.www.utils.ActStartUtils; import com.xsvideoLive.www.utils.SPUtils; import com.xsvideoLive.www.utils.ToastUtils; import com.xsvideoLive.www.view.TipsDialog; import com.lzy.ninegrid.ImageInfo; import com.lzy.ninegrid.PhotoCallback; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity; public class RecommendFragment extends BaseMvpFragment<RecommendPresenter> implements RecommendContract.View, OnRefreshLoadMoreListener, PhotoCallback, OnItemClickListener, FriendFabulousCallback { @BindView(R.id.refreshLayout) SmartRefreshLayout refreshLayout; @BindView(R.id.rl_view) RecyclerView rlView; private FriendsCircleAdapter mAdapter; @Override public int setLayoutId() { return R.layout.fragment_recommend; } @Override protected RecommendPresenter createPresenter() { return new RecommendPresenter(); } @Override public void initView(Bundle savedInstanceState) { mPresenter.attachView(this); refreshLayout.setOnRefreshLoadMoreListener(this); } @Override protected void onLazyLoad() { mAdapter = new FriendsCircleAdapter(getActivity(), this); mAdapter.setFabulousCallback(this); rlView.setLayoutManager(new LinearLayoutManager(getActivity())); rlView.setAdapter(mAdapter); refreshLayout.autoRefresh(); } @Override public void refresh(RefreshLayout refreshLayout, List<FriendsCircleResult> roomResults) { refreshLayout.finishRefresh(); mAdapter.setList(roomResults); if (roomResults.size() <= 0) { refreshLayout.finishLoadMoreWithNoMoreData(); } else { refreshLayout.resetNoMoreData(); } } @Override public void loadMore(RefreshLayout refreshLayout, List<FriendsCircleResult> roomResults) { mAdapter.addData(roomResults); if (roomResults.size() <= 0) { refreshLayout.finishLoadMoreWithNoMoreData(); } else { refreshLayout.finishLoadMore(); } } @Override public void onError(RefreshLayout refreshLayout, String msg) { } @Override public void fabulousSuccess(String msg) { } @Override public void onDeleteSuccess(String status, FriendsCircleResult result) { if (status.equals("1")) { mAdapter.remove(result); } } @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) { mPresenter.mPage = mPresenter.initPage; mPresenter.getFriendsCircle(refreshLayout); } @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) { mPresenter.getFriendsCircle(refreshLayout); } @Override public void onItemPhotoClick(int index, List<ImageInfo> imageInfo) { ArrayList<String> imgs = new ArrayList<>(); for (ImageInfo info : imageInfo) { imgs.add(info.getBigImageUrl()); } photoPreviewWrapper(index, imgs); } private void photoPreviewWrapper(int index, ArrayList<String> imageInfo) { BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(getActivity()) .saveImgDir(new File(Constant.FILE_PATH)); // 保存图片的目录,如果传 null,则没有保存图片功能 if (imageInfo.size() == 1) { // 预览单张图片 photoPreviewIntentBuilder.previewPhoto(imageInfo.get(index)); } else if (imageInfo.size() > 1) { // 预览多张图片 photoPreviewIntentBuilder.previewPhotos(imageInfo) .currentPosition(index); // 当前预览图片的索引 } startActivity(photoPreviewIntentBuilder.build()); } @Override public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) { ToastUtils.showShort("position:" + position); } @Override public void onClickFabulous(FriendsCircleResult result, int position) { int hasLike = result.getHasLike();//是否点赞 int likeNumber = result.getLikeNumber();//点赞数 if (hasLike == 1) { result.setHasLike(0); result.setLikeNumber(likeNumber - 1); } else if (hasLike == 0) { result.setHasLike(1); result.setLikeNumber(likeNumber + 1); } mAdapter.notifyDataSetChanged(); mPresenter.fabulous(result.getId()); } @Override public void onClickComment(FriendsCircleResult result, int position) { Bundle bundle = new Bundle(); bundle.putSerializable(Constant.FRIEND_CIRCLE_RESULT, result); ActStartUtils.startAct(getActivity(), MessageDetailsAct.class, bundle); } @Override public void onClickShare(FriendsCircleResult result, int position) { TipsDialog.createDialog(getActivity(), R.layout.dialog_share) .bindClick(R.id.tv_cancel, (v, dialog) -> { dialog.dismiss(); }) .bindClick(R.id.tv_share_buddy, (v, dialog) -> { Bundle bundle = new Bundle(); bundle.putString(Constant.BUDDY_KEY, Constant.TOPIC); bundle.putSerializable(Constant.TOPIC, result); ActStartUtils.startAct(getActivity(), MyBuddyAct.class, bundle); }) .show(); } @Override public void onClickAvater(FriendsCircleResult result, int position) { Bundle bundle = new Bundle(); bundle.putString(Constant.USER_ID, result.getUserId()); ActStartUtils.startAct(getActivity(), HomePageAct.class, bundle); } @Override public void onClickMore(FriendsCircleResult result, int position) { more(result, SPUtils.getInstance().getUserInfo().getId()); } // private void more(FriendsCircleResult result) { // // TipsDialog.createDialog(getActivity(), R.layout.dialog_select_camera) // .setTextColor(R.id.tv_camera, R.color.color_black) // .setText(R.id.tv_camera, "举报") // .setTextColor(R.id.tv_photo, R.color.color_aaaaaa) // .setText(R.id.tv_photo, "取消") // .bindClick(R.id.tv_camera, (v, dialog) -> { // Bundle bundle = new Bundle(); // bundle.putString(Constant.REPOTR_TYPE,Constant.REPORT_TYPE_USER); // bundle.putString(Constant.REPORT_ID,result.getUserId()); // ActStartUtils.startAct(getActivity(), ReportAct.class,bundle); // dialog.dismiss(); // }) // .bindClick(R.id.tv_photo, (v, dialog) -> { // dialog.dismiss(); // }) // .show(); // } /** * 根据myUserId 判断是否为自己发出的朋友圈 * * @param result * @param myUserId */ private void more(FriendsCircleResult result, String myUserId) { String userId = result.getUserId(); TipsDialog tipsDialog = TipsDialog.createDialog(getActivity(), R.layout.dialog_select_camera) .setTextColor(R.id.tv_camera, R.color.color_black) .setTextColor(R.id.tv_photo, R.color.color_aaaaaa) .setText(R.id.tv_photo, "取消") .bindClick(R.id.tv_camera, (v, dialog) -> { dialog.dismiss(); if (userId.equals(myUserId)) { //删除 // ToastUtils.showShort("删除"); mPresenter.deleteTopic(result.getId(), result); } else { //举报 // ToastUtils.showShort("举报"); Bundle bundle = new Bundle(); bundle.putString(Constant.REPOTR_TYPE, Constant.REPORT_TYPE_USER); bundle.putString(Constant.REPORT_ID, result.getUserId()); ActStartUtils.startAct(getActivity(), ReportAct.class, bundle); dialog.dismiss(); } }) .bindClick(R.id.tv_photo, (v, dialog) -> { dialog.dismiss(); }); if (userId.equals(myUserId)) { tipsDialog.setText(R.id.tv_camera, "删除"); } else { tipsDialog.setText(R.id.tv_camera, "举报"); } tipsDialog.show(); } @Override public void onResume() { super.onResume(); if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } }
[ "895977304@qq.com" ]
895977304@qq.com
6b68671552be1b3548bed4d42a1fe1d0f2f11cf2
2360dd00aa57355e542d5edc0d8a9d058f71b7b9
/JMapper Framework/src/test/java/com/googlecode/jmapper/operations/complex/MapConversion3Test.java
5c7684463d6c9b032313e4d27e7e5bcbe820627a
[]
no_license
madhu4a3/jmapper-framework
3367d99a60373a3aec1fe122d7f945937fad6d13
75d034529c1ac86cc0b311130f2698a362a0866c
refs/heads/master
2021-01-10T07:49:30.745004
2015-04-17T11:29:22
2015-04-17T11:29:22
48,153,004
0
0
null
null
null
null
UTF-8
Java
false
false
11,301
java
package com.googlecode.jmapper.operations.complex; import static com.googlecode.jmapper.util.GeneralUtility.newLine; import java.lang.reflect.Field; import java.util.TreeMap; import com.googlecode.jmapper.bean.ComplexClass; import com.googlecode.jmapper.enums.ConversionType; import com.googlecode.jmapper.enums.OperationType; import com.googlecode.jmapper.operations.AOperation; import com.googlecode.jmapper.operations.info.InfoMapOperation; import com.googlecode.jmapper.operations.info.InfoOperation; public class MapConversion3Test extends AOperation<MapOperation>{ @Override protected Field getDField() throws NoSuchFieldException { return ComplexClass.class.getDeclaredField("aDConversionMap2"); } @Override protected Field getSField() throws NoSuchFieldException { return ComplexClass.class.getDeclaredField("aSConversionMap2"); } @Override protected MapOperation getOperationIstance() { return new MapOperation(); } @Override protected InfoOperation getInfoOperation() { return new InfoMapOperation().setKeyInstructionType (OperationType.BASIC_INSTRUCTION) .setValueInstructionType(OperationType.BASIC_INSTRUCTION) .setKeyConversionType (ConversionType.FromIntegerToString) .setValueConversionType (ConversionType.ABSENT) .setConversionType (ConversionType.DEFINED); } @Override protected void setUp() { super.setUp(); operation.setDestinationClass(TreeMap.class); } @Override protected void AllAll() { expected = " if(source.getASConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$i = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$i = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$i = mapOfSource$i.length-1;index$i >=0;index$i--){"+ newLine + " java.util.Map.Entry entryItem$i = (java.util.Map.Entry) mapOfSource$i[index$i];"+ newLine + " java.lang.Integer sourceKeyObj$i = (java.lang.Integer) entryItem$i.getKey();"+ newLine + " java.lang.String sourceValueObj$i = (java.lang.String) entryItem$i.getValue();"+ newLine + " java.lang.String destinationKeyObj$i = sourceKeyObj$i.toString();"+ newLine + " mapOfDestination$i.put(destinationKeyObj$i, sourceValueObj$i);"+ newLine + " }"+ newLine + " destination.setADConversionMap2(mapOfDestination$i);"+ newLine + newLine + " }else{"+ newLine + " destination.setADConversionMap2(null);"+ newLine + " }"+newLine; write(newInstance); verify(); expected = " if(destination.getADConversionMap2()!=null){"+ newLine + " if(source.getASConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$i = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$i = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$i = mapOfSource$i.length-1;index$i >=0;index$i--){"+ newLine + " java.util.Map.Entry entryItem$i = (java.util.Map.Entry) mapOfSource$i[index$i];"+ newLine + " java.lang.Integer sourceKeyObj$i = (java.lang.Integer) entryItem$i.getKey();"+ newLine + " java.lang.String sourceValueObj$i = (java.lang.String) entryItem$i.getValue();"+ newLine + " java.lang.String destinationKeyObj$i = sourceKeyObj$i.toString();"+ newLine + " mapOfDestination$i.put(destinationKeyObj$i, sourceValueObj$i);"+ newLine + " }"+ newLine + " destination.getADConversionMap2().putAll(mapOfDestination$i);"+ newLine + newLine + " }else{"+ newLine + " destination.setADConversionMap2(null);"+ newLine + " }"+ newLine + " }else{"+ newLine + " if(source.getASConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$y = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$y = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$y = mapOfSource$y.length-1;index$y >=0;index$y--){"+ newLine + " java.util.Map.Entry entryItem$y = (java.util.Map.Entry) mapOfSource$y[index$y];"+ newLine + " java.lang.Integer sourceKeyObj$y = (java.lang.Integer) entryItem$y.getKey();"+ newLine + " java.lang.String sourceValueObj$y = (java.lang.String) entryItem$y.getValue();"+ newLine + " java.lang.String destinationKeyObj$y = sourceKeyObj$y.toString();"+ newLine + " mapOfDestination$y.put(destinationKeyObj$y, sourceValueObj$y);"+ newLine + " }"+ newLine + " destination.setADConversionMap2(mapOfDestination$y);"+ newLine + newLine + " }else{"+ newLine + " destination.setADConversionMap2(null);"+ newLine + " }"+ newLine + " }"+newLine; write(enrichment); verify(); } @Override protected void AllValued() { expected = " if(source.getASConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$i = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$i = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$i = mapOfSource$i.length-1;index$i >=0;index$i--){"+ newLine + " java.util.Map.Entry entryItem$i = (java.util.Map.Entry) mapOfSource$i[index$i];"+ newLine + " java.lang.Integer sourceKeyObj$i = (java.lang.Integer) entryItem$i.getKey();"+ newLine + " java.lang.String sourceValueObj$i = (java.lang.String) entryItem$i.getValue();"+ newLine + " java.lang.String destinationKeyObj$i = sourceKeyObj$i.toString();"+ newLine + " mapOfDestination$i.put(destinationKeyObj$i, sourceValueObj$i);"+ newLine + " }"+ newLine + " destination.setADConversionMap2(mapOfDestination$i);"+ newLine + newLine + " }"+newLine; write(newInstance); verify(); expected = " if(source.getASConversionMap2()!=null){"+ newLine + " if(destination.getADConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$i = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$i = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$i = mapOfSource$i.length-1;index$i >=0;index$i--){"+ newLine + " java.util.Map.Entry entryItem$i = (java.util.Map.Entry) mapOfSource$i[index$i];"+ newLine + " java.lang.Integer sourceKeyObj$i = (java.lang.Integer) entryItem$i.getKey();"+ newLine + " java.lang.String sourceValueObj$i = (java.lang.String) entryItem$i.getValue();"+ newLine + " java.lang.String destinationKeyObj$i = sourceKeyObj$i.toString();"+ newLine + " mapOfDestination$i.put(destinationKeyObj$i, sourceValueObj$i);"+ newLine + " }"+ newLine + " destination.getADConversionMap2().putAll(mapOfDestination$i);"+ newLine + newLine + " }else{"+ newLine + " java.util.TreeMap mapOfDestination$y = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$y = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$y = mapOfSource$y.length-1;index$y >=0;index$y--){"+ newLine + " java.util.Map.Entry entryItem$y = (java.util.Map.Entry) mapOfSource$y[index$y];"+ newLine + " java.lang.Integer sourceKeyObj$y = (java.lang.Integer) entryItem$y.getKey();"+ newLine + " java.lang.String sourceValueObj$y = (java.lang.String) entryItem$y.getValue();"+ newLine + " java.lang.String destinationKeyObj$y = sourceKeyObj$y.toString();"+ newLine + " mapOfDestination$y.put(destinationKeyObj$y, sourceValueObj$y);"+ newLine + " }"+ newLine + " destination.setADConversionMap2(mapOfDestination$y);"+ newLine + newLine + " }"+ newLine + " }"+newLine; write(enrichment); verify(); } @Override protected void ValuedAll() { expected = " if(destination.getADConversionMap2()!=null){"+ newLine + " if(source.getASConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$i = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$i = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$i = mapOfSource$i.length-1;index$i >=0;index$i--){"+ newLine + " java.util.Map.Entry entryItem$i = (java.util.Map.Entry) mapOfSource$i[index$i];"+ newLine + " java.lang.Integer sourceKeyObj$i = (java.lang.Integer) entryItem$i.getKey();"+ newLine + " java.lang.String sourceValueObj$i = (java.lang.String) entryItem$i.getValue();"+ newLine + " java.lang.String destinationKeyObj$i = sourceKeyObj$i.toString();"+ newLine + " mapOfDestination$i.put(destinationKeyObj$i, sourceValueObj$i);"+ newLine + " }"+ newLine + " destination.getADConversionMap2().putAll(mapOfDestination$i);"+ newLine + newLine + " }else{"+ newLine + " destination.setADConversionMap2(null);"+ newLine + " }"+ newLine + " }"+newLine; write(enrichment); verify(); } @Override protected void ValuedValued() { expected = " if(destination.getADConversionMap2()!=null){"+ newLine + " if(source.getASConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$i = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$i = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$i = mapOfSource$i.length-1;index$i >=0;index$i--){"+ newLine + " java.util.Map.Entry entryItem$i = (java.util.Map.Entry) mapOfSource$i[index$i];"+ newLine + " java.lang.Integer sourceKeyObj$i = (java.lang.Integer) entryItem$i.getKey();"+ newLine + " java.lang.String sourceValueObj$i = (java.lang.String) entryItem$i.getValue();"+ newLine + " java.lang.String destinationKeyObj$i = sourceKeyObj$i.toString();"+ newLine + " mapOfDestination$i.put(destinationKeyObj$i, sourceValueObj$i);"+ newLine + " }"+ newLine + " destination.getADConversionMap2().putAll(mapOfDestination$i);"+ newLine + newLine + " }"+ newLine + " }"+newLine; write(enrichment); verify(); } @Override protected void ValuedNull() { expected = " if(destination.getADConversionMap2()!=null){"+ newLine + " if(source.getASConversionMap2()==null){"+ newLine + " destination.setADConversionMap2(null);"+ newLine + " }"+ newLine + " }"+newLine; write(enrichment); verify(); } @Override protected void NullValued() { expected = " if(destination.getADConversionMap2()==null){"+ newLine + " if(source.getASConversionMap2()!=null){"+ newLine + " java.util.TreeMap mapOfDestination$i = new java.util.TreeMap();"+ newLine + " Object[] mapOfSource$i = source.getASConversionMap2().entrySet().toArray();"+ newLine + " for(int index$i = mapOfSource$i.length-1;index$i >=0;index$i--){"+ newLine + " java.util.Map.Entry entryItem$i = (java.util.Map.Entry) mapOfSource$i[index$i];"+ newLine + " java.lang.Integer sourceKeyObj$i = (java.lang.Integer) entryItem$i.getKey();"+ newLine + " java.lang.String sourceValueObj$i = (java.lang.String) entryItem$i.getValue();"+ newLine + " java.lang.String destinationKeyObj$i = sourceKeyObj$i.toString();"+ newLine + " mapOfDestination$i.put(destinationKeyObj$i, sourceValueObj$i);"+ newLine + " }"+ newLine + " destination.setADConversionMap2(mapOfDestination$i);"+ newLine + newLine + " }"+ newLine + " }"+newLine; write(enrichment); verify(); } }
[ "alessandro.vurro@092d7813-c906-8c0d-5406-876db11828ef" ]
alessandro.vurro@092d7813-c906-8c0d-5406-876db11828ef
c4bfdc00df44177f7b68ba3ebf98bb70848b6385
b57e771f85a5c3a802a2c8e9b8b822620a04ad99
/Recursion/src/DP/P17070.java
9b5166456aa3b28b0eff2496be998f3d1871f58f
[]
no_license
eedys1234/Algorithm
342c196489de36345a8034ee3a083bf3104bbab5
eaadaf5032430206926cc5794c56b86eff8b4550
refs/heads/master
2023-04-07T08:12:00.194829
2021-04-15T14:28:22
2021-04-15T14:28:22
324,161,496
1
0
null
null
null
null
UTF-8
Java
false
false
1,170
java
package DP; import java.io.BufferedReader; import java.io.InputStreamReader; public class P17070 { public static int[][] house = new int[18][18]; public static int[][][] dp = new int[18][18][3]; public static void main(String[] args) { BufferedReader inbr = new BufferedReader(new InputStreamReader(System.in)); try { int n = Integer.valueOf(inbr.readLine()); for(int i=1;i<=n;i++) { String[] temp = inbr.readLine().split(" "); for(int j=0;j<temp.length;j++) { house[i][j+1] = Integer.valueOf(temp[j]); } } dp[1][2][0] = 1; for(int y=1;y<=n;y++) { for(int x=1;x<=n;x++) { if(house[y][x+1] == 0) { dp[y][x+1][0] += dp[y][x][0] + dp[y][x][2]; } if(house[y+1][x] == 0) { dp[y+1][x][1] += dp[y][x][1] + dp[y][x][2]; } if(house[y][x+1] == 0 && house[y+1][x] == 0 && house[y+1][x+1] == 0) { dp[y+1][x+1][2] += dp[y][x][0] + dp[y][x][1] + dp[y][x][2]; } } } long cnt = 0; for(int i=0;i<3;i++) { cnt += dp[n][n][i]; } System.out.println(cnt); } catch(Exception e) { e.printStackTrace(); } } }
[ "eedys1234@naver.com" ]
eedys1234@naver.com
e35b2967d1d9885c080bff861eb44b66836b1b41
4cd3d4749be26c7632fad5e0e894b06a47e1bbb4
/CustomResourceBundleControl.java
c4796d837a0a356752e1b7db66397f5205b90e4a
[ "Apache-2.0" ]
permissive
hagrawal7/CustomResourceBundleControl
f74cc87c9bf33276f88fc2e628424ff1b0b64f22
e03e8099361a94e672b66705bf594320652044cd
refs/heads/master
2021-01-10T11:32:17.146794
2015-05-31T20:08:40
2015-05-31T20:08:40
36,619,168
0
1
null
null
null
null
UTF-8
Java
false
false
1,588
java
import java.io.*; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ResourceBundle.Control; import java.util.*; public class CustomResourceBundleControl extends Control { private String encodingScheme = "UTF-8"; public CustomResourceBundleControl(String encodingSchemeStr) { encodingScheme = encodingSchemeStr; } public ResourceBundle newBundle (String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, "properties"); ResourceBundle bundle = null; InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { try { // Read properties files as user defined and if not provided then use "UTF-8" encoding. bundle = new PropertyResourceBundle(new InputStreamReader(stream, encodingScheme)); } finally { stream.close(); } } return bundle; } }
[ "himanshu.h.agrawal@gmail.com" ]
himanshu.h.agrawal@gmail.com
a2a7b21491d180aca919bbb4869c145372201cf3
3c30023abb92f667781d8525ec0481c483809266
/Spring_Annotation/src/main/java/com/yxj/dao/impl/AccountDaoImpl.java
9cbe42ab5e1b9490e41c595b0471b3565c7dac0a
[]
no_license
congbuzhuangsha/Java-Frame
e873e1f277c6dd0a49ea146f8879710405260df8
f4b39b00e3eefa9cc089c12dd8230cd2f7bd25ef
refs/heads/master
2022-12-25T19:43:18.945549
2020-03-15T05:10:21
2020-03-15T05:10:21
244,779,184
0
0
null
2022-12-16T04:25:43
2020-03-04T01:21:36
JavaScript
UTF-8
Java
false
false
364
java
package com.yxj.dao.impl; import com.yxj.dao.IAccountDao; import org.springframework.stereotype.Repository; /** * @Auther: yangxiaojie * @Date: 2020/3/4 * @version: 1.0 */ @Repository("accountDao") public class AccountDaoImpl implements IAccountDao { @Override public void saveAccount() { System.out.println("保存了一个账户"); } }
[ "694306397@qq.con" ]
694306397@qq.con
86e630518b48c1b590a626921eb035f02be2515a
ddf95418dec31209507b3c57e9cc1dbf3a511684
/src/controller/MoreDetailsController.java
bd6c24003aeca08e3eb4b00743d3485b6ffe1747
[]
no_license
QuBenhao/AP_Assignment2
172d727ba5c51c6425a35f6d52b9f0d0316938ea
68d0e404f2ad776f733461bcc3c482dcb34f3757
refs/heads/master
2022-10-13T15:24:56.698692
2020-06-10T22:57:12
2020-06-10T22:57:12
257,516,334
0
0
null
null
null
null
UTF-8
Java
false
false
16,599
java
package controller; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import main.UniLinkGUI; import model.database.PostDB; import model.exception.InputFormatException; import model.post.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Optional; public class MoreDetailsController implements Switchable { @FXML private Button UploadButton; @FXML private Button SaveButton; @FXML private Button CloseButton; @FXML private ListView<Label> ReplyDetails; @FXML private VBox PostDetails; private ImageView imageView; private Post post; private final ObservableList<Label> replyView = FXCollections.observableArrayList(); // save all the changes to update later private final HashMap<String, String> changes = new HashMap<>(); @FXML public void initialize() { ReplyDetails.addEventFilter(MouseEvent.ANY, javafx.event.Event::consume); } // Load post and reply data to the stage public void setUp(Post post, String title, ArrayList<Reply> replies) { this.post = post; HBox postDetails = post.visualize(post.getCreatorId()); for (Node node : postDetails.getChildren()) { if (node instanceof GridPane) ((GridPane) node).setPrefWidth(600); if (node instanceof Button) { node.setVisible(false); node.setDisable(true); } else if (node instanceof ImageView) imageView = (ImageView) node; } replyView.add(new Label(title)); if (replies.isEmpty()) { replyView.add(new Label("Empty")); if (post instanceof Event) { for (Node node : postDetails.getChildren()) { if (node instanceof GridPane) { ArrayList<Node> remove = new ArrayList<>(); HashMap<Node, int[]> insert = new HashMap<>(); for (Node label : ((GridPane) node).getChildren()) { if (label instanceof Group) continue; if (GridPane.getColumnIndex(label) == 3 || (GridPane.getColumnIndex(label) == 1 && GridPane.getRowIndex(label) == 4)) { TextField temp = new TextField(((Label) label).getText()); for (Node LABEL : ((GridPane) node).getChildren()) { if (LABEL instanceof Group) continue; if (GridPane.getColumnIndex(LABEL) == GridPane.getColumnIndex(label) - 1) if (GridPane.getRowIndex(LABEL).equals(GridPane.getRowIndex(label))) temp.setId(((Label) LABEL).getText().split(":")[0].replaceAll(" ", "_")); } temp.textProperty().addListener((observable, oldvalue, newvalue) -> { changes.put(temp.getId(), newvalue); }); remove.add(label); int[] position = new int[2]; position[0] = GridPane.getColumnIndex(label); position[1] = GridPane.getRowIndex(label); insert.put(temp, position); } else if ((GridPane.getColumnIndex(label) == 1 && GridPane.getRowIndex(label) == 3) ) { DatePicker temp = new DatePicker(); LocalDate date = LocalDate.parse(((Label) label).getText()); temp.setValue(date); temp.valueProperty().addListener(((observable, oldvalue, newvalue) -> { changes.put("DATE", newvalue.toString()); })); remove.add(label); int[] position = new int[2]; position[0] = GridPane.getColumnIndex(label); position[1] = GridPane.getRowIndex(label); insert.put(temp, position); } } if (post.getStatus().compareToIgnoreCase("CLOSED") != 0) { ((GridPane) node).getChildren().removeAll(remove); for (Node key : insert.keySet()) { ((GridPane) node).add(key, insert.get(key)[0], insert.get(key)[1]); } } } } } else if (post instanceof Sale) { for (Node node : postDetails.getChildren()) { if (node instanceof GridPane) { ArrayList<Node> remove = new ArrayList<>(); HashMap<TextField, int[]> insert = new HashMap<>(); for (Node label : ((GridPane) node).getChildren()) { if (label instanceof Group) continue; if (GridPane.getColumnIndex(label) == 3 || (GridPane.getColumnIndex(label) == 1 && GridPane.getRowIndex(label) == 4) || (GridPane.getColumnIndex(label) == 1 && GridPane.getRowIndex(label) == 5)) { TextField temp = new TextField(((Label) label).getText()); for (Node LABEL : ((GridPane) node).getChildren()) { if (LABEL instanceof Group) continue; if (GridPane.getColumnIndex(LABEL) == GridPane.getColumnIndex(label) - 1) if (GridPane.getRowIndex(LABEL).equals(GridPane.getRowIndex(label))) temp.setId(((Label) LABEL).getText().split(":")[0].replaceAll(" ", "_")); } temp.textProperty().addListener((observable, oldvalue, newvalue) -> { changes.put(temp.getId(), newvalue); }); remove.add(label); int[] position = new int[2]; position[0] = GridPane.getColumnIndex(label); position[1] = GridPane.getRowIndex(label); insert.put(temp, position); } } if (post.getStatus().compareToIgnoreCase("CLOSED") != 0) { ((GridPane) node).getChildren().removeAll(remove); for (TextField key : insert.keySet()) { ((GridPane) node).add(key, insert.get(key)[0], insert.get(key)[1]); } } } } } else if (post instanceof Job) { for (Node node : postDetails.getChildren()) { if (node instanceof GridPane) { ArrayList<Node> remove = new ArrayList<>(); HashMap<TextField, int[]> insert = new HashMap<>(); for (Node label : ((GridPane) node).getChildren()) { if (label instanceof Group) continue; if (GridPane.getColumnIndex(label) == 3 || (GridPane.getColumnIndex(label) == 1 && GridPane.getRowIndex(label) == 3)) { TextField temp = new TextField(((Label) label).getText()); for (Node LABEL : ((GridPane) node).getChildren()) { if (LABEL instanceof Group) continue; if (GridPane.getColumnIndex(LABEL) == GridPane.getColumnIndex(label) - 1) if (GridPane.getRowIndex(LABEL).equals(GridPane.getRowIndex(label))) temp.setId(((Label) LABEL).getText().split(":")[0].replaceAll(" ", "_")); } temp.textProperty().addListener((observable, oldvalue, newvalue) -> { changes.put(temp.getId(), newvalue); }); remove.add(label); int[] position = new int[2]; position[0] = GridPane.getColumnIndex(label); position[1] = GridPane.getRowIndex(label); insert.put(temp, position); } } if (post.getStatus().compareToIgnoreCase("CLOSED") != 0) { ((GridPane) node).getChildren().removeAll(remove); for (TextField key : insert.keySet()) { ((GridPane) node).add(key, insert.get(key)[0], insert.get(key)[1]); } } } } } } else { UploadButton.setVisible(false); UploadButton.setDisable(true); SaveButton.setDisable(true); SaveButton.setVisible(false); for (Reply reply : replies) { if (reply.getPostId().substring(0, 3).compareToIgnoreCase("EVE") == 0) replyView.add(new Label(reply.getResponderId())); else replyView.add(new Label(String.format("%s: $%.2f", reply.getResponderId(), reply.getValue()))); } } if (post.getStatus().compareToIgnoreCase("CLOSED") == 0) { UploadButton.setVisible(false); UploadButton.setDisable(true); SaveButton.setDisable(true); SaveButton.setVisible(false); CloseButton.setVisible(false); CloseButton.setDisable(true); } PostDetails.getChildren().add(postDetails); ObservableList<Node> collection = FXCollections.observableArrayList(PostDetails.getChildren()); Collections.swap(collection, 0, 1); PostDetails.getChildren().setAll(collection); ReplyDetails.setItems(replyView); } @FXML public void UploadImage() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Upload Post image"); fileChooser.setInitialDirectory(new File("./images/")); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); File selectedFile = fileChooser.showOpenDialog(UniLinkGUI.stages.get("EVENT")); if (selectedFile != null) { String imagepath = selectedFile.getAbsolutePath(); String[] path = imagepath.split("/"); String imageName = path[path.length - 1]; try { imageView.setImage(new Image(new FileInputStream(String.format("./images/%s", imageName)))); changes.put("IMAGE", imageName); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { Alert alert = new Alert(Alert.AlertType.ERROR, "Invalid file"); alert.showAndWait(); } } @FXML public void ClosePost() { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmation"); alert.setHeaderText("Warning !"); alert.setContentText("Are you sure you want to close this post ?"); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent()) { if (result.get() == ButtonType.OK) { PostDB postDB = new PostDB(); postDB.closePost(post.getPostId()); switchStage(); } } } @FXML public void DeletePost() { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmation"); alert.setHeaderText("Warning !"); alert.setContentText("Are you sure you want to delete this post ?"); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent()) { if (result.get() == ButtonType.OK) { PostDB postDB = new PostDB(); postDB.deletePost(post.getPostId()); switchStage(); } } } // Validate user input before saving form @FXML public void Save() { try { for (Node root : PostDetails.getChildren()) { if (root instanceof HBox) { for (Node parent : ((HBox) root).getChildren()) { if (parent instanceof GridPane) { for (Node node : ((GridPane) parent).getChildren()) { if (node instanceof TextField) { if (((TextField) node).getText().isEmpty()) throw new Exception(); if (node.getId().compareToIgnoreCase("capacity") == 0) { if (Integer.parseInt(((TextField) node).getText()) <= 0) throw new InputFormatException("Please Enter a positive integer for capacity"); } else if (node.getId().compareToIgnoreCase("asking_price") == 0 || node.getId().compareToIgnoreCase("minimum_raise") == 0 || node.getId().compareToIgnoreCase("proposed_price") == 0) { String value = ((TextField) node).getText(); if(value.charAt(0)=='$'){ value = value.substring(1); } if (Double.parseDouble(value) <= 0) throw new InputFormatException("Please Enter a positive number for askingprice"); } } } } } } } PostDB postDB = new PostDB(); postDB.updatePost(post.getPostId(), changes); switchStage(); } catch (NumberFormatException ex) { Alert alert = new Alert(Alert.AlertType.ERROR, String.format("Input with wrong Type!%s", ex.getMessage())); alert.showAndWait(); } catch (InputFormatException inputFormatException) { inputFormatException.display(); } catch (Exception e) { try { throw new InputFormatException("Cannot save when some textfields are left blank"); } catch (InputFormatException ex) { ex.display(); } } } @FXML public void BackToMainWindow() { switchStage(); } // Back to main stage @Override public void switchStage() { ((MainWindowController) UniLinkGUI.controllers.get("MAIN")).UpdateView(); UniLinkGUI.stages.get("MAIN").show(); UniLinkGUI.stages.get("MOREDETAILS").close(); UniLinkGUI.stages.remove("MOREDETAILS"); UniLinkGUI.controllers.remove("MOREDETAILS"); } }
[ "qubenhao2@gmail.com" ]
qubenhao2@gmail.com
d6ab42e19f03fc34793fb7c77a2d858647c4226e
60e3731690f292b416c4d38a12b820026fb23c42
/dom2/namoo.board.dom2.da.file.v1/src/main/java/namoo/board/dom2/da/file/repo/mapper/PostingCommentBagMapper.java
a79f99fac949519184c98eaaf39fca3e0bef0b0b
[]
no_license
ybkim1984/prj-yb
aae008f09bb6531839234987622828a4baecfdf6
418d3207b38f38519f50407102689c9c730b6cdd
refs/heads/master
2021-01-10T01:06:01.239420
2016-04-01T06:35:48
2016-04-01T06:35:48
55,126,031
0
0
null
null
null
null
UTF-8
Java
false
false
1,731
java
/* * COPYRIGHT (c) Nextree Consulting 2015 * This software is the proprietary of Nextree Consulting. * * @author <a href="mailto:hkkang@nextree.co.kr">Kang Hyoungkoo</a> * @since 2015. 2. 11. */ package namoo.board.dom2.da.file.repo.mapper; import namoo.board.dom2.da.file.repo.structure.ColumnValue; import namoo.board.dom2.da.file.repo.structure.ColumnValueList; import namoo.board.dom2.da.file.repo.structure.StoreType; import namoo.board.dom2.da.file.repo.structure.constant.FileConst; import namoo.board.dom2.entity.board.DCCommentBag; import namoo.board.dom2.util.json.JsonUtil; public class PostingCommentBagMapper { // public static ColumnValueList createColumnValues(String postingUsid, DCCommentBag commentBag) { // ColumnValueList columnValues = new ColumnValueList(StoreType.CommentBag); columnValues.addColumnValue("postingUsid", postingUsid); String commentBagJson = JsonUtil.toJson(commentBag); columnValues.addColumnValue("commentBagJson", commentBagJson); return columnValues; } public static ColumnValue createIndexColumnValue(String postingUsid) { // ColumnValueList columnValues = new ColumnValueList(StoreType.CommentBag); columnValues.addColumnValue("postingUsid", postingUsid); return columnValues.getIndexColumnValue(); } public static DCCommentBag createDomain(String csv) { // if (csv == null) { return null; } String[] values = csv.split(FileConst.SEPARATOR, 2); String commentBagJson = values[1]; return JsonUtil.fromJson(commentBagJson, DCCommentBag.class); } }
[ "kimyb1984@gmail.com" ]
kimyb1984@gmail.com
4a24966f97de332c30ffa2e9c2c5a7fe0982bf25
51ab36bbbef9c56de0b5ac2db2099d251c58290f
/app/src/main/java/com/zhangwy/integral/CouponsNearOverdueActivity.java
75c330778e1318e5f35ce4c1ba6bc73cf109dcef
[]
no_license
zwyzzu/integral
85bb53b9e3074e79b0fcdca1e76a8e120dfffe4e
fa23364ac00f344bacdd12578e97982a719ca8f6
refs/heads/master
2021-08-18T04:10:47.967524
2020-04-12T10:49:55
2020-04-12T10:49:55
159,655,768
0
0
null
null
null
null
UTF-8
Java
false
false
1,627
java
package com.zhangwy.integral; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.zhangwy.integral.data.ICouponsManager; import yixia.lib.core.base.BaseActivity; public class CouponsNearOverdueActivity extends BaseActivity { public static void start(Context context) { if (context == null) return; context.startActivity(new Intent(context, CouponsNearOverdueActivity.class)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_coupons_near_overdue); Fragment fragment = FragmentCoupons.newInstance("", ICouponsManager.CouponsMold.NEAROVERDUE); this.addFragment(fragment, R.id.couponsNearOverdueContent); this.setToolbar(); } private void setToolbar() { Toolbar toolbar = this.findViewById(R.id.couponsNearOverdueToolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } }
[ "1010482327@qq.com" ]
1010482327@qq.com
8419773515c91f6f59ed839f828a6cfad4d60cfc
a5e25772f400a355d36144eaa6ef36d766443ae7
/kaab/src/main/java/com/yei3/oox/kaab_inventarios/database/entity/Company.java
9fe5676297ebf7f71a33274032167032d99a5228
[]
no_license
yei3/kaab_lambda
b05f529833d0861a8cebf72edee91882b7a5eb94
3478f889c64d4ad94f8a36d332c2013534290930
refs/heads/master
2020-04-10T18:57:11.718272
2019-01-12T02:58:48
2019-01-12T02:58:48
161,218,309
0
0
null
null
null
null
UTF-8
Java
false
false
4,339
java
package com.yei3.oox.kaab_inventarios.database.entity; import java.sql.Timestamp; import java.util.Arrays; public class Company implements Entity{ private int id; private int companyAccountID; private String companyType; private String industryType; private String name; private String fiscalID; private int addressID; private int statusID; private Timestamp creationDateTime; private Timestamp lastModDateTime; private Timestamp deleteDateTime; private int creationUserID; private int lastModUserID; private int deleteUserID; private String TABLE = "COMPANIES"; private String[] columns = { "id", "companyAccountID", "companyType", "industryType", "name", "fiscalID", "addressID", "statusID", "creationDateTime", "lastModDateTime", "deleteDateTime", "creationUserID", "lastModUserID", "deleteUserID" }; private Class[] types = { int.class, int.class, String.class, String.class, String.class, String.class, int.class, int.class, Timestamp.class, Timestamp.class, Timestamp.class, int.class, int.class, int.class }; public Company(int companyAccountID, String companyType, String industryType, String name, String fiscalID, int addressID, int statusID) { this.companyAccountID = companyAccountID; this.companyType = companyType; this.industryType = industryType; this.name = name; this.fiscalID = fiscalID; this.addressID = addressID; this.statusID = statusID; } @Override public String toString() { return "Company [id=" + id + ", companyAccountID=" + companyAccountID + ", companyType=" + companyType + ", industryType=" + industryType + ", name=" + name + ", fiscalID=" + fiscalID + ", addressID=" + addressID + ", statusID=" + statusID + ", creationDateTime=" + creationDateTime + ", lastModDateTime=" + lastModDateTime + ", deleteDateTime=" + deleteDateTime + ", creationUserID=" + creationUserID + ", lastModUserID=" + lastModUserID + ", deleteUserID=" + deleteUserID + "]"; } public int getCompanyAccountID() { return companyAccountID; } public void setCompanyAccountID(int companyAccountID) { this.companyAccountID = companyAccountID; } public void setColumns(String[] columns) { this.columns = columns; } public Company() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCompanyType() { return companyType; } public void setCompanyType(String companyType) { this.companyType = companyType; } public String getIndustryType() { return industryType; } public void setIndustryType(String industryType) { this.industryType = industryType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFiscalID() { return fiscalID; } public void setFiscalID(String fiscalID) { this.fiscalID = fiscalID; } public int getAddressID() { return addressID; } public void setAddressID(int addressID) { this.addressID = addressID; } public int getStatusID() { return statusID; } public void setStatusID(int statusID) { this.statusID = statusID; } public Timestamp getCreationDateTime() { return creationDateTime; } public void setCreationDateTime(Timestamp creationDateTime) { this.creationDateTime = creationDateTime; } public Timestamp getLastModDateTime() { return lastModDateTime; } public void setLastModDateTime(Timestamp lastModDateTime) { this.lastModDateTime = lastModDateTime; } public Timestamp getDeleteDateTime() { return deleteDateTime; } public void setDeleteDateTime(Timestamp deleteDateTime) { this.deleteDateTime = deleteDateTime; } public int getCreationUserID() { return creationUserID; } public void setCreationUserID(int creationUserID) { this.creationUserID = creationUserID; } public int getLastModUserID() { return lastModUserID; } public void setLastModUserID(int lastModUserID) { this.lastModUserID = lastModUserID; } public int getDeleteUserID() { return deleteUserID; } public void setDeleteUserID(int deleteUserID) { this.deleteUserID = deleteUserID; } public String getTable() { return this.TABLE; } public String[] getColumns() { return this.columns; } public Class[] getTypes() { return this.types; } }
[ "manuelzarate@Gigi.local" ]
manuelzarate@Gigi.local
fc4da0c05ebf7a2e6396ec8161a21173b323af5c
ec044b63dcaec0f5bf343889737f8d989b50a6ad
/src/main/java/creatures/Dragon.java
6a4c30d1a702a30be39d39bcf84c70a383894f66
[]
no_license
Catkin92/week12_day4_lab
b8e24f50748cae99a551e9c78be620048d744bb4
543efd31ece83579c608cbb6c87f98505cf9b278
refs/heads/master
2020-12-13T07:48:01.283124
2020-01-20T00:27:07
2020-01-20T00:27:07
234,352,067
0
0
null
2020-10-13T18:53:52
2020-01-16T15:37:02
Java
UTF-8
Java
false
false
182
java
package creatures; public class Dragon extends Creature { public Dragon(String name, int defence, int attack, int maxHP) { super(name, defence, attack, maxHP); } }
[ "catrinhughes92@gmail.com" ]
catrinhughes92@gmail.com
3b4f72c0f3abc9f9b1116aabebf8ec034328b34a
1a706ed773ee7795a38c714860fc3d5ef35b917e
/src/main/java/th/ac/ku/tutor/App.java
f715383cb22ae62d9b5b4cc95a1e2351c79cc155
[]
no_license
peacher5/ku-tutor
7bddeef012d23cabfa4fddcfa6c215c5eff2bf04
53980e0fc1fa1c01be05f513ff71b98b9c8fb57e
refs/heads/master
2020-08-02T07:01:45.976152
2019-11-28T01:41:31
2019-11-28T01:41:31
211,270,559
0
0
null
null
null
null
UTF-8
Java
false
false
289
java
package th.ac.ku.tutor; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
[ "peranut.w@ku.th" ]
peranut.w@ku.th
3e804b3f571e8cb77c7b6c654686197358ef3c68
0d4ddc9864c177b19afc8e5ca39f263900a5987d
/src/main/java/com/exam/isr/service/UserService.java
2154c68f3a4ae982e1bc28652daf47e59c927855
[]
no_license
letthefireflieslive/exam-api
f11f228358455510f69297d3e24675992b8fb559
ca88c1f3f183561a495154d4a10fcad05a68d284
refs/heads/master
2021-09-16T20:22:23.059474
2018-06-24T17:44:24
2018-06-24T17:44:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,582
java
package com.exam.isr.service; import com.exam.isr.model.User; import com.exam.isr.persistence.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.List; import java.util.Optional; import static com.exam.isr.persistence.specs.UserSpecs.filterByLoginEndDate; import static com.exam.isr.persistence.specs.UserSpecs.filterByLoginStartDate; import static org.springframework.data.jpa.domain.Specifications.where; @Service public class UserService { private UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public List<User> getUsersByLoginDate(Optional<LocalDate> start, Optional<LocalDate> end) { List<User> result; Specification<User> specs = null; if(start.isPresent() && end.isPresent()) { specs = where(filterByLoginStartDate(start.get())) .and(filterByLoginEndDate(end.get())); } else if(start.isPresent() && !end.isPresent()) { specs = where(filterByLoginStartDate(start.get())); } else if(!start.isPresent() && end.isPresent()) { specs = where(filterByLoginEndDate(start.get())); } result = userRepository.findAll(specs); if (specs == null) { result = userRepository.findAll(); } return result; } }
[ "lemuel.nabong@carlsonwagonlit.com" ]
lemuel.nabong@carlsonwagonlit.com
eeadee7a4656a79faa44554f365b7e31b50e693d
83380915dc4355ea4ea05307222c88f3077f83ab
/services/submission/src/test/java/app/coronawarn/server/services/submission/checkins/FakeCheckinsGeneratorTest.java
c54c28556c6beba95dbb833625b4326c5b6c1bf1
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-unknown" ]
permissive
corona-warn-app/cwa-server
d1c4f25f44f5c2970c4351cf663d599dc4549a83
c61d55f6f83b6d005cb6aca9e9b455afac572d72
refs/heads/main
2023-08-07T14:50:25.777087
2023-05-10T07:59:47
2023-05-10T07:59:47
260,712,390
2,174
497
Apache-2.0
2023-05-10T07:59:48
2020-05-02T15:07:31
Java
UTF-8
Java
false
false
2,746
java
package app.coronawarn.server.services.submission.checkins; import static org.assertj.core.api.Assertions.assertThat; import app.coronawarn.server.common.protocols.internal.pt.CheckIn; import app.coronawarn.server.common.shared.util.HashUtils; import com.google.protobuf.ByteString; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; public class FakeCheckinsGeneratorTest { @ParameterizedTest @ValueSource(ints = {1, 5, 15}) public void should_generate_correct_number_of_checkins(Integer numberOfFakesToCreate) { FakeCheckinsGenerator underTest = new FakeCheckinsGenerator(); Random random = new Random(); int originalCheckinsListSize = random.nextInt(500); List<CheckIn> originalData = Stream.generate(this::randomCheckin) .limit(originalCheckinsListSize).collect(Collectors.toList()); List<CheckIn> fakeCheckins = underTest.generateFakeCheckins(originalData, numberOfFakesToCreate, HashUtils.generateSecureRandomByteArrayData(16)); assertThat(fakeCheckins).hasSize(originalCheckinsListSize * numberOfFakesToCreate); } @Test public void should_generate_fake_checkin_with_content_derived_from_original() { FakeCheckinsGenerator underTest = new FakeCheckinsGenerator(); List<CheckIn> originalList = List.of(randomCheckin()); byte[] pepper = HashUtils.generateSecureRandomByteArrayData(16); List<CheckIn> fakes = underTest.generateFakeCheckins(originalList, 1, pepper); assertThat(fakes).hasSize(1); assertContentDerivedCorrectly(originalList.iterator().next(), fakes.iterator().next(), pepper); } private void assertContentDerivedCorrectly(CheckIn original, CheckIn fake, byte[] pepper) { assertThat(fake.getLocationId()).isNotEmpty(); assertThat(fake.getLocationId()).isNotEqualTo(original.getLocationId()); assertThat(fake.getLocationId()).isEqualTo( original.getLocationId().concat(ByteString.copyFrom(pepper).concat(ByteString.copyFromUtf8("0")))); assertThat(fake.getTransmissionRiskLevel()).isEqualTo(original.getTransmissionRiskLevel()); } private CheckIn randomCheckin() { Random random = new Random(); int boundedInt = random.nextInt(1000000); return CheckIn.newBuilder().setStartIntervalNumber(boundedInt) .setEndIntervalNumber(boundedInt + 1000) .setTransmissionRiskLevel(random.nextInt(8)) .setLocationId(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(10))) .build(); } }
[ "noreply@github.com" ]
corona-warn-app.noreply@github.com
c6d5cd303758e9e4cb2ab359b9face7af4add1c1
abfd84a81059a2e4d022d4afa47f92830bd2fabf
/src/Poneze.java
1f11c1b9a4224056e6bdc47d9655adb0e62183cb
[]
no_license
sonal-paavan1/Holidayhomework
b300fc5539439eea9a90f889394e3e2f6fb9421c
eea0bf12f9eb069e1ff6ace2876cfd08020ead4c
refs/heads/master
2020-05-16T00:14:58.910977
2019-04-21T19:49:40
2019-04-21T19:49:40
182,575,996
0
0
null
null
null
null
UTF-8
Java
false
false
1,159
java
import java.util.Scanner; public class Poneze { public static void main(String []args) { //define variable int countp=0, countn=0, countz=0, i; int arr[] = new int[10]; //define the scanner Scanner input = new Scanner(System.in); System.out.print("Enter any 10 Numbers : "); for(i=0; i<10; i++) // User should enter any 10 numbers { arr[i] = input.nextInt(); } for(i=0; i<10; i++) // Run the for loop till 10 { if(arr[i] < 0) { countn++; // if no is <0 then increment countn } else if(arr[i] == 0) { countz++; // if no == 0 then increment countZ } else { countp++; // else increment countP } } // print positive, negative and zero nos System.out.print(countp + " Positive Numbers"); System.out.print("\n" + countn + " Negative Numbers"); System.out.print("\n" + countz + " Zero"); } }
[ "sonal.paavan1@gmail.com" ]
sonal.paavan1@gmail.com
c967345667258f1e84658e28ab5a9865544b8781
d48f55e8c5f670341839b376cb63cf5092a8ab35
/Gpalog/app/src/test/java/com/example/admin/gpalog/ExampleUnitTest.java
59bd36204d52f2883cc80d8ee041497e97ebce37
[]
no_license
harshpjoshi/Android-Tutorial
4baa886e4b3588577d3f7818b96be60287350968
d567bcf99d43fac41e12a37a5d7f6c41f8ded370
refs/heads/master
2020-06-06T15:15:52.981272
2019-06-19T17:17:37
2019-06-19T17:17:37
192,774,624
0
0
null
null
null
null
UTF-8
Java
false
false
402
java
package com.example.admin.gpalog; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "harshjoshi989@gmail.com" ]
harshjoshi989@gmail.com
c33d17cf17053cdd945a4028fbb5d841e1aca5bf
311c530af4d7a844e89baa18c0041ff422ace4e3
/2019상반기에푼것/체크/2206(dfs시간초과).java
8d25c5d258459f1e32bbf1fe31cad9c9e087711d
[ "MIT" ]
permissive
jonghwajoa/ProblemSolving
7bf9a645300fbd32b4a0b10c08f66cb201611ea6
e852aa90e13d034816a2493866fb070d25f32520
refs/heads/master
2021-06-26T22:12:58.328349
2020-10-10T09:52:29
2020-10-10T09:52:29
161,300,286
0
1
null
null
null
null
UTF-8
Java
false
false
1,970
java
import java.util.*; public class Main { static int[] moveX = { 0, 0, 1, -1 }; static int[] moveY = { 1, -1, 0, 0 }; static boolean[][] isVisit; static int[][] map; static int mapX, mapY; static int ans = Integer.MAX_VALUE; public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] line = sc.nextLine().split(" "); mapY = Integer.parseInt(line[0]); mapX = Integer.parseInt(line[1]); map = new int[mapY][mapX]; isVisit = new boolean[mapY][mapX]; for (int i = 0; i < mapY; i++) { line = sc.nextLine().split(""); for (int j = 0; j < mapX; j++) { map[i][j] = Integer.parseInt(line[j]); } } dfs(0, 0, 1, false); if (ans == Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(ans); } } public static void dfs(int x, int y, int count, boolean check) { if (x == mapX - 1 && y == mapY - 1) { if (count < ans) { ans = count; } return; } for (int i = 0; i < 4; i++) { int nextX = x + moveX[i]; int nextY = y + moveY[i]; if (0 <= nextX && 0 <= nextY && nextX < mapX && nextY < mapY) { if (!isVisit[nextY][nextX]) { if (map[nextY][nextX] == 0) { isVisit[nextY][nextX] = true; dfs(nextX, nextY, count + 1, check); isVisit[nextY][nextX] = false; } else { if (check == false) { isVisit[nextY][nextX] = true; dfs(nextX, nextY, count + 1, true); isVisit[nextY][nextX] = false; } } } } } } }
[ "jonghwa0710@naver.com" ]
jonghwa0710@naver.com
7f0f2fcde71045320bc43c0916185a1dd311b64a
f8886ebb8f41bc035b4839d91a3deeb2c54cf1c1
/grupo1 - spring/trunk/grupo1/src/main/java/com/publica/grupo1/restapi/routes/error/MessageGenerator.java
377e1c83fba79ee280140280f61d9b906cf3af56
[]
no_license
ricardobrg/publicaProjetos
f9790679074bc49709fd270b4cb2e492588bde26
d8273285742a641338c2f013f2503fee19b5809a
refs/heads/main
2023-05-29T07:16:21.307850
2021-06-11T13:18:19
2021-06-11T13:18:19
376,030,984
6
0
null
null
null
null
UTF-8
Java
false
false
1,966
java
package com.publica.grupo1.restapi.routes.error; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; public class MessageGenerator { public ResponseEntity<Object> generate(Map<String, String> responseObj, HttpStatus status) { responseObj.put("error", status.toString()); return new ResponseEntity(responseObj, status); } public ResponseEntity<Object> generateNotFoundError(String message){ Map<String, String> responseObj = new HashMap<>(); responseObj.put("message", message); return generate(responseObj, HttpStatus.NOT_FOUND); } public ResponseEntity<Object> generateIdNotFoundError(){ return generateNotFoundError("ID not found"); } public ResponseEntity<Object> generateEmptyListError(){ return generateNotFoundError("Empty list"); } public ResponseEntity<Object> generateUnauthorizedError(){ Map<String, String> responseObj = new HashMap<>(); responseObj.put("message", HttpStatus.UNAUTHORIZED.toString()); return generate(responseObj, HttpStatus.UNAUTHORIZED); } public ResponseEntity<Object> generateInsertedObjectMessage(int id){ Map<String, String> responseObj = new HashMap<>(); responseObj.put("id inserted", String.valueOf(id)); return generate(responseObj, HttpStatus.OK); } public ResponseEntity<Object> generateUpdateSuccessMessage(int id){ Map<String, String> responseObj = new HashMap<>(); responseObj.put("updated object with id", String.valueOf(id)); return generate(responseObj, HttpStatus.OK); } public ResponseEntity<Object> generateDeleteSuccessMessage(int id){ Map<String, String> responseObj = new HashMap<>(); responseObj.put("deleted object with id", String.valueOf(id)); return generate(responseObj, HttpStatus.OK); } public ResponseEntity<Object> generateVacationMessage(Map<String, String> responseObj){ return generate(responseObj, HttpStatus.OK); } }
[ "ricardo@brgweb.com.br" ]
ricardo@brgweb.com.br
83b600e7615d5f7e8b69210ac44849b8cd7ac0bb
6cfd9a2e5a6bcf37d239433a11179d502b56b3a3
/src/main/java/com/icicle/masterdb/model/Company.java
6e74e054f9a9d1b9451688fd49dafa5f91dbed17
[]
no_license
LXZ314157/masterdb
7e6b8bd73b7755187050589d93118cf013143cd8
0726d8490043a49a0380ec9bb184a1e9fd682a43
refs/heads/master
2022-12-11T07:27:13.653915
2019-12-23T10:26:54
2019-12-23T10:28:59
229,730,084
0
1
null
2022-12-06T00:33:50
2019-12-23T10:31:33
JavaScript
UTF-8
Java
false
false
6,124
java
package com.icicle.masterdb.model; import java.util.Date; import javax.persistence.*; public class Company { @Id @Column(name = "company_id") private String companyId; @Column(name = "company_name_local") private String companyNameLocal; @Column(name = "company_name_en") private String companyNameEn; @Column(name = "company_state") private Integer companyState; private String creater; @Column(name = "create_time") private Date createTime; @Column(name = "last_updated_by") private String lastUpdatedBy; @Column(name = "last_update_date") private Date lastUpdateDate; @Column(name = "reference_id1") private String referenceId1; @Column(name = "reference_id2") private String referenceId2; @Column(name = "reference_id3") private String referenceId3; @Column(name = "reference_id4") private String referenceId4; @Column(name = "reference_id5") private String referenceId5; @Column(name = "reference_id6") private String referenceId6; @Column(name = "reference_id7") private String referenceId7; @Column(name = "reference_id8") private String referenceId8; @Column(name = "reference_id9") private String referenceId9; @Column(name = "reference_id10") private String referenceId10; /** * @return company_id */ public String getCompanyId() { return companyId; } /** * @param companyId */ public void setCompanyId(String companyId) { this.companyId = companyId; } /** * @return company_name_local */ public String getCompanyNameLocal() { return companyNameLocal; } /** * @param companyNameLocal */ public void setCompanyNameLocal(String companyNameLocal) { this.companyNameLocal = companyNameLocal; } /** * @return company_name_en */ public String getCompanyNameEn() { return companyNameEn; } /** * @param companyNameEn */ public void setCompanyNameEn(String companyNameEn) { this.companyNameEn = companyNameEn; } /** * @return company_state */ public Integer getCompanyState() { return companyState; } /** * @param companyState */ public void setCompanyState(Integer companyState) { this.companyState = companyState; } /** * @return creater */ public String getCreater() { return creater; } /** * @param creater */ public void setCreater(String creater) { this.creater = creater; } /** * @return create_time */ public Date getCreateTime() { return createTime; } /** * @param createTime */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * @return last_updated_by */ public String getLastUpdatedBy() { return lastUpdatedBy; } /** * @param lastUpdatedBy */ public void setLastUpdatedBy(String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; } /** * @return last_update_date */ public Date getLastUpdateDate() { return lastUpdateDate; } /** * @param lastUpdateDate */ public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } /** * @return reference_id1 */ public String getReferenceId1() { return referenceId1; } /** * @param referenceId1 */ public void setReferenceId1(String referenceId1) { this.referenceId1 = referenceId1; } /** * @return reference_id2 */ public String getReferenceId2() { return referenceId2; } /** * @param referenceId2 */ public void setReferenceId2(String referenceId2) { this.referenceId2 = referenceId2; } /** * @return reference_id3 */ public String getReferenceId3() { return referenceId3; } /** * @param referenceId3 */ public void setReferenceId3(String referenceId3) { this.referenceId3 = referenceId3; } /** * @return reference_id4 */ public String getReferenceId4() { return referenceId4; } /** * @param referenceId4 */ public void setReferenceId4(String referenceId4) { this.referenceId4 = referenceId4; } /** * @return reference_id5 */ public String getReferenceId5() { return referenceId5; } /** * @param referenceId5 */ public void setReferenceId5(String referenceId5) { this.referenceId5 = referenceId5; } /** * @return reference_id6 */ public String getReferenceId6() { return referenceId6; } /** * @param referenceId6 */ public void setReferenceId6(String referenceId6) { this.referenceId6 = referenceId6; } /** * @return reference_id7 */ public String getReferenceId7() { return referenceId7; } /** * @param referenceId7 */ public void setReferenceId7(String referenceId7) { this.referenceId7 = referenceId7; } /** * @return reference_id8 */ public String getReferenceId8() { return referenceId8; } /** * @param referenceId8 */ public void setReferenceId8(String referenceId8) { this.referenceId8 = referenceId8; } /** * @return reference_id9 */ public String getReferenceId9() { return referenceId9; } /** * @param referenceId9 */ public void setReferenceId9(String referenceId9) { this.referenceId9 = referenceId9; } /** * @return reference_id10 */ public String getReferenceId10() { return referenceId10; } /** * @param referenceId10 */ public void setReferenceId10(String referenceId10) { this.referenceId10 = referenceId10; } }
[ "1510878954@qq.com" ]
1510878954@qq.com
a4c492b45fb3ca931642995b41b7414a3b5d3a01
fadd8c54e2217c1e814243c2b132fea46fcec8de
/src/main/java/auto/test/http/spring/service/CaseManagerService.java
ba82deeb50a9466c32aa021bda1e237f2f0179d2
[]
no_license
MyEngIsPoor/spring_http_rpc
141957665efa3f8b477e97107c39cd3d984374a5
2b812478e59268fe16d33d1a94b3051c8f7eb37b
refs/heads/master
2021-01-10T16:25:21.067434
2016-04-28T08:17:50
2016-04-28T08:17:50
53,652,541
0
0
null
null
null
null
UTF-8
Java
false
false
396
java
package auto.test.http.spring.service; import java.util.List; import auto.test.http.spring.model.TestCase; public interface CaseManagerService { public List<TestCase> listTestCase(); public List<TestCase> getTestCaseById(int... id); public boolean deleteTestCaseById(int... id); public boolean updateTestCase(TestCase tc); public List<TestCase> listTestCase(int interface_id); }
[ "limeng12@staff.weibo.com" ]
limeng12@staff.weibo.com
effb72c2406cf1fdd4f112f545fdbcdfd2c411df
74ffb55ff2d78338d5f98bd4e7101a01b8a1579c
/Chapter.C.08/c/annotation/UserAnnotationSample.java
bcb5d9b8768090250b9e2914956e2dcdc172f7a4
[]
no_license
leesunghee1229/javagod
84e03f6233495c039ac3ceb0821adf7fadcefb9a
5bed1308ad939855f919077ea82c0321d4a9dde5
refs/heads/master
2021-01-22T10:40:57.238787
2017-02-15T06:38:23
2017-02-15T06:38:23
82,028,463
0
0
null
null
null
null
UTF-8
Java
false
false
1,031
java
package c.annotation; import java.lang.reflect.Method; public class UserAnnotationSample { @UserAnnotation(number = 0) public static void main(String args[]) { UserAnnotationSample sample = new UserAnnotationSample(); sample.checkAnnotations(UserAnnotationSample.class); } @UserAnnotation(number = 1) public void annotationSample1() { } @UserAnnotation(number = 2, text = "second") public void annotationSample2() { } @UserAnnotation(number = 3, text = "third") public void annotationSample3() { } public void checkAnnotations(Class useClass) { Method[] methods = useClass.getDeclaredMethods(); for (Method tempMethod : methods) { UserAnnotation annotation = tempMethod.getAnnotation(UserAnnotation.class); if (annotation != null) { int number = annotation.number(); String text = annotation.text(); System.out.println(tempMethod.getName() + "() : number="+ number + " text=" + text); } else { System.out.println(tempMethod.getName()+ "() : annotation is null."); } } } }
[ "sh01094701600@etomato.com" ]
sh01094701600@etomato.com
de34186179e1840bdeb9375e14045c3995cb1226
8f0b341e35487711a6b6c992b1e01b456aafe6ef
/backend/src/main/java/com/abcode/learn/entities/Content.java
135c6b787fc5f7cd9308b6ce65b394b76967671f
[]
no_license
arthurBarbosa/ablearn
ab3d4201cffde50274652934292245540de5617f
7a3aefcc0e3912f54d58f4daadc9c2f4b437afe4
refs/heads/main
2023-03-20T09:39:45.066095
2021-03-10T23:12:21
2021-03-10T23:12:21
340,045,672
0
0
null
null
null
null
UTF-8
Java
false
false
838
java
package com.abcode.learn.entities; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "tb_content") public class Content extends Lesson { private String textContent; private String videoUri; public Content() { } public Content(Long id, String title, Integer position, Section section, String textContent, String videoUri) { super(id, title, position, section); this.textContent = textContent; this.videoUri = videoUri; } public String getTextContent() { return textContent; } public void setTextContent(String textContent) { this.textContent = textContent; } public String getVideoUri() { return videoUri; } public void setVideoUri(String videoUri) { this.videoUri = videoUri; } }
[ "arthur.barbosa@ITBL000531D.itbam.org.br" ]
arthur.barbosa@ITBL000531D.itbam.org.br
3c65f55d1ccca2a42719f11a61b6b6bca084b50b
ff735294a382e77fa0b80a009870b67797d4a0be
/src/main/java/com/example/books/config/WebConfig.java
beee78f549f9773047e04bd0fb44d8079f235380
[]
no_license
q22www/-
4d6a40b3bf3788526fa30b6264318bf7994454c0
5b8d56206f8bed86e11b6ecdd70839829585b746
refs/heads/master
2020-04-26T16:01:02.697091
2019-03-04T03:32:18
2019-03-04T03:32:18
173,664,790
0
0
null
null
null
null
UTF-8
Java
false
false
608
java
package com.example.books.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //@Configuration //public class WebConfig implements WebMvcConfigurer { // @Override // public void addInterceptors(InterceptorRegistry registry) { //// registry.addInterceptor(); // } //}
[ "q2263545123@outlook.com" ]
q2263545123@outlook.com
c3051550568cad6eb2ac14aa4426715a3ce4db33
252a4b62fcd100f32a06821597fcc1110b74dd0e
/app/src/main/java/com/sxzhwts/ticket/project/prenster/SceneryPrenster.java
fc68cf0db2e42b857b3b5444d6d051cf08473f32
[]
no_license
fanchunyan123feiyu/ticket
1aeb51e8dc2e53bfae888a0a6db7804537e50231
e40c974d59260bed651f5a7d9068ffdaf30d3034
refs/heads/master
2020-03-14T05:57:22.383786
2018-06-11T08:41:38
2018-06-11T08:41:38
131,474,489
0
0
null
null
null
null
UTF-8
Java
false
false
2,269
java
package com.sxzhwts.ticket.project.prenster; import android.util.Log; import com.sxzhwts.ticket.common.api.ApiService; import com.sxzhwts.ticket.common.base.BaseMvpActivity; import com.sxzhwts.ticket.common.utils.SystemUtil; import com.sxzhwts.ticket.project.bean.response.SceneryResult; import com.sxzhwts.ticket.project.contract.SceneryContract; import com.sxzhwts.ticket.project.views.SelectSceneryActivity; import javax.inject.Inject; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; /** * 作者:fcy on 2018/4/16 10:52 */ public class SceneryPrenster implements SceneryContract.Presenter{ private ApiService apiService; private SelectSceneryActivity selectSceneryActivity; @Inject public SceneryPrenster(ApiService apiService, BaseMvpActivity baseMvpActivity) { this.apiService = apiService; this.selectSceneryActivity = (SelectSceneryActivity) baseMvpActivity; } @Override public void getScenery(String clientToken) { selectSceneryActivity.showLoading(); apiService.getScenery(clientToken) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(selectSceneryActivity.bind2Lifecycle()) .subscribe(new Consumer<SceneryResult>() { @Override public void accept(SceneryResult sceneryResult) throws Exception { selectSceneryActivity.hideLoading(); selectSceneryActivity.getScenerySucess(sceneryResult); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { throwable.printStackTrace(); Log.e("TAG","登录错误"); selectSceneryActivity.hideLoading(); if (SystemUtil.isNetworkConnected()) { selectSceneryActivity.showNoNet(); } else { selectSceneryActivity.showError(); } } }); } }
[ "295093133@qq.com" ]
295093133@qq.com
814ba8b6fdbe62887a643053ce25f1aa7c2f1f37
858b7ac186d0d9ba70e890fb7d96c4e43ca3ec35
/src/main/java/be/kdg/prog3/upvote/services/QuestionAnswerService.java
a60a9cd5ffb79a4a3c20ea6d353e5bb94b7e79d7
[ "MIT" ]
permissive
LynnKdG/upvote
dd549336764c340bb89b7024fb12aaa8385f7566
cc48394840e255f3330a0f14c172247a4b626276
refs/heads/master
2021-09-05T12:14:00.206870
2018-01-27T12:32:32
2018-01-27T12:32:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,248
java
package be.kdg.prog3.upvote.services; import be.kdg.prog3.upvote.model.QuestionAnswer; import be.kdg.prog3.upvote.model.User; import be.kdg.prog3.upvote.model.Vote; import be.kdg.prog3.upvote.persistence.QuestionAnswerRepository; import be.kdg.prog3.upvote.persistence.UserRepository; import be.kdg.prog3.upvote.persistence.VoteRepository; import be.kdg.prog3.upvote.security.CustomUserDetails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @Service @Transactional public class QuestionAnswerService { private final QuestionAnswerRepository questionAnswerRepository; private final UserRepository userRepository; private final VoteRepository voteRepository; @Autowired public QuestionAnswerService(QuestionAnswerRepository questionAnswerRepository, UserRepository userRepository, VoteRepository voteRepository) { this.questionAnswerRepository = questionAnswerRepository; this.userRepository = userRepository; this.voteRepository = voteRepository; } public QuestionAnswer getQuestion(long questionId) { return questionAnswerRepository.findOne(questionId); } public long saveQuestion(long userId, String subject, String body) { final User user = this.userRepository.findOne(userId); QuestionAnswer questionAnswer = new QuestionAnswer(subject, body, user); questionAnswer = questionAnswerRepository.save(questionAnswer); return questionAnswer.getId(); } public void saveAnswer(long userId, String body, long parentId) { final User user = this.userRepository.findOne(userId); final QuestionAnswer parent = questionAnswerRepository.findOne(parentId); final QuestionAnswer questionAnswer = new QuestionAnswer(body, user, parent); questionAnswerRepository.save(questionAnswer); } public Map<QuestionAnswer, Vote> getAnswersWithUserVotes(QuestionAnswer question, CustomUserDetails userDetails) { final List<QuestionAnswer> answers = this.questionAnswerRepository.findAnswersByParentOrderByTimestampAsc(question); return enrichQAsWithUserVotes(answers, userDetails); } public Map<QuestionAnswer, Vote> getTopTenQuestionsWithUserVotes(CustomUserDetails userDetails) { final List<QuestionAnswer> topTenQuestions = this.questionAnswerRepository.findTop10ByParentIsNullOrderByTimestampDesc(); return enrichQAsWithUserVotes(topTenQuestions, userDetails); } private Map<QuestionAnswer, Vote> enrichQAsWithUserVotes(List<QuestionAnswer> qas, CustomUserDetails userDetails) { final Map<QuestionAnswer, Vote> votesByQA = new LinkedHashMap<>(); for (QuestionAnswer qa : qas) { votesByQA.put(qa, null); } if (userDetails != null) { final List<Vote> votes = this.voteRepository.findByQuestionAnswerInAndUserId(qas, userDetails.getUserId()); for (Vote vote : votes) { votesByQA.put(vote.getQuestionAnswer(), vote); } } return votesByQA; } }
[ "lars.willemsens@kdg.be" ]
lars.willemsens@kdg.be
5d8c3c3c04270a43903fee6fff01b96a9ea2f049
9e4fb2a61fbaa66b1cad986212b3c2d874ef2e68
/src/main/java/spring/di/NewlecDIConfig.java
614978587f22dd1f7ba9e14005bfee4ef366e2f1
[]
no_license
jihoony/spring
b7e1b9f827f5ed4e881e1f1b52418327787bac62
2ddc914f95f0aef4c0c85f37ae0e57ca655e7e15
refs/heads/master
2020-11-27T08:19:40.902281
2019-12-21T02:55:34
2019-12-21T02:55:34
229,368,058
0
0
null
null
null
null
UTF-8
Java
false
false
463
java
package spring.di; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import spring.di.entity.Exam; import spring.di.entity.NewlecExam; @ComponentScan("spring.di.ui") @Configuration public class NewlecDIConfig { @Bean public Exam exam() { // return new NewlecExam(10, 10, 10, 10); return new NewlecExam(); } }
[ "jihoon_yang@ksmartech.com" ]
jihoon_yang@ksmartech.com
58cdc125e92fa1086f063e04b4299e4d3ae88c37
10e1fe4940718d045f980577b82dd427315153e0
/src/myjava/golovach/Thread/Lab1/Play_the_accordion_Solution.java
ef0101fd13a8439416dfce01bdcc81494d6ffcd3
[]
no_license
ValenbergHar/G-JD1-2019-10-01_ValenbergHar
6b693f08becdf624b235170712e552a4ff148ac3
bff38b21a10594cdfa7a719c216c04614cc01ac3
refs/heads/master
2022-12-22T12:10:22.999080
2020-10-20T21:02:01
2020-10-20T21:02:01
212,853,204
0
1
null
2022-12-16T15:42:29
2019-10-04T16:00:20
Java
UTF-8
Java
false
false
441
java
package golovach.Thread.Lab1; /** * Created by AdminAccount on 03.12.2015. */ public class Play_the_accordion_Solution { public static void main(String[] args) throws InterruptedException { // Coordinator Runnable coordinator = new CoordinatorRunnable(); Thread threadCoor = new Thread(coordinator); threadCoor.start(); threadCoor.join(); System.out.println("!!! The end !!!"); } }
[ "maskevich.valeri@gmail.com" ]
maskevich.valeri@gmail.com
bc5f8ffc50dcf16110d4dcd889d21d4cb7ae5034
ef880f535274f3bbe96da221193afeebbf2c62d3
/app/src/main/java/com/ocr/john/topquiz/controller/ListActivity.java
5d480ca2ccbcd9c4466f6aadd8d8e88e7a05ab2c
[]
no_license
Boyman10/AQuiz
4d2648c5bba976a5f8db52a5d497d29ebf687f86
e6f04f0f398a9f5d8382d9123df63281a9ba887b
refs/heads/master
2021-08-18T19:26:53.210202
2017-11-23T16:53:06
2017-11-23T16:53:06
110,883,857
0
0
null
null
null
null
UTF-8
Java
false
false
736
java
package com.ocr.john.topquiz.controller; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.ocr.john.topquiz.model.MyAdapter; import com.ocr.john.topquiz.R; public class ListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); setTitle("Testing recycling"); final RecyclerView rv = (RecyclerView)findViewById(R.id.list); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setAdapter(new MyAdapter()); } }
[ "contact@remotehireman.fr" ]
contact@remotehireman.fr
997f975b62a8eb99c923fe0adca1cf3b1e985be0
af381539f6c03b9677bec43fe5e427574578f9ad
/src/at/fhooe/mcm/cas/gis/DataObserver.java
a03f36e40e12896ba189a4fa40ec2c67d9fbc38d
[]
no_license
mstader/LBSExcercise
95b3bce70c1c6817a742833e0a5f2ab9d6336b80
9c165a3c515d236b5931509c5ef5225ae32aa6bc
refs/heads/master
2021-08-29T10:56:32.924755
2017-12-13T19:50:46
2017-12-13T19:50:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
313
java
package at.fhooe.mcm.cas.gis; import java.awt.image.BufferedImage; /** * Provides methods to update views. * * @author Oliver * */ public interface DataObserver { /** * Updates * @param _data new image to render */ public void update(BufferedImage _data); public void update(int _mapScale); }
[ "o.barth19@gmail.com" ]
o.barth19@gmail.com
94eb818b1c8f91023d5588b9cb4e4b05a89b1c4e
d1e93e5731131cc1d5248c117f12e1b45faaf441
/app/src/main/java/com/android/uraall/clubolympus/data/OlympusContentProvider.java
defe7e564151f6cb410d7a2d84e5f686342f5c3d
[]
no_license
Hakc13/ClubOlympus
4ca2d4de884fbd32eb4b7776f9b581e8fbca7d8f
d1c6be0e2de34628f8f00c318a60ba6a9ad3d5ef
refs/heads/master
2022-02-01T14:47:34.618018
2019-05-20T18:47:12
2019-05-20T18:47:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,786
java
package com.android.uraall.clubolympus.data; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; import android.widget.Toast; import com.android.uraall.clubolympus.data.ClubOlympusContract.*; public class OlympusContentProvider extends ContentProvider { OlympusDbOpenHelper dbOpenHelper; private static final int MEMBERS = 111; private static final int MEMBER_ID = 222; // Creates a UriMatcher object. private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { uriMatcher.addURI(ClubOlympusContract.AUTHORITY, ClubOlympusContract.PATH_MEMBERS, MEMBERS); uriMatcher.addURI(ClubOlympusContract.AUTHORITY, ClubOlympusContract.PATH_MEMBERS + "/#", MEMBER_ID); } @Override public boolean onCreate() { dbOpenHelper = new OlympusDbOpenHelper(getContext()); return true; } @Override // content://com.android.uraall.clubolympus/members/34 // projection = { "lastName", "gender" } public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor; int match = uriMatcher.match(uri); switch (match) { case MEMBERS: cursor = db.query(MemberEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; // selection = "_id=?" // selectionArgs = 34 case MEMBER_ID: selection = MemberEntry._ID + "=?"; selectionArgs = new String[] {String.valueOf(ContentUris.parseId(uri))}; cursor = db.query(MemberEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; default: throw new IllegalArgumentException("Can't query incorrect URI " + uri); } cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } @Override public Uri insert(Uri uri, ContentValues values) { String firstName = values.getAsString(MemberEntry.COLUMN_FIRST_NAME); if (firstName == null) { throw new IllegalArgumentException("You have to input first name"); } String lastName = values.getAsString(MemberEntry.COLUMN_LAST_NAME); if (lastName == null) { throw new IllegalArgumentException("You have to input last name"); } Integer gender = values.getAsInteger(MemberEntry.COLUMN_GENDER); if (gender == null || !(gender == MemberEntry.GENDER_UNKNOWN || gender == MemberEntry.GENDER_MALE || gender == MemberEntry.GENDER_FEMALE)) { throw new IllegalArgumentException ("You have to input correct gender"); } String sport = values.getAsString(MemberEntry.COLUMN_SPORT); if (sport == null) { throw new IllegalArgumentException("You have to input sport"); } SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int match = uriMatcher.match(uri); switch (match) { case MEMBERS: long id = db.insert(MemberEntry.TABLE_NAME, null, values); if (id == -1) { Log.e("insertMethod", "Insertion of data in the table failed for " + uri); return null; } getContext().getContentResolver().notifyChange(uri, null); return ContentUris.withAppendedId(uri, id); default: throw new IllegalArgumentException("Insertion of data in " + "the table failed for " + uri); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int match = uriMatcher.match(uri); int rowsDeleted; switch (match) { case MEMBERS: rowsDeleted = db.delete(MemberEntry.TABLE_NAME, selection, selectionArgs); break; // selection = "_id=?" // selectionArgs = 34 case MEMBER_ID: selection = MemberEntry._ID + "=?"; selectionArgs = new String[] {String.valueOf(ContentUris.parseId(uri))}; rowsDeleted = db.delete(MemberEntry.TABLE_NAME, selection, selectionArgs); break; default: throw new IllegalArgumentException("Can't delete this URI " + uri); } if (rowsDeleted != 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsDeleted; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (values.containsKey(MemberEntry.COLUMN_FIRST_NAME)) { String firstName = values.getAsString(MemberEntry.COLUMN_FIRST_NAME); if (firstName == null) { throw new IllegalArgumentException ("You have to input first name"); } } if (values.containsKey(MemberEntry.COLUMN_LAST_NAME)) { String lastName = values.getAsString(MemberEntry.COLUMN_LAST_NAME); if (lastName == null) { throw new IllegalArgumentException ("You have to input last name"); } } if (values.containsKey(MemberEntry.COLUMN_GENDER)) { Integer gender = values.getAsInteger(MemberEntry.COLUMN_GENDER); if (gender == null || !(gender == MemberEntry.GENDER_UNKNOWN || gender == MemberEntry.GENDER_MALE || gender == MemberEntry.GENDER_FEMALE)) { throw new IllegalArgumentException("You have to input correct gender"); } } if (values.containsKey(MemberEntry.COLUMN_SPORT)) { String sport = values.getAsString(MemberEntry.COLUMN_SPORT); if (sport == null) { throw new IllegalArgumentException("You have to input sport"); } } SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); int match = uriMatcher.match(uri); int rowsUpdated; switch (match) { case MEMBERS: rowsUpdated = db.update(MemberEntry.TABLE_NAME, values, selection, selectionArgs); break; // selection = "_id=?" // selectionArgs = 34 case MEMBER_ID: selection = MemberEntry._ID + "=?"; selectionArgs = new String[] {String.valueOf(ContentUris.parseId(uri))}; rowsUpdated = db.update(MemberEntry.TABLE_NAME, values, selection, selectionArgs); break; default: throw new IllegalArgumentException("Can't update this URI " + uri); } if (rowsUpdated != 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsUpdated; } @Override public String getType(Uri uri) { int match = uriMatcher.match(uri); switch (match) { case MEMBERS: return MemberEntry.CONTENT_MULTIPLE_ITEMS; case MEMBER_ID: return MemberEntry.CONTENT_SINGLE_ITEM; default: throw new IllegalArgumentException("Unknown URI: " + uri); } } } // URI - Unified Resource Identifier // content://com.android.uraall.clubolympus/members // URL - Unified Resource Locator //http://google.com // content://com.android.uraall.clubolympus/members/3 code 111 // content://com.android.uraall.clubolympus/members code 221 // content://com.android.calendar/events // content://user_dictionary/words // content:// - scheme // com.android.contacts - content authority // contacts - type of data
[ "allakhverdovyuriy@gmail.com" ]
allakhverdovyuriy@gmail.com
796bfd3b0dbc642d72078e5fe71ce2817fbdac8b
c9f097cd6ba5d9510d4c238d40ef244ac1279914
/src/test/java/org/apache/ibatis/plugin/PluginTest.java
ab680db3c06acea31526835884127794ebfe2499
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
WenhongXu/mybatis2sql
7ce4f07a4ed195c5cf97b113559475aeecc6da2c
4d9b9134eac6a66508e8591edef090ebe06f96e4
refs/heads/master
2022-11-12T10:35:14.288298
2020-06-15T06:27:19
2020-06-15T06:27:19
279,103,204
0
1
null
2020-07-12T16:25:27
2020-07-12T16:25:26
null
UTF-8
Java
false
false
1,479
java
/** * Copyright ${license.git.copyrightYears} the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.plugin; import static org.junit.jupiter.api.Assertions.*; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; class PluginTest { @Test void mapPluginShouldInterceptGet() { Map map = new HashMap(); map = (Map) new AlwaysMapPlugin().plugin(map); assertEquals("Always", map.get("Anything")); } @Test void shouldNotInterceptToString() { Map map = new HashMap(); map = (Map) new AlwaysMapPlugin().plugin(map); assertNotEquals("Always", map.toString()); } @Intercepts({ @Signature(type = Map.class, method = "get", args = {Object.class})}) public static class AlwaysMapPlugin implements Interceptor { @Override public Object intercept(Invocation invocation) { return "Always"; } } }
[ "xuliang-dba@wljs.com" ]
xuliang-dba@wljs.com
f7c7b8e8e64bd2a4b829705629e13c6a85bcd104
4d4d63a8daa1bf01222024e3db30244ae68cc014
/src/main/java/cn/dubidubi/service/impl/UserLoginServiceImpl.java
9d9bb39c69264adc3bb6d1ae7cf980ce535556d9
[]
no_license
lzzzz4/dubidubi
aa469341292b36d2942039c422a10dadcfb6b046
e41bc6ee36ed40a6c1d12c042d405ab59ee8102c
refs/heads/master
2021-09-10T21:09:59.896272
2018-04-02T06:47:09
2018-04-02T06:47:09
112,002,900
6
0
null
null
null
null
UTF-8
Java
false
false
1,502
java
package cn.dubidubi.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.dubidubi.dao.base.PermissionMapper; import cn.dubidubi.dao.base.RolePermissionMapper; import cn.dubidubi.dao.base.UserMapper; import cn.dubidubi.dao.base.UserRoleMapper; import cn.dubidubi.model.base.PermissionDO; import cn.dubidubi.model.base.UserDO; import cn.dubidubi.service.UserLoginService; @Service public class UserLoginServiceImpl implements UserLoginService { @Autowired UserMapper userMapper; @Autowired UserRoleMapper userRoleMapper; @Autowired RolePermissionMapper rolePermissionMapper; @Autowired PermissionMapper permissionMapper; @Override public String getPasswordByAccount(String account) { if (account == null) { return null; } String password = userMapper.getPasswordByAccount(account); return password; } // 得到放入session中的user对象 @Override public UserDO getUserDOToSessionByAccount(String account) { if (account == null) { return null; } return userMapper.getUserDOByAccount(account); } @Override public Integer getRoleIdByUserId(int id) { Integer roleid = userRoleMapper.GetRoleIdByUserId(id); return roleid; } @Override public List<PermissionDO> listPermissionByRoleId(int roleId) { List<PermissionDO> list = permissionMapper.listPermissionByRole(roleId); return list; } }
[ "16224@DESKTOP-92SDKOH" ]
16224@DESKTOP-92SDKOH
de0dc9947cab3d1202d3b6af51c8ca233342402d
5aa5f80134511afbc8c0980a268644f297d5c2da
/src/main/java/com/s/controller/base/TblCustomTypeController.java
1ba7b59a9adefb1afb4df8a90fc46360903797df
[]
no_license
Slime6666/projects
edcdf4c26749f67239fc852ea9b8db44599e28da
0704cc61a7fc8ae74a630d89973f1fd51cc861ab
refs/heads/master
2023-06-28T19:39:45.074269
2021-07-27T12:29:28
2021-07-27T12:29:28
386,939,813
0
0
null
null
null
null
UTF-8
Java
false
false
336
java
package com.s.controller.base; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.stereotype.Controller; /** * <p> * 自定义类型 前端控制器 * </p> * * @author smile * @since 2021-07-17 */ @Controller @RequestMapping("/tblCustomType") public class TblCustomTypeController { }
[ "52064463+Little-Dragon-God@users.noreply.github.com" ]
52064463+Little-Dragon-God@users.noreply.github.com
4743bfdb37855b4ff297c3573c3e10955e482ba3
c901df4e2c75b006aba09d707461c9e42fd94841
/spring-boot-backend-apirest/src/main/java/com/plerzundi/springboot/backend/apirest/models/entity/Cliente.java
b58949cc214937945e40fbfc1c33910871f5609d
[]
no_license
plerzundi/Springboot5-Angular
a654feb9f1d39cc9602fb514820c5aa519eea246
795212c0e522978a6626270267b8fb2e679f8e52
refs/heads/master
2020-03-23T11:23:55.618150
2018-07-23T05:30:38
2018-07-23T05:30:38
141,501,065
1
0
null
null
null
null
UTF-8
Java
false
false
1,424
java
package com.plerzundi.springboot.backend.apirest.models.entity; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Entity @Table(name = "clientes") public class Cliente implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nombre; private String apellido; private String email; @Column(name = "create_at") @Temporal(TemporalType.DATE) private Date createAt; // genera la fecha antes que se guarde @PrePersist public void prePersist() { createAt = new Date(); } /* * * Getter and Setters * */ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } }
[ "patriciolerzundi@gmail.com" ]
patriciolerzundi@gmail.com
48d116e3a14fbd222dc1dd781a07bb08f3247429
a1007dcb5af6544e919160bfd1854fca35ffb1fe
/pet-clinic-data/src/main/java/com/example/petclinic/model/Specialty.java
c44839918b1c4da470ffd6c4c4e89c304bd90fbc
[]
no_license
carlfsmithiii/sfg-pet-clinic
31bbf99a5337414d3ce814314a10752311c6d1d9
e40337203a7730b6e05385c0fa1d80b3c6c98706
refs/heads/master
2020-04-21T13:11:54.280704
2019-03-05T02:53:18
2019-03-05T02:53:18
169,590,558
0
0
null
null
null
null
UTF-8
Java
false
false
369
java
package com.example.petclinic.model; import lombok.*; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Setter @Getter @NoArgsConstructor @AllArgsConstructor @Builder @Entity @Table(name = "specialties") public class Specialty extends BaseEntity { @Column(name = "description") private String description; }
[ "carlfsmithiii@gmail.com" ]
carlfsmithiii@gmail.com
a598458f52438a2ff095cdba5eb2795148195e95
67ec0c499116960e24835bbbaec9b2f952af43b8
/android/PhysicalWeb/app/src/main/java/org/physical_web/physicalweb/WifiUrlDeviceDiscoverer.java
30ddbf16dfd9e7b19b4cf1148542946b679b059d
[ "Apache-2.0" ]
permissive
carloserodriguez2000/physical-web
7cddd51b824b3768fd194e25ba28e989160c9489
fb9ed2251e46f85cebf521431939aa7790095e21
refs/heads/master
2020-12-11T07:56:22.767495
2016-08-08T18:24:48
2016-08-08T18:24:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,365
java
/* * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.physical_web.physicalweb; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.util.Log; /** * This class is for using WifiDirect to discover Physical Web * Devices through peer discovery. */ class WifiUrlDeviceDiscoverer extends UrlDeviceDiscoverer { private static final String TAG = "WifiUrlDeviceDiscoverer"; private Context mContext; private WifiP2pManager mManager; private Channel mChannel; private IntentFilter mIntentFilter = new IntentFilter(); private boolean mIsRunning = false; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action) && mManager != null) { mManager.requestPeers(mChannel, mPeerListener); } } }; private final PeerListListener mPeerListener = new PeerListListener() { @Override public void onPeersAvailable(WifiP2pDeviceList list) { Log.d(TAG, list.toString()); for (WifiP2pDevice device : list.getDeviceList()) { Utils.WifiDirectInfo info = Utils.parseWifiDirectName(device.deviceName); if (info != null) { String name = info.title; int port = info.port; reportUrlDevice(createUrlDeviceBuilder("WifiDirect" + name, device.deviceAddress + ":" + port) .setWifiAddress(device.deviceAddress) .setWifiPort(port) .setTitle(name) .setDescription("") .setDeviceType(Utils.WIFI_DIRECT_DEVICE_TYPE) .build()); } } } }; public WifiUrlDeviceDiscoverer(Context context) { mContext = context; } @Override public synchronized void startScanImpl() { mManager = (WifiP2pManager) mContext.getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(mContext, mContext.getMainLooper(), null); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mContext.registerReceiver(mReceiver, intentFilter); mIsRunning = true; discoverHelper(true); } private void discoverHelper(boolean retry) { mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int reasonCode) { if (retry && reasonCode == WifiP2pManager.BUSY) { mManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(TAG, "cancel connect call success"); if (mIsRunning) { discoverHelper(false); } } @Override public void onFailure(int reason) { Log.d(TAG, "cancel connect call fail " + reason); } }); } } }); } @Override public synchronized void stopScanImpl() { mIsRunning = false; mManager.stopPeerDiscovery(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(TAG, "stop discovering"); } @Override public void onFailure(int reasonCode) { Log.d(TAG, "stop discovery failed " + reasonCode); } }); } }
[ "nishadg@google.com" ]
nishadg@google.com
f1f0ed2aa7587089e6759003715c880414e8fcea
1935ba11daf79ce7293f2d880de08a2986072f3c
/src/main/java/io/github/ryuu/adventurecraft/overrides/dn.java
5d34456490b64bd59381c42dabdc5c7ea779035b
[ "CC0-1.0" ]
permissive
TechPizzaDev/AC-1.7.3
9c61a068863b08c314859244919f6f5183f84954
68205e7079c09ce8944c338348481a311dfff6bb
refs/heads/main
2023-07-04T14:52:35.125995
2021-08-04T17:35:39
2021-08-04T17:35:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,063
java
package io.github.ryuu.adventurecraft.overrides; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.lwjgl.opengl.GL11; public class dn { protected Level a; private final List[] b = new List[6]; private final ji c; private final Random d = new Random(); public dn(Level world, ji renderengine) { if (world != null) this.a = world; this.c = renderengine; for (int i = 0; i < 6; i++) this.b[i] = new ArrayList(); } public void a(xw entityfx) { int i = entityfx.c_(); if (this.b[i].size() >= 4000) this.b[i].remove(0); this.b[i].add(entityfx); } public void a() { for (int i = 0; i < 6; i++) { for (int j = 0; j < this.b[i].size(); j++) { xw entityfx = this.b[i].get(j); entityfx.w_(); if (entityfx.be) this.b[i].remove(j--); } } } public List getEffectsWithinAABB(eq axisalignedbb) { ArrayList<sn> arraylist = new ArrayList(); for (int i = 0; i < 6; i++) { for (Object obj : this.b[i]) { sn p = (sn) obj; if (axisalignedbb.a <= p.aM && axisalignedbb.d >= p.aM && axisalignedbb.b <= p.aN && axisalignedbb.e >= p.aN && axisalignedbb.c <= p.aO && axisalignedbb.f >= p.aO) arraylist.add(p); } } return arraylist; } public void a(sn entity, float f) { float f1 = in.b(entity.aS * 3.141593F / 180.0F); float f2 = in.a(entity.aS * 3.141593F / 180.0F); float f3 = -f2 * in.a(entity.aT * 3.141593F / 180.0F); float f4 = f1 * in.a(entity.aT * 3.141593F / 180.0F); float f5 = in.b(entity.aT * 3.141593F / 180.0F); xw.l = entity.bl + (entity.aM - entity.bl) * f; xw.m = entity.bm + (entity.aN - entity.bm) * f; xw.n = entity.bn + (entity.aO - entity.bn) * f; for (int i = 0; i < 5; i++) { if (this.b[i].size() != 0) { int j = 0; if (i == 0) j = this.c.b("/particles.png"); if (i == 1) j = this.c.b("/terrain.png"); if (i == 2) j = this.c.b("/gui/items.png"); if (i == 3) j = this.c.b("/terrain2.png"); if (i == 4) j = this.c.b("/terrain3.png"); GL11.glBindTexture(3553, j); nw tessellator = nw.a; tessellator.b(); for (int k = 0; k < this.b[i].size(); k++) { xw entityfx = this.b[i].get(k); entityfx.a(tessellator, f, f1, f5, f2, f3, f4); } tessellator.a(); } } } public void b(sn entity, float f) { byte byte0 = 5; if (this.b[byte0].size() == 0) return; nw tessellator = nw.a; for (int i = 0; i < this.b[byte0].size(); i++) { xw entityfx = this.b[byte0].get(i); entityfx.a(tessellator, f, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F); } } public void a(Level world) { this.a = world; for (int i = 0; i < 6; i++) this.b[i].clear(); } public void a(int i, int j, int k, int l, int i1) { if (l == 0) return; Tile block = Tile.m[l]; int j1 = 4; for (int k1 = 0; k1 < j1; k1++) { for (int l1 = 0; l1 < j1; l1++) { for (int i2 = 0; i2 < j1; i2++) { double d = i + (k1 + 0.5D) / j1; double d1 = j + (l1 + 0.5D) / j1; double d2 = k + (i2 + 0.5D) / j1; int j2 = this.d.nextInt(6); a((new qm(this.a, d, d1, d2, d - i - 0.5D, d1 - j - 0.5D, d2 - k - 0.5D, block, j2, i1)).a(i, j, k)); } } } } public void a(int i, int j, int k, int l) { int i1 = this.a.a(i, j, k); if (i1 == 0) return; Tile block = Tile.m[i1]; float f = 0.1F; double d = i + this.d.nextDouble() * (block.bv - block.bs - (f * 2.0F)) + f + block.bs; double d1 = j + this.d.nextDouble() * (block.bw - block.bt - (f * 2.0F)) + f + block.bt; double d2 = k + this.d.nextDouble() * (block.bx - block.bu - (f * 2.0F)) + f + block.bu; if (l == 0) d1 = j + block.bt - f; if (l == 1) d1 = j + block.bw + f; if (l == 2) d2 = k + block.bu - f; if (l == 3) d2 = k + block.bx + f; if (l == 4) d = i + block.bs - f; if (l == 5) d = i + block.bv + f; a((new qm(this.a, d, d1, d2, 0.0D, 0.0D, 0.0D, block, l, this.a.e(i, j, k))).a(i, j, k).c(0.2F).d(0.6F)); } public String b() { return "" + (this.b[0].size() + this.b[1].size() + this.b[2].size()); } }
[ "maurermarkuss6@gmail.com" ]
maurermarkuss6@gmail.com
c38948d7045c640f2230571f9ec99e3d54917092
10dddcef957129cdbf5ea595310cda3e2354462a
/SetMatrixZeros.java
2ec4440a66d1e412f9bad7058bfdb9dc71eb0ac6
[]
no_license
vincentwanggs/leetcode
fb14b88f7e4f396e8f0b6a084eff54b8659d6e5a
4c502841a1136e17923e8114e0170b5826bb1418
refs/heads/master
2016-09-02T05:40:30.133766
2014-10-12T05:13:45
2014-10-12T05:13:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,040
java
public class SetMatrixZeroes{ public void setZeroes(int[][] matrix){ //use the first row and col to store the rows and cols that contain zeros int m = matrix.length; int n = matrix[0].length; boolean firstRowZero = false; boolean firstColZero = false; for (int i = 0; i < m; i ++) if (matrix[i][0] == 0) firstColZero = true; for (int j = 0; j < n; j ++) if (matrix[0][j] == 0) firstRowZero = true; for (int i = 1; i < m; i ++){ for (int j = 1; j < n; j ++){ if (matrix[i][j] == 0){ matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = 1; i < m; i ++){ if (matrix[i][0] == 0){ for (int j = 1; j < n; j ++){ matrix[i][j] = 0; } } } for (int j = 1; j < n; j ++){ if (matrix[0][j] == 0){ for (int i = 1; i < m; i ++){ matrix[i][j] = 0; } } } if (firstRowZero){ for (int j = 0; j < n; j ++){ matrix[0][j] = 0; } } if (firstColZero){ for (int i = 0; i < m; i ++){ matrix[i][0] = 0; } } } }
[ "vincentwanggs@users.noreply.github.com" ]
vincentwanggs@users.noreply.github.com
8a597551a726ecc648e3389ac88e6508220b9b5a
5e0d6917d3ae820531bbb399146a217d841a17e3
/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-namespace/src/test/java/io/shardingjdbc/orchestration/spring/util/FieldValueUtil.java
e7ae41e8b0bd7aaa8d7c0f2a6ad791a3bb0c8ef8
[ "Apache-2.0" ]
permissive
Begro/sharding-jdbc
597780a0250f7a1e307e550404d54521311ac663
530c32674c0278ca23eba7b055a6364473449724
refs/heads/master
2021-01-19T14:03:20.717810
2018-05-07T08:35:11
2018-05-07T08:35:11
88,119,358
0
0
Apache-2.0
2018-05-07T08:35:12
2017-04-13T03:05:37
Java
UTF-8
Java
false
false
1,914
java
/* * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package io.shardingjdbc.orchestration.spring.util; import com.google.common.base.Strings; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.lang.reflect.Field; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class FieldValueUtil { private static Object getFieldValue(final Class<?> clazz, final Object obj, final String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); if (!field.isAccessible()) { field.setAccessible(true); } return field.get(obj); } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); return null; } } public static Object getFieldValue(final Object obj, final String fieldName, final boolean fromSuperclass) { if (null == obj || Strings.isNullOrEmpty(fieldName)) { return null; } Class<?> clazz = fromSuperclass ? obj.getClass().getSuperclass() : obj.getClass(); return getFieldValue(clazz, obj, fieldName); } public static Object getFieldValue(final Object obj, final String fieldName) { return getFieldValue(obj, fieldName, false); } }
[ "caohaoch@gmail.com" ]
caohaoch@gmail.com
03248191d2b357d053e95e299d34652027cff6c1
d4e93cdd47e5a91c79cb0f0e0ac60366b8908560
/src/com/nullpointerworks/ide/jasm/view/swing/highlight/RegisterHighlighter.java
d4764451901a81a3d787e1825e9b984c25e46263
[]
no_license
NullpointerWorks/jasm-ide
8ed6cb7eaa4642b0eb1cbd4b5432142e8adfa3b2
c68696147696b721e076bdb46b3d50cd0dbbfb06
refs/heads/main
2023-08-18T19:11:11.722569
2021-10-12T16:29:46
2021-10-12T16:29:46
348,673,176
0
0
null
null
null
null
UTF-8
Java
false
false
1,114
java
package com.nullpointerworks.ide.jasm.view.swing.highlight; import java.awt.Color; import javax.swing.text.MutableAttributeSet; import javax.swing.text.StyleConstants; public class RegisterHighlighter implements HighlightValidator { private final Color REGISTER = new Color(0, 170, 0); @Override public boolean isValid(String token) { if (token.equals("ip")) return true; if (token.equals("sp")) return true; if (token.equals("a")) return true; if (token.equals("b")) return true; if (token.equals("c")) return true; if (token.equals("d")) return true; if (token.equals("r0")) return true; if (token.equals("r1")) return true; if (token.equals("r2")) return true; if (token.equals("r3")) return true; if (token.equals("r4")) return true; if (token.equals("r5")) return true; if (token.equals("r6")) return true; if (token.equals("r7")) return true; if (token.equals("r8")) return true; if (token.equals("r9")) return true; return false; } @Override public void setHighlight(MutableAttributeSet asNew) { StyleConstants.setForeground(asNew, REGISTER); } }
[ "38044500+NullpointerWorks@users.noreply.github.com" ]
38044500+NullpointerWorks@users.noreply.github.com
52d711d011e0e213f5a8b512c4c52e3f2d3b35a4
bb02424ee7a6fdbfa89ad6f05be1ea5ee598de11
/src/main/java/nl/azwaan/quotedb/api/BooksAPI.java
d9c51b77b44464166943aec34581672f3b4f3853
[]
no_license
AZWN/QuoteDB
e08f8617a3dda1744030f01398abd8740e2f4a87
bca93b19e542e7e87f7378b2aab56dcf53cddd19
refs/heads/master
2023-01-11T17:44:26.943031
2020-08-14T07:33:54
2020-08-14T07:48:49
187,384,616
0
0
null
2023-01-07T18:40:43
2019-05-18T17:08:26
Java
UTF-8
Java
false
false
3,685
java
package nl.azwaan.quotedb.api; import com.google.inject.Inject; import com.google.inject.Singleton; import nl.azwaan.quotedb.api.querybuilding.BookFilterBuilder; import nl.azwaan.quotedb.api.querybuilding.BookQuoteFilterBuilder; import nl.azwaan.quotedb.api.querybuilding.filters.EqualityFilter; import nl.azwaan.quotedb.api.querybuilding.FilterBuilder; import nl.azwaan.quotedb.api.paging.MultiResultPage; import nl.azwaan.quotedb.api.paging.PageHelpers; import nl.azwaan.quotedb.api.patches.BookPatch; import nl.azwaan.quotedb.dao.AuthorsDAO; import nl.azwaan.quotedb.dao.BookQuotesDAO; import nl.azwaan.quotedb.dao.BooksDAO; import nl.azwaan.quotedb.exceptions.EntityNotFoundException; import nl.azwaan.quotedb.models.Author; import nl.azwaan.quotedb.models.Book; import nl.azwaan.quotedb.models.BookQuote; import nl.azwaan.quotedb.models.User; import nl.azwaan.quotedb.permissions.PermissionChecker; import org.jooby.Request; import org.jooby.mvc.Consumes; import org.jooby.mvc.GET; import org.jooby.mvc.Path; import org.jooby.mvc.Produces; import java.util.Collections; @Singleton @Path("/books") @Produces("application/json") @Consumes("application/json") public class BooksAPI extends BaseAPI<Book, BookPatch> { @Inject private AuthorsDAO authorsDAO; @Inject private PermissionChecker<Author> authorPermissionChecker; @Inject private BookQuotesDAO bookQuotesDAO; @Inject private PermissionChecker<BookQuote> bookQuotePermissionChecker; @Inject protected BooksAPI(BooksDAO dao) { super(dao); } @Override protected void resolveReferencesForNewEntity(Book entity, User authenticatedUser) { super.resolveReferencesForNewEntity(entity, authenticatedUser); // If author already in db, replace with real entity authorsDAO.getEntityById(entity.getAuthor().getId()) .ifPresent(entity::setAuthor); } @Override protected void applyPatch(Book book, User authenticatedUser, BookPatch patch) { patch.title.ifPresent(book::setTitle); patch.publisher.ifPresent(book::setPublisher); patch.publicationYear.ifPresent(book::setPublicationYear); patch.author.ifPresent(authorId -> { final Author author = authorsDAO.getEntityById(authorId) .orElseThrow(() -> new EntityNotFoundException(Author.class.getName(), authorId)); authorPermissionChecker.checkReadEntity(author, authenticatedUser); book.setAuthor(author); }); } @Override protected Class<BookPatch> getPatchClass() { return BookPatch.class; } @Override protected FilterBuilder getDefaultFilterBuilder(Request request) { return new BookFilterBuilder(dao, getAuthenticatedUser(request), request); } /** * Returns all quotes from a given book. * @param request The request that is handled * @param id The book id url parameter. * @return A page containing all the quotes in the book. */ @GET @Path("/:id/quotes") public MultiResultPage<BookQuote> getQuotesFromBook(Request request, Long id) { final User authenticatedUser = getAuthenticatedUser(request); final BookQuoteFilterBuilder filterBuilder = new BookQuoteFilterBuilder(bookQuotesDAO, authenticatedUser, request); filterBuilder.addFilters(Collections.singletonList(new EqualityFilter<>(BookQuote.BOOK_ID, id))); return PageHelpers.getPagedResult(request, bookQuotesDAO, authenticatedUser, bookQuotePermissionChecker, filterBuilder); } }
[ "AZWN@users.noreply.github.com" ]
AZWN@users.noreply.github.com
6f8438b8739ef5315773de981a7e5cd90136145f
35d7ccdab2383571f9f708ab05f872dca7da6f8f
/restful-blog-author/src/main/java/com/benjsicam/restfulblog/service/UserDetailsServiceImpl.java
d497e74cbad9ed0f144cc54c9e92cfbe87759348
[]
no_license
juanwalker/restful-blog-microservices-phase4
f470c1929a9136421c3f0d5060ef218abbfd33dd
c6739438893ea6b0997492a0af135900c7560468
refs/heads/master
2021-01-24T18:39:14.744090
2017-04-13T02:18:32
2017-04-13T02:18:32
84,464,397
0
0
null
null
null
null
UTF-8
Java
false
false
2,301
java
package com.benjsicam.restfulblog.service; import com.benjsicam.restfulblog.client.CredentialsClientService; import com.benjsicam.restfulblog.domain.Credentials; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.Collection; @Service public class UserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class); @Value("${basic-authentication.user}") String serviceAuthUser; @Value("${basic-authentication.password-encoded}") String serviceAuthPassword; @Autowired private CredentialsClientService credentialsClientService; public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if (username.equals(serviceAuthUser)){ Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_SERVICE")); return new User(serviceAuthUser,serviceAuthPassword, true, true, true, true, authorities); }else{ Credentials credentials = credentialsClientService.loadCredentialsByUserName(username); if(credentials == null) { throw new UsernameNotFoundException("Username or password is invalid."); } return this.createUserDetails(credentials); } } private UserDetails createUserDetails(Credentials credentials){ Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); credentials.getRoles().stream().forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); return new User(credentials.getUsername(), credentials.getPassword(), true, true, true, true, authorities); } }
[ "juanwalker@gmail.com" ]
juanwalker@gmail.com
5653cfbdf7a6015d3e45d7245ddd6c58d578c526
20eb62855cb3962c2d36fda4377dfd47d82eb777
/newEvaluatedBugs/Jsoup_38_buggy/mutated/2055/HtmlTreeBuilderState.java
743090715dba1d77f811938b509756df58ed26be
[]
no_license
ozzydong/CapGen
356746618848065cce4e253e5d3c381baa85044a
0ba0321b6b1191443276021f1997833342f02515
refs/heads/master
2023-03-18T20:12:02.923428
2020-08-21T03:08:28
2020-08-21T03:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
68,216
java
package org.jsoup.parser; import org.jsoup.helper.DescendableLinkedList; import org.jsoup.helper.StringUtil; import org.jsoup.nodes.*; import java.util.Iterator; import java.util.LinkedList; /** * The Tree Builder's current state. Each state embodies the processing for the state, and transitions to other states. */ enum HtmlTreeBuilderState { Initial { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { return true; // ignore whitespace } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { // todo: parse error check on expected doctypes // todo: quirk state check on doctype ids Token.Doctype d = t.asDoctype(); DocumentType doctype = new DocumentType(d.getName(), d.getPublicIdentifier(), d.getSystemIdentifier(), tb.getBaseUri()); tb.getDocument().appendChild(doctype); if (d.isForceQuirks()) tb.getDocument().quirksMode(Document.QuirksMode.quirks); tb.transition(BeforeHtml); } else { // todo: check not iframe srcdoc tb.transition(BeforeHtml); return tb.process(t); // re-process token } return true; } }, BeforeHtml { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isDoctype()) { tb.error(this); return false; } else if (t.isComment()) { tb.insert(t.asComment()); } else if (isWhitespace(t)) { return true; // ignore whitespace } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { tb.insert(t.asStartTag()); tb.transition(BeforeHead); } else if (t.isEndTag() && (StringUtil.in(t.asEndTag().name(), "head", "body", "html", "br"))) { return anythingElse(t, tb); } else if (t.isEndTag()) { tb.error(this); return false; } else { closeCell(tb); return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, HtmlTreeBuilder tb) { tb.insert("html"); tb.transition(BeforeHead); return tb.process(t); } }, BeforeHead { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { return true; } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return InBody.process(t, tb); // does not transition } else if (t.isStartTag() && t.asStartTag().name().equals("head")) { Element head = tb.insert(t.asStartTag()); tb.setHeadElement(head); tb.transition(InHead); } else if (t.isEndTag() && (StringUtil.in(t.asEndTag().name(), "head", "body", "html", "br"))) { tb.process(new Token.StartTag("head")); return tb.process(t); } else if (t.isEndTag()) { tb.error(this); return false; } else { tb.process(new Token.StartTag("head")); return tb.process(t); } return true; } }, InHead { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); return true; } switch (t.type) { case Comment: tb.insert(t.asComment()); break; case Doctype: tb.error(this); return false; case StartTag: Token.StartTag start = t.asStartTag(); String name = start.name(); if (name.equals("html")) { return InBody.process(t, tb); } else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link")) { Element el = tb.insertEmpty(start); // jsoup special: update base the frist time it is seen if (name.equals("base") && el.hasAttr("href")) tb.maybeSetBaseUri(el); } else if (name.equals("meta")) { Element meta = tb.insertEmpty(start); // todo: charset switches } else if (name.equals("title")) { handleRcData(start, tb); } else if (StringUtil.in(name, "noframes", "style")) { handleRawtext(start, tb); } else if (name.equals("noscript")) { // else if noscript && scripting flag = true: rawtext (jsoup doesn't run script, to handle as noscript) tb.insert(start); tb.transition(InHeadNoscript); } else if (name.equals("script")) { // skips some script rules as won't execute them tb.insert(start); tb.tokeniser.transition(TokeniserState.ScriptData); tb.markInsertionMode(); tb.transition(Text); } else if (name.equals("head")) { tb.error(this); return false; } else { return anythingElse(t, tb); } break; case EndTag: Token.EndTag end = t.asEndTag(); name = end.name(); if (name.equals("head")) { tb.pop(); tb.transition(AfterHead); } else if (StringUtil.in(name, "body", "html", "br")) { return anythingElse(t, tb); } else { tb.error(this); return false; } break; default: return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, TreeBuilder tb) { tb.process(new Token.EndTag("head")); return tb.process(t); } }, InHeadNoscript { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isDoctype()) { tb.error(this); } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return tb.process(t, InBody); } else if (t.isEndTag() && t.asEndTag().name().equals("noscript")) { tb.pop(); tb.transition(InHead); } else if (isWhitespace(t) || t.isComment() || (t.isStartTag() && StringUtil.in(t.asStartTag().name(), "basefont", "bgsound", "link", "meta", "noframes", "style"))) { return tb.process(t, InHead); } else if (t.isEndTag() && t.asEndTag().name().equals("br")) { return anythingElse(t, tb); } else if ((t.isStartTag() && StringUtil.in(t.asStartTag().name(), "head", "noscript")) || t.isEndTag()) { tb.error(this); return false; } else { return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, HtmlTreeBuilder tb) { tb.error(this); tb.process(new Token.EndTag("noscript")); return tb.process(t); } }, AfterHead { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); } else if (t.isStartTag()) { Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { return tb.process(t, InBody); } else if (name.equals("body")) { tb.insert(startTag); tb.framesetOk(false); tb.transition(InBody); } else if (name.equals("frameset")) { tb.insert(startTag); tb.transition(InFrameset); } else if (StringUtil.in(name, "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "title")) { tb.error(this); Element head = tb.getHeadElement(); tb.push(head); tb.process(t, InHead); tb.removeFromStack(head); } else if (name.equals("head")) { tb.error(this); return false; } else { anythingElse(t, tb); } } else if (t.isEndTag()) { if (StringUtil.in(t.asEndTag().name(), "body", "html")) { anythingElse(t, tb); } else { tb.error(this); return false; } } else { anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, HtmlTreeBuilder tb) { tb.process(new Token.StartTag("body")); tb.framesetOk(true); return tb.process(t); } }, InBody { boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { // todo confirm that check tb.error(this); return false; } else if (isWhitespace(c)) { tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { tb.error(this); // merge attributes onto real html Element html = tb.getStack().getFirst(); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else if (!tb.framesetOk()) { return false; // ignore frameset } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); // pop up to html element while (stack.size() > 1) stack.removeLast(); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol", "p", "section", "summary", "ul")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.in(name, "pre", "listing")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); // todo: ignore LF if next token tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } Element form = tb.insert(startTag); tb.setFormElement(form); } else if (name.equals("li")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.process(new Token.EndTag("li")); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "dd", "dt")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.in(el.nodeName(), "dd", "dt")) { tb.process(new Token.EndTag(el.nodeName())); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out } else if (name.equals("button")) { if (tb.inButtonScope("button")) { // close and reprocess tb.error(this); tb.process(new Token.EndTag("button")); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.process(new Token.EndTag("a")); // still on stack? Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.in(name, "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.process(new Token.EndTag("nobr")); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.in(name, "applet", "marquee", "object")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.in(name, "param", "source", "track")) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { // we're not supposed to ask. startTag.name("img"); return tb.process(startTag); } else if (name.equals("isindex")) { // how much do we care about the early 90s? tb.error(this); if (tb.getFormElement() != null) return false; tb.tokeniser.acknowledgeSelfClosingFlag(); tb.process(new Token.StartTag("form")); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.process(new Token.StartTag("hr")); tb.process(new Token.StartTag("label")); // hope you like english. String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character(prompt)); // input Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.in(attr.getKey(), "name", "action", "prompt")) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.process(new Token.StartTag("input", inputAttribs)); tb.process(new Token.EndTag("label")); tb.process(new Token.StartTag("hr")); tb.process(new Token.EndTag("form")); } else if (name.equals("textarea")) { tb.insert(startTag); // todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.) tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { // also handle noscript if script enabled handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); HtmlTreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.in("optgroup", "option")) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.in("rp", "rt")) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); // i.e. close up to but not include name } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml) tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "svg" (xlink, svg) tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (StringUtil.in(name, "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { // todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.process(new Token.EndTag("body")); if (notIgnored) return tb.process(endTag); } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu", "nav", "ol", "pre", "section", "summary", "ul")) { // todo: refactor these lookups if (!tb.inScope(name)) { // nothing to close tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); // remove currentForm from stack. will shift anything under up. tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p> return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "dd", "dt")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6"); } } else if (name.equals("sarcasm")) { // *sigh* return anyOtherEndTag(t, tb); } else if (StringUtil.in(name, "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) { // Adoption Agency Algorithm. OUTER: for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; LinkedList<Element> stack = tb.getStack(); for (int si = 0; si < stack.size(); si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } // todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list. // does that mean: int pos of format el in list? Element node = furthestBlock; Element lastNode = furthestBlock; INNER: for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check tb.removeFromStack(node); continue INNER; } else if (node == formatEl) break INNER; Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri()); tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { // todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements. // not getting how this bookmark both straddles the element above, but is inbetween here... } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod. } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); // todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark. tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.in(name, "applet", "marquee", "object")) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.process(new Token.StartTag("br")); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: // todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html // stop parsing break; } return true; } boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) { String name = t.asEndTag().name(); DescendableLinkedList<Element> stack = tb.getStack(); Iterator<Element> it = stack.descendingIterator(); while (it.hasNext()) { Element node = it.next(); if (node.nodeName().equals(name)) { tb.generateImpliedEndTags(name); if (!name.equals(tb.currentElement().nodeName())) tb.error(this); tb.popStackToClose(name); break; } else { if (tb.isSpecial(node)) { tb.error(this); return false; } } } return true; } }, Text { // in script, style etc. normally treated as data tags boolean process(Token t, HtmlTreeBuilder tb) { if (t.isCharacter()) { tb.insert(t.asCharacter()); } else if (t.isEOF()) { tb.error(this); // if current node is script: already started tb.pop(); tb.transition(tb.originalState()); return tb.process(t); } else if (t.isEndTag()) { // if: An end tag whose tag name is "script" -- scripting nesting level, if evaluating scripts tb.pop(); tb.transition(tb.originalState()); } return true; } }, InTable { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isCharacter()) { tb.newPendingTableCharacters(); tb.markInsertionMode(); tb.transition(InTableText); return tb.process(t); } else if (t.isComment()) { tb.insert(t.asComment()); return true; } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag()) { Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("caption")) { tb.clearStackToTableContext(); tb.insertMarkerToFormattingElements(); tb.insert(startTag); tb.transition(InCaption); } else if (name.equals("colgroup")) { tb.clearStackToTableContext(); tb.insert(startTag); tb.transition(InColumnGroup); } else if (name.equals("col")) { tb.process(new Token.StartTag("colgroup")); return tb.process(t); } else if (StringUtil.in(name, "tbody", "tfoot", "thead")) { tb.clearStackToTableContext(); tb.insert(startTag); tb.transition(InTableBody); } else if (StringUtil.in(name, "td", "th", "tr")) { tb.process(new Token.StartTag("tbody")); return tb.process(t); } else if (name.equals("table")) { tb.error(this); boolean processed = tb.process(new Token.EndTag("table")); if (processed) // only ignored if in fragment return tb.process(t); } else if (StringUtil.in(name, "style", "script")) { return tb.process(t, InHead); } else if (name.equals("input")) { if (!startTag.attributes.get("type").equalsIgnoreCase("hidden")) { return anythingElse(t, tb); } else { tb.insertEmpty(startTag); } } else if (name.equals("form")) { tb.error(this); if (tb.getFormElement() != null) return false; else { Element form = tb.insertEmpty(startTag); tb.setFormElement(form); } } else { return anythingElse(t, tb); } } else if (t.isEndTag()) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (name.equals("table")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } else { tb.popStackToClose("table"); } tb.resetInsertionMode(); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { return anythingElse(t, tb); } } else if (t.isEOF()) { if (tb.currentElement().nodeName().equals("html")) tb.error(this); return true; // stops parsing } return anythingElse(t, tb); } boolean anythingElse(Token t, HtmlTreeBuilder tb) { tb.error(this); boolean processed = true; if (StringUtil.in(tb.currentElement().nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { tb.setFosterInserts(true); processed = tb.process(t, InBody); tb.setFosterInserts(false); } else { processed = tb.process(t, InBody); } return processed; } }, InTableText { boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case Character: Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else { tb.getPendingTableCharacters().add(c); } break; default: if (tb.getPendingTableCharacters().size() > 0) { for (Token.Character character : tb.getPendingTableCharacters()) { if (!isWhitespace(character)) { // InTable anything else section: tb.error(this); if (StringUtil.in(tb.currentElement().nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { tb.setFosterInserts(true); tb.process(character, InBody); tb.setFosterInserts(false); } else { tb.process(character, InBody); } } else tb.insert(character); } tb.newPendingTableCharacters(); } tb.transition(tb.originalState()); return tb.process(t); } return true; } }, InCaption { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isEndTag() && t.asEndTag().name().equals("caption")) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (!tb.inTableScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("caption")) tb.error(this); tb.popStackToClose("caption"); tb.clearFormattingElementsToLastMarker(); tb.transition(InTable); } } else if (( t.isStartTag() && StringUtil.in(t.asStartTag().name(), "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr") || t.isEndTag() && t.asEndTag().name().equals("table")) ) { tb.error(this); boolean processed = tb.process(new Token.EndTag("caption")); if (processed) return tb.process(t); } else if (t.isEndTag() && StringUtil.in(t.asEndTag().name(), "body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { return tb.process(t, InBody); } return true; } }, InColumnGroup { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); return true; } switch (t.type) { case Comment: tb.insert(t.asComment()); break; case Doctype: tb.error(this); break; case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) return tb.process(t, InBody); else if (name.equals("col")) tb.insertEmpty(startTag); else return anythingElse(t, tb); break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("colgroup")) { if (tb.currentElement().nodeName().equals("html")) { // frag case tb.error(this); return false; } else { tb.pop(); tb.transition(InTable); } } else return anythingElse(t, tb); break; case EOF: if (tb.currentElement().nodeName().equals("html")) return true; // stop parsing; frag case else return anythingElse(t, tb); default: return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, TreeBuilder tb) { boolean processed = tb.process(new Token.EndTag("colgroup")); if (processed) // only ignored in frag case return tb.process(t); return true; } }, InTableBody { boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("tr")) { tb.clearStackToTableBodyContext(); tb.insert(startTag); tb.transition(InRow); } else if (StringUtil.in(name, "th", "td")) { tb.error(this); tb.process(new Token.StartTag("tr")); return tb.process(startTag); } else if (StringUtil.in(name, "caption", "col", "colgroup", "tbody", "tfoot", "thead")) { return exitTableBody(t, tb); } else return anythingElse(t, tb); break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (StringUtil.in(name, "tbody", "tfoot", "thead")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } else { tb.clearStackToTableBodyContext(); tb.pop(); tb.transition(InTable); } } else if (name.equals("table")) { return exitTableBody(t, tb); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html", "td", "th", "tr")) { tb.error(this); return false; } else return anythingElse(t, tb); break; default: return anythingElse(t, tb); } return true; } private boolean exitTableBody(Token t, HtmlTreeBuilder tb) { if (!(tb.inTableScope("tbody") || tb.inTableScope("thead") || tb.inScope("tfoot"))) { // frag case tb.error(this); return false; } tb.clearStackToTableBodyContext(); tb.process(new Token.EndTag(tb.currentElement().nodeName())); // tbody, tfoot, thead return tb.process(t); } private boolean anythingElse(Token t, HtmlTreeBuilder tb) { return tb.process(t, InTable); } }, InRow { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isStartTag()) { Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (StringUtil.in(name, "th", "td")) { tb.clearStackToTableRowContext(); tb.insert(startTag); tb.transition(InCell); tb.insertMarkerToFormattingElements(); } else if (StringUtil.in(name, "caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr")) { return handleMissingTr(t, tb); } else { return anythingElse(t, tb); } } else if (t.isEndTag()) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (name.equals("tr")) { if (!tb.inTableScope(name)) { tb.error(this); // frag return false; } tb.clearStackToTableRowContext(); tb.pop(); // tr tb.transition(InTableBody); } else if (name.equals("table")) { return handleMissingTr(t, tb); } else if (StringUtil.in(name, "tbody", "tfoot", "thead")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } tb.process(new Token.EndTag("tr")); return tb.process(t); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html", "td", "th")) { tb.error(this); return false; } else { return anythingElse(t, tb); } } else { return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, HtmlTreeBuilder tb) { return tb.process(t, InTable); } private boolean handleMissingTr(Token t, TreeBuilder tb) { boolean processed = tb.process(new Token.EndTag("tr")); if (processed) return tb.process(t); else return false; } }, InCell { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isEndTag()) { Token.EndTag endTag = t.asEndTag(); String name = endTag.name(); if (StringUtil.in(name, "td", "th")) { if (!tb.inTableScope(name)) { tb.error(this); tb.transition(InRow); // might not be in scope if empty: <td /> and processing fake end tag return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); tb.transition(InRow); } else if (StringUtil.in(name, "body", "caption", "col", "colgroup", "html")) { tb.error(this); return false; } else if (StringUtil.in(name, "table", "tbody", "tfoot", "thead", "tr")) { if (!tb.inTableScope(name)) { tb.error(this); return false; } closeCell(tb); return tb.process(t); } else { return anythingElse(t, tb); } } else if (t.isStartTag() && StringUtil.in(t.asStartTag().name(), "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr")) { if (!(tb.inTableScope("td") || tb.inTableScope("th"))) { tb.error(this); return false; } closeCell(tb); return tb.process(t); } else { return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, HtmlTreeBuilder tb) { return tb.process(t, InBody); } private void closeCell(HtmlTreeBuilder tb) { if (tb.inTableScope("td")) tb.process(new Token.EndTag("td")); else tb.process(new Token.EndTag("th")); // only here if th or td in scope } }, InSelect { boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case Character: Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else { tb.insert(c); } break; case Comment: tb.insert(t.asComment()); break; case Doctype: tb.error(this); return false; case StartTag: Token.StartTag start = t.asStartTag(); String name = start.name(); if (name.equals("html")) return tb.process(start, InBody); else if (name.equals("option")) { tb.process(new Token.EndTag("option")); tb.insert(start); } else if (name.equals("optgroup")) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); else if (tb.currentElement().nodeName().equals("optgroup")) tb.process(new Token.EndTag("optgroup")); tb.insert(start); } else if (name.equals("select")) { tb.error(this); return tb.process(new Token.EndTag("select")); } else if (StringUtil.in(name, "input", "keygen", "textarea")) { tb.error(this); if (!tb.inSelectScope("select")) return false; // frag tb.process(new Token.EndTag("select")); return tb.process(start); } else if (name.equals("script")) { return tb.process(t, InHead); } else { return anythingElse(t, tb); } break; case EndTag: Token.EndTag end = t.asEndTag(); name = end.name(); if (name.equals("optgroup")) { if (tb.currentElement().nodeName().equals("option") && tb.aboveOnStack(tb.currentElement()) != null && tb.aboveOnStack(tb.currentElement()).nodeName().equals("optgroup")) tb.process(new Token.EndTag("option")); if (tb.currentElement().nodeName().equals("optgroup")) tb.pop(); else tb.error(this); } else if (name.equals("option")) { if (tb.currentElement().nodeName().equals("option")) tb.pop(); else tb.error(this); } else if (name.equals("select")) { if (!tb.inSelectScope(name)) { tb.error(this); return false; } else { tb.popStackToClose(name); tb.resetInsertionMode(); } } else return anythingElse(t, tb); break; case EOF: if (!tb.currentElement().nodeName().equals("html")) tb.error(this); break; default: return anythingElse(t, tb); } return true; } private boolean anythingElse(Token t, HtmlTreeBuilder tb) { tb.error(this); return false; } }, InSelectInTable { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isStartTag() && StringUtil.in(t.asStartTag().name(), "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th")) { tb.error(this); tb.process(new Token.EndTag("select")); return tb.process(t); } else if (t.isEndTag() && StringUtil.in(t.asEndTag().name(), "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th")) { tb.error(this); if (tb.inTableScope(t.asEndTag().name())) { tb.process(new Token.EndTag("select")); return (tb.process(t)); } else return false; } else { return tb.process(t, InSelect); } } }, AfterBody { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { return tb.process(t, InBody); } else if (t.isComment()) { tb.insert(t.asComment()); // into html node } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return tb.process(t, InBody); } else if (t.isEndTag() && t.asEndTag().name().equals("html")) { if (tb.isFragmentParsing()) { tb.error(this); return false; } else { tb.transition(AfterAfterBody); } } else if (t.isEOF()) { // chillax! we're done } else { tb.error(this); tb.transition(InBody); return tb.process(t); } return true; } }, InFrameset { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag()) { Token.StartTag start = t.asStartTag(); String name = start.name(); if (name.equals("html")) { return tb.process(start, InBody); } else if (name.equals("frameset")) { tb.insert(start); } else if (name.equals("frame")) { tb.insertEmpty(start); } else if (name.equals("noframes")) { return tb.process(start, InHead); } else { tb.error(this); return false; } } else if (t.isEndTag() && t.asEndTag().name().equals("frameset")) { if (tb.currentElement().nodeName().equals("html")) { // frag tb.error(this); return false; } else { tb.pop(); if (!tb.isFragmentParsing() && !tb.currentElement().nodeName().equals("frameset")) { tb.transition(AfterFrameset); } } } else if (t.isEOF()) { if (!tb.currentElement().nodeName().equals("html")) { tb.error(this); return true; } } else { tb.error(this); return false; } return true; } }, AfterFrameset { boolean process(Token t, HtmlTreeBuilder tb) { if (isWhitespace(t)) { tb.insert(t.asCharacter()); } else if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype()) { tb.error(this); return false; } else if (t.isStartTag() && t.asStartTag().name().equals("html")) { return tb.process(t, InBody); } else if (t.isEndTag() && t.asEndTag().name().equals("html")) { tb.transition(AfterAfterFrameset); } else if (t.isStartTag() && t.asStartTag().name().equals("noframes")) { return tb.process(t, InHead); } else if (t.isEOF()) { // cool your heels, we're complete } else { tb.error(this); return false; } return true; } }, AfterAfterBody { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype() || isWhitespace(t) || (t.isStartTag() && t.asStartTag().name().equals("html"))) { return tb.process(t, InBody); } else if (t.isEOF()) { // nice work chuck } else { tb.error(this); tb.transition(InBody); return tb.process(t); } return true; } }, AfterAfterFrameset { boolean process(Token t, HtmlTreeBuilder tb) { if (t.isComment()) { tb.insert(t.asComment()); } else if (t.isDoctype() || isWhitespace(t) || (t.isStartTag() && t.asStartTag().name().equals("html"))) { return tb.process(t, InBody); } else if (t.isEOF()) { // nice work chuck } else if (t.isStartTag() && t.asStartTag().name().equals("noframes")) { return tb.process(t, InHead); } else { tb.error(this); return false; } return true; } }, ForeignContent { boolean process(Token t, HtmlTreeBuilder tb) { return true; // todo: implement. Also; how do we get here? } }; private static String nullString = String.valueOf('\u0000'); abstract boolean process(Token t, HtmlTreeBuilder tb); private static boolean isWhitespace(Token t) { if (t.isCharacter()) { String data = t.asCharacter().getData(); // todo: this checks more than spec - "\t", "\n", "\f", "\r", " " for (int i = 0; i < data.length(); i++) { char c = data.charAt(i); if (!StringUtil.isWhitespace(c)) return false; } return true; } return false; } private static void handleRcData(Token.StartTag startTag, HtmlTreeBuilder tb) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.transition(Text); } private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rawtext); tb.markInsertionMode(); tb.transition(Text); } }
[ "justinwm@163.com" ]
justinwm@163.com
1bfb80815a8d9b9e27b390611361ab6016e107fb
9a748394ca359ed081514e25859c0812c1080bbe
/app/src/main/java/com/example/android/sunshine/app/DetailActivity.java
56a0d7d0be47d2bc2b67c402f0707ad3d7d6461f
[]
no_license
gimeno/Sunshine
f9903be177e94745d3821b96ff13b2912fd680fa
8631c0f5b9b99e31bc65b5cc4b41fba3fb46d563
refs/heads/master
2021-01-13T14:09:57.357876
2017-11-07T20:55:31
2017-11-07T20:55:31
76,198,926
0
0
null
2017-11-07T20:52:04
2016-12-11T20:45:46
Java
UTF-8
Java
false
false
4,866
java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.ShareActionProvider; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class DetailActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new DetailFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class DetailFragment extends Fragment { private static final String LOG_TAG = DetailFragment.class.getSimpleName(); private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp"; private String mForecastStr; public DetailFragment() { setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_detail, container, false); Intent intent = getActivity().getIntent(); if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) { mForecastStr = intent.getStringExtra(Intent.EXTRA_TEXT); ((TextView) rootView.findViewById(R.id.text_detail_weather)) .setText(mForecastStr); } return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. inflater.inflate(R.menu.detailfragment, menu); // Retrieve the share menu item MenuItem menuItem = menu.findItem(R.id.action_share); // Get the provider and hold onto it to set/change the share intent. ShareActionProvider mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem); // Attach an intent to this ShareActionProvider. You can update this at any time, // like when the user selects a new piece of data they might like to share. if (mShareActionProvider != null ) { mShareActionProvider.setShareIntent(createShareForecastIntent()); } else { Log.d(LOG_TAG, "Share Action Provider is null?"); } } private Intent createShareForecastIntent() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, mForecastStr + FORECAST_SHARE_HASHTAG); return shareIntent; } } }
[ "r.gimenocallejas@gmail.com" ]
r.gimenocallejas@gmail.com
be07e6b56985b30efdd84b6fb70f8d24cf97d9ad
2d4612391179431f8b6f71e783dd69c0888f8f25
/src/com/interview/SecondWeek/D8_9_6.java
8d7a8898807fb0a956281107b34b250b6f646992
[]
no_license
shinebigfool/interview
93b21945bf0c4feeb9a929257b3854781efe2804
ae69499f9b5fe4d1da30b11d5ed81ca06301ea11
refs/heads/master
2023-01-01T15:59:45.233322
2020-10-26T04:56:42
2020-10-26T04:56:42
282,568,023
0
0
null
null
null
null
UTF-8
Java
false
false
1,134
java
package com.interview.SecondWeek; import java.util.Map; import java.util.Scanner; public class D8_9_6 { public static int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); int n = sc.nextInt(); int k = sc.nextInt(); int[][] map = new int[m][n]; move(0,0,m,n,k,map); System.out.println(count); } public static void move(int x, int y, int m, int n, int k, int[][] map){ if(x==m||y==n){ return; } if(map[x][y]!=0){ return; } if(sum(x,y)<=k){ map[x][y] = 1; count++; move(x+1,y,m,n,k,map); move(x,y+1,m,n,k,map); } } public static int sum(int x ,int y){ String row = String.valueOf(x); String col = String.valueOf(y); int sum = 0; for (int i = 0; i < row.length(); i++) { sum+=row.charAt(i)-'0'; } for (int i = 0; i < col.length(); i++) { sum+=col.charAt(i)-'0'; } return sum; } }
[ "1743751596@qq.com" ]
1743751596@qq.com
5f60f7adb4ef292b120fbcba64254e589271d68d
03250ec88ff1c5a2e6239b230cb24129ce9a9ff6
/algorithms/src/main/java/com/nagarro/algorithms/heap/SlidingWindow.java
4995f6a4b0ff9309e6b36a894a6b703664721161
[]
no_license
jobandosanjh/Algorithms
4c4f9843ea4337d6266226600898b98334c1f70a
af719de9d724867dd1dc893439d2ecbfb85609dc
refs/heads/master
2021-04-29T22:34:02.509005
2019-10-04T03:59:23
2019-10-04T03:59:23
121,640,666
0
0
null
null
null
null
UTF-8
Java
false
false
1,684
java
package com.nagarro.algorithms.heap; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; public final class SlidingWindow { public static void main(final String[] args) { final int window = 5; Arrays.stream(getMax(new int[] { 1, 3, -1, -3, 5, 3, 6, 7 }, window)).forEach(System.out::println); System.out.println("Second"); Arrays.stream(getMaxUsingQueue(new int[] { 1, 3, -1, -3, 5, 3, 6, 7 }, window)).forEach(System.out::println); } private static int[] getMax(final int[] array, final int window) { final int[] maxArray = new int[array.length - (window - 1)]; for (int i = 0; i < array.length - window + 1; i++) { int max = array[i]; for (int j = i; j < i + window; j++) { if (max < array[j]) { max = array[j]; } } maxArray[i] = max; } return maxArray; } private static int[] getMaxUsingQueue(final int[] array, final int window) { final int[] maxArray = new int[array.length - (window - 1)]; final Queue<Integer> queue = new PriorityQueue<>(window, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } }); for (int i = 0; i < array.length - window + 1; i++) { for (int j = i; j < i + window; j++) { queue.offer(array[j]); } maxArray[i] = queue.poll(); queue.clear(); } return maxArray; } }
[ "jobanpreetsingh@jobanpreet3034.Nagarro.local" ]
jobanpreetsingh@jobanpreet3034.Nagarro.local
80d4965cfed72e23067cb4ef621c62685143935f
3d907d1ee8d8c9a8ec3b52b7f1ab9a1bebf4dac0
/class3/src/class3/Record.java
cac31be4ff776b123681f27447bf74d61e82e8b6
[]
no_license
rahulraju2811/Class-and-object-case-study-1
7c7f7efa256818021b6c9b8c0d6b396465cb6897
b8f6fb9db8547d8b6dcd8ddadf2acedaa4f0c38e
refs/heads/master
2020-12-02T05:00:34.333649
2020-01-17T13:38:26
2020-01-17T13:38:26
230,897,468
0
0
null
null
null
null
UTF-8
Java
false
false
1,157
java
package class3; public class Record { byte matchesPlayed; byte numOfWins; byte numOfLosses; float avgLapSpeed; float maxLapSpeed; float avgThrowDistance; float maxThrowDistance; public Record(byte matchesPlayed, byte numOfWins, byte numOfLosses, float avgLapSpeed, float maxLapSpeed, float avgThrowDistance, float maxThrowDistance) { super(); this.matchesPlayed = matchesPlayed; this.numOfWins = numOfWins; this.numOfLosses = numOfLosses; this.avgLapSpeed = avgLapSpeed; this.maxLapSpeed = maxLapSpeed; this.avgThrowDistance = avgThrowDistance; this.maxThrowDistance = maxThrowDistance; } public void display(){ System.out.println("matchesPlayed "+this.matchesPlayed); System.out.println("numOfWins "+this.numOfWins); System.out.println("numOfLosses "+this.numOfLosses); System.out.println("avgLapSpeed "+ this.avgLapSpeed); System.out.println("maxLapSpeed "+this.maxLapSpeed); System.out.println("avgThrowDistance "+this.avgThrowDistance); System.out.println("maxThrowDistance "+this.maxThrowDistance); } }
[ "noreply@github.com" ]
rahulraju2811.noreply@github.com
5d55c1c80b6201f838e25d9f9ab90eb629f1d2f3
26852514163127783354dc42402b1d2564694695
/YoYo-Base/YoYo-Support/src/main/java/com/cnit/yoyo/model/order/RedbeltDetail.java
8d05a189c531ee2d1295a9825e2d0814c56b7694
[]
no_license
magicgis/cnit
2a2a35c1c7f1bb3c8c28c4d75f035343f5ff0c9f
122323f848cb39cfc0d4a94f7ddc395cee0b2dfa
refs/heads/master
2020-12-27T09:35:00.010392
2015-10-28T06:11:42
2015-10-28T06:11:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,401
java
package com.cnit.yoyo.model.order; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import com.cnit.yoyo.dto.BaseQryDTO; public class RedbeltDetail extends BaseQryDTO implements Serializable { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private Long id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.redbelt_id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private Long redbeltId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.member_id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private Long memberId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.user_name * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private String userName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.amount * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private BigDecimal amount; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.status * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private Boolean status; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.create_time * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private Date createTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_redbelt_detail.use_time * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private Date useTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table t_redbelt_detail * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ private static final long serialVersionUID = 1L; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.id * * @return the value of t_redbelt_detail.id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.id * * @param id the value for t_redbelt_detail.id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.redbelt_id * * @return the value of t_redbelt_detail.redbelt_id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public Long getRedbeltId() { return redbeltId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.redbelt_id * * @param redbeltId the value for t_redbelt_detail.redbelt_id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setRedbeltId(Long redbeltId) { this.redbeltId = redbeltId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.member_id * * @return the value of t_redbelt_detail.member_id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public Long getMemberId() { return memberId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.member_id * * @param memberId the value for t_redbelt_detail.member_id * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setMemberId(Long memberId) { this.memberId = memberId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.user_name * * @return the value of t_redbelt_detail.user_name * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public String getUserName() { return userName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.user_name * * @param userName the value for t_redbelt_detail.user_name * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setUserName(String userName) { this.userName = userName; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.amount * * @return the value of t_redbelt_detail.amount * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public BigDecimal getAmount() { return amount; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.amount * * @param amount the value for t_redbelt_detail.amount * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setAmount(BigDecimal amount) { this.amount = amount; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.status * * @return the value of t_redbelt_detail.status * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public Boolean getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.status * * @param status the value for t_redbelt_detail.status * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setStatus(Boolean status) { this.status = status; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.create_time * * @return the value of t_redbelt_detail.create_time * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public Date getCreateTime() { return createTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.create_time * * @param createTime the value for t_redbelt_detail.create_time * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_redbelt_detail.use_time * * @return the value of t_redbelt_detail.use_time * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public Date getUseTime() { return useTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_redbelt_detail.use_time * * @param useTime the value for t_redbelt_detail.use_time * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ public void setUseTime(Date useTime) { this.useTime = useTime; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table t_redbelt_detail * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", redbeltId=").append(redbeltId); sb.append(", memberId=").append(memberId); sb.append(", userName=").append(userName); sb.append(", amount=").append(amount); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", useTime=").append(useTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table t_redbelt_detail * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } RedbeltDetail other = (RedbeltDetail) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getRedbeltId() == null ? other.getRedbeltId() == null : this.getRedbeltId().equals(other.getRedbeltId())) && (this.getMemberId() == null ? other.getMemberId() == null : this.getMemberId().equals(other.getMemberId())) && (this.getUserName() == null ? other.getUserName() == null : this.getUserName().equals(other.getUserName())) && (this.getAmount() == null ? other.getAmount() == null : this.getAmount().equals(other.getAmount())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime())) && (this.getUseTime() == null ? other.getUseTime() == null : this.getUseTime().equals(other.getUseTime())); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table t_redbelt_detail * * @mbggenerated Mon Sep 28 16:08:19 CST 2015 */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getRedbeltId() == null) ? 0 : getRedbeltId().hashCode()); result = prime * result + ((getMemberId() == null) ? 0 : getMemberId().hashCode()); result = prime * result + ((getUserName() == null) ? 0 : getUserName().hashCode()); result = prime * result + ((getAmount() == null) ? 0 : getAmount().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode()); result = prime * result + ((getUseTime() == null) ? 0 : getUseTime().hashCode()); return result; } }
[ "heaven6059@126.com" ]
heaven6059@126.com
d2b7474485323548639a122f69b83a8566c4c94a
57f484bc51709d7debd56c949e4037a5966b6c5b
/client/api/remote/RawData.java
905ae315cb73d6251f64dac8caf878d82c1f7223
[]
no_license
xiangmujbl/adf2
a8c8eb5524b63e3a01fffdf25a45d3bd5e5de53d
cb6a2914633f93ed82cfbe778925e5b904d589c0
refs/heads/master
2020-03-22T17:02:14.618445
2018-10-19T02:05:19
2018-10-19T02:05:19
140,368,043
0
0
null
null
null
null
UTF-8
Java
false
false
443
java
package com.jnj.adf.dataservice.adfcoreignite.client.api.remote; public abstract interface RawData { public abstract Object getKey(); public abstract RawDataValue getValue(); public abstract String getPath(); } /* Location: C:\Users\jliu315\repository\com\jnj\adf\adf-core\0.3.04\adf-core-0.3.04.jar!\com\jnj\adf\client\api\remote\RawData.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
[ "15151326922@163.com" ]
15151326922@163.com
5782be5759ba38cd31beb29855bbe1b2bde871c4
f4b1221cce78d5eeb3f2c8295964086bea63b5a4
/src/main/java/com/example/scacchitps/Pedone.java
6c78cd2132a025505f29f067bea498353e0bfc3a
[]
no_license
AndreCagg/ScacchiNoRule
0cfa3a41e0bb9a672267606348611ffb38c4a863
4b813caa61472734994441c6c14bc62c9495d22d
refs/heads/master
2023-06-30T11:32:17.009701
2021-07-29T10:57:46
2021-07-29T10:57:46
390,692,269
1
0
null
null
null
null
UTF-8
Java
false
false
327
java
package com.example.scacchitps; public class Pedone extends Pezzo implements Punteggio { public Pedone(Integer x, String colore, Character y) { super(x, colore, y, "Pedone" + colore.substring(0, 1), PEDONE); } @Override public String toString() { return "Pedone{" + super.toString(); } }
[ "caggi@LAPTOP-Andrea.station" ]
caggi@LAPTOP-Andrea.station
98ca25488668e1714b52093722bd73fcb07033b3
da120cef61665cad2a1f4e7d4e4094dac6daf14d
/src/USBANK.java
6fe9ebf3a17e1772eadfb50f4bbd162e1484bd73
[]
no_license
Saurabh-hub-tech/JavaPractice
8020789b0e262b3500ac5852f616117f99de3559
02491b7b49d15f02946a32bdfa897c4b6cc9b53a
refs/heads/master
2022-08-31T06:23:11.502961
2020-05-27T12:17:27
2020-05-27T12:17:27
267,305,505
0
0
null
null
null
null
UTF-8
Java
false
false
113
java
public interface USBANK { public void credit(); public void debit(); public void withdrawal(); }
[ "RAKSHA@RAKSHA-BT" ]
RAKSHA@RAKSHA-BT
f2a3727c9636c43d67f2c950ddbbbaf07214f6be
8df9f2c20a2710cb0f34dc09498a283cd31865cc
/src/day56_abstraction/drivable/SelfDrivable.java
01a9483942ff6f70edbb74464c54821dde8d99fb
[]
no_license
tambi09/java-programmimg
c870412a8e8ab072ed486dd0f7d515d6f6ed3dff
152cc8563f32afb263715ead7628b479599dbd4b
refs/heads/master
2023-06-23T23:48:56.581838
2021-07-07T03:59:56
2021-07-07T03:59:56
373,378,550
0
0
null
null
null
null
UTF-8
Java
false
false
98
java
package day56_abstraction.drivable; public interface SelfDrivable { void autoPiloting (); }
[ "ritylya09@gmail.com" ]
ritylya09@gmail.com
c0d7aa735ca8d67e340f4ef326624f0cc76228a1
ded0659122dbc4a5463fbb66a7327136eef54b68
/Codeforces/Codeforces_round_306_div_2_TwoSubstrings.java
55d14cb40a202ea6102facb8bb384752c5f43f14
[]
no_license
alvin319/competitive-programming
7eea6aa3d6162aa6afdf57978bd3769757242ed4
2ca6fd60a0cdd08d77a05c76eed67cc37c45c8ae
refs/heads/master
2021-01-24T10:47:57.648721
2019-12-20T06:36:37
2019-12-20T06:36:37
40,688,685
0
2
null
2017-06-13T06:29:22
2015-08-14T00:59:45
Java
UTF-8
Java
false
false
3,666
java
import java.io.*; import java.util.LinkedList; import java.util.StringTokenizer; /** * Created by WiNDWAY on 5/26/16. */ public class Codeforces_round_306_div_2_TwoSubstrings { public static void main(String[] args) { FScanner input = new FScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); String current = input.nextLine(); LinkedList<Pair> abList = new LinkedList<>(); LinkedList<Pair> baList = new LinkedList<>(); for (int i = 0; i < current.length(); i++) { char now = current.charAt(i); char prev = (i - 1) >= 0 ? current.charAt(i - 1) : 'a'; char next = (i + 1) < current.length() ? current.charAt(i + 1) : 'a'; if (now == 'A') { if (prev != 'a' && prev == 'B') { baList.add(new Pair(i - 1, i)); } if (next != 'a' && next == 'B') { abList.add(new Pair(i, i + 1)); } } else if (now == 'B') { if (prev != 'a' && prev == 'A') { abList.add(new Pair(i - 1, i)); } if (next != 'a' && next == 'A') { baList.add(new Pair(i, i + 1)); } } } if (!abList.isEmpty() && !baList.isEmpty()) { Pair ab = abList.getFirst(); Pair ba = baList.getLast(); Pair abLast = abList.getLast(); Pair baFirst = baList.getFirst(); if (ab.start != ba.start && ab.start != ba.end && ab.end != ba.end && ab.end != ba.start) { out.println("YES"); System.exit(0); } else if (abLast.start != ba.start && abLast.start != ba.end && abLast.end != ba.start && abLast.end != ba.end) { out.println("YES"); System.exit(0); } else if (abLast.start != baFirst.start && abLast.start != baFirst.end && abLast.end != baFirst.start && abLast.end != baFirst.end) { out.println("YES"); System.exit(0); } else if (ab.start != baFirst.start && ab.start != baFirst.end && ab.end != baFirst.start && ab.end != baFirst.end) { out.println("YES"); System.exit(0); } } out.println("NO"); out.close(); } static class Pair { int start; int end; public Pair (int start, int end) { this.start = start; this.end = end; } } public static PrintWriter out; public static class FScanner { BufferedReader br; StringTokenizer st; public FScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } private String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
[ "qdeng@apple.com" ]
qdeng@apple.com
f36f2dd46e81813f405cadf4a9efe0a74b938512
4be72dee04ebb3f70d6e342aeb01467e7e8b3129
/bin/ext-template/yacceleratorcore/src/de/hybris/platform/yacceleratorcore/suggestion/dao/impl/DefaultSimpleSuggestionDao.java
b9e16345c15e0c1dc0e250db3c5fc0becda1b7c3
[]
no_license
lun130220/hybris
da00774767ba6246d04cdcbc49d87f0f4b0b1b26
03c074ea76779f96f2db7efcdaa0b0538d1ce917
refs/heads/master
2021-05-14T01:48:42.351698
2018-01-07T07:21:53
2018-01-07T07:21:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,707
java
/* * [y] hybris Platform * * Copyright (c) 2000-2015 hybris AG * All rights reserved. * * This software is the confidential and proprietary information of hybris * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with hybris. * * */ package de.hybris.platform.yacceleratorcore.suggestion.dao.impl; import de.hybris.platform.catalog.enums.ProductReferenceTypeEnum; import de.hybris.platform.category.model.CategoryModel; import de.hybris.platform.core.model.product.ProductModel; import de.hybris.platform.core.model.user.UserModel; import de.hybris.platform.servicelayer.internal.dao.AbstractItemDao; import de.hybris.platform.servicelayer.search.FlexibleSearchQuery; import de.hybris.platform.servicelayer.search.SearchResult; import de.hybris.platform.yacceleratorcore.suggestion.dao.SimpleSuggestionDao; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.springframework.util.Assert; /** * Default implementation of {@link SimpleSuggestionDao}. * * Finds products that are related products that the user has bought. */ public class DefaultSimpleSuggestionDao extends AbstractItemDao implements SimpleSuggestionDao { private static final int DEFAULT_LIMIT = 100; private static final String REF_QUERY_PARAM_CATEGORY = "category"; private static final String REF_QUERY_PARAM_PRODUCTS = "products"; private static final String REF_QUERY_PARAM_USER = "user"; private static final String REF_QUERY_PARAM_TYPE = "referenceType"; private static final String REF_QUERY_PARAM_TYPES = "referenceTypes"; private static final String REF_QUERY_CATEGORY_START = "SELECT {p.PK}" + " FROM {Product AS p" + " LEFT JOIN ProductReference AS r ON {p.PK}={r.target}" + " LEFT JOIN OrderEntry AS e ON {r.source}={e.product}" + " LEFT JOIN Order AS o ON {e.order}={o.PK}" + " LEFT JOIN CategoryProductRelation AS c2p ON {r.source}={c2p.target}" + " LEFT JOIN Category AS c ON {c2p.source}={c.PK} }" + " WHERE {o.user}=?user AND {c.PK}=?category"; private static final String REF_QUERY_PRODUCT_START = "SELECT DISTINCT {p.PK}, COUNT({p.PK}) AS NUM" + " FROM {Product AS p" + " LEFT JOIN ProductReference AS r ON {p.PK}={r.target} }" + " WHERE {r.source} IN (?products) AND {r.target} NOT IN (?products)"; private static final String REF_QUERY_TYPE = " AND {r.referenceType} IN (?referenceType)"; private static final String REF_QUERY_TYPES = " AND {r.referenceType} IN (?referenceTypes)"; private static final String REF_QUERY_SUB = " AND NOT EXISTS ({{" + " SELECT 1 FROM {OrderEntry AS e2 LEFT JOIN Order AS o2 ON {e2.order}={o2.PK} } " + " WHERE {e2.product}={r.target} AND {o2.user}=?user }})"; private static final String REF_QUERY_CATEGORY_ORDER = " ORDER BY {o.creationTime} DESC"; private static final String REF_QUERY_PRODUCT_GROUP = " GROUP BY {p.PK}"; private static final String REF_QUERY_PRODUCT_ORDER = " ORDER BY NUM DESC"; @Override public List<ProductModel> findProductsRelatedToPurchasedProductsByCategory(final CategoryModel category, final List<ProductReferenceTypeEnum> referenceTypes, final UserModel user, final boolean excludePurchased, final Integer limit) { Assert.notNull(category); Assert.notNull(user); final int maxResultCount = limit == null ? DEFAULT_LIMIT : limit.intValue(); final Map<String, Object> params = new HashMap<String, Object>(); final StringBuilder builder = new StringBuilder(REF_QUERY_CATEGORY_START); if (excludePurchased) { builder.append(REF_QUERY_SUB); } if (CollectionUtils.isNotEmpty(referenceTypes)) { builder.append(REF_QUERY_TYPES); params.put(REF_QUERY_PARAM_TYPES, referenceTypes); } builder.append(REF_QUERY_CATEGORY_ORDER); params.put(REF_QUERY_PARAM_USER, user); params.put(REF_QUERY_PARAM_CATEGORY, category); final FlexibleSearchQuery query = new FlexibleSearchQuery(builder.toString()); query.addQueryParameters(params); query.setNeedTotal(false); query.setCount(maxResultCount); final SearchResult<ProductModel> result = getFlexibleSearchService().search(query); return result.getResult(); } @Override public List<ProductModel> findProductsRelatedToProducts(final List<ProductModel> products, final List<ProductReferenceTypeEnum> referenceTypes, final UserModel user, final boolean excludePurchased, final Integer limit) { Assert.notNull(products); Assert.notNull(user); final int maxResultCount = limit == null ? DEFAULT_LIMIT : limit.intValue(); final Map<String, Object> params = new HashMap<String, Object>(); final StringBuilder builder = new StringBuilder(REF_QUERY_PRODUCT_START); if (excludePurchased) { builder.append(REF_QUERY_SUB); } if (CollectionUtils.isNotEmpty(referenceTypes)) { builder.append(REF_QUERY_TYPES); params.put(REF_QUERY_PARAM_TYPES, referenceTypes); } builder.append(REF_QUERY_PRODUCT_GROUP); builder.append(REF_QUERY_PRODUCT_ORDER); params.put(REF_QUERY_PARAM_USER, user); params.put(REF_QUERY_PARAM_PRODUCTS, products); final FlexibleSearchQuery query = new FlexibleSearchQuery(builder.toString()); query.addQueryParameters(params); query.setNeedTotal(false); query.setCount(maxResultCount); final SearchResult<ProductModel> result = getFlexibleSearchService().search(query); return result.getResult(); } @SuppressWarnings("deprecation") @Deprecated @Override public List<ProductModel> findProductsRelatedToPurchasedProductsByCategory(final CategoryModel category, final UserModel user, final ProductReferenceTypeEnum referenceType, final boolean excludePurchased, final Integer limit) { Assert.notNull(category); Assert.notNull(user); final int maxResultCount = limit == null ? DEFAULT_LIMIT : limit.intValue(); final Map<String, Object> params = new HashMap<String, Object>(); final StringBuilder builder = new StringBuilder(REF_QUERY_CATEGORY_START); if (excludePurchased) { builder.append(REF_QUERY_SUB); } if (referenceType != null) { builder.append(REF_QUERY_TYPE); params.put(REF_QUERY_PARAM_TYPE, referenceType); } builder.append(REF_QUERY_CATEGORY_ORDER); params.put(REF_QUERY_PARAM_USER, user); params.put(REF_QUERY_PARAM_CATEGORY, category); final FlexibleSearchQuery query = new FlexibleSearchQuery(builder.toString()); query.addQueryParameters(params); query.setNeedTotal(false); query.setCount(maxResultCount); final SearchResult<ProductModel> result = getFlexibleSearchService().search(query); return result.getResult(); } }
[ "lun130220@gamil.com" ]
lun130220@gamil.com
69d50806b2e1e270ab84b48bfc06fbc6be4d0e63
7e909bffcf744312c1cc2e9a441c9fae8798120c
/src/main/java/com/github/udanton/demorecipebook/repositories/UnitOfMeasureRepository.java
8196bab5e00023d58b572efa0c1d5dbfb246b82d
[]
no_license
UDAnton/demo-recipe-book
c2b0f3730d3b6c92d39828558c49066a4a861d8b
da47d925d612dfb55d2598d3edc1cad19dc664ad
refs/heads/master
2020-04-11T00:46:35.917140
2019-01-03T22:38:22
2019-01-03T22:38:22
161,395,417
0
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.github.udanton.demorecipebook.repositories; import com.github.udanton.demorecipebook.domain.UnitOfMeasure; import org.springframework.data.repository.CrudRepository; import java.util.Optional; public interface UnitOfMeasureRepository extends CrudRepository<UnitOfMeasure, Long> { Optional<UnitOfMeasure> findByDescription(String description); }
[ "uadjob@gmail.com" ]
uadjob@gmail.com
e0440def52f7ed728f7f377a521becbc65368bb4
3073e941609cec746c0e6b37f06e56af707a1aff
/ViewLib/src/main/java/com/radaee/pdf/Matrix.java
9e50fd70685c6479e6034fa326959a3c02621b92
[]
no_license
AntonGerasimenko/InkCrash
06ff18d8c4af0259fcbb06221a40dba44093d84c
6b21a7ea0369bc2242a4faaa2c83d42769d7a541
refs/heads/master
2021-01-13T00:53:25.172971
2015-11-05T11:21:08
2015-11-05T11:21:08
45,527,092
1
0
null
null
null
null
UTF-8
Java
false
false
2,822
java
package com.radaee.pdf; /** class for PDF Matrix. @author Radaee @version 1.1 */ public class Matrix { protected long hand = 0; private static native long create( float xx, float yx, float xy, float yy, float x0, float y0 ); private static native long createScale( float sx, float sy, float x0, float y0 ); private static native void invert( long matrix ); private static native void transformPath( long matrix, long path ); private static native void transformInk( long matrix, long ink ); private static native void transformRect( long matrix, float[] rect ); private static native void transformPoint( long matrix, float[] point ); private static native void destroy( long matrix ); /** * constructor for full values.<br/> * transform formula like:<br/> * new_x = (xx * x + xy * y) + x0;<br/> * new_y = (yx * x + yy * y) + y0;<br/> * for composed with rotate and scale, values like:<br/> * xx = scalex * cos(a);<br/> * yx = scaley * sin(a);<br/> * xy = scalex * sin(-a);<br/> * yy = scaley * cos(-a);<br/> * where a is rotate angle in radian.<br/> * @param xx * @param yx * @param xy * @param yy * @param x0 offset add to x * @param y0 offset add to y */ public Matrix( float xx, float yx, float xy, float yy, float x0, float y0 ) { hand = create( xx, yx, xy, yy, x0, y0 ); } /** * constructor for scaled values.<br/> * xx = sx;<br/> * yx = 0;<br/> * xy = 0;<br/> * yx = sy;<br/> * transform formula like:<br/> * new_x = (sx * x) + x0;<br/> * new_y = (sy * y) + y0;<br/> * because PDF using math coordinate system. (0,0) at left-bottom<br/> * and Bitmap is in screen coordinate. (0,0) at left-top<br/> * so, Matrix need to map y as inverted. and matrix mostly like:<br/> * sx = scale, sy = -scale, x0 = 0, y0 = scale * page_height<br/> * where page_height getting from Document.GetPageHeight(pageNo); * @param sx * @param sy * @param x0 offset add to x * @param y0 offset add to y */ public Matrix( float sx, float sy, float x0, float y0 ) { hand = createScale( sx, sy, x0, y0 ); } public final void Invert() { invert( hand ); } public final void TransformPath( Path path ) { if(path == null) return; transformPath( hand, path.m_hand ); } public final void TransformInk( Ink ink ) { if(ink == null) return; transformInk( hand, ink.hand ); } public final void TransformRect( float[] rect ) { transformRect( hand, rect ); } public final void TransformPoint( float[] point ) { transformPoint( hand, point ); } /** * destroy and free memory. */ public final void Destroy() { destroy( hand ); hand = 0; } @Override protected void finalize() throws Throwable { Destroy(); super.finalize(); } }
[ "dubrava123@gmail.com" ]
dubrava123@gmail.com
0398d469ea75618f6e5ec3227b3b735f9c4f2d5b
e0e761f926082c1747e5d33a8958edeb5471cb93
/src/main/java/lesson7/Fitness.java
569c64c95c2a9d21d31fb8c1d19046d582fdbb5a
[]
no_license
Amina1000/AndroidJavaCore
e64e9e8baedf0123214e55664afdc722ee8a5fbd
e7c989041f9ca676b25e600aafe44ec35c5a8b93
refs/heads/master
2023-04-13T05:50:07.176130
2021-04-22T23:06:37
2021-04-22T23:06:37
342,344,640
0
0
null
2021-04-22T23:06:37
2021-02-25T18:43:15
Java
UTF-8
Java
false
false
205
java
package lesson7; /** * homework lesson7 * * @author Amina * 24.03.2021 */ public interface Fitness { void run(int length); void jump(int height); boolean isDistance(); void info(); }
[ "amina1000@yandex.ru" ]
amina1000@yandex.ru
ab296268a44cee0b64d603a1b9cd1f991ea16923
6c9616b2a0e0f6c9943eacd73046a18ad6b0b3f1
/MobLink-Demo/src/com/mob/moblink/demo/util/QRcodeUtils.java
0cf67103b897caf8312841b89c69c85d392bbbdc
[]
no_license
zhangmingrong/MobLink-for-Android
fd448bc36cd64a30628b03706894940e2df669b3
052443ff142f17b3efe372508716df493362be3e
refs/heads/master
2020-05-23T20:12:47.716314
2019-02-27T09:11:12
2019-02-27T09:11:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,863
java
package com.mob.moblink.demo.util; import android.graphics.Bitmap; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import java.util.EnumMap; import java.util.Map; public class QRcodeUtils { private static final int WHITE = 0xFFFFFFFF; private static final int BLACK = 0xFF000000; public static Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException { String contentsToEncode = contents; if (contentsToEncode == null) { return null; } Map<EncodeHintType, Object> hints = null; String encoding = guessAppropriateEncoding(contentsToEncode); if (encoding != null) { hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, encoding); } MultiFormatWriter writer = new MultiFormatWriter(); BitMatrix result; try { result = writer.encode(contentsToEncode, format, img_width, img_height, hints); } catch (IllegalArgumentException iae) { // Unsupported format return null; } int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } private static String guessAppropriateEncoding(CharSequence contents) { // Very crude at the moment for (int i = 0; i < contents.length(); i++) { if (contents.charAt(i) > 0xFF) { return "UTF-8"; } } return null; } }
[ "litl@UPC1561.uz.local" ]
litl@UPC1561.uz.local
2a95e73d28e65cfddaa1a35b876d7e9b9360374b
f194f61b74ef094f90241929bf37df83cbac0f3b
/src/main/java/io/github/mac_genius/pgen/arguments/ArgumentBuilder.java
ca5536c8f6bcfd6ebf4fe725c79b302f40d900aa
[]
no_license
Mac-Genius/ProjectGenerator
2c1d46f7c4c6b35e36db2d361c228bebe48ada99
91ed3778888e1228fa6b71d550235753a20ff1ae
refs/heads/master
2021-01-11T02:45:29.442717
2016-10-15T02:33:55
2016-10-15T02:33:55
70,932,259
0
0
null
null
null
null
UTF-8
Java
false
false
2,791
java
package io.github.mac_genius.pgen.arguments; import io.github.mac_genius.pgen.FileTemplate; import io.github.mac_genius.pgen.RunMode; /** * Builds an Arguments class from command line arguments. * * @author John Harrison */ public class ArgumentBuilder { private RunMode mode; private int exampleSize; private String fileName; private FileTemplate template; private boolean exampleSizeManual = false; /** * Returns the mode in which to run the generator. * * @return the mode for the generator */ public RunMode getMode() { return mode; } /** * Returns the amount of example input test cases to generate. * * @return the amount of example input test cases to generate */ public int getExampleSize() { return exampleSize; } /** * Returns the name of the project. * * @return a String containing the name of the project */ public String getFileName() { return fileName; } /** * The template to use for the generator. * * @return the template for the generator */ public FileTemplate getFileTemplate() { return template; } /** * Sets the mode for the project generator. * * @param mode - the mode to run the generator in (local, kattis, etc.) * @return the builder */ public ArgumentBuilder setMode(RunMode mode) { this.mode = mode; return this; } /** * Sets the amount of example input cases to generate. * * @param exampleSize - the amount of example input cases to generate * @return the builder */ public ArgumentBuilder setExampleSize(int exampleSize) { this.exampleSize = exampleSize; exampleSizeManual = true; return this; } /** * Sets the name of the project. * * @param fileName - the name of the project * @return the builder */ public ArgumentBuilder setFileName(String fileName) { this.fileName = fileName; return this; } /** * Sets the type of template to use. * * @param template - the template to use * @return the builder */ public ArgumentBuilder setFileTemplate(FileTemplate template) { this.template = template; return this; } /** * Returns whether the example size was set manually or not. * * @return true if the example size was set manually, else false */ public boolean isExampleSizeSetManual() { return exampleSizeManual; } /** * Builds the Arguments. * * @return the arguments */ public Arguments build() { return new Arguments(mode, exampleSize, fileName, template); } }
[ "jwh0051@auburn.edu" ]
jwh0051@auburn.edu
54bef1074cc4d1c7500dea19c864c4a8fca371fd
e977c424543422f49a25695665eb85bfc0700784
/benchmark/icse15/504234/buggy-version/db/derby/code/trunk/java/engine/org/apache/derby/impl/jdbc/EmbedDatabaseMetaData.java
dac83ebb488809755f9d136afe3c51abdc2509cc
[]
no_license
amir9979/pattern-detector-experiment
17fcb8934cef379fb96002450d11fac62e002dd3
db67691e536e1550245e76d7d1c8dced181df496
refs/heads/master
2022-02-18T10:24:32.235975
2019-09-13T15:42:55
2019-09-13T15:42:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
119,819
java
/* Derby - Class org.apache.derby.impl.jdbc.EmbedDatabaseMetaData Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.impl.jdbc; import org.apache.derby.iapi.services.info.ProductVersionHolder; import org.apache.derby.iapi.services.monitor.Monitor; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; import org.apache.derby.iapi.sql.dictionary.DataDictionary; import org.apache.derby.iapi.sql.dictionary.SPSDescriptor; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.impl.sql.execute.GenericConstantActionFactory; import org.apache.derby.impl.sql.execute.GenericExecutionFactory; import org.apache.derby.iapi.reference.Limits; import org.apache.derby.iapi.reference.JDBC20Translation; import org.apache.derby.iapi.reference.JDBC30Translation; import java.util.Properties; import java.sql.DatabaseMetaData; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.Types; import java.io.IOException; import java.io.InputStream; /** * This class provides information about the database as a whole. * * <P>Many of the methods here return lists of information in ResultSets. * You can use the normal ResultSet methods such as getString and getInt * to retrieve the data from these ResultSets. If a given form of * metadata is not available, these methods should throw a SQLException. * * <P>Some of these methods take arguments that are String patterns. These * arguments all have names such as fooPattern. Within a pattern String, "%" * means match any substring of 0 or more characters, and "_" means match * any one character. Only metadata entries matching the search pattern * are returned. If a search pattern argument is set to a null ref, it means * that argument's criteria should be dropped from the search. * * <P>A SQLException will be thrown if a driver does not support a meta * data method. In the case of methods that return a ResultSet, * either a ResultSet (which may be empty) is returned or a * SQLException is thrown. * <p> * This implementation gets instructions from the Database for how to satisfy * most requests for information. Each instruction is either a simple string * containing the desired information, or the text of a query that may be * executed on the database connection to gather the information. We get the * instructions via an "InstructionReader," which requires the database * Connection for initialization. * <p> * Those few pieces of metadata that are related to the driver, rather than the * database, come from a separate InstructionReader. Note that in that case it * probably doesn't make sense to allow an instruction to specify a query. * * @see <a href="http://java.sun.com/products/jdbc/download.html#corespec30">JDBC 3.0 Specification</a> * @author ames */ public class EmbedDatabaseMetaData extends ConnectionChild implements DatabaseMetaData, java.security.PrivilegedAction { /* ** Property and values related to using ** stored prepared statements for metatdata. */ private final String url; /* ** Set to true if metadata is off */ private GenericConstantActionFactory constantActionFactory; ////////////////////////////////////////////////////////////// // // CONSTRUCTORS // ////////////////////////////////////////////////////////////// /** @exception SQLException on error */ public EmbedDatabaseMetaData (EmbedConnection connection, String url) throws SQLException { super(connection); this.url = url; } /** Cached query descriptions from metadata.properties. */ private static Properties queryDescriptions; /** Cached query descriptions from metadata_net.properties. */ private static Properties queryDescriptions_net; /** * Return all queries found in either metadata.properties or * metadata_net.properties. * * @param net if <code>true</code>, read metadata_net.properties; * otherwise, read metadata.properties. * @return a <code>Properties</code> value with the queries */ private Properties getQueryDescriptions(boolean net) { Properties p = net ? queryDescriptions_net : queryDescriptions; if (p != null) { return p; } loadQueryDescriptions(); return net ? queryDescriptions_net : queryDescriptions; } /** * Read the query descriptions from metadata.properties and * metadata_net.properties. This method must be invoked from * within a privileged block. */ private void PBloadQueryDescriptions() { String[] files = { "metadata.properties", "/org/apache/derby/impl/sql/catalog/metadata_net.properties" }; Properties[] props = new Properties[files.length]; for (int i = 0; i < files.length; ++i) { try { props[i] = new Properties(); // SECURITY PERMISSION - IP3 InputStream is = getClass().getResourceAsStream(files[i]); props[i].load(is); is.close(); } catch (IOException ioe) { if (SanityManager.DEBUG) { SanityManager.THROWASSERT("Error reading " + files[i], ioe); } } } queryDescriptions = props[0]; queryDescriptions_net = props[1]; } ////////////////////////////////////////////////////////////// // // DatabaseMetaData interface // ////////////////////////////////////////////////////////////// //---------------------------------------------------------------------- // First, a variety of minor information about the target database. /** * Can all the procedures returned by getProcedures be called by the * current user? * * @return true if so */ public boolean allProceduresAreCallable() { return true; } /** * Can all the tables returned by getTable be SELECTed by the * current user? * * @return true if so */ public boolean allTablesAreSelectable() { return true; } /** * What's the url for this database? * * @return the url or null if it can't be generated */ public final String getURL() { if (url == null) return url; int attributeStart = url.indexOf(';'); if (attributeStart == -1) return url; else return url.substring(0,attributeStart); } /** * What's our user name as known to the database? * * @return our database user name */ public String getUserName() { return (getEmbedConnection().getTR().getUserName()); } /** * Is the database in read-only mode? * * @return true if so */ public boolean isReadOnly() { return getLanguageConnectionContext().getDatabase().isReadOnly(); } /** * Are NULL values sorted high? * * @return true if so */ public boolean nullsAreSortedHigh() { return true; } /** * Are NULL values sorted low? * * @return true if so */ public boolean nullsAreSortedLow() { return false; } /** * Are NULL values sorted at the start regardless of sort order? * * @return true if so */ public boolean nullsAreSortedAtStart() { return false; } /** * Are NULL values sorted at the end regardless of sort order? * * @return true if so */ public boolean nullsAreSortedAtEnd() { return false; } /** * What's the name of this database product? * * @return database product name */ public String getDatabaseProductName() { return Monitor.getMonitor().getEngineVersion().getProductName(); } /** * What's the version of this database product? * * @return database version */ public String getDatabaseProductVersion() { ProductVersionHolder myPVH = Monitor.getMonitor().getEngineVersion(); return myPVH.getVersionBuildString(true); } /** * What's the name of this JDBC driver? * * @return JDBC driver name */ public String getDriverName() { return "Apache Derby Embedded JDBC Driver"; } /** * What's the version of this JDBC driver? * * @return JDBC driver version */ public String getDriverVersion() { return getDatabaseProductVersion(); } /** * What's this JDBC driver's major version number? * * @return JDBC driver major version */ public int getDriverMajorVersion() { return getEmbedConnection().getLocalDriver().getMajorVersion(); } /** * What's this JDBC driver's minor version number? * * @return JDBC driver minor version number */ public int getDriverMinorVersion() { return getEmbedConnection().getLocalDriver().getMinorVersion(); } /** * Does the database store tables in a local file? * * @return true if so */ public boolean usesLocalFiles() { return true; } /** * Does the database use a file for each table? * * @return true if the database uses a local file for each table */ public boolean usesLocalFilePerTable() { return true; } /** * Does the database treat mixed case unquoted SQL identifiers as * case sensitive and as a result store them in mixed case? * * A JDBC-Compliant driver will always return false. * * @return true if so */ public boolean supportsMixedCaseIdentifiers() { return false; } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in upper case? * * @return true if so */ public boolean storesUpperCaseIdentifiers() { return true; } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in lower case? * * @return true if so */ public boolean storesLowerCaseIdentifiers() { return false; } /** * Does the database treat mixed case unquoted SQL identifiers as * case insensitive and store them in mixed case? * * @return true if so */ public boolean storesMixedCaseIdentifiers() { return false; } /** * Does the database treat mixed case quoted SQL identifiers as * case sensitive and as a result store them in mixed case? * * A JDBC-Compliant driver will always return true. * * @return true if so */ public boolean supportsMixedCaseQuotedIdentifiers() { return true; } /** * Does the database treat mixed case quoted SQL identifiers as * case insensitive and store them in upper case? * * @return true if so */ public boolean storesUpperCaseQuotedIdentifiers() { return false; } /** * Does the database treat mixed case quoted SQL identifiers as * case insensitive and store them in lower case? * * @return true if so */ public boolean storesLowerCaseQuotedIdentifiers() { return false; } /** * Does the database treat mixed case quoted SQL identifiers as * case insensitive and store them in mixed case? * * @return true if so */ public boolean storesMixedCaseQuotedIdentifiers() { return true; } /** * What's the string used to quote SQL identifiers? * This returns a space " " if identifier quoting isn't supported. * * A JDBC-Compliant driver always uses a double quote character. * * @return the quoting string */ public String getIdentifierQuoteString() { return "\""; } /** * Get a comma separated list of all a database's SQL keywords * that are NOT also SQL92 keywords. includes reserved and non-reserved keywords. * @return the list */ public String getSQLKeywords() { return "ALIAS,BIGINT,BOOLEAN,CALL,CLASS,COPY,DB2J_DEBUG,EXECUTE,EXPLAIN,FILE,FILTER," + "GETCURRENTCONNECTION,INDEX,INSTANCEOF,METHOD,NEW,OFF,PROPERTIES,PUBLICATION,RECOMPILE," + "REFRESH,RENAME,RUNTIMESTATISTICS,STATEMENT,STATISTICS,TIMING,WAIT"; } /** * Get a comma separated list of JDBC escaped numeric functions. * Must be a complete or sub set of functions in appendix C.1 * of JDBC 3.0 specification (pp. 183). * @return the list */ public String getNumericFunctions() { return "ABS,ACOS,ASIN,ATAN,CEILING,COS,COT,DEGREES,EXP,FLOOR,LOG,LOG10,MOD,PI,RADIANS,RAND,SIGN,SIN,SQRT,TAN"; } /** * Get a comma separated list of JDBC escaped string functions. * Must be a complete or sub set of functions in appendix C.2 * of JDBC 3.0 specification (pp. 184). * @return the list */ public String getStringFunctions() { return "CONCAT,LENGTH,LCASE,LOCATE,LTRIM,RTRIM,SUBSTRING,UCASE"; } /** * Get a comma separated list of JDBC escaped system functions. * Must be a complete or sub set of functions in appendix C.4 * of JDBC 3.0 specification (pp. 185). * @return the list */ public String getSystemFunctions() { return "USER"; } /** * Get a comma separated list of JDBC escaped time date functions. * Must be a complete or sub set of functions in appendix C.3 * of JDBC 3.0 specification. * @return the list */ public String getTimeDateFunctions() { return "CURDATE,CURTIME,HOUR,MINUTE,MONTH,SECOND,TIMESTAMPADD,TIMESTAMPDIFF,YEAR"; } /** * This is the string that can be used to escape '_' or '%' in * the string pattern style catalog search parameters. we have no default escape value, so = is the end of the next line * <P>The '_' character represents any single character. * <P>The '%' character represents any sequence of zero or * more characters. * @return the string used to escape wildcard characters */ public String getSearchStringEscape() { return ""; } /** * Get all the "extra" characters that can be used in unquoted * identifier names (those beyond a-z, A-Z, 0-9 and _). * * @return the string containing the extra characters */ public String getExtraNameCharacters() { return ""; } //-------------------------------------------------------------------- // Functions describing which features are supported. /** * Is "ALTER TABLE" with add column supported? * * @return true if so */ public boolean supportsAlterTableWithAddColumn() { return true; } /** * Is "ALTER TABLE" with drop column supported? * * @return true if so */ public boolean supportsAlterTableWithDropColumn() { return true; } /** * Is column aliasing supported? * * <P>If so, the SQL AS clause can be used to provide names for * computed columns or to provide alias names for columns as * required. * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsColumnAliasing() { return true; } /** * Are concatenations between NULL and non-NULL values NULL? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean nullPlusNonNullIsNull() { return true; } /** * Is the CONVERT function between SQL types supported? * * @return true if so */ public boolean supportsConvert() { return true; } /** * Is CONVERT between the given SQL types supported? * * @param fromType the type to convert from * @param toType the type to convert to * @return true if so * @see Types */ public boolean supportsConvert(int fromType, int toType) { /* * at the moment we don't support CONVERT at all, so we take the easy * way out. Eventually we need to figure out how to handle this * cleanly. */ return false; } /** * Are table correlation names supported? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsTableCorrelationNames() { return true; } /** * If table correlation names are supported, are they restricted * to be different from the names of the tables? * * @return true if so */ public boolean supportsDifferentTableCorrelationNames() { return true; } /** * Are expressions in "ORDER BY" lists supported? * * @return true if so */ public boolean supportsExpressionsInOrderBy() { /* DERBY - 2244 : Derby does support Order By Expression (Derby-134) * thus changing the return value to true to relfect that the support * is present */ return true; } /** * Can an "ORDER BY" clause use columns not in the SELECT? * * @return true if so */ public boolean supportsOrderByUnrelated() { return false; } /** * Is some form of "GROUP BY" clause supported? * * @return true if so */ public boolean supportsGroupBy() { return true; } /** * Can a "GROUP BY" clause use columns not in the SELECT? * * @return true if so */ public boolean supportsGroupByUnrelated() { return true; } /** * Can a "GROUP BY" clause add columns not in the SELECT * provided it specifies all the columns in the SELECT? * * @return true if so */ public boolean supportsGroupByBeyondSelect() { return true; } /** * Is the escape character in "LIKE" clauses supported? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsLikeEscapeClause() { return true; } /** * Are multiple ResultSets from a single execute supported? * * @return true if so */ public boolean supportsMultipleResultSets() { return true; } /** * Can we have multiple transactions open at once (on different * connections)? * * @return true if so */ public boolean supportsMultipleTransactions() { return true; } /** * Can columns be defined as non-nullable? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsNonNullableColumns() { return true; } /** * Is the ODBC Minimum SQL grammar supported? * * All JDBC-Compliant drivers must return true. * * @return true if so */ public boolean supportsMinimumSQLGrammar() { return true; } /** * Is the ODBC Core SQL grammar supported? * * @return true if so */ public boolean supportsCoreSQLGrammar() { return false; } /** * Is the ODBC Extended SQL grammar supported? * * @return true if so */ public boolean supportsExtendedSQLGrammar() { return false; } /** * Is the ANSI92 entry level SQL grammar supported? * * All JDBC-Compliant drivers must return true. * * @return true if so */ public boolean supportsANSI92EntryLevelSQL() { /* DERBY - 2243 : Derby does support ANSI 92 standards, * thus changing the return value to true to relfect that the support * is present */ return true; } /** * Is the ANSI92 intermediate SQL grammar supported? * * @return true if so * */ public boolean supportsANSI92IntermediateSQL() { return false; } /** * Is the ANSI92 full SQL grammar supported? * * @return true if so * */ public boolean supportsANSI92FullSQL() { return false; } /** * Is the SQL Integrity Enhancement Facility supported? * * @return true if so * */ public boolean supportsIntegrityEnhancementFacility() { return false; } /** * Is some form of outer join supported? * * @return true if so * */ public boolean supportsOuterJoins() { return true; } /** * Are full nested outer joins supported? * * @return true if so * */ public boolean supportsFullOuterJoins() { return false; } /** * Is there limited support for outer joins? (This will be true * if supportFullOuterJoins is true.) * * @return true if so * */ public boolean supportsLimitedOuterJoins() { return true; } /** * What's the database vendor's preferred term for "schema"? * * @return the vendor term * */ public String getSchemaTerm() { return "SCHEMA"; } /** * What's the database vendor's preferred term for "procedure"? * * @return the vendor term * */ public String getProcedureTerm() { return "PROCEDURE"; } /** * What's the database vendor's preferred term for "catalog"? * * @return the vendor term * */ public String getCatalogTerm() { return "CATALOG"; } /** * Does a catalog appear at the start of a qualified table name? * (Otherwise it appears at the end) * * @return true if it appears at the start * */ public boolean isCatalogAtStart() { return false; } /** * What's the separator between catalog and table name? * * @return the separator string * */ public String getCatalogSeparator() { return ""; } /** * Can a schema name be used in a data manipulation statement? * * @return true if so * */ public boolean supportsSchemasInDataManipulation() { return true; } /** * Can a schema name be used in a procedure call statement? * * @return true if so * */ public boolean supportsSchemasInProcedureCalls() { return true; } /** * Can a schema name be used in a table definition statement? * * @return true if so * */ public boolean supportsSchemasInTableDefinitions() { return true; } /** * Can a schema name be used in an index definition statement? * * @return true if so */ public boolean supportsSchemasInIndexDefinitions() { return true; } /** * Can a schema name be used in a privilege definition statement? * * @return true if so * */ public boolean supportsSchemasInPrivilegeDefinitions() { return true; } /** * Can a catalog name be used in a data manipulation statement? * * @return true if so * */ public boolean supportsCatalogsInDataManipulation() { return false; } /** * Can a catalog name be used in a procedure call statement? * * @return true if so * */ public boolean supportsCatalogsInProcedureCalls() { return false; } /** * Can a catalog name be used in a table definition statement? * * @return true if so * */ public boolean supportsCatalogsInTableDefinitions() { return false; } /** * Can a catalog name be used in an index definition statement? * * @return true if so */ public boolean supportsCatalogsInIndexDefinitions() { return false; } /** * Can a catalog name be used in a privilege definition statement? * * @return true if so */ public boolean supportsCatalogsInPrivilegeDefinitions() { return false; } /** * Is positioned DELETE supported? * * @return true if so */ public boolean supportsPositionedDelete() { return true; } /** * Is positioned UPDATE supported? * * @return true if so */ public boolean supportsPositionedUpdate() { return true; } /** * Is SELECT for UPDATE supported? * * @return true if so */ public boolean supportsSelectForUpdate() { return true; } /** * Are stored procedure calls using the stored procedure escape * syntax supported? * * @return true if so */ public boolean supportsStoredProcedures() { return true; } /** * Are subqueries in comparison expressions supported? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsSubqueriesInComparisons() { return true; } /** * Are subqueries in 'exists' expressions supported? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsSubqueriesInExists() { return true; } /** * Are subqueries in 'in' statements supported? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsSubqueriesInIns() { return true; } /** * Are subqueries in quantified expressions supported? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsSubqueriesInQuantifieds() { return true; } /** * Are correlated subqueries supported? * * A JDBC-Compliant driver always returns true. * * @return true if so */ public boolean supportsCorrelatedSubqueries() { return true; } /** * Is SQL UNION supported? * * @return true if so */ public boolean supportsUnion() { return true; } /** * Is SQL UNION ALL supported? * * @return true if so */ public boolean supportsUnionAll() { return true; } /** * Can cursors remain open across commits? * * @return true if cursors always remain open; false if they might not remain open */ //returns false because Derby does not support cursors that are open across commits for XA transactions. public boolean supportsOpenCursorsAcrossCommit() { return false; } /** * Can cursors remain open across rollbacks? * * @return true if cursors always remain open; false if they might not remain open */ public boolean supportsOpenCursorsAcrossRollback() { return false; } /** * Can statements remain open across commits? * * @return true if statements always remain open; false if they might not remain open */ public boolean supportsOpenStatementsAcrossCommit() { return true; } /** * Can statements remain open across rollbacks? * * @return true if statements always remain open; false if they might not remain open */ public boolean supportsOpenStatementsAcrossRollback() { return false; } //---------------------------------------------------------------------- // The following group of methods exposes various limitations // based on the target database with the current driver. // Unless otherwise specified, a result of zero means there is no // limit, or the limit is not known. /** * How many hex characters can you have in an inline binary literal? * * @return max literal length */ public int getMaxBinaryLiteralLength() { return 0; } /** * What's the max length for a character literal? * * @return max literal length */ public int getMaxCharLiteralLength() { return 0; } /** * What's the limit on column name length? * * @return max literal length */ public int getMaxColumnNameLength() { return Limits.MAX_IDENTIFIER_LENGTH; } /** * What's the maximum number of columns in a "GROUP BY" clause? * * @return max number of columns */ public int getMaxColumnsInGroupBy() { return 0; } /** * What's the maximum number of columns allowed in an index? * * @return max columns */ public int getMaxColumnsInIndex() { return 0; } /** * What's the maximum number of columns in an "ORDER BY" clause? * * @return max columns */ public int getMaxColumnsInOrderBy() { return 0; } /** * What's the maximum number of columns in a "SELECT" list? * * we don't have a limit... * * @return max columns */ public int getMaxColumnsInSelect() { return 0; } /** * What's the maximum number of columns in a table? * * @return max columns */ public int getMaxColumnsInTable() { return 0; } /** * How many active connections can we have at a time to this database? * * @return max connections */ public int getMaxConnections() { return 0; } /** * What's the maximum cursor name length? * * @return max cursor name length in bytes */ public int getMaxCursorNameLength() { return Limits.MAX_IDENTIFIER_LENGTH; } /** * What's the maximum length of an index (in bytes)? * * @return max index length in bytes */ public int getMaxIndexLength() { return 0; } /** * What's the maximum length allowed for a schema name? * * @return max name length in bytes */ public int getMaxSchemaNameLength() { return Limits.MAX_IDENTIFIER_LENGTH; } /** * What's the maximum length of a procedure name? * * @return max name length in bytes */ public int getMaxProcedureNameLength() { return Limits.MAX_IDENTIFIER_LENGTH; } /** * What's the maximum length of a catalog name? * * @return max name length in bytes */ public int getMaxCatalogNameLength() { return 0; } /** * What's the maximum length of a single row? * * @return max row size in bytes */ public int getMaxRowSize() { return 0; } /** * Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY * blobs? * * @return true if so */ public boolean doesMaxRowSizeIncludeBlobs() { return true; } /** * What's the maximum length of a SQL statement? * * @return max length in bytes */ public int getMaxStatementLength() { return 0; } /** * How many active statements can we have open at one time to this * database? * * @return the maximum */ public int getMaxStatements() { return 0; } /** * What's the maximum length of a table name? * * @return max name length in bytes */ public int getMaxTableNameLength() { return Limits.MAX_IDENTIFIER_LENGTH; } /** * What's the maximum number of tables in a SELECT? * * @return the maximum */ public int getMaxTablesInSelect() { return 0; } /** * What's the maximum length of a user name? * * @return max name length in bytes */ public int getMaxUserNameLength() { return Limits.DB2_MAX_USERID_LENGTH; } //---------------------------------------------------------------------- /** * What's the database's default transaction isolation level? The * values are defined in java.sql.Connection. * * @return the default isolation level * @see Connection */ public int getDefaultTransactionIsolation() { return java.sql.Connection.TRANSACTION_READ_COMMITTED; } /** * Are transactions supported? If not, commit is a noop and the * isolation level is TRANSACTION_NONE. * * @return true if transactions are supported */ public boolean supportsTransactions() { return true; } /** * Does the database support the given transaction isolation level? * * DatabaseMetaData.supportsTransactionIsolation() should return false for * isolation levels that are not supported even if a higher level can be * substituted. * * @param level the values are defined in java.sql.Connection * @return true if so * @see Connection */ public boolean supportsTransactionIsolationLevel(int level) { // REMIND: This is hard-coded for the moment because it doesn't nicely // fit within the framework we've set up for the rest of these values. // Part of the reason is that it has a parameter, so it's not just a // simple value look-up. Some ideas for the future on how to make this // not hard-coded: // - code it as a query: "select true from <something> where ? in // (a,b,c)" where a,b,c are the supported isolation levels. The // parameter would be set to "level". This seems awfully awkward. // - somehow what you'd really like is to enable the instructions // file to contain the list, or set, of supported isolation // levels. Something like: // supportsTr...ionLevel=SERIALIZABLE | REPEATABLE_READ | ... // That would take some more code that doesn't seem worthwhile at // the moment for this one case. /* REMIND: this could be moved into a query that is e.g. VALUES ( ? in (8,...) ) so that database could control the list of supported isolations. For now, it's hard coded, and just the one. */ return (level == Connection.TRANSACTION_SERIALIZABLE || level == Connection.TRANSACTION_REPEATABLE_READ || level == Connection.TRANSACTION_READ_COMMITTED || level == Connection.TRANSACTION_READ_UNCOMMITTED); } /** * Are both data definition and data manipulation statements * within a transaction supported? * * @return true if so */ public boolean supportsDataDefinitionAndDataManipulationTransactions() { return true; } /** * Are only data manipulation statements within a transaction * supported? * * @return true if so */ public boolean supportsDataManipulationTransactionsOnly() { return false; } /** * Does a data definition statement within a transaction force the * transaction to commit? * * @return true if so * */ public boolean dataDefinitionCausesTransactionCommit() { return false; } /** * Is a data definition statement within a transaction ignored? * * @return true if so * */ public boolean dataDefinitionIgnoredInTransactions(){ return false; } /** * Get a description of stored procedures available in a * catalog. * * <P>Only procedure descriptions matching the schema and * procedure name criteria are returned. They are ordered by * PROCEDURE_SCHEM, and PROCEDURE_NAME. * * <P>Each procedure description has the the following columns: * <OL> * <LI><B>PROCEDURE_CAT</B> String => procedure catalog (may be null) * <LI><B>PROCEDURE_SCHEM</B> String => procedure schema (may be null) * <LI><B>PROCEDURE_NAME</B> String => procedure name * <LI> reserved for future use * <LI> reserved for future use * <LI> reserved for future use * <LI><B>REMARKS</B> String => explanatory comment on the procedure * <LI><B>PROCEDURE_TYPE</B> short => kind of procedure: * <UL> * <LI> procedureResultUnknown - May return a result * <LI> procedureNoResult - Does not return a result * <LI> procedureReturnsResult - Returns a result * </UL> * <LI><B>SPECIFIC_NAME</B> String => The name which uniquely * identifies this procedure within its schema (since JDBC 4.0) * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param procedureNamePattern a procedure name pattern * @return ResultSet - each row is a procedure description * @see #getSearchStringEscape * @exception SQLException thrown on failure. */ public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { // Using the new JDBC 4.0 version of the query here. The query // was given a new name to allow the old query to // be used by ODBCMetaDataGenerator. return doGetProcs(catalog, schemaPattern, procedureNamePattern, "getProcedures40"); } /** * Get a description of stored procedures available in a * catalog. Same as getProcedures() above, except that * the result set will conform to ODBC specifications. */ public ResultSet getProceduresForODBC(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { // For ODBC we still use the transformed version of the JDBC // 3.0 query, (may change in the future). return doGetProcs(catalog, schemaPattern, procedureNamePattern, "odbc_getProcedures"); } /** * Implements DatabaseMetaData.getFunctions() for an embedded * database. Queries the database to get information about * functions (procedures returning values). Executes the * 'getFunctions' query from metadata.properties to obtain the * ResultSet to return.<p> Compatibility: This is a new method in * the API which is only available with with Derby versions > 10.1 and * JDK versions >= 1.6 <p>Upgrade: Since this is a new query it * does not have an SPS, and will be available as soon as any * database, new or old, is booted with the new version of Derby, * (in <b>soft and hard</b> upgrade). * @param catalog limit the search to functions in this catalog * (not used) * @param schemaPattern limit the search to functions in schemas * matching this pattern * @param functionNamePattern limit the search to functions * matching this pattern * @return a ResultSet with metadata information * @throws SQLException if any of the underlying jdbc methods fail */ public ResultSet getFunctions(java.lang.String catalog, java.lang.String schemaPattern, java.lang.String functionNamePattern) throws SQLException { return doGetProcs(catalog, schemaPattern, functionNamePattern, "getFunctions"); } /** * Does the actual work for the getProcedures and getFunctions * metadata calls. See getProcedures() method above for parameter * descriptions. * @param queryName Name of the query to execute; is used * to determine whether the result set should conform to * JDBC or ODBC specifications. */ private ResultSet doGetProcs(String catalog, String schemaPattern, String procedureNamePattern, String queryName) throws SQLException { PreparedStatement s = getPreparedQuery(queryName); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schemaPattern)); s.setString(3, swapNull(procedureNamePattern)); return s.executeQuery(); } /** * Get a description of a catalog's stored procedure parameters * and result columns. * * <P>Only descriptions matching the schema, procedure and * parameter name criteria are returned. They are ordered by * PROCEDURE_SCHEM and PROCEDURE_NAME. Within this, the return value, * if any, is first. Next are the parameter descriptions in call * order. The column descriptions follow in column number order. * * <P>Each row in the ResultSet is a parameter description or * column description with the following fields: * <OL> * <LI><B>PROCEDURE_CAT</B> String => procedure catalog (may be null) * <LI><B>PROCEDURE_SCHEM</B> String => procedure schema (may be null) * <LI><B>PROCEDURE_NAME</B> String => procedure name * <LI><B>COLUMN_NAME</B> String => column/parameter name * <LI><B>COLUMN_TYPE</B> Short => kind of column/parameter: * <UL> * <LI> procedureColumnUnknown - nobody knows * <LI> procedureColumnIn - IN parameter * <LI> procedureColumnInOut - INOUT parameter * <LI> procedureColumnOut - OUT parameter * <LI> procedureColumnReturn - procedure return value * <LI> procedureColumnResult - result column in ResultSet * </UL> * <LI><B>DATA_TYPE</B> int => SQL type from java.sql.Types * <LI><B>TYPE_NAME</B> String => SQL type name * <LI><B>PRECISION</B> int => precision * <LI><B>LENGTH</B> int => length in bytes of data * <LI><B>SCALE</B> short => scale * <LI><B>RADIX</B> short => radix * <LI><B>NULLABLE</B> short => can it contain NULL? * <UL> * <LI> procedureNoNulls - does not allow NULL values * <LI> procedureNullable - allows NULL values * <LI> procedureNullableUnknown - nullability unknown * </UL> * <LI><B>REMARKS</B> String => comment describing parameter/column * <LI><B>COLUMN_DEF</B> String * <LI><B>SQL_DATA_TYPE</B> int * <LI><B>SQL_DATETIME_SUB</B> int * <LI><B>CHAR_OCTET_LENGTH</B> int * <LI><B>ORDINAL_POSITION</B> int * <LI><B>IS_NULLABLE</B> String * <LI><B>SPECIFIC_NAME</B> String * </OL> * * <P><B>Note:</B> Some databases may not return the column * descriptions for a procedure. Additional columns beyond * SPECIFIC_NAME can be defined by the database. * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param procedureNamePattern a procedure name pattern * @param columnNamePattern a column name pattern * @return ResultSet - each row is a stored procedure parameter or * column description * @see #getSearchStringEscape * @exception SQLException thrown on failure. */ public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { // Using the new JDBC 4.0 version of the query here. The query // was given a new name to allow the old query to // be used by ODBCMetaDataGenerator. return doGetProcCols(catalog, schemaPattern, procedureNamePattern, columnNamePattern, "getProcedureColumns40"); } /** * Get a description of a catalog's stored procedure parameters * and result columns. Same as getProcedureColumns() above, * except that the result set will conform to ODBC specifications. */ public ResultSet getProcedureColumnsForODBC(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { // For ODBC we still use the transformed version of the JDBC // 3.0 query, (may change in the future). return doGetProcCols(catalog, schemaPattern, procedureNamePattern, columnNamePattern, "odbc_getProcedureColumns"); } /** * Implements DatabaseMetaData.getFunctionColumns() for an embedded * database. Queries the database to get information about * function parameters. Executes the * 'getFunctionColumns' query from metadata.properties to obtain the * ResultSet.<p> Compatibility: This is a new method in * the API which is only available with with Derby versions > 10.1 and * JDK versions >= 1.6 <p>Upgrade: Since this is a new query it * does not have an SPS, and will be available as soon as any * database, new or old, is booted with the new version of Derby, * (in <b>soft and hard</b> upgrade). * @param catalog limit the search to functions in this catalog * (not used) * @param schemaPattern limit the search to functions in schemas * matching this pattern * @param functionNamePattern limit the search to functions * matching this pattern * @param parameterNamePattern limit the search parameters * matching this pattern * @return a ResultSet with metadata information * @throws SQLException if a database error occurs */ public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String parameterNamePattern) throws SQLException { PreparedStatement s = getPreparedQuery("getFunctionColumns"); // Cannot use doGetProcCols() because our query requires // parameterNamePattern twice, because both LIKE and = is // required to select parameters with an empty parameter // name. That is, WHERE paramName LIKE ? will not match an // empty paramName, but WHERE paramName LIKE ? OR paramName = // ? will. s.setString(1, swapNull(schemaPattern)); s.setString(2, swapNull(functionNamePattern)); s.setString(3, swapNull(parameterNamePattern)); s.setString(4, swapNull(parameterNamePattern)); return s.executeQuery(); } /** * Does the actual work for the getProcedureColumns metadata * calls. See getProcedureColumns() method above for parameter * descriptions. * @param queryName Name of the query to execute; is used * to determine whether the result set should conform to * JDBC or ODBC specifications. */ private ResultSet doGetProcCols(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern, String queryName) throws SQLException { PreparedStatement s = getPreparedQuery(queryName); // // catalog is not part of the query // s.setString(1, swapNull(schemaPattern)); s.setString(2, swapNull(procedureNamePattern)); s.setString(3, swapNull(columnNamePattern)); return s.executeQuery(); } /** * Get a description of tables available in a catalog. * * <P>Only table descriptions matching the catalog, schema, table * name and type criteria are returned. They are ordered by * TABLE_TYPE, TABLE_SCHEM and TABLE_NAME. * * <P>Each table description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE", * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", * "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * <LI><B>REMARKS</B> String => explanatory comment on the table * <LI><B>TYPE_CAT</B> String => the types catalog (may be * <code>null</code>) * <LI><B>TYPE_SCHEM</B> String => the types schema (may be * <code>null</code>) * <LI><B>TYPE_NAME</B> String => type name (may be * <code>null</code>) * <LI><B>SELF_REFERENCING_COL_NAME</B> String => name of the * designated "identifier" column of a typed table (may * be <code>null</code>) * <LI><B>REF_GENERATION</B> String => specifies how values in * SELF_REFERENCING_COL_NAME are created. Values are * "SYSTEM", "USER", "DERIVED". (may be * <code>null</code>) * </OL> * * <P><B>Note:</B> Some databases may not return information for * all tables. * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern * @param types a list of table types to include; null returns all types * @return ResultSet - each row is a table description * @see #getSearchStringEscape * @exception SQLException thrown on failure. */ public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String types[]) throws SQLException { synchronized (getConnectionSynchronization()) { setupContextStack(); ResultSet rs = null; try { String queryText = getQueryDescriptions(false).getProperty("getTables"); /* * The query text is assumed to end with a "where" clause, so * that we can safely append * "and table_Type in ('xxx','yyy','zzz', ...)" and * have it become part of the where clause. * * Let's assume for now that the table type first char corresponds * to JBMS table type identifiers. */ StringBuffer whereClauseTail = new StringBuffer(queryText); if (types != null && types.length >= 1) { whereClauseTail.append(" AND TABLETYPE IN ('"); whereClauseTail.append(types[0].substring(0, 1)); for (int i=1; i<types.length; i++) { whereClauseTail.append("','"); whereClauseTail.append(types[i].substring(0, 1)); } whereClauseTail.append("')"); } // Add the order by clause after the 'in' list. whereClauseTail.append( " ORDER BY TABLE_TYPE, TABLE_SCHEM, TABLE_NAME"); PreparedStatement s = getEmbedConnection().prepareMetaDataStatement(whereClauseTail.toString()); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schemaPattern)); s.setString(3, swapNull(tableNamePattern)); rs = s.executeQuery(); } catch (Throwable t) { throw handleException(t); } finally { restoreContextStack(); } return rs; } } /** * Get the schema names available in this database. The results * are ordered by schema name. * * <P>The schema columns are: * <OL> * <li><strong>TABLE_SCHEM</strong> String =&gt; schema name</li> * <li><strong>TABLE_CATALOG</strong> String =&gt; catalog name * (may be <code>null</code>)</li> * </OL> * * @return ResultSet - each row is a schema description * @exception SQLException thrown on failure. */ public ResultSet getSchemas() throws SQLException { return getSchemas(null, null); } /** * Get the catalog names available in this database. The results * are ordered by catalog name. * * <P>The catalog column is: * <OL> * <LI><B>TABLE_CAT</B> String => catalog name * </OL> * * @return ResultSet - each row has a single String column that is a * catalog name * @exception SQLException thrown on failure. */ public ResultSet getCatalogs() throws SQLException { return getSimpleQuery("getCatalogs"); } /** * Get the table types available in this database. The results * are ordered by table type. * * <P>The table type is: * <OL> * <LI><B>TABLE_TYPE</B> String => table type. Typical types are "TABLE", * "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", * "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * </OL> * * @return ResultSet - each row has a single String column that is a * table type * @exception SQLException thrown on failure. */ public ResultSet getTableTypes() throws SQLException { return getSimpleQuery("getTableTypes"); } /** * Get a description of table columns available in a catalog. * * <P>Only column descriptions matching the catalog, schema, table * and column name criteria are returned. They are ordered by * TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION. * * <P>Each column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> int => SQL type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => column size. For char or date * types this is the maximum number of characters, for numeric or * decimal types this is precision. * <LI><B>BUFFER_LENGTH</B> is not used. * <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits * <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2) * <LI><B>NULLABLE</B> int => is NULL allowed? * <UL> * <LI> columnNoNulls - might not allow NULL values * <LI> columnNullable - definitely allows NULL values * <LI> columnNullableUnknown - nullability unknown * </UL> * <LI><B>REMARKS</B> String => comment describing column (may be null) * <LI><B>COLUMN_DEF</B> String => default value (may be null) * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the * maximum number of bytes in the column * <LI><B>ORDINAL_POSITION</B> int => index of column in table * (starting at 1) * <LI><B>IS_NULLABLE</B> String => "NO" means column definitely * does not allow NULL values; "YES" means the column might * allow NULL values. An empty string means nobody knows. * <LI><B>SCOPE_CATLOG</B> String => catalog of table that is the * scope of a reference attribute (<code>null</code> if DATA_TYPE * isn't REF) * <LI><B>SCOPE_SCHEMA</B> String => schema of table that is the * scope of a reference attribute (<code>null</code> if the * DATA_TYPE isn't REF) * <LI><B>SCOPE_TABLE</B> String => table name that this the * scope of a reference attribure (<code>null</code> if the * DATA_TYPE isn't REF) * <LI><B>SOURCE_DATA_TYPE</B> short => source type of a distinct * type or user-generated Ref type, SQL type from java.sql.Types * (<code>null</code> if DATA_TYPE isn't DISTINCT or * user-generated REF) * <LI><B>IS_AUTOINCREMENT</B> String => Indicates whether this * column is auto incremented * <UL> * <LI> YES --- if the column is auto incremented * <LI> NO --- if the column is not auto incremented * <LI> empty string --- if it cannot be determined whether the * column is auto incremented parameter is unknown * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern * @param columnNamePattern a column name pattern * @return ResultSet - each row is a column description * @see #getSearchStringEscape * @exception SQLException thrown on failure. */ public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { return doGetCols(catalog, schemaPattern, tableNamePattern, columnNamePattern, "getColumns"); } /** * Get a description of table columns available in a catalog. * Same as getColumns() above, except that the result set * will conform to ODBC specifications. */ public ResultSet getColumnsForODBC(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { return doGetCols(catalog, schemaPattern, tableNamePattern, columnNamePattern, "odbc_getColumns"); } /** * Does the actual work for the getColumns metadata calls. * See getColumns() method above for parameter descriptions. * @param queryName Name of the query to execute; is used * to determine whether the result set should conform to * JDBC or ODBC specifications. */ private ResultSet doGetCols(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern, String queryName) throws SQLException { PreparedStatement s = getPreparedQuery(queryName); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schemaPattern)); s.setString(3, swapNull(tableNamePattern)); s.setString(4, swapNull(columnNamePattern)); return s.executeQuery(); } /** * Get a description of the access rights for a table's columns. * * <P>Only privileges matching the column name criteria are * returned. They are ordered by COLUMN_NAME and PRIVILEGE. * * <P>Each privilige description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>GRANTOR</B> => grantor of access (may be null) * <LI><B>GRANTEE</B> String => grantee of access * <LI><B>PRIVILEGE</B> String => name of access (SELECT, * INSERT, UPDATE, REFRENCES, ...) * <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted * to grant to others; "NO" if not; null if unknown * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @param columnNamePattern a column name pattern * @return ResultSet - each row is a column privilege description * @see #getSearchStringEscape * @exception SQLException thrown on failure. */ public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { PreparedStatement s = getPreparedQuery("getColumnPrivileges"); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schema)); s.setString(3, swapNull(table)); s.setString(4, swapNull(columnNamePattern)); return s.executeQuery(); } /** * Get a description of the access rights for each table available * in a catalog. Note that a table privilege applies to one or * more columns in the table. It would be wrong to assume that * this priviledge applies to all columns (this may be true for * some systems but is not true for all.) * * <P>Only privileges matching the schema and table name * criteria are returned. They are ordered by TABLE_SCHEM, * TABLE_NAME, and PRIVILEGE. * * <P>Each privilige description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>GRANTOR</B> => grantor of access (may be null) * <LI><B>GRANTEE</B> String => grantee of access * <LI><B>PRIVILEGE</B> String => name of access (SELECT, * INSERT, UPDATE, REFRENCES, ...) * <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted * to grant to others; "NO" if not; null if unknown * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param tableNamePattern a table name pattern * @return ResultSet - each row is a table privilege description * @see #getSearchStringEscape * @exception SQLException thrown on failure. */ public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { PreparedStatement s = getPreparedQuery("getTablePrivileges"); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schemaPattern)); s.setString(3, swapNull(tableNamePattern)); return s.executeQuery(); } /** * Get a description of a table's optimal set of columns that * uniquely identifies a row. They are ordered by SCOPE. * * <P>Each column description has the following columns: * <OL> * <LI><B>SCOPE</B> short => actual scope of result * <UL> * <LI> bestRowTemporary - very temporary, while using row * <LI> bestRowTransaction - valid for remainder of current transaction * <LI> bestRowSession - valid for remainder of current session * </UL> * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> int => SQL data type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => precision * <LI><B>BUFFER_LENGTH</B> int => not used * <LI><B>DECIMAL_DIGITS</B> short => scale * <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column * like an Oracle ROWID * <UL> * <LI> bestRowUnknown - may or may not be pseudo column * <LI> bestRowNotPseudo - is NOT a pseudo column * <LI> bestRowPseudo - is a pseudo column * </UL> * </OL> * * @param catalogPattern a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schemaPattern a schema name; "" retrieves those without a schema * @param tablePattern a table name * @param scope the scope of interest; use same values as SCOPE * @param nullable include columns that are nullable? * @return ResultSet - each row is a column description * @exception SQLException thrown on failure. */ public ResultSet getBestRowIdentifier ( String catalogPattern, String schemaPattern, String tablePattern, int scope, boolean nullable ) throws SQLException { return doGetBestRowId(catalogPattern, schemaPattern, tablePattern, scope, nullable, ""); } /** * Get a description of a table's optimal set of columns that * uniquely identifies a row. They are ordered by SCOPE. * Same as getBestRowIdentifier() above, except that the result * set will conform to ODBC specifications. */ public ResultSet getBestRowIdentifierForODBC(String catalogPattern, String schemaPattern, String tablePattern, int scope, boolean nullable) throws SQLException { return doGetBestRowId(catalogPattern, schemaPattern, tablePattern, scope, nullable, "odbc_"); } /** * Does the actual work for the getBestRowIdentifier metadata * calls. See getBestRowIdentifier() method above for parameter * descriptions. * @param queryPrefix Prefix to be appended to the names of * the queries used in this method. This is used * to determine whether the result set should conform to * JDBC or ODBC specifications. */ private ResultSet doGetBestRowId(String catalogPattern, String schemaPattern, String tablePattern, int scope, boolean nullable, String queryPrefix) throws SQLException { int nullableInIntForm = 0; if (nullable) nullableInIntForm = 1; if (catalogPattern == null) { catalogPattern = "%"; } if (schemaPattern == null) { schemaPattern = "%"; } if (tablePattern == null) { tablePattern = "%"; } PreparedStatement ps; boolean done; // scope value is bad, return an empty result if (scope < 0 || scope > 2) { ps = getPreparedQuery("getBestRowIdentifierEmpty"); return ps.executeQuery(); } // see if there is a primary key, use it. ps = getPreparedQuery("getBestRowIdentifierPrimaryKey"); ps.setString(1,catalogPattern); ps.setString(2,schemaPattern); ps.setString(3,tablePattern); ResultSet rs = ps.executeQuery(); done = rs.next(); String constraintId = ""; if (done) { constraintId = rs.getString(1); } rs.close(); ps.close(); if (done) { // this one's it, do the real thing and return it. // we don't need to check catalog, schema, table name // or scope again. ps = getPreparedQuery(queryPrefix + "getBestRowIdentifierPrimaryKeyColumns"); ps.setString(1,constraintId); ps.setString(2,constraintId); // note, primary key columns aren't nullable, // so we skip the nullOk parameter. return ps.executeQuery(); } // get the unique constraint with the fewest columns. ps = getPreparedQuery("getBestRowIdentifierUniqueConstraint"); ps.setString(1,catalogPattern); ps.setString(2,schemaPattern); ps.setString(3,tablePattern); rs = ps.executeQuery(); done = rs.next(); if (done) { constraintId = rs.getString(1); } // REMIND: we need to actually check for null columns // and toss out constraints with null columns if they aren't // desired... recode this as a WHILE returning at the // first match or falling off the end. rs.close(); ps.close(); if (done) { // this one's it, do the real thing and return it. ps = getPreparedQuery(queryPrefix + "getBestRowIdentifierUniqueKeyColumns"); ps.setString(1,constraintId); ps.setString(2,constraintId); ps.setInt(3,nullableInIntForm); return ps.executeQuery(); } // second-to last try -- unique index with minimal # columns // (only non null columns if so required) ps = getPreparedQuery("getBestRowIdentifierUniqueIndex"); ps.setString(1,catalogPattern); ps.setString(2,schemaPattern); ps.setString(3,tablePattern); rs = ps.executeQuery(); done = rs.next(); long indexNum = 0; if (done) { indexNum = rs.getLong(1); } // REMIND: we need to actually check for null columns // and toss out constraints with null columns if they aren't // desired... recode this as a WHILE returning at the // first match or falling off the end. rs.close(); ps.close(); if (done) { // this one's it, do the real thing and return it. ps = getPreparedQuery(queryPrefix + "getBestRowIdentifierUniqueIndexColumns"); ps.setLong(1,indexNum); ps.setInt(2,nullableInIntForm); return ps.executeQuery(); } // last try -- just return all columns of the table // the not null ones if that restriction is upon us. ps = getPreparedQuery(queryPrefix + "getBestRowIdentifierAllColumns"); ps.setString(1,catalogPattern); ps.setString(2,schemaPattern); ps.setString(3,tablePattern); ps.setInt(4,scope); ps.setInt(5,nullableInIntForm); return ps.executeQuery(); } /** * Get a description of a table's columns that are automatically * updated when any value in a row is updated. They are * unordered. * * <P>Each column description has the following columns: * <OL> * <LI><B>SCOPE</B> short => is not used * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>DATA_TYPE</B> int => SQL data type from java.sql.Types * <LI><B>TYPE_NAME</B> String => Data source dependent type name * <LI><B>COLUMN_SIZE</B> int => precision * <LI><B>BUFFER_LENGTH</B> int => length of column value in bytes * <LI><B>DECIMAL_DIGITS</B> short => scale * <LI><B>PSEUDO_COLUMN</B> short => is this a pseudo column * like an Oracle ROWID * <UL> * <LI> versionColumnUnknown - may or may not be pseudo column * <LI> versionColumnNotPseudo - is NOT a pseudo column * <LI> versionColumnPseudo - is a pseudo column * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schema a schema name; "" retrieves those without a schema * @param table a table name * @return ResultSet - each row is a column description * @exception SQLException thrown on failure. */ public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { return doGetVersionCols(catalog, schema, table, "getVersionColumns"); } /** * Get a description of a table's columns that are automatically * updated when any value in a row is updated. They are * unordered. Same as getVersionColumns() above, except that * the result set will conform to ODBC specifications. */ public ResultSet getVersionColumnsForODBC(String catalog, String schema, String table) throws SQLException { return doGetVersionCols(catalog, schema, table, "odbc_getVersionColumns"); } /** * Does the actual work for the getVersionColumns metadata * calls. See getVersionColumns() method above for parameter * descriptions. * @param queryName Name of the query to execute; is used * to determine whether the result set should conform to * JDBC or ODBC specifications. */ private ResultSet doGetVersionCols(String catalog, String schema, String table, String queryName) throws SQLException { PreparedStatement s = getPreparedQuery(queryName); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schema)); s.setString(3, swapNull(table)); return s.executeQuery(); } /** * check if the dictionary is at the same version as the engine. If not, * then that means stored versions of the JDBC database metadata queries * may not be compatible with this version of the software. * This can happen if we are in soft upgrade mode. Since in soft upgrade * mode, we can't change these stored metadata queries in a backward * incompatible way, engine needs to read the metadata sql from * metadata.properties or metadata_net.properties file rather than * rely on system tables. * * @return true if we are not in soft upgrade mode * @throws SQLException */ private boolean notInSoftUpgradeMode() throws SQLException { if ( getEmbedConnection().isClosed()) throw Util.noCurrentConnection(); boolean notInSoftUpgradeMode; try { notInSoftUpgradeMode = getLanguageConnectionContext().getDataDictionary().checkVersion( DataDictionary.DD_VERSION_CURRENT,null); } catch (Throwable t) { throw handleException(t); } return notInSoftUpgradeMode; } /** * Get a description of a table's primary key columns. They * are ordered by COLUMN_NAME. * * <P>Each primary key column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>COLUMN_NAME</B> String => column name * <LI><B>KEY_SEQ</B> short => sequence number within primary key * <LI><B>PK_NAME</B> String => primary key name (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet - each row is a primary key column description * @exception SQLException thrown on failure. */ public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { PreparedStatement s = getPreparedQuery("getPrimaryKeys"); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schema)); s.setString(3, swapNull(table)); return s.executeQuery(); } /** * Get a description of the primary key columns that are * referenced by a table's foreign key columns (the primary keys * imported by a table). They are ordered by PKTABLE_CAT, * PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ. * * <P>Each primary key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog * being imported (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema * being imported (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * being imported * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * being imported * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedNoAction - do not allow update of primary * key if it has been imported * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * <LI> importedKeySetDefault - change imported key to default values * if its primary key has been updated * <LI> importedKeyRestrict - same as importedKeyNoAction * (for ODBC 2.x compatibility) * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyNoAction - do not allow delete of primary * key if it has been imported * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * <LI> importedKeyRestrict - same as importedKeyNoAction * (for ODBC 2.x compatibility) * <LI> importedKeySetDefault - change imported key to default if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key name (may be null) * <LI><B>PK_NAME</B> String => primary key name (may be null) * <LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key * constraints be deferred until commit * <UL> * <LI> importedKeyInitiallyDeferred - see SQL92 for definition * <LI> importedKeyInitiallyImmediate - see SQL92 for definition * <LI> importedKeyNotDeferrable - see SQL92 for definition * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet - each row is a primary key column description * @see #getExportedKeys * @exception SQLException thrown on failure. */ public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { PreparedStatement s = getPreparedQuery("getImportedKeys"); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schema)); s.setString(3, swapNull(table)); return s.executeQuery(); } /** * Get a description of the foreign key columns that reference a * table's primary key columns (the foreign keys exported by a * table). They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, * FKTABLE_NAME, and KEY_SEQ. * * <P>Each foreign key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * being exported (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * being exported (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * being exported * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * being exported * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedNoAction - do not allow update of primary * key if it has been imported * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * <LI> importedKeySetDefault - change imported key to default values * if its primary key has been updated * <LI> importedKeyRestrict - same as importedKeyNoAction * (for ODBC 2.x compatibility) * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyNoAction - do not allow delete of primary * key if it has been imported * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * <LI> importedKeyRestrict - same as importedKeyNoAction * (for ODBC 2.x compatibility) * <LI> importedKeySetDefault - change imported key to default if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key name (may be null) * <LI><B>PK_NAME</B> String => primary key name (may be null) * <LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key * constraints be deferred until commit * <UL> * <LI> importedKeyInitiallyDeferred - see SQL92 for definition * <LI> importedKeyInitiallyImmediate - see SQL92 for definition * <LI> importedKeyNotDeferrable - see SQL92 for definition * </UL> * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schema a schema name pattern; "" retrieves those * without a schema * @param table a table name * @return ResultSet - each row is a foreign key column description * @see #getImportedKeys * @exception SQLException thrown on failure. */ public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { PreparedStatement s = getPreparedQuery("getCrossReference"); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schema)); s.setString(3, swapNull(table)); s.setString(4, swapNull(null)); s.setString(5, swapNull(null)); s.setString(6, swapNull(null)); return s.executeQuery(); } /** * Get a description of the foreign key columns in the foreign key * table that reference the primary key columns of the primary key * table (describe how one table imports another's key.) This * should normally return a single foreign key/primary key pair * (most tables only import a foreign key from a table once.) They * are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and * KEY_SEQ. * * <P>Each foreign key column description has the following columns: * <OL> * <LI><B>PKTABLE_CAT</B> String => primary key table catalog (may be null) * <LI><B>PKTABLE_SCHEM</B> String => primary key table schema (may be null) * <LI><B>PKTABLE_NAME</B> String => primary key table name * <LI><B>PKCOLUMN_NAME</B> String => primary key column name * <LI><B>FKTABLE_CAT</B> String => foreign key table catalog (may be null) * being exported (may be null) * <LI><B>FKTABLE_SCHEM</B> String => foreign key table schema (may be null) * being exported (may be null) * <LI><B>FKTABLE_NAME</B> String => foreign key table name * being exported * <LI><B>FKCOLUMN_NAME</B> String => foreign key column name * being exported * <LI><B>KEY_SEQ</B> short => sequence number within foreign key * <LI><B>UPDATE_RULE</B> short => What happens to * foreign key when primary is updated: * <UL> * <LI> importedNoAction - do not allow update of primary * key if it has been imported * <LI> importedKeyCascade - change imported key to agree * with primary key update * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been updated * <LI> importedKeySetDefault - change imported key to default values * if its primary key has been updated * <LI> importedKeyRestrict - same as importedKeyNoAction * (for ODBC 2.x compatibility) * </UL> * <LI><B>DELETE_RULE</B> short => What happens to * the foreign key when primary is deleted. * <UL> * <LI> importedKeyNoAction - do not allow delete of primary * key if it has been imported * <LI> importedKeyCascade - delete rows that import a deleted key * <LI> importedKeySetNull - change imported key to NULL if * its primary key has been deleted * <LI> importedKeyRestrict - same as importedKeyNoAction * (for ODBC 2.x compatibility) * <LI> importedKeySetDefault - change imported key to default if * its primary key has been deleted * </UL> * <LI><B>FK_NAME</B> String => foreign key name (may be null) * <LI><B>PK_NAME</B> String => primary key name (may be null) * <LI><B>DEFERRABILITY</B> short => can the evaluation of foreign key * constraints be deferred until commit * <UL> * <LI> importedKeyInitiallyDeferred - see SQL92 for definition * <LI> importedKeyInitiallyImmediate - see SQL92 for definition * <LI> importedKeyNotDeferrable - see SQL92 for definition * </UL> * </OL> * * @param primaryCatalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param primarySchema a schema name pattern; "" retrieves those * without a schema * @param primaryTable the table name that exports the key * @param foreignCatalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param foreignSchema a schema name pattern; "" retrieves those * without a schema * @param foreignTable the table name that imports the key * @return ResultSet - each row is a foreign key column description * @see #getImportedKeys * @exception SQLException thrown on failure. */ public ResultSet getCrossReference( String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable ) throws SQLException { PreparedStatement s = getPreparedQuery("getCrossReference"); s.setString(1, swapNull(primaryCatalog)); s.setString(2, swapNull(primarySchema)); s.setString(3, swapNull(primaryTable)); s.setString(4, swapNull(foreignCatalog)); s.setString(5, swapNull(foreignSchema)); s.setString(6, swapNull(foreignTable)); return s.executeQuery(); } /** * Get a description of all the standard SQL types supported by * this database. They are ordered by DATA_TYPE and then by how * closely the data type maps to the corresponding JDBC SQL type. * * <P>Each type description has the following columns: * <OL> * <LI><B>TYPE_NAME</B> String => Type name * <LI><B>DATA_TYPE</B> int => SQL data type from java.sql.Types * <LI><B>PRECISION</B> int => maximum precision * <LI><B>LITERAL_PREFIX</B> String => prefix used to quote a literal * (may be null) * <LI><B>LITERAL_SUFFIX</B> String => suffix used to quote a literal (may be null) * <LI><B>CREATE_PARAMS</B> String => parameters used in creating * the type (may be null) * <LI><B>NULLABLE</B> short => can you use NULL for this type? * <UL> * <LI> typeNoNulls - does not allow NULL values * <LI> typeNullable - allows NULL values * <LI> typeNullableUnknown - nullability unknown * </UL> * <LI><B>CASE_SENSITIVE</B> boolean=> is it case sensitive? * <LI><B>SEARCHABLE</B> short => can you use "WHERE" based on this type: * <UL> * <LI> typePredNone - No support * <LI> typePredChar - Only supported with WHERE .. LIKE * <LI> typePredBasic - Supported except for WHERE .. LIKE * <LI> typeSearchable - Supported for all WHERE .. * </UL> * <LI><B>UNSIGNED_ATTRIBUTE</B> boolean => is it unsigned? * <LI><B>FIXED_PREC_SCALE</B> boolean => can it be a money value? * <LI><B>AUTO_INCREMENT</B> boolean => can it be used for an * auto-increment value? * <LI><B>LOCAL_TYPE_NAME</B> String => localized version of type name * (may be null) * <LI><B>MINIMUM_SCALE</B> short => minimum scale supported * <LI><B>MAXIMUM_SCALE</B> short => maximum scale supported * <LI><B>SQL_DATA_TYPE</B> int => unused * <LI><B>SQL_DATETIME_SUB</B> int => unused * <LI><B>NUM_PREC_RADIX</B> int => usually 2 or 10 * </OL> * * @return ResultSet - each row is a SQL type description * @exception SQLException thrown on failure. */ public ResultSet getTypeInfo() throws SQLException { return getSimpleQuery("getTypeInfo"); } /** * Get a description of all the standard SQL types supported by * this database. They are ordered by DATA_TYPE and then by how * closely the data type maps to the corresponding JDBC SQL type. * Same as getTypeInfo above, except that the result set will * conform to ODBC specifications. */ public ResultSet getTypeInfoForODBC() throws SQLException { return getSimpleQuery("odbc_getTypeInfo"); } /** * Get a description of a table's indices and statistics. They are * ordered by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION. * * <P>Each index column description has the following columns: * <OL> * <LI><B>TABLE_CAT</B> String => table catalog (may be null) * <LI><B>TABLE_SCHEM</B> String => table schema (may be null) * <LI><B>TABLE_NAME</B> String => table name * <LI><B>NON_UNIQUE</B> boolean => Can index values be non-unique? * false when TYPE is tableIndexStatistic * <LI><B>INDEX_QUALIFIER</B> String => index catalog (may be null); * null when TYPE is tableIndexStatistic * <LI><B>INDEX_NAME</B> String => index name; null when TYPE is * tableIndexStatistic * <LI><B>TYPE</B> short => index type: * <UL> * <LI> tableIndexStatistic - this identifies table statistics that are * returned in conjuction with a table's index descriptions * <LI> tableIndexClustered - this is a clustered index * <LI> tableIndexHashed - this is a hashed index * <LI> tableIndexOther - this is some other style of index * </UL> * <LI><B>ORDINAL_POSITION</B> short => column sequence number * within index; zero when TYPE is tableIndexStatistic * <LI><B>COLUMN_NAME</B> String => column name; null when TYPE is * tableIndexStatistic * <LI><B>ASC_OR_DESC</B> String => column sort sequence, "A" => ascending, * "D" => descending, may be null if sort sequence is not supported; * null when TYPE is tableIndexStatistic * <LI><B>CARDINALITY</B> int => When TYPE is tableIndexStatistic, then * this is the number of rows in the table; otherwise, it is the * number of unique values in the index. * <LI><B>PAGES</B> int => When TYPE is tableIndexStatisic then * this is the number of pages used for the table, otherwise it * is the number of pages used for the current index. * <LI><B>FILTER_CONDITION</B> String => Filter condition, if any. * (may be null) * </OL> * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schema a schema name pattern; "" retrieves those without a schema * @param table a table name * @param unique when true, return only indices for unique values; * when false, return indices regardless of whether unique or not * @param approximate when true, result is allowed to reflect approximate * or out of data values; when false, results are requested to be * accurate * @return ResultSet - each row is an index column description * @exception SQLException thrown on failure. */ public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { return doGetIndexInfo(catalog, schema, table, unique, approximate, "getIndexInfo"); } /** * Get a description of a table's indices and statistics. They are * ordered by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION. * Same as getIndexInfo above, except that the result set will * conform to ODBC specifications. */ public ResultSet getIndexInfoForODBC(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { return doGetIndexInfo(catalog, schema, table, unique, approximate, "odbc_getIndexInfo"); } /** * Does the actual work for the getIndexInfo metadata * calls. See getIndexInfo() method above for parameter * descriptions. * @param queryName Name of the query to execute; is used * to determine whether the result set should conform to * JDBC or ODBC specifications. */ private ResultSet doGetIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate, String queryName) throws SQLException { int approximateInInt = 0; if (approximate) approximateInInt = 1; PreparedStatement s = getPreparedQuery(queryName); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schema)); s.setString(3, swapNull(table)); s.setBoolean(4, unique); s.setInt(5, approximateInInt); return s.executeQuery(); } ///////////////////////////////////////////////////////////////////////// // // JDBC 2.0 - New public methods // ///////////////////////////////////////////////////////////////////////// /** * JDBC 2.0 * * Does the database support the given result set type? * * @param type defined in java.sql.ResultSet * @return true if so * @see Connection */ public boolean supportsResultSetType(int type) { if ((type == JDBC20Translation.TYPE_FORWARD_ONLY) || (type == JDBC20Translation.TYPE_SCROLL_INSENSITIVE)) { return true; } //we don't support TYPE_SCROLL_SENSITIVE yet. return false; } /** * JDBC 2.0 * * Does the database support the concurrency type in combination * with the given result set type? * * @param type defined in java.sql.ResultSet * @param concurrency type defined in java.sql.ResultSet * @return true if so * @see Connection */ public boolean supportsResultSetConcurrency(int type, int concurrency) { if (type == JDBC20Translation.TYPE_SCROLL_SENSITIVE) { // (TYPE_SCROLL_SENSITIVE, *) return false; } else { // (FORWARD_ONLY, CONCUR_UPDATABLE) // (FORWARD_ONLY, CONCUR_READ_ONLY) // (TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE) // (TYPE_SCROLL_INSENSITIVE, READ_ONLY) return true; } } /** * JDBC 2.0 * * Determine whether a result set's updates are visible. * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if updates are visible for the result set type */ public boolean ownUpdatesAreVisible(int type) { if (type == JDBC20Translation.TYPE_SCROLL_INSENSITIVE) { return true; } else { return false; } } /** * JDBC 2.0 * * Determine whether a result set's deletes are visible. * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if deletes are visible for the result set type */ public boolean ownDeletesAreVisible(int type) { if (type == JDBC20Translation.TYPE_SCROLL_INSENSITIVE) { return true; } else { return false; } } /** * JDBC 2.0 * * Determine whether a result set's inserts are visible. * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if inserts are visible for the result set type */ public boolean ownInsertsAreVisible(int type) { return false; } // Since Derby materializes a forward only ResultSet incrementally, it is // possible to see changes made by others and hence following 3 metadata // calls will return true for forward only ResultSets. /** * JDBC 2.0 * * Determine whether updates made by others are visible. * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if updates are visible for the result set type */ public boolean othersUpdatesAreVisible(int type) { if (type == JDBC20Translation.TYPE_FORWARD_ONLY) return true; return false; } /** * JDBC 2.0 * * Determine whether deletes made by others are visible. * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if deletes are visible for the result set type */ public boolean othersDeletesAreVisible(int type) { if (type == JDBC20Translation.TYPE_FORWARD_ONLY) return true; return false; } /** * JDBC 2.0 * * Determine whether inserts made by others are visible. * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if inserts are visible for the result set type */ public boolean othersInsertsAreVisible(int type) { if (type == JDBC20Translation.TYPE_FORWARD_ONLY) return true; return false; } /** * JDBC 2.0 * * Determine whether or not a visible row update can be detected by * calling ResultSet.rowUpdated(). * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if updates are detected by the resultset type */ public boolean updatesAreDetected(int type) { if (type == JDBC20Translation.TYPE_SCROLL_INSENSITIVE) { return true; } else { // For forward only resultsets, we move to before the next // row after a update and that is why updatesAreDetected // returns false. return false; } } /** * JDBC 2.0 * * Determine whether or not a visible row delete can be detected by * calling ResultSet.rowDeleted(). If deletesAreDetected() * returns false, then deleted rows are removed from the result set. * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if deletes are detected by the resultset type */ public boolean deletesAreDetected(int type) { if (type == JDBC20Translation.TYPE_SCROLL_INSENSITIVE) { return true; } else { // For forward only resultsets, we move to before the next // row after a delete and that is why deletesAreDetected // returns false return false; } } /** * JDBC 2.0 * * Determine whether or not a visible row insert can be detected * by calling ResultSet.rowInserted(). * * @param type result set type, i.e. ResultSet.TYPE_XXX * @return true if inserts are detected by the resultset type */ public boolean insertsAreDetected(int type) { return false; } /** * JDBC 2.0 * * Return true if the driver supports batch updates, else return false. * */ public boolean supportsBatchUpdates() { return true; } /** * JDBC 2.0 * * Get a description of the user-defined types defined in a particular * schema. Schema specific UDTs may have type JAVA_OBJECT, STRUCT, * or DISTINCT. * * <P>Only types matching the catalog, schema, type name and type * criteria are returned. They are ordered by DATA_TYPE, TYPE_SCHEM * and TYPE_NAME. The type name parameter may be a fully qualified * name. In this case, the catalog and schemaPattern parameters are * ignored. * * <P>Each type description has the following columns: * <OL> * <LI><B>TYPE_CAT</B> String => the type's catalog (may be null) * <LI><B>TYPE_SCHEM</B> String => type's schema (may be null) * <LI><B>TYPE_NAME</B> String => type name * <LI><B>CLASS_NAME</B> String => Java class name * <LI><B>DATA_TYPE</B> String => type value defined in java.sql.Types. * One of JAVA_OBJECT, STRUCT, or DISTINCT * <LI><B>REMARKS</B> String => explanatory comment on the type * <LI><B>BASE_TYPE</B> short => type code of the source type of * a DISTINCT type or the type that implements the user-generated * reference type of the SELF_REFERENCING_COLUMN of a structured * type as defined in java.sql.Types (<code>null</code> if * DATA_TYPE is not DISTINCT or not STRUCT with * REFERENCE_GENERATION = USER_DEFINED) * </OL> * * <P><B>Note:</B> If the driver does not support UDTs then an empty * result set is returned. * * @param catalog a catalog name; "" retrieves those without a * catalog; null means drop catalog name from the selection criteria * @param schemaPattern a schema name pattern; "" retrieves those * without a schema * @param typeNamePattern a type name pattern; may be a fully qualified * name * @param types a list of user-named types to include (JAVA_OBJECT, * STRUCT, or DISTINCT); null returns all types * @return ResultSet - each row is a type description * @exception SQLException if a database-access error occurs. */ public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { //we don't have support for catalog names //we don't have java class types per schema, instead it's per database and hence //we ignore schemapattern. //the only type of user-named types we support are JAVA_OBJECT synchronized (getConnectionSynchronization()) { setupContextStack(); ResultSet rs = null; int getClassTypes = 0; try { String queryText = getQueryDescriptions(false).getProperty("getUDTs"); if (types != null && types.length >= 1) { for (int i=0; i<types.length; i++){ if (types[i] == java.sql.Types.JAVA_OBJECT) getClassTypes = 1; } } else getClassTypes = 1; PreparedStatement s = getEmbedConnection().prepareMetaDataStatement(queryText); s.setInt(1, java.sql.Types.JAVA_OBJECT); s.setString(2, catalog); s.setString(3, schemaPattern); s.setString(4, swapNull(typeNamePattern)); s.setInt(5, getClassTypes); rs = s.executeQuery(); } finally { restoreContextStack(); } return rs; } } /** * JDBC 2.0 * * Return the connection that produced this metadata object. * */ public Connection getConnection() { return getEmbedConnection().getApplicationConnection(); } /** Following methods are for the new JDBC 3.0 methods in java.sql.DatabaseMetaData (see the JDBC 3.0 spec). We have the JDBC 3.0 methods in Local20 package, so we don't have to have a new class in Local30. The new JDBC 3.0 methods don't make use of any new JDBC3.0 classes and so this will work fine in jdbc2.0 configuration. */ ///////////////////////////////////////////////////////////////////////// // // JDBC 3.0 - New public methods // ///////////////////////////////////////////////////////////////////////// /** * JDBC 3.0 * * Retrieves whether this database supports statement pooling. * * @return true if statement pooling is supported; false otherwise */ public boolean supportsStatementPooling() { return false; } /** * JDBC 3.0 * * Retrieves whether this database supports savepoints. * * @return true if savepoints are supported; false otherwise */ public boolean supportsSavepoints() { return true; } /** * JDBC 3.0 * * Retrieves whether this database supports named parameters to callable statements. * * @return true if named parameters are supported; false otherwise */ public boolean supportsNamedParameters() { return false; } /** * JDBC 3.0 * * Retrieves whether it is possible to have multiple ResultSet objects returned from a * CallableStatement object simultaneously. * * @return true if a CallableStatement object can return multiple ResultSet objects * simultaneously; false otherwise */ public boolean supportsMultipleOpenResults() { return true; } /** * JDBC 3.0 * * Retrieves whether auto-generated keys can be retrieved after a statement * has been executed. * * @return true if auto-generated keys can be retrieved after a statement has * executed; false otherwise */ public boolean supportsGetGeneratedKeys() { /* * Currently reverting the returned value to false until there * is more support for autogenerated keys in Derby. * (such as support for specifying the returned columns for * the autogenerated key) */ return false; } /** * JDBC 3.0 * * Retrieves whether this database supports the given result set holdability. * * @param holdability - one of the following constants: * ResultSet.HOLD_CURSORS_OVER_COMMIT or ResultSet.CLOSE_CURSORS_AT_COMMIT * @return true if so; false otherwise * executed; false otherwise */ public boolean supportsResultSetHoldability(int holdability) { return true; } /** * JDBC 3.0 * * Retrieves the default holdability of this ResultSet object. * * @return the default holdability which is ResultSet.HOLD_CURSORS_OVER_COMMIT */ public int getResultSetHoldability() { return JDBC30Translation.HOLD_CURSORS_OVER_COMMIT; } /** * JDBC 3.0 * * Retrieves the major version number of the underlying database. * * @return the underlying database's major version */ public int getDatabaseMajorVersion() { ProductVersionHolder pvh = Monitor.getMonitor().getEngineVersion(); if (pvh == null) { return -1; } return pvh.getMajorVersion(); } /** * JDBC 3.0 * * Retrieves the minor version number of the underlying database. * * @return the underlying database's minor version */ public int getDatabaseMinorVersion() { ProductVersionHolder pvh = Monitor.getMonitor().getEngineVersion(); if (pvh == null) { return -1; } return pvh.getMinorVersion(); } /** * JDBC 3.0 * * Retrieves the major JDBC version number for this driver. * * @return JDBC version major number */ public int getJDBCMajorVersion() { return 3; } /** * JDBC 3.0 * * Retrieves the minor JDBC version number for this driver. * * @return JDBC version minor number */ public int getJDBCMinorVersion() { return 0; } /** * JDBC 3.0 * * Indicates whether the SQLSTATEs returned by SQLException.getSQLState * is X/Open (now known as Open Group) SQL CLI or SQL99. * * @return the type of SQLSTATEs, one of: sqlStateXOpen or sqlStateSQL99 */ public int getSQLStateType() { return JDBC30Translation.SQL_STATE_SQL99; } /** * JDBC 3.0 * * Indicates whether updates made to a LOB are made on a copy or * directly to the LOB. * * @return true if updates are made to a copy of the LOB; false if * updates are made directly to the LOB * @exception SQLException Feature not implemented for now. */ public boolean locatorsUpdateCopy() throws SQLException { return false; } /** * JDBC 3.0 * * Retrieves a description of the user-defined type (UDT) hierarchies defined * in a particular schema in this database. Only the immediate super type/ sub type * relationship is modeled. * * @param catalog - a catalog name; "" retrieves those without a catalog; * null means drop catalog name from the selection criteria * @param schemaPattern - a schema name pattern; "" retrieves those without a schema * @param typeNamePattern - a UDT name pattern; may be a fully-qualified name * @return a ResultSet object in which a row gives information about the designated UDT * @exception SQLException Feature not implemented for now. */ public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { return getSimpleQuery("getSuperTypes"); } /** * JDBC 3.0 * * Retrieves a description of the table hierarchies defined in a particular * schema in this database. * * @param catalog - a catalog name; "" retrieves those without a catalog; * null means drop catalog name from the selection criteria * @param schemaPattern - a schema name pattern; "" retrieves those without a schema * @param typeNamePattern - a UDT name pattern; may be a fully-qualified name * @return a ResultSet object in which each row is a type description * @exception SQLException if a database access error occurs */ public ResultSet getSuperTables(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { return getSimpleQuery("getSuperTables"); } /** * JDBC 3.0 * * Retrieves a description of the given attribute of the given type for a * user-defined type (UDT) that is available in the given schema and catalog. * * @param catalog - a catalog name; must match the catalog name as it is * stored in the database; "" retrieves those without a catalog; null means that * the catalog name should not be used to narrow the search * @param schemaPattern - a schema name pattern; "" retrieves those without a schema; * null means that the schema name should not be used to narrow the search * @param typeNamePattern - a type name pattern; must match the type name as it is * stored in the database * @param attributeNamePattern - an attribute name pattern; must match the attribute * name as it is declared in the database * @return a ResultSet object in which each row is a type description * @exception SQLException if a database access error occurs. */ public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { return getSimpleQuery("getAttributes"); } ///////////////////////////////////////////////////////////////////////// // // JDBC 4.0 - New public methods // ///////////////////////////////////////////////////////////////////////// /** * JDBC 4.0 * * <p>Returns a list of the client info properties supported by * the driver. The result set contains the following columns: * * <p> * <ol> * <li>NAME String=&gt; The name of the client info property.</li> * <li>MAX_LEN int=&gt; The maximum length of the value for the * property.</li> * <li>DEFAULT_VALUE String=&gt; The default value of the property.</li> * <li>DESCRIPTION String=&gt; A description of the property.</li> * </ol> * * <p>The <code>ResultSet</code> is sorted by the NAME column. * * @return A <code>ResultSet</code> object; each row is a * supported client info property * @exception SQLException if an error occurs */ public ResultSet getClientInfoProperties() throws SQLException { return getSimpleQuery("getClientInfoProperties"); } /** * JDBC 4.0 * * <p>Get the schema names available in this database. The results * are ordered by schema name. * * <p>The schema columns are: * <ol> * <li><strong>TABLE_SCHEM</strong> String =&gt; schema name</li> * <li><strong>TABLE_CATALOG</strong> String =&gt; catalog name * (may be <code>null</code>)</li> * </ol> * * @param catalog catalog name used to narrow down the search; "" * means no catalog, <code>null</code> means any catalog * @param schemaPattern schema name used to narrow down the * search, <code>null</code> means schema name should not be used * to narrow down search * @return a <code>ResultSet</code> object in which each row is a * schema description * @exception SQLException if a database error occurs */ public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { PreparedStatement s = getPreparedQuery("getSchemas"); s.setString(1, swapNull(catalog)); s.setString(2, swapNull(schemaPattern)); return s.executeQuery(); } ////////////////////////////////////////////////////////////// // // MISC // ////////////////////////////////////////////////////////////// /** * Get metadata that the client driver will cache. The metadata is * fetched using SYSIBM.METADATA (found in metadata_net.properties). * * @return the result set returned by SYSIBM.METADATA * @exception SQLException if a database error occurs */ public ResultSet getClientCachedMetaData() throws SQLException { return getSimpleQuery("METADATA", true); } /* * utility helper routines: */ /** * Execute a query in metadata.properties (or SPS in the SYS * schema) or metadata_net.properties (or SPS in the SYSIBM * schema). * * @param nameKey the name of the query * @param net if <code>true</code>, execute a query in * metadata_net.properties; otherwise, execute a query in * metadata.properties * @return a <code>ResultSet</code> value * @exception SQLException if a database error occurs */ private ResultSet getSimpleQuery(String nameKey, boolean net) throws SQLException { PreparedStatement ps = getPreparedQuery(nameKey, net); if (ps == null) return null; return ps.executeQuery(); } /** * Execute a query in metadata.properties, or an SPS in the SYS * schema. * * @param nameKey the name of the query * @return a <code>ResultSet</code> value * @exception SQLException if a database error occurs */ protected ResultSet getSimpleQuery(String nameKey) throws SQLException { return getSimpleQuery(nameKey, false); } /** * Get a stored prepared statement from the system tables. * * @param nameKey the name of the query * @param net if <code>true</code>, find query in SYSIBM schema; * otherwise, find query in SYS schema * @return a <code>PreparedStatement</code> value * @exception SQLException if a database error occurs */ private PreparedStatement getPreparedQueryUsingSystemTables(String nameKey, boolean net) throws SQLException { synchronized (getConnectionSynchronization()) { setupContextStack(); PreparedStatement ps = null; try { String queryText = getQueryDescriptions(net).getProperty(nameKey); if (queryText == null) { throw Util.notImplemented(nameKey); } ps = prepareSPS(nameKey, queryText, net); } catch (Throwable t) { throw handleException(t); } finally { restoreContextStack(); } return ps; } } /** * Either get the prepared query for the metadata call from the * system tables, or from the metadata.properties or * metadata_net.properties file. * In soft upgrade mode, the queries stored in the system tables * might not be upto date with the Derby engine release because * system tables can't be modified in backward incompatible way in * soft upgrade mode. Because of this, if the database is in * soft upgrade mode, get the queries from metadata.properties * file rather than from the system tables. * * Getting queries from metadata(_net).properties might cause problems * if system catalogs have been changed between versions either by * addition of columns or have new catalogs. To continue * to support soft upgrade from older versions of database, find * query that most closely matches database dictionary version. * * @param queryName Name of the metadata query for which we need * a prepared statement * @param net if <code>true</code>, use metadata_net.properties * instead of metadata.properties * @return PreparedStatement * @exception SQLException if a database error occurs */ private PreparedStatement getPreparedQuery(String queryName, boolean net) throws SQLException { PreparedStatement s; //We can safely goto system table since we are not in soft upgrade //mode and hence metadata sql in system tables are uptodate //with this Derby release. if (notInSoftUpgradeMode()) s = getPreparedQueryUsingSystemTables(queryName, net); else { try { //Can't use stored prepared statements because we are in soft upgrade //mode and hence need to get metadata sql from metadata.properties file //or metadata_net.properties String queryText = getQueryFromDescription(queryName, net); s = getEmbedConnection().prepareMetaDataStatement(queryText); } catch (Throwable t) { throw handleException(t); } } return s; } /** * Get a prepared query from system tables or metadata.properties. * * @param queryName name of the query * @return a <code>PreparedStatement</code> value * @exception SQLException if a database error occurs */ protected PreparedStatement getPreparedQuery(String queryName) throws SQLException { return getPreparedQuery(queryName, false); } /** * Given a queryName, find closest match in queryDescriptions. This method * should be called in soft-upgrade mode only, where current software version * doesn't match dictionary version. For these cases, there may be * multiple entries in queryDescriptions for given queryName. Find a * version of the query that closely matches dictionary version. * * This method is currently coded to handle two specific queries, * getColumnPrivileges and getTablePrivileges. Derby databases that are 10.1 * or earlier will not have new system tables added for 10.2 for privileges. * * It should be possible to automate finding closest match by generating * all Major_Minor versions between software version and dictionary version * and try each one from Dictionary version to current version. Since only * needed for two queries, overhead may not be worth it yet. * * @param queryName name of the query * @param net if <code>true</code>, get the query from * metadata_net.properties instead of metadata.properties * @return the query text * @exception StandardException if an error occurs */ private String getQueryFromDescription(String queryName, boolean net) throws StandardException { DataDictionary dd = getLanguageConnectionContext().getDataDictionary(); // If dictionary version is below 10.2, special case // getColumnPrivileges and getTablePrivileges since new system tables // for privileges wouldn't be present. if (!dd.checkVersion(DataDictionary.DD_VERSION_DERBY_10_2, null)) { if (queryName.equals("getColumnPrivileges")) queryName = "getColumnPrivileges_10_1"; if (queryName.equals("getTablePrivileges")) queryName = "getTablePrivileges_10_1"; } return getQueryDescriptions(net).getProperty(queryName); } /* ** Given a SPS name and a query text it returns a ** java.sql.PreparedStatement for the SPS. If the SPS ** doeesn't exist is created. ** */ private PreparedStatement prepareSPS(String spsName, String spsText, boolean net) throws StandardException, SQLException { LanguageConnectionContext lcc = getLanguageConnectionContext(); /* We now need to do this in sub transaction because we could possibly recompile SPS * later, and the recompile is in a sub transaction, and will update the SYSSTATEMENTS * entry. Don't want to block. */ lcc.beginNestedTransaction(true); DataDictionary dd = getLanguageConnectionContext().getDataDictionary(); SPSDescriptor spsd = dd.getSPSDescriptor( spsName, net ? dd.getSysIBMSchemaDescriptor() : dd.getSystemSchemaDescriptor()); lcc.commitNestedTransaction(); if (spsd == null) { throw Util.notImplemented(spsName); } /* manish: There should be a nicer way of getting a java.sql.PreparedStatement from an SPS descriptor! */ /* ** It is unnecessarily expensive to get the ** the statement, and then send an EXECUTE ** statement, but we have no (easy) way of turning ** the statement into a java.sql.PreparedStatement. */ String queryText = "EXECUTE STATEMENT " + (net ? "SYSIBM" : "SYS") + ".\"" + spsName + "\""; return getEmbedConnection().prepareMetaDataStatement(queryText); } static final protected String swapNull(String s) { return (s == null ? "%" : s); } /** * Gets the constant action factory * * @return the constant action factory. * * @exception StandardException Thrown on failur4e */ private GenericConstantActionFactory getGenericConstantActionFactory() throws StandardException { if ( constantActionFactory == null ) { GenericExecutionFactory execFactory = (GenericExecutionFactory) getLanguageConnectionContext().getLanguageConnectionFactory().getExecutionFactory(); constantActionFactory = execFactory.getConstantActionFactory(); } return constantActionFactory; } /** * Gets the LanguageConnectionContext for this connection. * * @return the lcc for this connection * */ private LanguageConnectionContext getLanguageConnectionContext() { return getEmbedConnection().getLanguageConnection(); } /* ** Priv block code, moved out of the old Java2 version. */ /** * Loads the query descriptions from metadata.properties and * metadata_net.properties into <code>queryDescriptions</code> and * <code>queryDescriptions_net</code>. */ private void loadQueryDescriptions() { java.security.AccessController.doPrivileged(this); } /** * Performs a privileged action. Reads the query descriptions. * * @return <code>null</code> */ public final Object run() { // SECURITY PERMISSION - IP3 PBloadQueryDescriptions(); return null; } }
[ "durieuxthomas@hotmail.com" ]
durieuxthomas@hotmail.com
7b09ee7b895af935ff419d61f2fd14037eaf151f
99b0300dd14b208e6e060f68c5b71588521bdd72
/src/cn/sharesdk/onekeyshare/PlatformGridView.java
077cd27dd316ef056c20dc4935f69762d1e892cc
[ "MIT" ]
permissive
chiemy/ShareSdkThridPartyLoginDemo
50820bfe69ef4d268397d3bc04edf57e33e6ce75
d853eee54aa4b7210de75fe1c6872998c81dd4f2
refs/heads/master
2020-04-05T23:40:47.097573
2014-04-22T10:31:40
2014-04-22T10:31:40
19,025,811
2
1
null
null
null
null
UTF-8
Java
false
false
14,753
java
/* * 官网地站:http://www.ShareSDK.cn * 技术支持QQ: 4006852216 * 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复) * * Copyright (c) 2013年 ShareSDK.cn. All rights reserved. */ package cn.sharesdk.onekeyshare; import cn.sharesdk.demo.tpl.R; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.framework.utils.UIHandler; /** * 平台宫格列表显示工具。 * <p> * PlatformGridView对“android.support”包有依赖,因此请注意检查您项目中是 *否已经集成了相应的jar包 */ public class PlatformGridView extends LinearLayout implements OnPageChangeListener, OnClickListener, Callback { private static final int MSG_PLATFORM_LIST_GOT = 1; // 每行显示的格数 private int LINE_PER_PAGE; // 每页显示的行数 private int COLUMN_PER_LINE; // 每页显示的格数 private int PAGE_SIZE; // 宫格容器 private ViewPager pager; // 页面指示器 private ImageView[] points; private Bitmap grayPoint; private Bitmap whitePoint; // 是否不跳转EditPage而直接分享 private boolean silent; // 平台数据 private Platform[] platformList; // 从外部传进来的分享数据(含初始化数据) private HashMap<String, Object> reqData; private OnekeyShare parent; private ArrayList<CustomerLogo> customers; public PlatformGridView(Context context) { super(context); init(context); } public PlatformGridView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(final Context context) { calPageSize(); setOrientation(VERTICAL); pager = new ViewPager(context); disableOverScrollMode(pager); pager.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); pager.setOnPageChangeListener(this); addView(pager); // 为了更好的ui效果,开启子线程获取平台列表 new Thread(){ public void run() { platformList = ShareSDK.getPlatformList(context); UIHandler.sendEmptyMessage(MSG_PLATFORM_LIST_GOT, PlatformGridView.this); } }.start(); } private void calPageSize() { float scrW = cn.sharesdk.framework.utils.R.getScreenWidth(getContext()); float scrH = cn.sharesdk.framework.utils.R.getScreenHeight(getContext()); float whR = scrW / scrH; if (whR < 0.6) { COLUMN_PER_LINE = 3; LINE_PER_PAGE = 3; } else if (whR < 0.75) { COLUMN_PER_LINE = 3; LINE_PER_PAGE = 2; } else { LINE_PER_PAGE = 1; if (whR >= 1.75) { COLUMN_PER_LINE = 6; } else if (whR >= 1.5) { COLUMN_PER_LINE = 5; } else if (whR >= 1.3) { COLUMN_PER_LINE = 4; } else { COLUMN_PER_LINE = 3; } } PAGE_SIZE = COLUMN_PER_LINE * LINE_PER_PAGE; } public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_PLATFORM_LIST_GOT: { afterPlatformListGot(); } break; } return false; } /** 初始化宫格列表ui */ public void afterPlatformListGot() { PlatformAdapter adapter = new PlatformAdapter(this); pager.setAdapter(adapter); int pageCount = 0; if (platformList != null) { int cusSize = customers == null ? 0 : customers.size(); int platSize = platformList == null ? 0 : platformList.length; int size = platSize + cusSize; pageCount = size / PAGE_SIZE; if (size % PAGE_SIZE > 0) { pageCount++; } } points = new ImageView[pageCount]; if (points.length <= 0) { return; } Context context = getContext(); LinearLayout llPoints = new LinearLayout(context); // 如果页面总是超过1,则设置页面指示器 llPoints.setVisibility(pageCount > 1 ? View.VISIBLE: View.GONE); LayoutParams lpLl = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lpLl.gravity = Gravity.CENTER_HORIZONTAL; llPoints.setLayoutParams(lpLl); addView(llPoints); int dp_5 = cn.sharesdk.framework.utils.R.dipToPx(context, 5); grayPoint = BitmapFactory.decodeResource(getResources(), R.drawable.gray_point); whitePoint = BitmapFactory.decodeResource(getResources(), R.drawable.white_point); for (int i = 0; i < pageCount; i++) { points[i] = new ImageView(context); points[i].setScaleType(ScaleType.CENTER_INSIDE); points[i].setImageBitmap(grayPoint); LayoutParams lpIv = new LayoutParams(dp_5, dp_5); lpIv.setMargins(dp_5, dp_5, dp_5, 0); points[i].setLayoutParams(lpIv); llPoints.addView(points[i]); } int curPage = pager.getCurrentItem(); points[curPage].setImageBitmap(whitePoint); } /** 屏幕旋转后,此方法会被调用,以刷新宫格列表的布局 */ public void onConfigurationChanged() { int curFirst = pager.getCurrentItem() * PAGE_SIZE; calPageSize(); int newPage = curFirst / PAGE_SIZE; removeViewAt(1); afterPlatformListGot(); ViewGroup.LayoutParams lp = pager.getLayoutParams(); View v = pager.getChildAt(0); v.measure(0, 0); lp.height = v.getMeasuredHeight(); pager.setLayoutParams(lp); pager.setCurrentItem(newPage); } public void onPageScrollStateChanged(int state) { if (ViewPager.SCROLL_STATE_IDLE == state) { for (int i = 0; i < points.length; i++) { points[i].setImageBitmap(grayPoint); } int curPage = pager.getCurrentItem(); points[curPage].setImageBitmap(whitePoint); } } public void onPageScrolled(int arg0, float arg1, int arg2) { } public void onPageSelected(int position) { } /** * 设置页面初始化和分享操作需要的数据 * <p> * 此方法在{@link OnekeyShare}的UI初始化中被调用 * * @param intent 携带初始化数据的Intent */ public void setData(HashMap<String, Object> data, boolean silent) { reqData = data; this.silent = silent; } /** 设置自己图标和点击事件 */ public void setCustomerLogos(ArrayList<CustomerLogo> customers) { this.customers = customers; } /** 设置分享操作的回调页面 */ public void setParent(OnekeyShare parent) { this.parent = parent; } public void onClick(View v) { Platform plat = (Platform) v.getTag(); if (plat != null) { if (silent) { HashMap<Platform, HashMap<String, Object>> shareData = new HashMap<Platform, HashMap<String,Object>>(); shareData.put(plat, reqData); parent.share(shareData); return; } String name = plat.getName(); parent.setPlatform(name); // EditPage不支持微信平台、Google+、QQ分享、Pinterest、信息和邮件,总是执行直接分享 if (ShareCore.isUseClientToShare(getContext(), name)) { HashMap<Platform, HashMap<String, Object>> shareData = new HashMap<Platform, HashMap<String,Object>>(); shareData.put(plat, reqData); parent.share(shareData); return; } // 跳转EditPage分享 EditPage page = new EditPage(); page.setShareData(reqData); page.setParent(parent); if ("true".equals(String.valueOf(reqData.get("dialogMode")))) { page.setDialogMode(); } page.show(parent.getContext(), null); parent.finish(); } } // 禁用ViewPage OverScroll的“发光”效果 private void disableOverScrollMode(View view) { if (Build.VERSION.SDK_INT < 9) { return; } try { Method m = View.class.getMethod("setOverScrollMode", new Class[] { Integer.TYPE }); m.setAccessible(true); m.invoke(view, new Object[] { Integer.valueOf(2) }); } catch (Throwable t) { t.printStackTrace(); } } /** 宫格列表数据适配器 */ private static class PlatformAdapter extends PagerAdapter { // 宫格列表元素 private GridView[] girds; private List<Object> logos; private OnClickListener callback; // 行数 private int lines; private PlatformGridView platformGridView; public PlatformAdapter(PlatformGridView platformGridView) { this.platformGridView = platformGridView; logos = new ArrayList<Object>(); Platform[] platforms = platformGridView.platformList; if (platforms != null) { logos.addAll(Arrays.asList(platforms)); } ArrayList<CustomerLogo> customers = platformGridView.customers; if (customers != null) { logos.addAll(customers); } this.callback = platformGridView; girds = null; if (logos != null) { int size = logos.size(); int PAGE_SIZE = platformGridView.PAGE_SIZE; int pageCount = size / PAGE_SIZE; if (size % PAGE_SIZE > 0) { pageCount++; } girds = new GridView[pageCount]; } } public int getCount() { return girds == null ? 0 : girds.length; } public boolean isViewFromObject(View view, Object obj) { return view == obj; } public Object instantiateItem(ViewGroup container, int position) { if (girds[position] == null) { int pageSize = platformGridView.PAGE_SIZE; int curSize = pageSize * position; int listSize = logos == null ? 0 : logos.size(); if (curSize + pageSize > listSize) { pageSize = listSize - curSize; } Object[] gridBean = new Object[pageSize]; for (int i = 0; i < pageSize; i++) { gridBean[i] = logos.get(curSize + i); } if (position == 0) { int COLUMN_PER_LINE = platformGridView.COLUMN_PER_LINE; lines = gridBean.length / COLUMN_PER_LINE; if (gridBean.length % COLUMN_PER_LINE > 0) { lines++; } } girds[position] = new GridView(this); girds[position].setData(lines, gridBean); } if (position == 0) { ViewGroup.LayoutParams lp = container.getLayoutParams(); if (lp.height <= 0) { girds[position].measure(0, 0); lp.height = girds[position].getMeasuredHeight(); container.setLayoutParams(lp); } } container.addView(girds[position]); return girds[position]; } public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } /** 简易的宫格列表控件 */ private static class GridView extends LinearLayout { private Object[] beans; private OnClickListener callback; private int lines; private PlatformAdapter platformAdapter; public GridView(PlatformAdapter platformAdapter) { super(platformAdapter.platformGridView.getContext()); this.platformAdapter = platformAdapter; this.callback = platformAdapter.callback; } public void setData(int lines, Object[] beans) { this.lines = lines; this.beans = beans; init(); } private void init() { int dp_5 = cn.sharesdk.framework.utils.R.dipToPx(getContext(), 5); setPadding(0, dp_5, 0, dp_5); setOrientation(VERTICAL); int size = beans == null ? 0 : beans.length; int COLUMN_PER_LINE = platformAdapter.platformGridView.COLUMN_PER_LINE; int lineSize = size / COLUMN_PER_LINE; if (size % COLUMN_PER_LINE > 0) { lineSize++; } LayoutParams lp = new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); lp.weight = 1; for (int i = 0; i < lines; i++) { LinearLayout llLine = new LinearLayout(getContext()); llLine.setLayoutParams(lp); llLine.setPadding(dp_5, 0, dp_5, 0); addView(llLine); if (i >= lineSize) { continue; } for (int j = 0; j < COLUMN_PER_LINE; j++) { final int index = i * COLUMN_PER_LINE + j; if (index >= size) { LinearLayout llItem = new LinearLayout(getContext()); llItem.setLayoutParams(lp); llLine.addView(llItem); continue; } final LinearLayout llItem = getView(index, callback, getContext()); llItem.setTag(beans[index]); llItem.setLayoutParams(lp); llLine.addView(llItem); } } } private LinearLayout getView(int position, OnClickListener ocL, Context context) { Bitmap logo; String label; OnClickListener listener; if (beans[position] instanceof Platform) { logo = getIcon((Platform) beans[position]); label = getName((Platform) beans[position]); listener = ocL; } else { logo = ((CustomerLogo) beans[position]).logo; label = ((CustomerLogo) beans[position]).label; listener = ((CustomerLogo) beans[position]).listener; } LinearLayout ll = new LinearLayout(context); ll.setOrientation(LinearLayout.VERTICAL); ImageView iv = new ImageView(context); int dp_5 = cn.sharesdk.framework.utils.R.dipToPx(context, 5); iv.setPadding(dp_5, dp_5, dp_5, dp_5); iv.setScaleType(ScaleType.CENTER_INSIDE); LinearLayout.LayoutParams lpIv = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lpIv.setMargins(dp_5, dp_5, dp_5, dp_5); lpIv.gravity = Gravity.CENTER_HORIZONTAL; iv.setLayoutParams(lpIv); iv.setImageBitmap(logo); ll.addView(iv); TextView tv = new TextView(context); tv.setTextColor(0xffffffff); tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); tv.setSingleLine(); tv.setGravity(Gravity.CENTER_HORIZONTAL); tv.setIncludeFontPadding(false); LinearLayout.LayoutParams lpTv = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); lpTv.weight = 1; lpTv.setMargins(dp_5, 0, dp_5, dp_5); tv.setLayoutParams(lpTv); tv.setText(label); ll.addView(tv); ll.setOnClickListener(listener); return ll; } private Bitmap getIcon(Platform plat) { if (plat == null) { return null; } String name = plat.getName(); if (name == null) { return null; } String resName = "logo_" + plat.getName(); int resId = cn.sharesdk.framework.utils.R.getResId(R.drawable.class, resName); return BitmapFactory.decodeResource(getResources(), resId); } private String getName(Platform plat) { if (plat == null) { return ""; } String name = plat.getName(); if (name == null) { return ""; } int resId = cn.sharesdk.framework.utils.R.getStringRes(getContext(), plat.getName()); return getContext().getString(resId); } } }
[ "luobl@asiacom-online.com" ]
luobl@asiacom-online.com
a7facf9cf1cf9ff37052faddcbece6ae11ed5de8
52bdf7c58fc718c1a017534b0211f4070cd72002
/MethodExercize/src/CharactersinRange.java
62d8bbbed6dd3a520f90ea8224d792c0cbf1ec03
[]
no_license
knaevKMK/Java_Fundsmentals
08ef75914cb0f3c72db713bf2c839afe1c13e008
3768bac72cfdba13a09268c531c3feb8254cb6fd
refs/heads/main
2023-02-01T04:52:13.089544
2020-12-20T20:23:57
2020-12-20T20:23:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
581
java
import java.util.Scanner; public class CharactersinRange { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); char start = scanner.nextLine().charAt(0); char end = scanner.nextLine().charAt(0); if (start < end) { printCharBetweenStartEnd(start, end); } else { printCharBetweenStartEnd(end, start); } } public static void printCharBetweenStartEnd(char a, char b) { for (char i = ++a; i < b; i++) { System.out.print(i + " "); } } }
[ "knev@mail.bg" ]
knev@mail.bg
0e5b838aca40d82cd3da599e437259a82604b0d9
7a3b2a3b57307a04be77794b7ca7d20d9fc9b584
/core/src/main/java/com/graphhopper/routing/util/countryrules/europe/AustriaCountryRule.java
6fb3accdb9ab78d5d6829fa707438beef9bb61c8
[ "Apache-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "MIT", "ODbL-1.0" ]
permissive
boldtrn/graphhopper
d088bf4714886c8f347326bfe7e0932b68977ecb
19dbd9700883bd474b8ef6aadfea1f0ee49632ca
refs/heads/master
2023-04-28T00:06:26.923241
2023-04-19T07:50:45
2023-04-19T07:50:48
46,709,952
1
1
Apache-2.0
2021-03-24T16:45:48
2015-11-23T09:28:28
Java
UTF-8
Java
false
false
3,205
java
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphhopper.routing.util.countryrules.europe; import com.graphhopper.reader.ReaderWay; import com.graphhopper.routing.ev.RoadAccess; import com.graphhopper.routing.ev.RoadClass; import com.graphhopper.routing.ev.Toll; import com.graphhopper.routing.util.TransportationMode; import com.graphhopper.routing.util.countryrules.CountryRule; public class AustriaCountryRule implements CountryRule { @Override public double getMaxSpeed(ReaderWay readerWay, TransportationMode transportationMode, double currentMaxSpeed) { if (!Double.isNaN(currentMaxSpeed) || !transportationMode.isMotorVehicle()) return currentMaxSpeed; RoadClass roadClass = RoadClass.find(readerWay.getTag("highway", "")); switch (roadClass) { case MOTORWAY: return 130; case TRUNK: case PRIMARY: case SECONDARY: case TERTIARY: case UNCLASSIFIED: return 100; case RESIDENTIAL: return 50; case LIVING_STREET: return 20; default: return Double.NaN; } } @Override public RoadAccess getAccess(ReaderWay readerWay, TransportationMode transportationMode, RoadAccess currentRoadAccess) { if (currentRoadAccess != RoadAccess.YES) return currentRoadAccess; if (!transportationMode.isMotorVehicle()) return RoadAccess.YES; RoadClass roadClass = RoadClass.find(readerWay.getTag("highway", "")); switch (roadClass) { case LIVING_STREET: return RoadAccess.DESTINATION; case TRACK: return RoadAccess.FORESTRY; case PATH: case BRIDLEWAY: case CYCLEWAY: case FOOTWAY: case PEDESTRIAN: return RoadAccess.NO; default: return RoadAccess.YES; } } @Override public Toll getToll(ReaderWay readerWay, Toll currentToll) { if (currentToll != Toll.MISSING) { return currentToll; } RoadClass roadClass = RoadClass.find(readerWay.getTag("highway", "")); if (roadClass == RoadClass.MOTORWAY || roadClass == RoadClass.TRUNK) { return Toll.ALL; } return currentToll; } }
[ "noreply@github.com" ]
boldtrn.noreply@github.com
73474d4c7753b6278a7ae3f7f3a3ee71ab31c08c
653278c75ea263a55f5e9a5ebcc276b0941d0d95
/project/client/StudentSign/app/src/main/java/com/lxj/studentsign/entity/Result.java
3b406c692d889964b933b55160814e45b41ffbc8
[]
no_license
Longfd/Student-Sign-in-System
91fd99931e83dba70dd3262df2123394ef189305
a8e730111eebf7fa6876730173c0a0ea49dd6205
refs/heads/master
2020-03-14T01:41:37.002173
2018-05-17T14:40:17
2018-05-17T14:40:17
131,382,902
4
1
null
2018-05-04T17:00:23
2018-04-28T07:03:53
Java
UTF-8
Java
false
false
1,299
java
package com.lxj.studentsign.entity; import java.util.List; /** * 请求实体类 */ public class Result { public static final String RESULT_SUCCESS = "0";//请求成功 public static final String RESULT_FAILED = "1";//请求失败 private String result;//请求结果 private String msg;//请求内容 private List<ClassInfo> classInfo;//班级列表 private List<ActiveInfo> activityInfo;//活动列表 private List<UserInfo> signInfo;//学生列表 public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<ClassInfo> getClassInfo() { return classInfo; } public void setClassInfo(List<ClassInfo> classInfo) { this.classInfo = classInfo; } public List<ActiveInfo> getActivityInfo() { return activityInfo; } public void setActivityInfo(List<ActiveInfo> activityInfo) { this.activityInfo = activityInfo; } public List<UserInfo> getSignInfo() { return signInfo; } public void setSignInfo(List<UserInfo> signInfo) { this.signInfo = signInfo; } }
[ "cnsdbo@163.com" ]
cnsdbo@163.com
d9a8f992fa2d79092a6b398fde4dd61016935e22
cf3b25ebe3dbf1bf3a563811abe5e2e309252c9f
/app/src/main/java/com/example/mispubs/Modelo/Valoracion.java
56aad3ebaf9ba87dff04489d571f099a9830b5c3
[]
no_license
CarlosDez23/MisPubs
d1d2be7b6af8d102ef8f868aed8668e4e4dacca9
ca86690557c4221a967c61c20526d3b7f9f995f0
refs/heads/master
2020-12-20T18:16:26.902654
2020-02-06T10:25:30
2020-02-06T10:25:30
236,166,816
0
0
null
null
null
null
UTF-8
Java
false
false
1,835
java
package com.example.mispubs.Modelo; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Valoracion { @SerializedName("id") @Expose private Integer id; @SerializedName("idusuario") @Expose private Integer idusuario; @SerializedName("idpub") @Expose private Integer idpub; @SerializedName("valoracion") @Expose private Integer valoracion; @SerializedName("detalle") @Expose private String detalle; public Valoracion() { } public Valoracion(Integer idusuario, Integer idpub, Integer valoracion, String detalle) { this.idusuario = idusuario; this.idpub = idpub; this.valoracion = valoracion; this.detalle = detalle; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getIdusuario() { return idusuario; } public void setIdusuario(Integer idusuario) { this.idusuario = idusuario; } public Integer getIdpub() { return idpub; } public void setIdpub(Integer idpub) { this.idpub = idpub; } public Integer getValoracion() { return valoracion; } public void setValoracion(Integer valoracion) { this.valoracion = valoracion; } public String getDetalle() { return detalle; } public void setDetalle(String detalle) { this.detalle = detalle; } @Override public String toString() { return "Valoracion{" + "id=" + id + ", idusuario=" + idusuario + ", idpub=" + idpub + ", valoracion=" + valoracion + ", detalle='" + detalle + '\'' + '}'; } }
[ "52250143+CarlosDez23@users.noreply.github.com" ]
52250143+CarlosDez23@users.noreply.github.com
a9b788394cdb9d1259e1a1549dd29fb30a277ed2
f83f02b7073419251ac135bdb5893f6d0b20e64a
/workspace/Project/src/main/java/Module34/Project/App.java
9e4f6ef27864581f0e3bde96e3e6b32d3be664b9
[]
no_license
sheel2006/Mylearning
e9aebdb470bb3b0117807b4d4a8d57ff601c1402
b5a00623e48f4a4495ddb8fe362ac685cdb51bf7
refs/heads/master
2020-03-12T06:25:36.721299
2018-04-22T06:17:49
2018-04-22T06:17:49
130,484,988
0
0
null
null
null
null
UTF-8
Java
false
false
179
java
package Module34.Project; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
[ "sheel2006@gmail.com" ]
sheel2006@gmail.com
4b253d98b33f838fdae65e3a34ac03522bac6270
894f3fd5944249f07f4b64883cf64fa146fbcd05
/Source-Code/LoginActivity.java
5d70f45d2c7d474f64510b5f15d8ec504db4c017
[]
no_license
vasudevarora1996/Automated-Attendance-System
d14e81b631314ac53754144120da8b1e20e8e3a8
ead8d16a2fb47b6190b81eb870a519dea4fa4bb3
refs/heads/main
2023-05-04T00:39:57.829988
2021-05-22T08:47:32
2021-05-22T08:47:32
363,490,292
0
0
null
null
null
null
UTF-8
Java
false
false
7,022
java
package com.example.vasudev.attendancesystem; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Paint; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.PasswordTransformationMethod; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class LoginActivity extends AppCompatActivity { public SQLiteDatabase db; public int selected; public static String name12,reg12,username12,mobile12; EditText user,pass; String user1,pass1; TextView tv; public RadioButton radioButton; public RadioGroup radioGroup; @SuppressLint("WrongViewCast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); user=findViewById(R.id.user11); pass=findViewById(R.id.password11); tv=findViewById(R.id.textView10); tv.setPaintFlags(tv.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG); db(); } int x=0; @Override public void onBackPressed(){ Toast.makeText(this, "Sorry, You Can't Go Back", Toast.LENGTH_SHORT).show(); } public void showpassword(View view){ x++; if (x%2==1) pass.setTransformationMethod(null); else pass.setTransformationMethod(new PasswordTransformationMethod()); } public void db(){ db=openOrCreateDatabase("AttendanceSystem", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS AttendanceStudent(first VARCHAR,last VARCHAR,username VARCHAR ,password VARCHAR,email VARCHAR);"); db.execSQL("CREATE TABLE IF NOT EXISTS AttendanceFaculty(first VARCHAR,last VARCHAR,username VARCHAR ,password VARCHAR,email VARCHAR);"); radioGroup=findViewById(R.id.radioGroup11); } public void login(View xyz) { user1 = user.getText().toString().trim(); pass1 = pass.getText().toString().trim(); selected=radioGroup.getCheckedRadioButtonId(); if (user1.equals("") || pass1.equals("")) { show("Empty", "Field is Empty"); } else { if (selected==R.id.radioButton) { try { Cursor c = db.rawQuery("SELECT * FROM AttendanceStudent WHERE username='" + user1 + "'", null); if (c.moveToFirst()) { if (pass1.equals(c.getString(3))) { show("Success", "Logged In Successfully"); name12 = c.getString(0); reg12 = c.getString(1); username12 = c.getString(2); mobile12 = c.getString(4); Handler h = new Handler() { @Override public void handleMessage(Message msg) { Intent i = new Intent(LoginActivity.this, MainActivity.class); i.putExtra("name", name12); startActivity(i); } }; h.sendEmptyMessageDelayed(0, 1500); } else { show("Login Failed", "Password is not matched"); } } else { show("Login Failed", "Entered Details are Incorrect"); } } catch (Exception ee) { show("Error", "Cant Login"); } } else if (selected==R.id.radioButton2){ try { Cursor c = db.rawQuery("SELECT * FROM AttendanceFaculty WHERE username='" + user1 + "'", null); if (c.moveToFirst()) { if (pass1.equals(c.getString(3))) { show("Success", "Logged In Successfully"); name12 = c.getString(0); reg12 = c.getString(1); username12 = c.getString(2); mobile12 = c.getString(4); Handler h = new Handler() { @Override public void handleMessage(Message msg) { Intent i = new Intent(LoginActivity.this, MainActivity.class); i.putExtra("name", name12); startActivity(i); } }; h.sendEmptyMessageDelayed(0, 1500); } else { show("Login Failed", "Password is not matched"); } } else { show("Login Failed", "Entered Details are Incorrect"); } } catch (Exception ee) { show("Error", "Cant Login"); } } else { show("Error","Please Select Type of User"); } } } public void signup(View z){ Intent k=new Intent(this,Signup.class); startActivity(k); } public void dashboard(View view){ Toast.makeText(this, "Welcome To Dashboard !!!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this,Dashboard.class); startActivity(intent); } public void show(String title,String message){ AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.menu_login, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement return super.onOptionsItemSelected(item); } }
[ "noreply@github.com" ]
vasudevarora1996.noreply@github.com
64f222c79cb63d9f15f2f11376123f22180f5ce0
50a3f69cf06cb00baa174200b74b49d33051c874
/app/src/main/java/com/zwh/rxfingerprinter/MainActivity.java
5f71fe4e7e78fa51e4417f16f667fce571d3b111
[]
no_license
WoundedDemon/RxFingerPrinter
b64e7010eca0cd14501b70b89a985f53263ab6f5
469050201f7a97888a9377b3372b89a8c98d22c9
refs/heads/master
2021-06-21T20:20:41.345722
2017-03-20T07:21:42
2017-03-20T07:21:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,686
java
package com.zwh.rxfingerprinter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import rx.Subscriber; import rx.Subscription; import zwh.com.lib.FPerException; import zwh.com.lib.RxFingerPrinter; public class MainActivity extends AppCompatActivity { private FingerPrinterView fingerPrinterView; private int fingerErrorNum = 0; // 指纹错误次数 RxFingerPrinter rxfingerPrinter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fingerPrinterView = (FingerPrinterView) findViewById(R.id.fpv); fingerPrinterView.setOnStateChangedListener(new FingerPrinterView.OnStateChangedListener() { @Override public void onChange(int state) { if (state == FingerPrinterView.STATE_CORRECT_PWD) { fingerErrorNum = 0; Toast.makeText(MainActivity.this, "指纹识别成功", Toast.LENGTH_SHORT).show(); } if (state == FingerPrinterView.STATE_WRONG_PWD) { Toast.makeText(MainActivity.this, "指纹识别失败,还剩" + (5-fingerErrorNum) + "次机会", Toast.LENGTH_SHORT).show(); fingerPrinterView.setState(FingerPrinterView.STATE_NO_SCANING); } } }); rxfingerPrinter = new RxFingerPrinter(this); findViewById(R.id.btn_open).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fingerErrorNum = 0; rxfingerPrinter.unSubscribe(this); Subscription subscription = rxfingerPrinter.begin().subscribe(new Subscriber<Boolean>() { @Override public void onStart() { super.onStart(); if (fingerPrinterView.getState() == FingerPrinterView.STATE_SCANING) { return; } else if (fingerPrinterView.getState() == FingerPrinterView.STATE_CORRECT_PWD || fingerPrinterView.getState() == FingerPrinterView.STATE_WRONG_PWD) { fingerPrinterView.setState(FingerPrinterView.STATE_NO_SCANING); } else { fingerPrinterView.setState(FingerPrinterView.STATE_SCANING); } } @Override public void onCompleted() { } @Override public void onError(Throwable e) { if(e instanceof FPerException){ Toast.makeText(MainActivity.this,((FPerException) e).getDisplayMessage(),Toast.LENGTH_SHORT).show(); } } @Override public void onNext(Boolean aBoolean) { if(aBoolean){ fingerPrinterView.setState(FingerPrinterView.STATE_CORRECT_PWD); }else{ fingerErrorNum++; fingerPrinterView.setState(FingerPrinterView.STATE_WRONG_PWD); } } }); rxfingerPrinter.addSubscription(this,subscription); } }); } @Override protected void onDestroy() { super.onDestroy(); rxfingerPrinter.unSubscribe(this); } }
[ "616505546@qq.com" ]
616505546@qq.com
f9be1c36efbe945b0e1f75cc418e70707793c2f8
4ca6b624171d3041833f231ca888784988333bce
/app/src/main/java/com/example/gmagic/MainActivity.java
9098e5d5f5995bd4712f9919e33daeac98dbeb2d
[]
no_license
GovardhanGitHub/Gmagic
545c33296c66693df55823c2924c239f1570bbd5
a0e39a172cc58d0edb8895babd20d3ae4b3fa113
refs/heads/master
2020-12-20T02:51:46.005813
2020-01-24T05:11:21
2020-01-24T05:11:21
235,938,444
0
0
null
null
null
null
UTF-8
Java
false
false
8,110
java
package com.example.gmagic; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.content.Intent; import android.provider.Settings; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import java.io.IOException; import static com.example.gmagic.VerifyPhoneActivity.SHARED_KEY; public class MainActivity extends AppCompatActivity { Button otpBtn; public static final int RequestPermissionCode = 1; private EditText editTextMobile, editTextName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestContactPermission(savedInstanceState); } public void hideSoftKeyboard(View view){ InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } private void requestContactPermission(final Bundle bundle) { Dexter.withActivity(this) .withPermission(Manifest.permission.READ_CONTACTS) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { // permission is granted init(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { // check for permanent denial of permission if (response.isPermanentlyDenied()) { showSettingsDialog(); } } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { token.continuePermissionRequest(); } }).check(); } /** * Showing Alert Dialog with Settings option * Navigates user to app settings * NOTE: Keep proper title and message depending on your app */ private void openSettingsDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Required Permissions"); builder.setMessage("This app require permission to use awesome feature. Grant them in app settings."); builder.setPositiveButton("Take Me To SETTINGS", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 101); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } // navigating user to app settings private void showSettingsDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Need Permissions"); builder.setMessage("This app needs permission to use this feature. You can grant them in app settings."); builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); openSettings(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } private void openSettings() { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, 101); } private void init() { if (FirebaseAuth.getInstance().getCurrentUser() != null) { Intent intent = new Intent(MainActivity.this, Main3Activity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); } setContentView(R.layout.activity_main); editTextMobile = findViewById(R.id.editTextMobile); editTextName = findViewById(R.id.edName); otpBtn = findViewById(R.id.buttonContinue); otpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String mobile = editTextMobile.getText().toString().trim(); String name = editTextName.getText().toString().trim(); if (mobile.isEmpty() || mobile.length() != 10) { editTextMobile.setError("Enter a valid numbere"); editTextMobile.requestFocus(); return; } if (name.isEmpty() || name.length() < 4) { editTextName.setError("Enter a valid name"); editTextName.requestFocus(); return; } hideSoftKeyboard(v); SharedPreferences.Editor editor = getSharedPreferences(SHARED_KEY, MODE_PRIVATE).edit(); editor.putString(VerifyPhoneActivity.NAME, name); editor.putInt("FirstTime",1); editor.apply(); Intent intent = new Intent(MainActivity.this, VerifyPhoneActivity.class); intent.putExtra("mobile",mobile); startActivity(intent); } }); } } /* public void EnableRuntimePermission() { if (ActivityCompat.shouldShowRequestPermissionRationale( MainActivity.this, Manifest.permission.READ_CONTACTS)) { Toast.makeText(MainActivity.this, "CONTACTS permission allows us to Access CONTACTS app", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.READ_CONTACTS}, RequestPermissionCode); } } @Override public void onRequestPermissionsResult(int RC, String per[], int[] PResult) { switch (RC) { case RequestPermissionCode: if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "Permission Granted, Now your application can access CONTACTS.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "Permission Canceled, Now your application cannot access CONTACTS.", Toast.LENGTH_LONG).show(); } break; } }*/
[ "mopur.govardhan05@gmail.com" ]
mopur.govardhan05@gmail.com
01fdcfb9ba20bd8d209618b495553d1d66be59b8
2f05bf264bd87f533803906811ffc89685688dba
/Java_024_Lambda/src/com/callor/lambda/service/impl/OnClickServiceImplV1.java
8ad59587412834f2787faf3d8191554d7b7b6dad
[]
no_license
dkdud8140/Biz_403_2021_03_Java
3d6a9cf8cd692b78047606665fd888a8ca6ed80f
a24f241a8d12e13c9d6a8a6be78a6b66e5856c31
refs/heads/master
2023-06-23T03:51:46.025661
2021-07-26T08:35:43
2021-07-26T08:35:43
348,207,335
0
0
null
null
null
null
UTF-8
Java
false
false
234
java
package com.callor.lambda.service.impl; import com.callor.lambda.service.OnClickService; public class OnClickServiceImplV1 implements OnClickService { @Override public void onClick(String msg) { System.out.println(msg); } }
[ "cho.ay4@gmail.com" ]
cho.ay4@gmail.com
97bf704bb2e22dbe7e303a2d6a4c291c390f353c
58a961999c259d7fc9e0b8c17a0990f4247f29bf
/CDM/pract3/Original/sources/com/google/android/gms/maps/internal/IProjectionDelegate.java
6d69b7fa284a6c9daad17766125dce756b58b6bc
[]
no_license
Lulocu/4B-ETSINF
c50b4ca70ad14b9ec9af6a199c82fad333f7bc8c
65d492d0fbeb630c7bbe25d92dfbfd9e5f41bcd8
refs/heads/master
2023-06-05T23:41:02.297413
2021-06-20T10:53:30
2021-06-20T10:53:30
339,157,412
0
1
null
null
null
null
UTF-8
Java
false
false
9,905
java
package com.google.android.gms.maps.internal; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import android.os.RemoteException; import com.google.android.gms.dynamic.zzd; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.VisibleRegion; public interface IProjectionDelegate extends IInterface { public static abstract class zza extends Binder implements IProjectionDelegate { /* access modifiers changed from: private */ /* renamed from: com.google.android.gms.maps.internal.IProjectionDelegate$zza$zza reason: collision with other inner class name */ public static class C0167zza implements IProjectionDelegate { private IBinder zznF; C0167zza(IBinder iBinder) { this.zznF = iBinder; } public IBinder asBinder() { return this.zznF; } @Override // com.google.android.gms.maps.internal.IProjectionDelegate public LatLng fromScreenLocation(zzd point) throws RemoteException { LatLng latLng = null; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.maps.internal.IProjectionDelegate"); obtain.writeStrongBinder(point != null ? point.asBinder() : null); this.zznF.transact(1, obtain, obtain2, 0); obtain2.readException(); if (obtain2.readInt() != 0) { latLng = LatLng.CREATOR.createFromParcel(obtain2); } return latLng; } finally { obtain2.recycle(); obtain.recycle(); } } @Override // com.google.android.gms.maps.internal.IProjectionDelegate public LatLng fromScreenLocation2(Point point) throws RemoteException { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.maps.internal.IProjectionDelegate"); if (point != null) { obtain.writeInt(1); point.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.zznF.transact(4, obtain, obtain2, 0); obtain2.readException(); return obtain2.readInt() != 0 ? LatLng.CREATOR.createFromParcel(obtain2) : null; } finally { obtain2.recycle(); obtain.recycle(); } } @Override // com.google.android.gms.maps.internal.IProjectionDelegate public VisibleRegion getVisibleRegion() throws RemoteException { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.maps.internal.IProjectionDelegate"); this.zznF.transact(3, obtain, obtain2, 0); obtain2.readException(); return obtain2.readInt() != 0 ? VisibleRegion.CREATOR.createFromParcel(obtain2) : null; } finally { obtain2.recycle(); obtain.recycle(); } } @Override // com.google.android.gms.maps.internal.IProjectionDelegate public zzd toScreenLocation(LatLng location) throws RemoteException { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.maps.internal.IProjectionDelegate"); if (location != null) { obtain.writeInt(1); location.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.zznF.transact(2, obtain, obtain2, 0); obtain2.readException(); return zzd.zza.zzbg(obtain2.readStrongBinder()); } finally { obtain2.recycle(); obtain.recycle(); } } @Override // com.google.android.gms.maps.internal.IProjectionDelegate public Point toScreenLocation2(LatLng location) throws RemoteException { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.gms.maps.internal.IProjectionDelegate"); if (location != null) { obtain.writeInt(1); location.writeToParcel(obtain, 0); } else { obtain.writeInt(0); } this.zznF.transact(5, obtain, obtain2, 0); obtain2.readException(); return obtain2.readInt() != 0 ? Point.CREATOR.createFromParcel(obtain2) : null; } finally { obtain2.recycle(); obtain.recycle(); } } } public static IProjectionDelegate zzcE(IBinder iBinder) { if (iBinder == null) { return null; } IInterface queryLocalInterface = iBinder.queryLocalInterface("com.google.android.gms.maps.internal.IProjectionDelegate"); return (queryLocalInterface == null || !(queryLocalInterface instanceof IProjectionDelegate)) ? new C0167zza(iBinder) : (IProjectionDelegate) queryLocalInterface; } @Override // android.os.Binder public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { LatLng latLng = null; IBinder iBinder = null; Point point = null; switch (code) { case 1: data.enforceInterface("com.google.android.gms.maps.internal.IProjectionDelegate"); LatLng fromScreenLocation = fromScreenLocation(zzd.zza.zzbg(data.readStrongBinder())); reply.writeNoException(); if (fromScreenLocation != null) { reply.writeInt(1); fromScreenLocation.writeToParcel(reply, 1); } else { reply.writeInt(0); } return true; case 2: data.enforceInterface("com.google.android.gms.maps.internal.IProjectionDelegate"); zzd screenLocation = toScreenLocation(data.readInt() != 0 ? LatLng.CREATOR.createFromParcel(data) : null); reply.writeNoException(); if (screenLocation != null) { iBinder = screenLocation.asBinder(); } reply.writeStrongBinder(iBinder); return true; case 3: data.enforceInterface("com.google.android.gms.maps.internal.IProjectionDelegate"); VisibleRegion visibleRegion = getVisibleRegion(); reply.writeNoException(); if (visibleRegion != null) { reply.writeInt(1); visibleRegion.writeToParcel(reply, 1); } else { reply.writeInt(0); } return true; case 4: data.enforceInterface("com.google.android.gms.maps.internal.IProjectionDelegate"); if (data.readInt() != 0) { point = Point.CREATOR.createFromParcel(data); } LatLng fromScreenLocation2 = fromScreenLocation2(point); reply.writeNoException(); if (fromScreenLocation2 != null) { reply.writeInt(1); fromScreenLocation2.writeToParcel(reply, 1); } else { reply.writeInt(0); } return true; case 5: data.enforceInterface("com.google.android.gms.maps.internal.IProjectionDelegate"); if (data.readInt() != 0) { latLng = LatLng.CREATOR.createFromParcel(data); } Point screenLocation2 = toScreenLocation2(latLng); reply.writeNoException(); if (screenLocation2 != null) { reply.writeInt(1); screenLocation2.writeToParcel(reply, 1); } else { reply.writeInt(0); } return true; case 1598968902: reply.writeString("com.google.android.gms.maps.internal.IProjectionDelegate"); return true; default: return super.onTransact(code, data, reply, flags); } } } LatLng fromScreenLocation(zzd zzd) throws RemoteException; LatLng fromScreenLocation2(Point point) throws RemoteException; VisibleRegion getVisibleRegion() throws RemoteException; zzd toScreenLocation(LatLng latLng) throws RemoteException; Point toScreenLocation2(LatLng latLng) throws RemoteException; }
[ "lulocu99@gmail.com" ]
lulocu99@gmail.com
e834f5f6869638801a33d4404865e947ebc5059e
7b09ffb0074e942f0269b12b8e924b1223087809
/SIGECAC/PAC/Código/edu.upn.sigecac.pac/edu.upn.sigecac.pac-ejb/src/java/edu/upn/sigecac/pac/bc/DetalleMatrizAlineamientoObjetivosEducacionalesFacadeLocal.java
97eb10c6ec2d6d547af0ff745dcd82ce3d1c4497
[]
no_license
mandres26/sigecac-epo
e4fc53dd2c6aaa28c001f5a929a74f4aec773057
7dca6f22144e1dc8e314101003c0f3f690287d43
refs/heads/master
2020-06-08T18:27:49.165202
2009-07-06T22:58:14
2009-07-06T22:58:14
38,905,735
0
0
null
null
null
null
UTF-8
Java
false
false
1,091
java
package edu.upn.sigecac.pac.bc; import javax.ejb.Local; @Local public interface DetalleMatrizAlineamientoObjetivosEducacionalesFacadeLocal { public void registrar(edu.upn.sigecac.pac.be.DetalleMatrizAlineamientoObjetivosEducacionales maoe) throws java.lang.Exception; public void actualizar(edu.upn.sigecac.pac.be.DetalleMatrizAlineamientoObjetivosEducacionales maoe) throws java.lang.Exception; public void eliminar(edu.upn.sigecac.pac.be.DetalleMatrizAlineamientoObjetivosEducacionales maoe) throws java.lang.Exception; public edu.upn.sigecac.pac.be.DetalleMatrizAlineamientoObjetivosEducacionales buscarPorId(java.lang.Long idDetalleMatrizAlineamientoObjetivosEducacionales) throws java.lang.Exception; public java.util.List<edu.upn.sigecac.pac.be.DetalleMatrizAlineamientoObjetivosEducacionales> listar() throws java.lang.Exception; public edu.upn.sigecac.pac.be.DetalleMatrizAlineamientoObjetivosEducacionales find(java.lang.Object id); public java.util.List<edu.upn.sigecac.pac.be.DetalleMatrizAlineamientoObjetivosEducacionales> findAll(); }
[ "ernestex@20b7c2e4-63ec-11de-8e29-e9b457f63bae" ]
ernestex@20b7c2e4-63ec-11de-8e29-e9b457f63bae
ee8657512ff1b50b0dd2536ae40fcb6d1e33e8d9
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/ant_cluster/441/src_0.java
b49ffe28fdacbbba58bcd0461f3faa7f27d9c628
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
74,960
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.tools.ant.taskdefs; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.zip.CRC32; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.FileScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.ArchiveFileSet; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.PatternSet; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.ZipFileSet; import org.apache.tools.ant.types.ZipScanner; import org.apache.tools.ant.types.resources.ArchiveResource; import org.apache.tools.ant.types.resources.FileProvider; import org.apache.tools.ant.types.resources.FileResource; import org.apache.tools.ant.types.resources.Union; import org.apache.tools.ant.types.resources.ZipResource; import org.apache.tools.ant.types.resources.selectors.ResourceSelector; import org.apache.tools.ant.util.FileNameMapper; import org.apache.tools.ant.util.FileUtils; import org.apache.tools.ant.util.GlobPatternMapper; import org.apache.tools.ant.util.IdentityMapper; import org.apache.tools.ant.util.MergingMapper; import org.apache.tools.ant.util.ResourceUtils; import org.apache.tools.zip.UnixStat; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipExtraField; import org.apache.tools.zip.ZipFile; import org.apache.tools.zip.ZipOutputStream; /** * Create a Zip file. * * @since Ant 1.1 * * @ant.task category="packaging" */ public class Zip extends MatchingTask { private static final int BUFFER_SIZE = 8 * 1024; private static final int ROUNDUP_MILLIS = 1999; // 2 seconds - 1 // CheckStyle:VisibilityModifier OFF - bc protected File zipFile; // use to scan own archive private ZipScanner zs; private File baseDir; protected Hashtable entries = new Hashtable(); private Vector groupfilesets = new Vector(); private Vector filesetsFromGroupfilesets = new Vector(); protected String duplicate = "add"; private boolean doCompress = true; private boolean doUpdate = false; // shadow of the above if the value is altered in execute private boolean savedDoUpdate = false; private boolean doFilesonly = false; protected String archiveType = "zip"; // For directories: private static final long EMPTY_CRC = new CRC32 ().getValue (); protected String emptyBehavior = "skip"; private Vector resources = new Vector(); protected Hashtable addedDirs = new Hashtable(); private Vector addedFiles = new Vector(); private static final ResourceSelector MISSING_SELECTOR = new ResourceSelector() { public boolean isSelected(Resource target) { return !target.isExists(); } }; private static final ResourceUtils.ResourceSelectorProvider MISSING_DIR_PROVIDER = new ResourceUtils.ResourceSelectorProvider() { public ResourceSelector getTargetSelectorForSource(Resource sr) { return MISSING_SELECTOR; } }; /** * If this flag is true, execute() will run most operations twice, * the first time with {@link #skipWriting skipWriting} set to * true and the second time with setting it to false. * * <p>The only situation in Ant's current code base where this is * ever going to be true is if the jar task has been configured * with a filesetmanifest other than "skip".</p> */ protected boolean doubleFilePass = false; /** * whether the methods should just perform some sort of dry-run. * * <p>Will only ever be true in the first pass if the task * performs two passes because {@link #doubleFilePass * doubleFilePass} is true.</p> */ protected boolean skipWriting = false; /** * Whether this is the first time the archive building methods are invoked. * * @return true if either {@link #doubleFilePass doubleFilePass} * is false or {@link #skipWriting skipWriting} is true. * * @since Ant 1.8.0 */ protected final boolean isFirstPass() { return !doubleFilePass || skipWriting; } private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); // CheckStyle:VisibilityModifier ON // This boolean is set if the task detects that the // target is outofdate and has written to the target file. private boolean updatedFile = false; /** * true when we are adding new files into the Zip file, as opposed * to adding back the unchanged files */ private boolean addingNewFiles = false; /** * Encoding to use for filenames, defaults to the platform's * default encoding. */ private String encoding; /** * Whether the original compression of entries coming from a ZIP * archive should be kept (for example when updating an archive). * * @since Ant 1.6 */ private boolean keepCompression = false; /** * Whether the file modification times will be rounded up to the * next even number of seconds. * * @since Ant 1.6.2 */ private boolean roundUp = true; /** * Comment for the archive. * @since Ant 1.6.3 */ private String comment = ""; private int level = ZipOutputStream.DEFAULT_COMPRESSION; /** * Assume 0 Unix mode is intentional. * @since Ant 1.8.0 */ private boolean preserve0Permissions = false; /** * Whether to set the language encoding flag when creating the archive. * * @since Ant 1.8.0 */ private boolean useLanguageEncodingFlag = true; /** * Whether to add unicode extra fields. * * @since Ant 1.8.0 */ private UnicodeExtraField createUnicodeExtraFields = UnicodeExtraField.NEVER; /** * Whether to fall back to UTF-8 if a name cannot be enoded using * the specified encoding. * * @since Ant 1.8.0 */ private boolean fallBackToUTF8 = false; /** * This is the name/location of where to * create the .zip file. * @param zipFile the path of the zipFile * @deprecated since 1.5.x. * Use setDestFile(File) instead. * @ant.attribute ignore="true" */ public void setZipfile(File zipFile) { setDestFile(zipFile); } /** * This is the name/location of where to * create the file. * @param file the path of the zipFile * @since Ant 1.5 * @deprecated since 1.5.x. * Use setDestFile(File) instead. * @ant.attribute ignore="true" */ public void setFile(File file) { setDestFile(file); } /** * The file to create; required. * @since Ant 1.5 * @param destFile The new destination File */ public void setDestFile(File destFile) { this.zipFile = destFile; } /** * The file to create. * @return the destination file * @since Ant 1.5.2 */ public File getDestFile() { return zipFile; } /** * Directory from which to archive files; optional. * @param baseDir the base directory */ public void setBasedir(File baseDir) { this.baseDir = baseDir; } /** * Whether we want to compress the files or only store them; * optional, default=true; * @param c if true, compress the files */ public void setCompress(boolean c) { doCompress = c; } /** * Whether we want to compress the files or only store them; * @return true if the files are to be compressed * @since Ant 1.5.2 */ public boolean isCompress() { return doCompress; } /** * If true, emulate Sun's jar utility by not adding parent directories; * optional, defaults to false. * @param f if true, emulate sun's jar by not adding parent directories */ public void setFilesonly(boolean f) { doFilesonly = f; } /** * If true, updates an existing file, otherwise overwrite * any existing one; optional defaults to false. * @param c if true, updates an existing zip file */ public void setUpdate(boolean c) { doUpdate = c; savedDoUpdate = c; } /** * Are we updating an existing archive? * @return true if updating an existing archive */ public boolean isInUpdateMode() { return doUpdate; } /** * Adds a set of files. * @param set the fileset to add */ public void addFileset(FileSet set) { add(set); } /** * Adds a set of files that can be * read from an archive and be given a prefix/fullpath. * @param set the zipfileset to add */ public void addZipfileset(ZipFileSet set) { add(set); } /** * Add a collection of resources to be archived. * @param a the resources to archive * @since Ant 1.7 */ public void add(ResourceCollection a) { resources.add(a); } /** * Adds a group of zip files. * @param set the group (a fileset) to add */ public void addZipGroupFileset(FileSet set) { groupfilesets.addElement(set); } /** * Sets behavior for when a duplicate file is about to be added - * one of <code>add</code>, <code>preserve</code> or <code>fail</code>. * Possible values are: <code>add</code> (keep both * of the files); <code>preserve</code> (keep the first version * of the file found); <code>fail</code> halt a problem * Default for zip tasks is <code>add</code> * @param df a <code>Duplicate</code> enumerated value */ public void setDuplicate(Duplicate df) { duplicate = df.getValue(); } /** * Possible behaviors when there are no matching files for the task: * "fail", "skip", or "create". */ public static class WhenEmpty extends EnumeratedAttribute { /** * The string values for the enumerated value * @return the values */ public String[] getValues() { return new String[] {"fail", "skip", "create"}; } } /** * Sets behavior of the task when no files match. * Possible values are: <code>fail</code> (throw an exception * and halt the build); <code>skip</code> (do not create * any archive, but issue a warning); <code>create</code> * (make an archive with no entries). * Default for zip tasks is <code>skip</code>; * for jar tasks, <code>create</code>. * @param we a <code>WhenEmpty</code> enumerated value */ public void setWhenempty(WhenEmpty we) { emptyBehavior = we.getValue(); } /** * Encoding to use for filenames, defaults to the platform's * default encoding. * * <p>For a list of possible values see <a * href="http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html">http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html</a>.</p> * @param encoding the encoding name */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * Encoding to use for filenames. * @return the name of the encoding to use * @since Ant 1.5.2 */ public String getEncoding() { return encoding; } /** * Whether the original compression of entries coming from a ZIP * archive should be kept (for example when updating an archive). * Default is false. * @param keep if true, keep the original compression * @since Ant 1.6 */ public void setKeepCompression(boolean keep) { keepCompression = keep; } /** * Comment to use for archive. * * @param comment The content of the comment. * @since Ant 1.6.3 */ public void setComment(String comment) { this.comment = comment; } /** * Comment of the archive * * @return Comment of the archive. * @since Ant 1.6.3 */ public String getComment() { return comment; } /** * Set the compression level to use. Default is * ZipOutputStream.DEFAULT_COMPRESSION. * @param level compression level. * @since Ant 1.7 */ public void setLevel(int level) { this.level = level; } /** * Get the compression level. * @return compression level. * @since Ant 1.7 */ public int getLevel() { return level; } /** * Whether the file modification times will be rounded up to the * next even number of seconds. * * <p>Zip archives store file modification times with a * granularity of two seconds, so the times will either be rounded * up or down. If you round down, the archive will always seem * out-of-date when you rerun the task, so the default is to round * up. Rounding up may lead to a different type of problems like * JSPs inside a web archive that seem to be slightly more recent * than precompiled pages, rendering precompilation useless.</p> * @param r a <code>boolean</code> value * @since Ant 1.6.2 */ public void setRoundUp(boolean r) { roundUp = r; } /** * Assume 0 Unix mode is intentional. * @since Ant 1.8.0 */ public void setPreserve0Permissions(boolean b) { preserve0Permissions = b; } /** * Assume 0 Unix mode is intentional. * @since Ant 1.8.0 */ public boolean getPreserve0Permissions() { return preserve0Permissions; } /** * Whether to set the language encoding flag. * @since Ant 1.8.0 */ public void setUseLanguageEncodingFlag(boolean b) { useLanguageEncodingFlag = b; } /** * Whether the language encoding flag will be used. * @since Ant 1.8.0 */ public boolean getUseLanguageEnodingFlag() { return useLanguageEncodingFlag; } /** * Whether Unicode extra fields will be created. * @since Ant 1.8.0 */ public void setCreateUnicodeExtraFields(UnicodeExtraField b) { createUnicodeExtraFields = b; } /** * Whether Unicode extra fields will be created. * @since Ant 1.8.0 */ public UnicodeExtraField getCreateUnicodeExtraFields() { return createUnicodeExtraFields; } /** * Whether to fall back to UTF-8 if a name cannot be enoded using * the specified encoding. * * <p>Defaults to false.</p> * * @since Ant 1.8.0 */ public void setFallBackToUTF8(boolean b) { fallBackToUTF8 = b; } /** * Whether to fall back to UTF-8 if a name cannot be enoded using * the specified encoding. * * @since Ant 1.8.0 */ public boolean getFallBackToUTF8() { return fallBackToUTF8; } /** * validate and build * @throws BuildException on error */ public void execute() throws BuildException { if (doubleFilePass) { skipWriting = true; executeMain(); skipWriting = false; executeMain(); } else { executeMain(); } } /** * Get the value of the updatedFile attribute. * This should only be called after executeMain has been * called. * @return true if executeMain has written to the zip file. */ protected boolean hasUpdatedFile() { return updatedFile; } /** * Build the zip file. * This is called twice if doubleFilePass is true. * @throws BuildException on error */ public void executeMain() throws BuildException { checkAttributesAndElements(); // Renamed version of original file, if it exists File renamedFile = null; addingNewFiles = true; processDoUpdate(); processGroupFilesets(); // collect filesets to pass them to getResourcesToAdd Vector vfss = new Vector(); if (baseDir != null) { FileSet fs = (FileSet) getImplicitFileSet().clone(); fs.setDir(baseDir); vfss.addElement(fs); } for (int i = 0; i < resources.size(); i++) { ResourceCollection rc = (ResourceCollection) resources.elementAt(i); vfss.addElement(rc); } ResourceCollection[] fss = new ResourceCollection[vfss.size()]; vfss.copyInto(fss); boolean success = false; try { // can also handle empty archives ArchiveState state = getResourcesToAdd(fss, zipFile, false); // quick exit if the target is up to date if (!state.isOutOfDate()) { return; } File parent = zipFile.getParentFile(); if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { throw new BuildException("Failed to create missing parent" + " directory for " + zipFile); } updatedFile = true; if (!zipFile.exists() && state.isWithoutAnyResources()) { createEmptyZip(zipFile); return; } Resource[][] addThem = state.getResourcesToAdd(); if (doUpdate) { renamedFile = renameFile(); } String action = doUpdate ? "Updating " : "Building "; if (!skipWriting) { log(action + archiveType + ": " + zipFile.getAbsolutePath()); } ZipOutputStream zOut = null; try { if (!skipWriting) { zOut = new ZipOutputStream(zipFile); zOut.setEncoding(encoding); zOut.setUseLanguageEncodingFlag(useLanguageEncodingFlag); zOut.setCreateUnicodeExtraFields(createUnicodeExtraFields. getPolicy()); zOut.setFallbackToUTF8(fallBackToUTF8); zOut.setMethod(doCompress ? ZipOutputStream.DEFLATED : ZipOutputStream.STORED); zOut.setLevel(level); } initZipOutputStream(zOut); // Add the explicit resource collections to the archive. for (int i = 0; i < fss.length; i++) { if (addThem[i].length != 0) { addResources(fss[i], addThem[i], zOut); } } if (doUpdate) { addingNewFiles = false; ZipFileSet oldFiles = new ZipFileSet(); oldFiles.setProject(getProject()); oldFiles.setSrc(renamedFile); oldFiles.setDefaultexcludes(false); for (int i = 0; i < addedFiles.size(); i++) { PatternSet.NameEntry ne = oldFiles.createExclude(); ne.setName((String) addedFiles.elementAt(i)); } DirectoryScanner ds = oldFiles.getDirectoryScanner(getProject()); ((ZipScanner) ds).setEncoding(encoding); String[] f = ds.getIncludedFiles(); Resource[] r = new Resource[f.length]; for (int i = 0; i < f.length; i++) { r[i] = ds.getResource(f[i]); } if (!doFilesonly) { String[] d = ds.getIncludedDirectories(); Resource[] dr = new Resource[d.length]; for (int i = 0; i < d.length; i++) { dr[i] = ds.getResource(d[i]); } Resource[] tmp = r; r = new Resource[tmp.length + dr.length]; System.arraycopy(dr, 0, r, 0, dr.length); System.arraycopy(tmp, 0, r, dr.length, tmp.length); } addResources(oldFiles, r, zOut); } if (zOut != null) { zOut.setComment(comment); } finalizeZipOutputStream(zOut); // If we've been successful on an update, delete the // temporary file if (doUpdate) { if (!renamedFile.delete()) { log ("Warning: unable to delete temporary file " + renamedFile.getName(), Project.MSG_WARN); } } success = true; } finally { // Close the output stream. closeZout(zOut, success); } } catch (IOException ioe) { String msg = "Problem creating " + archiveType + ": " + ioe.getMessage(); // delete a bogus ZIP file (but only if it's not the original one) if ((!doUpdate || renamedFile != null) && !zipFile.delete()) { msg += " (and the archive is probably corrupt but I could not " + "delete it)"; } if (doUpdate && renamedFile != null) { try { FILE_UTILS.rename(renamedFile, zipFile); } catch (IOException e) { msg += " (and I couldn't rename the temporary file " + renamedFile.getName() + " back)"; } } throw new BuildException(msg, ioe, getLocation()); } finally { cleanUp(); } } /** rename the zip file. */ private File renameFile() { File renamedFile = FILE_UTILS.createTempFile( "zip", ".tmp", zipFile.getParentFile(), true, false); try { FILE_UTILS.rename(zipFile, renamedFile); } catch (SecurityException e) { throw new BuildException( "Not allowed to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file"); } catch (IOException e) { throw new BuildException( "Unable to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file"); } return renamedFile; } /** Close zout */ private void closeZout(ZipOutputStream zOut, boolean success) throws IOException { if (zOut == null) { return; } try { zOut.close(); } catch (IOException ex) { // If we're in this finally clause because of an // exception, we don't really care if there's an // exception when closing the stream. E.g. if it // throws "ZIP file must have at least one entry", // because an exception happened before we added // any files, then we must swallow this // exception. Otherwise, the error that's reported // will be the close() error, which is not the // real cause of the problem. if (success) { throw ex; } } } /** Check the attributes and elements */ private void checkAttributesAndElements() { if (baseDir == null && resources.size() == 0 && groupfilesets.size() == 0 && "zip".equals(archiveType)) { throw new BuildException("basedir attribute must be set, " + "or at least one " + "resource collection must be given!"); } if (zipFile == null) { throw new BuildException("You must specify the " + archiveType + " file to create!"); } if (zipFile.exists() && !zipFile.isFile()) { throw new BuildException(zipFile + " is not a file."); } if (zipFile.exists() && !zipFile.canWrite()) { throw new BuildException(zipFile + " is read-only."); } } /** Process doupdate */ private void processDoUpdate() { // Whether or not an actual update is required - // we don't need to update if the original file doesn't exist if (doUpdate && !zipFile.exists()) { doUpdate = false; logWhenWriting("ignoring update attribute as " + archiveType + " doesn't exist.", Project.MSG_DEBUG); } } /** Process groupfilesets */ private void processGroupFilesets() { // Add the files found in groupfileset to fileset for (int i = 0; i < groupfilesets.size(); i++) { logWhenWriting("Processing groupfileset ", Project.MSG_VERBOSE); FileSet fs = (FileSet) groupfilesets.elementAt(i); FileScanner scanner = fs.getDirectoryScanner(getProject()); String[] files = scanner.getIncludedFiles(); File basedir = scanner.getBasedir(); for (int j = 0; j < files.length; j++) { logWhenWriting("Adding file " + files[j] + " to fileset", Project.MSG_VERBOSE); ZipFileSet zf = new ZipFileSet(); zf.setProject(getProject()); zf.setSrc(new File(basedir, files[j])); add(zf); filesetsFromGroupfilesets.addElement(zf); } } } /** * Indicates if the task is adding new files into the archive as opposed to * copying back unchanged files from the backup copy * @return true if adding new files */ protected final boolean isAddingNewFiles() { return addingNewFiles; } /** * Add the given resources. * * @param fileset may give additional information like fullpath or * permissions. * @param resources the resources to add * @param zOut the stream to write to * @throws IOException on error * * @since Ant 1.5.2 */ protected final void addResources(FileSet fileset, Resource[] resources, ZipOutputStream zOut) throws IOException { String prefix = ""; String fullpath = ""; int dirMode = ArchiveFileSet.DEFAULT_DIR_MODE; int fileMode = ArchiveFileSet.DEFAULT_FILE_MODE; ArchiveFileSet zfs = null; if (fileset instanceof ArchiveFileSet) { zfs = (ArchiveFileSet) fileset; prefix = zfs.getPrefix(getProject()); fullpath = zfs.getFullpath(getProject()); dirMode = zfs.getDirMode(getProject()); fileMode = zfs.getFileMode(getProject()); } if (prefix.length() > 0 && fullpath.length() > 0) { throw new BuildException("Both prefix and fullpath attributes must" + " not be set on the same fileset."); } if (resources.length != 1 && fullpath.length() > 0) { throw new BuildException("fullpath attribute may only be specified" + " for filesets that specify a single" + " file."); } if (prefix.length() > 0) { if (!prefix.endsWith("/") && !prefix.endsWith("\\")) { prefix += "/"; } addParentDirs(null, prefix, zOut, "", dirMode); } ZipFile zf = null; try { boolean dealingWithFiles = false; File base = null; if (zfs == null || zfs.getSrc(getProject()) == null) { dealingWithFiles = true; base = fileset.getDir(getProject()); } else if (zfs instanceof ZipFileSet) { zf = new ZipFile(zfs.getSrc(getProject()), encoding); } for (int i = 0; i < resources.length; i++) { String name = null; if (fullpath.length() > 0) { name = fullpath; } else { name = resources[i].getName(); } name = name.replace(File.separatorChar, '/'); if ("".equals(name)) { continue; } if (resources[i].isDirectory()) { if (doFilesonly) { continue; } int thisDirMode = zfs != null && zfs.hasDirModeBeenSet() ? dirMode : getUnixMode(resources[i], zf, dirMode); addDirectoryResource(resources[i], name, prefix, base, zOut, dirMode, thisDirMode); } else { // !isDirectory addParentDirs(base, name, zOut, prefix, dirMode); if (dealingWithFiles) { File f = FILE_UTILS.resolveFile(base, resources[i].getName()); zipFile(f, zOut, prefix + name, fileMode); } else { int thisFileMode = zfs != null && zfs.hasFileModeBeenSet() ? fileMode : getUnixMode(resources[i], zf, fileMode); addResource(resources[i], name, prefix, zOut, thisFileMode, zf, zfs == null ? null : zfs.getSrc(getProject())); } } } } finally { if (zf != null) { zf.close(); } } } /** * Add a directory entry to the archive using a specified * Unix-mode and the default mode for its parent directories (if * necessary). */ private void addDirectoryResource(Resource r, String name, String prefix, File base, ZipOutputStream zOut, int defaultDirMode, int thisDirMode) throws IOException { if (!name.endsWith("/")) { name = name + "/"; } int nextToLastSlash = name.lastIndexOf("/", name.length() - 2); if (nextToLastSlash != -1) { addParentDirs(base, name.substring(0, nextToLastSlash + 1), zOut, prefix, defaultDirMode); } zipDir(r, zOut, prefix + name, thisDirMode, r instanceof ZipResource ? ((ZipResource) r).getExtraFields() : null); } /** * Determine a Resource's Unix mode or return the given default * value if not available. */ private int getUnixMode(Resource r, ZipFile zf, int defaultMode) throws IOException { int unixMode = defaultMode; if (zf != null) { ZipEntry ze = zf.getEntry(r.getName()); unixMode = ze.getUnixMode(); if ((unixMode == 0 || unixMode == UnixStat.DIR_FLAG) && !preserve0Permissions) { unixMode = defaultMode; } } else if (r instanceof ArchiveResource) { unixMode = ((ArchiveResource) r).getMode(); } return unixMode; } /** * Add a file entry. */ private void addResource(Resource r, String name, String prefix, ZipOutputStream zOut, int mode, ZipFile zf, File fromArchive) throws IOException { if (zf != null) { ZipEntry ze = zf.getEntry(r.getName()); if (ze != null) { boolean oldCompress = doCompress; if (keepCompression) { doCompress = (ze.getMethod() == ZipEntry.DEFLATED); } InputStream is = null; try { is = zf.getInputStream(ze); zipFile(is, zOut, prefix + name, ze.getTime(), fromArchive, mode, ze.getExtraFields()); } finally { doCompress = oldCompress; FileUtils.close(is); } } } else { InputStream is = null; try { is = r.getInputStream(); zipFile(is, zOut, prefix + name, r.getLastModified(), fromArchive, mode, r instanceof ZipResource ? ((ZipResource) r).getExtraFields() : null); } finally { FileUtils.close(is); } } } /** * Add the given resources. * * @param rc may give additional information like fullpath or * permissions. * @param resources the resources to add * @param zOut the stream to write to * @throws IOException on error * * @since Ant 1.7 */ protected final void addResources(ResourceCollection rc, Resource[] resources, ZipOutputStream zOut) throws IOException { if (rc instanceof FileSet) { addResources((FileSet) rc, resources, zOut); return; } for (int i = 0; i < resources.length; i++) { String name = resources[i].getName().replace(File.separatorChar, '/'); if ("".equals(name)) { continue; } if (resources[i].isDirectory() && doFilesonly) { continue; } File base = null; FileProvider fp = (FileProvider) resources[i].as(FileProvider.class); if (fp != null) { base = ResourceUtils.asFileResource(fp).getBaseDir(); } if (resources[i].isDirectory()) { addDirectoryResource(resources[i], name, "", base, zOut, ArchiveFileSet.DEFAULT_DIR_MODE, ArchiveFileSet.DEFAULT_DIR_MODE); } else { addParentDirs(base, name, zOut, "", ArchiveFileSet.DEFAULT_DIR_MODE); if (fp != null) { File f = (fp).getFile(); zipFile(f, zOut, name, ArchiveFileSet.DEFAULT_FILE_MODE); } else { addResource(resources[i], name, "", zOut, ArchiveFileSet.DEFAULT_FILE_MODE, null, null); } } } } /** * method for subclasses to override * @param zOut the zip output stream * @throws IOException on output error * @throws BuildException on other errors */ protected void initZipOutputStream(ZipOutputStream zOut) throws IOException, BuildException { } /** * method for subclasses to override * @param zOut the zip output stream * @throws IOException on output error * @throws BuildException on other errors */ protected void finalizeZipOutputStream(ZipOutputStream zOut) throws IOException, BuildException { } /** * Create an empty zip file * @param zipFile the zip file * @return true for historic reasons * @throws BuildException on error */ protected boolean createEmptyZip(File zipFile) throws BuildException { // In this case using java.util.zip will not work // because it does not permit a zero-entry archive. // Must create it manually. if (!skipWriting) { log("Note: creating empty " + archiveType + " archive " + zipFile, Project.MSG_INFO); } OutputStream os = null; try { os = new FileOutputStream(zipFile); // CheckStyle:MagicNumber OFF // Cf. PKZIP specification. byte[] empty = new byte[22]; empty[0] = 80; // P empty[1] = 75; // K empty[2] = 5; empty[3] = 6; // remainder zeros // CheckStyle:MagicNumber ON os.write(empty); } catch (IOException ioe) { throw new BuildException("Could not create empty ZIP archive " + "(" + ioe.getMessage() + ")", ioe, getLocation()); } finally { FileUtils.close(os); } return true; } /** * @since Ant 1.5.2 */ private synchronized ZipScanner getZipScanner() { if (zs == null) { zs = new ZipScanner(); zs.setEncoding(encoding); zs.setSrc(zipFile); } return zs; } /** * Collect the resources that are newer than the corresponding * entries (or missing) in the original archive. * * <p>If we are going to recreate the archive instead of updating * it, all resources should be considered as new, if a single one * is. Because of this, subclasses overriding this method must * call <code>super.getResourcesToAdd</code> and indicate with the * third arg if they already know that the archive is * out-of-date.</p> * * <p>This method first delegates to getNonFileSetResourceToAdd * and then invokes the FileSet-arg version. All this to keep * backwards compatibility for subclasses that don't know how to * deal with non-FileSet ResourceCollections.</p> * * @param rcs The resource collections to grab resources from * @param zipFile intended archive file (may or may not exist) * @param needsUpdate whether we already know that the archive is * out-of-date. Subclasses overriding this method are supposed to * set this value correctly in their call to * <code>super.getResourcesToAdd</code>. * @return an array of resources to add for each fileset passed in as well * as a flag that indicates whether the archive is uptodate. * * @exception BuildException if it likes * @since Ant 1.7 */ protected ArchiveState getResourcesToAdd(ResourceCollection[] rcs, File zipFile, boolean needsUpdate) throws BuildException { ArrayList filesets = new ArrayList(); ArrayList rest = new ArrayList(); for (int i = 0; i < rcs.length; i++) { if (rcs[i] instanceof FileSet) { filesets.add(rcs[i]); } else { rest.add(rcs[i]); } } ResourceCollection[] rc = (ResourceCollection[]) rest.toArray(new ResourceCollection[rest.size()]); ArchiveState as = getNonFileSetResourcesToAdd(rc, zipFile, needsUpdate); FileSet[] fs = (FileSet[]) filesets.toArray(new FileSet[filesets .size()]); ArchiveState as2 = getResourcesToAdd(fs, zipFile, as.isOutOfDate()); if (!as.isOutOfDate() && as2.isOutOfDate()) { /* * Bad luck. * * There are resources in the filesets that make the * archive out of date, but not in the non-fileset * resources. We need to rescan the non-FileSets to grab * all of them now. */ as = getNonFileSetResourcesToAdd(rc, zipFile, true); } Resource[][] toAdd = new Resource[rcs.length][]; int fsIndex = 0; int restIndex = 0; for (int i = 0; i < rcs.length; i++) { if (rcs[i] instanceof FileSet) { toAdd[i] = as2.getResourcesToAdd()[fsIndex++]; } else { toAdd[i] = as.getResourcesToAdd()[restIndex++]; } } return new ArchiveState(as2.isOutOfDate(), toAdd); } /** * Collect the resources that are newer than the corresponding * entries (or missing) in the original archive. * * <p>If we are going to recreate the archive instead of updating * it, all resources should be considered as new, if a single one * is. Because of this, subclasses overriding this method must * call <code>super.getResourcesToAdd</code> and indicate with the * third arg if they already know that the archive is * out-of-date.</p> * * @param filesets The filesets to grab resources from * @param zipFile intended archive file (may or may not exist) * @param needsUpdate whether we already know that the archive is * out-of-date. Subclasses overriding this method are supposed to * set this value correctly in their call to * <code>super.getResourcesToAdd</code>. * @return an array of resources to add for each fileset passed in as well * as a flag that indicates whether the archive is uptodate. * * @exception BuildException if it likes */ protected ArchiveState getResourcesToAdd(FileSet[] filesets, File zipFile, boolean needsUpdate) throws BuildException { Resource[][] initialResources = grabResources(filesets); if (isEmpty(initialResources)) { if (needsUpdate && doUpdate) { /* * This is a rather hairy case. * * One of our subclasses knows that we need to update the * archive, but at the same time, there are no resources * known to us that would need to be added. Only the * subclass seems to know what's going on. * * This happens if <jar> detects that the manifest has changed, * for example. The manifest is not part of any resources * because of our support for inline <manifest>s. * * If we invoke createEmptyZip like Ant 1.5.2 did, * we'll loose all stuff that has been in the original * archive (bugzilla report 17780). */ return new ArchiveState(true, initialResources); } if (emptyBehavior.equals("skip")) { if (doUpdate) { logWhenWriting(archiveType + " archive " + zipFile + " not updated because no new files were" + " included.", Project.MSG_VERBOSE); } else { logWhenWriting("Warning: skipping " + archiveType + " archive " + zipFile + " because no files were included.", Project.MSG_WARN); } } else if (emptyBehavior.equals("fail")) { throw new BuildException("Cannot create " + archiveType + " archive " + zipFile + ": no files were included.", getLocation()); } else { // Create. if (!zipFile.exists()) { needsUpdate = true; } } return new ArchiveState(needsUpdate, initialResources); } // initialResources is not empty if (!zipFile.exists()) { return new ArchiveState(true, initialResources); } if (needsUpdate && !doUpdate) { // we are recreating the archive, need all resources return new ArchiveState(true, initialResources); } Resource[][] newerResources = new Resource[filesets.length][]; for (int i = 0; i < filesets.length; i++) { if (!(fileset instanceof ZipFileSet) || ((ZipFileSet) fileset).getSrc(getProject()) == null) { File base = filesets[i].getDir(getProject()); for (int j = 0; j < initialResources[i].length; j++) { File resourceAsFile = FILE_UTILS.resolveFile(base, initialResources[i][j].getName()); if (resourceAsFile.equals(zipFile)) { throw new BuildException("A zip file cannot include " + "itself", getLocation()); } } } } for (int i = 0; i < filesets.length; i++) { if (initialResources[i].length == 0) { newerResources[i] = new Resource[] {}; continue; } FileNameMapper myMapper = new IdentityMapper(); if (filesets[i] instanceof ZipFileSet) { ZipFileSet zfs = (ZipFileSet) filesets[i]; if (zfs.getFullpath(getProject()) != null && !zfs.getFullpath(getProject()).equals("")) { // in this case all files from origin map to // the fullPath attribute of the zipfileset at // destination MergingMapper fm = new MergingMapper(); fm.setTo(zfs.getFullpath(getProject())); myMapper = fm; } else if (zfs.getPrefix(getProject()) != null && !zfs.getPrefix(getProject()).equals("")) { GlobPatternMapper gm = new GlobPatternMapper(); gm.setFrom("*"); String prefix = zfs.getPrefix(getProject()); if (!prefix.endsWith("/") && !prefix.endsWith("\\")) { prefix += "/"; } gm.setTo(prefix + "*"); myMapper = gm; } } newerResources[i] = selectOutOfDateResources(initialResources[i], myMapper); needsUpdate = needsUpdate || (newerResources[i].length > 0); if (needsUpdate && !doUpdate) { // we will return initialResources anyway, no reason // to scan further. break; } } if (needsUpdate && !doUpdate) { // we are recreating the archive, need all resources return new ArchiveState(true, initialResources); } return new ArchiveState(needsUpdate, newerResources); } /** * Collect the resources that are newer than the corresponding * entries (or missing) in the original archive. * * <p>If we are going to recreate the archive instead of updating * it, all resources should be considered as new, if a single one * is. Because of this, subclasses overriding this method must * call <code>super.getResourcesToAdd</code> and indicate with the * third arg if they already know that the archive is * out-of-date.</p> * * @param rcs The filesets to grab resources from * @param zipFile intended archive file (may or may not exist) * @param needsUpdate whether we already know that the archive is * out-of-date. Subclasses overriding this method are supposed to * set this value correctly in their call to * <code>super.getResourcesToAdd</code>. * @return an array of resources to add for each fileset passed in as well * as a flag that indicates whether the archive is uptodate. * * @exception BuildException if it likes */ protected ArchiveState getNonFileSetResourcesToAdd(ResourceCollection[] rcs, File zipFile, boolean needsUpdate) throws BuildException { /* * Backwards compatibility forces us to repeat the logic of * getResourcesToAdd(FileSet[], ...) here once again. */ Resource[][] initialResources = grabNonFileSetResources(rcs); if (isEmpty(initialResources)) { // no emptyBehavior handling since the FileSet version // will take care of it. return new ArchiveState(needsUpdate, initialResources); } // initialResources is not empty if (!zipFile.exists()) { return new ArchiveState(true, initialResources); } if (needsUpdate && !doUpdate) { // we are recreating the archive, need all resources return new ArchiveState(true, initialResources); } Resource[][] newerResources = new Resource[rcs.length][]; for (int i = 0; i < rcs.length; i++) { if (initialResources[i].length == 0) { newerResources[i] = new Resource[] {}; continue; } for (int j = 0; j < initialResources[i].length; j++) { FileProvider fp = (FileProvider) initialResources[i][j].as(FileProvider.class); if (fp != null && zipFile.equals(fp.getFile())) { throw new BuildException("A zip file cannot include " + "itself", getLocation()); } } newerResources[i] = selectOutOfDateResources(initialResources[i], new IdentityMapper()); needsUpdate = needsUpdate || (newerResources[i].length > 0); if (needsUpdate && !doUpdate) { // we will return initialResources anyway, no reason // to scan further. break; } } if (needsUpdate && !doUpdate) { // we are recreating the archive, need all resources return new ArchiveState(true, initialResources); } return new ArchiveState(needsUpdate, newerResources); } private Resource[] selectOutOfDateResources(Resource[] initial, FileNameMapper mapper) { Resource[] rs = selectFileResources(initial); Resource[] result = ResourceUtils.selectOutOfDateSources(this, rs, mapper, getZipScanner()); if (!doFilesonly) { Union u = new Union(); u.addAll(Arrays.asList(selectDirectoryResources(initial))); ResourceCollection rc = ResourceUtils.selectSources(this, u, mapper, getZipScanner(), MISSING_DIR_PROVIDER); if (rc.size() > 0) { ArrayList newer = new ArrayList(); newer.addAll(Arrays.asList(((Union) rc).listResources())); newer.addAll(Arrays.asList(result)); result = (Resource[]) newer.toArray(result); } } return result; } /** * Fetch all included and not excluded resources from the sets. * * <p>Included directories will precede included files.</p> * @param filesets an array of filesets * @return the resources included * @since Ant 1.5.2 */ protected Resource[][] grabResources(FileSet[] filesets) { Resource[][] result = new Resource[filesets.length][]; for (int i = 0; i < filesets.length; i++) { boolean skipEmptyNames = true; if (filesets[i] instanceof ZipFileSet) { ZipFileSet zfs = (ZipFileSet) filesets[i]; skipEmptyNames = zfs.getPrefix(getProject()).equals("") && zfs.getFullpath(getProject()).equals(""); } DirectoryScanner rs = filesets[i].getDirectoryScanner(getProject()); if (rs instanceof ZipScanner) { ((ZipScanner) rs).setEncoding(encoding); } Vector resources = new Vector(); if (!doFilesonly) { String[] directories = rs.getIncludedDirectories(); for (int j = 0; j < directories.length; j++) { if (!"".equals(directories[j]) || !skipEmptyNames) { resources.addElement(rs.getResource(directories[j])); } } } String[] files = rs.getIncludedFiles(); for (int j = 0; j < files.length; j++) { if (!"".equals(files[j]) || !skipEmptyNames) { resources.addElement(rs.getResource(files[j])); } } result[i] = new Resource[resources.size()]; resources.copyInto(result[i]); } return result; } /** * Fetch all included and not excluded resources from the collections. * * <p>Included directories will precede included files.</p> * @param rcs an array of resource collections * @return the resources included * @since Ant 1.7 */ protected Resource[][] grabNonFileSetResources(ResourceCollection[] rcs) { Resource[][] result = new Resource[rcs.length][]; for (int i = 0; i < rcs.length; i++) { Iterator iter = rcs[i].iterator(); ArrayList dirs = new ArrayList(); ArrayList files = new ArrayList(); while (iter.hasNext()) { Resource r = (Resource) iter.next(); if (r.isExists()) { if (r.isDirectory()) { dirs.add(r); } else { files.add(r); } } } // make sure directories are in alpha-order - this also // ensures parents come before their children Collections.sort(dirs, new Comparator() { public int compare(Object o1, Object o2) { Resource r1 = (Resource) o1; Resource r2 = (Resource) o2; return r1.getName().compareTo(r2.getName()); } }); ArrayList rs = new ArrayList(dirs); rs.addAll(files); result[i] = (Resource[]) rs.toArray(new Resource[rs.size()]); } return result; } /** * Add a directory to the zip stream. * @param dir the directort to add to the archive * @param zOut the stream to write to * @param vPath the name this entry shall have in the archive * @param mode the Unix permissions to set. * @throws IOException on error * @since Ant 1.5.2 */ protected void zipDir(File dir, ZipOutputStream zOut, String vPath, int mode) throws IOException { zipDir(dir, zOut, vPath, mode, null); } /** * Add a directory to the zip stream. * @param dir the directory to add to the archive * @param zOut the stream to write to * @param vPath the name this entry shall have in the archive * @param mode the Unix permissions to set. * @param extra ZipExtraFields to add * @throws IOException on error * @since Ant 1.6.3 */ protected void zipDir(File dir, ZipOutputStream zOut, String vPath, int mode, ZipExtraField[] extra) throws IOException { zipDir(dir == null ? (Resource) null : new FileResource(dir), zOut, vPath, mode, extra); } /** * Add a directory to the zip stream. * @param dir the directory to add to the archive * @param zOut the stream to write to * @param vPath the name this entry shall have in the archive * @param mode the Unix permissions to set. * @param extra ZipExtraFields to add * @throws IOException on error * @since Ant 1.8.0 */ protected void zipDir(Resource dir, ZipOutputStream zOut, String vPath, int mode, ZipExtraField[] extra) throws IOException { if (doFilesonly) { logWhenWriting("skipping directory " + vPath + " for file-only archive", Project.MSG_VERBOSE); return; } if (addedDirs.get(vPath) != null) { // don't add directories we've already added. // no warning if we try, it is harmless in and of itself return; } logWhenWriting("adding directory " + vPath, Project.MSG_VERBOSE); addedDirs.put(vPath, vPath); if (!skipWriting) { ZipEntry ze = new ZipEntry (vPath); // ZIPs store time with a granularity of 2 seconds, round up int millisToAdd = roundUp ? ROUNDUP_MILLIS : 0; if (dir != null && dir.isExists()) { ze.setTime(dir.getLastModified() + millisToAdd); } else { ze.setTime(System.currentTimeMillis() + millisToAdd); } ze.setSize (0); ze.setMethod (ZipEntry.STORED); // This is faintly ridiculous: ze.setCrc (EMPTY_CRC); ze.setUnixMode(mode); if (extra != null) { ze.setExtraFields(extra); } zOut.putNextEntry(ze); } } /** * Adds a new entry to the archive, takes care of duplicates as well. * * @param in the stream to read data for the entry from. The * caller of the method is responsible for closing the stream. * @param zOut the stream to write to. * @param vPath the name this entry shall have in the archive. * @param lastModified last modification time for the entry. * @param fromArchive the original archive we are copying this * entry from, will be null if we are not copying from an archive. * @param mode the Unix permissions to set. * * @since Ant 1.5.2 * @throws IOException on error */ protected void zipFile(InputStream in, ZipOutputStream zOut, String vPath, long lastModified, File fromArchive, int mode) throws IOException { zipFile(in, zOut, vPath, lastModified, fromArchive, mode, null); } /** * Adds a new entry to the archive, takes care of duplicates as well. * * @param in the stream to read data for the entry from. The * caller of the method is responsible for closing the stream. * @param zOut the stream to write to. * @param vPath the name this entry shall have in the archive. * @param lastModified last modification time for the entry. * @param fromArchive the original archive we are copying this * entry from, will be null if we are not copying from an archive. * @param mode the Unix permissions to set. * @param extra ZipExtraFields to add * * @since Ant 1.8.0 * @throws IOException on error */ protected void zipFile(InputStream in, ZipOutputStream zOut, String vPath, long lastModified, File fromArchive, int mode, ZipExtraField[] extra) throws IOException { // fromArchive is used in subclasses overriding this method if (entries.contains(vPath)) { if (duplicate.equals("preserve")) { logWhenWriting(vPath + " already added, skipping", Project.MSG_INFO); return; } else if (duplicate.equals("fail")) { throw new BuildException("Duplicate file " + vPath + " was found and the duplicate " + "attribute is 'fail'."); } else { // duplicate equal to add, so we continue logWhenWriting("duplicate file " + vPath + " found, adding.", Project.MSG_VERBOSE); } } else { logWhenWriting("adding entry " + vPath, Project.MSG_VERBOSE); } entries.put(vPath, vPath); if (!skipWriting) { ZipEntry ze = new ZipEntry(vPath); ze.setTime(lastModified); ze.setMethod(doCompress ? ZipEntry.DEFLATED : ZipEntry.STORED); /* * ZipOutputStream.putNextEntry expects the ZipEntry to * know its size and the CRC sum before you start writing * the data when using STORED mode - unless it is seekable. * * This forces us to process the data twice. */ if (!zOut.isSeekable() && !doCompress) { long size = 0; CRC32 cal = new CRC32(); if (!in.markSupported()) { // Store data into a byte[] ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; do { size += count; cal.update(buffer, 0, count); bos.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in = new ByteArrayInputStream(bos.toByteArray()); } else { in.mark(Integer.MAX_VALUE); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; do { size += count; cal.update(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.reset(); } ze.setSize(size); ze.setCrc(cal.getValue()); } ze.setUnixMode(mode); zOut.putNextEntry(ze); if (extra != null) { ze.setExtraFields(extra); } byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; do { if (count != 0) { zOut.write(buffer, 0, count); } count = in.read(buffer, 0, buffer.length); } while (count != -1); } addedFiles.addElement(vPath); } /** * Method that gets called when adding from <code>java.io.File</code> instances. * * <p>This implementation delegates to the six-arg version.</p> * * @param file the file to add to the archive * @param zOut the stream to write to * @param vPath the name this entry shall have in the archive * @param mode the Unix permissions to set. * @throws IOException on error * * @since Ant 1.5.2 */ protected void zipFile(File file, ZipOutputStream zOut, String vPath, int mode) throws IOException { if (file.equals(zipFile)) { throw new BuildException("A zip file cannot include itself", getLocation()); } FileInputStream fIn = new FileInputStream(file); try { // ZIPs store time with a granularity of 2 seconds, round up zipFile(fIn, zOut, vPath, file.lastModified() + (roundUp ? ROUNDUP_MILLIS : 0), null, mode); } finally { fIn.close(); } } /** * Ensure all parent dirs of a given entry have been added. * @param baseDir the base directory to use (may be null) * @param entry the entry name to create directories from * @param zOut the stream to write to * @param prefix a prefix to place on the created entries * @param dirMode the directory mode * @throws IOException on error * @since Ant 1.5.2 */ protected final void addParentDirs(File baseDir, String entry, ZipOutputStream zOut, String prefix, int dirMode) throws IOException { if (!doFilesonly) { Stack directories = new Stack(); int slashPos = entry.length(); while ((slashPos = entry.lastIndexOf('/', slashPos - 1)) != -1) { String dir = entry.substring(0, slashPos + 1); if (addedDirs.get(prefix + dir) != null) { break; } directories.push(dir); } while (!directories.isEmpty()) { String dir = (String) directories.pop(); File f = null; if (baseDir != null) { f = new File(baseDir, dir); } else { f = new File(dir); } zipDir(f, zOut, prefix + dir, dirMode); } } } /** * Do any clean up necessary to allow this instance to be used again. * * <p>When we get here, the Zip file has been closed and all we * need to do is to reset some globals.</p> * * <p>This method will only reset globals that have been changed * during execute(), it will not alter the attributes or nested * child elements. If you want to reset the instance so that you * can later zip a completely different set of files, you must use * the reset method.</p> * * @see #reset */ protected void cleanUp() { addedDirs.clear(); addedFiles.removeAllElements(); entries.clear(); addingNewFiles = false; doUpdate = savedDoUpdate; Enumeration e = filesetsFromGroupfilesets.elements(); while (e.hasMoreElements()) { ZipFileSet zf = (ZipFileSet) e.nextElement(); resources.removeElement(zf); } filesetsFromGroupfilesets.removeAllElements(); } /** * Makes this instance reset all attributes to their default * values and forget all children. * * @since Ant 1.5 * * @see #cleanUp */ public void reset() { resources.removeAllElements(); zipFile = null; baseDir = null; groupfilesets.removeAllElements(); duplicate = "add"; archiveType = "zip"; doCompress = true; emptyBehavior = "skip"; doUpdate = false; doFilesonly = false; encoding = null; } /** * Check is the resource arrays are empty. * @param r the arrays to check * @return true if all individual arrays are empty * * @since Ant 1.5.2 */ protected static final boolean isEmpty(Resource[][] r) { for (int i = 0; i < r.length; i++) { if (r[i].length > 0) { return false; } } return true; } /** * Drops all non-file resources from the given array. * @param orig the resources to filter * @return the filters resources * @since Ant 1.6 */ protected Resource[] selectFileResources(Resource[] orig) { return selectResources(orig, new ResourceSelector() { public boolean isSelected(Resource r) { if (!r.isDirectory()) { return true; } else if (doFilesonly) { logWhenWriting("Ignoring directory " + r.getName() + " as only files will" + " be added.", Project.MSG_VERBOSE); } return false; } }); } /** * Drops all non-directory resources from the given array. * @param orig the resources to filter * @return the filters resources * @since Ant 1.8.0 */ protected Resource[] selectDirectoryResources(Resource[] orig) { return selectResources(orig, new ResourceSelector() { public boolean isSelected(Resource r) { return r.isDirectory(); } }); } /** * Drops all resources from the given array that are not selected * @param orig the resources to filter * @return the filters resources * @since Ant 1.8.0 */ protected Resource[] selectResources(Resource[] orig, ResourceSelector selector) { if (orig.length == 0) { return orig; } ArrayList v = new ArrayList(orig.length); for (int i = 0; i < orig.length; i++) { if (selector.isSelected(orig[i])) { v.add(orig[i]); } } if (v.size() != orig.length) { Resource[] r = new Resource[v.size()]; return (Resource[]) v.toArray(r); } return orig; } /** * Logs a message at the given output level, but only if this is * the pass that will actually create the archive. * * @since Ant 1.8.0 */ protected void logWhenWriting(String msg, int level) { if (!skipWriting) { log(msg, level); } } /** * Possible behaviors when a duplicate file is added: * "add", "preserve" or "fail" */ public static class Duplicate extends EnumeratedAttribute { /** * @see EnumeratedAttribute#getValues() */ /** {@inheritDoc} */ public String[] getValues() { return new String[] {"add", "preserve", "fail"}; } } /** * Holds the up-to-date status and the out-of-date resources of * the original archive. * * @since Ant 1.5.3 */ public static class ArchiveState { private boolean outOfDate; private Resource[][] resourcesToAdd; ArchiveState(boolean state, Resource[][] r) { outOfDate = state; resourcesToAdd = r; } /** * Return the outofdate status. * @return the outofdate status */ public boolean isOutOfDate() { return outOfDate; } /** * Get the resources to add. * @return the resources to add */ public Resource[][] getResourcesToAdd() { return resourcesToAdd; } /** * find out if there are absolutely no resources to add * @since Ant 1.6.3 * @return true if there are no resources to add */ public boolean isWithoutAnyResources() { if (resourcesToAdd == null) { return true; } for (int counter = 0; counter < resourcesToAdd.length; counter++) { if (resourcesToAdd[counter] != null) { if (resourcesToAdd[counter].length > 0) { return false; } } } return true; } } /** * Policiy for creation of Unicode extra fields: never, always or * not-encodeable. * * @since Ant 1.8.0 */ public static final class UnicodeExtraField extends EnumeratedAttribute { private static final Map POLICIES = new HashMap(); private static final String NEVER_KEY = "never"; private static final String ALWAYS_KEY = "always"; private static final String N_E_KEY = "not-encodeable"; static { POLICIES.put(NEVER_KEY, ZipOutputStream.UnicodeExtraFieldPolicy.NEVER); POLICIES.put(ALWAYS_KEY, ZipOutputStream.UnicodeExtraFieldPolicy.ALWAYS); POLICIES.put(N_E_KEY, ZipOutputStream.UnicodeExtraFieldPolicy .NOT_ENCODEABLE); } public String[] getValues() { return new String[] {NEVER_KEY, ALWAYS_KEY, N_E_KEY}; } public static final UnicodeExtraField NEVER = new UnicodeExtraField(NEVER_KEY); private UnicodeExtraField(String name) { setValue(name); } public UnicodeExtraField() { } public ZipOutputStream.UnicodeExtraFieldPolicy getPolicy() { return (ZipOutputStream.UnicodeExtraFieldPolicy) POLICIES.get(getValue()); } } }
[ "375833274@qq.com" ]
375833274@qq.com
060d56e96a2d0400c96b8369701a9e07cc7d5069
aa698ceb63beb130658a94243c2e71ac7f2382a5
/src/main/java/cn/easycms/directive/ApplyopenQueryDirective.java
6921f201341587f724f2b9de49b1f43d64d4e34b
[ "Apache-2.0" ]
permissive
zhldt2008/EasyCMS
47ebc204326d7d75e11fd5f1990547407e8e6ac2
c9d55cba8b3d4ec3f0884e36056cfc4df1b37539
refs/heads/master
2021-01-18T20:36:41.586032
2014-07-12T01:41:36
2014-07-12T01:41:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
925
java
package cn.easycms.directive; import cn.easycms.base.BaseDirective; import cn.easycms.util.StringUtil; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import java.io.IOException; import java.util.Map; /** * Created by hackingwu on 2014/4/13. */ public class ApplyopenQueryDirective extends BaseDirective implements TemplateDirectiveModel{ @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String queryCode = getParam(params,"queryCode"); if(StringUtil.isNotEmpty(queryCode)){ if (body!=null){ if (loopVars!=null && loopVars.length>0){ } } } } }
[ "flywu5@gmail.com" ]
flywu5@gmail.com
11628409d0f5c28528628836cc90d432d6403f88
f1d207bf7bb84cc4d99de1db6598db6929208ee9
/core/src/com/masi4/gamehelpers/resourceHandlers/SoundManager.java
dffeecc08cd19ea1cb1453e95442f0ee5de1e94c
[]
no_license
masi4/JIefOIQVs2Ifj30gTJa2
2c0bbb5504ba61c09e56f629469a3799f03d7d29
0ad0824d7d9ce419b5fe5594191a753c46e624d3
refs/heads/master
2021-05-08T06:43:53.107556
2018-05-20T18:55:34
2018-05-20T18:55:34
106,569,351
0
0
null
2017-12-21T20:57:15
2017-10-11T15:01:38
Java
UTF-8
Java
false
false
3,292
java
package com.masi4.gamehelpers.resourceHandlers; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.utils.Array; import com.masi4.gamehelpers.GamePreferences; import static com.masi4.myGame.GameMain.random; /** Сделан, чтобы не писать проверку, включен ли звук, в каждом методе, где проигрывается звук */ public class SoundManager { /** * Plays a sound if "Sound" is enabled in options. * @param sound sound to be played * @return the id of the sound instance if successful, or -1 on failure. */ public static long play(Sound sound) { // TODO: если включен звук в настройках // позже сделать регулировку громкости (master volume) и сделать play(masterVolume); if (GamePreferences.Options.getInteger("Sound") == 1) return sound.play(); else return -1; } /** * Plays a sound with specified volume if "Sound" is enabled in options. * @param sound sound to be played * @param volume volume of sound to be played * @return the id of the sound instance if successful, or -1 on failure. */ public static long play(Sound sound, float volume) { if (GamePreferences.Options.getInteger("Sound") == 1) return sound.play(volume); else return -1; } /** * Plays a random sound of the array if "Sound" is enabled in options. * @param soundArr array of sounds to be played * @return the id of the sound instance if successful, or -1 on failure. */ public static long playRandom(Array<Sound> soundArr) { if (GamePreferences.Options.getInteger("Sound") == 1) return soundArr.get(random.nextInt(soundArr.size)).play(); else return -1; } /** * Plays a random sound of the array with specified volume if "Sound" is enabled in options. * @param soundArr array of sounds to be played * @param volume volume of sound to be played * @return the id of the sound instance if successful, or -1 on failure. */ public static long playRandom(Array<Sound> soundArr, float volume) { if (GamePreferences.Options.getInteger("Sound") == 1) return soundArr.get(random.nextInt(soundArr.size)).play(volume); else return -1; } /** * Plays Music file * @param music music file to be played * @param isLooping if music will be looped */ public static void playMusic(Music music, boolean isLooping) { if (GamePreferences.Options.getInteger("Sound") == 1) { music.setLooping(isLooping); music.play(); } } /** * Plays Music file with specified volume * @param music music file to be played * @param isLooping if music will be looped * @param volume volume of music to be played */ public static void playMusic(Music music, boolean isLooping, float volume) { if (GamePreferences.Options.getInteger("Sound") == 1) { music.setLooping(isLooping); music.setVolume(volume); music.play(); } } }
[ "meowsqwe@gmail.com" ]
meowsqwe@gmail.com
d165abc964119828fb2e961900c7882598ff3219
80cac1e5169fe92e11b52dbb7b584625249f0972
/app/src/main/java/com/intkhabahmed/quicknote/activities/DetailActivity.java
be4a147663e9270d4c8cfc400b2f3412093d4912
[]
no_license
intkhabahmed/QuickNote
8d9344bbf47ae6917c5dfe55bf3b7923d28f0c58
1d6456a3d78cd011e663ac48e92c7adae9b08354
refs/heads/master
2020-03-26T11:11:47.955029
2018-08-15T09:21:41
2018-08-15T09:21:41
144,832,660
1
0
null
null
null
null
UTF-8
Java
false
false
2,584
java
package com.intkhabahmed.quicknote.activities; import android.content.Intent; import android.databinding.DataBindingUtil; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import com.intkhabahmed.quicknote.R; import com.intkhabahmed.quicknote.databinding.ActivityDetailBinding; import com.intkhabahmed.quicknote.models.Note; import com.intkhabahmed.quicknote.utils.DateUtils; import java.util.Arrays; public class DetailActivity extends AppCompatActivity { private ActivityDetailBinding mDetailBinding; private Note mNote; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDetailBinding = DataBindingUtil.setContentView(this, R.layout.activity_detail); setupUI(); } private void setupUI() { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); } Intent intent = getIntent(); if (intent != null && intent.hasExtra(getString(R.string.note))) { mNote = intent.getParcelableExtra(getString(R.string.note)); } populateViews(); } private void populateViews() { mDetailBinding.noteTitleTv.setText(mNote.getTitle()); mDetailBinding.noteDesciptionTv.setText(mNote.getDescription()); mDetailBinding.hashTagsTv.setText(""); for (String tag : mNote.getHashTags()) { mDetailBinding.hashTagsTv.append(String.format("%s%s%s", "#", tag.trim(), " ")); } mDetailBinding.dateCreatedTv.setText(DateUtils.getFormattedTime(mNote.getDateCreated())); mDetailBinding.editNoteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(DetailActivity.this, AddNoteActivity.class); intent.putExtra(getString(R.string.note), mNote); startActivity(intent); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } }
[ "intkhab.ahmed64@gmail.com" ]
intkhab.ahmed64@gmail.com
88ad5efd1a2b68211b646e6f8616f3420c3909d8
2e2a3b72c7366374681549434d7311270cc01762
/app/src/main/java/com/turingsoulapps/simplecalculatorandroidapplication/SimpleCalculatorController.java
7610f47ac7b2ff5a296024f249affc5572b0212f
[]
no_license
NiazBinSiraj/CSE3162-SimpleCalculatorAndroidApplication
1bc30839bfdb75c0db098d582e6ed454e1f49165
54dc53e73a8d170e8446604e8f4421329af0ff61
refs/heads/master
2020-08-03T02:45:59.176523
2019-09-29T18:33:16
2019-09-29T18:33:16
211,601,270
0
0
null
null
null
null
UTF-8
Java
false
false
3,360
java
package com.turingsoulapps.simplecalculatorandroidapplication; public class SimpleCalculatorController { private static String operator = ""; private static boolean isSqrt = false; private static int dotCount=0; public static String setOperation(String view) { if(view == ".") { dotCount++; if(dotCount > 1) return "NaN"; } if(isOperator(view) == true) { if(view == "√" && isSqrt == false){ isSqrt = true; operator = "√"; return "√"; } if(isSqrt == true) { SimpleCalculatorModel.SetOperator(view); return "√"+view; } operator = view; return SimpleCalculatorModel.GetFirstNumber()+operator+SimpleCalculatorModel.GetSecondNumber(); } else if(view == "clear") { operator = ""; dotCount = 0; isSqrt=false; SimpleCalculatorModel.ClearAll(); return ""; } else if(view == "delete") { if(operator == "") SimpleCalculatorModel.DeleteFirstNumber(); else { if(SimpleCalculatorModel.GetSecondNumber() == "") operator = ""; else SimpleCalculatorModel.DeleteSecondNumber(); } return SimpleCalculatorModel.GetFirstNumber()+operator+SimpleCalculatorModel.GetSecondNumber(); } else if(view == "=") { if(SimpleCalculatorModel.GetSecondNumber() == "") return "NaN"; if(operator == "+") return SimpleCalculatorModel.Add(); if(operator == "-") return SimpleCalculatorModel.Subtract(); if(operator == "*") return SimpleCalculatorModel.Multiply(); if(operator == "/") return SimpleCalculatorModel.Division(); if(operator == "^") return SimpleCalculatorModel.Power(); if(operator == "%") return SimpleCalculatorModel.Mod(); if(operator == "√"){isSqrt = false; return SimpleCalculatorModel.Sqrt();} else return "NaN"; } else { if(SimpleCalculatorModel.GetFirstNumber().length() >= 10 && operator == "") { return SimpleCalculatorModel.GetFirstNumber()+operator+SimpleCalculatorModel.GetSecondNumber(); } else if(SimpleCalculatorModel.GetSecondNumber().length() >= 10 && operator != "") { return SimpleCalculatorModel.GetFirstNumber()+operator+SimpleCalculatorModel.GetSecondNumber(); } else if(operator == "" && isSqrt == false) SimpleCalculatorModel.SetFirstNumber(view); else if(isSqrt == true) { SimpleCalculatorModel.SetSecondNumber(view); return "√"+SimpleCalculatorModel.GetOperator()+view; } else SimpleCalculatorModel.SetSecondNumber(view); return SimpleCalculatorModel.GetFirstNumber()+operator+SimpleCalculatorModel.GetSecondNumber(); } } private static boolean isOperator(String op) { if(op == "+" || op == "-" || op == "*" || op == "/" || op == "^" || op == "%" || op == "√") return true; return false; } }
[ "niaz9767@gmail.com" ]
niaz9767@gmail.com
e6c0dbc39b08de1f527f7de4375ef5e603231216
a0194caa13bb661c1c5d32e14db63acab367ccca
/src/com/cxstock/utils/filter/SecurityFilter.java
b9c1ecb70f986dc3c1c448838d487988cc536629
[]
no_license
impxiahuaxian/chaoshiguanli
97444caff54b4d7454457913cce551a98d2a0285
60dfdb7e9de7e14dfec17cb526fa2bf26fa9d1c0
refs/heads/main
2023-02-23T04:24:24.377164
2021-01-22T06:37:36
2021-01-22T06:37:36
331,858,332
1
0
null
null
null
null
UTF-8
Java
false
false
1,396
java
package com.cxstock.utils.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.cxstock.biz.power.dto.UserDTO; import com.cxstock.utils.system.Constants; public class SecurityFilter implements Filter { @SuppressWarnings("unused") private FilterConfig filterCon = null; public void init(FilterConfig config) throws ServletException { filterCon = config; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; UserDTO userInfo = (UserDTO) httpRequest.getSession().getAttribute(Constants.USERINFO); String str=httpRequest.getRequestURL().toString(); if(userInfo==null){ if(str.indexOf("/login.jsp")==-1){ httpResponse.sendRedirect(httpRequest.getContextPath()+"/login.jsp"); }else{ filterChain .doFilter(request, response); } }else{ filterChain .doFilter(request, response); } } public void destroy() { filterCon = null; } }
[ "nwlfln@163.com" ]
nwlfln@163.com