blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
56d0359ebb795da825e4c859843c41f49df51d6b
21,285,857,953,322
780f532da229819213c796f3a7fd720ba7969b5d
/src/main/java/app/dao/entities/SysFormFieldGroup.java
fe712fcfb388166ba02eadd0bb45eae3b00334a2
[]
no_license
codecows/FormPower
https://github.com/codecows/FormPower
6eb63f004db1b6104e86af9209cdc90c053b860a
8d07bd696b86707ac56bb0a53dad1ca639e1f800
refs/heads/master
2021-05-16T13:58:19.752000
2018-04-11T05:36:27
2018-04-11T05:36:27
117,779,550
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.dao.entities; import java.math.BigDecimal; public class SysFormFieldGroup { private String groupId; private String groupName; private String img; private BigDecimal orderNum; private String status; public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId == null ? null : groupId.trim(); } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName == null ? null : groupName.trim(); } public String getImg() { return img; } public void setImg(String img) { this.img = img == null ? null : img.trim(); } public BigDecimal getOrderNum() { return orderNum; } public void setOrderNum(BigDecimal orderNum) { this.orderNum = orderNum; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status == null ? null : status.trim(); } }
UTF-8
Java
1,098
java
SysFormFieldGroup.java
Java
[]
null
[]
package app.dao.entities; import java.math.BigDecimal; public class SysFormFieldGroup { private String groupId; private String groupName; private String img; private BigDecimal orderNum; private String status; public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId == null ? null : groupId.trim(); } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName == null ? null : groupName.trim(); } public String getImg() { return img; } public void setImg(String img) { this.img = img == null ? null : img.trim(); } public BigDecimal getOrderNum() { return orderNum; } public void setOrderNum(BigDecimal orderNum) { this.orderNum = orderNum; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status == null ? null : status.trim(); } }
1,098
0.613843
0.613843
55
18.981817
19.237738
69
false
false
0
0
0
0
0
0
0.309091
false
false
10
9f87d600aeb805e4e76b3424660a9dc0679adcbd
317,827,649,123
d513c897f0d7797877e93b9b1d44b550581daecb
/src/com/blueprintit/dbom/query/Join.java
3ed79060e2bfdb6d93ff41e7779c8e2c55ed427e
[]
no_license
Mossop/DBOM
https://github.com/Mossop/DBOM
f4f61b3715759018e0891ebb74c1e128ee927563
a91301115fb37551c842ce64f63b9803f8469ae9
refs/heads/master
2020-09-16T05:16:46.821000
2004-04-29T15:58:11
2004-04-29T15:58:11
223,664,398
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.blueprintit.dbom.query; import java.util.HashSet; import java.util.Set; import com.blueprintit.dbom.Database; /** * @author Dave */ public class Join implements TableReference { private String type; private TableReference left; private TableReference right; private Restriction condition; public Join(String type, TableReference left, TableReference right) { this(type,left,right,null); } public Join(String type, TableReference left, TableReference right, Restriction condition) { if (left.getDatabase()==right.getDatabase()) { this.type=type; this.left=left; this.right=right; this.condition=condition; } else { throw new IllegalArgumentException(); } } public Database getDatabase() { return left.getDatabase(); } public Set getPrimaryKeyFields() { Set key = new HashSet(); key.addAll(left.getPrimaryKeyFields()); key.addAll(right.getPrimaryKeyFields()); return key; } public String getSQL() { StringBuffer result = new StringBuffer(); result.append("("); result.append(left.getSQL()); result.append(" "); result.append(right.getSQL()); if ((condition!=null)&&(!condition.isEmpty())) { result.append(" ON "); result.append(condition.getSQL()); } result.append(")"); return result.toString(); } }
UTF-8
Java
1,311
java
Join.java
Java
[ { "context": "ort com.blueprintit.dbom.Database;\n\n/**\n * @author Dave\n */\npublic class Join implements TableReference\n{", "end": 144, "score": 0.9989838004112244, "start": 140, "tag": "NAME", "value": "Dave" } ]
null
[]
package com.blueprintit.dbom.query; import java.util.HashSet; import java.util.Set; import com.blueprintit.dbom.Database; /** * @author Dave */ public class Join implements TableReference { private String type; private TableReference left; private TableReference right; private Restriction condition; public Join(String type, TableReference left, TableReference right) { this(type,left,right,null); } public Join(String type, TableReference left, TableReference right, Restriction condition) { if (left.getDatabase()==right.getDatabase()) { this.type=type; this.left=left; this.right=right; this.condition=condition; } else { throw new IllegalArgumentException(); } } public Database getDatabase() { return left.getDatabase(); } public Set getPrimaryKeyFields() { Set key = new HashSet(); key.addAll(left.getPrimaryKeyFields()); key.addAll(right.getPrimaryKeyFields()); return key; } public String getSQL() { StringBuffer result = new StringBuffer(); result.append("("); result.append(left.getSQL()); result.append(" "); result.append(right.getSQL()); if ((condition!=null)&&(!condition.isEmpty())) { result.append(" ON "); result.append(condition.getSQL()); } result.append(")"); return result.toString(); } }
1,311
0.698703
0.698703
67
18.567163
18.529705
91
false
false
0
0
0
0
0
0
1.865672
false
false
10
66712d709efd51c89a261e88733332b898dc0b6b
23,287,312,682,280
76663c8c3df2d4111d3c0919b4035d3ceb76bb38
/app/src/main/java/com/zz/lamp/business/control/adapter/ControlLineAdapter.java
7e03d7e77045c49133143c80aabbbd44b5a8a2bc
[]
no_license
sunjingcat/EStreetLamp
https://github.com/sunjingcat/EStreetLamp
9daab0bedc37299d693f1ff260c6fbde8b59e1e1
f615e5e9091da1326fb2becdb7960fd0ba4b8bbc
refs/heads/master
2023-07-04T23:52:33.293000
2021-08-13T09:06:14
2021-08-13T09:06:14
258,905,423
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zz.lamp.business.control.adapter; import android.graphics.Color; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import androidx.annotation.LayoutRes; import androidx.annotation.Nullable; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import com.zz.lamp.R; import com.zz.lamp.bean.CameraBean; import com.zz.lamp.bean.LineBean; import java.util.List; /** * Created by ASUS on 2018/10/10. */ public class ControlLineAdapter extends BaseQuickAdapter<LineBean, BaseViewHolder> { public ControlLineAdapter(@LayoutRes int layoutResId, @Nullable List<LineBean> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder holper, final LineBean item) { ImageView imageView = holper.getView(R.id.item_control_check); if (item.isCheck()){ imageView.setImageResource(R.drawable.image_real_check); }else { imageView.setImageResource(R.drawable.image_real_uncheck); } holper.setText(R.id.item_control_title,item.getLineName()); holper.setText(R.id.item_control_state,item.getStatus()==1?"开":"关"); holper.setTextColor(R.id.item_control_state,item.getStatus()==1? Color.parseColor("#2EAE73") :Color.parseColor("#E84444")); } }
UTF-8
Java
1,427
java
ControlLineAdapter.java
Java
[ { "context": "neBean;\n\nimport java.util.List;\n\n/**\n * Created by ASUS on 2018/10/10.\n */\n\npublic class ControlLineAdapt", "end": 543, "score": 0.9850431680679321, "start": 539, "tag": "USERNAME", "value": "ASUS" } ]
null
[]
package com.zz.lamp.business.control.adapter; import android.graphics.Color; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import androidx.annotation.LayoutRes; import androidx.annotation.Nullable; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import com.zz.lamp.R; import com.zz.lamp.bean.CameraBean; import com.zz.lamp.bean.LineBean; import java.util.List; /** * Created by ASUS on 2018/10/10. */ public class ControlLineAdapter extends BaseQuickAdapter<LineBean, BaseViewHolder> { public ControlLineAdapter(@LayoutRes int layoutResId, @Nullable List<LineBean> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder holper, final LineBean item) { ImageView imageView = holper.getView(R.id.item_control_check); if (item.isCheck()){ imageView.setImageResource(R.drawable.image_real_check); }else { imageView.setImageResource(R.drawable.image_real_uncheck); } holper.setText(R.id.item_control_title,item.getLineName()); holper.setText(R.id.item_control_state,item.getStatus()==1?"开":"关"); holper.setTextColor(R.id.item_control_state,item.getStatus()==1? Color.parseColor("#2EAE73") :Color.parseColor("#E84444")); } }
1,427
0.728039
0.71539
46
29.956522
31.015394
131
false
false
0
0
0
0
0
0
0.608696
false
false
10
3817a5beacd87c444a140572478f89e728c085ee
28,157,805,661,303
d8bb23ec10964c7e65e08ec8db2605308649a39b
/app/src/main/java/com/netlify/thelusina/acalc/CalculatorExpressionBuilder.java
b991cf30fb00672f731f6d12442c5b3e54c586ea
[ "MIT" ]
permissive
BrianLusina/ACalc
https://github.com/BrianLusina/ACalc
5b7f6877c7bfd96c95e2f7806ca98de21ef89439
bffa7a5d096c6ff7ea1dffe8088ea90d69331b23
refs/heads/master
2020-12-03T18:47:19.661000
2017-01-19T05:38:59
2017-01-19T05:38:59
66,824,305
0
1
null
false
2017-01-19T05:39:00
2016-08-29T08:09:16
2017-01-19T03:42:38
2017-01-19T05:39:00
681
0
1
0
Java
null
null
package com.netlify.thelusina.acalc; import android.text.SpannableStringBuilder; import android.text.TextUtils; public class CalculatorExpressionBuilder extends SpannableStringBuilder { private final CalculatorExpressionTokenizer mTokenizer; private boolean mIsEdited; public CalculatorExpressionBuilder( CharSequence text, CalculatorExpressionTokenizer tokenizer, boolean isEdited) { super(text); mTokenizer = tokenizer; mIsEdited = isEdited; } @Override public SpannableStringBuilder replace(int start, int end, CharSequence tb, int tbstart, int tbend) { if (start != length() || end != length()) { mIsEdited = true; return super.replace(start, end, tb, tbstart, tbend); } String appendExpr = mTokenizer.getNormalizedExpression(tb.subSequence(tbstart, tbend).toString()); if (appendExpr.length() == 1) { final String expr = mTokenizer.getNormalizedExpression(toString()); switch (appendExpr.charAt(0)) { case '.': // don't allow two decimals in the same number final int index = expr.lastIndexOf('.'); if (index != -1 && TextUtils.isDigitsOnly(expr.substring(index + 1, start))) { appendExpr = ""; } break; case '+': case '*': case '/': // don't allow leading operator if (start == 0) { appendExpr = ""; break; } // don't allow multiple successive operators while (start > 0 && "+-*/".indexOf(expr.charAt(start - 1)) != -1) { --start; } // fall through case '-': // don't allow -- or +- if (start > 0 && "+-".indexOf(expr.charAt(start - 1)) != -1) { --start; } // mark as edited since operators can always be appended mIsEdited = true; break; default: break; } } // since this is the first edit replace the entire string if (!mIsEdited && appendExpr.length() > 0) { start = 0; mIsEdited = true; } appendExpr = mTokenizer.getLocalizedExpression(appendExpr); return super.replace(start, end, appendExpr, 0, appendExpr.length()); } }
UTF-8
Java
2,726
java
CalculatorExpressionBuilder.java
Java
[]
null
[]
package com.netlify.thelusina.acalc; import android.text.SpannableStringBuilder; import android.text.TextUtils; public class CalculatorExpressionBuilder extends SpannableStringBuilder { private final CalculatorExpressionTokenizer mTokenizer; private boolean mIsEdited; public CalculatorExpressionBuilder( CharSequence text, CalculatorExpressionTokenizer tokenizer, boolean isEdited) { super(text); mTokenizer = tokenizer; mIsEdited = isEdited; } @Override public SpannableStringBuilder replace(int start, int end, CharSequence tb, int tbstart, int tbend) { if (start != length() || end != length()) { mIsEdited = true; return super.replace(start, end, tb, tbstart, tbend); } String appendExpr = mTokenizer.getNormalizedExpression(tb.subSequence(tbstart, tbend).toString()); if (appendExpr.length() == 1) { final String expr = mTokenizer.getNormalizedExpression(toString()); switch (appendExpr.charAt(0)) { case '.': // don't allow two decimals in the same number final int index = expr.lastIndexOf('.'); if (index != -1 && TextUtils.isDigitsOnly(expr.substring(index + 1, start))) { appendExpr = ""; } break; case '+': case '*': case '/': // don't allow leading operator if (start == 0) { appendExpr = ""; break; } // don't allow multiple successive operators while (start > 0 && "+-*/".indexOf(expr.charAt(start - 1)) != -1) { --start; } // fall through case '-': // don't allow -- or +- if (start > 0 && "+-".indexOf(expr.charAt(start - 1)) != -1) { --start; } // mark as edited since operators can always be appended mIsEdited = true; break; default: break; } } // since this is the first edit replace the entire string if (!mIsEdited && appendExpr.length() > 0) { start = 0; mIsEdited = true; } appendExpr = mTokenizer.getLocalizedExpression(appendExpr); return super.replace(start, end, appendExpr, 0, appendExpr.length()); } }
2,726
0.488995
0.483859
76
34.86842
26.774075
98
false
false
0
0
0
0
0
0
0.578947
false
false
10
37dc2d117423779da60868a47b438b23a3a5893c
16,801,912,072,648
f12a5e7d0345475d037d651ad23b0d91122e0bf7
/SONRAY Calendar/src/sonraycalendar/EventButton.java
4b7c7c44487a0f0fa5812045bcce9ffdd2de42c4
[]
no_license
nrudba12/ICS4U-Summative-Project
https://github.com/nrudba12/ICS4U-Summative-Project
7d93b5ff6704fb9267c8d9b7aa16154edc13e577
2a91a6680b750c9319f76e0236aead7f0bd50459
refs/heads/master
2020-04-10T18:03:51.099000
2019-01-23T14:27:30
2019-01-23T14:27:30
161,192,851
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sonraycalendar; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; @SuppressWarnings("serial") public class EventButton extends JButton { //used by every button in program private boolean hovering; public boolean pressed; //can be set and seen easily; much convenient than getter and setter //since need to continually get and set value of pressed and no point in getter and no logic //needed to set and/or see public void init(Runnable runnable) { setOpaque(false); setContentAreaFilled(false); setBorderPainted(false); addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { hovering = true; Manager.getInstance().repaint(); } @Override public void mouseExited(MouseEvent e) { hovering = false; Manager.getInstance().repaint(); } @Override public void mousePressed(MouseEvent e) { runnable.run(); //behaviour different for every button, unlike mouseEntered() and mouseExited(), //whose behaviours are same (just to change colour) } }); } public boolean hovering() { return hovering; } }
UTF-8
Java
1,198
java
EventButton.java
Java
[]
null
[]
package sonraycalendar; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; @SuppressWarnings("serial") public class EventButton extends JButton { //used by every button in program private boolean hovering; public boolean pressed; //can be set and seen easily; much convenient than getter and setter //since need to continually get and set value of pressed and no point in getter and no logic //needed to set and/or see public void init(Runnable runnable) { setOpaque(false); setContentAreaFilled(false); setBorderPainted(false); addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { hovering = true; Manager.getInstance().repaint(); } @Override public void mouseExited(MouseEvent e) { hovering = false; Manager.getInstance().repaint(); } @Override public void mousePressed(MouseEvent e) { runnable.run(); //behaviour different for every button, unlike mouseEntered() and mouseExited(), //whose behaviours are same (just to change colour) } }); } public boolean hovering() { return hovering; } }
1,198
0.702838
0.702838
42
26.571428
25.623783
100
false
false
0
0
0
0
0
0
2.238095
false
false
10
e25a2b6ea80d39c15e30628c5201707d8b81ac95
25,821,343,416,142
e35a10bf66291e16f7e966b914e95ef58440d986
/qbit/core/src/main/java/io/advantageous/qbit/config/PropertyResolver.java
0c9ca7e4c022a8d32f98b81dd86f25119ff263f8
[ "Apache-2.0" ]
permissive
slachiewicz/qbit
https://github.com/slachiewicz/qbit
2ab46cacd662b405507775fe1357b3a563cc756b
b5060b83f577703a083fe0e84baa87f05cf4bf26
refs/heads/master
2021-01-21T08:46:22.928000
2015-12-28T20:49:38
2015-12-28T20:49:38
48,741,360
1
0
Apache-2.0
true
2018-12-30T21:18:20
2015-12-29T10:08:03
2015-12-29T10:08:07
2018-12-30T21:17:37
15,475
0
0
1
Java
false
null
package io.advantageous.qbit.config; import io.advantageous.boon.core.Conversions; import java.util.Properties; /** * Used for builders that need to be set from system property overrides and such. * It is essentially a way to get at properties stored in other property systems. */ public interface PropertyResolver { static PropertyResolver createPropertiesPropertyResolver(final String prefix, final Properties properties) { return propertyName -> properties.getProperty(prefix + propertyName); } static PropertyResolver createSystemPropertyResolver(final String prefix) { return createPropertiesPropertyResolver(prefix, System.getProperties()); } Object getProperty(final String propertyName); default Integer getIntegerProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).intValue(); } else if (property instanceof Enum) { return ((Enum) property).ordinal(); } else if (property instanceof CharSequence) { return Integer.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Integer getIntegerProperty(final String propertyName, final int defaultValue) { final Integer value = getIntegerProperty(propertyName); return value == null ? defaultValue : value; } default Boolean getBooleanProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Boolean) { return ((Boolean) property); } else if (property instanceof CharSequence) { return Boolean.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Boolean getBooleanProperty(final String propertyName, final boolean defaultValue) { final Boolean value = getBooleanProperty(propertyName); return value == null ? defaultValue : value; } default Long getLongProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).longValue(); } else if (property instanceof Enum) { return (long) ((Enum) property).ordinal(); } else if (property instanceof CharSequence) { return Long.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Long getLongProperty(final String propertyName, final long defaultValue) { final Long value = getLongProperty(propertyName); return value == null ? defaultValue : value; } default Double getDoubleProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).doubleValue(); } else if (property instanceof CharSequence) { return Double.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Double getDoubleProperty(final String propertyName, final double defaultValue) { final Double value = getDoubleProperty(propertyName); return value == null ? defaultValue : value; } default Float getFloatProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).floatValue(); } else if (property instanceof CharSequence) { return Float.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Float getFloatProperty(final String propertyName, final float defaultValue) { final Float value = getFloatProperty(propertyName); return value == null ? defaultValue : value; } default String getStringProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property != null) { return property.toString(); } else { return null; } } default String getStringProperty(final String propertyName, final String defaultValue) { final String value = getStringProperty(propertyName); return value == null ? defaultValue : value; } default <T> T getGenericProperty(final String propertyName, Class<T> type) { final Object value = getProperty(propertyName); if (value != null) { return Conversions.coerce(type, value); } else { return null; } } default <T> T getGenericPropertyWithDefault(final String propertyName, final T defaultValue) { @SuppressWarnings("unchecked") final T value = getGenericProperty(propertyName, (Class<T>) defaultValue.getClass()); return value == null ? defaultValue : value; } }
UTF-8
Java
5,728
java
PropertyResolver.java
Java
[]
null
[]
package io.advantageous.qbit.config; import io.advantageous.boon.core.Conversions; import java.util.Properties; /** * Used for builders that need to be set from system property overrides and such. * It is essentially a way to get at properties stored in other property systems. */ public interface PropertyResolver { static PropertyResolver createPropertiesPropertyResolver(final String prefix, final Properties properties) { return propertyName -> properties.getProperty(prefix + propertyName); } static PropertyResolver createSystemPropertyResolver(final String prefix) { return createPropertiesPropertyResolver(prefix, System.getProperties()); } Object getProperty(final String propertyName); default Integer getIntegerProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).intValue(); } else if (property instanceof Enum) { return ((Enum) property).ordinal(); } else if (property instanceof CharSequence) { return Integer.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Integer getIntegerProperty(final String propertyName, final int defaultValue) { final Integer value = getIntegerProperty(propertyName); return value == null ? defaultValue : value; } default Boolean getBooleanProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Boolean) { return ((Boolean) property); } else if (property instanceof CharSequence) { return Boolean.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Boolean getBooleanProperty(final String propertyName, final boolean defaultValue) { final Boolean value = getBooleanProperty(propertyName); return value == null ? defaultValue : value; } default Long getLongProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).longValue(); } else if (property instanceof Enum) { return (long) ((Enum) property).ordinal(); } else if (property instanceof CharSequence) { return Long.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Long getLongProperty(final String propertyName, final long defaultValue) { final Long value = getLongProperty(propertyName); return value == null ? defaultValue : value; } default Double getDoubleProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).doubleValue(); } else if (property instanceof CharSequence) { return Double.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Double getDoubleProperty(final String propertyName, final double defaultValue) { final Double value = getDoubleProperty(propertyName); return value == null ? defaultValue : value; } default Float getFloatProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property instanceof Number) { return ((Number) property).floatValue(); } else if (property instanceof CharSequence) { return Float.valueOf(property.toString()); } else if (property == null) { return null; } else { throw new IllegalStateException("Unexpected type " + property.getClass().getName()); } } default Float getFloatProperty(final String propertyName, final float defaultValue) { final Float value = getFloatProperty(propertyName); return value == null ? defaultValue : value; } default String getStringProperty(final String propertyName) { final Object property = getProperty(propertyName); if (property != null) { return property.toString(); } else { return null; } } default String getStringProperty(final String propertyName, final String defaultValue) { final String value = getStringProperty(propertyName); return value == null ? defaultValue : value; } default <T> T getGenericProperty(final String propertyName, Class<T> type) { final Object value = getProperty(propertyName); if (value != null) { return Conversions.coerce(type, value); } else { return null; } } default <T> T getGenericPropertyWithDefault(final String propertyName, final T defaultValue) { @SuppressWarnings("unchecked") final T value = getGenericProperty(propertyName, (Class<T>) defaultValue.getClass()); return value == null ? defaultValue : value; } }
5,728
0.643506
0.643506
160
34.799999
31.278147
124
false
false
0
0
0
0
0
0
0.40625
false
false
10
c571fd4d3f7c426b834a5df3d090fe192446eb7a
29,480,655,533,442
ee530f6285a4adce0ca19a5164f574fee5ba76b7
/src/main/java/cn/itcast/app16/UserAction.java
cde5ee6396cd8740f81fa4fb6703ae922f0ecf39
[]
no_license
kgy-study-Spring/maven_chuanzhi_springmvc02
https://github.com/kgy-study-Spring/maven_chuanzhi_springmvc02
79b3ab504cf68c022f3aae0d63748242f4866cc8
a87e04b381c32d0f86cc131d78facfc01bca9378
refs/heads/master
2021-08-19T19:55:37.756000
2017-11-27T09:19:18
2017-11-27T09:19:18
112,174,342
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.itcast.app16; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * 控制器 * @author AdminTC */ @Controller @RequestMapping(value="/user") public class UserAction { /** * 用户注册,只能接收POST请求 */ @RequestMapping(method=RequestMethod.POST,value="/register") public String registerMethod(Model model,String username,String salary) throws Exception{ System.out.println("用户注册-->" + username + ":" + salary); model.addAttribute("message", "员工注册成功"); return "/jsp/success.jsp"; } /** * 用户登录,即能接收POST请求,又能接收GET请求 */ @RequestMapping(value="/login") public String loginMethod(Model model,String username) throws Exception{ System.out.println("用户登录-->" + username); model.addAttribute("message","员工登录成功"); return "/jsp/success.jsp"; } }
UTF-8
Java
1,037
java
UserAction.java
Java
[ { "context": ".annotation.RequestMethod;\n\n/**\n * 控制器\n * @author AdminTC\n */\n@Controller\n@RequestMapping(value=\"/user\")\npu", "end": 269, "score": 0.9996808767318726, "start": 262, "tag": "USERNAME", "value": "AdminTC" } ]
null
[]
package cn.itcast.app16; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * 控制器 * @author AdminTC */ @Controller @RequestMapping(value="/user") public class UserAction { /** * 用户注册,只能接收POST请求 */ @RequestMapping(method=RequestMethod.POST,value="/register") public String registerMethod(Model model,String username,String salary) throws Exception{ System.out.println("用户注册-->" + username + ":" + salary); model.addAttribute("message", "员工注册成功"); return "/jsp/success.jsp"; } /** * 用户登录,即能接收POST请求,又能接收GET请求 */ @RequestMapping(value="/login") public String loginMethod(Model model,String username) throws Exception{ System.out.println("用户登录-->" + username); model.addAttribute("message","员工登录成功"); return "/jsp/success.jsp"; } }
1,037
0.733119
0.730975
36
24.916666
24.269751
90
false
false
0
0
0
0
0
0
1.222222
false
false
10
021d05e4edd9204ef56201db9b07978e7b065cf3
16,466,904,642,858
e527b868e60a8ef5d6a2187e2129199400bfc634
/reviewtracker/src/main/java/com/milo/amz/review/domain/ShippingAddress.java
f75ee0d8e63684f06d245b2bddf9e6e21af02634
[]
no_license
oraclemohammadi/ReviewManagement
https://github.com/oraclemohammadi/ReviewManagement
93d852e53b3c717e4d2d0580d7198dfc740792bb
d8f72dd8060e4447910814560374c08717cdc602
refs/heads/master
2021-01-13T12:19:02.693000
2017-01-31T05:49:13
2017-01-31T05:49:13
77,941,885
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.milo.amz.review.domain; import io.swagger.annotations.ApiModel; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.Objects; /** * not an ignored comment */ @ApiModel(description = "not an ignored comment") @Entity @Table(name = "shipping_address") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class ShippingAddress implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Column(name = "name", nullable = false) private String name; @NotNull @Column(name = "address_line_1", nullable = false) private String addressLine1; @Column(name = "address_line_2") private String addressLine2; @Column(name = "address_line_3") private String addressLine3; @NotNull @Column(name = "city", nullable = false) private String city; @NotNull @Column(name = "county", nullable = false) private String county; @Column(name = "postal_code") private String postalCode; @NotNull @Column(name = "district", nullable = false) private String district; @NotNull @Column(name = "state_or_region", nullable = false) private String stateOrRegion; @Column(name = "phone") private String phone; @ManyToOne private PurchaseOrder purchaseOrder; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public ShippingAddress name(String name) { this.name = name; return this; } public void setName(String name) { this.name = name; } public String getAddressLine1() { return addressLine1; } public ShippingAddress addressLine1(String addressLine1) { this.addressLine1 = addressLine1; return this; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public ShippingAddress addressLine2(String addressLine2) { this.addressLine2 = addressLine2; return this; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getAddressLine3() { return addressLine3; } public ShippingAddress addressLine3(String addressLine3) { this.addressLine3 = addressLine3; return this; } public void setAddressLine3(String addressLine3) { this.addressLine3 = addressLine3; } public String getCity() { return city; } public ShippingAddress city(String city) { this.city = city; return this; } public void setCity(String city) { this.city = city; } public String getCounty() { return county; } public ShippingAddress county(String county) { this.county = county; return this; } public void setCounty(String county) { this.county = county; } public String getPostalCode() { return postalCode; } public ShippingAddress postalCode(String postalCode) { this.postalCode = postalCode; return this; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getDistrict() { return district; } public ShippingAddress district(String district) { this.district = district; return this; } public void setDistrict(String district) { this.district = district; } public String getStateOrRegion() { return stateOrRegion; } public ShippingAddress stateOrRegion(String stateOrRegion) { this.stateOrRegion = stateOrRegion; return this; } public void setStateOrRegion(String stateOrRegion) { this.stateOrRegion = stateOrRegion; } public String getPhone() { return phone; } public ShippingAddress phone(String phone) { this.phone = phone; return this; } public void setPhone(String phone) { this.phone = phone; } public PurchaseOrder getPurchaseOrder() { return purchaseOrder; } public ShippingAddress purchaseOrder(PurchaseOrder purchaseOrder) { this.purchaseOrder = purchaseOrder; return this; } public void setPurchaseOrder(PurchaseOrder purchaseOrder) { this.purchaseOrder = purchaseOrder; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ShippingAddress shippingAddress = (ShippingAddress) o; if (shippingAddress.id == null || id == null) { return false; } return Objects.equals(id, shippingAddress.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "ShippingAddress{" + "id=" + id + ", name='" + name + "'" + ", addressLine1='" + addressLine1 + "'" + ", addressLine2='" + addressLine2 + "'" + ", addressLine3='" + addressLine3 + "'" + ", city='" + city + "'" + ", county='" + county + "'" + ", postalCode='" + postalCode + "'" + ", district='" + district + "'" + ", stateOrRegion='" + stateOrRegion + "'" + ", phone='" + phone + "'" + '}'; } }
UTF-8
Java
5,889
java
ShippingAddress.java
Java
[]
null
[]
package com.milo.amz.review.domain; import io.swagger.annotations.ApiModel; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.Objects; /** * not an ignored comment */ @ApiModel(description = "not an ignored comment") @Entity @Table(name = "shipping_address") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class ShippingAddress implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Column(name = "name", nullable = false) private String name; @NotNull @Column(name = "address_line_1", nullable = false) private String addressLine1; @Column(name = "address_line_2") private String addressLine2; @Column(name = "address_line_3") private String addressLine3; @NotNull @Column(name = "city", nullable = false) private String city; @NotNull @Column(name = "county", nullable = false) private String county; @Column(name = "postal_code") private String postalCode; @NotNull @Column(name = "district", nullable = false) private String district; @NotNull @Column(name = "state_or_region", nullable = false) private String stateOrRegion; @Column(name = "phone") private String phone; @ManyToOne private PurchaseOrder purchaseOrder; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public ShippingAddress name(String name) { this.name = name; return this; } public void setName(String name) { this.name = name; } public String getAddressLine1() { return addressLine1; } public ShippingAddress addressLine1(String addressLine1) { this.addressLine1 = addressLine1; return this; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public ShippingAddress addressLine2(String addressLine2) { this.addressLine2 = addressLine2; return this; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getAddressLine3() { return addressLine3; } public ShippingAddress addressLine3(String addressLine3) { this.addressLine3 = addressLine3; return this; } public void setAddressLine3(String addressLine3) { this.addressLine3 = addressLine3; } public String getCity() { return city; } public ShippingAddress city(String city) { this.city = city; return this; } public void setCity(String city) { this.city = city; } public String getCounty() { return county; } public ShippingAddress county(String county) { this.county = county; return this; } public void setCounty(String county) { this.county = county; } public String getPostalCode() { return postalCode; } public ShippingAddress postalCode(String postalCode) { this.postalCode = postalCode; return this; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getDistrict() { return district; } public ShippingAddress district(String district) { this.district = district; return this; } public void setDistrict(String district) { this.district = district; } public String getStateOrRegion() { return stateOrRegion; } public ShippingAddress stateOrRegion(String stateOrRegion) { this.stateOrRegion = stateOrRegion; return this; } public void setStateOrRegion(String stateOrRegion) { this.stateOrRegion = stateOrRegion; } public String getPhone() { return phone; } public ShippingAddress phone(String phone) { this.phone = phone; return this; } public void setPhone(String phone) { this.phone = phone; } public PurchaseOrder getPurchaseOrder() { return purchaseOrder; } public ShippingAddress purchaseOrder(PurchaseOrder purchaseOrder) { this.purchaseOrder = purchaseOrder; return this; } public void setPurchaseOrder(PurchaseOrder purchaseOrder) { this.purchaseOrder = purchaseOrder; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ShippingAddress shippingAddress = (ShippingAddress) o; if (shippingAddress.id == null || id == null) { return false; } return Objects.equals(id, shippingAddress.id); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "ShippingAddress{" + "id=" + id + ", name='" + name + "'" + ", addressLine1='" + addressLine1 + "'" + ", addressLine2='" + addressLine2 + "'" + ", addressLine3='" + addressLine3 + "'" + ", city='" + city + "'" + ", county='" + county + "'" + ", postalCode='" + postalCode + "'" + ", district='" + district + "'" + ", stateOrRegion='" + stateOrRegion + "'" + ", phone='" + phone + "'" + '}'; } }
5,889
0.607234
0.599932
253
22.27668
19.358347
71
false
false
0
0
0
0
0
0
0.375494
false
false
10
d9e28466ce0195b36c2d9a1e96f2594832847c7c
15,564,961,508,231
aad82f53c79bb1b0fa0523ca0b9dd18d8f39ec6d
/Sonitha/28-01-2020/j28_q13_addTreeSetToAnotherTreeSet.java
cf7d4b8218afc41fa648e8e3250e7a55538b37bf
[]
no_license
Cognizant-Training-Coimbatore/Lab-Excercise-Batch-2
https://github.com/Cognizant-Training-Coimbatore/Lab-Excercise-Batch-2
54b4d87238949f3ffa0b3f0209089a1beb93befe
58d65b309377b1b86a54d541c3d1ef5acb868381
refs/heads/master
2020-12-22T06:12:23.330000
2020-03-17T12:32:29
2020-03-17T12:32:29
236,676,704
1
0
null
false
2020-10-13T19:56:02
2020-01-28T07:00:34
2020-03-17T12:32:32
2020-10-13T19:56:00
166,778
0
0
1
Java
false
false
import java.util.TreeSet; public class j28_q13_addTreeSetToAnotherTreeSet { public static void main(String[] args) { TreeSet<String> myset = new TreeSet<String>(); myset.add("Item1"); myset.add("Item2"); myset.add("Item3"); myset.add("Item4"); myset.add("Item5"); myset.add("Item6"); System.out.println("the elements in first set is : "+myset); TreeSet<String> set = new TreeSet<String>(); set.add("Item11"); set.add("Item21"); set.add("Item31"); set.add("Item41"); set.add("Item51"); set.add("Item61"); System.out.println("the elements in second set is :"+ set); myset.addAll(set); System.out.println("After adding the set 2 in set1 : "+myset); } }
UTF-8
Java
723
java
j28_q13_addTreeSetToAnotherTreeSet.java
Java
[]
null
[]
import java.util.TreeSet; public class j28_q13_addTreeSetToAnotherTreeSet { public static void main(String[] args) { TreeSet<String> myset = new TreeSet<String>(); myset.add("Item1"); myset.add("Item2"); myset.add("Item3"); myset.add("Item4"); myset.add("Item5"); myset.add("Item6"); System.out.println("the elements in first set is : "+myset); TreeSet<String> set = new TreeSet<String>(); set.add("Item11"); set.add("Item21"); set.add("Item31"); set.add("Item41"); set.add("Item51"); set.add("Item61"); System.out.println("the elements in second set is :"+ set); myset.addAll(set); System.out.println("After adding the set 2 in set1 : "+myset); } }
723
0.630705
0.59751
28
23.821428
19.229912
64
false
false
0
0
0
0
0
0
2.107143
false
false
10
f5f2f3aed8f84b05e8fe0c2ca2ec61f7eac198aa
29,549,375,019,924
c70dd05cc2e87060866ad848d58625faf86e2480
/D2D/src/model/bully/BullyActionEvent.java
4ed5be2037178df923151b099a63411bb2c80419
[]
no_license
Michael-Hodges/mars_robots_dist_system
https://github.com/Michael-Hodges/mars_robots_dist_system
30b422544774fcc4325c7973cc8f38321b2c9e12
51825c4d24f8b0b936e00a7b1ba929d7a457ecae
refs/heads/main
2023-07-11T00:44:17.462000
2021-08-19T20:11:44
2021-08-19T20:11:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.bully; import model.ActionPeerEvent; import model.PeerEvent; /** * Implementation of ActionPeerEvent interface, to deal with ActionEvents in the bully algorithm. */ public class BullyActionEvent extends ActionPeerEvent { BullyAlgorithmParticipant respondent; BullyAlgorithmParticipantImpl.Status respondentStatus; /** * Constructs a new BullyActionEvent with a given source, id, and PeerEvent * @param source source of event * @param id id of event * @param event PeerEvent to set as event */ public BullyActionEvent(Object source, int id, PeerEvent event) { super(source, id, event); respondent = null; respondentStatus = BullyAlgorithmParticipantImpl.Status.Unknown; } /** * Returns the respondent of the event * @return respondent for event */ public BullyAlgorithmParticipant getRespondent() { return this.respondent; } /** * Returns status of the respondent of the event * @return Respondent status */ public BullyAlgorithmParticipantImpl.Status getRespondentStatus() { return this.respondentStatus; } }
UTF-8
Java
1,170
java
BullyActionEvent.java
Java
[]
null
[]
package model.bully; import model.ActionPeerEvent; import model.PeerEvent; /** * Implementation of ActionPeerEvent interface, to deal with ActionEvents in the bully algorithm. */ public class BullyActionEvent extends ActionPeerEvent { BullyAlgorithmParticipant respondent; BullyAlgorithmParticipantImpl.Status respondentStatus; /** * Constructs a new BullyActionEvent with a given source, id, and PeerEvent * @param source source of event * @param id id of event * @param event PeerEvent to set as event */ public BullyActionEvent(Object source, int id, PeerEvent event) { super(source, id, event); respondent = null; respondentStatus = BullyAlgorithmParticipantImpl.Status.Unknown; } /** * Returns the respondent of the event * @return respondent for event */ public BullyAlgorithmParticipant getRespondent() { return this.respondent; } /** * Returns status of the respondent of the event * @return Respondent status */ public BullyAlgorithmParticipantImpl.Status getRespondentStatus() { return this.respondentStatus; } }
1,170
0.698291
0.698291
41
27.536585
25.949385
97
false
false
0
0
0
0
0
0
0.414634
false
false
10
098044ffcb1c869f32a432b93ddcd6626b166773
14,680,198,280,212
efdce4ed5061fdd9e3c7fcacccc7b31537723e9a
/Java Files/POO/T4J-Daniel-FX+Spring/T4J/src/main/java/t4j/app/model/RegistoCompetenciasTecnicas.java
3046c316c61df02d2727c9e6469c9924fd470866
[]
no_license
jrzabott/exerciciosUpskill
https://github.com/jrzabott/exerciciosUpskill
1d48c75f342be6b6c42163a23bf5b58f19694e75
70b2ab58e1bed7be20468484bd48ed4f3bdd62de
refs/heads/main
2023-04-05T18:57:48.219000
2021-04-26T08:25:29
2021-04-26T08:25:29
309,065,593
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package t4j.app.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Objects; import t4j.app.exception.ElementoDuplicadoException; import t4j.app.exception.ElementoNaoExistenteException; @SuppressWarnings({"serial", "ClassWithoutLogger"}) public class RegistoCompetenciasTecnicas implements Serializable { /** * Variável de instância - contentor do tipo ArrayList que guarda todas as instâncias do tipo competência técnica */ private ArrayList<CompetenciaTecnica> competenciasTecnicas; /** * Construtor completo de lista de competências técnicas * * @param competenciasTecnicas */ public RegistoCompetenciasTecnicas(ArrayList<CompetenciaTecnica> competenciasTecnicas) { this.competenciasTecnicas = new ArrayList<>(competenciasTecnicas); } /** * Construtor vazio de lista de competências técnicas */ public RegistoCompetenciasTecnicas() { this.competenciasTecnicas = new ArrayList<>(); } /** * Construtor cópia de lista de competências técnicas * * @param outroRegistoCompetenciasTecnicas instância do tipo lista de competências técnicas a ser copiada */ public RegistoCompetenciasTecnicas(RegistoCompetenciasTecnicas outroRegistoCompetenciasTecnicas) { this.competenciasTecnicas = new ArrayList<>(outroRegistoCompetenciasTecnicas.competenciasTecnicas); } /** * * @return contentor do tipo ArrayList que guarda todas as instâncias do tipo competência técnica */ public ArrayList<CompetenciaTecnica> getCompetenciasTecnicas() { return competenciasTecnicas; } /** * * @return */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Registo de competências técnicas:\n"); for (int i = 0; i < competenciasTecnicas.size(); i++) { competenciasTecnicas.get(i).toString(); sb.append(competenciasTecnicas.get(i).toString()); } return sb.toString(); } /** * * @param codigoCompetenciaTecnica código de competências técnicas * @return a competência técnica ao qual pertence o código introduzido por parâmetro */ public CompetenciaTecnica getCompetenciaTecnicaByCodigoCompetenciaTecnica(String codigoCompetenciaTecnica) { for (CompetenciaTecnica competenciaTecnica : competenciasTecnicas) { if (competenciaTecnica.getCodigoCompetenciaTecnica().equalsIgnoreCase(codigoCompetenciaTecnica)) { return competenciaTecnica; } } return null; } /** * * @param competenciaTecnica instância do tipo competência técnica a ser adicionada ao contentor competenciasTecnicas * @return devolve verdadeiro se adicionou e falso se não adicionou */ public boolean addCompetenciaTecnica(CompetenciaTecnica competenciaTecnica) { return (validaCompetenciaTecnica(competenciaTecnica) != null) ? competenciasTecnicas.add(competenciaTecnica) : false; } /** * * @param codCT * @param ct */ public void updateCompetenciaTecnica(String codCT, CompetenciaTecnica ct) { CompetenciaTecnica competenciaTecnica = null; boolean updated = false; for (int i = 0; i < this.competenciasTecnicas.size(); i++) { competenciaTecnica = this.competenciasTecnicas.get(i); if (competenciaTecnica.getCodigoCompetenciaTecnica().equals(codCT)) { this.competenciasTecnicas.set(i, ct); updated = true; } } if (updated == false) { throw new ElementoNaoExistenteException(codCT + ": Não existe esta competência técnica!!"); } } /** * * @param codCT */ public void removeCompetenciaTecnica(String codCT) { CompetenciaTecnica competenciaTecnica = null; for (int i = 0; i < this.competenciasTecnicas.size(); i++) { competenciaTecnica = this.competenciasTecnicas.get(i); if (competenciaTecnica.getCodigoCompetenciaTecnica().equals(codCT)) { this.competenciasTecnicas.remove(i); return; } else { throw new ElementoNaoExistenteException(codCT + ": Não existe esta competência técnica!!"); } } } /** * * @param outroObjeto instância de lista de competências técnicas a ser comparada * @return reescrita do método equals e retorna um booleano */ @Override public boolean equals(Object outroObjeto) { if (this == outroObjeto) { return true; } if (outroObjeto == null || getClass() != outroObjeto.getClass()) { return false; } RegistoCompetenciasTecnicas outroRegistoCompetenciaTecnica = (RegistoCompetenciasTecnicas) outroObjeto; return competenciasTecnicas.equals(outroRegistoCompetenciaTecnica.competenciasTecnicas); } /** * * @return Override do hashCode */ @Override public int hashCode() { int hash = 7; hash = 53 * hash + Objects.hashCode(this.competenciasTecnicas); return hash; } /** * * @param competenciaTecnica instância do tipo competência técnica a ser validada * @return retorna a instância do tipo competência técnica para adição ao contentor depois de validada * @throws ElementoDuplicadoException */ private CompetenciaTecnica validaCompetenciaTecnica(CompetenciaTecnica competenciaTecnica) throws ElementoDuplicadoException { if (getCompetenciaTecnicaByCodigoCompetenciaTecnica(competenciaTecnica.getCodigoCompetenciaTecnica()) == null) { return competenciaTecnica; } else { throw new ElementoDuplicadoException("Já existe uma competência técnica com esse código!"); } } }
UTF-8
Java
5,982
java
RegistoCompetenciasTecnicas.java
Java
[]
null
[]
package t4j.app.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Objects; import t4j.app.exception.ElementoDuplicadoException; import t4j.app.exception.ElementoNaoExistenteException; @SuppressWarnings({"serial", "ClassWithoutLogger"}) public class RegistoCompetenciasTecnicas implements Serializable { /** * Variável de instância - contentor do tipo ArrayList que guarda todas as instâncias do tipo competência técnica */ private ArrayList<CompetenciaTecnica> competenciasTecnicas; /** * Construtor completo de lista de competências técnicas * * @param competenciasTecnicas */ public RegistoCompetenciasTecnicas(ArrayList<CompetenciaTecnica> competenciasTecnicas) { this.competenciasTecnicas = new ArrayList<>(competenciasTecnicas); } /** * Construtor vazio de lista de competências técnicas */ public RegistoCompetenciasTecnicas() { this.competenciasTecnicas = new ArrayList<>(); } /** * Construtor cópia de lista de competências técnicas * * @param outroRegistoCompetenciasTecnicas instância do tipo lista de competências técnicas a ser copiada */ public RegistoCompetenciasTecnicas(RegistoCompetenciasTecnicas outroRegistoCompetenciasTecnicas) { this.competenciasTecnicas = new ArrayList<>(outroRegistoCompetenciasTecnicas.competenciasTecnicas); } /** * * @return contentor do tipo ArrayList que guarda todas as instâncias do tipo competência técnica */ public ArrayList<CompetenciaTecnica> getCompetenciasTecnicas() { return competenciasTecnicas; } /** * * @return */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Registo de competências técnicas:\n"); for (int i = 0; i < competenciasTecnicas.size(); i++) { competenciasTecnicas.get(i).toString(); sb.append(competenciasTecnicas.get(i).toString()); } return sb.toString(); } /** * * @param codigoCompetenciaTecnica código de competências técnicas * @return a competência técnica ao qual pertence o código introduzido por parâmetro */ public CompetenciaTecnica getCompetenciaTecnicaByCodigoCompetenciaTecnica(String codigoCompetenciaTecnica) { for (CompetenciaTecnica competenciaTecnica : competenciasTecnicas) { if (competenciaTecnica.getCodigoCompetenciaTecnica().equalsIgnoreCase(codigoCompetenciaTecnica)) { return competenciaTecnica; } } return null; } /** * * @param competenciaTecnica instância do tipo competência técnica a ser adicionada ao contentor competenciasTecnicas * @return devolve verdadeiro se adicionou e falso se não adicionou */ public boolean addCompetenciaTecnica(CompetenciaTecnica competenciaTecnica) { return (validaCompetenciaTecnica(competenciaTecnica) != null) ? competenciasTecnicas.add(competenciaTecnica) : false; } /** * * @param codCT * @param ct */ public void updateCompetenciaTecnica(String codCT, CompetenciaTecnica ct) { CompetenciaTecnica competenciaTecnica = null; boolean updated = false; for (int i = 0; i < this.competenciasTecnicas.size(); i++) { competenciaTecnica = this.competenciasTecnicas.get(i); if (competenciaTecnica.getCodigoCompetenciaTecnica().equals(codCT)) { this.competenciasTecnicas.set(i, ct); updated = true; } } if (updated == false) { throw new ElementoNaoExistenteException(codCT + ": Não existe esta competência técnica!!"); } } /** * * @param codCT */ public void removeCompetenciaTecnica(String codCT) { CompetenciaTecnica competenciaTecnica = null; for (int i = 0; i < this.competenciasTecnicas.size(); i++) { competenciaTecnica = this.competenciasTecnicas.get(i); if (competenciaTecnica.getCodigoCompetenciaTecnica().equals(codCT)) { this.competenciasTecnicas.remove(i); return; } else { throw new ElementoNaoExistenteException(codCT + ": Não existe esta competência técnica!!"); } } } /** * * @param outroObjeto instância de lista de competências técnicas a ser comparada * @return reescrita do método equals e retorna um booleano */ @Override public boolean equals(Object outroObjeto) { if (this == outroObjeto) { return true; } if (outroObjeto == null || getClass() != outroObjeto.getClass()) { return false; } RegistoCompetenciasTecnicas outroRegistoCompetenciaTecnica = (RegistoCompetenciasTecnicas) outroObjeto; return competenciasTecnicas.equals(outroRegistoCompetenciaTecnica.competenciasTecnicas); } /** * * @return Override do hashCode */ @Override public int hashCode() { int hash = 7; hash = 53 * hash + Objects.hashCode(this.competenciasTecnicas); return hash; } /** * * @param competenciaTecnica instância do tipo competência técnica a ser validada * @return retorna a instância do tipo competência técnica para adição ao contentor depois de validada * @throws ElementoDuplicadoException */ private CompetenciaTecnica validaCompetenciaTecnica(CompetenciaTecnica competenciaTecnica) throws ElementoDuplicadoException { if (getCompetenciaTecnicaByCodigoCompetenciaTecnica(competenciaTecnica.getCodigoCompetenciaTecnica()) == null) { return competenciaTecnica; } else { throw new ElementoDuplicadoException("Já existe uma competência técnica com esse código!"); } } }
5,982
0.669927
0.66841
165
34.933334
35.895664
130
false
false
0
0
0
0
0
0
0.30303
false
false
10
75e57d725bdfc024b77ce30990d0a95cae08826b
21,998,822,509,551
6e03f2d63ad9363c1f88318ace360deab69f30f5
/src/main/java/com/updateHelper/StatusCheckController.java
c4a176fb2453a7562234fb6f4aafee124664b4b9
[]
no_license
smjie2800/UpdateHelper
https://github.com/smjie2800/UpdateHelper
ccede140c8e69f4d0fb0f99b7c56946ed4163ca5
18d4c39cd7c06c4f0aca1737ed6f122c76f36793
refs/heads/master
2021-01-12T06:48:36.136000
2019-08-12T06:02:11
2019-08-12T06:02:11
76,824,861
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.updateHelper; import com.updateHelper.utils.Utils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Created with IntelliJ IDEA. * User: mzj * Date: 16-1-27 * Time: 下午2:13 * To change this template use File | Settings | File Templates. */ @Controller public class StatusCheckController { @Value("${application.message:Hello World}") private String message = "Hello World"; @RequestMapping("/statusCheckPage") public String statusCheckPage(String systemName, String urls, Model model) { return "reslut"; } @RequestMapping("/statusCheck") public String statusCheck(String systemName, String urls, Model model) { String[] urlsArray = urls.split(";"); String result = "<h3> status result<h3><br/>"; for (int i = 0; i < urlsArray.length; i++) { result += urlsArray[i] + " status is " + Utils.URLGet(urlsArray[i]) + "<br/>"; } model.addAttribute("result", result); return "reslut"; } } ;
UTF-8
Java
1,248
java
StatusCheckController.java
Java
[ { "context": "ping;\n\n/**\n * Created with IntelliJ IDEA.\n * User: mzj\n * Date: 16-1-27\n * Time: 下午2:13\n * To change thi", "end": 353, "score": 0.9995715618133545, "start": 350, "tag": "USERNAME", "value": "mzj" } ]
null
[]
package com.updateHelper; import com.updateHelper.utils.Utils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Created with IntelliJ IDEA. * User: mzj * Date: 16-1-27 * Time: 下午2:13 * To change this template use File | Settings | File Templates. */ @Controller public class StatusCheckController { @Value("${application.message:Hello World}") private String message = "Hello World"; @RequestMapping("/statusCheckPage") public String statusCheckPage(String systemName, String urls, Model model) { return "reslut"; } @RequestMapping("/statusCheck") public String statusCheck(String systemName, String urls, Model model) { String[] urlsArray = urls.split(";"); String result = "<h3> status result<h3><br/>"; for (int i = 0; i < urlsArray.length; i++) { result += urlsArray[i] + " status is " + Utils.URLGet(urlsArray[i]) + "<br/>"; } model.addAttribute("result", result); return "reslut"; } } ;
1,248
0.655949
0.646302
43
27.88372
25.698801
94
false
false
0
0
0
0
0
0
0.581395
false
false
10
bf6435dd3b6fb0ffa3ed199d755afdc6760e9f62
21,998,822,510,910
bf8c0f462c03adc75572cb83d35fd01974d62d25
/weiyi/app_patient/.svn/pristine/29/29af341eb3889d9ab1543292b2daf10d5ab8dacf.svn-base
d68ee7b4cc93d7169dc1248383c025bbbfb6b904
[]
no_license
JHoo1988/lqq
https://github.com/JHoo1988/lqq
16509f1e1482a8a803a4073a22cb4d195a54a840
2f539f8c13653c3534e5a2b733f7e7ded4a280e3
refs/heads/master
2016-06-17T07:40:13.804000
2015-11-16T09:23:31
2015-11-16T09:23:31
46,261,266
0
0
null
false
2015-12-11T03:14:23
2015-11-16T08:19:49
2015-11-16T09:33:56
2015-12-11T03:02:22
156,190
0
0
1
Java
null
null
package com.greenline.guahao.server.entity; public class NavigationDetail { private String explain; private String locationn; private String Photo; public String getExplain() { return explain; } public void setExplain(String explain) { this.explain = explain; } public String getLocationn() { return locationn; } public void setLocationn(String locationn) { this.locationn = locationn; } public String getPhoto() { return Photo; } public void setPhoto(String photo) { Photo = photo; } }
UTF-8
Java
518
29af341eb3889d9ab1543292b2daf10d5ab8dacf.svn-base
Java
[]
null
[]
package com.greenline.guahao.server.entity; public class NavigationDetail { private String explain; private String locationn; private String Photo; public String getExplain() { return explain; } public void setExplain(String explain) { this.explain = explain; } public String getLocationn() { return locationn; } public void setLocationn(String locationn) { this.locationn = locationn; } public String getPhoto() { return Photo; } public void setPhoto(String photo) { Photo = photo; } }
518
0.72973
0.72973
27
18.185184
14.714662
45
false
false
0
0
0
0
0
0
1.407407
false
false
10
3b7660ea9e48120b8aaf4cd121eedff9762ea2e1
12,781,822,713,712
359faad59ed1eb92b87c87df93dbbb7bda81a217
/src/main/java/com/spike/controller/BaseController.java
6c8ff4bf00a2fb7937c7267de09483ff73090129
[]
no_license
ExcelCodeM/spike-self
https://github.com/ExcelCodeM/spike-self
85392e7282de361984e133cd8bafbe94259723a6
ea8b96d15e784ca6e851595af54e9c6279c0c8ec
refs/heads/master
2022-06-29T04:30:43.946000
2019-08-28T18:09:29
2019-08-28T18:09:29
200,882,660
0
0
null
false
2022-06-17T02:25:02
2019-08-06T15:55:34
2019-08-28T18:10:19
2022-06-17T02:25:01
21
0
0
1
Java
false
false
package com.spike.controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //@CrossOrigin public class BaseController { }
UTF-8
Java
267
java
BaseController.java
Java
[]
null
[]
package com.spike.controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //@CrossOrigin public class BaseController { }
267
0.835206
0.835206
11
23.272728
25.388226
62
false
false
0
0
0
0
0
0
0.363636
false
false
10
4f6e3e5281b99b2c531a707e5c9054077d70722f
34,119,220,218,990
5830b2c7a0d5293cb68d0297e0340006c6907389
/src/test/java/org/onap/dmaap/mr/dme/client/HeaderReplyHandlerTest.java
0cc824dcf8d10cd042cad3ac87bc6f9407bab466
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
onap/dmaap-messagerouter-dmaapclient
https://github.com/onap/dmaap-messagerouter-dmaapclient
af892eee34c13d35cabb51dc575c3f041cfa934d
69a25137be1b27265b8ced62ac9b7faf4774e80b
refs/heads/master
2023-06-11T22:11:30.938000
2022-12-05T17:32:10
2022-12-05T17:32:14
115,765,884
0
0
NOASSERTION
false
2021-06-29T18:12:24
2017-12-30T01:28:55
2021-05-17T09:33:01
2021-06-29T18:12:24
1,219
0
0
1
Java
false
false
/*- * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2021 Orange. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.dmaap.mr.dme.client; import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertTrue; public class HeaderReplyHandlerTest { private HeaderReplyHandler handler = null; @Before public void setUp() throws Exception { handler = new HeaderReplyHandler(); } @After public void tearDown() throws Exception { } @Test public void testHandleFault() { handler.handleFault(null); assertTrue(true); } @Test public void testHandleEndpointFault() { handler.handleEndpointFault(null); assertTrue(true); } @Test public void testHandleReply() { Map<String, String> responseHeaders = new HashMap<String, String>(); responseHeaders.put("transactionId", "1234"); DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext("service", 200, new HashMap<String, String>(), responseHeaders, "routeOffer", "1.0.0", "http://"); handler.handleReply(responseData); assertTrue(true); } }
UTF-8
Java
2,351
java
HeaderReplyHandlerTest.java
Java
[]
null
[]
/*- * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright © 2021 Orange. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.dmaap.mr.dme.client; import com.att.aft.dme2.api.util.DME2ExchangeResponseContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertTrue; public class HeaderReplyHandlerTest { private HeaderReplyHandler handler = null; @Before public void setUp() throws Exception { handler = new HeaderReplyHandler(); } @After public void tearDown() throws Exception { } @Test public void testHandleFault() { handler.handleFault(null); assertTrue(true); } @Test public void testHandleEndpointFault() { handler.handleEndpointFault(null); assertTrue(true); } @Test public void testHandleReply() { Map<String, String> responseHeaders = new HashMap<String, String>(); responseHeaders.put("transactionId", "1234"); DME2ExchangeResponseContext responseData = new DME2ExchangeResponseContext("service", 200, new HashMap<String, String>(), responseHeaders, "routeOffer", "1.0.0", "http://"); handler.handleReply(responseData); assertTrue(true); } }
2,351
0.580426
0.569362
79
28.746836
29.420336
103
false
false
0
0
0
0
81
0.103404
0.43038
false
false
10
a9d4cb608f0fdb837c105a148952efafe086bc53
12,189,117,223,853
7f0e330cf3efab4e7487e5a7b00a01e099f93922
/othello_exp/PatternEvaluation_AB.java
48983b991e73dc03b2c8fbc9dca8940c95fae710
[]
no_license
shukai9/takao_prosym
https://github.com/shukai9/takao_prosym
79385866d5b9d0db37b44f03a10617d37b22f452
9268c3b1e5432ade8e45200572ec5684f3a530e2
refs/heads/master
2020-04-02T12:31:42.655000
2018-11-22T00:44:01
2018-11-22T00:44:01
154,437,726
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//アルファベータプレイヤ用のZebra評価関数 class PatternEvaluation_AB { final static int BLACKSQ = 0; //黒 final static int EMPTY = 1; //空 final static int WHITESQ = 2; //白 final static int OUTSIDE = 3; //枠外 final static int MIDGAME_WIN = 29000; static int side_to_move; static int disks_played; static int stage_count = 12; static int[] stage = new int[]{8, 14, 20, 26, 32, 36, 40, 44, 48, 52, 56, 60}; static int[] eval_map = new int[61]; static CoeffSet[] set = new CoeffSet[61]; static int[] board = new int[100]; PatternEvaluation_AB() throws Exception { init_coeffs(); } /* eval_map[]への値の格納 set[]へのパラメータの格納 */ public static void init_coeffs() throws Exception { //eval_mapへの値の格納 int subsequent_stage; int i; for ( i = 0; i < stage[0]; i++ ) {//i = 0~7 eval_map[i] = stage[0]; } for ( i = 0; i < stage_count; i++ ) {//i = 0~11 eval_map[stage[i]] = stage[i]; //stage[i] = 8~60 } for ( i = subsequent_stage = 60; i >= stage[0]; i-- ) { //i = 60~8 if ( eval_map[i] == i ) subsequent_stage = i; else if ( i == subsequent_stage - 2 ) { eval_map[i] = i; subsequent_stage = i; } else eval_map[i] = subsequent_stage; } //setへのパラメータの格納 set[0] = CoeffSet.readFromFile(0); for(i = 1; i <= 60; i += 2) { set[i] = CoeffSet.readFromFile(eval_map[i]); if (i < 60) set[i+1] = CoeffSet.readFromFile(eval_map[i]); } } /* 評価値計算に必要なデータをセットする -現在の手番 side_to_move -局面の駒配置 board[] -現在の手数 disks_played */ static void set_data(GameState s) { if (s.player == 1) { side_to_move = BLACKSQ; } else if(s.player == -1) { side_to_move = WHITESQ; } disks_played = s.turn; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { int pos = 10 * i + j; if ( s.data[s.at(i,j)] == 1 ) board[pos] = BLACKSQ; //黒駒 else if ( s.data[s.at(i,j)] == -1 ) board[pos] = WHITESQ; //白駒 else if ( s.data[s.at(i,j)] == 0 ) board[pos] = EMPTY; //無 else if ( s.data[s.at(i,j)] == 2 ) board[pos] = OUTSIDE; //枠外 } } } /* 白の手番の時,局面上の全ての駒を反転する 黒駒 -> 白駒 白駒 -> 黒駒 */ static void reverse_all_disks() { for (int i = 1; i <= 8; i++) { for(int j = 1; j <= 8; j++) { int pos = 10 * i + j; if( board[pos] == BLACKSQ) { board[pos] = WHITESQ; } else if( board[pos] == WHITESQ ) { board[pos] = BLACKSQ; } } } } //盤面の評価を行うメソッド //MCTGameState型が渡されたらGameState型に変換する public static int Pattern_Evaluation(MCTGameState gamestate) { GameState s = new GameState(); s.set(gamestate.data, gamestate.turn, gamestate.player); return Pattern_Evaluation(s); } //盤面の評価を行うメソッド public static int Pattern_Evaluation(GameState s) { int eval_phase; int score; //局面や手番などの状態をセット set_data(s); //手を打つ前の手番のプレイヤにとっての評価なので //手番を入れ替える side_to_move = (0 + 2) - side_to_move; /* 黒一色または白一色の時 */ s.countDisc(); if ( s.black == 0 ) { //白一色 if( side_to_move == BLACKSQ ) { //黒の手番の場合 return -(MIDGAME_WIN + 64); } else { //白の手番の場合 return +(MIDGAME_WIN + 64); } } else if( s.white == 0 ) { //黒一色 if( side_to_move == BLACKSQ ) { //黒の手番の場合 return +(MIDGAME_WIN + 64); } else { //白の手番の場合 return -(MIDGAME_WIN + 64); } } eval_phase = eval_map[disks_played]; score = set[eval_phase].parity_constant[disks_played & 1]; if (side_to_move == WHITESQ) reverse_all_disks(); //評価値scoreの計算 int pattern0; pattern0 = board[72]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[81]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[61]; pattern0 = 3 * pattern0 + board[51]; pattern0 = 3 * pattern0 + board[41]; pattern0 = 3 * pattern0 + board[31]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[77]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[88]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[68]; pattern0 = 3 * pattern0 + board[58]; pattern0 = 3 * pattern0 + board[48]; pattern0 = 3 * pattern0 + board[38]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[27]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[18]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[16]; pattern0 = 3 * pattern0 + board[15]; pattern0 = 3 * pattern0 + board[14]; pattern0 = 3 * pattern0 + board[13]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[77]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[88]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[86]; pattern0 = 3 * pattern0 + board[85]; pattern0 = 3 * pattern0 + board[84]; pattern0 = 3 * pattern0 + board[83]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[82]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[12]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[87]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[17]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[28]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[21]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[78]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[71]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[83]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[13]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[86]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[16]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[38]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[31]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[68]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[61]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[84]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[14]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[85]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[15]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[48]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[41]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[58]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[51]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[88]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].diag8[pattern0]; pattern0 = board[81]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].diag8[pattern0]; pattern0 = board[78]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[12]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[87]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[21]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[71]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[17]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[82]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[28]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[68]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[13]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[86]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[31]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[61]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[16]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[83]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[38]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[58]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[14]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[85]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[41]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[51]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[15]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[84]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[48]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[48]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[15]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[84]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[51]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[41]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[14]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[85]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[58]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[33]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[31]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[13]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[63]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[61]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[83]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[36]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[38]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[16]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[66]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[68]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[86]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[88]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[25]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[15]; pattern0 = 3 * pattern0 + board[14]; pattern0 = 3 * pattern0 + board[13]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[75]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[85]; pattern0 = 3 * pattern0 + board[84]; pattern0 = 3 * pattern0 + board[83]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[24]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[14]; pattern0 = 3 * pattern0 + board[15]; pattern0 = 3 * pattern0 + board[16]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[74]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[84]; pattern0 = 3 * pattern0 + board[85]; pattern0 = 3 * pattern0 + board[86]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[88]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[52]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[51]; pattern0 = 3 * pattern0 + board[41]; pattern0 = 3 * pattern0 + board[31]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[57]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[58]; pattern0 = 3 * pattern0 + board[48]; pattern0 = 3 * pattern0 + board[38]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[42]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[41]; pattern0 = 3 * pattern0 + board[51]; pattern0 = 3 * pattern0 + board[61]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[47]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[48]; pattern0 = 3 * pattern0 + board[58]; pattern0 = 3 * pattern0 + board[68]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[88]; score += set[eval_phase].corner52[pattern0]; return score; } }
UTF-8
Java
19,919
java
PatternEvaluation_AB.java
Java
[]
null
[]
//アルファベータプレイヤ用のZebra評価関数 class PatternEvaluation_AB { final static int BLACKSQ = 0; //黒 final static int EMPTY = 1; //空 final static int WHITESQ = 2; //白 final static int OUTSIDE = 3; //枠外 final static int MIDGAME_WIN = 29000; static int side_to_move; static int disks_played; static int stage_count = 12; static int[] stage = new int[]{8, 14, 20, 26, 32, 36, 40, 44, 48, 52, 56, 60}; static int[] eval_map = new int[61]; static CoeffSet[] set = new CoeffSet[61]; static int[] board = new int[100]; PatternEvaluation_AB() throws Exception { init_coeffs(); } /* eval_map[]への値の格納 set[]へのパラメータの格納 */ public static void init_coeffs() throws Exception { //eval_mapへの値の格納 int subsequent_stage; int i; for ( i = 0; i < stage[0]; i++ ) {//i = 0~7 eval_map[i] = stage[0]; } for ( i = 0; i < stage_count; i++ ) {//i = 0~11 eval_map[stage[i]] = stage[i]; //stage[i] = 8~60 } for ( i = subsequent_stage = 60; i >= stage[0]; i-- ) { //i = 60~8 if ( eval_map[i] == i ) subsequent_stage = i; else if ( i == subsequent_stage - 2 ) { eval_map[i] = i; subsequent_stage = i; } else eval_map[i] = subsequent_stage; } //setへのパラメータの格納 set[0] = CoeffSet.readFromFile(0); for(i = 1; i <= 60; i += 2) { set[i] = CoeffSet.readFromFile(eval_map[i]); if (i < 60) set[i+1] = CoeffSet.readFromFile(eval_map[i]); } } /* 評価値計算に必要なデータをセットする -現在の手番 side_to_move -局面の駒配置 board[] -現在の手数 disks_played */ static void set_data(GameState s) { if (s.player == 1) { side_to_move = BLACKSQ; } else if(s.player == -1) { side_to_move = WHITESQ; } disks_played = s.turn; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { int pos = 10 * i + j; if ( s.data[s.at(i,j)] == 1 ) board[pos] = BLACKSQ; //黒駒 else if ( s.data[s.at(i,j)] == -1 ) board[pos] = WHITESQ; //白駒 else if ( s.data[s.at(i,j)] == 0 ) board[pos] = EMPTY; //無 else if ( s.data[s.at(i,j)] == 2 ) board[pos] = OUTSIDE; //枠外 } } } /* 白の手番の時,局面上の全ての駒を反転する 黒駒 -> 白駒 白駒 -> 黒駒 */ static void reverse_all_disks() { for (int i = 1; i <= 8; i++) { for(int j = 1; j <= 8; j++) { int pos = 10 * i + j; if( board[pos] == BLACKSQ) { board[pos] = WHITESQ; } else if( board[pos] == WHITESQ ) { board[pos] = BLACKSQ; } } } } //盤面の評価を行うメソッド //MCTGameState型が渡されたらGameState型に変換する public static int Pattern_Evaluation(MCTGameState gamestate) { GameState s = new GameState(); s.set(gamestate.data, gamestate.turn, gamestate.player); return Pattern_Evaluation(s); } //盤面の評価を行うメソッド public static int Pattern_Evaluation(GameState s) { int eval_phase; int score; //局面や手番などの状態をセット set_data(s); //手を打つ前の手番のプレイヤにとっての評価なので //手番を入れ替える side_to_move = (0 + 2) - side_to_move; /* 黒一色または白一色の時 */ s.countDisc(); if ( s.black == 0 ) { //白一色 if( side_to_move == BLACKSQ ) { //黒の手番の場合 return -(MIDGAME_WIN + 64); } else { //白の手番の場合 return +(MIDGAME_WIN + 64); } } else if( s.white == 0 ) { //黒一色 if( side_to_move == BLACKSQ ) { //黒の手番の場合 return +(MIDGAME_WIN + 64); } else { //白の手番の場合 return -(MIDGAME_WIN + 64); } } eval_phase = eval_map[disks_played]; score = set[eval_phase].parity_constant[disks_played & 1]; if (side_to_move == WHITESQ) reverse_all_disks(); //評価値scoreの計算 int pattern0; pattern0 = board[72]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[81]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[61]; pattern0 = 3 * pattern0 + board[51]; pattern0 = 3 * pattern0 + board[41]; pattern0 = 3 * pattern0 + board[31]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[77]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[88]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[68]; pattern0 = 3 * pattern0 + board[58]; pattern0 = 3 * pattern0 + board[48]; pattern0 = 3 * pattern0 + board[38]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[27]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[18]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[16]; pattern0 = 3 * pattern0 + board[15]; pattern0 = 3 * pattern0 + board[14]; pattern0 = 3 * pattern0 + board[13]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[77]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[88]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[86]; pattern0 = 3 * pattern0 + board[85]; pattern0 = 3 * pattern0 + board[84]; pattern0 = 3 * pattern0 + board[83]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].afile2x[pattern0]; pattern0 = board[82]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[12]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[87]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[17]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[28]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[21]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[78]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[71]; score += set[eval_phase].bfile[pattern0]; pattern0 = board[83]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[13]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[86]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[16]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[38]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[31]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[68]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[61]; score += set[eval_phase].cfile[pattern0]; pattern0 = board[84]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[14]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[85]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[15]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[48]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[41]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[58]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[51]; score += set[eval_phase].dfile[pattern0]; pattern0 = board[88]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].diag8[pattern0]; pattern0 = board[81]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].diag8[pattern0]; pattern0 = board[78]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[45]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[12]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[87]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[54]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[21]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[71]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[44]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[17]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[82]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[55]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[28]; score += set[eval_phase].diag7[pattern0]; pattern0 = board[68]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[46]; pattern0 = 3 * pattern0 + board[35]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[13]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[86]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[64]; pattern0 = 3 * pattern0 + board[53]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[31]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[61]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[43]; pattern0 = 3 * pattern0 + board[34]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[16]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[83]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[65]; pattern0 = 3 * pattern0 + board[56]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[38]; score += set[eval_phase].diag6[pattern0]; pattern0 = board[58]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[36]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[14]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[85]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[63]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[41]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[51]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[33]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[15]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[84]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[66]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[48]; score += set[eval_phase].diag5[pattern0]; pattern0 = board[48]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[15]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[84]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[51]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[41]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[14]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[85]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[58]; score += set[eval_phase].diag4[pattern0]; pattern0 = board[33]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[31]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[13]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[63]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[61]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[83]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[36]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[38]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[16]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[66]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[68]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[86]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[88]; score += set[eval_phase].corner33[pattern0]; pattern0 = board[25]; pattern0 = 3 * pattern0 + board[24]; pattern0 = 3 * pattern0 + board[23]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[15]; pattern0 = 3 * pattern0 + board[14]; pattern0 = 3 * pattern0 + board[13]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[75]; pattern0 = 3 * pattern0 + board[74]; pattern0 = 3 * pattern0 + board[73]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[85]; pattern0 = 3 * pattern0 + board[84]; pattern0 = 3 * pattern0 + board[83]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[24]; pattern0 = 3 * pattern0 + board[25]; pattern0 = 3 * pattern0 + board[26]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[14]; pattern0 = 3 * pattern0 + board[15]; pattern0 = 3 * pattern0 + board[16]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[74]; pattern0 = 3 * pattern0 + board[75]; pattern0 = 3 * pattern0 + board[76]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[84]; pattern0 = 3 * pattern0 + board[85]; pattern0 = 3 * pattern0 + board[86]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[88]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[52]; pattern0 = 3 * pattern0 + board[42]; pattern0 = 3 * pattern0 + board[32]; pattern0 = 3 * pattern0 + board[22]; pattern0 = 3 * pattern0 + board[12]; pattern0 = 3 * pattern0 + board[51]; pattern0 = 3 * pattern0 + board[41]; pattern0 = 3 * pattern0 + board[31]; pattern0 = 3 * pattern0 + board[21]; pattern0 = 3 * pattern0 + board[11]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[57]; pattern0 = 3 * pattern0 + board[47]; pattern0 = 3 * pattern0 + board[37]; pattern0 = 3 * pattern0 + board[27]; pattern0 = 3 * pattern0 + board[17]; pattern0 = 3 * pattern0 + board[58]; pattern0 = 3 * pattern0 + board[48]; pattern0 = 3 * pattern0 + board[38]; pattern0 = 3 * pattern0 + board[28]; pattern0 = 3 * pattern0 + board[18]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[42]; pattern0 = 3 * pattern0 + board[52]; pattern0 = 3 * pattern0 + board[62]; pattern0 = 3 * pattern0 + board[72]; pattern0 = 3 * pattern0 + board[82]; pattern0 = 3 * pattern0 + board[41]; pattern0 = 3 * pattern0 + board[51]; pattern0 = 3 * pattern0 + board[61]; pattern0 = 3 * pattern0 + board[71]; pattern0 = 3 * pattern0 + board[81]; score += set[eval_phase].corner52[pattern0]; pattern0 = board[47]; pattern0 = 3 * pattern0 + board[57]; pattern0 = 3 * pattern0 + board[67]; pattern0 = 3 * pattern0 + board[77]; pattern0 = 3 * pattern0 + board[87]; pattern0 = 3 * pattern0 + board[48]; pattern0 = 3 * pattern0 + board[58]; pattern0 = 3 * pattern0 + board[68]; pattern0 = 3 * pattern0 + board[78]; pattern0 = 3 * pattern0 + board[88]; score += set[eval_phase].corner52[pattern0]; return score; } }
19,919
0.593858
0.496831
648
27.949074
15.429515
82
false
false
0
0
0
0
0
0
1.635803
false
false
10
cf069a9f7950fe3dc17885a94ccc1f7526afa4e1
12,189,117,224,515
35c289ee6cc86f7f85308dd23606d444775df0e5
/train-wx/train-wx-db/src/main/java/com/train/wx/db/dao/WxKfDao.java
f486c63c6aba840b0149ed285f55a864f0c99425
[]
no_license
tory1989119/train-wx
https://github.com/tory1989119/train-wx
eca25dc7a0048d7a06c4be914bb5c2fe87b63b8d
6b361e7a4bd07e9cf4b4e50317ff655ae98e2768
refs/heads/master
2021-01-22T09:51:07.815000
2017-05-04T13:38:33
2017-05-04T13:38:33
53,955,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.train.wx.db.dao; import java.util.List; import com.train.wx.db.dto.SysSearchDto; import com.train.wx.db.model.WxKfInfo; public interface WxKfDao { /** * 插入客服 * @param wxKf */ public void insertWxKf(WxKfInfo wxKf); /** * 根据id获取客服信息 * @param id * @return */ public WxKfInfo getWxKfInfo(String id); /** * 查询客服列表 * @param sysSearchDto * @return */ public List<WxKfInfo> queryWxKf(SysSearchDto sysSearchDto); /** * 查询客服列表数 * @param sysSearchDto * @return */ public int countWxKf(SysSearchDto sysSearchDto); /** * 清空表数据 */ public void truncateWxKf(); /** * 删除客服 * @param id */ public void deleteWxKf(Long id); /** * 更新客服 * @param wxKf */ public void updateWxKf(WxKfInfo wxKf); }
UTF-8
Java
892
java
WxKfDao.java
Java
[]
null
[]
package com.train.wx.db.dao; import java.util.List; import com.train.wx.db.dto.SysSearchDto; import com.train.wx.db.model.WxKfInfo; public interface WxKfDao { /** * 插入客服 * @param wxKf */ public void insertWxKf(WxKfInfo wxKf); /** * 根据id获取客服信息 * @param id * @return */ public WxKfInfo getWxKfInfo(String id); /** * 查询客服列表 * @param sysSearchDto * @return */ public List<WxKfInfo> queryWxKf(SysSearchDto sysSearchDto); /** * 查询客服列表数 * @param sysSearchDto * @return */ public int countWxKf(SysSearchDto sysSearchDto); /** * 清空表数据 */ public void truncateWxKf(); /** * 删除客服 * @param id */ public void deleteWxKf(Long id); /** * 更新客服 * @param wxKf */ public void updateWxKf(WxKfInfo wxKf); }
892
0.598039
0.598039
53
13.396227
14.50093
60
false
false
0
0
0
0
0
0
1.037736
false
false
10
b1e522935ef2da4d55b6f3866ef4b90f1db1b847
38,800,734,554,205
6fc40e8e23498a88efc01113123b3e8cc289341f
/src/modele/Reservation.java
d665112491b0f9e0de5474d3d09c5290512f9598
[]
no_license
kaelres/projet_comparateur
https://github.com/kaelres/projet_comparateur
38a7a8b21d11800509c9fd41a4590428dfa65528
992906b914addf69eb4d2f3b64d2d1e600af14b7
refs/heads/master
2021-05-02T10:46:09.186000
2018-02-11T14:46:32
2018-02-11T14:46:32
120,763,591
2
1
null
false
2018-02-11T14:21:14
2018-02-08T13:16:56
2018-02-08T13:26:33
2018-02-11T14:20:41
908
0
0
0
Java
false
null
package modele; /** * Cette classe a pour but de représenter les lignes de la table "Reservation" de la base de données. * Une Réservation est une association entre un client et un ordinateur.<br> * @author Francois */ public class Reservation { /** * Login du client effectuant la reservation. */ private String loginClient; /** * Identifiant de l'ordi reservé. */ private int idOrdi; /** * Constructeur permettant de créer une réservation contenant les deux informations nécessaires à la création d'une réservation: <ul> * <li>Le login du client ayant effectué la commande.</li> * <li>L'identifiant de l'ordinateur qu'il a commandé.</li> * </ul> * @param login Login du client effectuant une commande. * @param id Identifiant du produit commandé. */ public Reservation(String login, int id) { loginClient = login; idOrdi = id; } /** * Cette méthode permet de récupérer le login du client ayant effectué cette commande. * @return Renvoie l'attribut "loginClient". */ public String getLogin_client() { return loginClient;} /** * Cette méthode permet de récupérer l'identifiant de l'ordinateur commandé. * @return Renvoie l'attribut "idOrdi". */ public int getId_ordi() { return idOrdi;} }
UTF-8
Java
1,317
java
Reservation.java
Java
[ { "context": " entre un client et un ordinateur.<br>\r\n * @author Francois\r\n */\r\npublic class Reservation {\r\n\t\r\n\t/**\r\n\t * Lo", "end": 224, "score": 0.9998059272766113, "start": 216, "tag": "NAME", "value": "Francois" } ]
null
[]
package modele; /** * Cette classe a pour but de représenter les lignes de la table "Reservation" de la base de données. * Une Réservation est une association entre un client et un ordinateur.<br> * @author Francois */ public class Reservation { /** * Login du client effectuant la reservation. */ private String loginClient; /** * Identifiant de l'ordi reservé. */ private int idOrdi; /** * Constructeur permettant de créer une réservation contenant les deux informations nécessaires à la création d'une réservation: <ul> * <li>Le login du client ayant effectué la commande.</li> * <li>L'identifiant de l'ordinateur qu'il a commandé.</li> * </ul> * @param login Login du client effectuant une commande. * @param id Identifiant du produit commandé. */ public Reservation(String login, int id) { loginClient = login; idOrdi = id; } /** * Cette méthode permet de récupérer le login du client ayant effectué cette commande. * @return Renvoie l'attribut "loginClient". */ public String getLogin_client() { return loginClient;} /** * Cette méthode permet de récupérer l'identifiant de l'ordinateur commandé. * @return Renvoie l'attribut "idOrdi". */ public int getId_ordi() { return idOrdi;} }
1,317
0.683642
0.683642
45
26.799999
31.440668
134
false
false
0
0
0
0
0
0
0.933333
false
false
10
d0a66c376a7fd853237cc194a8e7235f20bdab6d
17,575,006,233,959
b11ef50feae95b3c24a52e37336cdc9c6628fddf
/src/utils/WatchedList.java
2fc3c6283bb1f8992f5ac3b58277bd4a18712440
[]
no_license
lixiaoxiao1019/voice_communicate
https://github.com/lixiaoxiao1019/voice_communicate
2fb0bd06f221f9254f80e6d67abce915d829345f
70c373e67e1824ec691eabcbc7745d0efe9f6a19
refs/heads/master
2020-04-29T07:04:39.053000
2016-06-05T07:03:51
2016-06-05T07:03:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utils; import java.util.ArrayList; import java.util.List; public class WatchedList { List<WatchedBean> list = new ArrayList<WatchedBean>(); private final static int MAXCOUNT = 1; public void addToList(WatchedBean bean) { // bean.setInterval(0); for(WatchedBean b:list) { if(b.getRefValue()==bean.getRefValue()) { b.addToTotal(bean.getTotal()); return; } } if(list.size()>=MAXCOUNT) { list.remove(0); } list.add(bean); } public void clearList() { list.clear(); } /** * * @return 为-1时表示未找到 */ public int getConfirmedValue() { clear(list); for(WatchedBean b:list) { if(b.confirm()) { list.remove(b); return b.getRefValue(); } } return -1; } /** * 将间隔大于某数的清理了 */ private void clear(List<WatchedBean> list) { for(int i=0;i<list.size();i++) { if(list.get(i).shouldDelete()) { list.remove(i); clear(list); } } } // public void addInterval() // { // for(WatchedBean b:list) // { // b.addInterval(); // } // } // public boolean exist(int value) // { // for(WatchedBean bean:list) // { // if(bean.getRefValue()==value) // { // return true; // } // } // return false; // } }
GB18030
Java
1,259
java
WatchedList.java
Java
[]
null
[]
package utils; import java.util.ArrayList; import java.util.List; public class WatchedList { List<WatchedBean> list = new ArrayList<WatchedBean>(); private final static int MAXCOUNT = 1; public void addToList(WatchedBean bean) { // bean.setInterval(0); for(WatchedBean b:list) { if(b.getRefValue()==bean.getRefValue()) { b.addToTotal(bean.getTotal()); return; } } if(list.size()>=MAXCOUNT) { list.remove(0); } list.add(bean); } public void clearList() { list.clear(); } /** * * @return 为-1时表示未找到 */ public int getConfirmedValue() { clear(list); for(WatchedBean b:list) { if(b.confirm()) { list.remove(b); return b.getRefValue(); } } return -1; } /** * 将间隔大于某数的清理了 */ private void clear(List<WatchedBean> list) { for(int i=0;i<list.size();i++) { if(list.get(i).shouldDelete()) { list.remove(i); clear(list); } } } // public void addInterval() // { // for(WatchedBean b:list) // { // b.addInterval(); // } // } // public boolean exist(int value) // { // for(WatchedBean bean:list) // { // if(bean.getRefValue()==value) // { // return true; // } // } // return false; // } }
1,259
0.576451
0.571545
87
13.057471
12.987489
55
false
false
0
0
0
0
0
0
2.022989
false
false
10
1d47e74ee93202aa77b334ebee2d85d5b948331f
14,465,449,858,182
7dbfd673f17281cd9c880379a761ccee207940cf
/slider-core/src/test/java/org/apache/slider/providers/agent/TestAgentClientProvider2.java
b959e2f6ee9f5c488a3581025dbae108312aa0a7
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-3-Clause", "MIT", "BSD-2-Clause" ]
permissive
apache/incubator-slider
https://github.com/apache/incubator-slider
4c589a317e8e01113e1e9a7a93a8f3308aae6107
1d4f519d763210f46e327338be72efa99e65cb5d
refs/heads/develop
2021-05-22T10:50:46.876000
2018-05-24T21:04:51
2018-05-24T21:04:51
20,051,204
60
87
Apache-2.0
false
2018-07-30T14:14:41
2014-05-22T07:00:07
2018-06-27T13:01:24
2018-05-24T21:05:11
16,472
69
74
6
Java
false
null
/* * 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.slider.providers.agent; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.registry.client.binding.RegistryUtils; import org.apache.log4j.BasicConfigurator; import org.apache.slider.api.InternalKeys; import org.apache.slider.client.SliderClient; import org.apache.slider.common.SliderExitCodes; import org.apache.slider.common.params.ActionClientArgs; import org.apache.slider.common.tools.SliderFileSystem; import org.apache.slider.core.conf.AggregateConf; import org.apache.slider.core.conf.ConfTree; import org.apache.slider.core.exceptions.BadCommandArgumentsException; import org.apache.slider.core.exceptions.BadConfigException; import org.apache.slider.providers.ProviderUtils; import org.apache.slider.providers.agent.application.metadata.Application; import org.apache.slider.providers.agent.application.metadata.Metainfo; import org.apache.slider.providers.agent.application.metadata.Package; import org.apache.slider.test.SliderTestUtils; import org.codehaus.jettison.json.JSONObject; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.expect; /** * */ @RunWith(PowerMockRunner.class) @PowerMockIgnore("org.apache.log4j.*") @PrepareForTest({ProviderUtils.class, ProcessBuilder.class, AgentClientProvider.class, RegistryUtils.class}) public class TestAgentClientProvider2 extends SliderTestUtils { protected static final Logger log = LoggerFactory.getLogger(TestAgentClientProvider2.class); @Rule public TemporaryFolder folder = new TemporaryFolder(); @BeforeClass public static void initialize() { BasicConfigurator.resetConfiguration(); BasicConfigurator.configure(); } @Test public void testPrepareAMAndConfigForLaunch() throws Exception { AgentClientProvider provider = new AgentClientProvider(null); SliderFileSystem sfs = PowerMock.createMock(SliderFileSystem.class); FileSystem fs = PowerMock.createMock(FileSystem.class); Configuration serviceConf = PowerMock.createMock(Configuration.class); PowerMock.mockStatic(ProviderUtils.class); expect(sfs.getFileSystem()).andReturn(fs); expect(fs.mkdirs(anyObject(Path.class))).andReturn(true); expect(ProviderUtils.addAgentTar( anyObject(), anyObject(String.class), anyObject(SliderFileSystem.class), anyObject(Path.class))). andReturn(true); AggregateConf instanceDefinition = new AggregateConf(); ConfTree tree = new ConfTree(); tree.global.put(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH, "."); instanceDefinition.setInternal(tree); PowerMock.replay(sfs, fs, serviceConf, ProviderUtils.class); provider.prepareAMAndConfigForLaunch( sfs, serviceConf, null, instanceDefinition, null, null, null, null, null, false); Assert.assertTrue(tree.global.containsKey(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH)); tree.global.remove(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH); // Verify that slider-agent.tar.gz got added Path tempPath = new Path(".", "temp"); provider.prepareAMAndConfigForLaunch( sfs, serviceConf, null, instanceDefinition, null, null, null, null, tempPath, false); PowerMock.verify(sfs, fs, ProviderUtils.class); Assert.assertTrue(tree.global.containsKey(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH)); } @Test public void testGetCommandJson() throws Exception { AgentClientProvider provider = new AgentClientProvider(null); JSONObject defaultConfig = null; JSONObject inputConfig = new JSONObject(); JSONObject global = new JSONObject(); global.put("a", "b"); global.put("d", "{app_install_dir}/d"); global.put("e", "{app_name}"); inputConfig.put("global", global); Metainfo metainfo = new Metainfo(); Application app = new Application(); metainfo.setApplication(app); Package pkg = new Package(); pkg.setName("app.tar"); pkg.setType("tarball"); app.getPackages().add(pkg); // This is not a windows path, which is something we bear in mind in testisng File clientInstallPath = new File("/tmp/file1"); String appName = "name"; String user = "username"; PowerMock.mockStaticPartial(RegistryUtils.class, "currentUser"); expect(RegistryUtils.currentUser()).andReturn(user).times(2); PowerMock.replay(RegistryUtils.class); JSONObject output = provider.getCommandJson(defaultConfig, inputConfig, metainfo, clientInstallPath, appName); JSONObject outConfigs = output.getJSONObject("configurations"); assertNotNull("null configurations section", outConfigs); JSONObject outGlobal = outConfigs.getJSONObject("global"); assertNotNull("null globals section", outGlobal); assertEquals("b", outGlobal.getString("a")); assertContained("file1/d", outGlobal.getString("d")); assertContained(clientInstallPath.getAbsolutePath(), outGlobal.getString("app_install_dir")); assertEquals("name", outGlobal.getString("e")); assertEquals("name", outGlobal.getString("app_name")); assertEquals(user, outGlobal.getString("app_user")); defaultConfig = new JSONObject(); global = new JSONObject(); global.put("a1", "b2"); global.put("a", "b-not"); global.put("d1", "{app_install_dir}/d"); global.put("e", "{app_name}"); defaultConfig.put("global", global); output = provider.getCommandJson(defaultConfig, inputConfig, metainfo, clientInstallPath, null); outConfigs = output.getJSONObject("configurations"); assertNotNull("null configurations section", outConfigs); outGlobal = outConfigs.getJSONObject("global"); assertNotNull("null globals section", outGlobal); assertEquals("b", outGlobal.getString("a")); assertEquals("b2", outGlobal.getString("a1")); assertContained("file1/d", outGlobal.getString("d")); assertContained("file1/d", outGlobal.getString("d1")); assertContained(clientInstallPath.getAbsolutePath(), outGlobal.getString("app_install_dir")); assertEquals("{app_name}", outGlobal.getString("e")); assertFalse("no 'app_name' field", outGlobal.has("app_name")); assertEquals(user, outGlobal.getString("app_user")); PowerMock.verify(RegistryUtils.class); } public void assertContained(String expected, String actual) { assertNotNull(actual); assertTrue( String.format("Did not find \"%s\" in \"%s\"", expected, actual), actual.contains(expected)); } @Test public void testRunCommand() throws Exception { AgentClientProvider provider = new AgentClientProvider(null); File appPkgDir = new File("/tmp/pkg"); File agentPkgDir = new File("/tmp/agt"); File cmdDir = new File("/tmp/cmd"); String client_script = "scripts/abc.py"; List<String> commands = Arrays.asList("python", "-S", new File("/tmp/pkg").getAbsolutePath() + File.separator + "package" + File.separator + "scripts/abc.py", "INSTALL", new File("/tmp/cmd").getAbsolutePath() + File.separator + "command.json", new File("/tmp/pkg").getAbsolutePath() + File.separator + "package", new File("/tmp/cmd").getAbsolutePath() + File.separator + "command-out.json", "DEBUG"); ProcessBuilder pbMock = PowerMock.createMock(ProcessBuilder.class); Process procMock = PowerMock.createMock(Process.class); PowerMock.expectNew(ProcessBuilder.class, commands).andReturn(pbMock); expect(pbMock.environment()).andReturn(new HashMap<String, String>()).anyTimes(); expect(pbMock.start()).andReturn(procMock); expect(pbMock.command()).andReturn(new ArrayList<String>()); expect(procMock.waitFor()).andReturn(0); expect(procMock.exitValue()).andReturn(0); expect(procMock.getErrorStream()).andReturn(IOUtils.toInputStream("stderr", "UTF-8")); expect(procMock.getInputStream()).andReturn(IOUtils.toInputStream("stdout", "UTF-8")); PowerMock.replayAll(); provider.runCommand(appPkgDir, agentPkgDir, cmdDir, client_script); PowerMock.verifyAll(); } @Test public void testSliderClientForInstallFailures() throws Exception { describe(" IGNORE ANY STACK TRACES BELOW "); SliderClient client = PowerMock.createPartialMock(SliderClient.class, "getRegistryOperations"); expect(client.getRegistryOperations()).andReturn(null).anyTimes(); PowerMock.replay(SliderClient.class); client.bindArgs(new Configuration(), "client", "--dest", "a_random_path/none", "--package", "a_random_pkg.zip"); ActionClientArgs args = new ActionClientArgs(); args.install = true; try { client.actionClient(args); } catch (BadCommandArgumentsException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_COMMAND_ARGUMENT_ERROR, SliderClient.E_INVALID_INSTALL_LOCATION); } File tmpFile = File.createTempFile("del", ""); File dest = new File(tmpFile.getParentFile(), tmpFile.getName() + "dir"); args.installLocation = dest; try { client.actionClient(args); } catch (BadCommandArgumentsException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_COMMAND_ARGUMENT_ERROR, SliderClient.E_INSTALL_PATH_DOES_NOT_EXIST); } dest.mkdir(); try { client.actionClient(args); } catch (BadCommandArgumentsException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_COMMAND_ARGUMENT_ERROR, SliderClient.E_INVALID_APPLICATION_PACKAGE_LOCATION); } tmpFile = File.createTempFile("del", ".zip"); args.packageURI = tmpFile.toString(); args.clientConfig = tmpFile; try { client.actionClient(args); } catch (BadConfigException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_BAD_CONFIGURATION, SliderClient.E_MUST_BE_A_VALID_JSON_FILE); } describe(" END IGNORE "); args.clientConfig = null; try { client.actionClient(args); } catch (BadConfigException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_BAD_CONFIGURATION, AgentClientProvider.E_COULD_NOT_READ_METAINFO); } PowerMock.verify(SliderClient.class); } }
UTF-8
Java
11,911
java
TestAgentClientProvider2.java
Java
[ { "context": ";\n String appName = \"name\";\n String user = \"username\";\n\n PowerMock.mockStaticPartial(RegistryUtils.", "end": 5659, "score": 0.9994317889213562, "start": 5651, "tag": "USERNAME", "value": "username" } ]
null
[]
/* * 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.slider.providers.agent; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.registry.client.binding.RegistryUtils; import org.apache.log4j.BasicConfigurator; import org.apache.slider.api.InternalKeys; import org.apache.slider.client.SliderClient; import org.apache.slider.common.SliderExitCodes; import org.apache.slider.common.params.ActionClientArgs; import org.apache.slider.common.tools.SliderFileSystem; import org.apache.slider.core.conf.AggregateConf; import org.apache.slider.core.conf.ConfTree; import org.apache.slider.core.exceptions.BadCommandArgumentsException; import org.apache.slider.core.exceptions.BadConfigException; import org.apache.slider.providers.ProviderUtils; import org.apache.slider.providers.agent.application.metadata.Application; import org.apache.slider.providers.agent.application.metadata.Metainfo; import org.apache.slider.providers.agent.application.metadata.Package; import org.apache.slider.test.SliderTestUtils; import org.codehaus.jettison.json.JSONObject; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.expect; /** * */ @RunWith(PowerMockRunner.class) @PowerMockIgnore("org.apache.log4j.*") @PrepareForTest({ProviderUtils.class, ProcessBuilder.class, AgentClientProvider.class, RegistryUtils.class}) public class TestAgentClientProvider2 extends SliderTestUtils { protected static final Logger log = LoggerFactory.getLogger(TestAgentClientProvider2.class); @Rule public TemporaryFolder folder = new TemporaryFolder(); @BeforeClass public static void initialize() { BasicConfigurator.resetConfiguration(); BasicConfigurator.configure(); } @Test public void testPrepareAMAndConfigForLaunch() throws Exception { AgentClientProvider provider = new AgentClientProvider(null); SliderFileSystem sfs = PowerMock.createMock(SliderFileSystem.class); FileSystem fs = PowerMock.createMock(FileSystem.class); Configuration serviceConf = PowerMock.createMock(Configuration.class); PowerMock.mockStatic(ProviderUtils.class); expect(sfs.getFileSystem()).andReturn(fs); expect(fs.mkdirs(anyObject(Path.class))).andReturn(true); expect(ProviderUtils.addAgentTar( anyObject(), anyObject(String.class), anyObject(SliderFileSystem.class), anyObject(Path.class))). andReturn(true); AggregateConf instanceDefinition = new AggregateConf(); ConfTree tree = new ConfTree(); tree.global.put(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH, "."); instanceDefinition.setInternal(tree); PowerMock.replay(sfs, fs, serviceConf, ProviderUtils.class); provider.prepareAMAndConfigForLaunch( sfs, serviceConf, null, instanceDefinition, null, null, null, null, null, false); Assert.assertTrue(tree.global.containsKey(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH)); tree.global.remove(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH); // Verify that slider-agent.tar.gz got added Path tempPath = new Path(".", "temp"); provider.prepareAMAndConfigForLaunch( sfs, serviceConf, null, instanceDefinition, null, null, null, null, tempPath, false); PowerMock.verify(sfs, fs, ProviderUtils.class); Assert.assertTrue(tree.global.containsKey(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH)); } @Test public void testGetCommandJson() throws Exception { AgentClientProvider provider = new AgentClientProvider(null); JSONObject defaultConfig = null; JSONObject inputConfig = new JSONObject(); JSONObject global = new JSONObject(); global.put("a", "b"); global.put("d", "{app_install_dir}/d"); global.put("e", "{app_name}"); inputConfig.put("global", global); Metainfo metainfo = new Metainfo(); Application app = new Application(); metainfo.setApplication(app); Package pkg = new Package(); pkg.setName("app.tar"); pkg.setType("tarball"); app.getPackages().add(pkg); // This is not a windows path, which is something we bear in mind in testisng File clientInstallPath = new File("/tmp/file1"); String appName = "name"; String user = "username"; PowerMock.mockStaticPartial(RegistryUtils.class, "currentUser"); expect(RegistryUtils.currentUser()).andReturn(user).times(2); PowerMock.replay(RegistryUtils.class); JSONObject output = provider.getCommandJson(defaultConfig, inputConfig, metainfo, clientInstallPath, appName); JSONObject outConfigs = output.getJSONObject("configurations"); assertNotNull("null configurations section", outConfigs); JSONObject outGlobal = outConfigs.getJSONObject("global"); assertNotNull("null globals section", outGlobal); assertEquals("b", outGlobal.getString("a")); assertContained("file1/d", outGlobal.getString("d")); assertContained(clientInstallPath.getAbsolutePath(), outGlobal.getString("app_install_dir")); assertEquals("name", outGlobal.getString("e")); assertEquals("name", outGlobal.getString("app_name")); assertEquals(user, outGlobal.getString("app_user")); defaultConfig = new JSONObject(); global = new JSONObject(); global.put("a1", "b2"); global.put("a", "b-not"); global.put("d1", "{app_install_dir}/d"); global.put("e", "{app_name}"); defaultConfig.put("global", global); output = provider.getCommandJson(defaultConfig, inputConfig, metainfo, clientInstallPath, null); outConfigs = output.getJSONObject("configurations"); assertNotNull("null configurations section", outConfigs); outGlobal = outConfigs.getJSONObject("global"); assertNotNull("null globals section", outGlobal); assertEquals("b", outGlobal.getString("a")); assertEquals("b2", outGlobal.getString("a1")); assertContained("file1/d", outGlobal.getString("d")); assertContained("file1/d", outGlobal.getString("d1")); assertContained(clientInstallPath.getAbsolutePath(), outGlobal.getString("app_install_dir")); assertEquals("{app_name}", outGlobal.getString("e")); assertFalse("no 'app_name' field", outGlobal.has("app_name")); assertEquals(user, outGlobal.getString("app_user")); PowerMock.verify(RegistryUtils.class); } public void assertContained(String expected, String actual) { assertNotNull(actual); assertTrue( String.format("Did not find \"%s\" in \"%s\"", expected, actual), actual.contains(expected)); } @Test public void testRunCommand() throws Exception { AgentClientProvider provider = new AgentClientProvider(null); File appPkgDir = new File("/tmp/pkg"); File agentPkgDir = new File("/tmp/agt"); File cmdDir = new File("/tmp/cmd"); String client_script = "scripts/abc.py"; List<String> commands = Arrays.asList("python", "-S", new File("/tmp/pkg").getAbsolutePath() + File.separator + "package" + File.separator + "scripts/abc.py", "INSTALL", new File("/tmp/cmd").getAbsolutePath() + File.separator + "command.json", new File("/tmp/pkg").getAbsolutePath() + File.separator + "package", new File("/tmp/cmd").getAbsolutePath() + File.separator + "command-out.json", "DEBUG"); ProcessBuilder pbMock = PowerMock.createMock(ProcessBuilder.class); Process procMock = PowerMock.createMock(Process.class); PowerMock.expectNew(ProcessBuilder.class, commands).andReturn(pbMock); expect(pbMock.environment()).andReturn(new HashMap<String, String>()).anyTimes(); expect(pbMock.start()).andReturn(procMock); expect(pbMock.command()).andReturn(new ArrayList<String>()); expect(procMock.waitFor()).andReturn(0); expect(procMock.exitValue()).andReturn(0); expect(procMock.getErrorStream()).andReturn(IOUtils.toInputStream("stderr", "UTF-8")); expect(procMock.getInputStream()).andReturn(IOUtils.toInputStream("stdout", "UTF-8")); PowerMock.replayAll(); provider.runCommand(appPkgDir, agentPkgDir, cmdDir, client_script); PowerMock.verifyAll(); } @Test public void testSliderClientForInstallFailures() throws Exception { describe(" IGNORE ANY STACK TRACES BELOW "); SliderClient client = PowerMock.createPartialMock(SliderClient.class, "getRegistryOperations"); expect(client.getRegistryOperations()).andReturn(null).anyTimes(); PowerMock.replay(SliderClient.class); client.bindArgs(new Configuration(), "client", "--dest", "a_random_path/none", "--package", "a_random_pkg.zip"); ActionClientArgs args = new ActionClientArgs(); args.install = true; try { client.actionClient(args); } catch (BadCommandArgumentsException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_COMMAND_ARGUMENT_ERROR, SliderClient.E_INVALID_INSTALL_LOCATION); } File tmpFile = File.createTempFile("del", ""); File dest = new File(tmpFile.getParentFile(), tmpFile.getName() + "dir"); args.installLocation = dest; try { client.actionClient(args); } catch (BadCommandArgumentsException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_COMMAND_ARGUMENT_ERROR, SliderClient.E_INSTALL_PATH_DOES_NOT_EXIST); } dest.mkdir(); try { client.actionClient(args); } catch (BadCommandArgumentsException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_COMMAND_ARGUMENT_ERROR, SliderClient.E_INVALID_APPLICATION_PACKAGE_LOCATION); } tmpFile = File.createTempFile("del", ".zip"); args.packageURI = tmpFile.toString(); args.clientConfig = tmpFile; try { client.actionClient(args); } catch (BadConfigException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_BAD_CONFIGURATION, SliderClient.E_MUST_BE_A_VALID_JSON_FILE); } describe(" END IGNORE "); args.clientConfig = null; try { client.actionClient(args); } catch (BadConfigException e) { assertExceptionDetails(e, SliderExitCodes.EXIT_BAD_CONFIGURATION, AgentClientProvider.E_COULD_NOT_READ_METAINFO); } PowerMock.verify(SliderClient.class); } }
11,911
0.7101
0.707917
297
39.104378
26.315475
116
false
false
0
0
0
0
0
0
0.929293
false
false
10
943165b5749568a6e04b8b140cfd2aa2b1556a2b
22,230,750,731,569
11c8c6880a2fdf19655cf8da43ceacd8b1216de0
/jfom/src/org/jfom/_Spacer.java
d6c4cedf7b63ac8a09973016d37bb9cd1c7ed0cb
[]
no_license
michael-n-kaplan/jfom
https://github.com/michael-n-kaplan/jfom
7940f690dc4fd9b0ba7395dd31429f96bcedd93f
91e8a27e2834d0546d67324c521ba5be992b0ade
refs/heads/master
2021-01-10T19:44:34.074000
2010-04-13T23:32:53
2010-04-13T23:32:53
34,352,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * <copyright> * </copyright> * * $Id$ */ package org.jfom; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Spacer</b></em>'. * <!-- end-user-doc --> * * * @see org.jfom.JFOMPackage#get_Spacer() * @model * @generated */ public interface _Spacer extends ExecutionPartConstruct { } // _Spacer
UTF-8
Java
360
java
_Spacer.java
Java
[]
null
[]
/** * <copyright> * </copyright> * * $Id$ */ package org.jfom; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Spacer</b></em>'. * <!-- end-user-doc --> * * * @see org.jfom.JFOMPackage#get_Spacer() * @model * @generated */ public interface _Spacer extends ExecutionPartConstruct { } // _Spacer
360
0.552778
0.552778
21
15.142858
17.984877
65
false
false
0
0
0
0
0
0
0.047619
false
false
10
6d6d9f2e4ac33b2bdbe63e3c5ec4c65a871918a3
28,845,000,366,765
237ed0e79b37f40cf24643a5032112ef73afcc45
/lab2/src/com/company/communications.java
8d4d0f8bf6001122b3fd0806a5d1528f53b9a496
[]
no_license
pudovmgen/cryptography_tanya
https://github.com/pudovmgen/cryptography_tanya
ed7c8a2733698c1591a8d543e737a76878834085
515207fbfff4937e47102b9a2472fca2def59712
refs/heads/master
2020-03-06T00:48:22.640000
2017-05-14T13:03:11
2017-05-14T13:03:11
86,490,562
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; /** * Created by mikhail on 5/4/17. */ public class communications { private String left; private String ringt; private String vertex; private int left_value; private int ringt_value; public void setLeft(String vertex,String new_name,int value){ this.left =new_name; this.vertex =vertex; this.left_value = value; } public void setRingt(String vertex,String new_name,int value){ this.ringt =new_name; this.vertex =vertex; this.ringt_value = value; } public String getNameLeft(){ return this.left; } public String getNameRingt(){ return this.ringt; } public int getValueLeft(){ return this.left_value; } public int getValueRingt(){ return this.ringt_value; } public String getVertex(){ return this.vertex; } }
UTF-8
Java
903
java
communications.java
Java
[ { "context": "package com.company;\n\n/**\n * Created by mikhail on 5/4/17.\n */\npublic class communications {\n ", "end": 47, "score": 0.9911202192306519, "start": 40, "tag": "USERNAME", "value": "mikhail" } ]
null
[]
package com.company; /** * Created by mikhail on 5/4/17. */ public class communications { private String left; private String ringt; private String vertex; private int left_value; private int ringt_value; public void setLeft(String vertex,String new_name,int value){ this.left =new_name; this.vertex =vertex; this.left_value = value; } public void setRingt(String vertex,String new_name,int value){ this.ringt =new_name; this.vertex =vertex; this.ringt_value = value; } public String getNameLeft(){ return this.left; } public String getNameRingt(){ return this.ringt; } public int getValueLeft(){ return this.left_value; } public int getValueRingt(){ return this.ringt_value; } public String getVertex(){ return this.vertex; } }
903
0.612403
0.607973
44
19.522728
16.414362
66
false
false
0
0
0
0
0
0
0.477273
false
false
10
ea87b9be6e4c9b0419d50823f006700ca726cd80
24,026,047,076,866
d06ed468ad7e2c7b63f51866a8b4632b39bccf67
/1019_IO_study01/src/com/bo/io/FileDemo03.java
d6f3a22dd56d60dc34d94733c66da90d9e775ff4
[]
no_license
popobo/Java_pratice
https://github.com/popobo/Java_pratice
33da0c1d743799dc0c538ce572e53a09305e72b6
2d67c0c607ee9beb493bcbf317bf9d796e919922
refs/heads/master
2021-01-30T19:50:46.673000
2020-03-15T10:26:03
2020-03-15T10:26:03
243,505,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bo.io; import java.io.File; /** * getName() * getPath() * getAbsolutePath() * getParent():上路径 * @author 33136 * */ public class FileDemo03 { public static void main(String[] args) { File srcFile = new File("./src/com/bo/io/FileDemo01.java"); System.out.println("绝对路径" + srcFile.getAbsolutePath()); System.out.println("父路径" + srcFile.getParent()); System.out.println("路径" + srcFile.getPath()); System.out.println("父对象" + srcFile.getParentFile().getName()); } }
GB18030
Java
523
java
FileDemo03.java
Java
[ { "context": "* getAbsolutePath()\n * getParent():上路径\n * @author 33136\n *\n */\npublic class FileDemo03 {\n\tpublic static v", "end": 128, "score": 0.9744418859481812, "start": 123, "tag": "USERNAME", "value": "33136" } ]
null
[]
package com.bo.io; import java.io.File; /** * getName() * getPath() * getAbsolutePath() * getParent():上路径 * @author 33136 * */ public class FileDemo03 { public static void main(String[] args) { File srcFile = new File("./src/com/bo/io/FileDemo01.java"); System.out.println("绝对路径" + srcFile.getAbsolutePath()); System.out.println("父路径" + srcFile.getParent()); System.out.println("路径" + srcFile.getPath()); System.out.println("父对象" + srcFile.getParentFile().getName()); } }
523
0.669371
0.651116
21
22.476191
21.259438
64
false
false
0
0
0
0
0
0
0.904762
false
false
10
2f40b5f21cc11970c10ac2587db71f0dc69bc74b
33,011,118,661,447
ce2d50417d490f3520f0ff6285efb71b82f9ad5e
/src/org/dase/cogan/Main.java
54ce1e6f2ca1d118168bcfb90facaff7b54d08ab
[]
no_license
cogan-shimizu/Logician
https://github.com/cogan-shimizu/Logician
bac14eb9a012eff800d599aa9c7c7bf331e1042b
17b72657785f1c04d7a69f8fe7bc401f6fa91e41
refs/heads/master
2021-09-23T21:13:29.283000
2018-09-27T19:51:00
2018-09-27T19:51:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.dase.cogan; import org.dase.cogan.ui.RulifierGUI; import org.dase.cogan.ui.RulifierREPL; public class Main { public static void main(String[] args) { try { String flag = args[0]; if(flag.equals("-d")) { (new RulifierREPL()).run(); } else if(flag.equals("-t")) { RulifierREPL repl = new RulifierREPL(); if(args[1].equals("string")) { repl.stringTest(); } else { repl.ontoTest(); } } else // -g { RulifierGUI rg = new RulifierGUI(); rg.init(); } } catch(ArrayIndexOutOfBoundsException e) // run gui if no arguments { RulifierGUI rg = new RulifierGUI(); rg.init(); } finally { // } } }
UTF-8
Java
709
java
Main.java
Java
[]
null
[]
package org.dase.cogan; import org.dase.cogan.ui.RulifierGUI; import org.dase.cogan.ui.RulifierREPL; public class Main { public static void main(String[] args) { try { String flag = args[0]; if(flag.equals("-d")) { (new RulifierREPL()).run(); } else if(flag.equals("-t")) { RulifierREPL repl = new RulifierREPL(); if(args[1].equals("string")) { repl.stringTest(); } else { repl.ontoTest(); } } else // -g { RulifierGUI rg = new RulifierGUI(); rg.init(); } } catch(ArrayIndexOutOfBoundsException e) // run gui if no arguments { RulifierGUI rg = new RulifierGUI(); rg.init(); } finally { // } } }
709
0.572637
0.569817
47
14.085107
15.47246
68
false
false
0
0
0
0
0
0
2.595745
false
false
10
a26b2d1c93f5995d62f2a6f176cd715c0becc8d6
3,753,801,443,342
961db31543ce5862cdba98006ad307161546c9c8
/src/main/java/com/realtime/project/maven_cyberfox_255392/displayKedah.java
eeef46a69552641b0e5c266b0286811f4b9d99e2
[]
no_license
STIW3054-A182/CyberFox-Repo
https://github.com/STIW3054-A182/CyberFox-Repo
8195e9a131142bc40e60c3982f72af37592ffbc9
1e29afb40cb3a58377604715cf89e26ed8ab2b81
refs/heads/master
2022-09-23T11:12:12.059000
2019-06-03T12:17:36
2019-06-03T12:17:36
180,492,266
2
1
null
false
2022-09-01T23:07:37
2019-04-10T03:11:39
2019-06-03T12:17:38
2022-09-01T23:07:34
2,429
1
1
4
Java
false
false
package com.realtime.project.maven_cyberfox_255392; import org.apache.commons.lang3.StringUtils; import org.apache.commons.collections4.CollectionUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; class displayKedah { private List<String> ValidURLList; private Properties prop = new Properties(); displayKedah(List<String> ValidURLList) { this.ValidURLList = ValidURLList; } void RetrievePlayer() throws IOException, ParseException { System.out.println("\nDisplay All players From Kedah ......"); System.out.println(""); System.out.println("RK\t |Sno\t |Name\t\t\t\t |Rtg\t |State\t |Pts\t|Category"); System.out.println("---------------------------------------------------------------------------------------------"); for (String s : ValidURLList) { Document doc = Jsoup.connect(s).get(); Elements b = doc.select("div:nth-child(2)"); for (Element header : b) { Elements h2 = header.select("h2"); String category = h2.text(); if (StringUtils.contains(category, "NATIONAL")) { String showCat = StringUtils.substringAfter(category, "9"); Elements a = doc.select("table.CRs1 tr"); for (Element row : a) { String state = row.select("td:nth-child(7)").text(); String rank = row.select("td:nth-child(1)").text(); String sno = row.select("td:nth-child(2)").text(); String name = row.select(" td:nth-child(4)").text(); String rtg = row.select("td.CRr").text(); String pts = row.select("td:nth-child(8)").text(); if (state.contains("KEDAH")) { ShowPlayer(rank, sno, name, rtg, pts, showCat); } } } } } } private void ShowPlayer(String rank, String sNo, String name, String rtg, String replace, String showCat) { try (InputStream input = new FileInputStream("config.properties")) { // load a properties file prop.load(input); System.out.printf("\n%-5s | %-5s | %-30s | %-8s | %-8s | %-8s | %-8s", rank, sNo, name, rtg, prop.getProperty("sTATE"), replace, showCat); } catch (IOException ex) { ex.printStackTrace(); } } }
UTF-8
Java
2,775
java
displayKedah.java
Java
[]
null
[]
package com.realtime.project.maven_cyberfox_255392; import org.apache.commons.lang3.StringUtils; import org.apache.commons.collections4.CollectionUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; class displayKedah { private List<String> ValidURLList; private Properties prop = new Properties(); displayKedah(List<String> ValidURLList) { this.ValidURLList = ValidURLList; } void RetrievePlayer() throws IOException, ParseException { System.out.println("\nDisplay All players From Kedah ......"); System.out.println(""); System.out.println("RK\t |Sno\t |Name\t\t\t\t |Rtg\t |State\t |Pts\t|Category"); System.out.println("---------------------------------------------------------------------------------------------"); for (String s : ValidURLList) { Document doc = Jsoup.connect(s).get(); Elements b = doc.select("div:nth-child(2)"); for (Element header : b) { Elements h2 = header.select("h2"); String category = h2.text(); if (StringUtils.contains(category, "NATIONAL")) { String showCat = StringUtils.substringAfter(category, "9"); Elements a = doc.select("table.CRs1 tr"); for (Element row : a) { String state = row.select("td:nth-child(7)").text(); String rank = row.select("td:nth-child(1)").text(); String sno = row.select("td:nth-child(2)").text(); String name = row.select(" td:nth-child(4)").text(); String rtg = row.select("td.CRr").text(); String pts = row.select("td:nth-child(8)").text(); if (state.contains("KEDAH")) { ShowPlayer(rank, sno, name, rtg, pts, showCat); } } } } } } private void ShowPlayer(String rank, String sNo, String name, String rtg, String replace, String showCat) { try (InputStream input = new FileInputStream("config.properties")) { // load a properties file prop.load(input); System.out.printf("\n%-5s | %-5s | %-30s | %-8s | %-8s | %-8s | %-8s", rank, sNo, name, rtg, prop.getProperty("sTATE"), replace, showCat); } catch (IOException ex) { ex.printStackTrace(); } } }
2,775
0.547387
0.537658
65
41.707691
32.35273
155
false
false
0
0
0
0
0
0
1.061538
false
false
10
202b1f97e3ce8c68110e90be07ce7f3d4bc1cc9b
22,651,657,543,545
888d59b554274898d754ac1c481ea57f245f3c83
/app/src/main/java/com/example/efahrtenbuchapp/eFahrtenbuch/Fahrt.java
ac848ab36aa06616dde281662a1bbe2e65c055dc
[]
no_license
eFahrtenbuch/eFahrtenbuchApp
https://github.com/eFahrtenbuch/eFahrtenbuchApp
ef9c4f8594fca19463b3d73bcd8c5c9a1c775ddb
f34c1d6c9f8030a3c43c871a1f90597d6a5e2c22
refs/heads/master
2020-08-23T01:17:05.750000
2020-01-12T17:29:46
2020-01-12T17:29:46
216,513,805
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.efahrtenbuchapp.eFahrtenbuch; import java.util.Date; import java.util.concurrent.TimeUnit; import com.example.efahrtenbuchapp.utils.DateUtils; import org.json.JSONException; import org.json.JSONObject; /** Simples Business Objekt zur Repräsentation von einer Fahrt*/ public class Fahrt implements Comparable<Fahrt>{ private int id; private Date fahrtBeginnDatum = DateUtils.aktuellesDatum(); private Date fahrtBeginnZeit = DateUtils.aktuellesDatum(); private Date fahrtEndeDatum = DateUtils.aktuellesDatum(); private Date fahrtEndeZeit = DateUtils.aktuellesDatum(); private int adresseStartId; private Adresse startAdresse = new Adresse(adresseStartId, "", "", "", 0, ""); private int adresseZielId; private Adresse zielAdresse = new Adresse(adresseZielId, "", "", "", 0, ""); private String reisezweck; private String reiseroute; private String besuchtePersonenFirmenBehoerden; private double kmFahrtBeginn; private double kmFahrtEnde; private double kmGeschaeftlich; private double kmPrivat; private double kmWohnArbeit; private double kraftstoffLiter; private double kraftstoffBetrag; private double literPro100km; private double sonstigesBetrag; private String sonstigesBeschreibung; private String fahrerName; private boolean edited; private String kennzeichen; // no arg konstruktor public Fahrt() { } // full arg konstruktor //'Fahrt(int, java.util.Date, java.util.Date, java.util.Date, java.util.Date, int, int, java.lang.String, java.lang.String, java.lang.String, double, double, double, double, java.lang.String, java.lang.String, boolean, java.lang.String)' public Fahrt(int id, Date fahrtBeginnDatum, Date fahrtEndeDatum, Date fahrtBeginnZeit, Date fahrtEndeZeit, int adresseStartId, int adresseZielId, String reisezweck, String reiseroute, String beuchtePersonenFirmenBehoerden, double kmFahrtBeginn, double kmFahrtEnde, double kmGeschaeftlich, double kmPrivat, double kmWohnArbeit, double kraftstoffLiter, double kraftstoffBetrag, double literPro100km, double sonstigesBetrag, String sonstigesBezeichnung, String fahrerName, boolean edited, String kennzeichen) { super(); this.id = id; this.fahrtBeginnDatum = fahrtBeginnDatum; this.fahrtEndeDatum = fahrtEndeDatum; this.fahrtBeginnZeit = fahrtBeginnZeit; this.fahrtEndeZeit = fahrtEndeZeit; this.reisezweck = reisezweck; this.reiseroute = reiseroute; this.besuchtePersonenFirmenBehoerden = beuchtePersonenFirmenBehoerden; this.kmFahrtBeginn = kmFahrtBeginn; this.kmFahrtEnde = kmFahrtEnde; this.kmGeschaeftlich = kmGeschaeftlich; this.kmPrivat = kmPrivat; this.kmWohnArbeit = kmWohnArbeit; this.kraftstoffLiter = kraftstoffLiter; this.kraftstoffBetrag = kraftstoffBetrag; this.literPro100km = literPro100km; this.sonstigesBetrag = sonstigesBetrag; this.sonstigesBeschreibung = sonstigesBezeichnung; this.adresseStartId = adresseStartId; this.fahrerName = fahrerName; this.adresseZielId = adresseZielId; this.edited = edited; this.kennzeichen = kennzeichen; } /** * Vergleicht die IDs von Fahrten * @param o * @return */ @Override public int compareTo(Fahrt o) { if(this.id > o.getId()) return 1; if(this.id < o.getId()) return -1; return 0; } /** * Gibt die Fahrzeit als String aus * @param datum * @return */ @SuppressWarnings("deprecation") private String fahrzeitString(Date datum) { return String.format("%02d:%02d", datum.getMinutes(), datum.getHours()); } /** * Erstellt JSON Objekt aus dem aktuellen Objekt * @return */ public JSONObject toJSONObject(){ JSONObject json = new JSONObject(); try { json.put("id", id); json.put("fahrtBeginnDatum", fahrtBeginnDatum); json.put("fahrtEndeDatum" , fahrtEndeDatum); json.put("fahrtBeginnZeit" , fahrtBeginnZeit); json.put("fahrtEndeZeit" , fahrtEndeZeit); json.put("reisezweck" , reisezweck); json.put("reiseroute" , reiseroute); json.put("besuchtePersonenFirmenBehoerden" , besuchtePersonenFirmenBehoerden); json.put("kmFahrtBeginn" , kmFahrtBeginn); json.put("kmFahrtEnde" , kmFahrtEnde); json.put("kmGeschaeftlich" , kmGeschaeftlich); json.put("kmPrivat" , kmPrivat); json.put("kmWohnArbeit" , kmWohnArbeit); json.put("kraftstoffLiter" , kraftstoffLiter); json.put("kraftstoffBetrag" , kraftstoffBetrag); json.put("literPro100km" , literPro100km); json.put("sonstigesBetrag" , sonstigesBetrag); json.put("sonstigesBeschreibung" , sonstigesBeschreibung); json.put("adresseStartId" , adresseStartId); json.put("fahrerName" , fahrerName); json.put("adresseZielId" , adresseZielId); json.put("edited" , edited); json.put("kennzeichen" , kennzeichen); return json; } catch (JSONException e) { e.printStackTrace(); return null; } } @Override public String toString() { return "Fahrt{" + "id=" + id + ", fahrtBeginnDatum=" + fahrtBeginnDatum + ", fahrtBeginnZeit=" + fahrtBeginnZeit + ", fahrtEndeDatum=" + fahrtEndeDatum + ", fahrtEndeZeit=" + fahrtEndeZeit + ", adresseStartId=" + adresseStartId + ", startAdresse=" + startAdresse + ", adresseZielId=" + adresseZielId + ", zielAdresse=" + zielAdresse + ", reisezweck='" + reisezweck + '\'' + ", reiseroute='" + reiseroute + '\'' + ", besuchtePersonenFirmenBehoerden='" + besuchtePersonenFirmenBehoerden + '\'' + ", kmFahrtBeginn=" + kmFahrtBeginn + ", kmFahrtEnde=" + kmFahrtEnde + ", kmGeschaeftlich=" + kmGeschaeftlich + ", kmPrivat=" + kmPrivat + ", kmWohnArbeit=" + kmWohnArbeit + ", kraftstoffLiter=" + kraftstoffLiter + ", kraftstoffBetrag=" + kraftstoffBetrag + ", literPro100km=" + literPro100km + ", sonstigesBetrag=" + sonstigesBetrag + ", sonstigesBeschreibung='" + sonstigesBeschreibung + '\'' + ", fahrerName='" + fahrerName + '\'' + ", edited=" + edited + ", kennzeichen='" + kennzeichen + '\'' + '}'; } /*************************** Nur noch Getter/Setter ***************************/ public int getAdresseStartId() { return adresseStartId; } public int getAdresseZielId() { return adresseZielId; } public String getReisezweck() { return reisezweck; } public String getReiseroute() { return reiseroute; } public void setReiseroute(String reiseroute) { this.reiseroute = reiseroute; } public String getBesuchtePersonenFirmenBehoerden() { return besuchtePersonenFirmenBehoerden; } public double getKmFahrtBeginn() { return kmFahrtBeginn; } public double getKmFahrtEnde() { return kmFahrtEnde; } public double getKmGeschaeftlich() { return kmGeschaeftlich; } public double getKmPrivat() { return kmPrivat; } public String getSonstigesBeschreibung() { return sonstigesBeschreibung; } public String getFahrerName() { return fahrerName; } public double getKmWohnArbeit() { return kmWohnArbeit; } public double getKraftstoffLiter() { return kraftstoffLiter; } public double getKraftstoffBetrag() { return kraftstoffBetrag; } public double getLiterPro100km() { return literPro100km; } public double getSonstigesBetrag() { return sonstigesBetrag; } public int getId() { return id; } public Date getFahrtBeginnDatum() { return fahrtBeginnDatum; } public Date getFahrtEndeDatum() { return fahrtEndeDatum; } public Date getFahrtBeginnZeit() { return fahrtBeginnZeit; } public String getFahrtBeginnZeitMinusHour() { return fahrzeitString(DateUtils.minusHours(this.fahrtBeginnZeit, 1)); } public String getFahrtEndeZeitMinusHour() { return fahrzeitString(DateUtils.minusHours(this.fahrtBeginnZeit, 1)); } public Date getFahrtEndeZeit() { return fahrtEndeZeit; } public Adresse getStartAdresse() { return startAdresse; } public void setStartAdresse(Adresse startAdresse) { this.startAdresse = startAdresse; } public Adresse getZielAdresse() { return zielAdresse; } public void setZielAdresse(Adresse zielAdresse) { this.zielAdresse = zielAdresse; } public void setId(int id) { this.id = id; } public void setFahrtBeginnDatum(Date fahrtBeginnDatum) { this.fahrtBeginnDatum = fahrtBeginnDatum; } public void setFahrtEndeDatum(Date fahrtEndeDatum) { this.fahrtEndeDatum = fahrtEndeDatum; } public void setFahrtBeginnZeit(Date fahrtBeginnZeit) { this.fahrtBeginnZeit = fahrtBeginnZeit; } public void setFahrtEndeZeit(Date fahrtEndeZeit) { this.fahrtEndeZeit = fahrtEndeZeit; } public void setAdresseStartId(int adresseStartId) { this.adresseStartId = adresseStartId; } public void setAdresseZielId(int adresseZielId) { this.adresseZielId = adresseZielId; } public void setReisezweck(String reisezweck) { this.reisezweck = reisezweck; } public void setbesuchtePersonenFirmenBehoerden(String besuchtePersonenFirmenBehoerden) { this.besuchtePersonenFirmenBehoerden = besuchtePersonenFirmenBehoerden; } public void setKmFahrtBeginn(double kmFahrtBeginn) { this.kmFahrtBeginn = kmFahrtBeginn; } public void setKmFahrtEnde(double kmFahrtEnde) { this.kmFahrtEnde = kmFahrtEnde; } public void setkmGeschaeftlich(double kmGeschaeftlich) { this.kmGeschaeftlich = kmGeschaeftlich; } public void setKmPrivat(double kmPrivat) { this.kmPrivat = kmPrivat; } public void setKmWohnArbeit(double kmWohnArbeit) { this.kmWohnArbeit = kmWohnArbeit; } public void setKraftstoffLiter(double kraftstoffLiter) { this.kraftstoffLiter = kraftstoffLiter; } public void setKraftstoffBetrag(double kraftstoffBetrag) { this.kraftstoffBetrag = kraftstoffBetrag; } public void setLiterPro100km(double literPro100km) { this.literPro100km = literPro100km; } public void setSonstigesBetrag(double sonstigesBetrag) { this.sonstigesBetrag = sonstigesBetrag; } public void setSonstigesBeschreibung(String sonstigesBeschreibung) { this.sonstigesBeschreibung = sonstigesBeschreibung; } public void setFahrerName(String fahrerName) { this.fahrerName = fahrerName; } public boolean getEdited() { return edited; } public void setEdited(boolean edited) { this.edited = edited; } public String getKennzeichen() { return kennzeichen; } public void setKennzeichen(String kennzeichen) { this.kennzeichen = kennzeichen; } }
UTF-8
Java
10,257
java
Fahrt.java
Java
[]
null
[]
package com.example.efahrtenbuchapp.eFahrtenbuch; import java.util.Date; import java.util.concurrent.TimeUnit; import com.example.efahrtenbuchapp.utils.DateUtils; import org.json.JSONException; import org.json.JSONObject; /** Simples Business Objekt zur Repräsentation von einer Fahrt*/ public class Fahrt implements Comparable<Fahrt>{ private int id; private Date fahrtBeginnDatum = DateUtils.aktuellesDatum(); private Date fahrtBeginnZeit = DateUtils.aktuellesDatum(); private Date fahrtEndeDatum = DateUtils.aktuellesDatum(); private Date fahrtEndeZeit = DateUtils.aktuellesDatum(); private int adresseStartId; private Adresse startAdresse = new Adresse(adresseStartId, "", "", "", 0, ""); private int adresseZielId; private Adresse zielAdresse = new Adresse(adresseZielId, "", "", "", 0, ""); private String reisezweck; private String reiseroute; private String besuchtePersonenFirmenBehoerden; private double kmFahrtBeginn; private double kmFahrtEnde; private double kmGeschaeftlich; private double kmPrivat; private double kmWohnArbeit; private double kraftstoffLiter; private double kraftstoffBetrag; private double literPro100km; private double sonstigesBetrag; private String sonstigesBeschreibung; private String fahrerName; private boolean edited; private String kennzeichen; // no arg konstruktor public Fahrt() { } // full arg konstruktor //'Fahrt(int, java.util.Date, java.util.Date, java.util.Date, java.util.Date, int, int, java.lang.String, java.lang.String, java.lang.String, double, double, double, double, java.lang.String, java.lang.String, boolean, java.lang.String)' public Fahrt(int id, Date fahrtBeginnDatum, Date fahrtEndeDatum, Date fahrtBeginnZeit, Date fahrtEndeZeit, int adresseStartId, int adresseZielId, String reisezweck, String reiseroute, String beuchtePersonenFirmenBehoerden, double kmFahrtBeginn, double kmFahrtEnde, double kmGeschaeftlich, double kmPrivat, double kmWohnArbeit, double kraftstoffLiter, double kraftstoffBetrag, double literPro100km, double sonstigesBetrag, String sonstigesBezeichnung, String fahrerName, boolean edited, String kennzeichen) { super(); this.id = id; this.fahrtBeginnDatum = fahrtBeginnDatum; this.fahrtEndeDatum = fahrtEndeDatum; this.fahrtBeginnZeit = fahrtBeginnZeit; this.fahrtEndeZeit = fahrtEndeZeit; this.reisezweck = reisezweck; this.reiseroute = reiseroute; this.besuchtePersonenFirmenBehoerden = beuchtePersonenFirmenBehoerden; this.kmFahrtBeginn = kmFahrtBeginn; this.kmFahrtEnde = kmFahrtEnde; this.kmGeschaeftlich = kmGeschaeftlich; this.kmPrivat = kmPrivat; this.kmWohnArbeit = kmWohnArbeit; this.kraftstoffLiter = kraftstoffLiter; this.kraftstoffBetrag = kraftstoffBetrag; this.literPro100km = literPro100km; this.sonstigesBetrag = sonstigesBetrag; this.sonstigesBeschreibung = sonstigesBezeichnung; this.adresseStartId = adresseStartId; this.fahrerName = fahrerName; this.adresseZielId = adresseZielId; this.edited = edited; this.kennzeichen = kennzeichen; } /** * Vergleicht die IDs von Fahrten * @param o * @return */ @Override public int compareTo(Fahrt o) { if(this.id > o.getId()) return 1; if(this.id < o.getId()) return -1; return 0; } /** * Gibt die Fahrzeit als String aus * @param datum * @return */ @SuppressWarnings("deprecation") private String fahrzeitString(Date datum) { return String.format("%02d:%02d", datum.getMinutes(), datum.getHours()); } /** * Erstellt JSON Objekt aus dem aktuellen Objekt * @return */ public JSONObject toJSONObject(){ JSONObject json = new JSONObject(); try { json.put("id", id); json.put("fahrtBeginnDatum", fahrtBeginnDatum); json.put("fahrtEndeDatum" , fahrtEndeDatum); json.put("fahrtBeginnZeit" , fahrtBeginnZeit); json.put("fahrtEndeZeit" , fahrtEndeZeit); json.put("reisezweck" , reisezweck); json.put("reiseroute" , reiseroute); json.put("besuchtePersonenFirmenBehoerden" , besuchtePersonenFirmenBehoerden); json.put("kmFahrtBeginn" , kmFahrtBeginn); json.put("kmFahrtEnde" , kmFahrtEnde); json.put("kmGeschaeftlich" , kmGeschaeftlich); json.put("kmPrivat" , kmPrivat); json.put("kmWohnArbeit" , kmWohnArbeit); json.put("kraftstoffLiter" , kraftstoffLiter); json.put("kraftstoffBetrag" , kraftstoffBetrag); json.put("literPro100km" , literPro100km); json.put("sonstigesBetrag" , sonstigesBetrag); json.put("sonstigesBeschreibung" , sonstigesBeschreibung); json.put("adresseStartId" , adresseStartId); json.put("fahrerName" , fahrerName); json.put("adresseZielId" , adresseZielId); json.put("edited" , edited); json.put("kennzeichen" , kennzeichen); return json; } catch (JSONException e) { e.printStackTrace(); return null; } } @Override public String toString() { return "Fahrt{" + "id=" + id + ", fahrtBeginnDatum=" + fahrtBeginnDatum + ", fahrtBeginnZeit=" + fahrtBeginnZeit + ", fahrtEndeDatum=" + fahrtEndeDatum + ", fahrtEndeZeit=" + fahrtEndeZeit + ", adresseStartId=" + adresseStartId + ", startAdresse=" + startAdresse + ", adresseZielId=" + adresseZielId + ", zielAdresse=" + zielAdresse + ", reisezweck='" + reisezweck + '\'' + ", reiseroute='" + reiseroute + '\'' + ", besuchtePersonenFirmenBehoerden='" + besuchtePersonenFirmenBehoerden + '\'' + ", kmFahrtBeginn=" + kmFahrtBeginn + ", kmFahrtEnde=" + kmFahrtEnde + ", kmGeschaeftlich=" + kmGeschaeftlich + ", kmPrivat=" + kmPrivat + ", kmWohnArbeit=" + kmWohnArbeit + ", kraftstoffLiter=" + kraftstoffLiter + ", kraftstoffBetrag=" + kraftstoffBetrag + ", literPro100km=" + literPro100km + ", sonstigesBetrag=" + sonstigesBetrag + ", sonstigesBeschreibung='" + sonstigesBeschreibung + '\'' + ", fahrerName='" + fahrerName + '\'' + ", edited=" + edited + ", kennzeichen='" + kennzeichen + '\'' + '}'; } /*************************** Nur noch Getter/Setter ***************************/ public int getAdresseStartId() { return adresseStartId; } public int getAdresseZielId() { return adresseZielId; } public String getReisezweck() { return reisezweck; } public String getReiseroute() { return reiseroute; } public void setReiseroute(String reiseroute) { this.reiseroute = reiseroute; } public String getBesuchtePersonenFirmenBehoerden() { return besuchtePersonenFirmenBehoerden; } public double getKmFahrtBeginn() { return kmFahrtBeginn; } public double getKmFahrtEnde() { return kmFahrtEnde; } public double getKmGeschaeftlich() { return kmGeschaeftlich; } public double getKmPrivat() { return kmPrivat; } public String getSonstigesBeschreibung() { return sonstigesBeschreibung; } public String getFahrerName() { return fahrerName; } public double getKmWohnArbeit() { return kmWohnArbeit; } public double getKraftstoffLiter() { return kraftstoffLiter; } public double getKraftstoffBetrag() { return kraftstoffBetrag; } public double getLiterPro100km() { return literPro100km; } public double getSonstigesBetrag() { return sonstigesBetrag; } public int getId() { return id; } public Date getFahrtBeginnDatum() { return fahrtBeginnDatum; } public Date getFahrtEndeDatum() { return fahrtEndeDatum; } public Date getFahrtBeginnZeit() { return fahrtBeginnZeit; } public String getFahrtBeginnZeitMinusHour() { return fahrzeitString(DateUtils.minusHours(this.fahrtBeginnZeit, 1)); } public String getFahrtEndeZeitMinusHour() { return fahrzeitString(DateUtils.minusHours(this.fahrtBeginnZeit, 1)); } public Date getFahrtEndeZeit() { return fahrtEndeZeit; } public Adresse getStartAdresse() { return startAdresse; } public void setStartAdresse(Adresse startAdresse) { this.startAdresse = startAdresse; } public Adresse getZielAdresse() { return zielAdresse; } public void setZielAdresse(Adresse zielAdresse) { this.zielAdresse = zielAdresse; } public void setId(int id) { this.id = id; } public void setFahrtBeginnDatum(Date fahrtBeginnDatum) { this.fahrtBeginnDatum = fahrtBeginnDatum; } public void setFahrtEndeDatum(Date fahrtEndeDatum) { this.fahrtEndeDatum = fahrtEndeDatum; } public void setFahrtBeginnZeit(Date fahrtBeginnZeit) { this.fahrtBeginnZeit = fahrtBeginnZeit; } public void setFahrtEndeZeit(Date fahrtEndeZeit) { this.fahrtEndeZeit = fahrtEndeZeit; } public void setAdresseStartId(int adresseStartId) { this.adresseStartId = adresseStartId; } public void setAdresseZielId(int adresseZielId) { this.adresseZielId = adresseZielId; } public void setReisezweck(String reisezweck) { this.reisezweck = reisezweck; } public void setbesuchtePersonenFirmenBehoerden(String besuchtePersonenFirmenBehoerden) { this.besuchtePersonenFirmenBehoerden = besuchtePersonenFirmenBehoerden; } public void setKmFahrtBeginn(double kmFahrtBeginn) { this.kmFahrtBeginn = kmFahrtBeginn; } public void setKmFahrtEnde(double kmFahrtEnde) { this.kmFahrtEnde = kmFahrtEnde; } public void setkmGeschaeftlich(double kmGeschaeftlich) { this.kmGeschaeftlich = kmGeschaeftlich; } public void setKmPrivat(double kmPrivat) { this.kmPrivat = kmPrivat; } public void setKmWohnArbeit(double kmWohnArbeit) { this.kmWohnArbeit = kmWohnArbeit; } public void setKraftstoffLiter(double kraftstoffLiter) { this.kraftstoffLiter = kraftstoffLiter; } public void setKraftstoffBetrag(double kraftstoffBetrag) { this.kraftstoffBetrag = kraftstoffBetrag; } public void setLiterPro100km(double literPro100km) { this.literPro100km = literPro100km; } public void setSonstigesBetrag(double sonstigesBetrag) { this.sonstigesBetrag = sonstigesBetrag; } public void setSonstigesBeschreibung(String sonstigesBeschreibung) { this.sonstigesBeschreibung = sonstigesBeschreibung; } public void setFahrerName(String fahrerName) { this.fahrerName = fahrerName; } public boolean getEdited() { return edited; } public void setEdited(boolean edited) { this.edited = edited; } public String getKennzeichen() { return kennzeichen; } public void setKennzeichen(String kennzeichen) { this.kennzeichen = kennzeichen; } }
10,257
0.737422
0.732254
374
26.422461
25.940659
238
false
false
0
0
0
0
0
0
2.05615
false
false
10
ef13e4df47b550cf26c7bb732a48e7dd4fbe1852
28,776,280,935,694
ca030864a3a1c24be6b9d1802c2353da4ca0d441
/classes10.dex_source_from_JADX/com/facebook/groups/photos/adapter/GroupsPhotosPagerAdapter.java
f68786b261460e7e9b0e32bfac1ec4f2ccfc8863
[]
no_license
pxson001/facebook-app
https://github.com/pxson001/facebook-app
87aa51e29195eeaae69adeb30219547f83a5b7b1
640630f078980f9818049625ebc42569c67c69f7
refs/heads/master
2020-04-07T20:36:45.758000
2018-03-07T09:04:57
2018-03-07T09:04:57
124,208,458
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.groups.photos.adapter; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import com.facebook.groups.adapter.AbstractFragmentHolderFragmentPagerAdapter; import com.facebook.groups.photos.fragment.GroupAlbumsFragment; import com.facebook.groups.photos.fragment.GroupAllPhotosFragment; import com.facebook.photos.pandora.common.data.SimplePandoraInstanceId; /* compiled from: TOXICLE_PUBLIC_GOING_SELECTED_WITH_CHEVRON */ public class GroupsPhotosPagerAdapter extends AbstractFragmentHolderFragmentPagerAdapter { private Resources f22996a; private String f22997b; private String f22998c; public GroupsPhotosPagerAdapter(FragmentManager fragmentManager, String str, String str2, Resources resources) { super(fragmentManager); this.f22997b = str; this.f22998c = str2; this.f22996a = resources; } public final Fragment m24215a(int i) { Bundle bundle = new Bundle(); bundle.putString("group_feed_id", this.f22997b); bundle.putString("group_name", this.f22998c); Fragment groupAllPhotosFragment; switch (i) { case 0: groupAllPhotosFragment = new GroupAllPhotosFragment(); groupAllPhotosFragment.g(bundle); bundle.putParcelable("pandora_instance_id", new SimplePandoraInstanceId(this.f22997b)); return groupAllPhotosFragment; case 1: groupAllPhotosFragment = new GroupAlbumsFragment(); groupAllPhotosFragment.g(bundle); return groupAllPhotosFragment; default: return null; } } public final CharSequence J_(int i) { switch (i) { case 0: return this.f22996a.getString(2131242204); case 1: return this.f22996a.getString(2131242205); default: return null; } } public final int m24216b() { return 2; } }
UTF-8
Java
2,114
java
GroupsPhotosPagerAdapter.java
Java
[]
null
[]
package com.facebook.groups.photos.adapter; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import com.facebook.groups.adapter.AbstractFragmentHolderFragmentPagerAdapter; import com.facebook.groups.photos.fragment.GroupAlbumsFragment; import com.facebook.groups.photos.fragment.GroupAllPhotosFragment; import com.facebook.photos.pandora.common.data.SimplePandoraInstanceId; /* compiled from: TOXICLE_PUBLIC_GOING_SELECTED_WITH_CHEVRON */ public class GroupsPhotosPagerAdapter extends AbstractFragmentHolderFragmentPagerAdapter { private Resources f22996a; private String f22997b; private String f22998c; public GroupsPhotosPagerAdapter(FragmentManager fragmentManager, String str, String str2, Resources resources) { super(fragmentManager); this.f22997b = str; this.f22998c = str2; this.f22996a = resources; } public final Fragment m24215a(int i) { Bundle bundle = new Bundle(); bundle.putString("group_feed_id", this.f22997b); bundle.putString("group_name", this.f22998c); Fragment groupAllPhotosFragment; switch (i) { case 0: groupAllPhotosFragment = new GroupAllPhotosFragment(); groupAllPhotosFragment.g(bundle); bundle.putParcelable("pandora_instance_id", new SimplePandoraInstanceId(this.f22997b)); return groupAllPhotosFragment; case 1: groupAllPhotosFragment = new GroupAlbumsFragment(); groupAllPhotosFragment.g(bundle); return groupAllPhotosFragment; default: return null; } } public final CharSequence J_(int i) { switch (i) { case 0: return this.f22996a.getString(2131242204); case 1: return this.f22996a.getString(2131242205); default: return null; } } public final int m24216b() { return 2; } }
2,114
0.663198
0.618732
59
34.830509
26.395397
116
false
false
0
0
0
0
0
0
0.644068
false
false
10
9940ca470b94c43cdc8a5c8a842c5b2746ff4829
5,102,421,173,199
e22d613175560983542013a9988494820abeb5d1
/src/main/java/com/syntra/tristanbrewee/miniCrm/persistance/services/CommunityServiceImp.java
95691ab0001b0e68b032787ac3e854050a7e66f3
[]
no_license
tristanbrewee/miniCrm
https://github.com/tristanbrewee/miniCrm
ef6b25986ec49cdb4984b848ead22ff25aad2eae
8aa27958c47d25ee35cce85c4273a1e15f4d76d9
refs/heads/master
2023-06-06T14:16:59.041000
2021-06-29T14:35:04
2021-06-29T14:35:04
378,500,564
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.syntra.tristanbrewee.miniCrm.persistance.services; import com.syntra.tristanbrewee.miniCrm.model.Community; import com.syntra.tristanbrewee.miniCrm.model.dtos.CompletePerson; import com.syntra.tristanbrewee.miniCrm.persistance.repositories.CommunityRepository; import com.syntra.tristanbrewee.miniCrm.utils.Conversions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class CommunityServiceImp implements CommunityService{ private CommunityRepository communityRepository; @Autowired public CommunityServiceImp(CommunityRepository communityRepository) { this.communityRepository = communityRepository; } public List<Community> findAll(){ return communityRepository.findAll(); } public void save(Community community){ communityRepository.save(community); } public void delete(Community community){ communityRepository.delete(community); } public Optional<Community> findById(Integer id){ return communityRepository.findById(id); } }
UTF-8
Java
1,196
java
CommunityServiceImp.java
Java
[]
null
[]
package com.syntra.tristanbrewee.miniCrm.persistance.services; import com.syntra.tristanbrewee.miniCrm.model.Community; import com.syntra.tristanbrewee.miniCrm.model.dtos.CompletePerson; import com.syntra.tristanbrewee.miniCrm.persistance.repositories.CommunityRepository; import com.syntra.tristanbrewee.miniCrm.utils.Conversions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class CommunityServiceImp implements CommunityService{ private CommunityRepository communityRepository; @Autowired public CommunityServiceImp(CommunityRepository communityRepository) { this.communityRepository = communityRepository; } public List<Community> findAll(){ return communityRepository.findAll(); } public void save(Community community){ communityRepository.save(community); } public void delete(Community community){ communityRepository.delete(community); } public Optional<Community> findById(Integer id){ return communityRepository.findById(id); } }
1,196
0.782609
0.782609
39
29.666666
26.19878
85
false
false
0
0
0
0
0
0
0.410256
false
false
10
49b4814f0fdb978736553ab060a44630ea310df7
29,016,799,101,225
37cf5ca3c1534a2d073ba25a91536b0d48ab1785
/SuffocateGame/Quit.java
8c96a2c3b7187998eb350e315de44a65e946ef87
[]
no_license
m-glock/SuffocateGame
https://github.com/m-glock/SuffocateGame
586af4cadc0305ca5e43ceb14ea210284529381f
41a144091bb66e4a74f3ce3bf0c27f0650cbefdd
refs/heads/master
2020-06-27T21:44:31.270000
2016-11-22T21:23:00
2016-11-22T21:23:00
74,514,325
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Quit extends Command { public Quit(String parameter) { super(parameter); } /** * "Quit" was entered. Check the rest of the command to see * whether we really quit the game. * @return null, if this command quits the game, something else to output otherwise. */ public GameState execute(GameState state) { if(hasParameter()){ state.output = "Quit what?"; } else { state.wantsToQuit= true; state.output = null; } return state; } }
UTF-8
Java
571
java
Quit.java
Java
[]
null
[]
public class Quit extends Command { public Quit(String parameter) { super(parameter); } /** * "Quit" was entered. Check the rest of the command to see * whether we really quit the game. * @return null, if this command quits the game, something else to output otherwise. */ public GameState execute(GameState state) { if(hasParameter()){ state.output = "Quit what?"; } else { state.wantsToQuit= true; state.output = null; } return state; } }
571
0.562172
0.562172
23
23.73913
21.736
88
false
false
0
0
0
0
0
0
0.304348
false
false
10
78be0017d0a4a69f98d37a7b2d17e430024d36fc
6,416,681,145,929
17a5a3cfcf1f83cc3b543ab038174ec211e15609
/src/main/java/Relations/BasicRelationInterface.java
ccb6189465d56e0daca166c2f8f7308b824aa133
[]
no_license
DDDDDh/IncrementalCCC
https://github.com/DDDDDh/IncrementalCCC
c0ddb404c5a30bcc26d919c09159f0f86d270253
15bc4e9557d2edbb8e42473aa763829ac7cb110e
refs/heads/master
2023-07-31T17:54:50.038000
2021-09-17T13:49:26
2021-09-17T13:49:26
289,827,906
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Relations; import History.Operation; import java.util.LinkedList; import java.util.BitSet; public interface BasicRelationInterface { void setTrue(int fromIndex, int toIndex); boolean existEdge(int fromIndex, int toIndex); void printMatrix(); // boolean[][] getRelationMatrix(); BitSet[] getRelationMatrix(); int getMatrixSize(); void union(BasicRelation r1, BasicRelation r2); void unionAndSetVis(BasicRelation r1, BasicRelation r2, LinkedList<Operation> opList); }
UTF-8
Java
510
java
BasicRelationInterface.java
Java
[]
null
[]
package Relations; import History.Operation; import java.util.LinkedList; import java.util.BitSet; public interface BasicRelationInterface { void setTrue(int fromIndex, int toIndex); boolean existEdge(int fromIndex, int toIndex); void printMatrix(); // boolean[][] getRelationMatrix(); BitSet[] getRelationMatrix(); int getMatrixSize(); void union(BasicRelation r1, BasicRelation r2); void unionAndSetVis(BasicRelation r1, BasicRelation r2, LinkedList<Operation> opList); }
510
0.745098
0.737255
19
25.842106
23.131804
90
false
false
0
0
0
0
0
0
0.894737
false
false
10
5d104b712070f4a4a86aa31bec9f3954d2034a68
987,842,489,204
3943d6f3a246f402691c343f406aa8a326d33fd0
/src/main/java/com/koala/learn/entity/LabCourse.java
1c954ab8cdf6dd9218e49b5261fa5b5383086542
[]
no_license
jiaody111/online
https://github.com/jiaody111/online
c6909204af07a1f0a807b6ce9d95b99e2982401c
f3be218a502a9b72fb7a593fc4ead660ab6e9127
refs/heads/master
2020-08-30T00:18:09.377000
2020-03-11T01:47:49
2020-03-11T01:47:49
218,212,314
0
0
null
true
2019-10-29T05:41:22
2019-10-29T05:41:21
2019-10-21T06:14:31
2019-10-29T04:57:46
17,161
0
0
0
null
false
false
package com.koala.learn.entity; //精品课程 public class LabCourse { private Integer id; private String name; private Long blogId; private String cover; public LabCourse(){ } public LabCourse(Integer id, String name, Long blogId, String cover) { this.id = id; this.name = name; this.blogId = blogId; this.cover = cover; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getBlogId() { return blogId; } public void setBlogId(Long blogId) { this.blogId = blogId; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } }
UTF-8
Java
919
java
LabCourse.java
Java
[]
null
[]
package com.koala.learn.entity; //精品课程 public class LabCourse { private Integer id; private String name; private Long blogId; private String cover; public LabCourse(){ } public LabCourse(Integer id, String name, Long blogId, String cover) { this.id = id; this.name = name; this.blogId = blogId; this.cover = cover; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getBlogId() { return blogId; } public void setBlogId(Long blogId) { this.blogId = blogId; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } }
919
0.564215
0.564215
52
16.51923
15.254873
74
false
false
0
0
0
0
0
0
0.384615
false
false
10
5468a188f553e21a27ead391a89e0926763717f1
987,842,489,049
aa7bb13298c759240cb1e11ce49e7d15241b0c31
/src/org/cts/pun/sba/utils/DateUtils.java
d7ba13525fe8c775e5181e45b6cced34f024286f
[]
no_license
DipanGarg/Automation
https://github.com/DipanGarg/Automation
7817df708e291553fb1094848c85a2dee1bd2248
f6f6c3145f1b551baf5fdf08aea65543569282bc
refs/heads/master
2020-03-10T21:12:45.019000
2018-04-21T08:17:09
2018-04-21T08:17:09
129,588,278
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.cts.pun.sba.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtils { public static String parseIntoString(Date date){ SimpleDateFormat sdf= new SimpleDateFormat("dd-MMM yyyy"); return sdf.format(date); } public static Date parseIntoDate(String date) throws ParseException{ SimpleDateFormat sdf= new SimpleDateFormat("dd-MMM yyyy"); return sdf.parse(date); } public static String getCurrentDate(){ Calendar cal= Calendar.getInstance(); Date date=cal.getTime(); return parseIntoString(date); } public static String getTomorrowDate(){ return parseIntoString(getDateWrtCurrentDate(1)); } private static Date getDateWrtCurrentDate(int diff){ Calendar cal= Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE,diff); return cal.getTime(); } }
UTF-8
Java
909
java
DateUtils.java
Java
[]
null
[]
package org.cts.pun.sba.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtils { public static String parseIntoString(Date date){ SimpleDateFormat sdf= new SimpleDateFormat("dd-MMM yyyy"); return sdf.format(date); } public static Date parseIntoDate(String date) throws ParseException{ SimpleDateFormat sdf= new SimpleDateFormat("dd-MMM yyyy"); return sdf.parse(date); } public static String getCurrentDate(){ Calendar cal= Calendar.getInstance(); Date date=cal.getTime(); return parseIntoString(date); } public static String getTomorrowDate(){ return parseIntoString(getDateWrtCurrentDate(1)); } private static Date getDateWrtCurrentDate(int diff){ Calendar cal= Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE,diff); return cal.getTime(); } }
909
0.752475
0.751375
37
23.567568
20.414013
69
false
false
0
0
0
0
0
0
1.594595
false
false
10
f41e90f35a35551a52c5e1a85af3a50c77c3aa01
987,842,491,993
fccff8918645f8a5440db104aff3fef54fe1327d
/Bodil/Publications/src/se/blinfo/newsservice/publications/model/PublicationEntryChildrenFactory.java
0945557e9dd2a53fd43daf257df697a9592c5708
[]
no_license
blinfo/Bodil
https://github.com/blinfo/Bodil
8706c1fbc6875615ad4ff1f2d859c0e67d00df09
435ec1c81e66d46185576390a493f9d276d2164f
refs/heads/master
2018-12-28T23:31:42.195000
2018-04-09T08:23:39
2018-04-09T08:23:39
32,069,437
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.blinfo.newsservice.publications.model; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Comparator; import java.util.List; import org.openide.nodes.ChildFactory; import org.openide.nodes.Node; import org.openide.util.Lookup; import se.blinfo.newsservice.base.service.HandlerFactory; import se.blinfo.newsservice.core.domain.Article; import se.blinfo.newsservice.core.domain.Publication; import se.blinfo.newsservice.core.domain.publication.PublicationEntry; import se.blinfo.newsservice.publications.service.PublicationManager; /** * Created 2012-apr-19 * * @author jep */ public class PublicationEntryChildrenFactory extends ChildFactory<PublicationEntry> implements PropertyChangeListener { private final Publication publication; private static Comparator<Article> comparator = new Comparator<Article>() { @Override public int compare(Article o1, Article o2) { return o1.getTitle().compareToIgnoreCase(o2.getTitle()); } }; public PublicationEntryChildrenFactory(Publication publication) { this.publication = publication; PublicationManager manager = Lookup.getDefault().lookup(PublicationManager.class); manager.addPropertyChangeListener(this); } @Override protected boolean createKeys(List<PublicationEntry> toPopulate) { List<PublicationEntry> entriesByPublication = HandlerFactory.getServiceHandler().getPublicationService().findEntriesByPublication(publication); // Collections.sort(entriesByPublication, comparator); toPopulate.addAll(entriesByPublication); return true; } @Override protected Node createNodeForKey(PublicationEntry key) { return new PublicationEntryNode(key); } @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(PublicationManager.PROP_DOMAIN_ENTITY_UPDATE)) { if (evt.getNewValue() instanceof Publication) { Publication newValue = (Publication) evt.getNewValue(); if (newValue.equals(publication)) { refresh(true); } } } } }
UTF-8
Java
2,232
java
PublicationEntryChildrenFactory.java
Java
[ { "context": "Manager;\n\n/**\n * Created 2012-apr-19\n *\n * @author jep\n */\npublic class PublicationEntryChildrenFactory ", "end": 634, "score": 0.9963117837905884, "start": 631, "tag": "USERNAME", "value": "jep" } ]
null
[]
package se.blinfo.newsservice.publications.model; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Comparator; import java.util.List; import org.openide.nodes.ChildFactory; import org.openide.nodes.Node; import org.openide.util.Lookup; import se.blinfo.newsservice.base.service.HandlerFactory; import se.blinfo.newsservice.core.domain.Article; import se.blinfo.newsservice.core.domain.Publication; import se.blinfo.newsservice.core.domain.publication.PublicationEntry; import se.blinfo.newsservice.publications.service.PublicationManager; /** * Created 2012-apr-19 * * @author jep */ public class PublicationEntryChildrenFactory extends ChildFactory<PublicationEntry> implements PropertyChangeListener { private final Publication publication; private static Comparator<Article> comparator = new Comparator<Article>() { @Override public int compare(Article o1, Article o2) { return o1.getTitle().compareToIgnoreCase(o2.getTitle()); } }; public PublicationEntryChildrenFactory(Publication publication) { this.publication = publication; PublicationManager manager = Lookup.getDefault().lookup(PublicationManager.class); manager.addPropertyChangeListener(this); } @Override protected boolean createKeys(List<PublicationEntry> toPopulate) { List<PublicationEntry> entriesByPublication = HandlerFactory.getServiceHandler().getPublicationService().findEntriesByPublication(publication); // Collections.sort(entriesByPublication, comparator); toPopulate.addAll(entriesByPublication); return true; } @Override protected Node createNodeForKey(PublicationEntry key) { return new PublicationEntryNode(key); } @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(PublicationManager.PROP_DOMAIN_ENTITY_UPDATE)) { if (evt.getNewValue() instanceof Publication) { Publication newValue = (Publication) evt.getNewValue(); if (newValue.equals(publication)) { refresh(true); } } } } }
2,232
0.724462
0.719982
62
35
32.039795
151
false
false
0
0
0
0
0
0
0.451613
false
false
10
dc189dd41d26e360dd11932edb265ef36849baf3
16,028,817,958,074
ad02e150ccb70cf8e228911f1f5c2402423e446d
/src/main/java/fireopal/erodedsurface/NewDefaultSurfaceBuilder.java
ecd09de9e9e28b891102dd91c00616988e8ba6ac
[ "CC0-1.0" ]
permissive
firenh/eroded_surface_builder
https://github.com/firenh/eroded_surface_builder
189e43598bf001fba6d536025557b19473d18984
11df4178ca00c5fc4846569ed99d521125329f48
refs/heads/master
2023-08-11T03:16:58.902000
2021-10-03T21:42:32
2021-10-03T21:42:32
413,189,439
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fireopal.erodedsurface; import java.util.Random; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.gen.surfacebuilder.DefaultSurfaceBuilder; public class NewDefaultSurfaceBuilder { public static void generate(DefaultSurfaceBuilder self, Random random, Chunk chunk, Biome biome, int x, int z, int height, double noise, BlockState defaultBlock, BlockState fluidBlock, BlockState topBlock, BlockState underBlock, BlockState underwaterBlock, int seaLevel, int i) { BlockPos.Mutable mutable = new BlockPos.Mutable(); int j = (int)(noise / 3.0D + 3.0D + random.nextDouble() * 0.25D); int k; BlockState blockState5; BlockPos targetPos = new BlockPos(x, height - 1, z); BlockPos.Mutable newTargetPos; Direction[] xAxisDirections = {Direction.EAST, Direction.WEST}; Direction[] zAxisDirections = {Direction.NORTH, Direction.SOUTH}; Direction[] directions = {Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST}; int validSlope = 0; boolean isOnChunkBorder = (x % 16 == 0 || x % 16 == 15) && (z % 16 == 0 || z % 16 == 15); for (Direction d : directions) { newTargetPos = targetPos.offset(d).mutableCopy(); if (!(chunk.getBlockState(newTargetPos).isAir()) && chunk.getBlockState(newTargetPos.up()).isAir()) { validSlope += 5; } else if ((!(chunk.getBlockState(newTargetPos.up()).isAir()) && chunk.getBlockState(newTargetPos.up(2)).isAir())) { validSlope += 4; } else if ((!(chunk.getBlockState(newTargetPos.down()).isAir()) && chunk.getBlockState(newTargetPos).isAir())) { validSlope += 4; } if (d == Direction.NORTH || d == Direction.SOUTH) { for (Direction xDirection : xAxisDirections) { newTargetPos = targetPos.offset(d).offset(xDirection).mutableCopy(); if (!(chunk.getBlockState(newTargetPos).isAir()) && chunk.getBlockState(newTargetPos.up()).isAir()) { validSlope += 5; } else if ((!(chunk.getBlockState(newTargetPos.up()).isAir()) && chunk.getBlockState(newTargetPos.up(2)).isAir())) { validSlope += 4; } else if ((!(chunk.getBlockState(newTargetPos.down()).isAir()) && chunk.getBlockState(newTargetPos).isAir())) { validSlope += 4; } } } else if (d == Direction.EAST || d == Direction.WEST) { for (Direction zDirection : zAxisDirections) { newTargetPos = targetPos.offset(d).offset(zDirection).mutableCopy(); if (!(chunk.getBlockState(newTargetPos).isAir()) && chunk.getBlockState(newTargetPos.up()).isAir()) { validSlope += 3; } else if ((!(chunk.getBlockState(newTargetPos.up()).isAir()) && chunk.getBlockState(newTargetPos.up(2)).isAir())) { validSlope += 2; } else if ((!(chunk.getBlockState(newTargetPos.down()).isAir()) && chunk.getBlockState(newTargetPos).isAir())) { validSlope += 2; } } } } int threshold = 18 + (int)((3 * noise) / 8); boolean canGenerate = isOnChunkBorder ? validSlope >= 1 : validSlope >= threshold || validSlope == 0; if (validSlope > 0) { j = j - (int)(threshold * 0.5 / validSlope) ; } else { j = 0; } j = j <= 0 ? 0 : j; if (canGenerate) { if (j == 0) { boolean bl = false; for (k = height; k >= i; --k) { mutable.set(x, k, z); BlockState blockState = chunk.getBlockState(mutable); if (blockState.isAir()) { bl = false; } else if (blockState.isOf(defaultBlock.getBlock())) { if (!bl) { if (k >= seaLevel) { blockState5 = Blocks.AIR.getDefaultState(); } else if (k == seaLevel - 1) { blockState5 = biome.getTemperature(mutable) < 0.15F ? Blocks.ICE.getDefaultState() : fluidBlock; } else { blockState5 = underwaterBlock; } chunk.setBlockState(mutable, blockState5, false); } bl = true; } } } else { BlockState blockState6 = underBlock; k = -1; for (int m = height; m >= i; --m) { mutable.set(x, m, z); blockState5 = chunk.getBlockState(mutable); if (blockState5.isAir()) { k = -1; } else if (blockState5.isOf(defaultBlock.getBlock())) { if (k == -1) { k = j; BlockState blockState12; if (m >= seaLevel + 2) { blockState12 = topBlock; } else if (m >= seaLevel - 1) { blockState6 = underBlock; blockState12 = topBlock; } else if (m >= seaLevel - (7 + j)) { blockState12 = blockState6; } else { blockState6 = defaultBlock; blockState12 = underwaterBlock; } chunk.setBlockState(mutable, blockState12, false); } else if (k > 0) { --k; chunk.setBlockState(mutable, blockState6, false); if (k == 0 && blockState6.isOf(Blocks.SAND) && j > 1) { k = random.nextInt(4) + Math.max(0, m - seaLevel); blockState6 = blockState6.isOf(Blocks.RED_SAND) ? Blocks.RED_SANDSTONE.getDefaultState() : Blocks.SANDSTONE.getDefaultState(); } } } } } } } }
UTF-8
Java
6,742
java
NewDefaultSurfaceBuilder.java
Java
[]
null
[]
package fireopal.erodedsurface; import java.util.Random; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.gen.surfacebuilder.DefaultSurfaceBuilder; public class NewDefaultSurfaceBuilder { public static void generate(DefaultSurfaceBuilder self, Random random, Chunk chunk, Biome biome, int x, int z, int height, double noise, BlockState defaultBlock, BlockState fluidBlock, BlockState topBlock, BlockState underBlock, BlockState underwaterBlock, int seaLevel, int i) { BlockPos.Mutable mutable = new BlockPos.Mutable(); int j = (int)(noise / 3.0D + 3.0D + random.nextDouble() * 0.25D); int k; BlockState blockState5; BlockPos targetPos = new BlockPos(x, height - 1, z); BlockPos.Mutable newTargetPos; Direction[] xAxisDirections = {Direction.EAST, Direction.WEST}; Direction[] zAxisDirections = {Direction.NORTH, Direction.SOUTH}; Direction[] directions = {Direction.NORTH, Direction.SOUTH, Direction.EAST, Direction.WEST}; int validSlope = 0; boolean isOnChunkBorder = (x % 16 == 0 || x % 16 == 15) && (z % 16 == 0 || z % 16 == 15); for (Direction d : directions) { newTargetPos = targetPos.offset(d).mutableCopy(); if (!(chunk.getBlockState(newTargetPos).isAir()) && chunk.getBlockState(newTargetPos.up()).isAir()) { validSlope += 5; } else if ((!(chunk.getBlockState(newTargetPos.up()).isAir()) && chunk.getBlockState(newTargetPos.up(2)).isAir())) { validSlope += 4; } else if ((!(chunk.getBlockState(newTargetPos.down()).isAir()) && chunk.getBlockState(newTargetPos).isAir())) { validSlope += 4; } if (d == Direction.NORTH || d == Direction.SOUTH) { for (Direction xDirection : xAxisDirections) { newTargetPos = targetPos.offset(d).offset(xDirection).mutableCopy(); if (!(chunk.getBlockState(newTargetPos).isAir()) && chunk.getBlockState(newTargetPos.up()).isAir()) { validSlope += 5; } else if ((!(chunk.getBlockState(newTargetPos.up()).isAir()) && chunk.getBlockState(newTargetPos.up(2)).isAir())) { validSlope += 4; } else if ((!(chunk.getBlockState(newTargetPos.down()).isAir()) && chunk.getBlockState(newTargetPos).isAir())) { validSlope += 4; } } } else if (d == Direction.EAST || d == Direction.WEST) { for (Direction zDirection : zAxisDirections) { newTargetPos = targetPos.offset(d).offset(zDirection).mutableCopy(); if (!(chunk.getBlockState(newTargetPos).isAir()) && chunk.getBlockState(newTargetPos.up()).isAir()) { validSlope += 3; } else if ((!(chunk.getBlockState(newTargetPos.up()).isAir()) && chunk.getBlockState(newTargetPos.up(2)).isAir())) { validSlope += 2; } else if ((!(chunk.getBlockState(newTargetPos.down()).isAir()) && chunk.getBlockState(newTargetPos).isAir())) { validSlope += 2; } } } } int threshold = 18 + (int)((3 * noise) / 8); boolean canGenerate = isOnChunkBorder ? validSlope >= 1 : validSlope >= threshold || validSlope == 0; if (validSlope > 0) { j = j - (int)(threshold * 0.5 / validSlope) ; } else { j = 0; } j = j <= 0 ? 0 : j; if (canGenerate) { if (j == 0) { boolean bl = false; for (k = height; k >= i; --k) { mutable.set(x, k, z); BlockState blockState = chunk.getBlockState(mutable); if (blockState.isAir()) { bl = false; } else if (blockState.isOf(defaultBlock.getBlock())) { if (!bl) { if (k >= seaLevel) { blockState5 = Blocks.AIR.getDefaultState(); } else if (k == seaLevel - 1) { blockState5 = biome.getTemperature(mutable) < 0.15F ? Blocks.ICE.getDefaultState() : fluidBlock; } else { blockState5 = underwaterBlock; } chunk.setBlockState(mutable, blockState5, false); } bl = true; } } } else { BlockState blockState6 = underBlock; k = -1; for (int m = height; m >= i; --m) { mutable.set(x, m, z); blockState5 = chunk.getBlockState(mutable); if (blockState5.isAir()) { k = -1; } else if (blockState5.isOf(defaultBlock.getBlock())) { if (k == -1) { k = j; BlockState blockState12; if (m >= seaLevel + 2) { blockState12 = topBlock; } else if (m >= seaLevel - 1) { blockState6 = underBlock; blockState12 = topBlock; } else if (m >= seaLevel - (7 + j)) { blockState12 = blockState6; } else { blockState6 = defaultBlock; blockState12 = underwaterBlock; } chunk.setBlockState(mutable, blockState12, false); } else if (k > 0) { --k; chunk.setBlockState(mutable, blockState6, false); if (k == 0 && blockState6.isOf(Blocks.SAND) && j > 1) { k = random.nextInt(4) + Math.max(0, m - seaLevel); blockState6 = blockState6.isOf(Blocks.RED_SAND) ? Blocks.RED_SANDSTONE.getDefaultState() : Blocks.SANDSTONE.getDefaultState(); } } } } } } } }
6,742
0.481311
0.467814
147
44.863945
40.50626
283
false
false
0
0
0
0
0
0
0.782313
false
false
10
fb3f6c83156d336579eed3e2c8ec920921709270
23,476,291,249,385
8cbcf2bb8b930a8c1d0402d17977f17bb50ddfb2
/app/src/main/java/team/exp/solaretrace/RequestObjects/AssignmentRequest.java
5f1807857a1300bde04e85d2217e63413d41d9f2
[]
no_license
Aashijit/SolareTrace
https://github.com/Aashijit/SolareTrace
1072f9d80ae823c4b5d910fcd3f1fbb25f1dbcc8
eff618386f88534914cb5876a92c376168d69d6d
refs/heads/master
2020-05-01T03:00:29.579000
2020-03-25T16:37:48
2020-03-25T16:37:48
177,235,159
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package team.exp.solaretrace.RequestObjects; import java.util.List; /** * Created by Aashijit on 07/04/2019. */ public class AssignmentRequest { private String _ClockInId; private String _ClockOut; private String _DeviceId; private String _ClockOutLat; private String _ClockOutLang; private List<LocationRequest> locations; public String get_ClockInId() { return _ClockInId; } public void set_ClockInId(String _ClockInId) { this._ClockInId = _ClockInId; } public String get_ClockOut() { return _ClockOut; } public void set_ClockOut(String _ClockOut) { this._ClockOut = _ClockOut; } public String get_DeviceId() { return _DeviceId; } public void set_DeviceId(String _DeviceId) { this._DeviceId = _DeviceId; } public String get_ClockOutLat() { return _ClockOutLat; } public void set_ClockOutLat(String _ClockOutLat) { this._ClockOutLat = _ClockOutLat; } public String get_ClockOutLang() { return _ClockOutLang; } public void set_ClockOutLang(String _ClockOutLang) { this._ClockOutLang = _ClockOutLang; } public List<LocationRequest> getLocations() { return locations; } public void setLocations(List<LocationRequest> locations) { this.locations = locations; } @Override public String toString() { return "AssignmentRequest{" + "_ClockInId='" + _ClockInId + '\'' + ", _ClockOut='" + _ClockOut + '\'' + ", _DeviceId='" + _DeviceId + '\'' + ", _ClockOutLat='" + _ClockOutLat + '\'' + ", _ClockOutLang='" + _ClockOutLang + '\'' + ", locations=" + locations + '}'; } }
UTF-8
Java
1,828
java
AssignmentRequest.java
Java
[ { "context": "bjects;\n\nimport java.util.List;\n\n/**\n * Created by Aashijit on 07/04/2019.\n */\n\npublic class AssignmentReques", "end": 96, "score": 0.9814020395278931, "start": 88, "tag": "NAME", "value": "Aashijit" } ]
null
[]
package team.exp.solaretrace.RequestObjects; import java.util.List; /** * Created by Aashijit on 07/04/2019. */ public class AssignmentRequest { private String _ClockInId; private String _ClockOut; private String _DeviceId; private String _ClockOutLat; private String _ClockOutLang; private List<LocationRequest> locations; public String get_ClockInId() { return _ClockInId; } public void set_ClockInId(String _ClockInId) { this._ClockInId = _ClockInId; } public String get_ClockOut() { return _ClockOut; } public void set_ClockOut(String _ClockOut) { this._ClockOut = _ClockOut; } public String get_DeviceId() { return _DeviceId; } public void set_DeviceId(String _DeviceId) { this._DeviceId = _DeviceId; } public String get_ClockOutLat() { return _ClockOutLat; } public void set_ClockOutLat(String _ClockOutLat) { this._ClockOutLat = _ClockOutLat; } public String get_ClockOutLang() { return _ClockOutLang; } public void set_ClockOutLang(String _ClockOutLang) { this._ClockOutLang = _ClockOutLang; } public List<LocationRequest> getLocations() { return locations; } public void setLocations(List<LocationRequest> locations) { this.locations = locations; } @Override public String toString() { return "AssignmentRequest{" + "_ClockInId='" + _ClockInId + '\'' + ", _ClockOut='" + _ClockOut + '\'' + ", _DeviceId='" + _DeviceId + '\'' + ", _ClockOutLat='" + _ClockOutLat + '\'' + ", _ClockOutLang='" + _ClockOutLang + '\'' + ", locations=" + locations + '}'; } }
1,828
0.578228
0.573851
77
22.753246
19.871115
63
false
false
0
0
0
0
0
0
0.337662
false
false
10
1bfe77210a046259d80c4a17350086b183aae51d
33,706,903,339,905
f02df56b8aebdab3d3946071fdf9f39713bac629
/wx-tools/src/test/java/org/zongf/tools/wx/utils/HttpUtilTest.java
0129eeb4c64c386b0ffa00ec28225ab4d134ad67
[]
no_license
zongf0504/zongf-tools
https://github.com/zongf0504/zongf-tools
298226e534f7f8cef9761104b3e523051a42ce39
396171e758d6c7370efd856bbec401dcc42058db
refs/heads/master
2022-06-22T05:26:15.582000
2020-07-18T02:24:22
2020-07-18T02:24:22
227,114,267
0
0
null
false
2022-06-17T03:13:12
2019-12-10T12:23:36
2020-07-18T05:50:24
2022-06-17T03:13:12
117
0
0
8
Java
false
false
package org.zongf.tools.wx.utils; import com.alibaba.fastjson.JSONObject; import org.junit.Test; import org.zongf.tools.wx.utils.entity.Student; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author zongf * @date 2020-03-27 */ public class HttpUtilTest { @Test public void getToken(){ String url = "https://api.weixin.qq.com/cgi-bin/token"; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("grant_type", "client_credential"); paramMap.put("appid", "wx1587b789e22236dd"); paramMap.put("secret", "62b6e13395e0833aa27ee93e7391e817"); String content = HttpUtil.doGet(url, paramMap); System.out.println(content); // 31_QVNBcfPuAp1GTVXHOnSY9q3Gu4joGbGpQHnCF6MhYFPLzeR4-XhmhksGAfOxcOp4hxqz2UoA6rlP2gPMXUoUGvYUVqA5Q4hUvvGieUMi3C9ztcNCqXYERv7-zplPsNXSx-XmqUOf9LfoQH9KDWNaAIAWPG } String token = "31_QVNBcfPuAp1GTVXHOnSY9q3Gu4joGbGpQHnCF6MhYFPLzeR4-XhmhksGAfOxcOp4hxqz2UoA6rlP2gPMXUoUGvYUVqA5Q4hUvvGieUMi3C9ztcNCqXYERv7-zplPsNXSx-XmqUOf9LfoQH9KDWNaAIAWPG"; @Test public void createCollection(){ String cloudId = "zongf-prod"; String url = "https://api.weixin.qq.com/tcb/databasecollectionadd?access_token=" + token; String collectionName = "student"; String jsonBody = "{\"env\":\"" + cloudId + "\", \"collection_name\":\"" + collectionName + "\"}"; String result = HttpUtil.doPost(url, jsonBody, null, null, null, null, null, null); System.out.println("result:" + result); } @Test public void addData(){ String url = "https://api.weixin.qq.com/tcb/databaseadd?access_token=" + token; String collectionName = "student"; String cloudId = "zongf-prod"; List<Student> stuList = new ArrayList<>(); for (int i = 0; i < 10; i++) { stuList.add(new Student(i, "stu_" + i, "aa_" + i)); } StringBuffer querySb = new StringBuffer(); querySb.append("db.collection(\\\"").append(collectionName).append("\\\")") .append(".add(\\\"").append(JSONObject.toJSONString(stuList)).append("\\\")"); String jsonBody = "{\"env\":\"" + cloudId + "\", \"query\":\"{" + querySb.toString() + "}\"}"; System.out.println(jsonBody); String result = HttpUtil.doPost(url, jsonBody, null, null, null, null, null, null); System.out.println("result:" + result); } }
UTF-8
Java
2,489
java
HttpUtilTest.java
Java
[ { "context": "a.util.List;\nimport java.util.Map;\n\n/**\n * @author zongf\n * @date 2020-03-27\n */\npublic class HttpUtilTest", "end": 267, "score": 0.9997007846832275, "start": 262, "tag": "USERNAME", "value": "zongf" }, { "context": "87b789e22236dd\");\n paramMap.put(\"sec...
null
[]
package org.zongf.tools.wx.utils; import com.alibaba.fastjson.JSONObject; import org.junit.Test; import org.zongf.tools.wx.utils.entity.Student; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author zongf * @date 2020-03-27 */ public class HttpUtilTest { @Test public void getToken(){ String url = "https://api.weixin.qq.com/cgi-bin/token"; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("grant_type", "client_credential"); paramMap.put("appid", "wx1587b789e22236dd"); paramMap.put("secret", "62b6e13395e0833aa27ee93e7391e817"); String content = HttpUtil.doGet(url, paramMap); System.out.println(content); // <KEY> } String token = "<KEY>"; @Test public void createCollection(){ String cloudId = "zongf-prod"; String url = "https://api.weixin.qq.com/tcb/databasecollectionadd?access_token=" + token; String collectionName = "student"; String jsonBody = "{\"env\":\"" + cloudId + "\", \"collection_name\":\"" + collectionName + "\"}"; String result = HttpUtil.doPost(url, jsonBody, null, null, null, null, null, null); System.out.println("result:" + result); } @Test public void addData(){ String url = "https://api.weixin.qq.com/tcb/databaseadd?access_token=" + token; String collectionName = "student"; String cloudId = "zongf-prod"; List<Student> stuList = new ArrayList<>(); for (int i = 0; i < 10; i++) { stuList.add(new Student(i, "stu_" + i, "aa_" + i)); } StringBuffer querySb = new StringBuffer(); querySb.append("db.collection(\\\"").append(collectionName).append("\\\")") .append(".add(\\\"").append(JSONObject.toJSONString(stuList)).append("\\\")"); String jsonBody = "{\"env\":\"" + cloudId + "\", \"query\":\"{" + querySb.toString() + "}\"}"; System.out.println(jsonBody); String result = HttpUtil.doPost(url, jsonBody, null, null, null, null, null, null); System.out.println("result:" + result); } }
2,185
0.647248
0.613499
70
34.557144
38.54631
179
false
false
0
0
0
0
70
0.056247
0.828571
false
false
10
e4ff741fd298b62e860231767138a75cad79e477
2,250,562,895,576
ce17c491aad33d67c4be98ade208caf5d12d3738
/jdi-light-material-ui-tests/src/test/java/io/github/epam/material/tests/displaydata/MUIListTests.java
f565ec638102cf160e693f49c00276868a87fd4b
[ "MIT" ]
permissive
jdi-testing/jdi-light
https://github.com/jdi-testing/jdi-light
2b1a0026b0bb87d93c828c206ee7d4dd8cf86878
cfe696c8288fea9254e31bf672a027d00a28a97c
refs/heads/master
2023-08-31T18:12:25.357000
2023-08-25T04:48:39
2023-08-25T04:48:39
127,065,400
117
63
MIT
false
2023-09-14T20:04:59
2018-03-28T01:20:16
2023-09-12T11:07:50
2023-09-14T20:04:58
167,134
101
48
274
Java
false
false
package io.github.epam.material.tests.displaydata; import com.epam.jdi.light.material.elements.displaydata.Icon; import com.epam.jdi.light.material.elements.inputs.Checkbox; import com.epam.jdi.light.material.elements.inputs.Switch; import com.epam.jdi.light.ui.html.elements.common.Text; import io.github.com.custom.elements.CustomSiteListItem; import io.github.epam.TestsInit; import io.github.epam.enums.Colors; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static io.github.com.StaticSite.listPage; import static io.github.com.pages.displaydata.MUIListPage.simpleList; import static io.github.com.pages.displaydata.MUIListPage.iconWithTextList; import static io.github.com.pages.displaydata.MUIListPage.simpleListLastClickInfo; import static io.github.com.pages.displaydata.MUIListPage.checkboxList; import static io.github.com.pages.displaydata.MUIListPage.avatarWithTextList; import static io.github.com.pages.displaydata.MUIListPage.avatarWithTextAndIconList; import static io.github.com.pages.displaydata.MUIListPage.listWithSwitch; import static io.github.com.pages.displaydata.MUIListPage.pinnedSubheaderList; import static io.github.com.pages.displaydata.MUIListPage.selectedListUpperHalf; import static io.github.com.pages.displaydata.MUIListPage.secondaryTextCheckbox; import static io.github.com.pages.displaydata.MUIListPage.selectedListLowerHalf; import static java.lang.String.format; import static org.hamcrest.Matchers.containsString; public class MUIListTests extends TestsInit { @BeforeClass public void setup() { listPage.open(); listPage.checkOpened(); } @Test public void simpleListTests() { simpleList.show(); simpleList.is().visible().and().size(2); simpleList.item(0).has().text("List item 1"); simpleList.item("List item 2").is().visible(); simpleList.items().get(1).click(); String clickedOn = simpleList.items().get(1).getText(); simpleListLastClickInfo.has().text(format("You clicked on: %s", clickedOn)); } @Test public void iconWithTextTests() { iconWithTextList.is().notEmpty(); CustomSiteListItem item = iconWithTextList.items(CustomSiteListItem.class).get(0); Icon icon = item.icon(); icon.has().css("color", Colors.GREY_600_TRANSPARENT.rgba()); } @Test public void avatarWithTextTests() { avatarWithTextList.show(); CustomSiteListItem item = avatarWithTextList.items(CustomSiteListItem.class).get(0); item.avatar().is().visible(); item.asText().has().text("Single-line item"); secondaryTextCheckbox.check(); item.asText().has().text(containsString("Secondary text")); } @Test public void avatarWithTextAndIconTests() { avatarWithTextAndIconList.show(); avatarWithTextAndIconList.has().size(3); CustomSiteListItem item = avatarWithTextAndIconList.item(1); item.asText().has().text("Single-line item"); item.secondaryAction().is().visible(); item.secondaryAction().click(); } @Test public void selectedListTests() { selectedListUpperHalf.show(); CustomSiteListItem upperItem = selectedListUpperHalf.item("Inbox").with(CustomSiteListItem.class); CustomSiteListItem lowerItem = selectedListLowerHalf.item("Spam").with(CustomSiteListItem.class); upperItem.click(); upperItem.is().selected(); lowerItem.is().notSelected(); lowerItem.click(); lowerItem.is().selected(); upperItem.is().notSelected(); } @Test public void checkboxListTests() { checkboxList.show(); checkboxList.has().size(4); //first option CustomSiteListItem item = checkboxList.items(CustomSiteListItem.class).get(0); Checkbox checkbox = item.checkbox(); checkbox.is().checked(); checkbox.uncheck(); checkbox.is().unchecked(); //second option CustomSiteListItem item2 = checkboxList.item("Line item 2").with(CustomSiteListItem.class); Checkbox checkbox2 = item2.checkbox(); checkbox2.is().unchecked(); checkbox2.check(); checkbox2.is().checked(); //third option CustomSiteListItem item3 = checkboxList.item(2).with(CustomSiteListItem.class); Checkbox checkbox3 = new Checkbox().setCore(Checkbox.class, item3.find(".MuiCheckbox-root").base()); checkbox3.is().unchecked(); checkbox3.check(); checkbox3.is().checked(); } @Test public void listWithSwitchTests() { listWithSwitch.show(); listWithSwitch.has().headers(); CustomSiteListItem item = listWithSwitch.item(0).with(CustomSiteListItem.class); Switch el = new Switch().setCore(Switch.class, item.secondaryAction().find(".MuiSwitch-root").base()); el.is().enabled(); el.is().checked(); el.uncheck(); el.is().unchecked(); } @Test public void pinnedSubheaderTests() { pinnedSubheaderList.show(); pinnedSubheaderList.has().headers(); Text header = pinnedSubheaderList.headers().get(0); header.has().text("I'm sticky 0"); } }
UTF-8
Java
5,269
java
MUIListTests.java
Java
[]
null
[]
package io.github.epam.material.tests.displaydata; import com.epam.jdi.light.material.elements.displaydata.Icon; import com.epam.jdi.light.material.elements.inputs.Checkbox; import com.epam.jdi.light.material.elements.inputs.Switch; import com.epam.jdi.light.ui.html.elements.common.Text; import io.github.com.custom.elements.CustomSiteListItem; import io.github.epam.TestsInit; import io.github.epam.enums.Colors; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static io.github.com.StaticSite.listPage; import static io.github.com.pages.displaydata.MUIListPage.simpleList; import static io.github.com.pages.displaydata.MUIListPage.iconWithTextList; import static io.github.com.pages.displaydata.MUIListPage.simpleListLastClickInfo; import static io.github.com.pages.displaydata.MUIListPage.checkboxList; import static io.github.com.pages.displaydata.MUIListPage.avatarWithTextList; import static io.github.com.pages.displaydata.MUIListPage.avatarWithTextAndIconList; import static io.github.com.pages.displaydata.MUIListPage.listWithSwitch; import static io.github.com.pages.displaydata.MUIListPage.pinnedSubheaderList; import static io.github.com.pages.displaydata.MUIListPage.selectedListUpperHalf; import static io.github.com.pages.displaydata.MUIListPage.secondaryTextCheckbox; import static io.github.com.pages.displaydata.MUIListPage.selectedListLowerHalf; import static java.lang.String.format; import static org.hamcrest.Matchers.containsString; public class MUIListTests extends TestsInit { @BeforeClass public void setup() { listPage.open(); listPage.checkOpened(); } @Test public void simpleListTests() { simpleList.show(); simpleList.is().visible().and().size(2); simpleList.item(0).has().text("List item 1"); simpleList.item("List item 2").is().visible(); simpleList.items().get(1).click(); String clickedOn = simpleList.items().get(1).getText(); simpleListLastClickInfo.has().text(format("You clicked on: %s", clickedOn)); } @Test public void iconWithTextTests() { iconWithTextList.is().notEmpty(); CustomSiteListItem item = iconWithTextList.items(CustomSiteListItem.class).get(0); Icon icon = item.icon(); icon.has().css("color", Colors.GREY_600_TRANSPARENT.rgba()); } @Test public void avatarWithTextTests() { avatarWithTextList.show(); CustomSiteListItem item = avatarWithTextList.items(CustomSiteListItem.class).get(0); item.avatar().is().visible(); item.asText().has().text("Single-line item"); secondaryTextCheckbox.check(); item.asText().has().text(containsString("Secondary text")); } @Test public void avatarWithTextAndIconTests() { avatarWithTextAndIconList.show(); avatarWithTextAndIconList.has().size(3); CustomSiteListItem item = avatarWithTextAndIconList.item(1); item.asText().has().text("Single-line item"); item.secondaryAction().is().visible(); item.secondaryAction().click(); } @Test public void selectedListTests() { selectedListUpperHalf.show(); CustomSiteListItem upperItem = selectedListUpperHalf.item("Inbox").with(CustomSiteListItem.class); CustomSiteListItem lowerItem = selectedListLowerHalf.item("Spam").with(CustomSiteListItem.class); upperItem.click(); upperItem.is().selected(); lowerItem.is().notSelected(); lowerItem.click(); lowerItem.is().selected(); upperItem.is().notSelected(); } @Test public void checkboxListTests() { checkboxList.show(); checkboxList.has().size(4); //first option CustomSiteListItem item = checkboxList.items(CustomSiteListItem.class).get(0); Checkbox checkbox = item.checkbox(); checkbox.is().checked(); checkbox.uncheck(); checkbox.is().unchecked(); //second option CustomSiteListItem item2 = checkboxList.item("Line item 2").with(CustomSiteListItem.class); Checkbox checkbox2 = item2.checkbox(); checkbox2.is().unchecked(); checkbox2.check(); checkbox2.is().checked(); //third option CustomSiteListItem item3 = checkboxList.item(2).with(CustomSiteListItem.class); Checkbox checkbox3 = new Checkbox().setCore(Checkbox.class, item3.find(".MuiCheckbox-root").base()); checkbox3.is().unchecked(); checkbox3.check(); checkbox3.is().checked(); } @Test public void listWithSwitchTests() { listWithSwitch.show(); listWithSwitch.has().headers(); CustomSiteListItem item = listWithSwitch.item(0).with(CustomSiteListItem.class); Switch el = new Switch().setCore(Switch.class, item.secondaryAction().find(".MuiSwitch-root").base()); el.is().enabled(); el.is().checked(); el.uncheck(); el.is().unchecked(); } @Test public void pinnedSubheaderTests() { pinnedSubheaderList.show(); pinnedSubheaderList.has().headers(); Text header = pinnedSubheaderList.headers().get(0); header.has().text("I'm sticky 0"); } }
5,269
0.691403
0.685329
142
36.105633
28.684959
110
false
false
0
0
0
0
0
0
0.640845
false
false
10
806e3bcdc34de0dbf20349a15790254d055f7a93
32,452,772,891,901
6b47950fe7def3838e86aaa4c82bb9fdba2507af
/HeadFirst/MyMessenger/app/src/main/java/ahmaabdo/mymessenger/CreateMessageActivity.java
2eeba4b1788e982ab8a82c6aa74b4ae9975065f5
[]
no_license
ahmaabdo/Samples
https://github.com/ahmaabdo/Samples
d6d6188aacddd307b07ab5458081cadcdb6d13a6
389da193e3983558a0037235e534dfc9b8cbc76b
refs/heads/master
2021-05-09T03:54:43.734000
2018-03-28T06:23:13
2018-03-28T06:23:13
119,255,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ahmaabdo.mymessenger; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; public class CreateMessageActivity extends AppCompatActivity { private EditText mEditTextMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_message); mEditTextMessage = findViewById(R.id.edit_text_msg); } //Call onSendMessage when Send button clicked public void onSendMessage2(View view) { //Create a new Intent with an extra name called myMsg Intent i = new Intent(this, ReceiveMessageActivity.class); //Get the text from edit text field and convert it to String //And pass it with the intent i.putExtra(ReceiveMessageActivity.EXTRA_MESSAGE, mEditTextMessage.getText().toString()); //Start the intent startActivity(i); } //Call onSendMessage when Send button clicked //This method will create a chooser with a custom title to send sms. public void onSendMessage(View view) { //Create a new Intent with Action Send Intent i = new Intent(Intent.ACTION_SEND); //set the MIME type to text plain and passes the edit text field i.setType("text/plain") .putExtra(Intent.EXTRA_TEXT, mEditTextMessage.getText().toString()); //Display a chooser dialog with a custom title -> Choose by your self.. Intent chosenIntent = Intent.createChooser(i, "Choose by your self.."); //Start the chosenIntent startActivity(chosenIntent); } }
UTF-8
Java
1,719
java
CreateMessageActivity.java
Java
[ { "context": "package ahmaabdo.mymessenger;\n\nimport android.content.Intent;\n", "end": 12, "score": 0.7009190320968628, "start": 8, "tag": "USERNAME", "value": "ahma" } ]
null
[]
package ahmaabdo.mymessenger; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; public class CreateMessageActivity extends AppCompatActivity { private EditText mEditTextMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_message); mEditTextMessage = findViewById(R.id.edit_text_msg); } //Call onSendMessage when Send button clicked public void onSendMessage2(View view) { //Create a new Intent with an extra name called myMsg Intent i = new Intent(this, ReceiveMessageActivity.class); //Get the text from edit text field and convert it to String //And pass it with the intent i.putExtra(ReceiveMessageActivity.EXTRA_MESSAGE, mEditTextMessage.getText().toString()); //Start the intent startActivity(i); } //Call onSendMessage when Send button clicked //This method will create a chooser with a custom title to send sms. public void onSendMessage(View view) { //Create a new Intent with Action Send Intent i = new Intent(Intent.ACTION_SEND); //set the MIME type to text plain and passes the edit text field i.setType("text/plain") .putExtra(Intent.EXTRA_TEXT, mEditTextMessage.getText().toString()); //Display a chooser dialog with a custom title -> Choose by your self.. Intent chosenIntent = Intent.createChooser(i, "Choose by your self.."); //Start the chosenIntent startActivity(chosenIntent); } }
1,719
0.700989
0.699825
43
38.976746
26.015638
96
false
false
0
0
0
0
0
0
0.488372
false
false
10
95ccc0b664fb09c67cfa6e0b332cce20bb4898a0
28,492,813,063,568
4ffa9e8454ca4c12b0b8e960184768d5be2d7e6b
/src/main/java/com/hackovation/hybo/scheduled/BasedOnThresholdRebalcing.java
be77156077a00a11ca0019888ba45e8ca8fb2f59
[]
no_license
AppSecAI-TEST/hybo
https://github.com/AppSecAI-TEST/hybo
19c1403dd0035909eb7f94fc221beeef1829db51
cdcd65b755320c7b3ed0c28d6e9b6c3fcfbea7ec
refs/heads/master
2021-01-16T15:31:23.164000
2017-08-11T04:54:07
2017-08-11T04:54:07
100,002,332
0
0
null
true
2017-08-11T07:01:23
2017-08-11T07:01:23
2017-07-11T10:06:14
2017-08-11T04:54:10
46,254
0
0
0
null
null
null
package com.hackovation.hybo.scheduled; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import java.util.Set; import org.algo.finance.data.GoogleSymbol; import org.algo.finance.data.GoogleSymbol.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.hack17.hybo.domain.Allocation; import com.hack17.hybo.domain.InvestorProfile; import com.hack17.hybo.domain.MarketStatus; import com.hack17.hybo.domain.Portfolio; import com.hack17.hybo.domain.RiskTolerance; import com.hack17.hybo.repository.PortfolioRepository; import com.hack17.hybo.service.DBLoggerService; import com.hackovation.hybo.AllocationType; import com.hackovation.hybo.Util.EtfIndexMap; import com.hackovation.hybo.Util.PathsAsPerAssetClass; import com.hackovation.hybo.rebalance.Rebalance; @Component public class BasedOnThresholdRebalcing implements Rebalance{ @Autowired PortfolioRepository portfolioRepository; @Autowired DBLoggerService dbLoggerService; final int threshold = 15; Map<String,String> indexToEtfMap; Map<String,String> EtfToIndexMap; final Map<Double,Double> assetClassTieredTable; { assetClassTieredTable = new HashMap<>(); assetClassTieredTable.put(2.0, 1.0); assetClassTieredTable.put(5.0, 1.5); assetClassTieredTable.put(10.0, 2.5); assetClassTieredTable.put(20.0, 5.0); assetClassTieredTable.put(40.0, 6.0); assetClassTieredTable.put(60.0, 7.0); assetClassTieredTable.put(80.0, 7.0); } @Override // @Scheduled(cron="0 0/1 * 1/1 * *") @Transactional public void rebalance() { System.out.println("Cron Running"); System.out.println("Rebalancing Started!!!"); EtfToIndexMap = EtfIndexMap.getEtfToIndexMapping(); indexToEtfMap = EtfIndexMap.getIndexToEtfMapping(); List<Portfolio> listOfPortfolios = portfolioRepository.getAllPortfolios(); System.out.println("Fetched all portfolios... "+listOfPortfolios.size()); System.out.println("Grouping Allocation based on portfolio.."); Map<Portfolio,List<Allocation>> groupWisePortfolio = groupByUserId(listOfPortfolios); Set<Entry<Portfolio,List<Allocation>>> entrySet = groupWisePortfolio.entrySet(); for(Entry<Portfolio,List<Allocation>> entry:entrySet){ Portfolio portfolio = entry.getKey(); List<Allocation> portfolioList = entry.getValue(); System.out.println("Rebalancing ... "+portfolio); rebalancePortfolio(portfolio,portfolioList); } System.out.println("Rebalancing Done !!! "); } /* * There are 2 Levels of rebalancing. * 1. Rebalancing based on Asset type (ETF,BOND) * 2. Rebalacing based on Asset class types for ETF */ public void rebalancePortfolio(Portfolio portfolio,List<Allocation> portfolioList){ HashMap<AllocationType,List<Allocation>> typeWiseAllocation = getAllocationBasedOnType(portfolioList); boolean triggerRebalancing = true; List<Allocation> eqAllocationList = typeWiseAllocation.get(AllocationType.EQ); List<Allocation> bondAllocationList = typeWiseAllocation.get(AllocationType.BOND); if(typeWiseAllocation.size()>1){ int P = getValueOfP(portfolio, typeWiseAllocation); double initialEQSum = getTotalValue(eqAllocationList); } rebalanceEquity(portfolio,eqAllocationList,bondAllocationList); } public HashMap<AllocationType, List<Allocation>> getAllocationBasedOnType(List<Allocation> portfolioList){ HashMap<AllocationType,List<Allocation>> map = new HashMap<>(); List<Allocation> EQList = portfolioList.stream().filter(a->a.getType().equals(AllocationType.EQ.name())).collect(Collectors.toList()); List<Allocation> BONDList = portfolioList.stream().filter(a->a.getType().equals(AllocationType.BOND.name())).collect(Collectors.toList()); map.put(AllocationType.EQ, EQList); map.put(AllocationType.BOND, BONDList); return map; } public int getValueOfP(Portfolio portfolio,HashMap<AllocationType,List<Allocation>> typeWiseAllocation){ int P = 5; InvestorProfile profile = portfolio.getInvestorProfile(); if(profile.getRiskTolerance().equals(RiskTolerance.HIGH)||profile.getRiskTolerance().equals(RiskTolerance.VERY_HIGH)) P=10; else{ // if volatility is higer then we have to keep small range double eqCost = typeWiseAllocation.get(AllocationType.EQ).stream().mapToDouble(d->d.getCostPrice()).sum(); double bondCost = typeWiseAllocation.get(AllocationType.BOND).stream().mapToDouble(d->d.getCostPrice()).sum(); double perc = eqCost / (eqCost+bondCost); if(perc>30){ P=3; } } return P; } public double getTotalValue(List<Allocation> allocationList){ double sum = 0; Iterator<Allocation> iter = allocationList.iterator(); while(iter.hasNext()){ Allocation allocation = iter.next(); sum+=allocation.getCostPrice(); } return sum; } public void rebalanceEquity(Portfolio portfolio, List<Allocation> equityAllocationList,List<Allocation> bondAllocationList){ MarketStatus marketStatus = (MarketStatus)portfolioRepository.getEntity(1, MarketStatus.class); InvestorProfile profile = portfolio.getInvestorProfile(); RiskTolerance riskTolerance = profile.getRiskTolerance(); if(riskTolerance.equals(RiskTolerance.VERY_HIGH) && marketStatus.isGoingUp){ System.out.println(" Not rebalancing because RiskToleranc is High and Market is going up."); return; } if(riskTolerance.equals(RiskTolerance.MEDIUM) && marketStatus.isFluctuating){ System.out.println(" Tiered Rebalncing because RiskToleranc is Moderate/Mediun and Market is fluctuating."); tieredBasedRebalancing(portfolio, equityAllocationList); return; } if(riskTolerance.equals(RiskTolerance.HIGH) && (marketStatus.isGoingDown || marketStatus.isGoingUp)){ System.out.println(" Formula Based Rebalncing because RiskToleranc is High and Market is not fluctuating."); formulaBasedRebalancing(portfolio, equityAllocationList,bondAllocationList); } } private void tieredBasedRebalancing(Portfolio portfolio, List<Allocation> equityAllocationList){ HashMap<String,Double> existPercMap = new HashMap<>(); HashMap<String, Double> newPercMap = new HashMap<>(); HashMap<String, Double> newPricesPerETF = new HashMap<>(); double totalValue = 0; for(Allocation existingAllocation:equityAllocationList){ int noOfETF = existingAllocation.getQuantity(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); GoogleSymbol gs = new GoogleSymbol(existingAllocation.getFund().getTicker()); List<Data> dataList = gs.getHistoricalPrices(); Data data = dataList.get(0); /* double perIndexCost = data.getPrice(); ReadFile readFile = new ReadFile(); */ double latestPrice = data.getPrice(); double cost = latestPrice*existingAllocation.getQuantity(); totalValue +=cost; newPercMap.put(existingAllocation.getFund().getTicker(), cost); newPricesPerETF.put(existingAllocation.getFund().getTicker(), latestPrice); existPercMap.put(existingAllocation.getFund().getTicker(), existingAllocation.getPercentage()); } newPercMap = updatePercentagesAsPerLatestCost(newPercMap, totalValue); List<Allocation> newAllocationList = new ArrayList<>(); Date currentDate = new Date(); double newInvestment = 0.0; for(Allocation allocation:equityAllocationList){ Allocation newAllocation = copyAllocationInNewObject(allocation, currentDate); String ticker = allocation.getFund().getTicker(); double existingPerc = existPercMap.get(ticker); double newPerc = newPercMap.get(ticker); double adjustment = checkEligibilityForAssetClassRebalanncing(existingPerc,newPerc); if(adjustment == 0){ newAllocationList.add(newAllocation); allocation.setIsActive("N"); newInvestment+=newAllocation.getInvestment(); } else if (adjustment < 0 ){ double newPer =existingPerc-Math.abs(adjustment); double averagePerc = (existingPerc+newPer)/2; double cost = (totalValue*averagePerc)/100; double etfTodayPrice = newPricesPerETF.get(ticker); int quantity = new Double(cost/etfTodayPrice).intValue(); cost = quantity*etfTodayPrice; newAllocation.setCostPrice(cost); newAllocation.setQuantity(quantity); allocation.setIsActive("N"); newInvestment+=newAllocation.getCostPrice(); newAllocationList.add(newAllocation); log(allocation, newAllocation, currentDate); } else if (adjustment > 0 ){ double newPer =existingPerc+Math.abs(adjustment); double averagePerc = (existingPerc+newPer)/2; double cost = (totalValue*averagePerc)/100; double etfTodayPrice = newPricesPerETF.get(ticker); int quantity = new Double(cost/etfTodayPrice).intValue(); cost = quantity*etfTodayPrice; newAllocation.setCostPrice(cost); newAllocation.setQuantity(quantity); allocation.setIsActive("N"); newInvestment+=newAllocation.getCostPrice(); newAllocationList.add(newAllocation); log(allocation, newAllocation, currentDate); } } for(Allocation allocation:newAllocationList){ allocation.setInvestment(newInvestment); allocation.setIsActive("Y"); } for(Allocation allocation:equityAllocationList) allocation.setIsActive("N"); newAllocationList.addAll(equityAllocationList); portfolio.setAllocations(newAllocationList); portfolioRepository.persist(portfolio); } public void formulaBasedRebalancing(Portfolio portfolio, List<Allocation> equityAllocationList,List<Allocation> bondAllocationList){ double totalInvestment = 0.0; RiskTolerance riskTolerance = portfolio.getInvestorProfile().getRiskTolerance(); if(equityAllocationList != null && equityAllocationList.size()>0) totalInvestment+= equityAllocationList.get(0).getInvestment(); if(bondAllocationList != null && bondAllocationList.size()>0) totalInvestment+= bondAllocationList.get(0).getInvestment(); final int m = 2; final int floor = getFloorValue(riskTolerance, totalInvestment); double currentValueOfPortfolio = 0; HashMap<String, Double> newPricesPerETF = new HashMap<>(); HashMap<String,Double> existPercMap = new HashMap<>(); for(Allocation existingAllocation:equityAllocationList){ int noOfETF = existingAllocation.getQuantity(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); GoogleSymbol gs = new GoogleSymbol(existingAllocation.getFund().getTicker()); List<Data> dataList = gs.getHistoricalPrices(); Data data = dataList.get(0); double latestPrice = data.getPrice(); double cost = latestPrice*existingAllocation.getQuantity(); currentValueOfPortfolio +=cost; newPricesPerETF.put(existingAllocation.getFund().getTicker(), latestPrice); existPercMap.put(existingAllocation.getFund().getTicker(), existingAllocation.getPercentage()); } double equityPortion = m*(currentValueOfPortfolio-floor); Date currentDate = new Date(); List<Allocation> newAllocationList = new ArrayList<>(); double investment = 0; for(Allocation allocation : equityAllocationList){ String ticker = allocation.getFund().getTicker(); Allocation newAllocation = copyAllocationInNewObject(allocation, currentDate); double perc = existPercMap.get(ticker); double etfTodayPrice = newPricesPerETF.get(ticker); double cost = equityPortion*perc; int number = Double.valueOf(cost/etfTodayPrice).intValue(); cost = number*etfTodayPrice; investment += cost; newAllocation.setCostPrice(cost); newAllocation.setPercentage(perc); newAllocation.setQuantity(number); newAllocation.setIsActive("Y"); log(allocation, newAllocation, currentDate); } for(Allocation allocation:equityAllocationList) allocation.setIsActive("N"); equityAllocationList.addAll(newAllocationList); equityAllocationList.addAll(bondAllocationList); portfolioRepository.persist(equityAllocationList); } private int getFloorValue(RiskTolerance riskTolerance,double totalInvestment){ int floorValue = 0; int perc = 0; if(riskTolerance.equals(RiskTolerance.HIGH) || riskTolerance.equals(RiskTolerance.VERY_HIGH)) perc = 25; if(riskTolerance.equals(RiskTolerance.LOW) || riskTolerance.equals(RiskTolerance.VERY_LOW)) perc = 75; if(riskTolerance.equals(RiskTolerance.MEDIUM)) perc = 50; floorValue = Double.valueOf((totalInvestment*perc)/100).intValue(); return floorValue; } private Allocation copyAllocationInNewObject(Allocation allocation,Date currentDate){ Allocation newAllocation = new Allocation(); newAllocation.setFund(allocation.getFund()); newAllocation.setTransactionDate(currentDate); newAllocation.setExpenseRatio(allocation.getExpenseRatio()); newAllocation.setCostPrice(allocation.getCostPrice()); newAllocation.setInvestment(allocation.getInvestment()); newAllocation.setPercentage(allocation.getPercentage()); newAllocation.setQuantity(allocation.getQuantity()); newAllocation.setType(allocation.getType()); return newAllocation; } public HashMap<String,Double> updatePercentagesAsPerLatestCost(HashMap<String,Double> dataMap,double totalCost){ HashMap<String,Double> resultMap = new HashMap<>(); for(String key:dataMap.keySet()){ double cost = dataMap.get(key); resultMap.put(key,(cost/totalCost)*100); } return resultMap; } public double checkEligibilityForAssetClassRebalanncing(double existingPerc,double newPerc){ boolean rebalanceAssetClass = true; double diff = 0; double range = 0; for(Double key:assetClassTieredTable.keySet()){ if(existingPerc>key)continue; if(existingPerc<=key) range = assetClassTieredTable.get(key); } diff = newPerc-existingPerc; if(Math.abs(diff)<=newPerc)rebalanceAssetClass = true; else rebalanceAssetClass = false; if(!rebalanceAssetClass)diff = 0; return diff; } public void log(Allocation existingAllocation,Allocation newAllocation,Date sellDate){ int oldQuantity = existingAllocation.getQuantity(); int newQuantity = newAllocation.getQuantity(); if(oldQuantity>newQuantity){//SELL dbLoggerService.logTransaction(existingAllocation, newAllocation.getCostPrice(), sellDate, oldQuantity-newQuantity); }else if(newQuantity>oldQuantity){//BUY dbLoggerService.logTransaction(existingAllocation, newAllocation.getCostPrice(), sellDate, newQuantity-oldQuantity); } } /* public void rebalancePortfolio(Portfolio portfolio,List<Allocation> actualAllocationList){ try{ boolean rebalancePortfolio = false; Map<String,Integer> todaysWeight = getETFWiseWeight(actualAllocationList); for(Allocation allocation:actualAllocationList){ double actualWeight = allocation.getPercentage(); int today = todaysWeight.get(allocation.getFund().getTicker()); double diff = Math.abs(today-actualWeight); double perc = (diff/actualWeight)*100; if(perc>=threshold){ rebalancePortfolio = true; break; } } if(rebalancePortfolio){ double totalInvestmentAsOfToday = 0; for(Allocation existingPortfolio:actualAllocationList){ int noOfETF = existingPortfolio.getQuantity(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); ReadFile readFile = new ReadFile(); totalInvestmentAsOfToday += noOfETF*readFile.getETFPriceForDate(paths.get(existingPortfolio.getFund().getTicker()), existingPortfolio.getFund().getTicker(), date); } List<Allocation> newAllocationList = new ArrayList<>(); for(Allocation existingAllocation:actualAllocationList){ int weight = todaysWeight.get(existingAllocation.getFund().getTicker()); double etfWiseInvestment = (totalInvestmentAsOfToday*weight)/100; Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); ReadFile readFile = new ReadFile(); double costPerETF = readFile.getETFPriceForDate(paths.get(existingAllocation.getFund().getTicker()), existingAllocation.getFund().getTicker(), date); int noOfEtf = Double.valueOf(etfWiseInvestment/costPerETF).intValue(); // double cost = noOfEtf*costPerETF; Allocation allocation = new Allocation(); allocation.setCostPrice(costPerETF); allocation.setInvestment(totalInvestmentAsOfToday); allocation.setInvestment(totalInvestmentAsOfToday); allocation.setPercentage(weight); newAllocationList.add(allocation); } portfolio.setAllocations(newAllocationList); portfolioRepository.merge(portfolio); } }catch(Exception e){ e.printStackTrace(); } } private Map<String,Integer> getETFWiseWeight(List<Allocation> allocationList) throws Exception{ Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); ReadFile readFile = new ReadFile(); Map<String, Integer> etfWiseWeight = new HashMap<>(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Map<String,Double> etfWisePrice = new HashMap<>(); double totalPrice = 0; for(Allocation allocation:allocationList){ String filePath = paths.get(EtfToIndexMap.get(allocation.getFund().getTicker())); double price = 0; price = readFile.getETFPriceForDate(filePath,allocation.getFund().getTicker(),date); if(price==0){ throw new Exception("Data is not present for today!!"); } etfWisePrice.put(allocation.getFund().getTicker(),price); totalPrice+=price; } Set<Entry<String, Double>> entrySet = etfWisePrice.entrySet(); for(Entry<String,Double> entry:entrySet){ Double weight = entry.getValue()/totalPrice; etfWiseWeight.put(entry.getKey(), weight.intValue()); } return etfWiseWeight; } */ }
UTF-8
Java
18,924
java
BasedOnThresholdRebalcing.java
Java
[]
null
[]
package com.hackovation.hybo.scheduled; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import java.util.Set; import org.algo.finance.data.GoogleSymbol; import org.algo.finance.data.GoogleSymbol.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.hack17.hybo.domain.Allocation; import com.hack17.hybo.domain.InvestorProfile; import com.hack17.hybo.domain.MarketStatus; import com.hack17.hybo.domain.Portfolio; import com.hack17.hybo.domain.RiskTolerance; import com.hack17.hybo.repository.PortfolioRepository; import com.hack17.hybo.service.DBLoggerService; import com.hackovation.hybo.AllocationType; import com.hackovation.hybo.Util.EtfIndexMap; import com.hackovation.hybo.Util.PathsAsPerAssetClass; import com.hackovation.hybo.rebalance.Rebalance; @Component public class BasedOnThresholdRebalcing implements Rebalance{ @Autowired PortfolioRepository portfolioRepository; @Autowired DBLoggerService dbLoggerService; final int threshold = 15; Map<String,String> indexToEtfMap; Map<String,String> EtfToIndexMap; final Map<Double,Double> assetClassTieredTable; { assetClassTieredTable = new HashMap<>(); assetClassTieredTable.put(2.0, 1.0); assetClassTieredTable.put(5.0, 1.5); assetClassTieredTable.put(10.0, 2.5); assetClassTieredTable.put(20.0, 5.0); assetClassTieredTable.put(40.0, 6.0); assetClassTieredTable.put(60.0, 7.0); assetClassTieredTable.put(80.0, 7.0); } @Override // @Scheduled(cron="0 0/1 * 1/1 * *") @Transactional public void rebalance() { System.out.println("Cron Running"); System.out.println("Rebalancing Started!!!"); EtfToIndexMap = EtfIndexMap.getEtfToIndexMapping(); indexToEtfMap = EtfIndexMap.getIndexToEtfMapping(); List<Portfolio> listOfPortfolios = portfolioRepository.getAllPortfolios(); System.out.println("Fetched all portfolios... "+listOfPortfolios.size()); System.out.println("Grouping Allocation based on portfolio.."); Map<Portfolio,List<Allocation>> groupWisePortfolio = groupByUserId(listOfPortfolios); Set<Entry<Portfolio,List<Allocation>>> entrySet = groupWisePortfolio.entrySet(); for(Entry<Portfolio,List<Allocation>> entry:entrySet){ Portfolio portfolio = entry.getKey(); List<Allocation> portfolioList = entry.getValue(); System.out.println("Rebalancing ... "+portfolio); rebalancePortfolio(portfolio,portfolioList); } System.out.println("Rebalancing Done !!! "); } /* * There are 2 Levels of rebalancing. * 1. Rebalancing based on Asset type (ETF,BOND) * 2. Rebalacing based on Asset class types for ETF */ public void rebalancePortfolio(Portfolio portfolio,List<Allocation> portfolioList){ HashMap<AllocationType,List<Allocation>> typeWiseAllocation = getAllocationBasedOnType(portfolioList); boolean triggerRebalancing = true; List<Allocation> eqAllocationList = typeWiseAllocation.get(AllocationType.EQ); List<Allocation> bondAllocationList = typeWiseAllocation.get(AllocationType.BOND); if(typeWiseAllocation.size()>1){ int P = getValueOfP(portfolio, typeWiseAllocation); double initialEQSum = getTotalValue(eqAllocationList); } rebalanceEquity(portfolio,eqAllocationList,bondAllocationList); } public HashMap<AllocationType, List<Allocation>> getAllocationBasedOnType(List<Allocation> portfolioList){ HashMap<AllocationType,List<Allocation>> map = new HashMap<>(); List<Allocation> EQList = portfolioList.stream().filter(a->a.getType().equals(AllocationType.EQ.name())).collect(Collectors.toList()); List<Allocation> BONDList = portfolioList.stream().filter(a->a.getType().equals(AllocationType.BOND.name())).collect(Collectors.toList()); map.put(AllocationType.EQ, EQList); map.put(AllocationType.BOND, BONDList); return map; } public int getValueOfP(Portfolio portfolio,HashMap<AllocationType,List<Allocation>> typeWiseAllocation){ int P = 5; InvestorProfile profile = portfolio.getInvestorProfile(); if(profile.getRiskTolerance().equals(RiskTolerance.HIGH)||profile.getRiskTolerance().equals(RiskTolerance.VERY_HIGH)) P=10; else{ // if volatility is higer then we have to keep small range double eqCost = typeWiseAllocation.get(AllocationType.EQ).stream().mapToDouble(d->d.getCostPrice()).sum(); double bondCost = typeWiseAllocation.get(AllocationType.BOND).stream().mapToDouble(d->d.getCostPrice()).sum(); double perc = eqCost / (eqCost+bondCost); if(perc>30){ P=3; } } return P; } public double getTotalValue(List<Allocation> allocationList){ double sum = 0; Iterator<Allocation> iter = allocationList.iterator(); while(iter.hasNext()){ Allocation allocation = iter.next(); sum+=allocation.getCostPrice(); } return sum; } public void rebalanceEquity(Portfolio portfolio, List<Allocation> equityAllocationList,List<Allocation> bondAllocationList){ MarketStatus marketStatus = (MarketStatus)portfolioRepository.getEntity(1, MarketStatus.class); InvestorProfile profile = portfolio.getInvestorProfile(); RiskTolerance riskTolerance = profile.getRiskTolerance(); if(riskTolerance.equals(RiskTolerance.VERY_HIGH) && marketStatus.isGoingUp){ System.out.println(" Not rebalancing because RiskToleranc is High and Market is going up."); return; } if(riskTolerance.equals(RiskTolerance.MEDIUM) && marketStatus.isFluctuating){ System.out.println(" Tiered Rebalncing because RiskToleranc is Moderate/Mediun and Market is fluctuating."); tieredBasedRebalancing(portfolio, equityAllocationList); return; } if(riskTolerance.equals(RiskTolerance.HIGH) && (marketStatus.isGoingDown || marketStatus.isGoingUp)){ System.out.println(" Formula Based Rebalncing because RiskToleranc is High and Market is not fluctuating."); formulaBasedRebalancing(portfolio, equityAllocationList,bondAllocationList); } } private void tieredBasedRebalancing(Portfolio portfolio, List<Allocation> equityAllocationList){ HashMap<String,Double> existPercMap = new HashMap<>(); HashMap<String, Double> newPercMap = new HashMap<>(); HashMap<String, Double> newPricesPerETF = new HashMap<>(); double totalValue = 0; for(Allocation existingAllocation:equityAllocationList){ int noOfETF = existingAllocation.getQuantity(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); GoogleSymbol gs = new GoogleSymbol(existingAllocation.getFund().getTicker()); List<Data> dataList = gs.getHistoricalPrices(); Data data = dataList.get(0); /* double perIndexCost = data.getPrice(); ReadFile readFile = new ReadFile(); */ double latestPrice = data.getPrice(); double cost = latestPrice*existingAllocation.getQuantity(); totalValue +=cost; newPercMap.put(existingAllocation.getFund().getTicker(), cost); newPricesPerETF.put(existingAllocation.getFund().getTicker(), latestPrice); existPercMap.put(existingAllocation.getFund().getTicker(), existingAllocation.getPercentage()); } newPercMap = updatePercentagesAsPerLatestCost(newPercMap, totalValue); List<Allocation> newAllocationList = new ArrayList<>(); Date currentDate = new Date(); double newInvestment = 0.0; for(Allocation allocation:equityAllocationList){ Allocation newAllocation = copyAllocationInNewObject(allocation, currentDate); String ticker = allocation.getFund().getTicker(); double existingPerc = existPercMap.get(ticker); double newPerc = newPercMap.get(ticker); double adjustment = checkEligibilityForAssetClassRebalanncing(existingPerc,newPerc); if(adjustment == 0){ newAllocationList.add(newAllocation); allocation.setIsActive("N"); newInvestment+=newAllocation.getInvestment(); } else if (adjustment < 0 ){ double newPer =existingPerc-Math.abs(adjustment); double averagePerc = (existingPerc+newPer)/2; double cost = (totalValue*averagePerc)/100; double etfTodayPrice = newPricesPerETF.get(ticker); int quantity = new Double(cost/etfTodayPrice).intValue(); cost = quantity*etfTodayPrice; newAllocation.setCostPrice(cost); newAllocation.setQuantity(quantity); allocation.setIsActive("N"); newInvestment+=newAllocation.getCostPrice(); newAllocationList.add(newAllocation); log(allocation, newAllocation, currentDate); } else if (adjustment > 0 ){ double newPer =existingPerc+Math.abs(adjustment); double averagePerc = (existingPerc+newPer)/2; double cost = (totalValue*averagePerc)/100; double etfTodayPrice = newPricesPerETF.get(ticker); int quantity = new Double(cost/etfTodayPrice).intValue(); cost = quantity*etfTodayPrice; newAllocation.setCostPrice(cost); newAllocation.setQuantity(quantity); allocation.setIsActive("N"); newInvestment+=newAllocation.getCostPrice(); newAllocationList.add(newAllocation); log(allocation, newAllocation, currentDate); } } for(Allocation allocation:newAllocationList){ allocation.setInvestment(newInvestment); allocation.setIsActive("Y"); } for(Allocation allocation:equityAllocationList) allocation.setIsActive("N"); newAllocationList.addAll(equityAllocationList); portfolio.setAllocations(newAllocationList); portfolioRepository.persist(portfolio); } public void formulaBasedRebalancing(Portfolio portfolio, List<Allocation> equityAllocationList,List<Allocation> bondAllocationList){ double totalInvestment = 0.0; RiskTolerance riskTolerance = portfolio.getInvestorProfile().getRiskTolerance(); if(equityAllocationList != null && equityAllocationList.size()>0) totalInvestment+= equityAllocationList.get(0).getInvestment(); if(bondAllocationList != null && bondAllocationList.size()>0) totalInvestment+= bondAllocationList.get(0).getInvestment(); final int m = 2; final int floor = getFloorValue(riskTolerance, totalInvestment); double currentValueOfPortfolio = 0; HashMap<String, Double> newPricesPerETF = new HashMap<>(); HashMap<String,Double> existPercMap = new HashMap<>(); for(Allocation existingAllocation:equityAllocationList){ int noOfETF = existingAllocation.getQuantity(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); GoogleSymbol gs = new GoogleSymbol(existingAllocation.getFund().getTicker()); List<Data> dataList = gs.getHistoricalPrices(); Data data = dataList.get(0); double latestPrice = data.getPrice(); double cost = latestPrice*existingAllocation.getQuantity(); currentValueOfPortfolio +=cost; newPricesPerETF.put(existingAllocation.getFund().getTicker(), latestPrice); existPercMap.put(existingAllocation.getFund().getTicker(), existingAllocation.getPercentage()); } double equityPortion = m*(currentValueOfPortfolio-floor); Date currentDate = new Date(); List<Allocation> newAllocationList = new ArrayList<>(); double investment = 0; for(Allocation allocation : equityAllocationList){ String ticker = allocation.getFund().getTicker(); Allocation newAllocation = copyAllocationInNewObject(allocation, currentDate); double perc = existPercMap.get(ticker); double etfTodayPrice = newPricesPerETF.get(ticker); double cost = equityPortion*perc; int number = Double.valueOf(cost/etfTodayPrice).intValue(); cost = number*etfTodayPrice; investment += cost; newAllocation.setCostPrice(cost); newAllocation.setPercentage(perc); newAllocation.setQuantity(number); newAllocation.setIsActive("Y"); log(allocation, newAllocation, currentDate); } for(Allocation allocation:equityAllocationList) allocation.setIsActive("N"); equityAllocationList.addAll(newAllocationList); equityAllocationList.addAll(bondAllocationList); portfolioRepository.persist(equityAllocationList); } private int getFloorValue(RiskTolerance riskTolerance,double totalInvestment){ int floorValue = 0; int perc = 0; if(riskTolerance.equals(RiskTolerance.HIGH) || riskTolerance.equals(RiskTolerance.VERY_HIGH)) perc = 25; if(riskTolerance.equals(RiskTolerance.LOW) || riskTolerance.equals(RiskTolerance.VERY_LOW)) perc = 75; if(riskTolerance.equals(RiskTolerance.MEDIUM)) perc = 50; floorValue = Double.valueOf((totalInvestment*perc)/100).intValue(); return floorValue; } private Allocation copyAllocationInNewObject(Allocation allocation,Date currentDate){ Allocation newAllocation = new Allocation(); newAllocation.setFund(allocation.getFund()); newAllocation.setTransactionDate(currentDate); newAllocation.setExpenseRatio(allocation.getExpenseRatio()); newAllocation.setCostPrice(allocation.getCostPrice()); newAllocation.setInvestment(allocation.getInvestment()); newAllocation.setPercentage(allocation.getPercentage()); newAllocation.setQuantity(allocation.getQuantity()); newAllocation.setType(allocation.getType()); return newAllocation; } public HashMap<String,Double> updatePercentagesAsPerLatestCost(HashMap<String,Double> dataMap,double totalCost){ HashMap<String,Double> resultMap = new HashMap<>(); for(String key:dataMap.keySet()){ double cost = dataMap.get(key); resultMap.put(key,(cost/totalCost)*100); } return resultMap; } public double checkEligibilityForAssetClassRebalanncing(double existingPerc,double newPerc){ boolean rebalanceAssetClass = true; double diff = 0; double range = 0; for(Double key:assetClassTieredTable.keySet()){ if(existingPerc>key)continue; if(existingPerc<=key) range = assetClassTieredTable.get(key); } diff = newPerc-existingPerc; if(Math.abs(diff)<=newPerc)rebalanceAssetClass = true; else rebalanceAssetClass = false; if(!rebalanceAssetClass)diff = 0; return diff; } public void log(Allocation existingAllocation,Allocation newAllocation,Date sellDate){ int oldQuantity = existingAllocation.getQuantity(); int newQuantity = newAllocation.getQuantity(); if(oldQuantity>newQuantity){//SELL dbLoggerService.logTransaction(existingAllocation, newAllocation.getCostPrice(), sellDate, oldQuantity-newQuantity); }else if(newQuantity>oldQuantity){//BUY dbLoggerService.logTransaction(existingAllocation, newAllocation.getCostPrice(), sellDate, newQuantity-oldQuantity); } } /* public void rebalancePortfolio(Portfolio portfolio,List<Allocation> actualAllocationList){ try{ boolean rebalancePortfolio = false; Map<String,Integer> todaysWeight = getETFWiseWeight(actualAllocationList); for(Allocation allocation:actualAllocationList){ double actualWeight = allocation.getPercentage(); int today = todaysWeight.get(allocation.getFund().getTicker()); double diff = Math.abs(today-actualWeight); double perc = (diff/actualWeight)*100; if(perc>=threshold){ rebalancePortfolio = true; break; } } if(rebalancePortfolio){ double totalInvestmentAsOfToday = 0; for(Allocation existingPortfolio:actualAllocationList){ int noOfETF = existingPortfolio.getQuantity(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); ReadFile readFile = new ReadFile(); totalInvestmentAsOfToday += noOfETF*readFile.getETFPriceForDate(paths.get(existingPortfolio.getFund().getTicker()), existingPortfolio.getFund().getTicker(), date); } List<Allocation> newAllocationList = new ArrayList<>(); for(Allocation existingAllocation:actualAllocationList){ int weight = todaysWeight.get(existingAllocation.getFund().getTicker()); double etfWiseInvestment = (totalInvestmentAsOfToday*weight)/100; Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); ReadFile readFile = new ReadFile(); double costPerETF = readFile.getETFPriceForDate(paths.get(existingAllocation.getFund().getTicker()), existingAllocation.getFund().getTicker(), date); int noOfEtf = Double.valueOf(etfWiseInvestment/costPerETF).intValue(); // double cost = noOfEtf*costPerETF; Allocation allocation = new Allocation(); allocation.setCostPrice(costPerETF); allocation.setInvestment(totalInvestmentAsOfToday); allocation.setInvestment(totalInvestmentAsOfToday); allocation.setPercentage(weight); newAllocationList.add(allocation); } portfolio.setAllocations(newAllocationList); portfolioRepository.merge(portfolio); } }catch(Exception e){ e.printStackTrace(); } } private Map<String,Integer> getETFWiseWeight(List<Allocation> allocationList) throws Exception{ Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date date = cal.getTime(); ReadFile readFile = new ReadFile(); Map<String, Integer> etfWiseWeight = new HashMap<>(); Map<String,String> paths = PathsAsPerAssetClass.getETFPaths(); Map<String,Double> etfWisePrice = new HashMap<>(); double totalPrice = 0; for(Allocation allocation:allocationList){ String filePath = paths.get(EtfToIndexMap.get(allocation.getFund().getTicker())); double price = 0; price = readFile.getETFPriceForDate(filePath,allocation.getFund().getTicker(),date); if(price==0){ throw new Exception("Data is not present for today!!"); } etfWisePrice.put(allocation.getFund().getTicker(),price); totalPrice+=price; } Set<Entry<String, Double>> entrySet = etfWisePrice.entrySet(); for(Entry<String,Double> entry:entrySet){ Double weight = entry.getValue()/totalPrice; etfWiseWeight.put(entry.getKey(), weight.intValue()); } return etfWiseWeight; } */ }
18,924
0.736261
0.729233
468
38.435898
30.213028
168
false
false
0
0
0
0
0
0
3.202991
false
false
10
9a610d989ab9dbaf210b957db329c7ab7a0ec865
16,157,667,017,343
bff7b9e373c9b1d3e418640779e81e9352692586
/src/database/data/VisitorUser.java
dfb5972574b5d0b2edfbbe8be428af1189c1d53f
[]
no_license
Vinoooooq/FarmersDatabase
https://github.com/Vinoooooq/FarmersDatabase
9ff90e78d2d9b7e5cb8f0be6260e11a0dac36414
2908b66a04a42e2e7a5e9f8ab33cd2db74b80602
refs/heads/master
2020-04-08T02:50:34.366000
2018-11-24T15:58:26
2018-11-24T15:58:26
158,951,059
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package database.data; public class VisitorUser extends User { }
UTF-8
Java
67
java
VisitorUser.java
Java
[]
null
[]
package database.data; public class VisitorUser extends User { }
67
0.776119
0.776119
5
12.4
15.730226
39
false
false
0
0
0
0
0
0
0.2
false
false
10
7f573acba41de5ab41b37c2f7176b160928d4051
6,167,573,058,407
dda2be974bf26abbc47074c2a4787f49066e84a8
/week-13/src/NumArray.java
85ae0a2eebb44d17bd3e24b20525ac147e54d169
[]
no_license
green-fox-academy/etterke
https://github.com/green-fox-academy/etterke
a6266c1066531532d7e904994eacc2d3b5f7a226
b650654e99b674bb4be3ee28fbc9dae63741bd1a
refs/heads/master
2020-03-31T17:29:12.219000
2019-04-10T07:41:36
2019-04-10T07:41:36
152,424,803
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; public class NumArray { // Írj egy functiont, ami a kapott számokat tartalmazó tömbből (array) visszaadja a legnagyobb elemet. public static void main(String[] args) { int[] numbers = {3, 6, 34, 23, 87, 19, 44}; findBiggestNumber(numbers); } public static void findBiggestNumber(int[] numbers) { int[] ascending = new int[numbers.length]; int temp; for (int i = 0; i < numbers.length; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] > numbers[j]) { temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; ascending = numbers; } } } print(ascending); printBiggestNumber(ascending); } private static void printBiggestNumber(int[] ascending) { int biggestNumber = ascending[6]; System.out.println(biggestNumber); } private static void print(int[] numbers) { for (int number : numbers) { System.out.println(" " + number + " "); } } }
UTF-8
Java
1,035
java
NumArray.java
Java
[]
null
[]
import java.util.Arrays; public class NumArray { // Írj egy functiont, ami a kapott számokat tartalmazó tömbből (array) visszaadja a legnagyobb elemet. public static void main(String[] args) { int[] numbers = {3, 6, 34, 23, 87, 19, 44}; findBiggestNumber(numbers); } public static void findBiggestNumber(int[] numbers) { int[] ascending = new int[numbers.length]; int temp; for (int i = 0; i < numbers.length; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] > numbers[j]) { temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; ascending = numbers; } } } print(ascending); printBiggestNumber(ascending); } private static void printBiggestNumber(int[] ascending) { int biggestNumber = ascending[6]; System.out.println(biggestNumber); } private static void print(int[] numbers) { for (int number : numbers) { System.out.println(" " + number + " "); } } }
1,035
0.597087
0.582524
41
24.121952
22.676081
103
false
false
0
0
0
0
0
0
0.609756
false
false
10
86f8406b97aca2e0fb3095a9662bd85d2fc8b621
18,468,359,407,731
39bff1e58852ecd7ab6f0bfb1af708ebd99b0f36
/seleniumproject/src/com/selenium/reveson/prpts.java
04cb72b99a1ac1640e9a2ce7cd3d818cbfadabff
[]
no_license
smdsameer/selenium
https://github.com/smdsameer/selenium
3bcd8940db26a7cd3fe1e1caeeeab383db9adab9
3e3c0ee2d32781ed7d94aa6558c3a35ba5eab805
refs/heads/master
2022-11-21T23:56:44.351000
2020-07-07T16:19:02
2020-07-07T16:19:02
276,306,805
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.selenium.reveson; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class prpts { public static void main(String[] args) throws IOException { Properties pro=new Properties(); FileInputStream ip=new FileInputStream("C:\\Users\\sam\\eclipse-workspace\\seleniumproject\\src\\com\\selenium\\reveson\\register.properties"); pro.load(ip); System.out.println(pro.getProperty("name")); System.out.println(pro.getProperty("age")); String BName=pro.getProperty("Browser"); if(BName.equals("chrome")) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\sam\\Desktop\\java webdrivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get(pro.getProperty("URL")); driver.findElement(By.xpath(pro.getProperty("first_xpath"))).sendKeys(pro.getProperty("firstname")); driver.findElement(By.xpath(pro.getProperty("sure_xpath"))).sendKeys(pro.getProperty("lastname")); Select sel=new Select(driver.findElement(By.xpath(pro.getProperty("select_xpath")))); sel.selectByVisibleText("10"); } } }
UTF-8
Java
1,377
java
prpts.java
Java
[]
null
[]
package com.selenium.reveson; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class prpts { public static void main(String[] args) throws IOException { Properties pro=new Properties(); FileInputStream ip=new FileInputStream("C:\\Users\\sam\\eclipse-workspace\\seleniumproject\\src\\com\\selenium\\reveson\\register.properties"); pro.load(ip); System.out.println(pro.getProperty("name")); System.out.println(pro.getProperty("age")); String BName=pro.getProperty("Browser"); if(BName.equals("chrome")) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\sam\\Desktop\\java webdrivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get(pro.getProperty("URL")); driver.findElement(By.xpath(pro.getProperty("first_xpath"))).sendKeys(pro.getProperty("firstname")); driver.findElement(By.xpath(pro.getProperty("sure_xpath"))).sendKeys(pro.getProperty("lastname")); Select sel=new Select(driver.findElement(By.xpath(pro.getProperty("select_xpath")))); sel.selectByVisibleText("10"); } } }
1,377
0.732026
0.730574
40
32.424999
34.278191
145
false
false
0
0
0
0
0
0
1.625
false
false
10
049e86ffef47da2a5ba2484b708acd47754cbf5f
27,006,754,381,818
c1e385e0147bbf743d6e9ca8f7f35453bb55c639
/app/src/main/java/com/example/sufehelperapp/Selection2.java
cc4151a9b19c35bc9881a735ab23b4cc295fe099
[]
no_license
SufeHelperApp/SufeHelperApp
https://github.com/SufeHelperApp/SufeHelperApp
a6681557476a725849089f02afe6af6bf1e3e15e
423609e2b09a35cf5191646d54ae2432b25f914c
refs/heads/master
2021-05-05T07:22:45.956000
2018-06-30T11:41:39
2018-06-30T11:41:39
118,866,092
2
1
null
false
2018-06-30T11:41:40
2018-01-25T05:20:46
2018-06-28T13:25:28
2018-06-30T11:41:40
47,118
1
0
1
Java
false
null
package com.example.sufehelperapp; import android.content.Intent; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.Spinner; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; import org.litepal.crud.DataSupport; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class Selection2 extends AppCompatActivity { private String POIName; private MapView mMapView; private BaiduMap baiduMap; private boolean firstLocation; private BitmapDescriptor mCurrentMarker; private MyLocationConfiguration config; List<task> taskList = new ArrayList<>(); private String myPhone; private Connection con; Statement st; private ResultSet rs; private user user; String[] subtaskTypes; private int num = 0; private String subtaskType; private String payment; private int position1=0; private int position2=0; private int position3=0; private int position4=0; private String pay1string = "0"; private String pay2string = "10000"; private LocationClient locationClient = new LocationClient(this); private double latNow; //TODO private double lngNow; //TODO /* public void requestLocation() { locationClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(final BDLocation location) { latNow = location.getLatitude(); lngNow = location.getLongitude(); } }); }*/ public void requestLocation() { locationClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(final BDLocation location) { // map view 销毁后不在处理新接收的位置 if (location == null || mMapView == null) return; // 构造定位数据 MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(100).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); // 设置定位数据 //baiduMap.setMyLocationData(locData); // 第一次定位时,将地图位置移动到当前位置 if (firstLocation) { firstLocation = false; LatLng xy = new LatLng(location.getLatitude(), location.getLongitude()); MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(xy); //baiduMap.animateMapStatus(status); } latNow = location.getLatitude(); lngNow = location.getLongitude(); /* runOnUiThread(new Runnable() { @Override public void run() { StringBuilder currentPosition = new StringBuilder(); currentPosition.append("纬度:").append(location.getLatitude()).append("\n"); currentPosition.append("经线:").append(location.getLongitude()).append("\n"); currentPosition.append("定位方式:"); if (location.getLocType() == BDLocation.TypeGpsLocation) { currentPosition.append("GPS"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) { currentPosition.append("网络"); } } });*/ } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //user myPhone = getIntent().getStringExtra("user_phone"); try{ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); con = DbUtils.getConn(); Statement st = con.createStatement(); rs = st.executeQuery("SELECT * FROM `user` WHERE `phonenumber` = '"+myPhone+"'"); List<user> userList = new ArrayList<>(); List list = DbUtils.populate(rs,user.class); for(int i=0; i<list.size(); i++){ userList.add((user)list.get(i)); } user = userList.get(0); Log.d("user",user.getMyName()); } catch (Exception e) { e.printStackTrace(); }finally { if (con != null) try { con.close(); } catch (SQLException e) { } } //此方法要再setContentView方法之前实现 SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_selection); android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); //mMapView =(MapView)findViewById(R.id.bmapView_task); //baiduMap = mMapView.getMap(); MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16f); //baiduMap.setMapStatus(msu); // 定位初始化 locationClient = new LocationClient(this); firstLocation =true; // 设置定位的相关配置 LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); option.setOpenGps(true); option.setCoorType("bd09ll"); // 设置坐标类型 option.setScanSpan(5000); locationClient.setLocOption(option); requestLocation(); BottomNavigationView bottomNavigationItemView = (BottomNavigationView) findViewById(R.id.btn_navigation); bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch(item.getItemId()) { case R.id.item_task: Intent intent1 = new Intent(Selection2.this, Task_HomeActivity.class); intent1.putExtra("user_phone", myPhone); startActivity(intent1); break; case R.id.item_explore: Intent intent3 = new Intent(Selection2.this, ExploreActivity.class); intent3.putExtra("user_phone", myPhone); startActivity(intent3); break; case R.id.item_my: Intent intent2 = new Intent(Selection2.this, My_HomeActivity.class); intent2.putExtra("user_phone", myPhone); startActivity(intent2); break; } return true; } }); final Spinner subtaskView = (Spinner) findViewById(R.id.selection_subtask); final String[] subtaskTypes = getResources().getStringArray(R.array.subtasks_skill); final Spinner distView = (Spinner) findViewById(R.id.selection_area); final Spinner paymentView = (Spinner) findViewById(R.id.selection_payment); final String[] payments = getResources().getStringArray(R.array.payments); final Spinner ddlView = (Spinner) findViewById(R.id.selection_ddl); final String[] ddls = getResources().getStringArray(R.array.ddls); StatusUtils.updateAllTaskStatus(); double dis = MapUtils.getDistance(latNow,lngNow,31.3079395836,121.5089110332); Log.d("lat",String.valueOf(latNow)); Log.d("lng",String.valueOf(lngNow)); Log.d("dis",String.valueOf(dis)); if(num == 0 ) { try{ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); con = DbUtils.getConn(); //initialize connection st = con.createStatement(); //initialize connection rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' AND `ifDisplayable` = '1'"); //List<task> sampleList = new ArrayList<>(); List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ taskList.add((task)list.get(i)); } //taskList = sampleList; Log.d("msg",String.valueOf(taskList.size())); TaskAdapter adapter = new TaskAdapter(taskList,user,1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this,1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); con.close(); } catch (Exception e) { e.printStackTrace(); } } num++; subtaskView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position1 = position; subtaskType = subtaskTypes[position]; if(num!=0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } //check ddl List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); distView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position2 = position; if(num!=0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); paymentView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position3 = position; payment = payments[position]; switch (payment) { case "报酬": { pay1string = "0"; pay2string = "10000"; break; } case "0-5元": { pay1string = "0"; pay2string = "5"; break; } case "6-10元": { pay1string = "6"; pay2string = "10"; break; } case "11-15元": { pay1string = "11"; pay2string = "15"; break; } case "15元以上": { pay1string = "15"; pay2string = "10000"; break; } } if (num != 0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ddlView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position4 = position; if(num!=0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Button button1 = (Button) findViewById(R.id.title_back); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Selection2.this, Task_ErrandActivity.class); intent.putExtra("user_phone", myPhone); startActivity(intent); } }); } @Override public void onBackPressed(){ Intent intent = new Intent(Selection2.this, Task_ErrandActivity.class); intent.putExtra("user_phone", myPhone); startActivity(intent); finish(); } }
UTF-8
Java
39,499
java
Selection2.java
Java
[]
null
[]
package com.example.sufehelperapp; import android.content.Intent; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.Spinner; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; import org.litepal.crud.DataSupport; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class Selection2 extends AppCompatActivity { private String POIName; private MapView mMapView; private BaiduMap baiduMap; private boolean firstLocation; private BitmapDescriptor mCurrentMarker; private MyLocationConfiguration config; List<task> taskList = new ArrayList<>(); private String myPhone; private Connection con; Statement st; private ResultSet rs; private user user; String[] subtaskTypes; private int num = 0; private String subtaskType; private String payment; private int position1=0; private int position2=0; private int position3=0; private int position4=0; private String pay1string = "0"; private String pay2string = "10000"; private LocationClient locationClient = new LocationClient(this); private double latNow; //TODO private double lngNow; //TODO /* public void requestLocation() { locationClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(final BDLocation location) { latNow = location.getLatitude(); lngNow = location.getLongitude(); } }); }*/ public void requestLocation() { locationClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(final BDLocation location) { // map view 销毁后不在处理新接收的位置 if (location == null || mMapView == null) return; // 构造定位数据 MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(100).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); // 设置定位数据 //baiduMap.setMyLocationData(locData); // 第一次定位时,将地图位置移动到当前位置 if (firstLocation) { firstLocation = false; LatLng xy = new LatLng(location.getLatitude(), location.getLongitude()); MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(xy); //baiduMap.animateMapStatus(status); } latNow = location.getLatitude(); lngNow = location.getLongitude(); /* runOnUiThread(new Runnable() { @Override public void run() { StringBuilder currentPosition = new StringBuilder(); currentPosition.append("纬度:").append(location.getLatitude()).append("\n"); currentPosition.append("经线:").append(location.getLongitude()).append("\n"); currentPosition.append("定位方式:"); if (location.getLocType() == BDLocation.TypeGpsLocation) { currentPosition.append("GPS"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) { currentPosition.append("网络"); } } });*/ } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //user myPhone = getIntent().getStringExtra("user_phone"); try{ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); con = DbUtils.getConn(); Statement st = con.createStatement(); rs = st.executeQuery("SELECT * FROM `user` WHERE `phonenumber` = '"+myPhone+"'"); List<user> userList = new ArrayList<>(); List list = DbUtils.populate(rs,user.class); for(int i=0; i<list.size(); i++){ userList.add((user)list.get(i)); } user = userList.get(0); Log.d("user",user.getMyName()); } catch (Exception e) { e.printStackTrace(); }finally { if (con != null) try { con.close(); } catch (SQLException e) { } } //此方法要再setContentView方法之前实现 SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_selection); android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); //mMapView =(MapView)findViewById(R.id.bmapView_task); //baiduMap = mMapView.getMap(); MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16f); //baiduMap.setMapStatus(msu); // 定位初始化 locationClient = new LocationClient(this); firstLocation =true; // 设置定位的相关配置 LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); option.setOpenGps(true); option.setCoorType("bd09ll"); // 设置坐标类型 option.setScanSpan(5000); locationClient.setLocOption(option); requestLocation(); BottomNavigationView bottomNavigationItemView = (BottomNavigationView) findViewById(R.id.btn_navigation); bottomNavigationItemView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch(item.getItemId()) { case R.id.item_task: Intent intent1 = new Intent(Selection2.this, Task_HomeActivity.class); intent1.putExtra("user_phone", myPhone); startActivity(intent1); break; case R.id.item_explore: Intent intent3 = new Intent(Selection2.this, ExploreActivity.class); intent3.putExtra("user_phone", myPhone); startActivity(intent3); break; case R.id.item_my: Intent intent2 = new Intent(Selection2.this, My_HomeActivity.class); intent2.putExtra("user_phone", myPhone); startActivity(intent2); break; } return true; } }); final Spinner subtaskView = (Spinner) findViewById(R.id.selection_subtask); final String[] subtaskTypes = getResources().getStringArray(R.array.subtasks_skill); final Spinner distView = (Spinner) findViewById(R.id.selection_area); final Spinner paymentView = (Spinner) findViewById(R.id.selection_payment); final String[] payments = getResources().getStringArray(R.array.payments); final Spinner ddlView = (Spinner) findViewById(R.id.selection_ddl); final String[] ddls = getResources().getStringArray(R.array.ddls); StatusUtils.updateAllTaskStatus(); double dis = MapUtils.getDistance(latNow,lngNow,31.3079395836,121.5089110332); Log.d("lat",String.valueOf(latNow)); Log.d("lng",String.valueOf(lngNow)); Log.d("dis",String.valueOf(dis)); if(num == 0 ) { try{ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); con = DbUtils.getConn(); //initialize connection st = con.createStatement(); //initialize connection rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' AND `ifDisplayable` = '1'"); //List<task> sampleList = new ArrayList<>(); List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ taskList.add((task)list.get(i)); } //taskList = sampleList; Log.d("msg",String.valueOf(taskList.size())); TaskAdapter adapter = new TaskAdapter(taskList,user,1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this,1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); con.close(); } catch (Exception e) { e.printStackTrace(); } } num++; subtaskView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position1 = position; subtaskType = subtaskTypes[position]; if(num!=0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } //check ddl List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); distView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position2 = position; if(num!=0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); paymentView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position3 = position; payment = payments[position]; switch (payment) { case "报酬": { pay1string = "0"; pay2string = "10000"; break; } case "0-5元": { pay1string = "0"; pay2string = "5"; break; } case "6-10元": { pay1string = "6"; pay2string = "10"; break; } case "11-15元": { pay1string = "11"; pay2string = "15"; break; } case "15元以上": { pay1string = "15"; pay2string = "10000"; break; } } if (num != 0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ddlView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { position4 = position; if(num!=0) { if (position1 == 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } else if (position1 != 0) { try{ con = DbUtils.getConn(); st = con.createStatement(); rs= st.executeQuery("SELECT * FROM `task` WHERE `taskType` = '技能' " + " AND `subtaskType` = '"+subtaskType+"' AND `payment` >= '"+pay1string+"' AND `payment` <= '"+pay2string+"'" + " AND `ifDisplayable` = '1'"); List<task> sampleList = new ArrayList<>(); //清空taskList List list = DbUtils.populate(rs,task.class); for(int i = 0; i < list.size(); i++){ sampleList.add((task)list.get(i)); } taskList = sampleList; con.close(); } catch (Exception e) { e.printStackTrace(); } } //check dist List<task> demand1; switch (position2) { case 0: break; case 1: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin500m(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 2: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin1km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; case 3: demand1 = new ArrayList<>(); for (task task : taskList) { if (MapUtils.isTaskWithin3km(latNow,lngNow,task.getLatitude(),task.getLongtitude())) { demand1.add(task); } } taskList = demand1; break; } List<task> demand; switch (position4) { case 0: break; case 1: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeHour(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 2: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 3: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinThreeDay(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 4: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneWeek(task.getDdl())) { demand.add(task); } } taskList = demand; break; case 5: demand = new ArrayList<>(); for (task task : taskList) { if (TimeUtils.isDateWithinOneMonth(task.getDdl())) { demand.add(task); } } taskList = demand; break; } TaskAdapter adapter = new TaskAdapter(taskList, user, 1); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.selection_recycler); GridLayoutManager layoutManager = new GridLayoutManager(Selection2.this, 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); Button button1 = (Button) findViewById(R.id.title_back); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Selection2.this, Task_ErrandActivity.class); intent.putExtra("user_phone", myPhone); startActivity(intent); } }); } @Override public void onBackPressed(){ Intent intent = new Intent(Selection2.this, Task_ErrandActivity.class); intent.putExtra("user_phone", myPhone); startActivity(intent); finish(); } }
39,499
0.401265
0.393459
999
38.235237
28.43713
146
false
false
0
0
0
0
0
0
0.53954
false
false
10
f8fc44b193b4d356ed9aecf9493abb7241dc3d21
13,872,744,407,977
a89c95173ba2d099e37803f618033a824d5387e1
/6.19/Week1/SharingDataViaIntents/app/src/main/java/com/example/singh/sharingdataviaintents/SerialiazablePersonActivity.java
2e47f10f2579cb16e363872ffcac447b070dae09
[]
no_license
DroidSingh89/MAC_Training
https://github.com/DroidSingh89/MAC_Training
69715c2b1476857d924034391449b70400d80b15
096293a249f220cb7366747d45a727c05a9050e7
refs/heads/master
2021-07-12T23:01:46.912000
2018-12-13T15:26:12
2018-12-13T15:26:12
133,825,375
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.singh.sharingdataviaintents; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class SerialiazablePersonActivity extends AppCompatActivity { TextView tvPersonName, tvPersonAge, tvPersonGender; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_person); Intent intent = getIntent(); SerializablePerson person = (SerializablePerson) intent.getSerializableExtra("serializablePerson"); tvPersonAge = (TextView) findViewById(R.id.tvPersonAge); tvPersonName= (TextView) findViewById(R.id.tvPersonName); tvPersonGender = (TextView) findViewById(R.id.tvPersonGender); tvPersonName.setText(person.getName()); tvPersonAge.setText(String.valueOf(person.getAge())); tvPersonGender.setText(person.getGender()); } public void sendParcelablePerson(View view) { ParcelablePerson person = new ParcelablePerson("Johnny depp", 50, "Male"); Intent intent = new Intent(SerialiazablePersonActivity.this, ParcelablePersonActivity.class); intent.putExtra("parcelablePerson", person); startActivity(intent); } }
UTF-8
Java
1,358
java
SerialiazablePersonActivity.java
Java
[ { "context": " ParcelablePerson person = new ParcelablePerson(\"Johnny depp\", 50, \"Male\");\n Intent intent = new Intent", "end": 1146, "score": 0.9998719692230225, "start": 1135, "tag": "NAME", "value": "Johnny depp" } ]
null
[]
package com.example.singh.sharingdataviaintents; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class SerialiazablePersonActivity extends AppCompatActivity { TextView tvPersonName, tvPersonAge, tvPersonGender; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_person); Intent intent = getIntent(); SerializablePerson person = (SerializablePerson) intent.getSerializableExtra("serializablePerson"); tvPersonAge = (TextView) findViewById(R.id.tvPersonAge); tvPersonName= (TextView) findViewById(R.id.tvPersonName); tvPersonGender = (TextView) findViewById(R.id.tvPersonGender); tvPersonName.setText(person.getName()); tvPersonAge.setText(String.valueOf(person.getAge())); tvPersonGender.setText(person.getGender()); } public void sendParcelablePerson(View view) { ParcelablePerson person = new ParcelablePerson("<NAME>", 50, "Male"); Intent intent = new Intent(SerialiazablePersonActivity.this, ParcelablePersonActivity.class); intent.putExtra("parcelablePerson", person); startActivity(intent); } }
1,353
0.734904
0.732695
41
32.121952
30.482458
107
false
false
0
0
0
0
0
0
0.658537
false
false
10
d23a4f2f87a6c3bbe3b89b02f8b641b393f697d7
16,432,544,910,878
d798e0d7cfe0c8e340d3bdf0b88b625840ddab39
/src/main/java/com/common/controller/LoginController.java
2807362224a6a94020221292988a0e24d2e4dd17
[]
no_license
Billseeyao/jx_manage
https://github.com/Billseeyao/jx_manage
685a7b67c5b18f51311cba2ddc6d05c004167722
6905fa1bda9b631a6c775cb8cf9f40d8c4166e92
refs/heads/master
2023-03-30T13:20:21.962000
2020-03-10T03:32:58
2020-03-10T03:32:58
244,552,208
0
0
null
false
2023-03-27T22:18:43
2020-03-03T05:45:12
2020-03-10T03:33:17
2023-03-27T22:18:42
165
0
0
2
Java
false
false
package main.java.com.common.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import main.java.com.po.dao.UserMapper; import main.java.com.po.entity.UserEntity; import main.java.com.utils.ReMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * 用户登录controller * @author ylyao * */ @RestController @RequestMapping(value="/user") public class LoginController { private Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private HttpSession session; @Autowired private UserMapper userMapper; private String loginUser = ""; private String pwd = ""; /** * 用户登陆 * @param request * @param httpSession */ @RequestMapping(value="/login",method = RequestMethod.POST) public ReMessage loginIn(HttpServletRequest request){ Map<String,Object> map = new HashMap<String ,Object>(); try { loginUser = request.getParameter("userName"); pwd = request.getParameter("passWord"); UserEntity entity = new UserEntity(); entity.setName(loginUser); entity.setPassWord(pwd); String flag = userMapper.isExistUser(entity); if("1".equals(flag)){ request.getSession().setAttribute("currentUser", loginUser); //其他要用到的地方使用 注入HttpSession session即可 map.put("user", loginUser); return ReMessage.ok(map); } else { //提示登陆失败 return ReMessage.error(500, "用户名或密码错误,请重试..."); } } catch (Exception e){ logger.error("登录异常["+ e.getMessage() +"],请重试..."); return ReMessage.error(500, "登录异常,请重试..."); } } /** * 退出登陆 * @param session * @return */ @RequestMapping(value = "/logout",method = RequestMethod.POST) public ReMessage logout(HttpServletRequest request){ session.removeAttribute(request.getParameter("userName"));//使Session变成无效,及用户退出 return ReMessage.ok(); } /** * 登录后获取用户名 * @param request * @return */ @RequestMapping(value = "/getUser",method = RequestMethod.POST) public ReMessage getUser(){ try { String user = session.getAttribute("currentUser").toString(); return ReMessage.ok(user); } catch (Exception e){ logger.error("获取当前用户失败["+e.getMessage()+"]"); return ReMessage.error(500,"获取当前用户失败..."); } } }
UTF-8
Java
2,817
java
LoginController.java
Java
[ { "context": "ontroller;\r\n\r\n\r\n/**\r\n * 用户登录controller\r\n * @author ylyao\r\n *\r\n */\r\n@RestController\r\n@RequestMapping(value=", "end": 669, "score": 0.9996485710144043, "start": 664, "tag": "USERNAME", "value": "ylyao" } ]
null
[]
package main.java.com.common.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import main.java.com.po.dao.UserMapper; import main.java.com.po.entity.UserEntity; import main.java.com.utils.ReMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * 用户登录controller * @author ylyao * */ @RestController @RequestMapping(value="/user") public class LoginController { private Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private HttpSession session; @Autowired private UserMapper userMapper; private String loginUser = ""; private String pwd = ""; /** * 用户登陆 * @param request * @param httpSession */ @RequestMapping(value="/login",method = RequestMethod.POST) public ReMessage loginIn(HttpServletRequest request){ Map<String,Object> map = new HashMap<String ,Object>(); try { loginUser = request.getParameter("userName"); pwd = request.getParameter("passWord"); UserEntity entity = new UserEntity(); entity.setName(loginUser); entity.setPassWord(pwd); String flag = userMapper.isExistUser(entity); if("1".equals(flag)){ request.getSession().setAttribute("currentUser", loginUser); //其他要用到的地方使用 注入HttpSession session即可 map.put("user", loginUser); return ReMessage.ok(map); } else { //提示登陆失败 return ReMessage.error(500, "用户名或密码错误,请重试..."); } } catch (Exception e){ logger.error("登录异常["+ e.getMessage() +"],请重试..."); return ReMessage.error(500, "登录异常,请重试..."); } } /** * 退出登陆 * @param session * @return */ @RequestMapping(value = "/logout",method = RequestMethod.POST) public ReMessage logout(HttpServletRequest request){ session.removeAttribute(request.getParameter("userName"));//使Session变成无效,及用户退出 return ReMessage.ok(); } /** * 登录后获取用户名 * @param request * @return */ @RequestMapping(value = "/getUser",method = RequestMethod.POST) public ReMessage getUser(){ try { String user = session.getAttribute("currentUser").toString(); return ReMessage.ok(user); } catch (Exception e){ logger.error("获取当前用户失败["+e.getMessage()+"]"); return ReMessage.error(500,"获取当前用户失败..."); } } }
2,817
0.686715
0.682147
101
24.009901
22.766788
104
false
false
0
0
0
0
0
0
1.792079
false
false
10
d776efd54d9bb42689e975f279ed03b2f0de7178
16,432,544,910,965
ae2d97e9976c92d2023f36e48e310834a15a07d3
/springboot-miaosha-portal/src/main/java/com/simple/service/impl/ConsumerTransactionListener.java
c7fe70911ed1fea23cad13383e0ce3eb318f9149
[]
no_license
zhangshl/springboot-miaosha
https://github.com/zhangshl/springboot-miaosha
2fbe98b77194b9cbce24d403f64f0b885e558e7a
c3df1c3f9b81a9abc45aa9ad6d8b10ecd20b70ad
refs/heads/master
2023-02-26T21:39:42.450000
2021-02-05T08:47:44
2021-02-05T08:47:44
331,294,009
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.simple.service.impl; import com.alibaba.fastjson.JSONObject; import com.simple.domain.SkOrderPayResult; import com.simple.domain.Stock; import com.simple.service.StockService; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; /** * 消费事务消息,执行实际扣库存步骤 */ @Service @RocketMQMessageListener( topic = "${rocketmq.producer.transaction.topic}", consumerGroup = "transactionGroup" ) public class ConsumerTransactionListener implements RocketMQListener<String> { @Value("${times:10}") private int LIMIT_TIMES; @Autowired private StockService stockService; @Override public void onMessage(String s) { SkOrderPayResult payResult = JSONObject.parseObject(s, SkOrderPayResult.class); //去扣库存,乐观锁自旋扣库存 int result = 0; int times = 0; while (result==0){ result = stockService.updateByPrimaryKeySelective(payResult.getSkuId(), payResult.getBuyNum()); if (++times > LIMIT_TIMES){ break; } } if (result != 1){ //TODO 失败处理流程,修改订单状态,退款 } } }
UTF-8
Java
1,316
java
ConsumerTransactionListener.java
Java
[]
null
[]
package com.simple.service.impl; import com.alibaba.fastjson.JSONObject; import com.simple.domain.SkOrderPayResult; import com.simple.domain.Stock; import com.simple.service.StockService; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; /** * 消费事务消息,执行实际扣库存步骤 */ @Service @RocketMQMessageListener( topic = "${rocketmq.producer.transaction.topic}", consumerGroup = "transactionGroup" ) public class ConsumerTransactionListener implements RocketMQListener<String> { @Value("${times:10}") private int LIMIT_TIMES; @Autowired private StockService stockService; @Override public void onMessage(String s) { SkOrderPayResult payResult = JSONObject.parseObject(s, SkOrderPayResult.class); //去扣库存,乐观锁自旋扣库存 int result = 0; int times = 0; while (result==0){ result = stockService.updateByPrimaryKeySelective(payResult.getSkuId(), payResult.getBuyNum()); if (++times > LIMIT_TIMES){ break; } } if (result != 1){ //TODO 失败处理流程,修改订单状态,退款 } } }
1,316
0.769168
0.764274
46
25.652174
24.586332
98
false
false
0
0
0
0
0
0
1.326087
false
false
10
653704fadfdc552b039d3d2aa4c789b6b6ca92b9
28,432,683,540,300
f0f6d353e251fed4bc66bd04b5ff9042aa0b1c8f
/AndroidStudioProjects/RealRecyclerView/app/src/main/java/com/example/anas/realrecyclerview/MainActivity.java
2f90dde72af47738d34c3105d80ae0efe6c2a6f4
[]
no_license
anasqazi/Practice
https://github.com/anasqazi/Practice
e2228d9d8116ee44f6d26451c2831994ef8c6669
7472b632df7153196949c9dbbdcea2b5e000ddaf
refs/heads/master
2021-01-01T18:15:44.344000
2017-07-26T13:41:09
2017-07-26T13:41:09
98,289,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.anas.realrecyclerview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; public class MainActivity extends AppCompatActivity { static RecyclerView myview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myview=(RecyclerView)findViewById(R.id.myrecycler); CustomAdapter adapter =new CustomAdapter(); LinearLayoutManager mngr=new LinearLayoutManager(getApplicationContext()); myview.setLayoutManager(mngr); myview.setItemAnimator(new DefaultItemAnimator()); myview.setAdapter(adapter); adapter.notifyDataSetChanged(); } public void ButtonPresssed(final int post) { myview.smoothScrollToPosition((int)Math.pow(post,2)); } }
UTF-8
Java
1,029
java
MainActivity.java
Java
[]
null
[]
package com.example.anas.realrecyclerview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; public class MainActivity extends AppCompatActivity { static RecyclerView myview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myview=(RecyclerView)findViewById(R.id.myrecycler); CustomAdapter adapter =new CustomAdapter(); LinearLayoutManager mngr=new LinearLayoutManager(getApplicationContext()); myview.setLayoutManager(mngr); myview.setItemAnimator(new DefaultItemAnimator()); myview.setAdapter(adapter); adapter.notifyDataSetChanged(); } public void ButtonPresssed(final int post) { myview.smoothScrollToPosition((int)Math.pow(post,2)); } }
1,029
0.74344
0.738581
31
32.19355
23.765547
82
false
false
0
0
0
0
0
0
0.580645
false
false
10
56617925d8d5c973465de9ecc4a57d9a0068c546
11,544,872,102,555
7d12a0fbece73d6ef812182478452819f8cfe891
/Source/User App (Mobile)/TMSSKS/app/src/main/java/kfu/ccsit/tmssks/ActivityAbout.java
0aa5f49d7e331c532522762c7a4527f910ff7025
[]
no_license
alomardev/tmssks
https://github.com/alomardev/tmssks
6f819a9d958583154a2aac84ba659f31ecf75bf7
6c1f94e079c13308e02a278d06461c5cb859a6bc
refs/heads/master
2021-05-07T07:17:18.506000
2017-11-03T15:38:19
2017-11-03T15:38:19
109,113,777
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kfu.ccsit.tmssks; import android.os.Bundle; import android.view.MenuItem; import android.view.View; public class ActivityAbout extends ActivityBase { @SuppressWarnings("ConstantConditions") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); // Setting up the toolbar setSupportActionBar(getToolbar()); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Go back to the main activity when home (UP) button is clicked case android.R.id.home: super.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public void buttonClick(View v) { switch (v.getId()) { case R.id.btn_licenses: MiscUtils.showLicenseDialog(this); break; case R.id.btn_contact: MiscUtils.contactDeveloper(this); break; } } }
UTF-8
Java
1,237
java
ActivityAbout.java
Java
[]
null
[]
package kfu.ccsit.tmssks; import android.os.Bundle; import android.view.MenuItem; import android.view.View; public class ActivityAbout extends ActivityBase { @SuppressWarnings("ConstantConditions") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); // Setting up the toolbar setSupportActionBar(getToolbar()); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Go back to the main activity when home (UP) button is clicked case android.R.id.home: super.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public void buttonClick(View v) { switch (v.getId()) { case R.id.btn_licenses: MiscUtils.showLicenseDialog(this); break; case R.id.btn_contact: MiscUtils.contactDeveloper(this); break; } } }
1,237
0.620049
0.620049
45
26.48889
20.928049
76
false
false
0
0
0
0
0
0
0.355556
false
false
10
bb842f61e9fd94a2d931d3d00050c58b971e41f4
12,008,728,586,623
18b65fcacb22f6aa253602f88394d740fe1e4c33
/src/main/java/jp/co/businessportal/mapper/AgentMapper.java
5d2e9296d9e8c47e41df269ac4001984fefba0d8
[]
no_license
HirofumiTsukahara/BusinessPortal
https://github.com/HirofumiTsukahara/BusinessPortal
fec4e28108e3891f84c03f380a9146f617d0b555
9926f563045cec02a6dcd578e02e98b0e9443292
refs/heads/master
2018-12-25T18:35:26.726000
2018-12-19T05:59:45
2018-12-19T05:59:45
94,853,840
0
0
null
false
2019-11-13T03:59:28
2017-06-20T05:41:12
2019-07-18T23:59:54
2019-11-13T03:59:24
3,426
0
0
1
Java
false
false
package jp.co.businessportal.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import jp.co.businessportal.dto.AgentDto; import jp.co.businessportal.dto.SelectAfltCodeDto; public interface AgentMapper { public List<AgentDto> SQL_AGENT_001(@Param("agentList") List<String> agentList); public String SQL_AGENT_002(@Param("agentCode") String agentCode); public AgentDto SQL_AGENT_003(@Param("agentCode") String agentCode); public List<String> SQL_AGENT_004(@Param("agentList") List<String> agentList); public List<AgentDto> SQL_AGENT_005(); public String SQL_AGENT_006(@Param("afltCode") String afltCode); public List<SelectAfltCodeDto> SQL_AGENT_007(@Param("groupCode")String groupCode); public List<AgentDto> SQL_AGENT_008(@Param("compCode") String compCode); public List<String> SQL_AGENT_009(); public String SQL_AGENT_010(@Param("compCode") String compCode); public void SQL_AGENT_D_001(); public void SQL_AGENT_C_001(AgentDto agentDto); }
UTF-8
Java
1,046
java
AgentMapper.java
Java
[]
null
[]
package jp.co.businessportal.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import jp.co.businessportal.dto.AgentDto; import jp.co.businessportal.dto.SelectAfltCodeDto; public interface AgentMapper { public List<AgentDto> SQL_AGENT_001(@Param("agentList") List<String> agentList); public String SQL_AGENT_002(@Param("agentCode") String agentCode); public AgentDto SQL_AGENT_003(@Param("agentCode") String agentCode); public List<String> SQL_AGENT_004(@Param("agentList") List<String> agentList); public List<AgentDto> SQL_AGENT_005(); public String SQL_AGENT_006(@Param("afltCode") String afltCode); public List<SelectAfltCodeDto> SQL_AGENT_007(@Param("groupCode")String groupCode); public List<AgentDto> SQL_AGENT_008(@Param("compCode") String compCode); public List<String> SQL_AGENT_009(); public String SQL_AGENT_010(@Param("compCode") String compCode); public void SQL_AGENT_D_001(); public void SQL_AGENT_C_001(AgentDto agentDto); }
1,046
0.724665
0.690249
25
39.84
29.956875
86
false
false
0
0
0
0
0
0
0.68
false
false
10
f25b5fe71e0b01386f5e10c6fcc0f42146f4ecb1
9,706,626,093,105
d02c524cdeb983863bca5743d16d14cf1c010113
/src/com/motorola/nicu/MyApplication.java
a43fe83700ac0c29a1cda6b37272ee36b23a3c67
[]
no_license
syedhassan/NICU2Home
https://github.com/syedhassan/NICU2Home
18eb46b3d0c2ee1972e582f661f889da017928af
7d2985013e76044ca693ded5925b5275fd1ad96f
refs/heads/master
2016-09-06T07:57:24.891000
2014-03-09T06:27:00
2014-03-09T06:27:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.motorola.nicu; import org.acra.ACRA; import org.acra.ErrorReporter; import org.acra.annotation.ReportsCrashes; import org.json.JSONException; import org.json.JSONObject; import com.motorola.nicu.database.DatabaseHandler; import android.app.Application; /** * Handles crashes report and are saved under https://docs.google.com/spreadsheet/ccc?key=dEp2T3h1ZmoxUGMxblR0dFpLS0JablE6MQ * @author Sana * */ @ReportsCrashes(formKey = "dEp2T3h1ZmoxUGMxblR0dFpLS0JablE6MQ") public class MyApplication extends Application { private DatabaseHandler db; @SuppressWarnings("deprecation") @Override public void onCreate() { ACRA.init(this); super.onCreate(); db = DatabaseHandler.getInstance(getApplicationContext()); JSONObject data = db.getParentData(); try { if (data.has("email")) { ErrorReporter.getInstance().putCustomData("email", data.getString("email")); } ErrorReporter.getInstance().putCustomData("name", data.getString("fName")+" "+data.getString("mName")+" "+data.getString("lName")); } catch (JSONException e) { e.printStackTrace(); } } }
UTF-8
Java
1,236
java
MyApplication.java
Java
[ { "context": "under https://docs.google.com/spreadsheet/ccc?key=dEp2T3h1ZmoxUGMxblR0dFpLS0JablE6MQ\n * @author Sana\n *\n */\n@ReportsCrashes(formKey = ", "end": 397, "score": 0.999756932258606, "start": 363, "tag": "KEY", "value": "dEp2T3h1ZmoxUGMxblR0dFpLS0JablE6MQ" }, { "context":...
null
[]
package com.motorola.nicu; import org.acra.ACRA; import org.acra.ErrorReporter; import org.acra.annotation.ReportsCrashes; import org.json.JSONException; import org.json.JSONObject; import com.motorola.nicu.database.DatabaseHandler; import android.app.Application; /** * Handles crashes report and are saved under https://docs.google.com/spreadsheet/ccc?key=<KEY> * @author Sana * */ @ReportsCrashes(formKey = "<KEY>") public class MyApplication extends Application { private DatabaseHandler db; @SuppressWarnings("deprecation") @Override public void onCreate() { ACRA.init(this); super.onCreate(); db = DatabaseHandler.getInstance(getApplicationContext()); JSONObject data = db.getParentData(); try { if (data.has("email")) { ErrorReporter.getInstance().putCustomData("email", data.getString("email")); } ErrorReporter.getInstance().putCustomData("name", data.getString("fName")+" "+data.getString("mName")+" "+data.getString("lName")); } catch (JSONException e) { e.printStackTrace(); } } }
1,178
0.664239
0.654531
41
29.146341
31.421261
143
false
false
0
0
0
0
0
0
0.439024
false
false
10
dbc137c7105ae27a9c5958f7d733f00eacc1917f
1,786,706,400,155
0c8199193118dd688dc19c252bd441b87dbbcabb
/finalexception/disabled/Disabled.java
be6bc4b871c4885be448a7ea4183ea0d0af8bbaf
[ "Unlicense" ]
permissive
FinalException/discord-disabler
https://github.com/FinalException/discord-disabler
f6b6fe6dcdad680644cb038497d75ff7d5bde226
c2b231dec6aa7824eb5ce51f953b46db451dc982
refs/heads/master
2020-06-06T20:22:30.725000
2019-09-24T09:47:23
2019-09-24T09:47:23
192,844,297
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package finalexception.disabled; import finalexception.disabled.scanner.ContentScanner; import finalexception.disabled.scanner.callback.Callback; import finalexception.disabled.scanner.callback.CallbackResult; import finalexception.disabled.utils.FormatUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * An application that scans through messages and (attempts) to find * messages that could potentially get the user suspended from Discord. * * <p> * This doesn't use JDA to actually scan the messages fully because * JDA for some reason takes a shit and wouldn't work, even latest version * so you'll have to make your scanner with JDA and make this application * process it. * </p> * * @author FinalException */ public final class Disabled { private final ContentScanner CONTENT_SCANNER = new ContentScanner(); private Disabled() { ArrayList<String> content = new ArrayList<>(Arrays.asList("i'm literally gonna fucking ddos you", "get fucking doxxed kid", "Hey, how are you?", "I'm doing fine, wbu", "watch ur door, swat might come in ;)")); StringBuilder outcome = new StringBuilder(); content.forEach(s -> { // Bad API usage, too tired to fix. Pls fix HashMap<Callback, CallbackResult> callbacks = new HashMap<>(); callbacks.put(CONTENT_SCANNER, CONTENT_SCANNER.scan(s)); outcome.append(FormatUtils.formatForPrinting(callbacks)); }); System.out.print(outcome); } // ---- public static void main(String[] args) { new Disabled(); } }
UTF-8
Java
1,752
java
Disabled.java
Java
[ { "context": "ation\r\n * process it.\r\n * </p>\r\n *\r\n * @author FinalException\r\n */\r\npublic final class Disabled {\r\n private ", "end": 803, "score": 0.9988900423049927, "start": 789, "tag": "USERNAME", "value": "FinalException" } ]
null
[]
package finalexception.disabled; import finalexception.disabled.scanner.ContentScanner; import finalexception.disabled.scanner.callback.Callback; import finalexception.disabled.scanner.callback.CallbackResult; import finalexception.disabled.utils.FormatUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * An application that scans through messages and (attempts) to find * messages that could potentially get the user suspended from Discord. * * <p> * This doesn't use JDA to actually scan the messages fully because * JDA for some reason takes a shit and wouldn't work, even latest version * so you'll have to make your scanner with JDA and make this application * process it. * </p> * * @author FinalException */ public final class Disabled { private final ContentScanner CONTENT_SCANNER = new ContentScanner(); private Disabled() { ArrayList<String> content = new ArrayList<>(Arrays.asList("i'm literally gonna fucking ddos you", "get fucking doxxed kid", "Hey, how are you?", "I'm doing fine, wbu", "watch ur door, swat might come in ;)")); StringBuilder outcome = new StringBuilder(); content.forEach(s -> { // Bad API usage, too tired to fix. Pls fix HashMap<Callback, CallbackResult> callbacks = new HashMap<>(); callbacks.put(CONTENT_SCANNER, CONTENT_SCANNER.scan(s)); outcome.append(FormatUtils.formatForPrinting(callbacks)); }); System.out.print(outcome); } // ---- public static void main(String[] args) { new Disabled(); } }
1,752
0.646689
0.646689
53
31.056604
28.43358
105
false
false
0
0
0
0
0
0
0.54717
false
false
10
3ba98ff676585d0da75cc8b01c646709950da9d4
14,482,629,751,667
d93ce3950a3c805cd2a5b32e09ed8341a0ff9bbd
/md-sal/sal-test-model/src/main/yang-gen-sal/org/opendaylight/yang/gen/v1/urn/opendaylight/params/xml/ns/yang/controller/md/sal/test/augment/rev140709/RpcLeafOnlyAugmentBuilder.java
a8ebd471cef81184627f6928a43fc4d7ae64fb9a
[]
no_license
ycymio/opendaylight-adsal-controller
https://github.com/ycymio/opendaylight-adsal-controller
6247d6d4b2a11718932528f4873dc90844f6145d
c3d5164e990e5f95faf02594646c164c66759a23
refs/heads/master
2021-01-11T09:05:36.364000
2016-12-26T02:40:46
2016-12-26T02:40:46
77,222,077
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709; import org.opendaylight.yangtools.yang.binding.DataObject; /** * Class that builds {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment} instances. * * @see org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment */ public class RpcLeafOnlyAugmentBuilder { private java.lang.String _simpleValue; public RpcLeafOnlyAugmentBuilder() { } public RpcLeafOnlyAugmentBuilder(RpcLeafOnlyAugment base) { this._simpleValue = base.getSimpleValue(); } public java.lang.String getSimpleValue() { return _simpleValue; } public RpcLeafOnlyAugmentBuilder setSimpleValue(java.lang.String value) { this._simpleValue = value; return this; } public RpcLeafOnlyAugment build() { return new RpcLeafOnlyAugmentImpl(this); } private static final class RpcLeafOnlyAugmentImpl implements RpcLeafOnlyAugment { public java.lang.Class<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment> getImplementedInterface() { return org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment.class; } private final java.lang.String _simpleValue; private RpcLeafOnlyAugmentImpl(RpcLeafOnlyAugmentBuilder base) { this._simpleValue = base.getSimpleValue(); } @Override public java.lang.String getSimpleValue() { return _simpleValue; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_simpleValue == null) ? 0 : _simpleValue.hashCode()); return result; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (!(obj instanceof DataObject)) { return false; } if (!org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment.class.equals(((DataObject)obj).getImplementedInterface())) { return false; } org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment other = (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment)obj; if (_simpleValue == null) { if (other.getSimpleValue() != null) { return false; } } else if(!_simpleValue.equals(other.getSimpleValue())) { return false; } return true; } @Override public java.lang.String toString() { java.lang.StringBuilder builder = new java.lang.StringBuilder ("RpcLeafOnlyAugment ["); boolean first = true; if (_simpleValue != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_simpleValue="); builder.append(_simpleValue); } return builder.append(']').toString(); } } }
UTF-8
Java
3,690
java
RpcLeafOnlyAugmentBuilder.java
Java
[]
null
[]
package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709; import org.opendaylight.yangtools.yang.binding.DataObject; /** * Class that builds {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment} instances. * * @see org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment */ public class RpcLeafOnlyAugmentBuilder { private java.lang.String _simpleValue; public RpcLeafOnlyAugmentBuilder() { } public RpcLeafOnlyAugmentBuilder(RpcLeafOnlyAugment base) { this._simpleValue = base.getSimpleValue(); } public java.lang.String getSimpleValue() { return _simpleValue; } public RpcLeafOnlyAugmentBuilder setSimpleValue(java.lang.String value) { this._simpleValue = value; return this; } public RpcLeafOnlyAugment build() { return new RpcLeafOnlyAugmentImpl(this); } private static final class RpcLeafOnlyAugmentImpl implements RpcLeafOnlyAugment { public java.lang.Class<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment> getImplementedInterface() { return org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment.class; } private final java.lang.String _simpleValue; private RpcLeafOnlyAugmentImpl(RpcLeafOnlyAugmentBuilder base) { this._simpleValue = base.getSimpleValue(); } @Override public java.lang.String getSimpleValue() { return _simpleValue; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_simpleValue == null) ? 0 : _simpleValue.hashCode()); return result; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (!(obj instanceof DataObject)) { return false; } if (!org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment.class.equals(((DataObject)obj).getImplementedInterface())) { return false; } org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment other = (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.RpcLeafOnlyAugment)obj; if (_simpleValue == null) { if (other.getSimpleValue() != null) { return false; } } else if(!_simpleValue.equals(other.getSimpleValue())) { return false; } return true; } @Override public java.lang.String toString() { java.lang.StringBuilder builder = new java.lang.StringBuilder ("RpcLeafOnlyAugment ["); boolean first = true; if (_simpleValue != null) { if (first) { first = false; } else { builder.append(", "); } builder.append("_simpleValue="); builder.append(_simpleValue); } return builder.append(']').toString(); } } }
3,690
0.617615
0.601355
102
35.176472
45.944855
275
false
false
0
0
0
0
0
0
0.303922
false
false
10
802ca952eba18e55d0a11b4680b817d922c094a6
12,395,275,634,614
b5ecffb7142b0658ff180dc28dde20b3417551a4
/DZbusness/src/main/java/com/lbd/dz/lbdapp/service/JphOrderAppService.java
d3ab787be0a18ae9b31016c0c3135562e4eda1e4
[]
no_license
mm114249/dzRep
https://github.com/mm114249/dzRep
687c7a5057aad4ee7b1c81454df1e5d632992084
3278dda35bc90ea09238839ab402275e8062db30
refs/heads/master
2016-09-06T17:50:15.909000
2015-07-28T01:08:11
2015-07-28T01:08:11
39,805,747
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lbd.dz.lbdapp.service; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.ui.Model; public interface JphOrderAppService { //接收app传过来的json数据进行解析 //订单确认 public Map<String, Object> addOrderinfo(String json) throws Exception; //订单状态改变 public Map<String,Object> updateOrderState(String json)throws Exception; //获取订单列表 public Map<String,Object> getOrderMap(String json)throws Exception; //获取订单详情 public Map<String,Object>getOrderDetails(String json)throws Exception; //根据订单状态获取订单数量 public Map<String, List<Integer>> getOrderManage4State(HttpServletRequest request,HttpServletResponse response)throws Exception; public List<Integer> getSaleOrderManage4State(HttpServletRequest request,HttpServletResponse response)throws Exception; //生成支付码,订单更新 public Map<String,Object> updateOrder(String json)throws Exception; //获取二级平台订单列表(seller) public String getSencondOrderList(HttpServletRequest request,HttpServletResponse response)throws Exception; //修改订单价钱(运费,减现) public Map<String,Object> updateOrderPrice(String json)throws Exception; //到订单价钱修改页面 public void toUpdateOrderPrice(HttpServletRequest request,Model model)throws Exception; //获取评论信息 public Map<String,Object> getCon(HttpServletRequest request)throws Exception; //获取评论信息 public Map<String,Object> getComment(HttpServletRequest request)throws Exception; //常用订单 public Map<String,Object> getCommonOrder(HttpServletRequest request)throws Exception; //付款 public int pay(HttpServletRequest request)throws Exception; //获取联系人列表 public Map<String,Object> getContactList(HttpServletRequest request)throws Exception; //修改联系人 public Map<String,Object> updateContact(HttpServletRequest request)throws Exception; //新增联系人 public Map<String,Object> addContact(HttpServletRequest request)throws Exception; }
UTF-8
Java
2,157
java
JphOrderAppService.java
Java
[]
null
[]
package com.lbd.dz.lbdapp.service; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.ui.Model; public interface JphOrderAppService { //接收app传过来的json数据进行解析 //订单确认 public Map<String, Object> addOrderinfo(String json) throws Exception; //订单状态改变 public Map<String,Object> updateOrderState(String json)throws Exception; //获取订单列表 public Map<String,Object> getOrderMap(String json)throws Exception; //获取订单详情 public Map<String,Object>getOrderDetails(String json)throws Exception; //根据订单状态获取订单数量 public Map<String, List<Integer>> getOrderManage4State(HttpServletRequest request,HttpServletResponse response)throws Exception; public List<Integer> getSaleOrderManage4State(HttpServletRequest request,HttpServletResponse response)throws Exception; //生成支付码,订单更新 public Map<String,Object> updateOrder(String json)throws Exception; //获取二级平台订单列表(seller) public String getSencondOrderList(HttpServletRequest request,HttpServletResponse response)throws Exception; //修改订单价钱(运费,减现) public Map<String,Object> updateOrderPrice(String json)throws Exception; //到订单价钱修改页面 public void toUpdateOrderPrice(HttpServletRequest request,Model model)throws Exception; //获取评论信息 public Map<String,Object> getCon(HttpServletRequest request)throws Exception; //获取评论信息 public Map<String,Object> getComment(HttpServletRequest request)throws Exception; //常用订单 public Map<String,Object> getCommonOrder(HttpServletRequest request)throws Exception; //付款 public int pay(HttpServletRequest request)throws Exception; //获取联系人列表 public Map<String,Object> getContactList(HttpServletRequest request)throws Exception; //修改联系人 public Map<String,Object> updateContact(HttpServletRequest request)throws Exception; //新增联系人 public Map<String,Object> addContact(HttpServletRequest request)throws Exception; }
2,157
0.823683
0.82264
50
37.34
36.836727
129
false
false
0
0
0
0
0
0
1.58
false
false
10
ad081c50815c99ec4421b35e0ed3318af51af7cd
12,738,873,036,096
73f2372b96db0e359c6571e0a221a44e05b44f71
/JUnitTesting/src/main/java/com/fil/junit/JUnitTesting/App.java
1ff0b236e4de594812d679b46c5cd0eeb1387eb7
[]
no_license
DhruvamSharma/EclipseWorkSpace
https://github.com/DhruvamSharma/EclipseWorkSpace
82fea9a7fece6d25eaeced71dbd4df81a56113e5
cf272adf90ace6c70efc61c95466900d182e337a
refs/heads/master
2020-03-22T14:23:37.229000
2018-07-24T18:19:40
2018-07-24T18:19:40
140,175,828
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fil.junit.JUnitTesting; import java.math.BigInteger; /** * Hello world! * */ public class App { public void multiply() { BigInteger integer1 = BigInteger.valueOf(976452739); BigInteger integer2 = BigInteger.valueOf(9999999); BigInteger integer = integer1.multiply(integer2).multiply(integer2); //dhruvam sharma } }
UTF-8
Java
347
java
App.java
Java
[ { "context": "teger1.multiply(integer2).multiply(integer2);\n\t\t//dhruvam sharma \n\n\t}\n\n}\n", "end": 338, "score": 0.8898475766181946, "start": 324, "tag": "NAME", "value": "dhruvam sharma" } ]
null
[]
package com.fil.junit.JUnitTesting; import java.math.BigInteger; /** * Hello world! * */ public class App { public void multiply() { BigInteger integer1 = BigInteger.valueOf(976452739); BigInteger integer2 = BigInteger.valueOf(9999999); BigInteger integer = integer1.multiply(integer2).multiply(integer2); //<NAME> } }
339
0.726225
0.665706
20
16.35
20.909986
70
false
false
0
0
0
0
0
0
0.75
false
false
9
71fb5996f0d4111dd8d5311b7c170355139bef6d
6,528,350,355,177
9d91c647656a9ee9252bd94dcf4b9788d4897385
/Project/com.example.xlgame.XLGame/src/com/example/xlgame/MainActivity.java
2cf83404839e3dd9ed6c7a8843677500a88c3103
[]
no_license
xtreme-adrian-carolli/darkwata
https://github.com/xtreme-adrian-carolli/darkwata
f303229689fcb8cbda739fe8acbca51abbb3e139
44360f6dfb84f2ad781ea97dd4f2b7b6de885a43
refs/heads/master
2020-05-21T01:09:15.792000
2012-09-28T22:33:24
2012-09-28T22:33:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.xlgame; import Views.MainGamePanel; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.Window; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Remove title bar this.requestWindowFeature(Window.FEATURE_NO_TITLE); //Set the main view setContentView(new MainGamePanel(this)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
UTF-8
Java
674
java
MainActivity.java
Java
[]
null
[]
package com.example.xlgame; import Views.MainGamePanel; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.Window; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Remove title bar this.requestWindowFeature(Window.FEATURE_NO_TITLE); //Set the main view setContentView(new MainGamePanel(this)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
674
0.68546
0.68546
29
22.241379
19.466425
62
false
false
0
0
0
0
0
0
0.413793
false
false
9
5230c3015beee8b94c35d21399025eb97c756ff2
8,881,992,388,781
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
/benchmark/validation/org/apache/ignite/internal/processors/cache/IgniteBinaryObjectFieldsQuerySelfTest.java
0739b7be65ee60e8ddd475c6142d5d03ba954658
[]
no_license
STAMP-project/dspot-experiments
https://github.com/STAMP-project/dspot-experiments
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
121487e65cdce6988081b67f21bbc6731354a47f
refs/heads/master
2023-02-07T14:40:12.919000
2019-11-06T07:17:09
2019-11-06T07:17:09
75,710,758
14
19
null
false
2023-01-26T23:57:41
2016-12-06T08:27:42
2022-02-18T17:43:31
2023-01-26T23:57:40
651,434
12
14
5
null
false
false
/** * 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.ignite.internal.processors.cache; import CacheAtomicityMode.ATOMIC; import CacheAtomicityMode.TRANSACTIONAL; import CacheMode.PARTITIONED; import CacheMode.REPLICATED; import org.apache.ignite.binary.BinaryObject; import org.apache.ignite.lang.IgniteBiPredicate; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; /** * Tests that server nodes do not need class definitions to execute queries. */ public class IgniteBinaryObjectFieldsQuerySelfTest extends GridCommonAbstractTest { /** * */ public static final String PERSON_KEY_CLS_NAME = "org.apache.ignite.tests.p2p.cache.PersonKey"; /** * Grid count. */ public static final int GRID_CNT = 4; /** * */ private static ClassLoader extClassLoader; /** * * * @throws Exception * If failed. */ @Test public void testQueryPartitionedAtomic() throws Exception { checkQuery(PARTITIONED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testQueryReplicatedAtomic() throws Exception { checkQuery(REPLICATED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testQueryPartitionedTransactional() throws Exception { checkQuery(PARTITIONED, TRANSACTIONAL); } /** * * * @throws Exception * If failed. */ @Test public void testQueryReplicatedTransactional() throws Exception { checkQuery(REPLICATED, TRANSACTIONAL); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryPartitionedAtomic() throws Exception { checkFieldsQuery(PARTITIONED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryReplicatedAtomic() throws Exception { checkFieldsQuery(REPLICATED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryPartitionedTransactional() throws Exception { checkFieldsQuery(PARTITIONED, TRANSACTIONAL); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryReplicatedTransactional() throws Exception { checkFieldsQuery(REPLICATED, TRANSACTIONAL); } /** * */ private static class PersonKeyFilter implements IgniteBiPredicate<BinaryObject, BinaryObject> { /** * Max ID allowed. */ private int maxId; /** * * * @param maxId * Max ID allowed. */ public PersonKeyFilter(int maxId) { this.maxId = maxId; } /** * {@inheritDoc } */ @Override public boolean apply(BinaryObject key, BinaryObject val) { return (key.<Integer>field("id")) <= (maxId); } } }
UTF-8
Java
3,904
java
IgniteBinaryObjectFieldsQuerySelfTest.java
Java
[]
null
[]
/** * 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.ignite.internal.processors.cache; import CacheAtomicityMode.ATOMIC; import CacheAtomicityMode.TRANSACTIONAL; import CacheMode.PARTITIONED; import CacheMode.REPLICATED; import org.apache.ignite.binary.BinaryObject; import org.apache.ignite.lang.IgniteBiPredicate; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; /** * Tests that server nodes do not need class definitions to execute queries. */ public class IgniteBinaryObjectFieldsQuerySelfTest extends GridCommonAbstractTest { /** * */ public static final String PERSON_KEY_CLS_NAME = "org.apache.ignite.tests.p2p.cache.PersonKey"; /** * Grid count. */ public static final int GRID_CNT = 4; /** * */ private static ClassLoader extClassLoader; /** * * * @throws Exception * If failed. */ @Test public void testQueryPartitionedAtomic() throws Exception { checkQuery(PARTITIONED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testQueryReplicatedAtomic() throws Exception { checkQuery(REPLICATED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testQueryPartitionedTransactional() throws Exception { checkQuery(PARTITIONED, TRANSACTIONAL); } /** * * * @throws Exception * If failed. */ @Test public void testQueryReplicatedTransactional() throws Exception { checkQuery(REPLICATED, TRANSACTIONAL); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryPartitionedAtomic() throws Exception { checkFieldsQuery(PARTITIONED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryReplicatedAtomic() throws Exception { checkFieldsQuery(REPLICATED, ATOMIC); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryPartitionedTransactional() throws Exception { checkFieldsQuery(PARTITIONED, TRANSACTIONAL); } /** * * * @throws Exception * If failed. */ @Test public void testFieldsQueryReplicatedTransactional() throws Exception { checkFieldsQuery(REPLICATED, TRANSACTIONAL); } /** * */ private static class PersonKeyFilter implements IgniteBiPredicate<BinaryObject, BinaryObject> { /** * Max ID allowed. */ private int maxId; /** * * * @param maxId * Max ID allowed. */ public PersonKeyFilter(int maxId) { this.maxId = maxId; } /** * {@inheritDoc } */ @Override public boolean apply(BinaryObject key, BinaryObject val) { return (key.<Integer>field("id")) <= (maxId); } } }
3,904
0.622951
0.621414
164
22.79878
24.890291
99
true
false
0
0
0
0
0
0
0.341463
false
false
9
ed2c59e3621a522989c0410985b192e71e6f596a
9,491,877,772,506
ca14899a50302ef3cb6de9b42b7669d8cec00e95
/src/cn/sevenyuan/dynamicprogramming/LengthOfLIS.java
7426d5a0a68bf324acc41c067c779361a72d8adc
[]
no_license
Vip-Augus/algorithm-learning-note
https://github.com/Vip-Augus/algorithm-learning-note
587691861aafd160c0894b74d187d761c39e6bf1
d55fad9f9de9f14a33b1743c7b8de83cfd357752
refs/heads/master
2022-12-10T20:39:04.471000
2022-12-04T09:14:48
2022-12-04T09:14:48
249,011,450
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.sevenyuan.dynamicprogramming; import java.util.Arrays; /** * 最长增长序列的长度 * * https://leetcode-cn.com/problems/longest-increasing-subsequence/submissions/ * * @author JingQ at 9/20/20 */ public class LengthOfLIS { public static void main(String[] args) { int[] nums = new int[] {10,9,2,5,3,7,101,18}; System.out.println(lengthOfLIS(nums)); System.out.println(lengthOfLISByBS(nums)); } public static int lengthOfLIS(int[] nums) { // 考虑边界值 if (nums == null || nums.length == 0) { return 0; } int size = nums.length; int[] dp = new int[size]; // base case Arrays.fill(dp, 1); // 状态转移工程 // dp[i] 的定义:以 nums[i] 结尾,最长的递增子序列 // 理解:dp[5] 依赖于 dp[0..4] 中,确认比 nums[5] 小,所以 dp[5] 的最长子序列长度基于前面的结果 + 1 for (int i = 1; i < size; ++i) { for (int j = 0; j < i; ++j) { // 状态判断,固定最后一位,从前到后判断,如果 nums[i] 比前面的要大,取已比较过的「最长子序列」,还有 dp[j] + 1,取最大值 if (nums[i] > nums[j]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } } int max = 1; for (int temp : dp) { max = Math.max(max, temp); } return max; } public static int lengthOfLISByBS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } // 使用了二分查找来找,poker 扑克牌原理,牌堆初始化为 0 int piles = 0; int[] tops = new int[nums.length]; for (int poker : nums) { int left = 0 , right = piles; while (left < right) { int mid = left + (right - left) / 2; if (tops[mid] >= poker) { right = mid; } else if (tops[mid] < poker) { left = mid + 1; } } // 没有找到合适的牌堆,新建一个 if (left == piles) ++piles; // 将这张牌放到牌堆顶 tops[left] = poker; } return piles; } }
UTF-8
Java
2,353
java
LengthOfLIS.java
Java
[ { "context": "-increasing-subsequence/submissions/\n *\n * @author JingQ at 9/20/20\n */\npublic class LengthOfLIS {\n\n pu", "end": 187, "score": 0.8783839344978333, "start": 182, "tag": "USERNAME", "value": "JingQ" } ]
null
[]
package cn.sevenyuan.dynamicprogramming; import java.util.Arrays; /** * 最长增长序列的长度 * * https://leetcode-cn.com/problems/longest-increasing-subsequence/submissions/ * * @author JingQ at 9/20/20 */ public class LengthOfLIS { public static void main(String[] args) { int[] nums = new int[] {10,9,2,5,3,7,101,18}; System.out.println(lengthOfLIS(nums)); System.out.println(lengthOfLISByBS(nums)); } public static int lengthOfLIS(int[] nums) { // 考虑边界值 if (nums == null || nums.length == 0) { return 0; } int size = nums.length; int[] dp = new int[size]; // base case Arrays.fill(dp, 1); // 状态转移工程 // dp[i] 的定义:以 nums[i] 结尾,最长的递增子序列 // 理解:dp[5] 依赖于 dp[0..4] 中,确认比 nums[5] 小,所以 dp[5] 的最长子序列长度基于前面的结果 + 1 for (int i = 1; i < size; ++i) { for (int j = 0; j < i; ++j) { // 状态判断,固定最后一位,从前到后判断,如果 nums[i] 比前面的要大,取已比较过的「最长子序列」,还有 dp[j] + 1,取最大值 if (nums[i] > nums[j]) { dp[i] = Math.max(dp[i], dp[j] + 1); } } } int max = 1; for (int temp : dp) { max = Math.max(max, temp); } return max; } public static int lengthOfLISByBS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } // 使用了二分查找来找,poker 扑克牌原理,牌堆初始化为 0 int piles = 0; int[] tops = new int[nums.length]; for (int poker : nums) { int left = 0 , right = piles; while (left < right) { int mid = left + (right - left) / 2; if (tops[mid] >= poker) { right = mid; } else if (tops[mid] < poker) { left = mid + 1; } } // 没有找到合适的牌堆,新建一个 if (left == piles) ++piles; // 将这张牌放到牌堆顶 tops[left] = poker; } return piles; } }
2,353
0.457452
0.43876
72
27.236111
19.846979
87
false
false
0
0
0
0
0
0
0.583333
false
false
9
6bffbfadc0b982f341bbdc80145278f9fb377649
28,192,165,353,465
c8766a5160770bb440d5ffb386e9723288399ceb
/TeamProject/src/board/svc/Service.java
67c7eee67a1fd6604593536b03850c1cc832bd08
[]
no_license
dnjsrud3407/TeemProject
https://github.com/dnjsrud3407/TeemProject
06c8fc6969701c4b3e118e089a2e333e29c90d90
02c67d3253713aa15e8ccb2280b0544cfb88584d
refs/heads/master
2022-12-09T22:18:47.526000
2020-04-24T02:06:49
2020-04-24T02:06:49
240,448,436
0
2
null
false
2022-12-05T11:52:59
2020-02-14T07:05:35
2020-04-24T02:06:55
2022-12-05T11:52:57
21,743
0
2
15
Java
false
false
package board.svc; public class Service { }
UTF-8
Java
46
java
Service.java
Java
[]
null
[]
package board.svc; public class Service { }
46
0.717391
0.717391
5
8.2
9.724196
22
false
false
0
0
0
0
0
0
0.2
false
false
9
c323b740f8abd1226796a24cda55ecb65a761f25
1,984,274,912,218
568a47260c1cb3503a58c41bc0bc4f1ffd7debf7
/src/main/java/com.study/basics/multiThread/threadPool/threadPoolIIIII.java
bd462cdcb2ba7a84fe6917726877b3074187bacd
[]
no_license
549819221/study
https://github.com/549819221/study
70f6dcf6929e73d5e70d02432e63dd6e348a06ac
0ba3db1d65e43900e974df14eda2deac1fa1025b
refs/heads/master
2021-06-08T03:27:25.660000
2021-05-28T07:45:49
2021-05-28T07:45:49
162,812,300
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.study.basics.multiThread.threadPool; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * submit()和 execute()方法的区别 */ public class threadPoolIIIII { public static void execute() { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) { final int index = i; executorService.execute(() -> System.out.println(Thread.currentThread().getName() + "-" + index)); } executorService.shutdown(); } public static void submit() { List<Future<String>> res = new ArrayList<>(); Date startDate = new Date(); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int ind = i; Future<String> submit = executorService.submit(() -> { try { Thread.sleep( ind * 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ind + " --> return String...."); return "结果:" + ind; }); res.add(submit); } res.forEach(r -> { try { System.out.println("返回值->" + r.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }); System.out.println("=================>共耗时"+(System.currentTimeMillis() - startDate.getTime())+"毫秒"); } public static void main(String[] args) { //execute(); submit(); } }
UTF-8
Java
1,919
java
threadPoolIIIII.java
Java
[]
null
[]
package com.study.basics.multiThread.threadPool; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * submit()和 execute()方法的区别 */ public class threadPoolIIIII { public static void execute() { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) { final int index = i; executorService.execute(() -> System.out.println(Thread.currentThread().getName() + "-" + index)); } executorService.shutdown(); } public static void submit() { List<Future<String>> res = new ArrayList<>(); Date startDate = new Date(); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int ind = i; Future<String> submit = executorService.submit(() -> { try { Thread.sleep( ind * 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(ind + " --> return String...."); return "结果:" + ind; }); res.add(submit); } res.forEach(r -> { try { System.out.println("返回值->" + r.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }); System.out.println("=================>共耗时"+(System.currentTimeMillis() - startDate.getTime())+"毫秒"); } public static void main(String[] args) { //execute(); submit(); } }
1,919
0.541645
0.53687
59
30.932203
24.374107
110
false
false
0
0
0
0
0
0
0.559322
false
false
9
f5734550261859f71f6007a8410399ab9b1d13b0
15,341,623,201,239
8d3b0b5796cf00028fe49057916584572af492ec
/demo1/src/main/java/com/bankapplication/customer/Customer.java
5e7d5895e3b7ea102df21d120282d67916493c98
[]
no_license
vishnubalan19/demo1
https://github.com/vishnubalan19/demo1
5b5d13747dbfeb5f8c7e7dd0d5fa1b4c654c1997
ca54920893d98395a46fbf54d481eb351d5f5948
refs/heads/main
2023-07-13T17:10:10.126000
2021-08-26T13:22:50
2021-08-26T13:22:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bankapplication.customer; //Customer is the pojo class. public class Customer{ private int customerId; private String name; private long mobileNo; public void setCustomerId(int customerId){ this.customerId = customerId; } public void setName(String name){ this.name = name; } public void setMobileNo(long mobileNo){ this.mobileNo = mobileNo; } public int getCustomerId(){ return customerId; } public String getName(){ return name; } public long getMobileNo() { return mobileNo; } @Override public String toString(){ return this.getName()+" "+this.getCustomerId()+" "+this.getMobileNo(); } }
UTF-8
Java
750
java
Customer.java
Java
[]
null
[]
package com.bankapplication.customer; //Customer is the pojo class. public class Customer{ private int customerId; private String name; private long mobileNo; public void setCustomerId(int customerId){ this.customerId = customerId; } public void setName(String name){ this.name = name; } public void setMobileNo(long mobileNo){ this.mobileNo = mobileNo; } public int getCustomerId(){ return customerId; } public String getName(){ return name; } public long getMobileNo() { return mobileNo; } @Override public String toString(){ return this.getName()+" "+this.getCustomerId()+" "+this.getMobileNo(); } }
750
0.614667
0.614667
31
22.258064
16.339085
72
false
false
0
0
0
0
0
0
0.483871
false
false
9
b785df6fae22cd05e7de17cfca4cd29f961255eb
6,073,083,787,520
8ee9d6cfb089c16de99e36503a870f33fd71b9d0
/sk-compiler/src/main/java/sk/di/SKDILibraryCreate.java
09790a535e3d70de974db1005940bca32b958d5a
[]
no_license
dugufei/sky
https://github.com/dugufei/sky
e665b5649e85db9bdf35c3c8c0ae8a9f82b0fe10
254f91283352384ed44573c73d1929d17887bdec
refs/heads/master
2020-05-15T02:29:41.534000
2019-04-18T08:45:40
2019-04-18T08:45:40
182,050,064
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sk.di; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import sk.di.model.SKConstructorsModel; import sk.di.model.SKDILibraryModel; import sk.di.model.SKInputClassModel; import sk.di.model.SKInputModel; import sk.di.model.SKParamProviderModel; import sk.di.model.SKProviderModel; import sk.di.model.SKSourceModel; import sky.SKSingleton; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static sk.di.SKUtils.lowerCase; import static sk.di.SkConsts.COLLECTIONS; import static sk.di.SkConsts.FACADE_PACKAGE; import static sk.di.SkConsts.INPUT_IMPL; import static sk.di.SkConsts.MAP; import static sk.di.SkConsts.NAME_INPUT; import static sk.di.SkConsts.NAME_INPUT_IMPL; import static sk.di.SkConsts.NAME_LIBRARY; import static sk.di.SkConsts.NAME_LIBRARY_PROVIDERS; import static sk.di.SkConsts.NAME_LIBRARY_PROVIDERS_OPEN; import static sk.di.SkConsts.NAME_PROVIDER; import static sk.di.SkConsts.PROVIDER; import static sk.di.SkConsts.SK_COMMOM_PROVIDER; import static sk.di.SkConsts.SK_DC; import static sk.di.SkConsts.SK_DEFAULT_PROVIDER; import static sk.di.SkConsts.SK_DI; import static sk.di.SkConsts.SK_HELPER; import static sk.di.SkConsts.SK_INPUTS; import static sk.di.SkConsts.SK_I_PROVIDER; import static sk.di.SkConsts.SK_MANAGE_INTERFACE; import static sk.di.SkConsts.SK_MAP; import static sk.di.SkConsts.WARNING_TIPS; /** * @author sky * @version 1.0 on 2018-07-05 上午10:42 * @see SKDILibraryCreate */ class SKDILibraryCreate { Map<String, SKProviderModel> skProviderModels; Map<TypeElement, SKInputClassModel> skInputModels; Map<String, SKSourceModel> skSourceModelMap; SKDILibraryModel skLibraryModel; public JavaFile brewDILibrary(Map<String, SKProviderModel> skProviderModels, Map<TypeElement, SKInputClassModel> skInputModels, Map<String, SKSourceModel> skSourceModelMap, SKDILibraryModel skLibraryModel) { String packageName = "sk"; this.skProviderModels = skProviderModels; this.skInputModels = skInputModels; this.skSourceModelMap = skSourceModelMap; this.skLibraryModel = skLibraryModel; return JavaFile.builder(packageName, createClassDILibrary(packageName)).addFileComment("Generated code from Sk. Do not modify!").build(); } private TypeSpec createClassDILibrary(String packageName) { ClassName currentClassName = ClassName.get(packageName, skLibraryModel.name + NAME_LIBRARY); ClassName builderName = ClassName.get("", "Builder"); TypeSpec.Builder skdiBuilder = TypeSpec.classBuilder(currentClassName); skdiBuilder.addJavadoc(WARNING_TIPS); skdiBuilder.addModifiers(PUBLIC, FINAL); // 创建属性 builder skdiBuilder.addField(builderName, "builder"); // 初始化方法 MethodSpec.Builder initialize = MethodSpec.methodBuilder("initialize").addModifiers(Modifier.PRIVATE).addParameter(builderName, "builder"); initialize.addStatement("this.builder = builder"); HashMap<String, ParameterizedTypeName> singleSKDIProvider = new HashMap<>(); for (SKInputClassModel item : skInputModels.values()) { HashMap<String, ParameterizedTypeName> singleImplProvider = new HashMap<>(); HashMap<String, ClassName> singleImplSource = new HashMap<>(); String inputNameImpl = item.className.simpleName() + NAME_INPUT_IMPL; ClassName inputClassNameImpl = ClassName.get("", inputNameImpl); TypeSpec.Builder builderInput = TypeSpec.classBuilder(inputClassNameImpl); builderInput.addModifiers(PRIVATE, FINAL); builderInput.addSuperinterface(ParameterizedTypeName.get(SK_MANAGE_INTERFACE, item.className)); // 构造函数 MethodSpec.Builder clazzConstructors = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE); // 重写方法 MethodSpec.Builder clazzOverride = MethodSpec.methodBuilder("input").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class); clazzOverride.addParameter(item.className, lowerCase(item.className.simpleName())); clazzOverride.addStatement("input$T($N)", item.className, lowerCase(item.className.simpleName())); builderInput.addMethod(clazzOverride.build()); // 初始化方法 MethodSpec.Builder initializeImpl = MethodSpec.methodBuilder("initialize").addModifiers(Modifier.PRIVATE); // 初始化方法2 MethodSpec.Builder clazzInput = MethodSpec.methodBuilder("input" + item.className.simpleName()).addModifiers(Modifier.PRIVATE).returns(item.className); clazzInput.addParameter(item.className, "instance"); // 注入 for (SKInputModel skInputModel : item.skInputModels) { // 注入属性 if (skInputModel.skProviderModel == null) { skInputModel.skProviderModel = skProviderModels.get(skInputModel.providerKey); if (skInputModel.skProviderModel == null) { skInputModel.skProviderModel = skLibraryModel.skProviderModels.get(skInputModel.providerKey); } } if (skInputModel.skProviderModel == null) { continue; } // 初始化 initProvider(skInputModel.skProviderModel, clazzConstructors, skdiBuilder, builderInput, initialize, initializeImpl, singleSKDIProvider, singleImplProvider, singleImplSource); // 注入类名 String providerName = lowerCase(skInputModel.skProviderModel.getClassName(PROVIDER)); String inputClass = skInputModel.className.simpleName() + NAME_INPUT; ClassName inputClassName = ClassName.get(skInputModel.packageName, inputClass); if (skInputModel.isLazy) { clazzInput.addStatement("$T.input$N(instance, $T.lazy($N))", inputClassName, skInputModel.methodName, SK_DC, providerName); } else { clazzInput.addStatement("$T.input$N(instance, $N.get())", inputClassName, skInputModel.methodName, providerName); } } // 构造函数 clazzConstructors.addStatement("initialize()"); builderInput.addMethod(clazzConstructors.build()); clazzInput.addStatement("return instance"); builderInput.addMethod(initializeImpl.build()); builderInput.addMethod(clazzInput.build()); skdiBuilder.addType(builderInput.build()); // 初始化注入类 String nameInputImpl = item.className.simpleName() + INPUT_IMPL; skdiBuilder.addField(ParameterizedTypeName.get(SK_I_PROVIDER, inputClassNameImpl), nameInputImpl, PRIVATE); TypeSpec.Builder comparatorImpl = TypeSpec.anonymousClassBuilder(""); comparatorImpl.addSuperinterface(ParameterizedTypeName.get(SK_I_PROVIDER, inputClassNameImpl)); comparatorImpl.addMethod(MethodSpec.methodBuilder("get").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(inputClassNameImpl) .addStatement("return new $T()", inputClassNameImpl).build()); initialize.addStatement("this.$N = $L", nameInputImpl, comparatorImpl.build()); } // 创建内部类 builder TypeSpec.Builder builder = TypeSpec.classBuilder(builderName); builder.addModifiers(PUBLIC, FINAL, STATIC); // 构造方法 MethodSpec.Builder builderConstructors = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE); builder.addMethod(builderConstructors.build()); MethodSpec.Builder builderConstructorsMethod = MethodSpec.methodBuilder("build").addModifiers(Modifier.PUBLIC).returns(currentClassName); HashMap<String, SKConstructorsModel> singleConsProvider = new HashMap<>(); for (SKSourceModel item : skSourceModelMap.values()) { if (item.isSingle || item.isSingleGenerate) { String name = lowerCase(item.className.simpleName()); // 构造函数 if (item.skConstructorsModelList == null) { builder.addField(item.className, name); builderConstructorsMethod.addStatement("if($N == null)this.$N = new $T()", name, name, item.className); } else { CodeBlock.Builder consCodeBlock = null; for (SKConstructorsModel skConstructorsModel : item.skConstructorsModelList) { SKConstructorsModel temp = singleConsProvider.get(skConstructorsModel.className.reflectionName()); String consName = lowerCase(skConstructorsModel.className.simpleName()); if (consCodeBlock == null) { consCodeBlock = CodeBlock.builder(); consCodeBlock.add("$N", consName); } else { consCodeBlock.add(",$N", consName); } if (temp != null) { continue; } builder.addField(skConstructorsModel.className, consName, PRIVATE); // 增加赋值方法 builder.addMethod(addEqualMethod(builderName, skConstructorsModel.className, skConstructorsModel.className.simpleName())); singleConsProvider.put(skConstructorsModel.className.reflectionName(), skConstructorsModel); } builder.addField(item.className, name); if (item.classNameLibrary != null) { builderConstructorsMethod.addParameter(item.className, name); builderConstructorsMethod.addStatement("this.$N = $N", name, name); continue; } if (consCodeBlock == null) { builderConstructorsMethod.addStatement("if($N == null)this.$N = new $T()", name, name, item.className); } else { builderConstructorsMethod.addStatement("if($N == null)this.$N = new $T($N)", name, name, item.className, consCodeBlock.build().toString()); } } // 增加赋值方法 builder.addMethod(addEqualMethod(builderName, item.className, item.className.simpleName())); } } // 添加是否library初始化 String initFieldName = "isInit"; String initMethodName = "setInit"; builder.addField(boolean.class, initFieldName, PRIVATE); MethodSpec.Builder isInitBuilder = MethodSpec.methodBuilder(initMethodName).returns(builderName).addModifiers(PUBLIC).addParameter(boolean.class, initFieldName); isInitBuilder.addStatement("this.$N = $N", initFieldName, initFieldName); isInitBuilder.addStatement("return this"); builder.addMethod(isInitBuilder.build()); builderConstructorsMethod.addStatement("return new $T(this)", currentClassName); builder.addMethod(builderConstructorsMethod.build()); skdiBuilder.addType(builder.build()); // 创建内部方法 builder MethodSpec.Builder builderMethod = MethodSpec.methodBuilder("builder").addModifiers(Modifier.PUBLIC, STATIC).returns(builderName); builderMethod.addStatement("return new $T()", builderName); skdiBuilder.addMethod(builderMethod.build()); // 构造方法 MethodSpec.Builder constructors = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE); constructors.addParameter(builderName, "builder"); constructors.addStatement("initialize(builder)"); if (skLibraryModel.isSKDefaultLibrary) { initialize.addStatement("$T.skDefaultManager = iSKProvider.get().manage()", SK_HELPER); } initialize.addStatement("if(this.builder.$N) $T.inputDispatching(newSKDispatchingInput())", initFieldName, SK_INPUTS); skdiBuilder.addMethod(initialize.build()); skdiBuilder.addMethod(constructors.build()); TypeName wildcard = WildcardTypeName.subtypeOf(Object.class); TypeName classOfAny = ParameterizedTypeName.get(ClassName.get(Class.class), wildcard); // map集合 TypeName interfaceSK = ParameterizedTypeName.get(SK_MANAGE_INTERFACE, wildcard); TypeName providerSK = ParameterizedTypeName.get(SK_I_PROVIDER, interfaceSK); String mapBuilderName = "getMapOfClassOfSKProvider"; MethodSpec.Builder mapBuilder = MethodSpec.methodBuilder(mapBuilderName).returns(ParameterizedTypeName.get(MAP, classOfAny, providerSK)); int size = skInputModels.values().size(); if (size == 1) { for (SKInputClassModel item : skInputModels.values()) { String inputNameImpl = item.className.simpleName() + INPUT_IMPL; mapBuilder.addStatement("return $T.<$T,$T>singletonMap($T.class,($T)$N)", COLLECTIONS, classOfAny, providerSK, item.className, SK_I_PROVIDER, inputNameImpl); } } else if (size > 1) { CodeBlock.Builder codeBlock = CodeBlock.builder().add("return $T.<$T,$T>newMapBuilder($L)", SK_MAP, classOfAny, providerSK, size); for (SKInputClassModel item : skInputModels.values()) { String inputNameImpl = item.className.simpleName() + INPUT_IMPL; codeBlock.add(".put($T.class,($T)$T.this.$N)", item.className, SK_I_PROVIDER, currentClassName, inputNameImpl); } mapBuilder.addStatement("$L.build()", codeBlock.build()); } else { mapBuilder.addStatement("return $T.<$T,$T>newMapBuilder($L).build()", SK_MAP, classOfAny, providerSK, size); } skdiBuilder.addMethod(mapBuilder.build()); // 动态注入方法 MethodSpec.Builder newSKDispatchingInputBuilder = MethodSpec.methodBuilder("newSKDispatchingInput").returns(SK_DI); newSKDispatchingInputBuilder.addStatement("return new $T($N(),$T.EMPTY_MAP)", SK_DI, mapBuilderName, COLLECTIONS); skdiBuilder.addMethod(newSKDispatchingInputBuilder.build()); return skdiBuilder.build(); } private void initProvider(SKProviderModel skProviderModel, MethodSpec.Builder clazzConstructors, TypeSpec.Builder skdiBuilder, TypeSpec.Builder builderInput, MethodSpec.Builder initialize, MethodSpec.Builder initializeImpl, HashMap<String, ParameterizedTypeName> singleSKDIProvider, HashMap<String, ParameterizedTypeName> singleImplProvider, HashMap<String, ClassName> singleImplSource) { // 根据返回结果找到对应的类 String providerName = lowerCase(skProviderModel.getClassName(PROVIDER)); ClassName providerClassName = ClassName.get(skProviderModel.packageName, skProviderModel.getClassName(NAME_PROVIDER)); // 创建属性 ParameterizedTypeName fieldProvider = ParameterizedTypeName.get(SK_I_PROVIDER, skProviderModel.returnType); if (skProviderModel.isSingle) { if (singleSKDIProvider.get(providerName) == null) { skdiBuilder.addField(fieldProvider, providerName, PRIVATE); CodeBlock.Builder initProvider = generateParams(skProviderModel.parameters, clazzConstructors, skdiBuilder, skdiBuilder, initialize, initialize, singleSKDIProvider, singleSKDIProvider, singleImplSource); initialize.addStatement("this.$N = $T.provider($T.create(builder.$N$N))", providerName, SK_DC, providerClassName, lowerCase(skProviderModel.className.simpleName()), initProvider.build().toString()); singleSKDIProvider.put(providerName, fieldProvider); } } else { if (singleImplProvider.get(providerName) == null) { if (singleSKDIProvider.get(providerName) == null) { builderInput.addField(fieldProvider, providerName, PRIVATE); CodeBlock.Builder initProvider = generateParams(skProviderModel.parameters, clazzConstructors, skdiBuilder, builderInput, initialize, initializeImpl, singleSKDIProvider, singleImplProvider, singleImplSource); // 来源 SKSourceModel skSourceModel = skSourceModelMap.get(skProviderModel.className.reflectionName()); // 添加来源属性 和 初始化 String sourceName = lowerCase(skSourceModel.className.simpleName()); if (skSourceModel.isSingle) { // 引用来源属性 initializeImpl.addStatement("this.$N = $T.create(builder.$N$N)", providerName, providerClassName, lowerCase(skProviderModel.className.simpleName()), initProvider.build().toString()); } else { if (initialize.equals(initializeImpl)) { skSourceModel.isSingleGenerate = true; initializeImpl.addStatement("this.$N = $T.create(builder.$N$N)", providerName, providerClassName, sourceName, initProvider.build().toString()); } else { if (singleImplSource.get(skSourceModel.className.reflectionName()) == null) { builderInput.addField(skSourceModel.className, sourceName, PRIVATE); clazzConstructors.addStatement("this.$N = new $T()", sourceName, skSourceModel.className); singleImplSource.put(skSourceModel.className.reflectionName(), skSourceModel.className); } initializeImpl.addStatement("this.$N = $T.create($N$N)", providerName, providerClassName, sourceName, initProvider.build().toString()); } } } singleImplProvider.put(providerName, fieldProvider); } } } private CodeBlock.Builder generateParams(List<SKParamProviderModel> parameters, MethodSpec.Builder clazzConstructors, TypeSpec.Builder skdiBuilder, TypeSpec.Builder builderInput, MethodSpec.Builder initialize, MethodSpec.Builder initializeImpl, HashMap<String, ParameterizedTypeName> singleSKDIProvider, HashMap<String, ParameterizedTypeName> singleImplProvider, HashMap<String, ClassName> singleImplSource) { CodeBlock.Builder builder = CodeBlock.builder(); for (SKParamProviderModel item : parameters) { // 寻找来源 ClassName providerName = (ClassName) item.classType; SKProviderModel skProviderModel = skProviderModels.get(providerName.reflectionName()); initProvider(skProviderModel, clazzConstructors, skdiBuilder, builderInput, initialize, initializeImpl, singleSKDIProvider, singleImplProvider, singleImplSource); builder.add(",$N", lowerCase(providerName.simpleName()) + PROVIDER); } return builder; } private MethodSpec addEqualMethod(ClassName returnName, ClassName parameName, String name) { String methodSourceName = "set" + name; MethodSpec.Builder setSource = MethodSpec.methodBuilder(methodSourceName).addModifiers(Modifier.PUBLIC).returns(returnName); setSource.addParameter(parameName, lowerCase(name)); setSource.addStatement("this.$N = $N", lowerCase(name), lowerCase(name)); setSource.addStatement("return this"); return setSource.build(); } public JavaFile brewDILibraryProvider() { return JavaFile.builder(FACADE_PACKAGE, createClassDILibraryProviders()).addFileComment("Generated code from Sk. Do not modify!").build(); } public JavaFile brewDILibraryProviderOpen() { return JavaFile.builder(FACADE_PACKAGE, createClassDILibraryProvidersOpen()).addFileComment("Generated code from Sk. Do not modify!").build(); } private TypeSpec createClassDILibraryProviders() { TypeSpec.Builder skdiBuilder = TypeSpec.classBuilder(skLibraryModel.name + NAME_LIBRARY_PROVIDERS); skdiBuilder.addJavadoc(WARNING_TIPS); skdiBuilder.addModifiers(PUBLIC, FINAL); for (SKProviderModel item : skProviderModels.values()) { if (!item.isClass) { continue; } MethodSpec.Builder providerBuilder = MethodSpec.methodBuilder(item.name).returns(item.returnType).addModifiers(Modifier.PUBLIC); providerBuilder.addStatement("return new $T()", item.returnType); if (item.isSingle) { providerBuilder.addAnnotation(SKSingleton.class); } skdiBuilder.addMethod(providerBuilder.build()); } return skdiBuilder.build(); } private TypeSpec createClassDILibraryProvidersOpen() { TypeSpec.Builder skdiBuilder = TypeSpec.interfaceBuilder(skLibraryModel.name + NAME_LIBRARY_PROVIDERS_OPEN); skdiBuilder.addJavadoc(WARNING_TIPS); skdiBuilder.addModifiers(PUBLIC); ClassName library = ClassName.get("sk", skLibraryModel.name + NAME_LIBRARY_PROVIDERS); MethodSpec.Builder providerBuilder = MethodSpec.methodBuilder(lowerCase(skLibraryModel.name) + NAME_LIBRARY_PROVIDERS).returns(library).addModifiers(PUBLIC, ABSTRACT); skdiBuilder.addMethod(providerBuilder.build()); HashMap<String, String> isCheck = new HashMap<>(); for (SKProviderModel item : skProviderModels.values()) { if (item.isClass) { continue; } if (isCheck.get(item.className.reflectionName()) != null) { continue; } providerBuilder = MethodSpec.methodBuilder(lowerCase(item.className.simpleName()) + PROVIDER).returns(item.className).addModifiers(PUBLIC, ABSTRACT); isCheck.put(item.className.reflectionName(), item.className.reflectionName()); skdiBuilder.addMethod(providerBuilder.build()); } return skdiBuilder.build(); } }
UTF-8
Java
20,114
java
SKDILibraryCreate.java
Java
[ { "context": "tatic sk.di.SkConsts.WARNING_TIPS;\n\n/**\n * @author sky\n * @version 1.0 on 2018-07-05 上午10:42\n * @see SKD", "end": 2071, "score": 0.9989538192749023, "start": 2068, "tag": "USERNAME", "value": "sky" } ]
null
[]
package sk.di; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.squareup.javapoet.WildcardTypeName; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import sk.di.model.SKConstructorsModel; import sk.di.model.SKDILibraryModel; import sk.di.model.SKInputClassModel; import sk.di.model.SKInputModel; import sk.di.model.SKParamProviderModel; import sk.di.model.SKProviderModel; import sk.di.model.SKSourceModel; import sky.SKSingleton; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static sk.di.SKUtils.lowerCase; import static sk.di.SkConsts.COLLECTIONS; import static sk.di.SkConsts.FACADE_PACKAGE; import static sk.di.SkConsts.INPUT_IMPL; import static sk.di.SkConsts.MAP; import static sk.di.SkConsts.NAME_INPUT; import static sk.di.SkConsts.NAME_INPUT_IMPL; import static sk.di.SkConsts.NAME_LIBRARY; import static sk.di.SkConsts.NAME_LIBRARY_PROVIDERS; import static sk.di.SkConsts.NAME_LIBRARY_PROVIDERS_OPEN; import static sk.di.SkConsts.NAME_PROVIDER; import static sk.di.SkConsts.PROVIDER; import static sk.di.SkConsts.SK_COMMOM_PROVIDER; import static sk.di.SkConsts.SK_DC; import static sk.di.SkConsts.SK_DEFAULT_PROVIDER; import static sk.di.SkConsts.SK_DI; import static sk.di.SkConsts.SK_HELPER; import static sk.di.SkConsts.SK_INPUTS; import static sk.di.SkConsts.SK_I_PROVIDER; import static sk.di.SkConsts.SK_MANAGE_INTERFACE; import static sk.di.SkConsts.SK_MAP; import static sk.di.SkConsts.WARNING_TIPS; /** * @author sky * @version 1.0 on 2018-07-05 上午10:42 * @see SKDILibraryCreate */ class SKDILibraryCreate { Map<String, SKProviderModel> skProviderModels; Map<TypeElement, SKInputClassModel> skInputModels; Map<String, SKSourceModel> skSourceModelMap; SKDILibraryModel skLibraryModel; public JavaFile brewDILibrary(Map<String, SKProviderModel> skProviderModels, Map<TypeElement, SKInputClassModel> skInputModels, Map<String, SKSourceModel> skSourceModelMap, SKDILibraryModel skLibraryModel) { String packageName = "sk"; this.skProviderModels = skProviderModels; this.skInputModels = skInputModels; this.skSourceModelMap = skSourceModelMap; this.skLibraryModel = skLibraryModel; return JavaFile.builder(packageName, createClassDILibrary(packageName)).addFileComment("Generated code from Sk. Do not modify!").build(); } private TypeSpec createClassDILibrary(String packageName) { ClassName currentClassName = ClassName.get(packageName, skLibraryModel.name + NAME_LIBRARY); ClassName builderName = ClassName.get("", "Builder"); TypeSpec.Builder skdiBuilder = TypeSpec.classBuilder(currentClassName); skdiBuilder.addJavadoc(WARNING_TIPS); skdiBuilder.addModifiers(PUBLIC, FINAL); // 创建属性 builder skdiBuilder.addField(builderName, "builder"); // 初始化方法 MethodSpec.Builder initialize = MethodSpec.methodBuilder("initialize").addModifiers(Modifier.PRIVATE).addParameter(builderName, "builder"); initialize.addStatement("this.builder = builder"); HashMap<String, ParameterizedTypeName> singleSKDIProvider = new HashMap<>(); for (SKInputClassModel item : skInputModels.values()) { HashMap<String, ParameterizedTypeName> singleImplProvider = new HashMap<>(); HashMap<String, ClassName> singleImplSource = new HashMap<>(); String inputNameImpl = item.className.simpleName() + NAME_INPUT_IMPL; ClassName inputClassNameImpl = ClassName.get("", inputNameImpl); TypeSpec.Builder builderInput = TypeSpec.classBuilder(inputClassNameImpl); builderInput.addModifiers(PRIVATE, FINAL); builderInput.addSuperinterface(ParameterizedTypeName.get(SK_MANAGE_INTERFACE, item.className)); // 构造函数 MethodSpec.Builder clazzConstructors = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE); // 重写方法 MethodSpec.Builder clazzOverride = MethodSpec.methodBuilder("input").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class); clazzOverride.addParameter(item.className, lowerCase(item.className.simpleName())); clazzOverride.addStatement("input$T($N)", item.className, lowerCase(item.className.simpleName())); builderInput.addMethod(clazzOverride.build()); // 初始化方法 MethodSpec.Builder initializeImpl = MethodSpec.methodBuilder("initialize").addModifiers(Modifier.PRIVATE); // 初始化方法2 MethodSpec.Builder clazzInput = MethodSpec.methodBuilder("input" + item.className.simpleName()).addModifiers(Modifier.PRIVATE).returns(item.className); clazzInput.addParameter(item.className, "instance"); // 注入 for (SKInputModel skInputModel : item.skInputModels) { // 注入属性 if (skInputModel.skProviderModel == null) { skInputModel.skProviderModel = skProviderModels.get(skInputModel.providerKey); if (skInputModel.skProviderModel == null) { skInputModel.skProviderModel = skLibraryModel.skProviderModels.get(skInputModel.providerKey); } } if (skInputModel.skProviderModel == null) { continue; } // 初始化 initProvider(skInputModel.skProviderModel, clazzConstructors, skdiBuilder, builderInput, initialize, initializeImpl, singleSKDIProvider, singleImplProvider, singleImplSource); // 注入类名 String providerName = lowerCase(skInputModel.skProviderModel.getClassName(PROVIDER)); String inputClass = skInputModel.className.simpleName() + NAME_INPUT; ClassName inputClassName = ClassName.get(skInputModel.packageName, inputClass); if (skInputModel.isLazy) { clazzInput.addStatement("$T.input$N(instance, $T.lazy($N))", inputClassName, skInputModel.methodName, SK_DC, providerName); } else { clazzInput.addStatement("$T.input$N(instance, $N.get())", inputClassName, skInputModel.methodName, providerName); } } // 构造函数 clazzConstructors.addStatement("initialize()"); builderInput.addMethod(clazzConstructors.build()); clazzInput.addStatement("return instance"); builderInput.addMethod(initializeImpl.build()); builderInput.addMethod(clazzInput.build()); skdiBuilder.addType(builderInput.build()); // 初始化注入类 String nameInputImpl = item.className.simpleName() + INPUT_IMPL; skdiBuilder.addField(ParameterizedTypeName.get(SK_I_PROVIDER, inputClassNameImpl), nameInputImpl, PRIVATE); TypeSpec.Builder comparatorImpl = TypeSpec.anonymousClassBuilder(""); comparatorImpl.addSuperinterface(ParameterizedTypeName.get(SK_I_PROVIDER, inputClassNameImpl)); comparatorImpl.addMethod(MethodSpec.methodBuilder("get").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(inputClassNameImpl) .addStatement("return new $T()", inputClassNameImpl).build()); initialize.addStatement("this.$N = $L", nameInputImpl, comparatorImpl.build()); } // 创建内部类 builder TypeSpec.Builder builder = TypeSpec.classBuilder(builderName); builder.addModifiers(PUBLIC, FINAL, STATIC); // 构造方法 MethodSpec.Builder builderConstructors = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE); builder.addMethod(builderConstructors.build()); MethodSpec.Builder builderConstructorsMethod = MethodSpec.methodBuilder("build").addModifiers(Modifier.PUBLIC).returns(currentClassName); HashMap<String, SKConstructorsModel> singleConsProvider = new HashMap<>(); for (SKSourceModel item : skSourceModelMap.values()) { if (item.isSingle || item.isSingleGenerate) { String name = lowerCase(item.className.simpleName()); // 构造函数 if (item.skConstructorsModelList == null) { builder.addField(item.className, name); builderConstructorsMethod.addStatement("if($N == null)this.$N = new $T()", name, name, item.className); } else { CodeBlock.Builder consCodeBlock = null; for (SKConstructorsModel skConstructorsModel : item.skConstructorsModelList) { SKConstructorsModel temp = singleConsProvider.get(skConstructorsModel.className.reflectionName()); String consName = lowerCase(skConstructorsModel.className.simpleName()); if (consCodeBlock == null) { consCodeBlock = CodeBlock.builder(); consCodeBlock.add("$N", consName); } else { consCodeBlock.add(",$N", consName); } if (temp != null) { continue; } builder.addField(skConstructorsModel.className, consName, PRIVATE); // 增加赋值方法 builder.addMethod(addEqualMethod(builderName, skConstructorsModel.className, skConstructorsModel.className.simpleName())); singleConsProvider.put(skConstructorsModel.className.reflectionName(), skConstructorsModel); } builder.addField(item.className, name); if (item.classNameLibrary != null) { builderConstructorsMethod.addParameter(item.className, name); builderConstructorsMethod.addStatement("this.$N = $N", name, name); continue; } if (consCodeBlock == null) { builderConstructorsMethod.addStatement("if($N == null)this.$N = new $T()", name, name, item.className); } else { builderConstructorsMethod.addStatement("if($N == null)this.$N = new $T($N)", name, name, item.className, consCodeBlock.build().toString()); } } // 增加赋值方法 builder.addMethod(addEqualMethod(builderName, item.className, item.className.simpleName())); } } // 添加是否library初始化 String initFieldName = "isInit"; String initMethodName = "setInit"; builder.addField(boolean.class, initFieldName, PRIVATE); MethodSpec.Builder isInitBuilder = MethodSpec.methodBuilder(initMethodName).returns(builderName).addModifiers(PUBLIC).addParameter(boolean.class, initFieldName); isInitBuilder.addStatement("this.$N = $N", initFieldName, initFieldName); isInitBuilder.addStatement("return this"); builder.addMethod(isInitBuilder.build()); builderConstructorsMethod.addStatement("return new $T(this)", currentClassName); builder.addMethod(builderConstructorsMethod.build()); skdiBuilder.addType(builder.build()); // 创建内部方法 builder MethodSpec.Builder builderMethod = MethodSpec.methodBuilder("builder").addModifiers(Modifier.PUBLIC, STATIC).returns(builderName); builderMethod.addStatement("return new $T()", builderName); skdiBuilder.addMethod(builderMethod.build()); // 构造方法 MethodSpec.Builder constructors = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE); constructors.addParameter(builderName, "builder"); constructors.addStatement("initialize(builder)"); if (skLibraryModel.isSKDefaultLibrary) { initialize.addStatement("$T.skDefaultManager = iSKProvider.get().manage()", SK_HELPER); } initialize.addStatement("if(this.builder.$N) $T.inputDispatching(newSKDispatchingInput())", initFieldName, SK_INPUTS); skdiBuilder.addMethod(initialize.build()); skdiBuilder.addMethod(constructors.build()); TypeName wildcard = WildcardTypeName.subtypeOf(Object.class); TypeName classOfAny = ParameterizedTypeName.get(ClassName.get(Class.class), wildcard); // map集合 TypeName interfaceSK = ParameterizedTypeName.get(SK_MANAGE_INTERFACE, wildcard); TypeName providerSK = ParameterizedTypeName.get(SK_I_PROVIDER, interfaceSK); String mapBuilderName = "getMapOfClassOfSKProvider"; MethodSpec.Builder mapBuilder = MethodSpec.methodBuilder(mapBuilderName).returns(ParameterizedTypeName.get(MAP, classOfAny, providerSK)); int size = skInputModels.values().size(); if (size == 1) { for (SKInputClassModel item : skInputModels.values()) { String inputNameImpl = item.className.simpleName() + INPUT_IMPL; mapBuilder.addStatement("return $T.<$T,$T>singletonMap($T.class,($T)$N)", COLLECTIONS, classOfAny, providerSK, item.className, SK_I_PROVIDER, inputNameImpl); } } else if (size > 1) { CodeBlock.Builder codeBlock = CodeBlock.builder().add("return $T.<$T,$T>newMapBuilder($L)", SK_MAP, classOfAny, providerSK, size); for (SKInputClassModel item : skInputModels.values()) { String inputNameImpl = item.className.simpleName() + INPUT_IMPL; codeBlock.add(".put($T.class,($T)$T.this.$N)", item.className, SK_I_PROVIDER, currentClassName, inputNameImpl); } mapBuilder.addStatement("$L.build()", codeBlock.build()); } else { mapBuilder.addStatement("return $T.<$T,$T>newMapBuilder($L).build()", SK_MAP, classOfAny, providerSK, size); } skdiBuilder.addMethod(mapBuilder.build()); // 动态注入方法 MethodSpec.Builder newSKDispatchingInputBuilder = MethodSpec.methodBuilder("newSKDispatchingInput").returns(SK_DI); newSKDispatchingInputBuilder.addStatement("return new $T($N(),$T.EMPTY_MAP)", SK_DI, mapBuilderName, COLLECTIONS); skdiBuilder.addMethod(newSKDispatchingInputBuilder.build()); return skdiBuilder.build(); } private void initProvider(SKProviderModel skProviderModel, MethodSpec.Builder clazzConstructors, TypeSpec.Builder skdiBuilder, TypeSpec.Builder builderInput, MethodSpec.Builder initialize, MethodSpec.Builder initializeImpl, HashMap<String, ParameterizedTypeName> singleSKDIProvider, HashMap<String, ParameterizedTypeName> singleImplProvider, HashMap<String, ClassName> singleImplSource) { // 根据返回结果找到对应的类 String providerName = lowerCase(skProviderModel.getClassName(PROVIDER)); ClassName providerClassName = ClassName.get(skProviderModel.packageName, skProviderModel.getClassName(NAME_PROVIDER)); // 创建属性 ParameterizedTypeName fieldProvider = ParameterizedTypeName.get(SK_I_PROVIDER, skProviderModel.returnType); if (skProviderModel.isSingle) { if (singleSKDIProvider.get(providerName) == null) { skdiBuilder.addField(fieldProvider, providerName, PRIVATE); CodeBlock.Builder initProvider = generateParams(skProviderModel.parameters, clazzConstructors, skdiBuilder, skdiBuilder, initialize, initialize, singleSKDIProvider, singleSKDIProvider, singleImplSource); initialize.addStatement("this.$N = $T.provider($T.create(builder.$N$N))", providerName, SK_DC, providerClassName, lowerCase(skProviderModel.className.simpleName()), initProvider.build().toString()); singleSKDIProvider.put(providerName, fieldProvider); } } else { if (singleImplProvider.get(providerName) == null) { if (singleSKDIProvider.get(providerName) == null) { builderInput.addField(fieldProvider, providerName, PRIVATE); CodeBlock.Builder initProvider = generateParams(skProviderModel.parameters, clazzConstructors, skdiBuilder, builderInput, initialize, initializeImpl, singleSKDIProvider, singleImplProvider, singleImplSource); // 来源 SKSourceModel skSourceModel = skSourceModelMap.get(skProviderModel.className.reflectionName()); // 添加来源属性 和 初始化 String sourceName = lowerCase(skSourceModel.className.simpleName()); if (skSourceModel.isSingle) { // 引用来源属性 initializeImpl.addStatement("this.$N = $T.create(builder.$N$N)", providerName, providerClassName, lowerCase(skProviderModel.className.simpleName()), initProvider.build().toString()); } else { if (initialize.equals(initializeImpl)) { skSourceModel.isSingleGenerate = true; initializeImpl.addStatement("this.$N = $T.create(builder.$N$N)", providerName, providerClassName, sourceName, initProvider.build().toString()); } else { if (singleImplSource.get(skSourceModel.className.reflectionName()) == null) { builderInput.addField(skSourceModel.className, sourceName, PRIVATE); clazzConstructors.addStatement("this.$N = new $T()", sourceName, skSourceModel.className); singleImplSource.put(skSourceModel.className.reflectionName(), skSourceModel.className); } initializeImpl.addStatement("this.$N = $T.create($N$N)", providerName, providerClassName, sourceName, initProvider.build().toString()); } } } singleImplProvider.put(providerName, fieldProvider); } } } private CodeBlock.Builder generateParams(List<SKParamProviderModel> parameters, MethodSpec.Builder clazzConstructors, TypeSpec.Builder skdiBuilder, TypeSpec.Builder builderInput, MethodSpec.Builder initialize, MethodSpec.Builder initializeImpl, HashMap<String, ParameterizedTypeName> singleSKDIProvider, HashMap<String, ParameterizedTypeName> singleImplProvider, HashMap<String, ClassName> singleImplSource) { CodeBlock.Builder builder = CodeBlock.builder(); for (SKParamProviderModel item : parameters) { // 寻找来源 ClassName providerName = (ClassName) item.classType; SKProviderModel skProviderModel = skProviderModels.get(providerName.reflectionName()); initProvider(skProviderModel, clazzConstructors, skdiBuilder, builderInput, initialize, initializeImpl, singleSKDIProvider, singleImplProvider, singleImplSource); builder.add(",$N", lowerCase(providerName.simpleName()) + PROVIDER); } return builder; } private MethodSpec addEqualMethod(ClassName returnName, ClassName parameName, String name) { String methodSourceName = "set" + name; MethodSpec.Builder setSource = MethodSpec.methodBuilder(methodSourceName).addModifiers(Modifier.PUBLIC).returns(returnName); setSource.addParameter(parameName, lowerCase(name)); setSource.addStatement("this.$N = $N", lowerCase(name), lowerCase(name)); setSource.addStatement("return this"); return setSource.build(); } public JavaFile brewDILibraryProvider() { return JavaFile.builder(FACADE_PACKAGE, createClassDILibraryProviders()).addFileComment("Generated code from Sk. Do not modify!").build(); } public JavaFile brewDILibraryProviderOpen() { return JavaFile.builder(FACADE_PACKAGE, createClassDILibraryProvidersOpen()).addFileComment("Generated code from Sk. Do not modify!").build(); } private TypeSpec createClassDILibraryProviders() { TypeSpec.Builder skdiBuilder = TypeSpec.classBuilder(skLibraryModel.name + NAME_LIBRARY_PROVIDERS); skdiBuilder.addJavadoc(WARNING_TIPS); skdiBuilder.addModifiers(PUBLIC, FINAL); for (SKProviderModel item : skProviderModels.values()) { if (!item.isClass) { continue; } MethodSpec.Builder providerBuilder = MethodSpec.methodBuilder(item.name).returns(item.returnType).addModifiers(Modifier.PUBLIC); providerBuilder.addStatement("return new $T()", item.returnType); if (item.isSingle) { providerBuilder.addAnnotation(SKSingleton.class); } skdiBuilder.addMethod(providerBuilder.build()); } return skdiBuilder.build(); } private TypeSpec createClassDILibraryProvidersOpen() { TypeSpec.Builder skdiBuilder = TypeSpec.interfaceBuilder(skLibraryModel.name + NAME_LIBRARY_PROVIDERS_OPEN); skdiBuilder.addJavadoc(WARNING_TIPS); skdiBuilder.addModifiers(PUBLIC); ClassName library = ClassName.get("sk", skLibraryModel.name + NAME_LIBRARY_PROVIDERS); MethodSpec.Builder providerBuilder = MethodSpec.methodBuilder(lowerCase(skLibraryModel.name) + NAME_LIBRARY_PROVIDERS).returns(library).addModifiers(PUBLIC, ABSTRACT); skdiBuilder.addMethod(providerBuilder.build()); HashMap<String, String> isCheck = new HashMap<>(); for (SKProviderModel item : skProviderModels.values()) { if (item.isClass) { continue; } if (isCheck.get(item.className.reflectionName()) != null) { continue; } providerBuilder = MethodSpec.methodBuilder(lowerCase(item.className.simpleName()) + PROVIDER).returns(item.className).addModifiers(PUBLIC, ABSTRACT); isCheck.put(item.className.reflectionName(), item.className.reflectionName()); skdiBuilder.addMethod(providerBuilder.build()); } return skdiBuilder.build(); } }
20,114
0.763689
0.762832
458
42.305676
43.804527
189
false
false
0
0
0
0
0
0
3.135371
false
false
9
c2e8bc4df1800ff7f8f852d255a64bb8dc54a74e
7,301,444,409,878
eb2334158fd6268696df7cf0f3bddf49cf85e999
/src/main/java/com/hibi/www/controller/mq/ProductController.java
a93df39a23e65598f644c3824da504a13bfbef35
[]
no_license
forever159/daodaotong
https://github.com/forever159/daodaotong
1966bb0071dc499c74b6485f049991f51ba40d4a
54039c8dc8e10e7274f8dcc379ccca64f76edee8
refs/heads/master
2020-03-24T10:00:57.297000
2018-08-15T03:42:07
2018-08-15T03:42:07
142,644,829
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hibi.www.controller.mq; import com.hibi.www.queue.producer.ProductProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("product") public class ProductController { @Autowired ProductProducer productProducer; @RequestMapping("/getId/{productId}") @ResponseBody public String getId(@PathVariable final long productId){ this.productProducer.sendMessage(productId); return String.valueOf(productId); } }
UTF-8
Java
740
java
ProductController.java
Java
[]
null
[]
package com.hibi.www.controller.mq; import com.hibi.www.queue.producer.ProductProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("product") public class ProductController { @Autowired ProductProducer productProducer; @RequestMapping("/getId/{productId}") @ResponseBody public String getId(@PathVariable final long productId){ this.productProducer.sendMessage(productId); return String.valueOf(productId); } }
740
0.790541
0.790541
24
29.833334
23.42482
62
false
false
0
0
0
0
0
0
0.416667
false
false
9
237143e01ed105f73a186e0fc94094b4369b1883
9,010,841,395,933
b599036921598d8a944d3c459042a5f06f15d5fd
/APP3_Les Layout_Intent_Bandel_Spiner_ArrayAdapter/app/src/main/java/com/example/walid/app3/Page3.java
91724c412eb8c9b0fca5932c1e90d4a194b5be2f
[]
no_license
Oualid-jennani/Exercises_java_android_studio
https://github.com/Oualid-jennani/Exercises_java_android_studio
ee8f3cf8886f988d1fe1f4f3c09c4924a152d1ea
3141f17cae0860b5fe5c10f1fad17187997449cd
refs/heads/main
2023-06-23T00:54:20.739000
2021-07-21T02:37:55
2021-07-21T02:37:55
387,971,438
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.walid.app3; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class Page3 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_page3); TextView txtInfo = (TextView)findViewById(R.id.TextINFO); Bundle b = getIntent().getExtras(); String name = b.getString("username"); String Passw = b.getString("password"); txtInfo.setText("User : " + name + " Password : " + Passw); Button go = (Button) findViewById(R.id.Go); final Intent Page5 = new Intent(this,Page5.class); go.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(Page5); } }); //----------------------------------------------------------------------------------- Spinner sp = (Spinner)findViewById(R.id.spinner1); sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String nameIten = parent.getItemAtPosition(position).toString(); Toast.makeText(Page3.this, nameIten, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { Toast.makeText(Page3.this, "", Toast.LENGTH_SHORT).show(); } }); //----------------------------------------------------------------------------------- //add items in java code Spinner sp2 = (Spinner)findViewById(R.id.spinner2); ArrayList<String> myarray = new ArrayList<>(); myarray.add("Element 1"); myarray.add("Element 2"); myarray.add("Element 3"); myarray.add("Element 4"); myarray.add("Element 5"); ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,myarray); sp2.setAdapter(adapter); } }
UTF-8
Java
2,505
java
Page3.java
Java
[ { "context": "getExtras();\n\n String name = b.getString(\"username\");\n String Passw = b.getString(\"password\"", "end": 789, "score": 0.998907208442688, "start": 781, "tag": "USERNAME", "value": "username" }, { "context": "b.getString(\"username\");\n String...
null
[]
package com.example.walid.app3; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class Page3 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_page3); TextView txtInfo = (TextView)findViewById(R.id.TextINFO); Bundle b = getIntent().getExtras(); String name = b.getString("username"); String Passw = b.<PASSWORD>("<PASSWORD>"); txtInfo.setText("User : " + name + " Password : " + <PASSWORD>); Button go = (Button) findViewById(R.id.Go); final Intent Page5 = new Intent(this,Page5.class); go.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(Page5); } }); //----------------------------------------------------------------------------------- Spinner sp = (Spinner)findViewById(R.id.spinner1); sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String nameIten = parent.getItemAtPosition(position).toString(); Toast.makeText(Page3.this, nameIten, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { Toast.makeText(Page3.this, "", Toast.LENGTH_SHORT).show(); } }); //----------------------------------------------------------------------------------- //add items in java code Spinner sp2 = (Spinner)findViewById(R.id.spinner2); ArrayList<String> myarray = new ArrayList<>(); myarray.add("Element 1"); myarray.add("Element 2"); myarray.add("Element 3"); myarray.add("Element 4"); myarray.add("Element 5"); ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,myarray); sp2.setAdapter(adapter); } }
2,513
0.592814
0.58523
76
31.960526
27.984224
108
false
false
0
0
0
0
0
0
0.631579
false
false
9
56f3610e157cac24b27f894d15fbb7f9cb76c543
9,259,949,534,428
444459a54e0bc0c4d51cf4b77907cc3a50fa43ff
/build-info-extractor/src/main/java/org/jfrog/build/extractor/clientConfiguration/client/distribution/request/DeleteReleaseBundleRequest.java
2a0b0aca48e68fe6326c781e655f99de429d4eab
[ "Apache-2.0" ]
permissive
eyalbe4/build-info
https://github.com/eyalbe4/build-info
424df7c276945a230c2d40455dbc1482361dc995
c1b0da1351e26d99c2f1f60acf88e2aca8771bf0
refs/heads/master
2023-04-14T10:06:36.251000
2023-04-09T13:19:02
2023-04-09T13:19:02
213,185,077
0
0
Apache-2.0
true
2019-10-06T14:40:06
2019-10-06T14:40:06
2019-09-23T12:22:57
2019-10-04T19:36:34
107,331
0
0
0
null
false
false
package org.jfrog.build.extractor.clientConfiguration.client.distribution.request; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents a request to delete a remote release bundle. * * @author yahavi */ @SuppressWarnings("unused") public class DeleteReleaseBundleRequest extends RemoteReleaseBundleRequest { public enum OnSuccess { keep, delete } @JsonProperty("on_success") private OnSuccess onSuccess; public OnSuccess getOnSuccess() { return onSuccess; } public void setOnSuccess(OnSuccess onSuccess) { this.onSuccess = onSuccess; } }
UTF-8
Java
621
java
DeleteReleaseBundleRequest.java
Java
[ { "context": "t to delete a remote release bundle.\n *\n * @author yahavi\n */\n@SuppressWarnings(\"unused\")\npublic class Dele", "end": 222, "score": 0.9994006752967834, "start": 216, "tag": "USERNAME", "value": "yahavi" } ]
null
[]
package org.jfrog.build.extractor.clientConfiguration.client.distribution.request; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents a request to delete a remote release bundle. * * @author yahavi */ @SuppressWarnings("unused") public class DeleteReleaseBundleRequest extends RemoteReleaseBundleRequest { public enum OnSuccess { keep, delete } @JsonProperty("on_success") private OnSuccess onSuccess; public OnSuccess getOnSuccess() { return onSuccess; } public void setOnSuccess(OnSuccess onSuccess) { this.onSuccess = onSuccess; } }
621
0.723027
0.723027
26
22.884615
24.104464
82
false
false
0
0
0
0
0
0
0.230769
false
false
9
7d5c7e961d500727012a7bfd83ff29120133a483
10,728,828,307,888
c90896a0370f73c58b2bc339fb703616ddf91bf3
/src/com/chinaredstar/learn/reflect/Demo3.java
af7b8c2333f8d4e23d6e1297742703f6c1c5f0b7
[]
no_license
wbyxxmy/StudentDemo
https://github.com/wbyxxmy/StudentDemo
cf9e58a629f0dc877ed7def32ca47c5ab6ff6be6
4c574d1d8f7c2bb67c282496c0ec0cc2f00331b5
refs/heads/master
2019-07-29T23:51:40.703000
2017-03-12T15:43:02
2017-03-12T15:43:02
84,735,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chinaredstar.learn.reflect; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Created by xinjian.ye on 2017/3/6. * Time: 14:14 */ public class Demo3 { @Test public void test1() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Constructor constructor = clazz.getConstructor(null); Method md = clazz.getMethod("mm1",null); md.invoke(constructor.newInstance(null), null); } @Test public void test2() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Constructor constructor = clazz.getConstructor(String.class, int.class); Method md = clazz.getMethod("mm1",int.class); md.invoke(constructor.newInstance("zhangsan",15), 16); } @Test public void test3() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Method method = clazz.getMethod("main",String[].class); method.invoke(null, (Object)new String[]{"aa", "bb"}); } @Test public void test4() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Method method = clazz.getMethod("mm1",String[].class); method.invoke(null,(Object)new String[]{"aa", "bb"}); } }
UTF-8
Java
1,386
java
Demo3.java
Java
[ { "context": "mport java.lang.reflect.Method;\n\n/**\n * Created by xinjian.ye on 2017/3/6.\n * Time: 14:14\n */\npublic class Demo", "end": 165, "score": 0.9452330470085144, "start": 155, "tag": "USERNAME", "value": "xinjian.ye" } ]
null
[]
package com.chinaredstar.learn.reflect; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Created by xinjian.ye on 2017/3/6. * Time: 14:14 */ public class Demo3 { @Test public void test1() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Constructor constructor = clazz.getConstructor(null); Method md = clazz.getMethod("mm1",null); md.invoke(constructor.newInstance(null), null); } @Test public void test2() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Constructor constructor = clazz.getConstructor(String.class, int.class); Method md = clazz.getMethod("mm1",int.class); md.invoke(constructor.newInstance("zhangsan",15), 16); } @Test public void test3() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Method method = clazz.getMethod("main",String[].class); method.invoke(null, (Object)new String[]{"aa", "bb"}); } @Test public void test4() throws Exception { Class clazz = Class.forName("com.chinaredstar.learn.reflect.Person"); Method method = clazz.getMethod("mm1",String[].class); method.invoke(null,(Object)new String[]{"aa", "bb"}); } }
1,386
0.660173
0.6443
39
34.53846
27.049665
80
false
false
0
0
0
0
0
0
0.769231
false
false
9
4672ffd775c48fb7cf967c555a5fff525d845063
1,228,360,672,302
2d791da9de704335997700ac52603a8279bad63e
/src/main/java/it/academy/PropertyBean.java
2ae09c755d03b2d387b6a18b1810e4e82df07184
[]
no_license
aluor/springTest
https://github.com/aluor/springTest
7cadc87779db79268e6824d380e072e6539fc41a
e6fc623ae4f490391ad2649e787d144a62e34208
refs/heads/master
2021-01-01T05:19:37.489000
2016-05-18T22:16:06
2016-05-18T22:16:06
58,885,726
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.academy; import org.apache.log4j.Logger; import java.util.Properties; /** * Created by Rabotnik on 16.05.2016. */ public class PropertyBean { private static Logger log = Logger.getLogger(Main.class); private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public void init() { log.info(this.getClass().getName()+" init...\n"+this); } public void destroy() { log.info(this.getClass().getName()+" destroyed!"); } @Override public String toString() { return "PropertyBean{" + "properties=" + properties + '}'; } }
UTF-8
Java
709
java
PropertyBean.java
Java
[ { "context": ";\n\nimport java.util.Properties;\n\n/**\n * Created by Rabotnik on 16.05.2016.\n */\npublic class PropertyBe", "end": 103, "score": 0.5067123174667358, "start": 102, "tag": "USERNAME", "value": "R" }, { "context": "\nimport java.util.Properties;\n\n/**\n * Created by R...
null
[]
package it.academy; import org.apache.log4j.Logger; import java.util.Properties; /** * Created by Rabotnik on 16.05.2016. */ public class PropertyBean { private static Logger log = Logger.getLogger(Main.class); private Properties properties; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public void init() { log.info(this.getClass().getName()+" init...\n"+this); } public void destroy() { log.info(this.getClass().getName()+" destroyed!"); } @Override public String toString() { return "PropertyBean{" + "properties=" + properties + '}'; } }
709
0.660085
0.647391
36
18.694445
18.525988
59
false
false
0
0
0
0
0
0
0.277778
false
false
9
0db432d249f8ece8198917391ea4d8d353ebed36
10,325,101,413,331
1a055b8ca37232763eec49a09646fd8215076efa
/src/main/java/edu/netcracker/project/logistic/dao/ResetPasswordTokenDao.java
6e36188adb1bf7b8c8fd5f48e6e3ef780a70442e
[]
no_license
Bohdan11101997/Logistics_company
https://github.com/Bohdan11101997/Logistics_company
b0e1b8e6e59dad06f3b1b0234d7b7eb4674cc2e0
5bbb68789ed08d8825393f949128e747ac75cb74
refs/heads/master
2021-05-02T08:51:36.532000
2018-03-29T09:04:37
2018-03-29T09:04:37
120,813,897
0
4
null
false
2018-03-29T07:59:42
2018-02-08T20:27:11
2018-03-29T07:29:51
2018-03-29T07:59:42
16,706
0
2
0
Java
false
null
package edu.netcracker.project.logistic.dao; import edu.netcracker.project.logistic.model.ResetPasswordToken; import java.util.Optional; public interface ResetPasswordTokenDao extends CrudDao<ResetPasswordToken, Long> { Optional<ResetPasswordToken> findOneByToken(String token); }
UTF-8
Java
289
java
ResetPasswordTokenDao.java
Java
[]
null
[]
package edu.netcracker.project.logistic.dao; import edu.netcracker.project.logistic.model.ResetPasswordToken; import java.util.Optional; public interface ResetPasswordTokenDao extends CrudDao<ResetPasswordToken, Long> { Optional<ResetPasswordToken> findOneByToken(String token); }
289
0.83045
0.83045
10
27.9
30.810551
82
false
false
0
0
0
0
0
0
0.5
false
false
9
419df91d2ae4b7ae0e9656fba66c02e8f4759ce8
20,169,166,433,642
d48d43f39d9c1bcfce963b0ab24b27a53b70eb31
/src/java/lml/snir/concession/client/AdminBeanCommande.java
1af32a004215458ba0b7dd8a0e817850cb0580b5
[]
no_license
MJacqueline/MyLittleConcession
https://github.com/MJacqueline/MyLittleConcession
d6135d7fae81958811a4e2df05860adb37e211ee
30a6f369d22ed8c1467296987eaaf9e477f00b64
refs/heads/master
2023-05-06T00:41:29.188000
2021-05-24T17:12:28
2021-05-24T17:12:28
370,427,209
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lml.snir.concession.client; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import lml.snir.concession.metier.MetierFactory; import lml.snir.concession.metier.entity.Client; import lml.snir.concession.metier.entity.Commande; import lml.snir.concession.metier.entity.Voiture; import lml.snir.concession.physique.CommandeService; /** * * @author saturne */ @ManagedBean @SessionScoped public class AdminBeanCommande { private Date date; private Map<Date, Date> dates; private Commande commande; private Commande selectedCommande; private CommandeService commandeSrv; private List<Commande> commandes; private int count; private Client selectedClient; private Voiture selectedVoiture; /** * Creates a new instance of AdminBeanCommande */ @PostConstruct public void init() { try { this.date = new Date(); this.setCommande(new Commande()); this.selectedCommande = new Commande(); this.commandeSrv = MetierFactory.getCommandeService(); this.setCommandes(this.commandeSrv.getAll(0, this.getCount())); this.selectedClient = new Client(); this.selectedVoiture = new Voiture(); List<Date> datas = this.getCommandeSrv().getDates(); this.setDates(new HashMap<Date, Date>()); for (Date st : datas) { if (st != null) { this.getDates().put(st, st); } } System.out.println("-------------------------INIT OK---------------------------"); } catch (Exception ex) { // do nothing for this moment System.err.println("BOBO"); } } public void onDateChange() { if (this.getDate() != null) { try { this.setCount(this.getCommandeSrv().getCountByDates(this.getDate())); this.setCommandes(this.getCommandeSrv().getByDates(this.getDate(), 0, this.getCount())); } catch (Exception ex) { Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex); } } else { try { this.setCount((int) this.getCommandeSrv().getCount()); this.setCommandes(this.getCommandeSrv().getAll(0, this.getCount())); } catch (Exception ex) { Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex); } } } public void ajoutCommande() { FacesMessage message = null; try { if (this.selectedClient != null) { if (this.selectedVoiture != null) { this.commande.setClient(selectedClient); this.commande.setVoitures(selectedVoiture); this.commande.setDates(Date.from(Instant.now())); this.commandeSrv.add(this.commande); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Ajouter"); } else { message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Voiture", "Non Sélectionner"); } } else { message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Client", "Non Sélectionner"); } } catch (Exception ex) { Logger.getLogger(AdminBeanCommande.class.getName()).log(Level.SEVERE, null, ex); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Aucun Client et Voiture", "Sélectionner"); } FacesContext.getCurrentInstance().addMessage(null, message); } public void supprCommande(){ FacesMessage message = null; try{ this.commandeSrv.remove(this.selectedCommande); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Supprimer"); }catch (Exception ex) { Logger.getLogger(AdminBeanVoiture.class.getName()).log(Level.SEVERE, null, ex); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Non Supprimer"); } FacesContext.getCurrentInstance().addMessage(null, message); } public void modifCommande(){ FacesMessage message = null; try{ this.commande.setClient(selectedClient); this.commande.setVoitures(selectedVoiture); this.commandeSrv.update(this.commande); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Modifier"); }catch (Exception ex) { Logger.getLogger(AdminBeanVoiture.class.getName()).log(Level.SEVERE, null, ex); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Non Modifier"); } FacesContext.getCurrentInstance().addMessage(null, message); } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the dates */ public Map<Date, Date> getDates() { return dates; } /** * @param dates the dates to set */ public void setDates(Map<Date, Date> dates) { this.dates = dates; } /** * @return the selectedCommande */ public Commande getSelectedCommande() { return selectedCommande; } /** * @param selectedCommande the selectedCommande to set */ public void setSelectedCommande(Commande selectedCommande) { this.selectedCommande = selectedCommande; } /** * @return the commandeSrv */ public CommandeService getCommandeSrv() { return commandeSrv; } /** * @param commandeSrv the commandeSrv to set */ public void setCommandeSrv(CommandeService commandeSrv) { this.commandeSrv = commandeSrv; } /** * @return the commandes */ public List<Commande> getCommandes() { return commandes; } /** * @param commandes the commandes to set */ public void setCommandes(List<Commande> commandes) { this.commandes = commandes; } /** * @return the count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } /** * @return the selectedClient */ public Client getSelectedClient() { return selectedClient; } /** * @param selectedClient the selectedClient to set */ public void setSelectedClient(Client selectedClient) { this.selectedClient = selectedClient; } /** * @return the selectedVoiture */ public Voiture getSelectedVoiture() { return selectedVoiture; } /** * @param selectedVoiture the selectedVoiture to set */ public void setSelectedVoiture(Voiture selectedVoiture) { this.selectedVoiture = selectedVoiture; } /** * @return the commande */ public Commande getCommande() { return commande; } /** * @param commande the commande to set */ public void setCommande(Commande commande) { this.commande = commande; } }
UTF-8
Java
7,905
java
AdminBeanCommande.java
Java
[ { "context": "ssion.physique.CommandeService;\n\n/**\n *\n * @author saturne\n */\n@ManagedBean\n@SessionScoped\npublic class Admi", "end": 914, "score": 0.9805182814598083, "start": 907, "tag": "USERNAME", "value": "saturne" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lml.snir.concession.client; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import lml.snir.concession.metier.MetierFactory; import lml.snir.concession.metier.entity.Client; import lml.snir.concession.metier.entity.Commande; import lml.snir.concession.metier.entity.Voiture; import lml.snir.concession.physique.CommandeService; /** * * @author saturne */ @ManagedBean @SessionScoped public class AdminBeanCommande { private Date date; private Map<Date, Date> dates; private Commande commande; private Commande selectedCommande; private CommandeService commandeSrv; private List<Commande> commandes; private int count; private Client selectedClient; private Voiture selectedVoiture; /** * Creates a new instance of AdminBeanCommande */ @PostConstruct public void init() { try { this.date = new Date(); this.setCommande(new Commande()); this.selectedCommande = new Commande(); this.commandeSrv = MetierFactory.getCommandeService(); this.setCommandes(this.commandeSrv.getAll(0, this.getCount())); this.selectedClient = new Client(); this.selectedVoiture = new Voiture(); List<Date> datas = this.getCommandeSrv().getDates(); this.setDates(new HashMap<Date, Date>()); for (Date st : datas) { if (st != null) { this.getDates().put(st, st); } } System.out.println("-------------------------INIT OK---------------------------"); } catch (Exception ex) { // do nothing for this moment System.err.println("BOBO"); } } public void onDateChange() { if (this.getDate() != null) { try { this.setCount(this.getCommandeSrv().getCountByDates(this.getDate())); this.setCommandes(this.getCommandeSrv().getByDates(this.getDate(), 0, this.getCount())); } catch (Exception ex) { Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex); } } else { try { this.setCount((int) this.getCommandeSrv().getCount()); this.setCommandes(this.getCommandeSrv().getAll(0, this.getCount())); } catch (Exception ex) { Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex); } } } public void ajoutCommande() { FacesMessage message = null; try { if (this.selectedClient != null) { if (this.selectedVoiture != null) { this.commande.setClient(selectedClient); this.commande.setVoitures(selectedVoiture); this.commande.setDates(Date.from(Instant.now())); this.commandeSrv.add(this.commande); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Ajouter"); } else { message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Voiture", "Non Sélectionner"); } } else { message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Client", "Non Sélectionner"); } } catch (Exception ex) { Logger.getLogger(AdminBeanCommande.class.getName()).log(Level.SEVERE, null, ex); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Aucun Client et Voiture", "Sélectionner"); } FacesContext.getCurrentInstance().addMessage(null, message); } public void supprCommande(){ FacesMessage message = null; try{ this.commandeSrv.remove(this.selectedCommande); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Supprimer"); }catch (Exception ex) { Logger.getLogger(AdminBeanVoiture.class.getName()).log(Level.SEVERE, null, ex); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Non Supprimer"); } FacesContext.getCurrentInstance().addMessage(null, message); } public void modifCommande(){ FacesMessage message = null; try{ this.commande.setClient(selectedClient); this.commande.setVoitures(selectedVoiture); this.commandeSrv.update(this.commande); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Modifier"); }catch (Exception ex) { Logger.getLogger(AdminBeanVoiture.class.getName()).log(Level.SEVERE, null, ex); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Commande", "Non Modifier"); } FacesContext.getCurrentInstance().addMessage(null, message); } /** * @return the date */ public Date getDate() { return date; } /** * @param date the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the dates */ public Map<Date, Date> getDates() { return dates; } /** * @param dates the dates to set */ public void setDates(Map<Date, Date> dates) { this.dates = dates; } /** * @return the selectedCommande */ public Commande getSelectedCommande() { return selectedCommande; } /** * @param selectedCommande the selectedCommande to set */ public void setSelectedCommande(Commande selectedCommande) { this.selectedCommande = selectedCommande; } /** * @return the commandeSrv */ public CommandeService getCommandeSrv() { return commandeSrv; } /** * @param commandeSrv the commandeSrv to set */ public void setCommandeSrv(CommandeService commandeSrv) { this.commandeSrv = commandeSrv; } /** * @return the commandes */ public List<Commande> getCommandes() { return commandes; } /** * @param commandes the commandes to set */ public void setCommandes(List<Commande> commandes) { this.commandes = commandes; } /** * @return the count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } /** * @return the selectedClient */ public Client getSelectedClient() { return selectedClient; } /** * @param selectedClient the selectedClient to set */ public void setSelectedClient(Client selectedClient) { this.selectedClient = selectedClient; } /** * @return the selectedVoiture */ public Voiture getSelectedVoiture() { return selectedVoiture; } /** * @param selectedVoiture the selectedVoiture to set */ public void setSelectedVoiture(Voiture selectedVoiture) { this.selectedVoiture = selectedVoiture; } /** * @return the commande */ public Commande getCommande() { return commande; } /** * @param commande the commande to set */ public void setCommande(Commande commande) { this.commande = commande; } }
7,905
0.599089
0.598709
272
28.05147
25.946869
110
false
false
0
0
0
0
0
0
0.477941
false
false
9
9e66be9d9e18fc328245c56ba12c2650aefa385c
20,169,166,435,384
ec1d871d32d181151b912e79d73186dd04341424
/backEnd/src/main/java/com/kockumation/backEnd/controller/SessionsAndReportsController/SessionsReportsController.java
89eab39e2cef04ad8835c07ee1ca7695bb051637
[]
no_license
mohammedalmahfoodh/WashMaster
https://github.com/mohammedalmahfoodh/WashMaster
9fdac3b14ce0fd09136a1088ca398874d5669065
6853260d2e73156a82fc2cba95d483f03a8a73a0
refs/heads/master
2022-12-09T00:16:35.049000
2020-09-07T07:17:33
2020-09-07T07:17:33
273,531,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kockumation.backEnd.controller.SessionsAndReportsController; import com.kockumation.backEnd.service.sessionsReports.SessionsReportsService; import com.kockumation.backEnd.service.sessionsReports.model.GetReportById; import com.kockumation.backEnd.service.sessionsReports.model.GetSessionById; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @RestController @RequestMapping("/api/") public class SessionsReportsController { @Autowired SessionsReportsService sessionsReportsService; private ExecutorService executor; public SessionsReportsController() { executor = Executors.newSingleThreadExecutor(); } @GetMapping("/getReportsIds") public ResponseEntity<List<JSONObject>> getReportsIds() { List<JSONObject> planIdsList = new ArrayList<>(); ResponseEntity<List<JSONObject>> responseEntity = null; try { planIdsList = sessionsReportsService.getReportsIds().get(); if (planIdsList.size() == 0) { System.out.println("No elements"); responseEntity = new ResponseEntity<List<JSONObject>>( planIdsList, HttpStatus.NO_CONTENT); } else { responseEntity = new ResponseEntity<List<JSONObject>>( planIdsList, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//********************************* Get Reports Ids **************************************************************************** //*************************** Get Session Ids ********************************************************************************** @GetMapping("/getSessionsIds") public ResponseEntity<List<JSONObject>> getSessionsIds() { List<JSONObject> sessionsList = new ArrayList<>(); ResponseEntity<List<JSONObject>> responseEntity = null; try { sessionsList = sessionsReportsService.getSessionsIds().get(); if (sessionsList.size() == 0) { System.out.println("No elements"); responseEntity = new ResponseEntity<List<JSONObject>>( sessionsList, HttpStatus.NO_CONTENT); } else { responseEntity = new ResponseEntity<List<JSONObject>>( sessionsList, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//*************************** Get Session Ids ********************************************************************************** //************************* Get Report By Id ************************************************************************************ @PostMapping("/getReportById") public ResponseEntity getReportById(@Valid @RequestBody GetReportById getReportById) { JSONObject reportObject = new JSONObject(); ResponseEntity<JSONObject> responseEntity = null; try { reportObject = sessionsReportsService.getReport(getReportById.getReport_id()).get(); if (reportObject.size() == 0) { System.out.println("No report for this id "); return new ResponseEntity<>( "No report for this id " + getReportById.getReport_id(), HttpStatus.NOT_FOUND); } else { responseEntity = new ResponseEntity<JSONObject>( reportObject, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//************************* Get Report By Id ************************************************************************************ //************************* Get Report By Id ************************************************************************************ @PostMapping("/getSessionById") public ResponseEntity getSessionById(@Valid @RequestBody GetSessionById getSessionById) { JSONObject sessionObject = new JSONObject(); ResponseEntity responseEntity = null; try { sessionObject = sessionsReportsService.getSessionObject(getSessionById.getSession_id()).get(); if (sessionObject.size() == 0) { System.out.println("No session for this id "); return new ResponseEntity<>( "No session for this id " + getSessionById.getSession_id(), HttpStatus.NOT_FOUND); } else { responseEntity = new ResponseEntity<JSONObject>( sessionObject, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//************************* Get Report By Id ************************************************************************************ }
UTF-8
Java
5,892
java
SessionsReportsController.java
Java
[]
null
[]
package com.kockumation.backEnd.controller.SessionsAndReportsController; import com.kockumation.backEnd.service.sessionsReports.SessionsReportsService; import com.kockumation.backEnd.service.sessionsReports.model.GetReportById; import com.kockumation.backEnd.service.sessionsReports.model.GetSessionById; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @RestController @RequestMapping("/api/") public class SessionsReportsController { @Autowired SessionsReportsService sessionsReportsService; private ExecutorService executor; public SessionsReportsController() { executor = Executors.newSingleThreadExecutor(); } @GetMapping("/getReportsIds") public ResponseEntity<List<JSONObject>> getReportsIds() { List<JSONObject> planIdsList = new ArrayList<>(); ResponseEntity<List<JSONObject>> responseEntity = null; try { planIdsList = sessionsReportsService.getReportsIds().get(); if (planIdsList.size() == 0) { System.out.println("No elements"); responseEntity = new ResponseEntity<List<JSONObject>>( planIdsList, HttpStatus.NO_CONTENT); } else { responseEntity = new ResponseEntity<List<JSONObject>>( planIdsList, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//********************************* Get Reports Ids **************************************************************************** //*************************** Get Session Ids ********************************************************************************** @GetMapping("/getSessionsIds") public ResponseEntity<List<JSONObject>> getSessionsIds() { List<JSONObject> sessionsList = new ArrayList<>(); ResponseEntity<List<JSONObject>> responseEntity = null; try { sessionsList = sessionsReportsService.getSessionsIds().get(); if (sessionsList.size() == 0) { System.out.println("No elements"); responseEntity = new ResponseEntity<List<JSONObject>>( sessionsList, HttpStatus.NO_CONTENT); } else { responseEntity = new ResponseEntity<List<JSONObject>>( sessionsList, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//*************************** Get Session Ids ********************************************************************************** //************************* Get Report By Id ************************************************************************************ @PostMapping("/getReportById") public ResponseEntity getReportById(@Valid @RequestBody GetReportById getReportById) { JSONObject reportObject = new JSONObject(); ResponseEntity<JSONObject> responseEntity = null; try { reportObject = sessionsReportsService.getReport(getReportById.getReport_id()).get(); if (reportObject.size() == 0) { System.out.println("No report for this id "); return new ResponseEntity<>( "No report for this id " + getReportById.getReport_id(), HttpStatus.NOT_FOUND); } else { responseEntity = new ResponseEntity<JSONObject>( reportObject, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//************************* Get Report By Id ************************************************************************************ //************************* Get Report By Id ************************************************************************************ @PostMapping("/getSessionById") public ResponseEntity getSessionById(@Valid @RequestBody GetSessionById getSessionById) { JSONObject sessionObject = new JSONObject(); ResponseEntity responseEntity = null; try { sessionObject = sessionsReportsService.getSessionObject(getSessionById.getSession_id()).get(); if (sessionObject.size() == 0) { System.out.println("No session for this id "); return new ResponseEntity<>( "No session for this id " + getSessionById.getSession_id(), HttpStatus.NOT_FOUND); } else { responseEntity = new ResponseEntity<JSONObject>( sessionObject, HttpStatus.OK); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return responseEntity; }//************************* Get Report By Id ************************************************************************************ }
5,892
0.524949
0.52427
152
37.763157
32.801582
136
false
false
0
0
0
0
0
0
0.407895
false
false
9
c4a5e63a7f7d8278c248326beefec75c8f10fa0e
23,922,967,847,469
1f2abaec0a04355efeb0a00715207a259a42511c
/upskilling/src/inheritance/sampleinheritance.java
bd2ae699a9db9fa19495d1546256fdb0d5f85d90
[]
no_license
Suan28cancy/suan
https://github.com/Suan28cancy/suan
3fb3168d73d510607a2da9abf5429f7150412940
cfb4b5828f4b3ed9abf2b8fd7a54de0be664e748
refs/heads/master
2020-03-21T14:17:36.574000
2018-06-25T21:23:21
2018-06-25T21:23:21
138,649,900
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package inheritance; //import org.junit.Test; public class sampleinheritance { public int Add(){ int a = 5; int b = 2; int c=a+b; return c;} }
UTF-8
Java
177
java
sampleinheritance.java
Java
[]
null
[]
package inheritance; //import org.junit.Test; public class sampleinheritance { public int Add(){ int a = 5; int b = 2; int c=a+b; return c;} }
177
0.559322
0.548023
17
8.294118
9.826523
32
false
false
0
0
0
0
0
0
0.764706
false
false
9
3955a35b2ca0f31cca7633a39f61d4ce18fa92a5
19,370,302,509,508
982074ef28743d1c5726de79ccd13f5426f9b2ae
/src/pe/joedayz/supermercado/exception/PersistenceException.java
07de39d9f16b33759c26a397dc35cbd54e0c8da0
[ "Apache-2.0" ]
permissive
joedayz/TrabajoJavaDelCanal
https://github.com/joedayz/TrabajoJavaDelCanal
266555bef2d7811281da75a978889d05fce350fa
1758f412cd7de0f2d9db4bdeae05425cfe47c324
refs/heads/master
2022-12-16T21:05:21.714000
2020-09-09T20:18:10
2020-09-09T20:18:10
280,558,877
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.joedayz.supermercado.exception; public class PersistenceException extends RuntimeException { public PersistenceException(String msg){ super(msg); } public PersistenceException(Exception ex){ super(ex); } public PersistenceException(String msg, Exception ex){ super(msg, ex); } }
UTF-8
Java
342
java
PersistenceException.java
Java
[]
null
[]
package pe.joedayz.supermercado.exception; public class PersistenceException extends RuntimeException { public PersistenceException(String msg){ super(msg); } public PersistenceException(Exception ex){ super(ex); } public PersistenceException(String msg, Exception ex){ super(msg, ex); } }
342
0.684211
0.684211
16
20.375
21.546099
60
false
false
0
0
0
0
0
0
0.375
false
false
9
f1c7837dad5e5d4c93bbd9de4a37ca5c5f1f69d2
24,000,277,283,395
26472b7e73ffa0ba72965fd84f281fcca6dc9f8d
/leecode/src/牛客/剑指offer/JZ21_Solution.java
6b07ef65827f5208698bb58a03b14f7075eced83
[]
no_license
z-dian/Java
https://github.com/z-dian/Java
cfa1d08a465152871859319e8cc846476f54b1d2
461e6b3b64f26a20f5e2d083eefcb17586c9cd4b
refs/heads/master
2023-04-11T15:03:48.176000
2021-04-14T05:00:50
2021-04-14T05:00:50
225,359,228
0
0
null
false
2020-06-19T12:54:08
2019-12-02T11:30:22
2020-06-19T12:43:12
2020-06-18T06:38:18
10,098
0
0
0
Java
false
false
package 牛客.剑指offer; import java.util.Stack; /** * @ClassName JZ21_Solution * @Description 栈的压入、弹出序列 * @Author 张点 * @Date 2020/8/22 12:14 * @Version 1.0 **/ public class JZ21_Solution { public static boolean IsPopOrder(int[] pushA, int[] popA) { Stack<Integer> stackA = new Stack<>(); int j = 0; for (int i = 0; i < pushA.length; i++) { stackA.push(pushA[i]); while (!stackA.isEmpty()&&stackA.peek() == popA[j]) { stackA.pop(); j++; } } return stackA.isEmpty(); } public static void main(String[] args) { int[] numA = {1, 2, 3, 4, 5}; int[] popA = {4, 5, 3, 2, 1}; System.out.println(IsPopOrder(numA, popA)); } }
UTF-8
Java
831
java
JZ21_Solution.java
Java
[ { "context": "1_Solution\r\n * @Description 栈的压入、弹出序列\r\n * @Author 张点\r\n * @Date 2020/8/22 12:14\r\n * @Version 1.0\r\n **/", "end": 123, "score": 0.9421285390853882, "start": 122, "tag": "NAME", "value": "张" }, { "context": "_Solution\r\n * @Description 栈的压入、弹出序列\r\n * @Author 张点\...
null
[]
package 牛客.剑指offer; import java.util.Stack; /** * @ClassName JZ21_Solution * @Description 栈的压入、弹出序列 * @Author 张点 * @Date 2020/8/22 12:14 * @Version 1.0 **/ public class JZ21_Solution { public static boolean IsPopOrder(int[] pushA, int[] popA) { Stack<Integer> stackA = new Stack<>(); int j = 0; for (int i = 0; i < pushA.length; i++) { stackA.push(pushA[i]); while (!stackA.isEmpty()&&stackA.peek() == popA[j]) { stackA.pop(); j++; } } return stackA.isEmpty(); } public static void main(String[] args) { int[] numA = {1, 2, 3, 4, 5}; int[] popA = {4, 5, 3, 2, 1}; System.out.println(IsPopOrder(numA, popA)); } }
831
0.489388
0.453184
31
23.838709
18.379681
66
false
false
0
0
0
0
0
0
0.741935
false
false
9
7aff30a2b3e2314e8d1db9088168c33d4c50fe0a
21,345,987,487,403
d42229ef1334e83d6e1db6dc0e0d1c370ba69f03
/app/src/main/java/com/healthwix/activity/BaseActivity.java
dc5bf7c7ccadcc0a7dcf70b887d09e240f3db51e
[]
no_license
Aniruddh2008/HealthWix
https://github.com/Aniruddh2008/HealthWix
13753fcb39e51f8246777ae6280cb870a62d7497
276c857de01f46a6d133883ddae1f204becee34b
refs/heads/master
2020-04-21T20:45:04.194000
2019-02-09T10:35:39
2019-02-09T10:35:39
169,855,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.healthwix.activity; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import com.healthwix.util.Util; /** * Created by A12PCHBR on 11/9/2017. */ public abstract class BaseActivity extends AppCompatActivity { private int REQUEST_STORAGE_PERMISSION = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(myView()); } /*@Override protected void attachBaseContext(Context context) { super.attachBaseContext(CalligraphyContextWrapper.wrap(context)); }*/ public void addFragment(@IdRes int containerViewId, @NonNull Fragment fragment, @NonNull String fragmentTag) { getSupportFragmentManager() .beginTransaction() .add(containerViewId, fragment, fragmentTag) .disallowAddToBackStack() .commit(); } public void replaceFragment(@IdRes int containerViewId, @NonNull Fragment fragment, @NonNull String fragmentTag, @Nullable String backStackStateName) { getSupportFragmentManager() .beginTransaction() .replace(containerViewId, fragment, fragmentTag) .commitAllowingStateLoss(); } /* public void addFragment(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(R.anim.left_to_right, R.anim.right_to_left); fragmentTransaction.replace(R.id.fragment_container, fragment, fragment.getClass().getName()); fragmentTransaction.addToBackStack(fragment.getClass().getName()); fragmentTransaction.commit(); }*/ protected abstract int myView(); public boolean checkPermission(Activity activity) { int result = ContextCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE); int result1 = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA); return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED; } // private onPermissionCallback permissionCallback; // public void setPermissionCallback(onPermissionCallback permissionCallback) // { // this.permissionCallback=permissionCallback; // } // @Override // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); // if (requestCode == REQUEST_STORAGE_PERMISSION) { // if (grantResults.length > 0) { // // boolean storagPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED; // boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; // if (storagPermission && cameraAccepted) { // if (permissionCallback != null) // permissionCallback.onPermissionGranted(requestCode); // } // else Util.showToast(this, "Please grant permission"); // } // // else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) { // if(permissionCallback!=null) // permissionCallback.onPermissionRationale(requestCode); // } else { // if(permissionCallback!=null) // permissionCallback.onPermissionDenied(requestCode); // } // } // } // public interface onPermissionCallback{ // void onPermissionGranted(int requestCode); // void onPermissionDenied(int requestCode); // void onPermissionRationale(int requestCode); // } }
UTF-8
Java
4,526
java
BaseActivity.java
Java
[ { "context": "ort com.healthwix.util.Util;\r\n\r\n/**\r\n * Created by A12PCHBR on 11/9/2017.\r\n */\r\n\r\npublic abstract class BaseA", "end": 556, "score": 0.9996369481086731, "start": 548, "tag": "USERNAME", "value": "A12PCHBR" } ]
null
[]
package com.healthwix.activity; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import com.healthwix.util.Util; /** * Created by A12PCHBR on 11/9/2017. */ public abstract class BaseActivity extends AppCompatActivity { private int REQUEST_STORAGE_PERMISSION = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(myView()); } /*@Override protected void attachBaseContext(Context context) { super.attachBaseContext(CalligraphyContextWrapper.wrap(context)); }*/ public void addFragment(@IdRes int containerViewId, @NonNull Fragment fragment, @NonNull String fragmentTag) { getSupportFragmentManager() .beginTransaction() .add(containerViewId, fragment, fragmentTag) .disallowAddToBackStack() .commit(); } public void replaceFragment(@IdRes int containerViewId, @NonNull Fragment fragment, @NonNull String fragmentTag, @Nullable String backStackStateName) { getSupportFragmentManager() .beginTransaction() .replace(containerViewId, fragment, fragmentTag) .commitAllowingStateLoss(); } /* public void addFragment(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(R.anim.left_to_right, R.anim.right_to_left); fragmentTransaction.replace(R.id.fragment_container, fragment, fragment.getClass().getName()); fragmentTransaction.addToBackStack(fragment.getClass().getName()); fragmentTransaction.commit(); }*/ protected abstract int myView(); public boolean checkPermission(Activity activity) { int result = ContextCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE); int result1 = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA); return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED; } // private onPermissionCallback permissionCallback; // public void setPermissionCallback(onPermissionCallback permissionCallback) // { // this.permissionCallback=permissionCallback; // } // @Override // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); // if (requestCode == REQUEST_STORAGE_PERMISSION) { // if (grantResults.length > 0) { // // boolean storagPermission = grantResults[0] == PackageManager.PERMISSION_GRANTED; // boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; // if (storagPermission && cameraAccepted) { // if (permissionCallback != null) // permissionCallback.onPermissionGranted(requestCode); // } // else Util.showToast(this, "Please grant permission"); // } // // else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) { // if(permissionCallback!=null) // permissionCallback.onPermissionRationale(requestCode); // } else { // if(permissionCallback!=null) // permissionCallback.onPermissionDenied(requestCode); // } // } // } // public interface onPermissionCallback{ // void onPermissionGranted(int requestCode); // void onPermissionDenied(int requestCode); // void onPermissionRationale(int requestCode); // } }
4,526
0.645603
0.640963
106
40.698112
30.933029
123
false
false
0
0
0
0
0
0
0.575472
false
false
9
3fed58f9e1b3fa32e9dcce179795e9b32604d093
17,119,739,700,103
4e74a163478798d3a82585b1b26ed7b8f27c79cd
/probus-dist-queue/probus-dist-queue-nio/src/main/java/com/tmaxsoft/probus/dq/nio/server/DqReadWorker.java
af903c71ad59a604a5bb24e7a10f796aea13e872
[]
no_license
xenzo/Distributed-Queue
https://github.com/xenzo/Distributed-Queue
ffa7211e224c7b7f3925ed2d8a2e14ed6132d9a1
9f9ea0aa07ecc12f0ca21ef4c07ada9bbc51fd8d
refs/heads/master
2021-01-20T05:58:28.241000
2014-10-16T17:03:03
2014-10-16T17:03:03
3,150,586
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * DqReadWorker.java Version 1.0 Jan 27, 2012 * * * Copyright (c) 2010 by Tmax Soft co., Ltd. * All rights reserved. * * * This software is the confidential and proprietary information of * Tmax Soft co.,Ltd("Confidential Information"). * You shall not disclose such Confidential Information * and shall use it only in accordance with the terms of the license agreement * entered into with Tmax Soft co., Ltd. */ package com.tmaxsoft.probus.dq.nio.server; import static java.util.logging.Level.*; import java.nio.channels.SelectionKey; import java.util.logging.Logger; import com.tmaxsoft.probus.dq.DqNode; import com.tmaxsoft.probus.dq.nio.AbstractDqReadWorker; /** * */ public class DqReadWorker extends AbstractDqReadWorker { /** * Logger for this class */ private final transient Logger logger = Logger.getLogger("com.tmaxsoft.probus.dq.nio"); /** * @param id * @param key * @param protocol * @param length */ public DqReadWorker(final DqNode node, String id, final SelectionKey key, final String protocol, final int length) { super(node, id, key, protocol, length); } // (non-Javadoc) // @see com.tmaxsoft.probus.dq.nio.IDqWorker#process() @Override public void process() { if (logger.isLoggable(INFO)) logger.logp(INFO, getClass().getName(), "process", "", new Object[] {}); } }
UTF-8
Java
1,395
java
DqReadWorker.java
Java
[]
null
[]
/* * DqReadWorker.java Version 1.0 Jan 27, 2012 * * * Copyright (c) 2010 by Tmax Soft co., Ltd. * All rights reserved. * * * This software is the confidential and proprietary information of * Tmax Soft co.,Ltd("Confidential Information"). * You shall not disclose such Confidential Information * and shall use it only in accordance with the terms of the license agreement * entered into with Tmax Soft co., Ltd. */ package com.tmaxsoft.probus.dq.nio.server; import static java.util.logging.Level.*; import java.nio.channels.SelectionKey; import java.util.logging.Logger; import com.tmaxsoft.probus.dq.DqNode; import com.tmaxsoft.probus.dq.nio.AbstractDqReadWorker; /** * */ public class DqReadWorker extends AbstractDqReadWorker { /** * Logger for this class */ private final transient Logger logger = Logger.getLogger("com.tmaxsoft.probus.dq.nio"); /** * @param id * @param key * @param protocol * @param length */ public DqReadWorker(final DqNode node, String id, final SelectionKey key, final String protocol, final int length) { super(node, id, key, protocol, length); } // (non-Javadoc) // @see com.tmaxsoft.probus.dq.nio.IDqWorker#process() @Override public void process() { if (logger.isLoggable(INFO)) logger.logp(INFO, getClass().getName(), "process", "", new Object[] {}); } }
1,395
0.685305
0.676702
49
27.469387
29.59185
120
false
false
0
0
0
0
0
0
0.510204
false
false
9
a3bf62c50c8d2d35065efab18bb95883b79aa2a9
16,887,811,439,724
e574a169bde3fbf21840d838290a1d44486804fd
/src/main/java/com/model/CustomerOrder.java
4ada2508a180e5a9b93dc2945654608ff2262605
[]
no_license
dangvu5998/Ecommerce-Web
https://github.com/dangvu5998/Ecommerce-Web
0cddbb5fff02c73040f91249b85f49f51d4b3bbe
9589e011d454fa707b5fa46cc1ff2503a2159c2b
refs/heads/master
2023-01-09T07:12:33.501000
2019-12-11T07:06:26
2019-12-11T07:06:26
220,037,579
0
2
null
false
2022-12-16T09:45:12
2019-11-06T16:09:30
2019-12-11T07:06:36
2022-12-16T09:45:08
12,862
0
0
11
Java
false
false
package com.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "customerorder") public class CustomerOrder implements Serializable { private static final long serialVersionUID = -6571020025726257848L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int customerOrderId; private String address; private String note; @OneToOne @JoinColumn(name = "cartId") private Cart cart; @OneToOne @JoinColumn(name = "customerId") private Customer customer; public int getCustomerOrderId() { return customerOrderId; } public void setCustomerOrderId(int customerOrderId) { this.customerOrderId = customerOrderId; } public Cart getCart() { return cart; } public void setCart(Cart cart) { this.cart = cart; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public void setNote(String note) { this.note = note; } public String getNote() { return note; } }
UTF-8
Java
1,366
java
CustomerOrder.java
Java
[]
null
[]
package com.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "customerorder") public class CustomerOrder implements Serializable { private static final long serialVersionUID = -6571020025726257848L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int customerOrderId; private String address; private String note; @OneToOne @JoinColumn(name = "cartId") private Cart cart; @OneToOne @JoinColumn(name = "customerId") private Customer customer; public int getCustomerOrderId() { return customerOrderId; } public void setCustomerOrderId(int customerOrderId) { this.customerOrderId = customerOrderId; } public Cart getCart() { return cart; } public void setCart(Cart cart) { this.cart = cart; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public void setNote(String note) { this.note = note; } public String getNote() { return note; } }
1,366
0.752562
0.738653
74
17.459459
16.959562
68
false
false
0
0
0
0
0
0
1.054054
false
false
9
fb179d2dc4ac4b015a844342819c59c2a351dc77
15,547,781,633,706
686792a4375b084648a7ef86208fcffb919f8a87
/src/main/java/com/ghostph/lucene/htmlParser/FetchTable.java
97e18127165b5a4402a76299e6647f9d46e91169
[]
no_license
ghost-ph/lucenedemo
https://github.com/ghost-ph/lucenedemo
3ea41eb489c010bfc0ee55c0113f4888488efcad
c9035b4db53da58c1dc246e1ac323ebe32d898fa
refs/heads/master
2021-04-09T14:16:04.726000
2018-03-18T14:44:30
2018-03-18T14:44:30
125,732,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ghostph.lucene.htmlParser; /** * Created by ghostph on 2016-02-06. */ public class FetchTable { }
UTF-8
Java
113
java
FetchTable.java
Java
[ { "context": " com.ghostph.lucene.htmlParser;\n\n/**\n * Created by ghostph on 2016-02-06.\n */\npublic class FetchTable {\n}\n", "end": 65, "score": 0.9993035197257996, "start": 58, "tag": "USERNAME", "value": "ghostph" } ]
null
[]
package com.ghostph.lucene.htmlParser; /** * Created by ghostph on 2016-02-06. */ public class FetchTable { }
113
0.707965
0.637168
7
15.142858
15.941218
38
false
false
0
0
0
0
0
0
0.142857
false
false
9
423f5294eb6d1626c34c7c82f22f8857225d47b4
8,220,567,410,881
4b0bf4787e89bcae7e4759bde6d7f3ab2c81f849
/aliyun-java-sdk-eflo/src/main/java/com/aliyuncs/eflo/model/v20220530/QueryInstanceNcdResponse.java
22b2d831f0107cfb6e984e045d6c712f7db3f81d
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-java-sdk
https://github.com/aliyun/aliyun-openapi-java-sdk
a263fa08e261f12d45586d1b3ad8a6609bba0e91
e19239808ad2298d32dda77db29a6d809e4f7add
refs/heads/master
2023-09-03T12:28:09.765000
2023-09-01T09:03:00
2023-09-01T09:03:00
39,555,898
1,542
1,317
NOASSERTION
false
2023-09-14T07:27:05
2015-07-23T08:41:13
2023-08-31T07:30:44
2023-09-14T07:27:03
72,323
1,375
1,144
12
Java
false
false
/* * 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.aliyuncs.eflo.model.v20220530; import com.aliyuncs.AcsResponse; import com.aliyuncs.eflo.transform.v20220530.QueryInstanceNcdResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class QueryInstanceNcdResponse extends AcsResponse { private Integer code; private String message; private String requestId; private Content content; public Integer getCode() { return this.code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Content getContent() { return this.content; } public void setContent(Content content) { this.content = content; } public static class Content { private Integer ncd; private String instanceId1; private String instanceId2; private String instanceType; public Integer getNcd() { return this.ncd; } public void setNcd(Integer ncd) { this.ncd = ncd; } public String getInstanceId1() { return this.instanceId1; } public void setInstanceId1(String instanceId1) { this.instanceId1 = instanceId1; } public String getInstanceId2() { return this.instanceId2; } public void setInstanceId2(String instanceId2) { this.instanceId2 = instanceId2; } public String getInstanceType() { return this.instanceType; } public void setInstanceType(String instanceType) { this.instanceType = instanceType; } } @Override public QueryInstanceNcdResponse getInstance(UnmarshallerContext context) { return QueryInstanceNcdResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
UTF-8
Java
2,576
java
QueryInstanceNcdResponse.java
Java
[]
null
[]
/* * 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.aliyuncs.eflo.model.v20220530; import com.aliyuncs.AcsResponse; import com.aliyuncs.eflo.transform.v20220530.QueryInstanceNcdResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class QueryInstanceNcdResponse extends AcsResponse { private Integer code; private String message; private String requestId; private Content content; public Integer getCode() { return this.code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Content getContent() { return this.content; } public void setContent(Content content) { this.content = content; } public static class Content { private Integer ncd; private String instanceId1; private String instanceId2; private String instanceType; public Integer getNcd() { return this.ncd; } public void setNcd(Integer ncd) { this.ncd = ncd; } public String getInstanceId1() { return this.instanceId1; } public void setInstanceId1(String instanceId1) { this.instanceId1 = instanceId1; } public String getInstanceId2() { return this.instanceId2; } public void setInstanceId2(String instanceId2) { this.instanceId2 = instanceId2; } public String getInstanceType() { return this.instanceType; } public void setInstanceType(String instanceType) { this.instanceType = instanceType; } } @Override public QueryInstanceNcdResponse getInstance(UnmarshallerContext context) { return QueryInstanceNcdResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
2,576
0.712733
0.699534
119
19.857143
21.819075
82
false
false
0
0
0
0
0
0
1.252101
false
false
9
f612c49d5497a02a066810862d4c61f8df957cf5
27,513,560,558,693
1d9bb0a245c91e6ad1ea52f9e19d235b70315dcb
/src/main/java/com/mazanov/alexander/repository/ExpenseRepositoryImpl.java
82111862fc9d7dc5677f5c49448c0d510ccbbce9
[]
no_license
Bawrip/TestForAzoft
https://github.com/Bawrip/TestForAzoft
036bd2feac6e3f3551baf5b5933b377874386396
dd1b4c248f56f7cafc1be114ae9db67b48bf45f2
refs/heads/master
2020-06-28T11:58:27.862000
2019-08-02T11:13:31
2019-08-02T11:13:31
200,228,819
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mazanov.alexander.repository; import com.mazanov.alexander.entities.Expense; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class ExpenseRepositoryImpl implements ExpenseRepository{ private List<Expense> expenses = new ArrayList<>(); public ExpenseRepositoryImpl() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH); Expense expense1 = new Expense(); expense1.setId(1L); expense1.setComment("comment1"); expense1.setDescription("desc1"); expense1.setSpendingAmount(312.1); expense1.setDate(LocalDate.parse("21.03.2019", formatter)); Expense expense2 = new Expense(); expense2.setId(2L); expense2.setComment("comment2"); expense2.setDescription("desc2"); expense2.setSpendingAmount(855.31); expense2.setDate(LocalDate.parse("17.04.2019", formatter)); expenses.add(expense1); expenses.add(expense2); } public void save(Expense expense) { expenses.add(expense); } public void delete(Expense expense) { expenses.remove(expense); } public List<Expense> getAll() { return expenses; } public Expense getById(Long id) { return expenses.get(id.intValue()); } }
UTF-8
Java
1,416
java
ExpenseRepositoryImpl.java
Java
[]
null
[]
package com.mazanov.alexander.repository; import com.mazanov.alexander.entities.Expense; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class ExpenseRepositoryImpl implements ExpenseRepository{ private List<Expense> expenses = new ArrayList<>(); public ExpenseRepositoryImpl() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH); Expense expense1 = new Expense(); expense1.setId(1L); expense1.setComment("comment1"); expense1.setDescription("desc1"); expense1.setSpendingAmount(312.1); expense1.setDate(LocalDate.parse("21.03.2019", formatter)); Expense expense2 = new Expense(); expense2.setId(2L); expense2.setComment("comment2"); expense2.setDescription("desc2"); expense2.setSpendingAmount(855.31); expense2.setDate(LocalDate.parse("17.04.2019", formatter)); expenses.add(expense1); expenses.add(expense2); } public void save(Expense expense) { expenses.add(expense); } public void delete(Expense expense) { expenses.remove(expense); } public List<Expense> getAll() { return expenses; } public Expense getById(Long id) { return expenses.get(id.intValue()); } }
1,416
0.675141
0.643362
49
27.897959
22.041931
96
false
false
0
0
0
0
0
0
0.612245
false
false
9
438959115831c2210ea1729b283bf4a9cd780b4e
20,547,123,566,635
919e6c9bc5b061903148dabfc0875816818d2460
/Play-LeetCode/leetcode_417_PacificAtlanticWaterFlow.java
2467038eeee3241d9569577cc5acb096ab95e30a
[]
no_license
fightzhong/Play_Algorithm
https://github.com/fightzhong/Play_Algorithm
214c441de0bacaf8aade2dea7658d3809fd8ed80
9e0016c50c4d58697c56f236a67350324e16a998
refs/heads/master
2020-05-16T19:47:16.862000
2019-08-30T14:27:50
2019-08-30T14:27:50
183,269,757
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 思路: 遍历每一个元素, 对每一个元素都去查找路径 * */ public class leetcode_417_PacificAtlanticWaterFlow { private boolean[][] isVisited; private int[][] flowData = new int[][] { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } }; public static void main(String[] args) { int[][] matrix = new int[][] { {1,2,3}, {8,9,4}, {7,6,5} }; new leetcode_417_PacificAtlanticWaterFlow().pacificAtlantic( matrix ); } public List<int[]> pacificAtlantic(int[][] matrix) { ArrayList<int[]> list = new ArrayList<>(); if ( matrix.length == 0 ) { return list; } isVisited = new boolean[matrix.length][matrix[0].length]; for ( boolean[] b: isVisited ) { Arrays.fill( b, false ); } // 对每一个元素都进行遍历, 查看是否符合条件 for ( int i = 0; i < matrix.length; i ++ ) { for ( int j = 0; j < matrix[i].length; j ++ ) { isVisited[i][j] = true; boolean[] hasPath = new boolean[] { false, false }; searchPath( i, j, matrix, hasPath ); isVisited[i][j] = false; if ( hasPath[0] && hasPath[1] ) { list.add( new int[] { i, j } ); // 同一数组下, 如果一个值能够满足条件, 则其后面相连的所有比其大的值都能满足条件 while ( j + 1 < matrix[0].length && matrix[i][j + 1] >= matrix[i][j] ){ list.add( new int[] { i, j + 1 } ); j++; } } } } return list; } // 判断一个坐标是否能流向太平洋 private void searchPath (int outIndex, int inIndex, int[][] matrix, boolean[] hasPath) { for ( int i = 0; i < 4; i ++ ) { int newOutIndex = outIndex + flowData[i][0]; int newInIndex = inIndex + flowData[i][1]; // 能到达太平洋 if ( newOutIndex < 0 || newInIndex < 0 ) { hasPath[0] = true; } // 能到达大西洋 if ( newOutIndex >= matrix.length || newInIndex >= matrix[0].length ) { hasPath[1] = true; } // 如果没越界, 判断与当前值的大小, 小于等于, 则需要递归下去查找下一层 // 如果hasPath[0] 与 hasPath[1]都为true了, 就不用再找下去了 if ( newOutIndex < matrix.length && newOutIndex >= 0 && newInIndex < matrix[0].length && newInIndex >= 0 && matrix[newOutIndex][newInIndex] <= matrix[outIndex][inIndex] && !isVisited[newOutIndex][newInIndex] && ( !hasPath[0] || !hasPath[1] ) ) { isVisited[newOutIndex][newInIndex] = true; searchPath( newOutIndex, newInIndex, matrix, hasPath ); isVisited[newOutIndex][newInIndex] = false; } } } }
UTF-8
Java
3,247
java
leetcode_417_PacificAtlanticWaterFlow.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 思路: 遍历每一个元素, 对每一个元素都去查找路径 * */ public class leetcode_417_PacificAtlanticWaterFlow { private boolean[][] isVisited; private int[][] flowData = new int[][] { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } }; public static void main(String[] args) { int[][] matrix = new int[][] { {1,2,3}, {8,9,4}, {7,6,5} }; new leetcode_417_PacificAtlanticWaterFlow().pacificAtlantic( matrix ); } public List<int[]> pacificAtlantic(int[][] matrix) { ArrayList<int[]> list = new ArrayList<>(); if ( matrix.length == 0 ) { return list; } isVisited = new boolean[matrix.length][matrix[0].length]; for ( boolean[] b: isVisited ) { Arrays.fill( b, false ); } // 对每一个元素都进行遍历, 查看是否符合条件 for ( int i = 0; i < matrix.length; i ++ ) { for ( int j = 0; j < matrix[i].length; j ++ ) { isVisited[i][j] = true; boolean[] hasPath = new boolean[] { false, false }; searchPath( i, j, matrix, hasPath ); isVisited[i][j] = false; if ( hasPath[0] && hasPath[1] ) { list.add( new int[] { i, j } ); // 同一数组下, 如果一个值能够满足条件, 则其后面相连的所有比其大的值都能满足条件 while ( j + 1 < matrix[0].length && matrix[i][j + 1] >= matrix[i][j] ){ list.add( new int[] { i, j + 1 } ); j++; } } } } return list; } // 判断一个坐标是否能流向太平洋 private void searchPath (int outIndex, int inIndex, int[][] matrix, boolean[] hasPath) { for ( int i = 0; i < 4; i ++ ) { int newOutIndex = outIndex + flowData[i][0]; int newInIndex = inIndex + flowData[i][1]; // 能到达太平洋 if ( newOutIndex < 0 || newInIndex < 0 ) { hasPath[0] = true; } // 能到达大西洋 if ( newOutIndex >= matrix.length || newInIndex >= matrix[0].length ) { hasPath[1] = true; } // 如果没越界, 判断与当前值的大小, 小于等于, 则需要递归下去查找下一层 // 如果hasPath[0] 与 hasPath[1]都为true了, 就不用再找下去了 if ( newOutIndex < matrix.length && newOutIndex >= 0 && newInIndex < matrix[0].length && newInIndex >= 0 && matrix[newOutIndex][newInIndex] <= matrix[outIndex][inIndex] && !isVisited[newOutIndex][newInIndex] && ( !hasPath[0] || !hasPath[1] ) ) { isVisited[newOutIndex][newInIndex] = true; searchPath( newOutIndex, newInIndex, matrix, hasPath ); isVisited[newOutIndex][newInIndex] = false; } } } }
3,247
0.458883
0.442301
82
35.036587
25.150011
92
false
false
0
0
0
0
0
0
0.902439
false
false
9
b3dcbd2aa85d9394a817798fdc44a07acf7774e3
15,350,213,151,344
d52dbc38377d30500adc052fb07416140d9f0784
/component/src/main/java/org/wso2/siddhi/runner/beam/SiddhiPartitionDoFnOperator.java
f1336de3efd517aa8c6358291b4d9597d63bb725
[ "Apache-2.0" ]
permissive
wso2/siddhi-runner-beam
https://github.com/wso2/siddhi-runner-beam
938e9c547e1d78e9ad5bb9b26843461542b98fdd
8e29a11137f1dfdcad4726507713481fb1edd0e6
refs/heads/master
2023-06-28T18:49:46.249000
2020-01-06T04:31:11
2020-01-06T04:31:11
168,316,728
32
6
Apache-2.0
false
2020-01-06T04:31:12
2019-01-30T09:35:57
2019-03-08T12:47:31
2020-01-06T04:31:12
99
1
3
0
Java
false
false
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.siddhi.runner.beam; import org.apache.beam.runners.core.SimpleDoFnRunner; import org.apache.beam.sdk.runners.AppliedPTransform; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.TupleTag; import org.wso2.siddhi.core.event.ComplexEventChunk; /** * DoFnOperator for partition transform. * @param <InputT> * @param <OutputT> */ public class SiddhiPartitionDoFnOperator<InputT, OutputT> extends SiddhiDoFnOperator { private TupleTag secondaryTag; public SiddhiPartitionDoFnOperator (AppliedPTransform transform, PCollection collection, TupleTag tag) throws Exception { super(transform, collection); this.secondaryTag = tag; } @Override public void start() { this.outputManager = new EventChunkOutputManager(new ComplexEventChunk<>(false), this.mainOutputTag, this.secondaryTag); this.delegate = new SimpleDoFnRunner<InputT, OutputT>(options, fn, sideInputReader, outputManager, mainOutputTag, additionalOutputTags, stepContext, inputCoder, outputCoders, windowingStrategy); this.delegate.startBundle(); } }
UTF-8
Java
1,844
java
SiddhiPartitionDoFnOperator.java
Java
[]
null
[]
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.siddhi.runner.beam; import org.apache.beam.runners.core.SimpleDoFnRunner; import org.apache.beam.sdk.runners.AppliedPTransform; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.TupleTag; import org.wso2.siddhi.core.event.ComplexEventChunk; /** * DoFnOperator for partition transform. * @param <InputT> * @param <OutputT> */ public class SiddhiPartitionDoFnOperator<InputT, OutputT> extends SiddhiDoFnOperator { private TupleTag secondaryTag; public SiddhiPartitionDoFnOperator (AppliedPTransform transform, PCollection collection, TupleTag tag) throws Exception { super(transform, collection); this.secondaryTag = tag; } @Override public void start() { this.outputManager = new EventChunkOutputManager(new ComplexEventChunk<>(false), this.mainOutputTag, this.secondaryTag); this.delegate = new SimpleDoFnRunner<InputT, OutputT>(options, fn, sideInputReader, outputManager, mainOutputTag, additionalOutputTags, stepContext, inputCoder, outputCoders, windowingStrategy); this.delegate.startBundle(); } }
1,844
0.731562
0.724512
51
35.156864
30.861088
111
false
false
0
0
0
0
0
0
0.666667
false
false
9
12d9d889b64fa971172931ae88938356e4e9b803
1,382,979,484,599
b1a2fbd474e6385cf8647cad06ab45450ed42cf6
/src/main/java/com/jingzhun/service/TDishwasherLogServiceI.java
230d227e980251ec595625d33b64a1345c7c5358
[]
no_license
wdwhwn/dishwashermanage
https://github.com/wdwhwn/dishwashermanage
70333141c88979274b6979b0c3c77ecd4a6e7a6e
fee7907af185352d1d001821f4a3029b438c0d1f
refs/heads/master
2020-05-23T12:34:22.402000
2019-05-22T06:42:56
2019-05-22T06:42:56
186,758,733
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jingzhun.service; import com.jingzhun.entity.TDishwasherLogEntity; import org.jeecgframework.core.common.service.CommonService; import java.io.Serializable; public interface TDishwasherLogServiceI extends CommonService{ public void delete(TDishwasherLogEntity entity) throws Exception; public Serializable save(TDishwasherLogEntity entity) throws Exception; public void saveOrUpdate(TDishwasherLogEntity entity) throws Exception; }
UTF-8
Java
463
java
TDishwasherLogServiceI.java
Java
[]
null
[]
package com.jingzhun.service; import com.jingzhun.entity.TDishwasherLogEntity; import org.jeecgframework.core.common.service.CommonService; import java.io.Serializable; public interface TDishwasherLogServiceI extends CommonService{ public void delete(TDishwasherLogEntity entity) throws Exception; public Serializable save(TDishwasherLogEntity entity) throws Exception; public void saveOrUpdate(TDishwasherLogEntity entity) throws Exception; }
463
0.831533
0.831533
15
29.866667
29.612761
73
false
false
0
0
0
0
0
0
0.933333
false
false
9
e36ed97f65238a8530719918c9cf588235242c0e
32,564,442,061,649
edcb29cdac45a4c99a66e77d30408fad64be0a5b
/xmq-api/src/main/java/cn/com/xd/interfaces/service/huancheng/impl/HuanchengCodeServiceImpl.java
1c53ffeffd41e7967d158aa40d7339e41c2b26fb
[]
no_license
happy6eve/xmq_server
https://github.com/happy6eve/xmq_server
ff280dd2f1e7cfe44718828d8cbeb9db26f9a412
88b6c2fbb8a2be1921912933ba97c855a3403e71
refs/heads/master
2018-04-12T14:56:07.342000
2016-10-26T15:58:54
2016-10-26T15:58:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.com.xd.interfaces.service.huancheng.impl; import java.util.Date; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.com.xd.interfaces.dao.hc.HcActivityTransactionMapper; import cn.com.xd.interfaces.entity.hc.HcActivityTransaction; import cn.com.xd.interfaces.service.huancheng.HuanchengCodeService; import cn.com.xd.redis.Template.MySpringRedisTemplates; import com.xingmoquan.rediskey.HuanchengKey; import com.xingmoquan.utils.ObjectMapperUtils; @Service public class HuanchengCodeServiceImpl implements HuanchengCodeService { private static Logger logger = LoggerFactory .getLogger(HuanchengCodeServiceImpl.class); @Autowired HcActivityTransactionMapper hcActivityTransactionMapper; @Autowired private MySpringRedisTemplates mySpringRedisTemplates; @Override public Map checkCode(String userName, String fromUser, String sysType) { Code code = new Code(); String codeStr = checkUserHasCode(userName); if (codeStr == null) { code.setStatus("N"); code.setCode(""); code.setMsg("未领取"); } else if (codeStr != null) { code.setStatus("Y"); code.setCode(codeStr); code.setMsg("已经领取"); } /* long count = 1; * try { if (sysType.toUpperCase().contains("IOS")) { String key = String.format( HuanchengKey.SET_HUANCHENG_IOS_RESOURCE_USER, fromUser); // 随机弹出一个code count = mySpringRedisTemplates.countList(key); } else if (sysType.toUpperCase().contains("ANDROID")) { count = mySpringRedisTemplates .countList(HuanchengKey.SET_HUANCHENG_ANDROID_RESOURCE); } } catch (Exception e) { // TODO: handle exception count = 0; logger.error(" checkCode error :", e); } if (count == 0) { code.setStatus("NOCODE"); code.setCode(""); code.setMsg("已经领取完毕"); }*/ return ObjectMapperUtils.convertValue(code, Map.class); } private String checkUserHasCode(String userName) { HcActivityTransaction record = new HcActivityTransaction(); record.setToId(userName); List<HcActivityTransaction> results = hcActivityTransactionMapper .queryToIdAndFromID(record); if (results.size() < 1) { return null; } return results.get(0).getCode(); } @Override public Map sendCode(String userName, String fromUser, String sysType) { String codeStr = checkUserHasCode(userName); Code code = new Code(); // 已经领取激活码 if (codeStr != null) { code.setStatus("Y"); // 已经 code.setCode(codeStr); code.setMsg("成功"); return ObjectMapperUtils.convertValue(code, Map.class); } else { // 未领取激活码 return ObjectMapperUtils.convertValue( getCode(userName, fromUser, sysType, code), Map.class); } } private Code getCode(String userName, String fromUser, String sysType, Code code) { String codeStr = null; if (sysType.toUpperCase().contains("IOS")) { String key = String.format( HuanchengKey.SET_HUANCHENG_IOS_RESOURCE_USER, fromUser); // 随机弹出一个code codeStr = mySpringRedisTemplates.spop(key); } else if (sysType.toUpperCase().contains("ANDROID")) { codeStr = mySpringRedisTemplates .spop(HuanchengKey.SET_HUANCHENG_ANDROID_RESOURCE); } if (codeStr == null) { code.setStatus("N"); // code.setCode(""); code.setMsg("已经领取完"); return code; } // 插入记录表 HcActivityTransaction record = new HcActivityTransaction(); record.setCreateDate(new Date()); record.setFromId(fromUser); record.setCode(codeStr); record.setToId(userName); record.setType(sysType.toUpperCase()); hcActivityTransactionMapper.insert(record); return getRsult(codeStr); } private Code getRsult(String codeStr) { Code code = new Code(); if (codeStr == null) { code.setStatus("N"); code.setCode(""); code.setMsg("已经领取完毕"); } else { code.setStatus("Y"); // 已经 code.setCode(codeStr); code.setMsg("成功"); } return code; } class Code { String status; // y n n没有code String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } String code; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } }
UTF-8
Java
4,525
java
HuanchengCodeServiceImpl.java
Java
[ { "context": "tring key = String.format(\n\t\t\t\t\t\tHuanchengKey.SET_HUANCHENG_IOS_RESOURCE_USER, fromUser);\n\t\t\t\t// 随机弹出一个code\n\t\t", "end": 1456, "score": 0.6357662677764893, "start": 1446, "tag": "KEY", "value": "HUANCHENG_" }, { "context": "ring.format(\n\t\t\t\t\t\tHuanch...
null
[]
package cn.com.xd.interfaces.service.huancheng.impl; import java.util.Date; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.com.xd.interfaces.dao.hc.HcActivityTransactionMapper; import cn.com.xd.interfaces.entity.hc.HcActivityTransaction; import cn.com.xd.interfaces.service.huancheng.HuanchengCodeService; import cn.com.xd.redis.Template.MySpringRedisTemplates; import com.xingmoquan.rediskey.HuanchengKey; import com.xingmoquan.utils.ObjectMapperUtils; @Service public class HuanchengCodeServiceImpl implements HuanchengCodeService { private static Logger logger = LoggerFactory .getLogger(HuanchengCodeServiceImpl.class); @Autowired HcActivityTransactionMapper hcActivityTransactionMapper; @Autowired private MySpringRedisTemplates mySpringRedisTemplates; @Override public Map checkCode(String userName, String fromUser, String sysType) { Code code = new Code(); String codeStr = checkUserHasCode(userName); if (codeStr == null) { code.setStatus("N"); code.setCode(""); code.setMsg("未领取"); } else if (codeStr != null) { code.setStatus("Y"); code.setCode(codeStr); code.setMsg("已经领取"); } /* long count = 1; * try { if (sysType.toUpperCase().contains("IOS")) { String key = String.format( HuanchengKey.SET_HUANCHENG_IOS_RESOURCE_USER, fromUser); // 随机弹出一个code count = mySpringRedisTemplates.countList(key); } else if (sysType.toUpperCase().contains("ANDROID")) { count = mySpringRedisTemplates .countList(HuanchengKey.SET_HUANCHENG_ANDROID_RESOURCE); } } catch (Exception e) { // TODO: handle exception count = 0; logger.error(" checkCode error :", e); } if (count == 0) { code.setStatus("NOCODE"); code.setCode(""); code.setMsg("已经领取完毕"); }*/ return ObjectMapperUtils.convertValue(code, Map.class); } private String checkUserHasCode(String userName) { HcActivityTransaction record = new HcActivityTransaction(); record.setToId(userName); List<HcActivityTransaction> results = hcActivityTransactionMapper .queryToIdAndFromID(record); if (results.size() < 1) { return null; } return results.get(0).getCode(); } @Override public Map sendCode(String userName, String fromUser, String sysType) { String codeStr = checkUserHasCode(userName); Code code = new Code(); // 已经领取激活码 if (codeStr != null) { code.setStatus("Y"); // 已经 code.setCode(codeStr); code.setMsg("成功"); return ObjectMapperUtils.convertValue(code, Map.class); } else { // 未领取激活码 return ObjectMapperUtils.convertValue( getCode(userName, fromUser, sysType, code), Map.class); } } private Code getCode(String userName, String fromUser, String sysType, Code code) { String codeStr = null; if (sysType.toUpperCase().contains("IOS")) { String key = String.format( HuanchengKey.SET_HUANCHENG_IOS_RESOURCE_USER, fromUser); // 随机弹出一个code codeStr = mySpringRedisTemplates.spop(key); } else if (sysType.toUpperCase().contains("ANDROID")) { codeStr = mySpringRedisTemplates .spop(HuanchengKey.SET_HUANCHENG_ANDROID_RESOURCE); } if (codeStr == null) { code.setStatus("N"); // code.setCode(""); code.setMsg("已经领取完"); return code; } // 插入记录表 HcActivityTransaction record = new HcActivityTransaction(); record.setCreateDate(new Date()); record.setFromId(fromUser); record.setCode(codeStr); record.setToId(userName); record.setType(sysType.toUpperCase()); hcActivityTransactionMapper.insert(record); return getRsult(codeStr); } private Code getRsult(String codeStr) { Code code = new Code(); if (codeStr == null) { code.setStatus("N"); code.setCode(""); code.setMsg("已经领取完毕"); } else { code.setStatus("Y"); // 已经 code.setCode(codeStr); code.setMsg("成功"); } return code; } class Code { String status; // y n n没有code String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } String code; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } }
4,525
0.705936
0.704344
174
24.270115
20.304903
73
false
false
0
0
0
0
0
0
2.362069
false
false
9
941907e81288801647054cc64b023ea655b195e8
25,159,918,460,075
903d3f8b7d39c3bd9f065d42f4a94824beb9a1f8
/SeleniumFramework/src/test/java/test/FindSmallestNumber.java
42ec8169a45802705902be489c4257ecd5d761f7
[]
no_license
KhandelwalHarish/WW_Assignment
https://github.com/KhandelwalHarish/WW_Assignment
45ef704afc5976fa9f5977f5b4d8a02ee4272495
0fdecb1d33b5d863603fe139460866140e1e378d
refs/heads/master
2021-07-14T07:41:32.744000
2019-09-19T06:44:50
2019-09-19T06:44:50
209,413,829
0
0
null
false
2020-10-13T16:08:08
2019-09-18T22:22:35
2019-09-19T06:44:52
2020-10-13T16:08:03
64
0
0
1
HTML
false
false
package test; import java.util.Arrays; import java.util.Random; public class FindSmallestNumber{ public static void main(String[] args) { // Create array object. int[] randomNumbers = new int[500]; // Create random numbers. random(randomNumbers); //Using the predefined sort method Arrays.sort(randomNumbers); //Printing the 10th smallest number System.out.println(findNthSmallestNumber(10, randomNumbers)); } /** random number create method */ public static void random(int[] arraylist){ for(int i=0; i < arraylist.length; i++){ arraylist[i] = (int) (Math.random() * 1000); } } // End of random method. /** find nth smallest method. */ public static int findNthSmallestNumber(int n, int[] numbers){ return numbers[n-1]; } // End of findNthSmallesNumber method. }
UTF-8
Java
858
java
FindSmallestNumber.java
Java
[]
null
[]
package test; import java.util.Arrays; import java.util.Random; public class FindSmallestNumber{ public static void main(String[] args) { // Create array object. int[] randomNumbers = new int[500]; // Create random numbers. random(randomNumbers); //Using the predefined sort method Arrays.sort(randomNumbers); //Printing the 10th smallest number System.out.println(findNthSmallestNumber(10, randomNumbers)); } /** random number create method */ public static void random(int[] arraylist){ for(int i=0; i < arraylist.length; i++){ arraylist[i] = (int) (Math.random() * 1000); } } // End of random method. /** find nth smallest method. */ public static int findNthSmallestNumber(int n, int[] numbers){ return numbers[n-1]; } // End of findNthSmallesNumber method. }
858
0.659674
0.644522
37
21.18919
19.225319
63
false
false
0
0
0
0
0
0
1.324324
false
false
9
80a4304a21939077850952b1cb7e4d6e61b90dcd
11,295,764,023,924
9503dc527a4331d796845493520fad003bd9ba9a
/src/cake_ordering_system_design/View_By_Mobile.java
d9ae831c7919690319f89db5eb3dcc7281dddd17
[]
no_license
inayatmemon/CakeOrderingSystem
https://github.com/inayatmemon/CakeOrderingSystem
541a90f61746095422d434d905a98c19cb51bf91
21e18db5f2ffdb1fd1b52a0ade0e6d1c3a9558e9
refs/heads/main
2023-01-22T20:45:51.465000
2020-11-25T08:41:22
2020-11-25T08:41:22
315,865,779
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cake_ordering_system_design; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class View_By_Mobile extends JFrame implements ActionListener { private JPanel contentPane; private JTextField tf_mobile; JTable table; JFrame frame1; String[] columnNames = {"Order_ID","Name", "Mobile No", "Cake Type", "Cake Flavour", "Shape", "Weight", "Rate", "Advance", "Pending", "Rec. Date", "Rec. Time","Special Note"}; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { View_By_Mobile frame = new View_By_Mobile(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public View_By_Mobile() { setTitle("Cake Ordering System"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 497, 431); contentPane = new JPanel(); contentPane.setBackground(new Color(250, 250, 210)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(null); setContentPane(contentPane); javax.swing.UIManager.put("OptionPane.messageFont", new Font("Segoe UI", Font.BOLD, 20)); javax.swing.UIManager.put("OptionPane.buttonFont", new Font("Segoe UI", Font.BOLD, 15)); JLabel lb_title = new JLabel("VIEW BY MOBILE"); lb_title.setForeground(new Color(70, 130, 180)); lb_title.setFont(new Font("Tempus Sans ITC", Font.BOLD, 35)); lb_title.setBounds(76, 13, 332, 45); contentPane.add(lb_title); JLabel lb_mobile = new JLabel("Mobile Number :"); lb_mobile.setFont(new Font("Sitka Text", Font.BOLD, 20)); lb_mobile.setBounds(147, 58, 169, 45); contentPane.add(lb_mobile); tf_mobile = new JTextField(); tf_mobile.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ view(); } } }); tf_mobile.setHorizontalAlignment(SwingConstants.CENTER); tf_mobile.setForeground(new Color(106, 90, 205)); tf_mobile.setFont(new Font("Trebuchet MS", Font.BOLD, 22)); tf_mobile.setBackground(new Color(253, 245, 230)); tf_mobile.setBounds(65, 97, 326, 45); contentPane.add(tf_mobile); tf_mobile.setColumns(10); JButton btn_Submit = new JButton("Submit"); btn_Submit.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ view(); } } }); btn_Submit.setFont(new Font("Sylfaen", Font.BOLD, 25)); btn_Submit.setBackground(new Color(152, 251, 152)); btn_Submit.setBounds(162, 170, 139, 45); contentPane.add(btn_Submit); btn_Submit.addActionListener(this); btn_Submit.setActionCommand("Sub"); JButton btn_Home = new JButton("Home"); btn_Home.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ home(); } } }); btn_Home.setFont(new Font("Sylfaen", Font.BOLD, 25)); btn_Home.setBackground(new Color(72, 209, 204)); btn_Home.setBounds(162, 310, 139, 45); contentPane.add(btn_Home); btn_Home.addActionListener(this); btn_Home.setActionCommand("Home"); JButton btn_back = new JButton("Back"); btn_back.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ back(); } } }); btn_back.setFont(new Font("Sylfaen", Font.BOLD, 25)); btn_back.setBackground(new Color(72, 209, 204)); btn_back.setActionCommand("Home"); btn_back.setBounds(162, 240, 139, 45); contentPane.add(btn_back); btn_back.addActionListener(this); btn_back.setActionCommand("Back"); } public void view(){ try{ frame1 = new JFrame("Database Search Result"); //frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.getContentPane().setLayout(new BorderLayout()); //TableModel tm = new TableModel(); DefaultTableModel model = new DefaultTableModel(); model.setColumnIdentifiers(columnNames); //DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames()); table = new JTable(model); table = new JTable(); table.setModel(model); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setFillsViewportHeight(true); table.setFont(new Font("Sylfaen", Font.PLAIN, 20)); table.setRowHeight(30); table.getColumn("Order_ID").setPreferredWidth(200); table.getColumn("Name").setPreferredWidth(220); table.getColumn("Mobile No").setPreferredWidth(150); table.getColumn("Cake Type").setPreferredWidth(170); table.getColumn("Cake Flavour").setPreferredWidth(170); table.getColumn("Shape").setPreferredWidth(170); table.getColumn("Weight").setPreferredWidth(100); table.getColumn("Rate").setPreferredWidth(100); table.getColumn("Advance").setPreferredWidth(100); table.getColumn("Pending").setPreferredWidth(100); table.getColumn("Rec. Date").setPreferredWidth(180); table.getColumn("Rec. Time").setPreferredWidth(100); table.getColumn("Special Note").setPreferredWidth(400); JScrollPane scroll = new JScrollPane(table); scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); frame1.getContentPane().add(new JScrollPane(scroll)); String mobile = tf_mobile.getText(); Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cake_ordering_system","",""); PreparedStatement ps = con.prepareStatement("Select * from cake_order where Mobile = '"+mobile+"'"); ResultSet rs = ps.executeQuery(); int i=0; while(rs.next()) { long id = rs.getLong("Order_ID"); String name = rs.getString("Name"); String mobile_2 = rs.getString("Mobile"); String cake_type = rs.getString("Cake_Type"); String cake_flavour = rs.getString("Cake_Flavour"); String shape = rs.getString("Shape"); String weight = rs.getString("Weight"); String rate = rs.getString("Rate"); String advance = rs.getString("Advance"); String pending = rs.getString("Pending"); String pickup_date = rs.getString("Rec_Date"); String pickup_time = rs.getString("Rec_Time"); String specialnote = rs.getString("Special_Note"); model.addRow(new Object[]{id,name, mobile_2, cake_type, cake_flavour, shape, weight, rate, advance, pending, pickup_date, pickup_time,specialnote}); i++; } if(i <1) { JOptionPane.showMessageDialog(null, "No Record Found"); } else if(i ==1) { JOptionPane.showMessageDialog(null,i+" Record Found"); } else { JOptionPane.showMessageDialog(null,i+" Records Found"); } con.close(); } catch(Exception ex) { JOptionPane.showMessageDialog(null,"Error"); } //Component scroll = null; frame1.setVisible(true); frame1.setSize(2000,1000); } public void home(){ this.dispose(); Cake_ordering_system_Home pl = new Cake_ordering_system_Home(); pl.setVisible(true); } public void back(){ this.dispose(); View_Order pl2 = new View_Order(); pl2.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String cmd = e.getActionCommand(); if(cmd.equals("Home")){ home(); } else if(cmd.equals("Back")){ back(); } else if(cmd.equals("Sub")){ view(); } }}
UTF-8
Java
9,119
java
View_By_Mobile.java
Java
[]
null
[]
package cake_ordering_system_design; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class View_By_Mobile extends JFrame implements ActionListener { private JPanel contentPane; private JTextField tf_mobile; JTable table; JFrame frame1; String[] columnNames = {"Order_ID","Name", "Mobile No", "Cake Type", "Cake Flavour", "Shape", "Weight", "Rate", "Advance", "Pending", "Rec. Date", "Rec. Time","Special Note"}; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { View_By_Mobile frame = new View_By_Mobile(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public View_By_Mobile() { setTitle("Cake Ordering System"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 497, 431); contentPane = new JPanel(); contentPane.setBackground(new Color(250, 250, 210)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(null); setContentPane(contentPane); javax.swing.UIManager.put("OptionPane.messageFont", new Font("Segoe UI", Font.BOLD, 20)); javax.swing.UIManager.put("OptionPane.buttonFont", new Font("Segoe UI", Font.BOLD, 15)); JLabel lb_title = new JLabel("VIEW BY MOBILE"); lb_title.setForeground(new Color(70, 130, 180)); lb_title.setFont(new Font("Tempus Sans ITC", Font.BOLD, 35)); lb_title.setBounds(76, 13, 332, 45); contentPane.add(lb_title); JLabel lb_mobile = new JLabel("Mobile Number :"); lb_mobile.setFont(new Font("Sitka Text", Font.BOLD, 20)); lb_mobile.setBounds(147, 58, 169, 45); contentPane.add(lb_mobile); tf_mobile = new JTextField(); tf_mobile.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ view(); } } }); tf_mobile.setHorizontalAlignment(SwingConstants.CENTER); tf_mobile.setForeground(new Color(106, 90, 205)); tf_mobile.setFont(new Font("Trebuchet MS", Font.BOLD, 22)); tf_mobile.setBackground(new Color(253, 245, 230)); tf_mobile.setBounds(65, 97, 326, 45); contentPane.add(tf_mobile); tf_mobile.setColumns(10); JButton btn_Submit = new JButton("Submit"); btn_Submit.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ view(); } } }); btn_Submit.setFont(new Font("Sylfaen", Font.BOLD, 25)); btn_Submit.setBackground(new Color(152, 251, 152)); btn_Submit.setBounds(162, 170, 139, 45); contentPane.add(btn_Submit); btn_Submit.addActionListener(this); btn_Submit.setActionCommand("Sub"); JButton btn_Home = new JButton("Home"); btn_Home.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ home(); } } }); btn_Home.setFont(new Font("Sylfaen", Font.BOLD, 25)); btn_Home.setBackground(new Color(72, 209, 204)); btn_Home.setBounds(162, 310, 139, 45); contentPane.add(btn_Home); btn_Home.addActionListener(this); btn_Home.setActionCommand("Home"); JButton btn_back = new JButton("Back"); btn_back.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER){ back(); } } }); btn_back.setFont(new Font("Sylfaen", Font.BOLD, 25)); btn_back.setBackground(new Color(72, 209, 204)); btn_back.setActionCommand("Home"); btn_back.setBounds(162, 240, 139, 45); contentPane.add(btn_back); btn_back.addActionListener(this); btn_back.setActionCommand("Back"); } public void view(){ try{ frame1 = new JFrame("Database Search Result"); //frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.getContentPane().setLayout(new BorderLayout()); //TableModel tm = new TableModel(); DefaultTableModel model = new DefaultTableModel(); model.setColumnIdentifiers(columnNames); //DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames()); table = new JTable(model); table = new JTable(); table.setModel(model); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setFillsViewportHeight(true); table.setFont(new Font("Sylfaen", Font.PLAIN, 20)); table.setRowHeight(30); table.getColumn("Order_ID").setPreferredWidth(200); table.getColumn("Name").setPreferredWidth(220); table.getColumn("Mobile No").setPreferredWidth(150); table.getColumn("Cake Type").setPreferredWidth(170); table.getColumn("Cake Flavour").setPreferredWidth(170); table.getColumn("Shape").setPreferredWidth(170); table.getColumn("Weight").setPreferredWidth(100); table.getColumn("Rate").setPreferredWidth(100); table.getColumn("Advance").setPreferredWidth(100); table.getColumn("Pending").setPreferredWidth(100); table.getColumn("Rec. Date").setPreferredWidth(180); table.getColumn("Rec. Time").setPreferredWidth(100); table.getColumn("Special Note").setPreferredWidth(400); JScrollPane scroll = new JScrollPane(table); scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); frame1.getContentPane().add(new JScrollPane(scroll)); String mobile = tf_mobile.getText(); Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cake_ordering_system","",""); PreparedStatement ps = con.prepareStatement("Select * from cake_order where Mobile = '"+mobile+"'"); ResultSet rs = ps.executeQuery(); int i=0; while(rs.next()) { long id = rs.getLong("Order_ID"); String name = rs.getString("Name"); String mobile_2 = rs.getString("Mobile"); String cake_type = rs.getString("Cake_Type"); String cake_flavour = rs.getString("Cake_Flavour"); String shape = rs.getString("Shape"); String weight = rs.getString("Weight"); String rate = rs.getString("Rate"); String advance = rs.getString("Advance"); String pending = rs.getString("Pending"); String pickup_date = rs.getString("Rec_Date"); String pickup_time = rs.getString("Rec_Time"); String specialnote = rs.getString("Special_Note"); model.addRow(new Object[]{id,name, mobile_2, cake_type, cake_flavour, shape, weight, rate, advance, pending, pickup_date, pickup_time,specialnote}); i++; } if(i <1) { JOptionPane.showMessageDialog(null, "No Record Found"); } else if(i ==1) { JOptionPane.showMessageDialog(null,i+" Record Found"); } else { JOptionPane.showMessageDialog(null,i+" Records Found"); } con.close(); } catch(Exception ex) { JOptionPane.showMessageDialog(null,"Error"); } //Component scroll = null; frame1.setVisible(true); frame1.setSize(2000,1000); } public void home(){ this.dispose(); Cake_ordering_system_Home pl = new Cake_ordering_system_Home(); pl.setVisible(true); } public void back(){ this.dispose(); View_Order pl2 = new View_Order(); pl2.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String cmd = e.getActionCommand(); if(cmd.equals("Home")){ home(); } else if(cmd.equals("Back")){ back(); } else if(cmd.equals("Sub")){ view(); } }}
9,119
0.624959
0.600395
374
22.377005
22.676041
152
false
false
0
0
0
0
0
0
3.360963
false
false
9
a23fdf2b4d4667c3c87982d0f75a26980272582e
22,892,175,728,076
93b7bceadeb25eadbd35707624bf2a67d5869a94
/src/dao/registered_crimes.java
b1b2c9241c6e41dc0182edb85ce63155ae55d829
[]
no_license
Endagegnehu/crs
https://github.com/Endagegnehu/crs
c9145a7aeb5d6adabdb8334bc61f2b86648bd3ef
0f3f5ba7c66a14bd5ccdf1770c2b1e597e6a52ac
refs/heads/master
2020-06-25T10:18:21.223000
2020-02-18T08:47:53
2020-02-18T08:47:53
199,281,964
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dao; import java.util.List; import entity.crime_log; public interface registered_crimes { public List<crime_log> getRegisteredCrimes(); }
UTF-8
Java
150
java
registered_crimes.java
Java
[]
null
[]
package dao; import java.util.List; import entity.crime_log; public interface registered_crimes { public List<crime_log> getRegisteredCrimes(); }
150
0.773333
0.773333
9
15.666667
16.357126
46
false
false
0
0
0
0
0
0
0.555556
false
false
9
1c164bff7c3db1a36892ae2a10503c91958e2529
27,960,237,144,540
454a3166d8a923049316494a54e43e590ecde802
/src/LinkedList/MyDoublyLinkedList.java
573da6e81cf5fd06c3d852e8b52a03716c16e7f7
[]
no_license
eslamalaaeddin/DataStructures
https://github.com/eslamalaaeddin/DataStructures
58909bd0703498c1a4c1bac4b161da0387b1d08c
4f5b3cdb4861651a3c4a2ef8c6c8d39e0c0c56e3
refs/heads/master
2023-06-17T07:33:39.344000
2021-07-13T02:51:31
2021-07-13T02:51:31
376,974,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LinkedList; import java.util.*; public class MyDoublyLinkedList<T> implements Iterable<Node<T>> { //nulls mean empty linked list private Node<T> head = null; private Node<T> tail = null; private int size = 0; public void clear() { Node<T> traversal = head; while (traversal.next != null) { Node<T> nextToTraversal = traversal.next; traversal.previous = traversal.next = null; traversal.value = null; traversal.next = nextToTraversal; } head = tail = traversal = null; size = 0; } public int size() { return size; } public boolean isEmpty() { return size() == 0; } //element means value public void addLast(T element) { Node<T> addedNode = new Node(element, null, null); if (isEmpty()) head = tail = addedNode; else { addedNode.previous = tail; tail.next = addedNode; tail = addedNode; } size++; } public void addFirst(T element) { Node<T> addedNode = new Node(element, null, null); if (isEmpty()) head = tail = addedNode; else { addedNode.next = head; head.previous = addedNode; head = addedNode; } size++; } public T peakFirst() { if (isEmpty()) throw new RuntimeException("Empty List"); return head.value; } public T peakLast() { if (isEmpty()) throw new RuntimeException("Empty List"); return tail.value; } public T removeFirst() { if (isEmpty()) throw new RuntimeException("Empty List"); T value = head.value; head = head.next; --size; //if it becomes empty after deleting the last node if (isEmpty()) tail = null; //there one node at least else head.previous = null; return value; } public T removeLast() { if (isEmpty()) throw new RuntimeException("Empty List"); T value = tail.value; tail = tail.previous; --size; //if it becomes empty after deleting the last node if (isEmpty()) head = null; //there one node at least else tail.next = null; return value; } public boolean remove(T element) { if (isEmpty()) throw new RuntimeException("Empty List"); if (size() == 1 && element == head) { tail = head = null; size--; return true; } for (Node<T> item : this) { if (item.value.equals(element)) { if (item.value.equals(tail.value)) removeLast(); else if (item.value.equals(head.value)) removeFirst(); else { Node<T> previousToRemoved = item.previous; Node<T> nextToRemoved = item.next; nextToRemoved.previous = previousToRemoved; previousToRemoved.next = nextToRemoved; size--; } return true; } } return false; } public void print() { if (this.isEmpty()) { System.out.println("[]"); return; } for (Node<T> node : this) { System.out.print(node.value + " "); } System.out.print("\n----------"); } @Override public Iterator<Node<T>> iterator() { return new Iterator<>() { private Node<T> traversal = head; @Override public boolean hasNext() { return traversal != null; } @Override public Node<T> next() { Node<T> currentNode = traversal; T value = traversal.value; traversal = traversal.next; return currentNode; } }; } } class Node<T> { T value; Node<T> previous, next; public Node(T value, Node<T> previous, Node<T> next) { this.value = value; this.previous = previous; this.next = next; } }
UTF-8
Java
4,362
java
MyDoublyLinkedList.java
Java
[]
null
[]
package LinkedList; import java.util.*; public class MyDoublyLinkedList<T> implements Iterable<Node<T>> { //nulls mean empty linked list private Node<T> head = null; private Node<T> tail = null; private int size = 0; public void clear() { Node<T> traversal = head; while (traversal.next != null) { Node<T> nextToTraversal = traversal.next; traversal.previous = traversal.next = null; traversal.value = null; traversal.next = nextToTraversal; } head = tail = traversal = null; size = 0; } public int size() { return size; } public boolean isEmpty() { return size() == 0; } //element means value public void addLast(T element) { Node<T> addedNode = new Node(element, null, null); if (isEmpty()) head = tail = addedNode; else { addedNode.previous = tail; tail.next = addedNode; tail = addedNode; } size++; } public void addFirst(T element) { Node<T> addedNode = new Node(element, null, null); if (isEmpty()) head = tail = addedNode; else { addedNode.next = head; head.previous = addedNode; head = addedNode; } size++; } public T peakFirst() { if (isEmpty()) throw new RuntimeException("Empty List"); return head.value; } public T peakLast() { if (isEmpty()) throw new RuntimeException("Empty List"); return tail.value; } public T removeFirst() { if (isEmpty()) throw new RuntimeException("Empty List"); T value = head.value; head = head.next; --size; //if it becomes empty after deleting the last node if (isEmpty()) tail = null; //there one node at least else head.previous = null; return value; } public T removeLast() { if (isEmpty()) throw new RuntimeException("Empty List"); T value = tail.value; tail = tail.previous; --size; //if it becomes empty after deleting the last node if (isEmpty()) head = null; //there one node at least else tail.next = null; return value; } public boolean remove(T element) { if (isEmpty()) throw new RuntimeException("Empty List"); if (size() == 1 && element == head) { tail = head = null; size--; return true; } for (Node<T> item : this) { if (item.value.equals(element)) { if (item.value.equals(tail.value)) removeLast(); else if (item.value.equals(head.value)) removeFirst(); else { Node<T> previousToRemoved = item.previous; Node<T> nextToRemoved = item.next; nextToRemoved.previous = previousToRemoved; previousToRemoved.next = nextToRemoved; size--; } return true; } } return false; } public void print() { if (this.isEmpty()) { System.out.println("[]"); return; } for (Node<T> node : this) { System.out.print(node.value + " "); } System.out.print("\n----------"); } @Override public Iterator<Node<T>> iterator() { return new Iterator<>() { private Node<T> traversal = head; @Override public boolean hasNext() { return traversal != null; } @Override public Node<T> next() { Node<T> currentNode = traversal; T value = traversal.value; traversal = traversal.next; return currentNode; } }; } } class Node<T> { T value; Node<T> previous, next; public Node(T value, Node<T> previous, Node<T> next) { this.value = value; this.previous = previous; this.next = next; } }
4,362
0.482348
0.481431
193
21.606218
18.072977
65
false
false
0
0
0
0
0
0
0.414508
false
false
9
2d8f87ce2d6d6dcbdf3d82e0b8d8227edefa94de
23,776,938,984,549
94088caa0e404d070ada5bab1fcc89257c32e4d0
/ANDROBOTIX/src/com/dips/androbotix/game.java
dbcb099d165814bcd9e381fb22796924e5cf3420
[]
no_license
dkarmaka/Projects_Karmakar_Dipayan
https://github.com/dkarmaka/Projects_Karmakar_Dipayan
fa972144a9c082069687ea87642729d59dc9beeb
54c1ec071628620d5f40f9b56b3c8f61d15b5807
refs/heads/master
2020-04-13T13:54:03.348000
2018-12-27T04:42:51
2018-12-27T04:42:51
163,245,873
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dips.androbotix; import java.io.IOException; import java.io.OutputStream; import java.util.UUID; import android.annotation.SuppressLint; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class game extends Activity{ static final int REQUEST_ENABLE_BT = 1; BluetoothAdapter bt=null; TextView dir,spd,lf; BluetoothSocket bs=null; OutputStream ops=null; private static final String t="arduino"; private static final UUID id=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static String address= "20:14:04:10:12:89"; Button f1,f2,f3,b1,b2,b3,cr,ar; Handler h= new Handler(); int delay=1,c=0; MediaPlayer m2,m3; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.game); bt = BluetoothAdapter.getDefaultAdapter(); dir=(TextView)findViewById(R.id.textView3); spd=(TextView)findViewById(R.id.textView2); lf=(TextView)findViewById(R.id.textView4); SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE); final float[] mValuesMagnet = new float[3]; final float[] mValuesAccel = new float[3]; final float[] mValuesOrientation = new float[3]; final float[] mRotationMatrix = new float[9]; final SensorEventListener mEventListener = new SensorEventListener() { public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { // Handle the events for which we registered switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: System.arraycopy(event.values, 0, mValuesAccel, 0, 3); break; case Sensor.TYPE_MAGNETIC_FIELD: System.arraycopy(event.values, 0, mValuesMagnet, 0, 3); break; } }; }; setListners(sensorManager, mEventListener); h.postDelayed(new Runnable(){ public void run(){ SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet); SensorManager.getOrientation(mRotationMatrix, mValuesOrientation); final float y=mValuesOrientation[1]; if(y<(-.3) && c!=1){ send("R"); lf.setText("RIGHT"); c=1; } else if(y>(.3) && c!=2){ send("L"); lf.setText("LEFT"); c=2; } else if(y>(-.3) && y<(.3) && c!=0){ send("F"); lf.setText("DIRECTION"); c=0; } h.postDelayed(this, delay); }}, delay); cr=(Button)findViewById(R.id.button9); cr.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("U"); dir.setText("GEAR: CLOCKWISE"); } if(action==MotionEvent.ACTION_UP){ send("z"); dir.setText("GEAR"); } return false; } }); ar=(Button)findViewById(R.id.button10); ar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("V"); dir.setText("GEAR: ANTICLOCKWISE"); } if(action==MotionEvent.ACTION_UP){ send("z"); dir.setText("GEAR"); } return false; } }); b1=(Button)findViewById(R.id.button5); b1.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("a"); dir.setText("GEAR: BACKWARD"); spd.setText("SPEED: 1"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); b2=(Button)findViewById(R.id.button4); b2.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("b"); dir.setText("GEAR: BACKWARD"); spd.setText("SPEED: 2"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); b3=(Button)findViewById(R.id.button3); b3.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("c"); dir.setText("GEAR: BACKWARD"); spd.setText("SPEED: 3"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); f1=(Button)findViewById(R.id.button6); f1.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("A"); dir.setText("GEAR: FORWARD"); spd.setText("SPEED: 1"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); f2=(Button)findViewById(R.id.button7); f2.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("B"); dir.setText("GEAR: FORWARD"); spd.setText("SPEED: 2"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); f3=(Button)findViewById(R.id.button8); f3.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("C"); dir.setText("GEAR: FORWARD"); spd.setText("SPEED: 3"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); } @SuppressLint("NewApi") public void onResume(){ super.onResume(); m2= MediaPlayer.create(getApplicationContext(), R.raw.engine); m3=MediaPlayer.create(getApplicationContext(), R.raw.game); m3.setLooping(true); m2.setNextMediaPlayer(m3); m2.start(); Log.d(t, "attempting client connect"); BluetoothDevice target= bt.getRemoteDevice(address); try { bs=target.createInsecureRfcommSocketToServiceRecord(id);} catch(IOException e){ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } bt.cancelDiscovery(); Log.d(t, "connecting to remote"); try { bs.connect();} catch(IOException e1){ try {bs.close();} catch(IOException e2){ Toast.makeText(getApplicationContext(), e2.getMessage(), Toast.LENGTH_SHORT).show(); }} Log.d(t, "creating socket"); try { ops= bs.getOutputStream();} catch(IOException e){ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } public void onPause(){ super.onPause(); m2.stop(); m3.stop(); Log.d(t, "In pause"); if(ops!=null){ try {ops.flush();} catch(IOException e){ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } try { bs.close();} catch(IOException e2){ Toast.makeText(getApplicationContext(), e2.getMessage(), Toast.LENGTH_SHORT).show(); } } public void send(String m){ byte[] mb= m.getBytes(); Log.d(t, "sending data" + m); try { ops.write(mb);} catch (IOException e){} } public void setListners(SensorManager sensorManager, SensorEventListener mEventListener) { sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL); } }
UTF-8
Java
9,572
java
game.java
Java
[]
null
[]
package com.dips.androbotix; import java.io.IOException; import java.io.OutputStream; import java.util.UUID; import android.annotation.SuppressLint; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class game extends Activity{ static final int REQUEST_ENABLE_BT = 1; BluetoothAdapter bt=null; TextView dir,spd,lf; BluetoothSocket bs=null; OutputStream ops=null; private static final String t="arduino"; private static final UUID id=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static String address= "20:14:04:10:12:89"; Button f1,f2,f3,b1,b2,b3,cr,ar; Handler h= new Handler(); int delay=1,c=0; MediaPlayer m2,m3; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.game); bt = BluetoothAdapter.getDefaultAdapter(); dir=(TextView)findViewById(R.id.textView3); spd=(TextView)findViewById(R.id.textView2); lf=(TextView)findViewById(R.id.textView4); SensorManager sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE); final float[] mValuesMagnet = new float[3]; final float[] mValuesAccel = new float[3]; final float[] mValuesOrientation = new float[3]; final float[] mRotationMatrix = new float[9]; final SensorEventListener mEventListener = new SensorEventListener() { public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { // Handle the events for which we registered switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: System.arraycopy(event.values, 0, mValuesAccel, 0, 3); break; case Sensor.TYPE_MAGNETIC_FIELD: System.arraycopy(event.values, 0, mValuesMagnet, 0, 3); break; } }; }; setListners(sensorManager, mEventListener); h.postDelayed(new Runnable(){ public void run(){ SensorManager.getRotationMatrix(mRotationMatrix, null, mValuesAccel, mValuesMagnet); SensorManager.getOrientation(mRotationMatrix, mValuesOrientation); final float y=mValuesOrientation[1]; if(y<(-.3) && c!=1){ send("R"); lf.setText("RIGHT"); c=1; } else if(y>(.3) && c!=2){ send("L"); lf.setText("LEFT"); c=2; } else if(y>(-.3) && y<(.3) && c!=0){ send("F"); lf.setText("DIRECTION"); c=0; } h.postDelayed(this, delay); }}, delay); cr=(Button)findViewById(R.id.button9); cr.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("U"); dir.setText("GEAR: CLOCKWISE"); } if(action==MotionEvent.ACTION_UP){ send("z"); dir.setText("GEAR"); } return false; } }); ar=(Button)findViewById(R.id.button10); ar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("V"); dir.setText("GEAR: ANTICLOCKWISE"); } if(action==MotionEvent.ACTION_UP){ send("z"); dir.setText("GEAR"); } return false; } }); b1=(Button)findViewById(R.id.button5); b1.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("a"); dir.setText("GEAR: BACKWARD"); spd.setText("SPEED: 1"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); b2=(Button)findViewById(R.id.button4); b2.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("b"); dir.setText("GEAR: BACKWARD"); spd.setText("SPEED: 2"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); b3=(Button)findViewById(R.id.button3); b3.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("c"); dir.setText("GEAR: BACKWARD"); spd.setText("SPEED: 3"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); f1=(Button)findViewById(R.id.button6); f1.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("A"); dir.setText("GEAR: FORWARD"); spd.setText("SPEED: 1"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); f2=(Button)findViewById(R.id.button7); f2.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("B"); dir.setText("GEAR: FORWARD"); spd.setText("SPEED: 2"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); f3=(Button)findViewById(R.id.button8); f3.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub int action= event.getAction(); if(action==MotionEvent.ACTION_DOWN){ send("C"); dir.setText("GEAR: FORWARD"); spd.setText("SPEED: 3"); } if(action==MotionEvent.ACTION_UP){ send("z"); spd.setText("SPEED: 0"); dir.setText("GEAR"); } return false; } }); } @SuppressLint("NewApi") public void onResume(){ super.onResume(); m2= MediaPlayer.create(getApplicationContext(), R.raw.engine); m3=MediaPlayer.create(getApplicationContext(), R.raw.game); m3.setLooping(true); m2.setNextMediaPlayer(m3); m2.start(); Log.d(t, "attempting client connect"); BluetoothDevice target= bt.getRemoteDevice(address); try { bs=target.createInsecureRfcommSocketToServiceRecord(id);} catch(IOException e){ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } bt.cancelDiscovery(); Log.d(t, "connecting to remote"); try { bs.connect();} catch(IOException e1){ try {bs.close();} catch(IOException e2){ Toast.makeText(getApplicationContext(), e2.getMessage(), Toast.LENGTH_SHORT).show(); }} Log.d(t, "creating socket"); try { ops= bs.getOutputStream();} catch(IOException e){ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } public void onPause(){ super.onPause(); m2.stop(); m3.stop(); Log.d(t, "In pause"); if(ops!=null){ try {ops.flush();} catch(IOException e){ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } try { bs.close();} catch(IOException e2){ Toast.makeText(getApplicationContext(), e2.getMessage(), Toast.LENGTH_SHORT).show(); } } public void send(String m){ byte[] mb= m.getBytes(); Log.d(t, "sending data" + m); try { ops.write(mb);} catch (IOException e){} } public void setListners(SensorManager sensorManager, SensorEventListener mEventListener) { sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(mEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL); } }
9,572
0.62359
0.610949
342
26.988304
21.749231
115
false
false
0
0
0
0
0
0
2.865497
false
false
9
b075b1ff1b7b711afa30d5e0ce58bc7b477e1266
14,559,939,179,247
8a1a9cd277d84939f271d7a3943380e1a4625393
/world-server/src/main/java/pl/cwanix/opensun/worldserver/packets/processors/sync/C2S483CProcessor.java
abd0a2b1ede0766e995737a5bf37902e39625cc2
[ "MIT" ]
permissive
peterboynn/OpenSUN-Server
https://github.com/peterboynn/OpenSUN-Server
21bd94a30c45edb0b0ab584f36608c4a2aeb38cc
00eea3963795fead3ec1de7e977a63ff6a4ce8e2
refs/heads/master
2023-06-18T03:42:36.076000
2021-07-13T21:38:22
2021-07-13T21:38:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.cwanix.opensun.worldserver.packets.processors.sync; import io.netty.channel.ChannelHandlerContext; import lombok.RequiredArgsConstructor; import pl.cwanix.opensun.commonserver.packets.SUNPacketProcessor; import pl.cwanix.opensun.commonserver.packets.annotations.PacketProcessor; import pl.cwanix.opensun.worldserver.packets.c2s.connection.C2S483CPacket; @RequiredArgsConstructor @PacketProcessor(packetClass = C2S483CPacket.class) public class C2S483CProcessor implements SUNPacketProcessor<C2S483CPacket> { @Override public void process(final ChannelHandlerContext ctx, final C2S483CPacket packet) { } }
UTF-8
Java
632
java
C2S483CProcessor.java
Java
[]
null
[]
package pl.cwanix.opensun.worldserver.packets.processors.sync; import io.netty.channel.ChannelHandlerContext; import lombok.RequiredArgsConstructor; import pl.cwanix.opensun.commonserver.packets.SUNPacketProcessor; import pl.cwanix.opensun.commonserver.packets.annotations.PacketProcessor; import pl.cwanix.opensun.worldserver.packets.c2s.connection.C2S483CPacket; @RequiredArgsConstructor @PacketProcessor(packetClass = C2S483CPacket.class) public class C2S483CProcessor implements SUNPacketProcessor<C2S483CPacket> { @Override public void process(final ChannelHandlerContext ctx, final C2S483CPacket packet) { } }
632
0.841772
0.808544
17
36.176472
31.507675
86
false
false
0
0
0
0
0
0
0.411765
false
false
9
73e6a2c1a504d48232170cd7ef81409e4570dfc4
7,103,875,952,059
c9afb2c99d339591e3b4bae55730cf9e6ee6d83b
/src/main/java/com/joha/exercise/configuration/ApplicationConfiguration.java
a770a0b48bc1249b3e21a968df0e3df450941030
[]
no_license
johannesblhansen/search
https://github.com/johannesblhansen/search
43b33dfd95ed5209c2fee4424b0f3c7fff509e31
006dcab8d658c1bcdea6356f9d4da9b55639d7de
refs/heads/master
2023-08-12T12:57:26.297000
2021-09-20T19:13:02
2021-09-20T19:13:02
376,573,611
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.joha.exercise.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration @EnableScheduling @ComponentScan(basePackages = "com.joha.exercise.*") @EnableAsync public class ApplicationConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.joha.exercise.controllers")) .paths(PathSelectors.any()) .build(); } }
UTF-8
Java
1,005
java
ApplicationConfiguration.java
Java
[]
null
[]
package com.joha.exercise.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration @EnableScheduling @ComponentScan(basePackages = "com.joha.exercise.*") @EnableAsync public class ApplicationConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.joha.exercise.controllers")) .paths(PathSelectors.any()) .build(); } }
1,005
0.775124
0.774129
27
36.222221
25.095865
91
false
false
0
0
0
0
0
0
0.407407
false
false
9
e83afafa1fa25170e96c0e9d2065938e43abfc98
16,449,724,790,780
598439ae96926bfb7d4b04c046b899c1065710cc
/thizzle/src/main/java/com/example/thizzle/ai/algorithms/AStar.java
40fca17c8bfd0926adcd657552099d6a8ab5ee96
[]
no_license
Thizzle12/thizzle-ai-server
https://github.com/Thizzle12/thizzle-ai-server
f6266cd35058f4fe1f948e6b49bc39b3c1412325
d0dfd85cf67f07016209da892031c4976a688490
refs/heads/master
2021-04-05T23:53:47.644000
2018-10-08T23:34:44
2018-10-08T23:34:44
124,557,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package com.example.thizzle.ai.algorithms; // //import java.util.ArrayList; //import java.util.Collections; //import java.util.Comparator; //import java.util.List; // // //public class AStar { // // // // public List<Node> aStarSearch(Node start, Node goal) { // List<Node> visitedNodes = new ArrayList<Node>(); // List<Node> edges = new ArrayList<Node>(); // edges.add(start); // //// double gScore = Double.POSITIVE_INFINITY; // start.setGScore(0); // //// double fScore = Double.POSITIVE_INFINITY; // start.setFScore(calcHeuristics(start, goal, "additive", "manhattan", "goalcount")); // // while(!edges.isEmpty()) { // Collections.sort(edges,new Comparator<Node>(){ // @Override // public int compare(Node n1,Node n2) { // return n1.getFScore() - n2.getFScore(); // } // }); // Node current = edges.get(0); // edges.remove(0); // visitedNodes.add(current); // // if(current == goal) { // return reconstructPath(current); // } // // for(Node newEdge: current.getEdges()) { // if(visitedNodes.contains(newEdge)) { // continue; // } // // if(!edges.contains(newEdge)) { // edges.add(newEdge); // } // // int tempGScore = current.getGScore() + 1; // // if(tempGScore >= newEdge.getGScore()) { // continue; // } // current.setCameFrom(newEdge); // newEdge.setGScore(tempGScore); // newEdge.setFScore(newEdge.getGScore() + calcHeuristics(newEdge, goal, "additive", "manhattan", "goalcount")); // } // } // return null; // } // // // private int calcHeuristics(Node startNode, Node goalNode, String heuristicMethod, String heuristic1, String heuristic2){ // int retValue = 0; // // if(heuristic1.equalsIgnoreCase("manhattan") || heuristic2.equalsIgnoreCase("manhattan")) { // retValue += manhattanDistance(startNode, goalNode); // } // if(heuristic1.equalsIgnoreCase("goalcount") || heuristic2.equalsIgnoreCase("goalcount")) { // retValue += goalCount(startNode, goalNode); // } // // // return retValue; // // } // // // private List<Node> reconstructPath(Node current){ // List<Node> finalPath = new ArrayList<>(); // finalPath.add(current); // Node nextNode = current; // boolean stillAPath = true; // while(stillAPath) { // finalPath.add(current.getCameFrom()); // nextNode = current.getCameFrom(); // } // // return finalPath; // // } // //} // //
UTF-8
Java
2,420
java
AStar.java
Java
[]
null
[]
//package com.example.thizzle.ai.algorithms; // //import java.util.ArrayList; //import java.util.Collections; //import java.util.Comparator; //import java.util.List; // // //public class AStar { // // // // public List<Node> aStarSearch(Node start, Node goal) { // List<Node> visitedNodes = new ArrayList<Node>(); // List<Node> edges = new ArrayList<Node>(); // edges.add(start); // //// double gScore = Double.POSITIVE_INFINITY; // start.setGScore(0); // //// double fScore = Double.POSITIVE_INFINITY; // start.setFScore(calcHeuristics(start, goal, "additive", "manhattan", "goalcount")); // // while(!edges.isEmpty()) { // Collections.sort(edges,new Comparator<Node>(){ // @Override // public int compare(Node n1,Node n2) { // return n1.getFScore() - n2.getFScore(); // } // }); // Node current = edges.get(0); // edges.remove(0); // visitedNodes.add(current); // // if(current == goal) { // return reconstructPath(current); // } // // for(Node newEdge: current.getEdges()) { // if(visitedNodes.contains(newEdge)) { // continue; // } // // if(!edges.contains(newEdge)) { // edges.add(newEdge); // } // // int tempGScore = current.getGScore() + 1; // // if(tempGScore >= newEdge.getGScore()) { // continue; // } // current.setCameFrom(newEdge); // newEdge.setGScore(tempGScore); // newEdge.setFScore(newEdge.getGScore() + calcHeuristics(newEdge, goal, "additive", "manhattan", "goalcount")); // } // } // return null; // } // // // private int calcHeuristics(Node startNode, Node goalNode, String heuristicMethod, String heuristic1, String heuristic2){ // int retValue = 0; // // if(heuristic1.equalsIgnoreCase("manhattan") || heuristic2.equalsIgnoreCase("manhattan")) { // retValue += manhattanDistance(startNode, goalNode); // } // if(heuristic1.equalsIgnoreCase("goalcount") || heuristic2.equalsIgnoreCase("goalcount")) { // retValue += goalCount(startNode, goalNode); // } // // // return retValue; // // } // // // private List<Node> reconstructPath(Node current){ // List<Node> finalPath = new ArrayList<>(); // finalPath.add(current); // Node nextNode = current; // boolean stillAPath = true; // while(stillAPath) { // finalPath.add(current.getCameFrom()); // nextNode = current.getCameFrom(); // } // // return finalPath; // // } // //} // //
2,420
0.618595
0.612397
94
24.74468
25.244732
123
false
false
0
0
0
0
0
0
2.861702
false
false
9
ea3ea9dadff67e3e0e8fac78ae3d543af5c73275
21,474,836,540,998
7eaa1605e601236dc7fd7d40d2313b06be289f93
/BoysinHighGrade.java
6decf90076ca3c87fc1b3c32ba3313f0744c4565
[]
no_license
Orange199609/iCal1s
https://github.com/Orange199609/iCal1s
1609c2dd865f3cea0da28d7863aab0ce4ae5b89c
5be2c9f3c7d33ccf3b5f2d29e1169a98b7e20495
refs/heads/master
2021-01-10T22:18:58.169000
2016-10-08T15:26:31
2016-10-08T15:26:31
69,139,977
0
0
null
false
2016-09-25T03:02:24
2016-09-25T02:45:45
2016-09-25T02:45:45
2016-09-25T03:02:24
0
0
0
0
null
null
null
package iCalculator; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BoysinHighGrade extends JFrame implements ActionListener{ JButton counting; JTextField textheight,textweight,textlungcontent,textfiftymeters1,textfiftymeters2,textsittingpush,textjump,textpullup,textthousandmeters1,textthousandmeters2,textmajor,texttotal,texttest,textskippingrope; JLabel labelheight1,labelheight2,labelweight1,labelweight2,labellungcontent1,labellungcontent2,labelfiftymeters1,labelfiftymeters2,labelsittingpush1,labelsittingpush2,labeljump1,labeljump2,labelpullup1,labelpullup2,labelthousandmeters1,labelthousandmeters2,labelthousandmeters3,labelmajor1,labelmajor2,labeltotal1,labeltotal2,labeltest1,labeltest2,labelskippingrope1,labelskippingrope2,labelblank; JPanel pmain,pleft,pright,pheight,pweight,plungcontent,pfiftymeters,psittingpush,pjump,ppullup,pthousandmeters,pmajor,ptotal,ptest,pskippingrope; double height,weight,lungcontent,fiftymeters1,fiftymeters2,sittingpush,jump,pullup,thousandmeters1,thousandmeters2,major,total,test; double BMIgrade,lungcontentgrade,fiftymetersgrade,sittingpushgrade,jumpgrade,pullupgrade,thousandmetersgrade,skippingropegrade,BMI; String s = new String(""); Font font = new Font("华文行楷",Font.BOLD,16); public BoysinHighGrade(){ super("大三大四男生体测成绩计算"); setLayout(new FlowLayout()); /*主界面*/ pmain = new JPanel(); pmain.setLayout(new GridLayout(1,2)); add(pmain); /*成绩界面*/ pleft = new JPanel(); pleft.setLayout(new GridLayout(12,1)); pmain.add(pleft); /*计算按钮界面*/ pright = new JPanel(); pright.setLayout(new FlowLayout()); pmain.add(pright); /*分项成绩*/ /*身高*/ pheight = new JPanel(); pheight.setLayout(new GridLayout(1,3)); pleft.add(pheight); labelheight1 = new JLabel("身高"); labelheight1.setFont(font); textheight = new JTextField(10); labelheight2 = new JLabel("m"); labelheight2.setFont(font); pheight.add(labelheight1); pheight.add(textheight); pheight.add(labelheight2); /*体重*/ pweight = new JPanel(); pweight.setLayout(new GridLayout(1,3)); pleft.add(pweight); labelweight1 = new JLabel("体重"); labelweight1.setFont(font); textweight = new JTextField(10); labelweight2 = new JLabel("kg"); labelweight2.setFont(font); pweight.add(labelweight1); pweight.add(textweight); pweight.add(labelweight2); /*肺活量*/ plungcontent = new JPanel(); plungcontent.setLayout(new GridLayout(1,3)); pleft.add(plungcontent); labellungcontent1 = new JLabel("肺活量"); labellungcontent1.setFont(font); textlungcontent = new JTextField(10); labellungcontent2 = new JLabel("ml"); labellungcontent2.setFont(font); plungcontent.add(labellungcontent1); plungcontent.add(textlungcontent); plungcontent.add(labellungcontent2); /*50米*/ pfiftymeters = new JPanel(); pfiftymeters.setLayout(new GridLayout(1,4)); pleft.add(pfiftymeters); labelfiftymeters1 = new JLabel("50米"); labelfiftymeters1.setFont(font); textfiftymeters1 = new JTextField(1); labelfiftymeters2 = new JLabel("秒"); labelfiftymeters2.setFont(font); textfiftymeters2 = new JTextField(1); labelblank = new JLabel(""); labelblank.setFont(font); pfiftymeters.add(labelfiftymeters1); pfiftymeters.add(textfiftymeters1); pfiftymeters.add(labelfiftymeters2); pfiftymeters.add(textfiftymeters2); pfiftymeters.add(labelblank); /*坐位体前屈*/ psittingpush = new JPanel(); psittingpush.setLayout(new GridLayout(1,3)); pleft.add(psittingpush); labelsittingpush1 = new JLabel("坐位体前屈"); labelsittingpush1.setFont(font); textsittingpush = new JTextField(3); labelsittingpush2 = new JLabel("cm"); labelsittingpush2.setFont(font); psittingpush.add(labelsittingpush1); psittingpush.add(textsittingpush); psittingpush.add(labelsittingpush2); /*立定跳远*/ pjump = new JPanel(); pjump.setLayout(new GridLayout(1,3)); pleft.add(pjump); labeljump1 = new JLabel("立定跳远"); labeljump1.setFont(font); textjump = new JTextField(10); labeljump2 = new JLabel("cm"); labeljump2.setFont(font); pjump.add(labeljump1); pjump.add(textjump); pjump.add(labeljump2); /*引体向上*/ ppullup = new JPanel(); ppullup.setLayout(new GridLayout(1,3)); pleft.add(ppullup); labelpullup1 = new JLabel("引体向上"); labelpullup1.setFont(font); textpullup = new JTextField(10); labelpullup2 = new JLabel("个"); labelpullup2.setFont(font); ppullup.add(labelpullup1); ppullup.add(textpullup); ppullup.add(labelpullup2); /*1000米*/ pthousandmeters = new JPanel(); pthousandmeters.setLayout(new GridLayout(1,5)); pleft.add(pthousandmeters); labelthousandmeters1 = new JLabel("1000米耐力跑"); labelthousandmeters1.setFont(font); textthousandmeters1 = new JTextField(1); labelthousandmeters2 = new JLabel("分"); labelthousandmeters2.setFont(font); textthousandmeters2 = new JTextField(1); labelthousandmeters3 = new JLabel("秒"); labelthousandmeters3.setFont(font); pthousandmeters.add(labelthousandmeters1); pthousandmeters.add(textthousandmeters1); pthousandmeters.add(labelthousandmeters2); pthousandmeters.add(textthousandmeters2); pthousandmeters.add(labelthousandmeters3); /*专项课*/ pmajor = new JPanel(); pmajor.setLayout(new GridLayout(1,3)); pleft.add(pmajor); labelmajor1 = new JLabel("专项课得分"); labelmajor1.setFont(font); textmajor = new JTextField(10); labelmajor2 = new JLabel("分"); labelmajor2.setFont(font); pmajor.add(labelmajor1); pmajor.add(textmajor); pmajor.add(labelmajor2); /*跳绳得分*/ pskippingrope = new JPanel(); pskippingrope.setLayout(new GridLayout(1,3)); pleft.add(pskippingrope); labelskippingrope1 = new JLabel("跳绳得分"); labelskippingrope1.setFont(font); textskippingrope = new JTextField(10); labelskippingrope2 = new JLabel("分"); labelskippingrope2.setFont(font); pskippingrope.add(labelskippingrope1); pskippingrope.add(textskippingrope); pskippingrope.add(labelskippingrope2); /*体侧得分*/ ptest = new JPanel(); ptest.setLayout(new GridLayout(1,3)); pleft.add(ptest); labeltest1 = new JLabel("体侧得分"); labeltest1.setFont(font); texttest = new JTextField(10); labeltest2 = new JLabel("分"); labeltest2.setFont(font); ptest.add(labeltest1); ptest.add(texttest); ptest.add(labeltest2); /*总分*/ ptotal = new JPanel(); ptotal.setLayout(new GridLayout(1,3)); pleft.add(ptotal); labeltotal1 = new JLabel("总分"); labeltotal1.setFont(font); texttotal = new JTextField(10); labeltotal2 = new JLabel("分"); labeltotal2.setFont(font); ptotal.add(labeltotal1); ptotal.add(texttotal); ptotal.add(labeltotal2); /*右侧布局*/ counting = new JButton("计算得分"); counting.setFont(font); counting.addActionListener(this); pright.add(counting); this.setVisible(true); } public void actionPerformed(ActionEvent e){ if(e.getSource()==counting){ /*计算BMI得分*/ height = Double.parseDouble(textheight.getText()); weight = Double.parseDouble(textweight.getText()); BMI = weight/(height*height); if(BMI>=17.9 & BMI<=23.9) BMIgrade = 100; else if( (BMI<=17.8) | (BMI>=24.0&BMI<=27.9)) BMIgrade = 80; else if( BMI>=28.0 ) BMIgrade = 60; /*计算肺活量得分*/ lungcontent = Double.parseDouble(textlungcontent.getText()); if(lungcontent>=5140) lungcontentgrade = 100; else if(lungcontent>=5020) lungcontentgrade = 95; else if(lungcontent>=4900) lungcontentgrade = 90; else if(lungcontent>=4650) lungcontentgrade = 85; else if(lungcontent>=4400) lungcontentgrade = 80; else if(lungcontent>=4280) lungcontentgrade = 78; else if(lungcontent>=4160) lungcontentgrade = 76; else if(lungcontent>=4040) lungcontentgrade = 74; else if(lungcontent>=3920) lungcontentgrade = 72; else if(lungcontent>=3800) lungcontentgrade = 70; else if(lungcontent>=3680) lungcontentgrade = 68; else if(lungcontent>=3560) lungcontentgrade = 66; else if(lungcontent>=3440) lungcontentgrade = 64; else if(lungcontent>=3320) lungcontentgrade = 62; else if(lungcontent>=3200) lungcontentgrade = 60; else if(lungcontent>=3030) lungcontentgrade = 50; else if(lungcontent>=2860) lungcontentgrade = 40; else if(lungcontent>=2690) lungcontentgrade = 30; else if(lungcontent>=2520) lungcontentgrade = 20; else if(lungcontent>=2350) lungcontentgrade = 10; else lungcontentgrade = 0; /*计算50米得分*/ fiftymeters1 = Double.parseDouble(textfiftymeters1.getText()); fiftymeters2 = Double.parseDouble(textfiftymeters2.getText()); if(fiftymeters1<=5) fiftymetersgrade = 100; else if(fiftymeters1 == 6){ if(fiftymeters2<=6) fiftymetersgrade = 100; else if(fiftymeters2 == 7) fiftymetersgrade = 95; else if(fiftymeters2 == 8) fiftymetersgrade = 90; else if(fiftymeters2 == 9) fiftymetersgrade = 85; }else if(fiftymeters1 == 7){ if(fiftymeters2 == 0) fiftymetersgrade = 80; else if(fiftymeters2 <= 2) fiftymetersgrade = 78; else if(fiftymeters2 <= 4) fiftymetersgrade = 76; else if(fiftymeters2 <= 6) fiftymetersgrade = 74; else if(fiftymeters2 <= 8) fiftymetersgrade = 72; }else if(fiftymeters1 == 8){ if(fiftymeters2 == 0) fiftymetersgrade = 70; else if(fiftymeters2 <= 2) fiftymetersgrade = 68; else if(fiftymeters2 <= 4) fiftymetersgrade = 66; else if(fiftymeters2 <= 6) fiftymetersgrade = 64; else if(fiftymeters2 <= 8) fiftymetersgrade = 62; }else if(fiftymeters1 == 9){ if(fiftymeters2 == 0) fiftymetersgrade = 60; else if(fiftymeters2 <= 2) fiftymetersgrade = 50; else if(fiftymeters2 <= 4) fiftymetersgrade = 40; else if(fiftymeters2 <= 6) fiftymetersgrade = 30; else if(fiftymeters2 <= 8) fiftymetersgrade = 20; }else if(fiftymeters1 == 10){ if(fiftymeters2 == 0) fiftymetersgrade = 10; else fiftymetersgrade = 0; }else fiftymetersgrade = 0; /*坐位体前屈得分计算*/ sittingpush = Double.parseDouble(textsittingpush.getText()); if(sittingpush >= 25.1) sittingpushgrade = 100; else if(sittingpush >= 23.3) sittingpushgrade = 95; else if(sittingpush >= 21.5) sittingpushgrade = 90; else if(sittingpush >= 19.9) sittingpushgrade = 85; else if(sittingpush >= 18.2) sittingpushgrade = 80; else if(sittingpush >= 16.8) sittingpushgrade = 78; else if(sittingpush >= 15.4) sittingpushgrade = 76; else if(sittingpush >= 14.0) sittingpushgrade = 74; else if(sittingpush >= 12.6) sittingpushgrade = 72; else if(sittingpush >= 11.2) sittingpushgrade = 70; else if(sittingpush >= 9.8) sittingpushgrade = 68; else if(sittingpush >= 8.4) sittingpushgrade = 66; else if(sittingpush >= 7.0) sittingpushgrade = 64; else if(sittingpush >= 5.6) sittingpushgrade = 62; else if(sittingpush >= 4.2) sittingpushgrade = 60; else if(sittingpush >= 3.2) sittingpushgrade = 50; else if(sittingpush >= 2.2) sittingpushgrade = 40; else if(sittingpush >= 1.2) sittingpushgrade = 30; else if(sittingpush >= 0.2) sittingpushgrade = 20; else if(sittingpush >= -0.8) sittingpushgrade = 10; else sittingpushgrade = 0; /*立定跳远得分*/ jump = Double.parseDouble(textjump.getText()); if(jump >= 275) jumpgrade = 100; else if(jump >= 270) jumpgrade = 95; else if(jump >= 265) jumpgrade = 90; else if(jump >= 258) jumpgrade = 85; else if(jump >= 250) jumpgrade = 80; else if(jump >= 246) jumpgrade = 78; else if(jump >= 242) jumpgrade = 76; else if(jump >= 238) jumpgrade = 74; else if(jump >= 234) jumpgrade = 72; else if(jump >= 230) jumpgrade = 70; else if(jump >= 226) jumpgrade = 68; else if(jump >= 222) jumpgrade = 66; else if(jump >= 218) jumpgrade = 64; else if(jump >= 214) jumpgrade = 62; else if(jump >= 210) jumpgrade = 60; else if(jump >= 205) jumpgrade = 50; else if(jump >= 200) jumpgrade = 40; else if(jump >= 195) jumpgrade = 30; else if(jump >= 190) jumpgrade = 20; else if(jump >= 185) jumpgrade = 10; else jumpgrade = 0; /*计算引体向上得分*/ pullup = Double.parseDouble(textpullup.getText()); if(pullup >= 20) pullupgrade = 100; else if(pullup == 19) pullupgrade = 95; else if(pullup == 18) pullupgrade = 90; else if(pullup == 17) pullupgrade = 85; else if(pullup == 16) pullupgrade = 80; else if(pullup == 15) pullupgrade = 76; else if(pullup == 14) pullupgrade = 72; else if(pullup == 13) pullupgrade = 68; else if(pullup == 12) pullupgrade = 64; else if(pullup == 11) pullupgrade = 60; else if(pullup == 10) pullupgrade = 50; else if(pullup == 9) pullupgrade = 40; else if(pullup == 8) pullupgrade = 30; else if(pullup == 7) pullupgrade = 20; else if(pullup == 6) pullupgrade = 10; else pullupgrade = 0; /*计算1000米得分*/ thousandmeters1 = Double.parseDouble(textthousandmeters1.getText()); thousandmeters2 = Double.parseDouble(textthousandmeters2.getText()); if(thousandmeters1<=2) thousandmetersgrade = 100; else if(thousandmeters1 == 3){ if(thousandmeters2 <= 15) thousandmetersgrade = 100; else if(thousandmeters2 <= 20) thousandmetersgrade = 95; else if(thousandmeters2 <= 25) thousandmetersgrade = 90; else if(thousandmeters2 <= 32) thousandmetersgrade = 85; else if(thousandmeters2 <= 40) thousandmetersgrade = 80; else if(thousandmeters2 <= 45) thousandmetersgrade = 78; else if(thousandmeters2 <= 50) thousandmetersgrade = 76; else if(thousandmeters2 <= 55) thousandmetersgrade = 74; else thousandmetersgrade = 72; }else if(thousandmeters1 == 4){ if(thousandmeters2 <= 0) thousandmetersgrade = 72; else if(thousandmeters2 <= 5) thousandmetersgrade = 70; else if(thousandmeters2 <= 10) thousandmetersgrade = 68; else if(thousandmeters2 <= 15) thousandmetersgrade = 66; else if(thousandmeters2 <= 20) thousandmetersgrade = 64; else if(thousandmeters2 <= 25) thousandmetersgrade = 62; else if(thousandmeters2 <= 30) thousandmetersgrade = 60; else if(thousandmeters2 <= 50) thousandmetersgrade = 50; else thousandmetersgrade = 40; }else if(thousandmeters1 == 5){ if(thousandmeters2 <= 10) thousandmetersgrade = 40; else if(thousandmeters2 <= 30) thousandmetersgrade = 30; else if(thousandmeters2 <= 50) thousandmetersgrade = 20; else thousandmetersgrade = 10; }else if(thousandmeters1 == 6){ if(thousandmeters2 <= 10) thousandmetersgrade = 10; else thousandmetersgrade = 0; }else thousandmetersgrade = 0; /*计算体侧总分*/ test = 0.15*BMIgrade + 0.15*lungcontentgrade + 0.2*fiftymetersgrade + 0.1*sittingpushgrade + 0.1*jumpgrade + 0.1*pullupgrade + 0.2*thousandmetersgrade; texttest.setText(String.valueOf(test)); /*计算总分*/ total = test*0.5 + Double.parseDouble(textmajor.getText())*0.4 + Double.parseDouble(textskippingrope.getText())*0.1; texttotal.setText(new java.text.DecimalFormat("#.00").format(total)); } } }
GB18030
Java
15,783
java
BoysinHighGrade.java
Java
[]
null
[]
package iCalculator; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BoysinHighGrade extends JFrame implements ActionListener{ JButton counting; JTextField textheight,textweight,textlungcontent,textfiftymeters1,textfiftymeters2,textsittingpush,textjump,textpullup,textthousandmeters1,textthousandmeters2,textmajor,texttotal,texttest,textskippingrope; JLabel labelheight1,labelheight2,labelweight1,labelweight2,labellungcontent1,labellungcontent2,labelfiftymeters1,labelfiftymeters2,labelsittingpush1,labelsittingpush2,labeljump1,labeljump2,labelpullup1,labelpullup2,labelthousandmeters1,labelthousandmeters2,labelthousandmeters3,labelmajor1,labelmajor2,labeltotal1,labeltotal2,labeltest1,labeltest2,labelskippingrope1,labelskippingrope2,labelblank; JPanel pmain,pleft,pright,pheight,pweight,plungcontent,pfiftymeters,psittingpush,pjump,ppullup,pthousandmeters,pmajor,ptotal,ptest,pskippingrope; double height,weight,lungcontent,fiftymeters1,fiftymeters2,sittingpush,jump,pullup,thousandmeters1,thousandmeters2,major,total,test; double BMIgrade,lungcontentgrade,fiftymetersgrade,sittingpushgrade,jumpgrade,pullupgrade,thousandmetersgrade,skippingropegrade,BMI; String s = new String(""); Font font = new Font("华文行楷",Font.BOLD,16); public BoysinHighGrade(){ super("大三大四男生体测成绩计算"); setLayout(new FlowLayout()); /*主界面*/ pmain = new JPanel(); pmain.setLayout(new GridLayout(1,2)); add(pmain); /*成绩界面*/ pleft = new JPanel(); pleft.setLayout(new GridLayout(12,1)); pmain.add(pleft); /*计算按钮界面*/ pright = new JPanel(); pright.setLayout(new FlowLayout()); pmain.add(pright); /*分项成绩*/ /*身高*/ pheight = new JPanel(); pheight.setLayout(new GridLayout(1,3)); pleft.add(pheight); labelheight1 = new JLabel("身高"); labelheight1.setFont(font); textheight = new JTextField(10); labelheight2 = new JLabel("m"); labelheight2.setFont(font); pheight.add(labelheight1); pheight.add(textheight); pheight.add(labelheight2); /*体重*/ pweight = new JPanel(); pweight.setLayout(new GridLayout(1,3)); pleft.add(pweight); labelweight1 = new JLabel("体重"); labelweight1.setFont(font); textweight = new JTextField(10); labelweight2 = new JLabel("kg"); labelweight2.setFont(font); pweight.add(labelweight1); pweight.add(textweight); pweight.add(labelweight2); /*肺活量*/ plungcontent = new JPanel(); plungcontent.setLayout(new GridLayout(1,3)); pleft.add(plungcontent); labellungcontent1 = new JLabel("肺活量"); labellungcontent1.setFont(font); textlungcontent = new JTextField(10); labellungcontent2 = new JLabel("ml"); labellungcontent2.setFont(font); plungcontent.add(labellungcontent1); plungcontent.add(textlungcontent); plungcontent.add(labellungcontent2); /*50米*/ pfiftymeters = new JPanel(); pfiftymeters.setLayout(new GridLayout(1,4)); pleft.add(pfiftymeters); labelfiftymeters1 = new JLabel("50米"); labelfiftymeters1.setFont(font); textfiftymeters1 = new JTextField(1); labelfiftymeters2 = new JLabel("秒"); labelfiftymeters2.setFont(font); textfiftymeters2 = new JTextField(1); labelblank = new JLabel(""); labelblank.setFont(font); pfiftymeters.add(labelfiftymeters1); pfiftymeters.add(textfiftymeters1); pfiftymeters.add(labelfiftymeters2); pfiftymeters.add(textfiftymeters2); pfiftymeters.add(labelblank); /*坐位体前屈*/ psittingpush = new JPanel(); psittingpush.setLayout(new GridLayout(1,3)); pleft.add(psittingpush); labelsittingpush1 = new JLabel("坐位体前屈"); labelsittingpush1.setFont(font); textsittingpush = new JTextField(3); labelsittingpush2 = new JLabel("cm"); labelsittingpush2.setFont(font); psittingpush.add(labelsittingpush1); psittingpush.add(textsittingpush); psittingpush.add(labelsittingpush2); /*立定跳远*/ pjump = new JPanel(); pjump.setLayout(new GridLayout(1,3)); pleft.add(pjump); labeljump1 = new JLabel("立定跳远"); labeljump1.setFont(font); textjump = new JTextField(10); labeljump2 = new JLabel("cm"); labeljump2.setFont(font); pjump.add(labeljump1); pjump.add(textjump); pjump.add(labeljump2); /*引体向上*/ ppullup = new JPanel(); ppullup.setLayout(new GridLayout(1,3)); pleft.add(ppullup); labelpullup1 = new JLabel("引体向上"); labelpullup1.setFont(font); textpullup = new JTextField(10); labelpullup2 = new JLabel("个"); labelpullup2.setFont(font); ppullup.add(labelpullup1); ppullup.add(textpullup); ppullup.add(labelpullup2); /*1000米*/ pthousandmeters = new JPanel(); pthousandmeters.setLayout(new GridLayout(1,5)); pleft.add(pthousandmeters); labelthousandmeters1 = new JLabel("1000米耐力跑"); labelthousandmeters1.setFont(font); textthousandmeters1 = new JTextField(1); labelthousandmeters2 = new JLabel("分"); labelthousandmeters2.setFont(font); textthousandmeters2 = new JTextField(1); labelthousandmeters3 = new JLabel("秒"); labelthousandmeters3.setFont(font); pthousandmeters.add(labelthousandmeters1); pthousandmeters.add(textthousandmeters1); pthousandmeters.add(labelthousandmeters2); pthousandmeters.add(textthousandmeters2); pthousandmeters.add(labelthousandmeters3); /*专项课*/ pmajor = new JPanel(); pmajor.setLayout(new GridLayout(1,3)); pleft.add(pmajor); labelmajor1 = new JLabel("专项课得分"); labelmajor1.setFont(font); textmajor = new JTextField(10); labelmajor2 = new JLabel("分"); labelmajor2.setFont(font); pmajor.add(labelmajor1); pmajor.add(textmajor); pmajor.add(labelmajor2); /*跳绳得分*/ pskippingrope = new JPanel(); pskippingrope.setLayout(new GridLayout(1,3)); pleft.add(pskippingrope); labelskippingrope1 = new JLabel("跳绳得分"); labelskippingrope1.setFont(font); textskippingrope = new JTextField(10); labelskippingrope2 = new JLabel("分"); labelskippingrope2.setFont(font); pskippingrope.add(labelskippingrope1); pskippingrope.add(textskippingrope); pskippingrope.add(labelskippingrope2); /*体侧得分*/ ptest = new JPanel(); ptest.setLayout(new GridLayout(1,3)); pleft.add(ptest); labeltest1 = new JLabel("体侧得分"); labeltest1.setFont(font); texttest = new JTextField(10); labeltest2 = new JLabel("分"); labeltest2.setFont(font); ptest.add(labeltest1); ptest.add(texttest); ptest.add(labeltest2); /*总分*/ ptotal = new JPanel(); ptotal.setLayout(new GridLayout(1,3)); pleft.add(ptotal); labeltotal1 = new JLabel("总分"); labeltotal1.setFont(font); texttotal = new JTextField(10); labeltotal2 = new JLabel("分"); labeltotal2.setFont(font); ptotal.add(labeltotal1); ptotal.add(texttotal); ptotal.add(labeltotal2); /*右侧布局*/ counting = new JButton("计算得分"); counting.setFont(font); counting.addActionListener(this); pright.add(counting); this.setVisible(true); } public void actionPerformed(ActionEvent e){ if(e.getSource()==counting){ /*计算BMI得分*/ height = Double.parseDouble(textheight.getText()); weight = Double.parseDouble(textweight.getText()); BMI = weight/(height*height); if(BMI>=17.9 & BMI<=23.9) BMIgrade = 100; else if( (BMI<=17.8) | (BMI>=24.0&BMI<=27.9)) BMIgrade = 80; else if( BMI>=28.0 ) BMIgrade = 60; /*计算肺活量得分*/ lungcontent = Double.parseDouble(textlungcontent.getText()); if(lungcontent>=5140) lungcontentgrade = 100; else if(lungcontent>=5020) lungcontentgrade = 95; else if(lungcontent>=4900) lungcontentgrade = 90; else if(lungcontent>=4650) lungcontentgrade = 85; else if(lungcontent>=4400) lungcontentgrade = 80; else if(lungcontent>=4280) lungcontentgrade = 78; else if(lungcontent>=4160) lungcontentgrade = 76; else if(lungcontent>=4040) lungcontentgrade = 74; else if(lungcontent>=3920) lungcontentgrade = 72; else if(lungcontent>=3800) lungcontentgrade = 70; else if(lungcontent>=3680) lungcontentgrade = 68; else if(lungcontent>=3560) lungcontentgrade = 66; else if(lungcontent>=3440) lungcontentgrade = 64; else if(lungcontent>=3320) lungcontentgrade = 62; else if(lungcontent>=3200) lungcontentgrade = 60; else if(lungcontent>=3030) lungcontentgrade = 50; else if(lungcontent>=2860) lungcontentgrade = 40; else if(lungcontent>=2690) lungcontentgrade = 30; else if(lungcontent>=2520) lungcontentgrade = 20; else if(lungcontent>=2350) lungcontentgrade = 10; else lungcontentgrade = 0; /*计算50米得分*/ fiftymeters1 = Double.parseDouble(textfiftymeters1.getText()); fiftymeters2 = Double.parseDouble(textfiftymeters2.getText()); if(fiftymeters1<=5) fiftymetersgrade = 100; else if(fiftymeters1 == 6){ if(fiftymeters2<=6) fiftymetersgrade = 100; else if(fiftymeters2 == 7) fiftymetersgrade = 95; else if(fiftymeters2 == 8) fiftymetersgrade = 90; else if(fiftymeters2 == 9) fiftymetersgrade = 85; }else if(fiftymeters1 == 7){ if(fiftymeters2 == 0) fiftymetersgrade = 80; else if(fiftymeters2 <= 2) fiftymetersgrade = 78; else if(fiftymeters2 <= 4) fiftymetersgrade = 76; else if(fiftymeters2 <= 6) fiftymetersgrade = 74; else if(fiftymeters2 <= 8) fiftymetersgrade = 72; }else if(fiftymeters1 == 8){ if(fiftymeters2 == 0) fiftymetersgrade = 70; else if(fiftymeters2 <= 2) fiftymetersgrade = 68; else if(fiftymeters2 <= 4) fiftymetersgrade = 66; else if(fiftymeters2 <= 6) fiftymetersgrade = 64; else if(fiftymeters2 <= 8) fiftymetersgrade = 62; }else if(fiftymeters1 == 9){ if(fiftymeters2 == 0) fiftymetersgrade = 60; else if(fiftymeters2 <= 2) fiftymetersgrade = 50; else if(fiftymeters2 <= 4) fiftymetersgrade = 40; else if(fiftymeters2 <= 6) fiftymetersgrade = 30; else if(fiftymeters2 <= 8) fiftymetersgrade = 20; }else if(fiftymeters1 == 10){ if(fiftymeters2 == 0) fiftymetersgrade = 10; else fiftymetersgrade = 0; }else fiftymetersgrade = 0; /*坐位体前屈得分计算*/ sittingpush = Double.parseDouble(textsittingpush.getText()); if(sittingpush >= 25.1) sittingpushgrade = 100; else if(sittingpush >= 23.3) sittingpushgrade = 95; else if(sittingpush >= 21.5) sittingpushgrade = 90; else if(sittingpush >= 19.9) sittingpushgrade = 85; else if(sittingpush >= 18.2) sittingpushgrade = 80; else if(sittingpush >= 16.8) sittingpushgrade = 78; else if(sittingpush >= 15.4) sittingpushgrade = 76; else if(sittingpush >= 14.0) sittingpushgrade = 74; else if(sittingpush >= 12.6) sittingpushgrade = 72; else if(sittingpush >= 11.2) sittingpushgrade = 70; else if(sittingpush >= 9.8) sittingpushgrade = 68; else if(sittingpush >= 8.4) sittingpushgrade = 66; else if(sittingpush >= 7.0) sittingpushgrade = 64; else if(sittingpush >= 5.6) sittingpushgrade = 62; else if(sittingpush >= 4.2) sittingpushgrade = 60; else if(sittingpush >= 3.2) sittingpushgrade = 50; else if(sittingpush >= 2.2) sittingpushgrade = 40; else if(sittingpush >= 1.2) sittingpushgrade = 30; else if(sittingpush >= 0.2) sittingpushgrade = 20; else if(sittingpush >= -0.8) sittingpushgrade = 10; else sittingpushgrade = 0; /*立定跳远得分*/ jump = Double.parseDouble(textjump.getText()); if(jump >= 275) jumpgrade = 100; else if(jump >= 270) jumpgrade = 95; else if(jump >= 265) jumpgrade = 90; else if(jump >= 258) jumpgrade = 85; else if(jump >= 250) jumpgrade = 80; else if(jump >= 246) jumpgrade = 78; else if(jump >= 242) jumpgrade = 76; else if(jump >= 238) jumpgrade = 74; else if(jump >= 234) jumpgrade = 72; else if(jump >= 230) jumpgrade = 70; else if(jump >= 226) jumpgrade = 68; else if(jump >= 222) jumpgrade = 66; else if(jump >= 218) jumpgrade = 64; else if(jump >= 214) jumpgrade = 62; else if(jump >= 210) jumpgrade = 60; else if(jump >= 205) jumpgrade = 50; else if(jump >= 200) jumpgrade = 40; else if(jump >= 195) jumpgrade = 30; else if(jump >= 190) jumpgrade = 20; else if(jump >= 185) jumpgrade = 10; else jumpgrade = 0; /*计算引体向上得分*/ pullup = Double.parseDouble(textpullup.getText()); if(pullup >= 20) pullupgrade = 100; else if(pullup == 19) pullupgrade = 95; else if(pullup == 18) pullupgrade = 90; else if(pullup == 17) pullupgrade = 85; else if(pullup == 16) pullupgrade = 80; else if(pullup == 15) pullupgrade = 76; else if(pullup == 14) pullupgrade = 72; else if(pullup == 13) pullupgrade = 68; else if(pullup == 12) pullupgrade = 64; else if(pullup == 11) pullupgrade = 60; else if(pullup == 10) pullupgrade = 50; else if(pullup == 9) pullupgrade = 40; else if(pullup == 8) pullupgrade = 30; else if(pullup == 7) pullupgrade = 20; else if(pullup == 6) pullupgrade = 10; else pullupgrade = 0; /*计算1000米得分*/ thousandmeters1 = Double.parseDouble(textthousandmeters1.getText()); thousandmeters2 = Double.parseDouble(textthousandmeters2.getText()); if(thousandmeters1<=2) thousandmetersgrade = 100; else if(thousandmeters1 == 3){ if(thousandmeters2 <= 15) thousandmetersgrade = 100; else if(thousandmeters2 <= 20) thousandmetersgrade = 95; else if(thousandmeters2 <= 25) thousandmetersgrade = 90; else if(thousandmeters2 <= 32) thousandmetersgrade = 85; else if(thousandmeters2 <= 40) thousandmetersgrade = 80; else if(thousandmeters2 <= 45) thousandmetersgrade = 78; else if(thousandmeters2 <= 50) thousandmetersgrade = 76; else if(thousandmeters2 <= 55) thousandmetersgrade = 74; else thousandmetersgrade = 72; }else if(thousandmeters1 == 4){ if(thousandmeters2 <= 0) thousandmetersgrade = 72; else if(thousandmeters2 <= 5) thousandmetersgrade = 70; else if(thousandmeters2 <= 10) thousandmetersgrade = 68; else if(thousandmeters2 <= 15) thousandmetersgrade = 66; else if(thousandmeters2 <= 20) thousandmetersgrade = 64; else if(thousandmeters2 <= 25) thousandmetersgrade = 62; else if(thousandmeters2 <= 30) thousandmetersgrade = 60; else if(thousandmeters2 <= 50) thousandmetersgrade = 50; else thousandmetersgrade = 40; }else if(thousandmeters1 == 5){ if(thousandmeters2 <= 10) thousandmetersgrade = 40; else if(thousandmeters2 <= 30) thousandmetersgrade = 30; else if(thousandmeters2 <= 50) thousandmetersgrade = 20; else thousandmetersgrade = 10; }else if(thousandmeters1 == 6){ if(thousandmeters2 <= 10) thousandmetersgrade = 10; else thousandmetersgrade = 0; }else thousandmetersgrade = 0; /*计算体侧总分*/ test = 0.15*BMIgrade + 0.15*lungcontentgrade + 0.2*fiftymetersgrade + 0.1*sittingpushgrade + 0.1*jumpgrade + 0.1*pullupgrade + 0.2*thousandmetersgrade; texttest.setText(String.valueOf(test)); /*计算总分*/ total = test*0.5 + Double.parseDouble(textmajor.getText())*0.4 + Double.parseDouble(textskippingrope.getText())*0.1; texttotal.setText(new java.text.DecimalFormat("#.00").format(total)); } } }
15,783
0.696182
0.641862
382
38.384815
27.955576
398
false
false
0
0
0
0
0
0
3.463351
false
false
9
830ff00ffe5936ce799dd6fae44c7471512532d4
22,643,067,638,452
b3013a9f09934a5d47bb1853d09a3d377ef6464a
/app/controllers/Home.java
54bdcdce663a366f0b2f17c355a992bcf4cb35a9
[]
no_license
rzhang86/adagie
https://github.com/rzhang86/adagie
208eb17aaf38473333beb141906fa2271096f937
46ac02ed5e2df230f646fe6cb8502bf051bdf9d5
HEAD
2016-09-06T07:37:27.825000
2013-07-10T04:01:39
2013-07-10T04:01:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import java.io.*; import java.text.*; import java.util.*; import play.mvc.*; import play.mvc.Http.*; import play.mvc.Http.MultipartFormData.*; import play.data.*; import play.db.ebean.*; import com.avaje.ebean.*; import static play.data.Form.*; import models.*; import views.html.*; @Security.Authenticated(Secured.class) public class Home extends Controller { public static Result get() { User user = User.findByUsername(request().username()); List<Long> watchedVideoIds = new ArrayList<Long>(); for (WatchedVideo watchedVideo : user.watchedVideos) if (watchedVideo.endTime != null) watchedVideoIds.add(watchedVideo.video.id); List<Video> unwatchedVideos = Video.find.where().ne("user", user).not(Expr.in("id", watchedVideoIds)).findList(); if (unwatchedVideos.size() > 0) { List<VideoPayoutRate> videoPayoutRates = new ArrayList<VideoPayoutRate>(); for (Video video : unwatchedVideos) { long payout = video.getPayout(user); User payer = video.user; if (payout <= user.committedBalance) { VideoPayoutRate videoPayoutRate = new VideoPayoutRate(video, payout); videoPayoutRates.add(videoPayoutRate); } } Collections.sort(videoPayoutRates); // todo: send a list of top few videos, to lessen queries for (VideoPayoutRate videoPayoutRate : videoPayoutRates) { // todo: dont send video by form like this? may not be safe someone could change source to different video id user.watchingVideo = videoPayoutRate.video; user.watchingStartTime = Calendar.getInstance().getTimeInMillis(); user.watchingEndTime = user.watchingStartTime + user.watchingVideo.duration; user.watchingPayout = videoPayoutRate.payout; user.save(); return ok(home.render(user, form(VideoEndedForm.class))); } } return ok(home.render(user, form(VideoEndedForm.class))); } // only get paid if watching video is being tracked public static Result post() { Form<VideoEndedForm> videoEndedForm = form(VideoEndedForm.class).bindFromRequest(); try { User user = User.findByUsername(request().username()); Video video = Video.find.byId(Long.parseLong(videoEndedForm.get().videoId)); if (!user.watchingVideo.equals(video)) flash("failure", "Video was not tracked"); else { Long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime < user.watchingEndTime) flash("failure", "Video ended prematurely"); else if (user.watchedVideos.contains(video)) flash("failure", "You have already been paid for watching this video recently"); else { WatchedVideo watchedVideo = new WatchedVideo(); watchedVideo.user = user; watchedVideo.video = video; watchedVideo.startTime = user.watchingStartTime; watchedVideo.endTime = currentTime; watchedVideo.payout = user.watchingPayout; watchedVideo.save(); if (transferMoney(video.user, user, watchedVideo.payout)) flash("success", "You earned " + Application.centsToDollars(watchedVideo.payout)); else flash("failure", "Error transferring money"); } } } catch (Exception e) {} return redirect(routes.Home.get()); } public static class VideoPayoutRate implements Comparable<VideoPayoutRate> { Video video; Long payout; double payoutRate; public VideoPayoutRate(Video video, Long payout) { this.video = video; this.payout = payout; this.payoutRate = (double) payout / (double) video.duration; } @Override public int compareTo(VideoPayoutRate otherVideo) { return otherVideo.payoutRate > this.payoutRate ? 1 : otherVideo.payoutRate < this.payoutRate ? -1 : 0; } } public static class VideoEndedForm { public String videoId; } @Transactional public static boolean transferMoney(User payer, User payee, Long amount) { // are these transactions safe? require table lock? try { payer.committedBalance -= amount; payee.balance += amount; payer.save(); payee.save(); return true; } catch (Exception e) {System.out.println("error transferring money: " + e.getMessage());} return false; } }
UTF-8
Java
4,583
java
Home.java
Java
[]
null
[]
package controllers; import java.io.*; import java.text.*; import java.util.*; import play.mvc.*; import play.mvc.Http.*; import play.mvc.Http.MultipartFormData.*; import play.data.*; import play.db.ebean.*; import com.avaje.ebean.*; import static play.data.Form.*; import models.*; import views.html.*; @Security.Authenticated(Secured.class) public class Home extends Controller { public static Result get() { User user = User.findByUsername(request().username()); List<Long> watchedVideoIds = new ArrayList<Long>(); for (WatchedVideo watchedVideo : user.watchedVideos) if (watchedVideo.endTime != null) watchedVideoIds.add(watchedVideo.video.id); List<Video> unwatchedVideos = Video.find.where().ne("user", user).not(Expr.in("id", watchedVideoIds)).findList(); if (unwatchedVideos.size() > 0) { List<VideoPayoutRate> videoPayoutRates = new ArrayList<VideoPayoutRate>(); for (Video video : unwatchedVideos) { long payout = video.getPayout(user); User payer = video.user; if (payout <= user.committedBalance) { VideoPayoutRate videoPayoutRate = new VideoPayoutRate(video, payout); videoPayoutRates.add(videoPayoutRate); } } Collections.sort(videoPayoutRates); // todo: send a list of top few videos, to lessen queries for (VideoPayoutRate videoPayoutRate : videoPayoutRates) { // todo: dont send video by form like this? may not be safe someone could change source to different video id user.watchingVideo = videoPayoutRate.video; user.watchingStartTime = Calendar.getInstance().getTimeInMillis(); user.watchingEndTime = user.watchingStartTime + user.watchingVideo.duration; user.watchingPayout = videoPayoutRate.payout; user.save(); return ok(home.render(user, form(VideoEndedForm.class))); } } return ok(home.render(user, form(VideoEndedForm.class))); } // only get paid if watching video is being tracked public static Result post() { Form<VideoEndedForm> videoEndedForm = form(VideoEndedForm.class).bindFromRequest(); try { User user = User.findByUsername(request().username()); Video video = Video.find.byId(Long.parseLong(videoEndedForm.get().videoId)); if (!user.watchingVideo.equals(video)) flash("failure", "Video was not tracked"); else { Long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime < user.watchingEndTime) flash("failure", "Video ended prematurely"); else if (user.watchedVideos.contains(video)) flash("failure", "You have already been paid for watching this video recently"); else { WatchedVideo watchedVideo = new WatchedVideo(); watchedVideo.user = user; watchedVideo.video = video; watchedVideo.startTime = user.watchingStartTime; watchedVideo.endTime = currentTime; watchedVideo.payout = user.watchingPayout; watchedVideo.save(); if (transferMoney(video.user, user, watchedVideo.payout)) flash("success", "You earned " + Application.centsToDollars(watchedVideo.payout)); else flash("failure", "Error transferring money"); } } } catch (Exception e) {} return redirect(routes.Home.get()); } public static class VideoPayoutRate implements Comparable<VideoPayoutRate> { Video video; Long payout; double payoutRate; public VideoPayoutRate(Video video, Long payout) { this.video = video; this.payout = payout; this.payoutRate = (double) payout / (double) video.duration; } @Override public int compareTo(VideoPayoutRate otherVideo) { return otherVideo.payoutRate > this.payoutRate ? 1 : otherVideo.payoutRate < this.payoutRate ? -1 : 0; } } public static class VideoEndedForm { public String videoId; } @Transactional public static boolean transferMoney(User payer, User payee, Long amount) { // are these transactions safe? require table lock? try { payer.committedBalance -= amount; payee.balance += amount; payer.save(); payee.save(); return true; } catch (Exception e) {System.out.println("error transferring money: " + e.getMessage());} return false; } }
4,583
0.639101
0.638228
107
41.831776
34.714993
160
false
false
0
0
0
0
0
0
1.392523
false
false
9
41313713d5c58758a84670b3f1dc51f0bb3a38e5
35,407,710,414,257
5b782467e3c84f97f626fd18e000aabcba758c3b
/JustCheckingIn/src/co/uk/justcheckingin/ContactsAdapter.java
8288a199e180b5670c3656117f3e38b43e9b93bf
[]
no_license
sc14ga/JustCheckingIn_Android
https://github.com/sc14ga/JustCheckingIn_Android
bd8af5b7c2e2d0924f37a402aac5aface654025b
2d7e059803c840b855ed85e79e702ff873727728
refs/heads/master
2021-01-25T10:07:41.595000
2015-09-06T10:42:56
2015-09-06T10:42:56
37,592,278
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.uk.justcheckingin; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Specifies how a Contact will be shown as an item of a ListView. * * @author Georgios Aikaterinakis * @see CreateContactListActivity * @see EditContactListActivity * @see EmergencyContactListActivity */ class ContactsAdapter extends BaseAdapter { LayoutInflater mInflater; List<String> namesList = new ArrayList<String>(); List<String> numbersList = new ArrayList<String>(); List<Boolean> boxes = new ArrayList<Boolean>(); @Override public int getCount() { return namesList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) { vi = mInflater.inflate(R.layout.listview_contacts, null); } TextView name = (TextView) vi.findViewById(R.id.name); TextView number = (TextView) vi.findViewById(R.id.number); CheckBox box = (CheckBox) vi.findViewById(R.id.checkBox); name.setText(namesList.get(position)); number.setText(numbersList.get(position)); box.setEnabled(true); box.setOnCheckedChangeListener(myCheckedChangeListener); box.setTag(position); box.setChecked(boxes.get(position)); return vi; } OnCheckedChangeListener myCheckedChangeListener = new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { boxes.set(((Integer) buttonView.getTag()), isChecked); } }; }
UTF-8
Java
2,073
java
ContactsAdapter.java
Java
[ { "context": " be shown as an item of a ListView.\n * \n * @author Georgios Aikaterinakis\n * @see CreateContactListActivity\n * @see EditCon", "end": 485, "score": 0.9998844861984253, "start": 463, "tag": "NAME", "value": "Georgios Aikaterinakis" } ]
null
[]
package co.uk.justcheckingin; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Specifies how a Contact will be shown as an item of a ListView. * * @author <NAME> * @see CreateContactListActivity * @see EditContactListActivity * @see EmergencyContactListActivity */ class ContactsAdapter extends BaseAdapter { LayoutInflater mInflater; List<String> namesList = new ArrayList<String>(); List<String> numbersList = new ArrayList<String>(); List<Boolean> boxes = new ArrayList<Boolean>(); @Override public int getCount() { return namesList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View vi = convertView; if (convertView == null) { vi = mInflater.inflate(R.layout.listview_contacts, null); } TextView name = (TextView) vi.findViewById(R.id.name); TextView number = (TextView) vi.findViewById(R.id.number); CheckBox box = (CheckBox) vi.findViewById(R.id.checkBox); name.setText(namesList.get(position)); number.setText(numbersList.get(position)); box.setEnabled(true); box.setOnCheckedChangeListener(myCheckedChangeListener); box.setTag(position); box.setChecked(boxes.get(position)); return vi; } OnCheckedChangeListener myCheckedChangeListener = new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { boxes.set(((Integer) buttonView.getTag()), isChecked); } }; }
2,057
0.694163
0.693681
70
28.6
23.816801
85
false
false
0
0
0
0
0
0
0.528571
false
false
9
46e6c80a1221a6dbe2833d46c165a76ceae65e00
24,060,406,793,488
e8d7e8448d5ac6a1b914b0174ff6c66b45f2d04a
/src/main/java/net/avalith/city_pass/services/CityPassService.java
3890487dd6562498c601ba2311ac0cb169322644
[]
no_license
NicolasMitre/city_pass_microservice
https://github.com/NicolasMitre/city_pass_microservice
479518ec34dfefda6fb1bac37fe3cc5bd98cdbe3
5768886b0fa9e162d7ad6bef7f8d36b4f5983286
refs/heads/development
2022-12-27T08:37:38.357000
2020-07-30T22:57:45
2020-07-30T22:57:45
268,800,831
0
2
null
false
2020-10-14T00:04:06
2020-06-02T12:55:27
2020-07-30T22:57:49
2020-10-14T00:04:05
327
0
0
2
Java
false
false
package net.avalith.city_pass.services; import lombok.RequiredArgsConstructor; import net.avalith.city_pass.dto.CityPassDto; import net.avalith.city_pass.exceptions.CityPassNameIsAlreadyUsedException; import net.avalith.city_pass.exceptions.CityPassNotFoundException; import net.avalith.city_pass.models.City; import net.avalith.city_pass.models.CityPass; import net.avalith.city_pass.repositories.CityPassRepository; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import java.util.List; @Service @RequiredArgsConstructor public class CityPassService { private final CityPassRepository cityPassRepository; private final CityService cityService; public List<CityPass> getAllCityPasses() { return cityPassRepository.findAllByIsActive(true); } public CityPass createCityPass(CityPassDto cityPassDto) { CityPass cityPass = CityPass.builder() .name(cityPassDto.getName()) .description(cityPassDto.getDescription()) .days(cityPassDto.getDays()) .price(cityPassDto.getPrice()) .city(cityService.getByName(cityPassDto.getCityName())) .build(); try { cityPass = cityPassRepository.save(cityPass); } catch (DataIntegrityViolationException e) { throw new CityPassNameIsAlreadyUsedException(); } return cityPass; } public CityPass getById(Integer idCityPass) { return cityPassRepository.findByIdCityPassAndIsActive(idCityPass, true) .orElseThrow(CityPassNotFoundException::new); } public CityPass updateCityPass(Integer idCityPass, CityPassDto cityPassDto) { City city = cityService.getByName(cityPassDto.getCityName()); CityPass cityPass = cityPassRepository.findByIdCityPassAndIsActive(idCityPass, Boolean.TRUE) .orElseThrow(CityPassNotFoundException::new); try { cityPass = cityPass.update(cityPassDto, city); cityPass = cityPassRepository.save(cityPass); } catch (DataIntegrityViolationException e) { throw new CityPassNameIsAlreadyUsedException(); } return cityPass; } public CityPass deleteCityPass(Integer idCityPass) { CityPass cityPass = cityPassRepository.findByIdCityPassAndIsActive(idCityPass, true) .orElseThrow(CityPassNotFoundException::new); cityPass.setIsActive(Boolean.FALSE); return cityPassRepository.save(cityPass); } }
UTF-8
Java
2,590
java
CityPassService.java
Java
[]
null
[]
package net.avalith.city_pass.services; import lombok.RequiredArgsConstructor; import net.avalith.city_pass.dto.CityPassDto; import net.avalith.city_pass.exceptions.CityPassNameIsAlreadyUsedException; import net.avalith.city_pass.exceptions.CityPassNotFoundException; import net.avalith.city_pass.models.City; import net.avalith.city_pass.models.CityPass; import net.avalith.city_pass.repositories.CityPassRepository; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import java.util.List; @Service @RequiredArgsConstructor public class CityPassService { private final CityPassRepository cityPassRepository; private final CityService cityService; public List<CityPass> getAllCityPasses() { return cityPassRepository.findAllByIsActive(true); } public CityPass createCityPass(CityPassDto cityPassDto) { CityPass cityPass = CityPass.builder() .name(cityPassDto.getName()) .description(cityPassDto.getDescription()) .days(cityPassDto.getDays()) .price(cityPassDto.getPrice()) .city(cityService.getByName(cityPassDto.getCityName())) .build(); try { cityPass = cityPassRepository.save(cityPass); } catch (DataIntegrityViolationException e) { throw new CityPassNameIsAlreadyUsedException(); } return cityPass; } public CityPass getById(Integer idCityPass) { return cityPassRepository.findByIdCityPassAndIsActive(idCityPass, true) .orElseThrow(CityPassNotFoundException::new); } public CityPass updateCityPass(Integer idCityPass, CityPassDto cityPassDto) { City city = cityService.getByName(cityPassDto.getCityName()); CityPass cityPass = cityPassRepository.findByIdCityPassAndIsActive(idCityPass, Boolean.TRUE) .orElseThrow(CityPassNotFoundException::new); try { cityPass = cityPass.update(cityPassDto, city); cityPass = cityPassRepository.save(cityPass); } catch (DataIntegrityViolationException e) { throw new CityPassNameIsAlreadyUsedException(); } return cityPass; } public CityPass deleteCityPass(Integer idCityPass) { CityPass cityPass = cityPassRepository.findByIdCityPassAndIsActive(idCityPass, true) .orElseThrow(CityPassNotFoundException::new); cityPass.setIsActive(Boolean.FALSE); return cityPassRepository.save(cityPass); } }
2,590
0.710425
0.710425
72
34.944443
27.665104
100
false
false
0
0
0
0
0
0
0.458333
false
false
9
8bb1eaa36d6152603bc7abb292d5d6ffbe2dbc58
33,526,514,748,333
d536e2f004b22d1829c5a9428c4093228425a0ac
/diarydemo/src/main/java/com/example/vis/diarydemo/UI/RefreshListView.java
82253bf0a67a59ef81fd0a0e00ac5462f3bf820c
[]
no_license
shamao/Firstdemo
https://github.com/shamao/Firstdemo
451ddfdcb916577d4d0a9eaa51079bddc0fdd635
b0465493e957c20514a4bae6f4ad81254bea4a4d
refs/heads/master
2015-08-22T04:22:11.914000
2015-03-26T08:23:22
2015-03-26T08:23:22
32,915,496
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.vis.diarydemo.UI; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Handler; import android.os.Message; import android.text.Layout; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.vis.diarydemo.R; /** * Created by Vis on 2015/3/12. */ public class RefreshListView extends ListView implements AbsListView.OnScrollListener { private OnRefreshListeners listener; private View mHeader; private int mHeaderHeight; private ImageView mImgHeader; private TextView mTvHeader; private int scrollState; private int firstVisibleItem = 0; //四种状态 正常 下拉 下拉刷新 释放 private int state = NORMAL; private static final int NORMAL = 0; private static final int PULL = 1; private static final int RELESE = 2; private static final int RELESING = 3; public RefreshListView(Context context) { this(context, null); } public RefreshListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { mHeader = LayoutInflater.from(context).inflate(R.layout.header, null); measureView(mHeader); mHeaderHeight = mHeader.getMeasuredHeight(); setTopPadding(-mHeaderHeight); addHeaderView(mHeader); Log.e("mHeaderHeight:", "" + mHeaderHeight); setOnScrollListener(this); } private void setTopPadding(int topPadding) { mHeader.setPadding(0, topPadding, 0, 0); Log.e("top", mHeader.getPaddingBottom() + ""); mHeader.invalidate(); } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } /*spec 表示外边距 */ int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width); int height = p.height; int childHeightSpec; if (height > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } private boolean IsCanRefresh = false; int startY; int moveY; int distanceY; int toppadding; @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: if (firstVisibleItem == 0) { IsCanRefresh = true; //获取起始位置 startY = (int) ev.getY(); } else { IsCanRefresh = false; } break; case MotionEvent.ACTION_MOVE: onMove(ev); break; case MotionEvent.ACTION_UP: IsCanRefresh = false; if (state == RELESE) { state = RELESING; Log.e("finish", "finish"); refreshByState(); listener.onRefresh(); Log.e("消失", "消失"); } else { state = NORMAL; refreshByState(); } break; } return super.onTouchEvent(ev); } private void onMove(MotionEvent ev) { Log.e("state:", state + ""); if (!IsCanRefresh) { return; } moveY = (int) ev.getY(); distanceY = moveY - startY; if (distanceY > mHeaderHeight + 70) { distanceY = mHeaderHeight + 70; } Log.e("distanceY:", distanceY + ""); toppadding = distanceY - mHeaderHeight;//用来动态变化头布局的高度变化 Log.e("toppadding:", toppadding + ""); switch (state) { case NORMAL://默认的state为NORMAL if (distanceY > 10) { state = PULL; refreshByState(); } break; case PULL: Log.e("pull", "pull"); setTopPadding(toppadding); Log.i("distanceY>mHeaderHeight + 10:", (distanceY > mHeaderHeight + 30) + ""); Log.i("scrollState:", scrollState + ""); if (distanceY > mHeaderHeight + 50 ) { Log.e("-----------------------------------------------", "1"); state = RELESE; refreshByState(); } else if (distanceY <= 0) { state = NORMAL; refreshByState(); } break; case RELESE: Log.e("RELESE", "RELESE"); setTopPadding(toppadding); if (distanceY < mHeaderHeight + 50) { state = PULL; refreshByState(); } break; } } private void refreshByState() { mTvHeader = (TextView) mHeader.findViewById(R.id.id_header_tv); mImgHeader = (ImageView) mHeader.findViewById(R.id.id_header_img); RotateAnimation anim1 = new RotateAnimation(180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); anim1.setDuration(300); anim1.setFillAfter(true);//保持动画过后的状态 RotateAnimation anim2 = new RotateAnimation(0, 180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); anim2.setDuration(600); anim2.setFillAfter(true);//保持动画过后的状态 switch (state) { case NORMAL: mImgHeader.clearAnimation(); setTopPadding(-mHeaderHeight); break; case PULL: mImgHeader.setVisibility(VISIBLE); mImgHeader.clearAnimation(); mImgHeader.setAnimation(anim1); mTvHeader.setText("下拉开始同步"); break; case RELESE: mTvHeader.setText("松开开始同步"); mImgHeader.setVisibility(VISIBLE); mImgHeader.clearAnimation(); mImgHeader.setAnimation(anim2); break; case RELESING: setTopPadding(-mHeaderHeight); mTvHeader.setText("正在同步"); setTopPadding(20); mImgHeader.setVisibility(GONE); mImgHeader.clearAnimation(); break; } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { this.scrollState = scrollState; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.firstVisibleItem = firstVisibleItem; } public void completeRefresh() { state = NORMAL; IsCanRefresh = false; refreshByState(); Toast.makeText(getContext(), "Ok", Toast.LENGTH_SHORT).show(); } public interface OnRefreshListeners { public void onRefresh(); } public void setOnRefreshListeners(OnRefreshListeners listener) { this.listener = listener; } }
UTF-8
Java
7,996
java
RefreshListView.java
Java
[ { "context": "t com.example.vis.diarydemo.R;\n\n\n/**\n * Created by Vis on 2015/3/12.\n */\npublic class RefreshListView ex", "end": 745, "score": 0.9761393070220947, "start": 742, "tag": "NAME", "value": "Vis" } ]
null
[]
package com.example.vis.diarydemo.UI; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Handler; import android.os.Message; import android.text.Layout; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.vis.diarydemo.R; /** * Created by Vis on 2015/3/12. */ public class RefreshListView extends ListView implements AbsListView.OnScrollListener { private OnRefreshListeners listener; private View mHeader; private int mHeaderHeight; private ImageView mImgHeader; private TextView mTvHeader; private int scrollState; private int firstVisibleItem = 0; //四种状态 正常 下拉 下拉刷新 释放 private int state = NORMAL; private static final int NORMAL = 0; private static final int PULL = 1; private static final int RELESE = 2; private static final int RELESING = 3; public RefreshListView(Context context) { this(context, null); } public RefreshListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { mHeader = LayoutInflater.from(context).inflate(R.layout.header, null); measureView(mHeader); mHeaderHeight = mHeader.getMeasuredHeight(); setTopPadding(-mHeaderHeight); addHeaderView(mHeader); Log.e("mHeaderHeight:", "" + mHeaderHeight); setOnScrollListener(this); } private void setTopPadding(int topPadding) { mHeader.setPadding(0, topPadding, 0, 0); Log.e("top", mHeader.getPaddingBottom() + ""); mHeader.invalidate(); } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } /*spec 表示外边距 */ int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width); int height = p.height; int childHeightSpec; if (height > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } private boolean IsCanRefresh = false; int startY; int moveY; int distanceY; int toppadding; @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: if (firstVisibleItem == 0) { IsCanRefresh = true; //获取起始位置 startY = (int) ev.getY(); } else { IsCanRefresh = false; } break; case MotionEvent.ACTION_MOVE: onMove(ev); break; case MotionEvent.ACTION_UP: IsCanRefresh = false; if (state == RELESE) { state = RELESING; Log.e("finish", "finish"); refreshByState(); listener.onRefresh(); Log.e("消失", "消失"); } else { state = NORMAL; refreshByState(); } break; } return super.onTouchEvent(ev); } private void onMove(MotionEvent ev) { Log.e("state:", state + ""); if (!IsCanRefresh) { return; } moveY = (int) ev.getY(); distanceY = moveY - startY; if (distanceY > mHeaderHeight + 70) { distanceY = mHeaderHeight + 70; } Log.e("distanceY:", distanceY + ""); toppadding = distanceY - mHeaderHeight;//用来动态变化头布局的高度变化 Log.e("toppadding:", toppadding + ""); switch (state) { case NORMAL://默认的state为NORMAL if (distanceY > 10) { state = PULL; refreshByState(); } break; case PULL: Log.e("pull", "pull"); setTopPadding(toppadding); Log.i("distanceY>mHeaderHeight + 10:", (distanceY > mHeaderHeight + 30) + ""); Log.i("scrollState:", scrollState + ""); if (distanceY > mHeaderHeight + 50 ) { Log.e("-----------------------------------------------", "1"); state = RELESE; refreshByState(); } else if (distanceY <= 0) { state = NORMAL; refreshByState(); } break; case RELESE: Log.e("RELESE", "RELESE"); setTopPadding(toppadding); if (distanceY < mHeaderHeight + 50) { state = PULL; refreshByState(); } break; } } private void refreshByState() { mTvHeader = (TextView) mHeader.findViewById(R.id.id_header_tv); mImgHeader = (ImageView) mHeader.findViewById(R.id.id_header_img); RotateAnimation anim1 = new RotateAnimation(180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); anim1.setDuration(300); anim1.setFillAfter(true);//保持动画过后的状态 RotateAnimation anim2 = new RotateAnimation(0, 180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); anim2.setDuration(600); anim2.setFillAfter(true);//保持动画过后的状态 switch (state) { case NORMAL: mImgHeader.clearAnimation(); setTopPadding(-mHeaderHeight); break; case PULL: mImgHeader.setVisibility(VISIBLE); mImgHeader.clearAnimation(); mImgHeader.setAnimation(anim1); mTvHeader.setText("下拉开始同步"); break; case RELESE: mTvHeader.setText("松开开始同步"); mImgHeader.setVisibility(VISIBLE); mImgHeader.clearAnimation(); mImgHeader.setAnimation(anim2); break; case RELESING: setTopPadding(-mHeaderHeight); mTvHeader.setText("正在同步"); setTopPadding(20); mImgHeader.setVisibility(GONE); mImgHeader.clearAnimation(); break; } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { this.scrollState = scrollState; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.firstVisibleItem = firstVisibleItem; } public void completeRefresh() { state = NORMAL; IsCanRefresh = false; refreshByState(); Toast.makeText(getContext(), "Ok", Toast.LENGTH_SHORT).show(); } public interface OnRefreshListeners { public void onRefresh(); } public void setOnRefreshListeners(OnRefreshListeners listener) { this.listener = listener; } }
7,996
0.561271
0.552591
263
28.78327
23.41205
140
false
false
0
0
0
0
0
0
0.676806
false
false
9
81fad26706895e226ada37d235e5dce5c912a6e6
21,191,368,674,027
35039e2aac933eefa8c4657595ab268f74f3b993
/src/main/java/fr/epsi/b3/ConcertProjet/domain/Groupe.java
4e33ec229f73a8ff51247b6b48d313c191e7e9d9
[]
no_license
b94752/projet_dp
https://github.com/b94752/projet_dp
b999ba86d68f3eaa48c1d7054bfce42bbe7544aa
6d435b0dd11b858c89366ad74308bb08e682d96a
refs/heads/master
2021-08-22T09:19:05.887000
2018-07-01T22:20:48
2018-07-01T22:20:48
135,592,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.epsi.b3.ConcertProjet.domain; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Groupe{ @Id @GeneratedValue(strategy=GenerationType.AUTO) long id; String nomGroupe; String genre; Date dateCreation; String description; @OneToMany Collection<JouerConcert> jouer_s = new ArrayList<JouerConcert>(); public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNomGroupe() { return nomGroupe; } public void setNomGroupe(String nomGroupe) { this.nomGroupe = nomGroupe; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public Date getDateCreation() { return dateCreation; } public void setDateCreation(Date dateCreation) { this.dateCreation = dateCreation; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Collection<JouerConcert> getJouer_s() { return jouer_s; } public void setJouer_s(Collection<JouerConcert> jouer_s) { this.jouer_s = jouer_s; } public void addGroupe(Groupe groupe) { // TODO Auto-generated method stub } public void removeGroupe(Groupe groupe) { // TODO Auto-generated method stub } public void addConcert(Concert concert) { JouerConcert jouerConcert = new JouerConcert(); jouer_s.add(jouerConcert); jouerConcert.setGroupe(this); concert.groupesConcert.add(jouerConcert); jouerConcert.setConcert(concert); } public void removeConcert(Concert concert) { // TODO Auto-generated method stub } }
UTF-8
Java
1,872
java
Groupe.java
Java
[]
null
[]
package fr.epsi.b3.ConcertProjet.domain; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Groupe{ @Id @GeneratedValue(strategy=GenerationType.AUTO) long id; String nomGroupe; String genre; Date dateCreation; String description; @OneToMany Collection<JouerConcert> jouer_s = new ArrayList<JouerConcert>(); public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNomGroupe() { return nomGroupe; } public void setNomGroupe(String nomGroupe) { this.nomGroupe = nomGroupe; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public Date getDateCreation() { return dateCreation; } public void setDateCreation(Date dateCreation) { this.dateCreation = dateCreation; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Collection<JouerConcert> getJouer_s() { return jouer_s; } public void setJouer_s(Collection<JouerConcert> jouer_s) { this.jouer_s = jouer_s; } public void addGroupe(Groupe groupe) { // TODO Auto-generated method stub } public void removeGroupe(Groupe groupe) { // TODO Auto-generated method stub } public void addConcert(Concert concert) { JouerConcert jouerConcert = new JouerConcert(); jouer_s.add(jouerConcert); jouerConcert.setGroupe(this); concert.groupesConcert.add(jouerConcert); jouerConcert.setConcert(concert); } public void removeConcert(Concert concert) { // TODO Auto-generated method stub } }
1,872
0.731303
0.730769
115
15.278261
17.460289
66
false
false
0
0
0
0
0
0
1.086957
false
false
9
4b2f48532cdf941a16df379090d61bd2f76f1b34
27,350,351,775,230
b75cd3ff003647cbccca9366f6afe948bc5733dd
/SoupaStars/src/test/java/com/sg/soupastars/SoupaStarsCommentDBImplTest.java
b11707f0d06d7ad1c4c26fb449874bd6e92024c2
[]
no_license
wlong3000/LiamLongProjects
https://github.com/wlong3000/LiamLongProjects
ea305f8dd9d0f790af038767a490231bd7e8b1f4
e64dd8a5886a22505db23591e9fde78a2008d72b
refs/heads/master
2020-06-30T08:08:37.670000
2016-12-08T16:02:40
2016-12-08T16:02:40
74,384,942
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sg.soupastars; import com.sg.soupastars.dao.SoupaStarsCommentDao; import com.sg.soupastars.dao.SoupaStarsPostDao; import com.sg.soupastars.model.Comment; import com.sg.soupastars.model.Post; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * * @author apprentice */ public class SoupaStarsCommentDBImplTest { private SoupaStarsCommentDao dao; private SoupaStarsPostDao pdao; public SoupaStarsCommentDBImplTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setup() { ApplicationContext ctx = new ClassPathXmlApplicationContext("test-applicationContext.xml"); dao = (SoupaStarsCommentDao) ctx.getBean("SoupaStarsCommentDBImpl"); pdao = (SoupaStarsPostDao) ctx.getBean("SoupaStarsPostDaoDBImpl"); JdbcTemplate cleaner = (JdbcTemplate) ctx.getBean("jdbcTemplate"); cleaner.execute("delete from PostComment"); cleaner.execute("delete from Comments"); cleaner.execute("delete from PostTag"); cleaner.execute("delete from PostComment"); cleaner.execute("delete from Post"); } @After public void tearDown() { } @Test public void addGetDeleteComment() { Post pt = new Post(); pt.setTitle("Cookies"); pt.setYear(2016); pt.setMonth("December"); pt.setDay(02); pt.setAuthor("admin"); pt.setBody("hello"); pt.setCategory("Food"); List<String> tagList = new ArrayList(); tagList.add("tag"); pt.setTagList(tagList); Post post = pdao.addPost(pt); Comment nc = new Comment(); nc.setName("Alyssa"); nc.setEmail("arice713@yahoo.com"); nc.setText("hi"); nc.setDate("November 17, 2016"); nc = dao.addComment(nc, post.postId); Comment fromDb = dao.getCommentById(nc.getCommentId()); assertEquals(fromDb.getCommentId(), nc.getCommentId()); assertEquals(fromDb.getName(), nc.getName()); assertEquals(fromDb.getEmail(), nc.getEmail()); assertEquals(fromDb.getText(), nc.getText()); assertEquals(fromDb.getDate(), nc.getDate()); dao.removeComment(nc.getCommentId()); assertNull(dao.getCommentById(nc.getCommentId())); } }
UTF-8
Java
3,001
java
SoupaStarsCommentDBImplTest.java
Java
[ { "context": "ic org.junit.Assert.assertNull;\n\n/**\n *\n * @author apprentice\n */\npublic class SoupaStarsCommentDBImplTest {\n\n ", "end": 897, "score": 0.9983625411987305, "start": 887, "tag": "USERNAME", "value": "apprentice" }, { "context": "r\");\n pt.setDay(02);\n ...
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sg.soupastars; import com.sg.soupastars.dao.SoupaStarsCommentDao; import com.sg.soupastars.dao.SoupaStarsPostDao; import com.sg.soupastars.model.Comment; import com.sg.soupastars.model.Post; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * * @author apprentice */ public class SoupaStarsCommentDBImplTest { private SoupaStarsCommentDao dao; private SoupaStarsPostDao pdao; public SoupaStarsCommentDBImplTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setup() { ApplicationContext ctx = new ClassPathXmlApplicationContext("test-applicationContext.xml"); dao = (SoupaStarsCommentDao) ctx.getBean("SoupaStarsCommentDBImpl"); pdao = (SoupaStarsPostDao) ctx.getBean("SoupaStarsPostDaoDBImpl"); JdbcTemplate cleaner = (JdbcTemplate) ctx.getBean("jdbcTemplate"); cleaner.execute("delete from PostComment"); cleaner.execute("delete from Comments"); cleaner.execute("delete from PostTag"); cleaner.execute("delete from PostComment"); cleaner.execute("delete from Post"); } @After public void tearDown() { } @Test public void addGetDeleteComment() { Post pt = new Post(); pt.setTitle("Cookies"); pt.setYear(2016); pt.setMonth("December"); pt.setDay(02); pt.setAuthor("admin"); pt.setBody("hello"); pt.setCategory("Food"); List<String> tagList = new ArrayList(); tagList.add("tag"); pt.setTagList(tagList); Post post = pdao.addPost(pt); Comment nc = new Comment(); nc.setName("Alyssa"); nc.setEmail("<EMAIL>"); nc.setText("hi"); nc.setDate("November 17, 2016"); nc = dao.addComment(nc, post.postId); Comment fromDb = dao.getCommentById(nc.getCommentId()); assertEquals(fromDb.getCommentId(), nc.getCommentId()); assertEquals(fromDb.getName(), nc.getName()); assertEquals(fromDb.getEmail(), nc.getEmail()); assertEquals(fromDb.getText(), nc.getText()); assertEquals(fromDb.getDate(), nc.getDate()); dao.removeComment(nc.getCommentId()); assertNull(dao.getCommentById(nc.getCommentId())); } }
2,990
0.676774
0.671776
102
28.421568
22.797676
99
false
false
0
0
0
0
0
0
0.637255
false
false
9
2e0bc4a82fc758e8b55542917d6e4960bbbea63b
16,552,803,997,076
4beea41d660cfc572f814a75c6505685e9c25044
/src/6_Inheritance/StaffTetap1841720004Bellas.java
146b21c135c13960c991034009554782908eda3e
[]
no_license
b-bella99/laporan-praktikum-pbo-2019
https://github.com/b-bella99/laporan-praktikum-pbo-2019
6d09a4c8c3749628052a90189c62be0e19eb8c3f
67bc2eb11a5d45bbb573eab87fb995c7e9e11bb2
refs/heads/master
2020-07-21T16:05:03.168000
2019-12-10T04:16:24
2019-12-10T04:16:24
206,916,284
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bella.inheritance.percobaan6; /** * * @author bella */ public class StaffTetap1841720004Bellas extends Staff1841720004Bellas{ public String golongan; public int asuransi; public StaffTetap1841720004Bellas() { } public StaffTetap1841720004Bellas(String nama, String alamat, String jk, int umur, int gaji, int lembur, int potongan, String golongan, int asuransi) { super(nama, alamat, jk, umur, gaji, potongan, lembur); this.golongan = golongan; this.asuransi = asuransi; } public void tampilStaffTetapBella(){ System.out.println("==============Data Staff Tetap==============="); super.tampilDataStaffBella(); System.out.println("Golongan = " + golongan); System.out.println("Jumlah Asuransi = " + asuransi); System.out.println("Gaji Bersih = " + (gaji + lembur - potongan - asuransi)); } }
UTF-8
Java
1,095
java
StaffTetap1841720004Bellas.java
Java
[ { "context": "e bella.inheritance.percobaan6;\n\n/**\n *\n * @author bella\n */\npublic class StaffTetap1841720004Bellas exten", "end": 247, "score": 0.9991528987884521, "start": 242, "tag": "USERNAME", "value": "bella" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bella.inheritance.percobaan6; /** * * @author bella */ public class StaffTetap1841720004Bellas extends Staff1841720004Bellas{ public String golongan; public int asuransi; public StaffTetap1841720004Bellas() { } public StaffTetap1841720004Bellas(String nama, String alamat, String jk, int umur, int gaji, int lembur, int potongan, String golongan, int asuransi) { super(nama, alamat, jk, umur, gaji, potongan, lembur); this.golongan = golongan; this.asuransi = asuransi; } public void tampilStaffTetapBella(){ System.out.println("==============Data Staff Tetap==============="); super.tampilDataStaffBella(); System.out.println("Golongan = " + golongan); System.out.println("Jumlah Asuransi = " + asuransi); System.out.println("Gaji Bersih = " + (gaji + lembur - potongan - asuransi)); } }
1,095
0.660274
0.622831
31
34.322582
35.023849
155
false
false
0
0
0
0
0
0
0.903226
false
false
9
70e049f11cddb07baa26a437c8f073e2ac4979ea
343,597,428,404
a817a633d2c78c30ac2ca8f7a68a9e638fc16e30
/Main/src/UVA/Main1185.java
aa9567312fb667f6194c7e0f30e694f42aa49934
[]
no_license
jojstepersan/maratones
https://github.com/jojstepersan/maratones
4a2d295ae85d9f43931f4f5c6dfd9e151c852f94
c013dcee15bb26be5992b584fa59bea90d8afdf8
refs/heads/master
2021-01-19T04:16:28.692000
2019-08-26T14:10:52
2019-08-26T14:10:52
87,362,773
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UVA; import java.io.BufferedReader; import java.io.InputStreamReader; /** * * @author jojstepersan 1185 - Big Number */ public class Main1185 { static int MAX = 10000000 + 5; static int DP[] = new int[MAX]; static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws Exception { double last = 0; for(int i = 1; i <= 10000000; i++) { last += Math.log10(i); DP[i] = (int)last; } int x=Integer.valueOf(in.readLine().trim()); for (int i = 0; i <x; i++) { int n=Integer.valueOf(in.readLine().trim()); System.out.println(DP[n]+1); } } }
UTF-8
Java
910
java
Main1185.java
Java
[ { "context": "mport java.io.InputStreamReader;\n/**\n *\n * @author jojstepersan 1185 - Big Number\n */\npublic class Main1185 {\n\n ", "end": 294, "score": 0.9977137446403503, "start": 282, "tag": "USERNAME", "value": "jojstepersan" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UVA; import java.io.BufferedReader; import java.io.InputStreamReader; /** * * @author jojstepersan 1185 - Big Number */ public class Main1185 { static int MAX = 10000000 + 5; static int DP[] = new int[MAX]; static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws Exception { double last = 0; for(int i = 1; i <= 10000000; i++) { last += Math.log10(i); DP[i] = (int)last; } int x=Integer.valueOf(in.readLine().trim()); for (int i = 0; i <x; i++) { int n=Integer.valueOf(in.readLine().trim()); System.out.println(DP[n]+1); } } }
910
0.607692
0.573626
36
24.277779
23.884689
84
false
false
0
0
0
0
0
0
0.583333
false
false
9
38b98d44e69a133ddf4a27ec778c8bd3155ee579
33,285,996,578,150
fd03f37b57e5c16415eec76b2ef62d49fdc79aea
/patched/src/main/java/com/huami/watch/companion/sport/ui/fragment/SportDetailTrackFragment.java
eff67b0136b47459020181b9402fb047094068de
[]
no_license
hilde0407/AmazMod
https://github.com/hilde0407/AmazMod
8669eac0bd10e651cbfdac72b9339e21a43e3040
29ea9b11303bc749233fa97d698a28a1f538b971
refs/heads/master
2020-03-18T17:46:21.492000
2018-05-15T12:41:22
2018-05-15T12:41:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huami.watch.companion.sport.ui.fragment; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import lanchon.dexpatcher.annotation.DexAction; import lanchon.dexpatcher.annotation.DexEdit; import lanchon.dexpatcher.annotation.DexIgnore; import lanchon.dexpatcher.annotation.DexPrepend; import lanchon.dexpatcher.annotation.DexWrap; /** * Created by edoardotassinari on 24/02/18. */ @DexEdit(defaultAction = DexAction.IGNORE) public class SportDetailTrackFragment extends BaseSportDetailFragment implements View.OnClickListener{ @DexIgnore private boolean x; @SuppressLint("MissingSuperCall") @DexWrap @Override public void onActivityCreated(@Nullable Bundle bundle) { this.x = true; onActivityCreated(bundle); this.x = false; } @DexIgnore @Override public void onClick(View view) { } @DexIgnore @Override protected int getLayout() { return 0; } @Override protected void initViews(View view) { } }
UTF-8
Java
1,116
java
SportDetailTrackFragment.java
Java
[ { "context": ".dexpatcher.annotation.DexWrap;\n\n/**\n * Created by edoardotassinari on 24/02/18.\n */\n\n@DexEdit(defaultAction = DexAct", "end": 463, "score": 0.999438464641571, "start": 447, "tag": "USERNAME", "value": "edoardotassinari" } ]
null
[]
package com.huami.watch.companion.sport.ui.fragment; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import lanchon.dexpatcher.annotation.DexAction; import lanchon.dexpatcher.annotation.DexEdit; import lanchon.dexpatcher.annotation.DexIgnore; import lanchon.dexpatcher.annotation.DexPrepend; import lanchon.dexpatcher.annotation.DexWrap; /** * Created by edoardotassinari on 24/02/18. */ @DexEdit(defaultAction = DexAction.IGNORE) public class SportDetailTrackFragment extends BaseSportDetailFragment implements View.OnClickListener{ @DexIgnore private boolean x; @SuppressLint("MissingSuperCall") @DexWrap @Override public void onActivityCreated(@Nullable Bundle bundle) { this.x = true; onActivityCreated(bundle); this.x = false; } @DexIgnore @Override public void onClick(View view) { } @DexIgnore @Override protected int getLayout() { return 0; } @Override protected void initViews(View view) { } }
1,116
0.72491
0.718638
50
21.32
19.348839
69
false
false
0
0
0
0
0
0
0.3
false
false
9